db9decade6253b72bc8eaac556251f02ffd31404
[yaz-moved-to-github.git] / src / odr_mem.c
1 /*
2  * Copyright (c) 1995-2004, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: odr_mem.c,v 1.2 2004-09-30 11:06:41 adam Exp $
6  */
7 #if HAVE_CONFIG_H
8 #include <config.h>
9 #endif
10
11 #include <stdlib.h>
12 #include "odr-priv.h"
13 #include <yaz/xmalloc.h>
14
15 /* ------------------------ NIBBLE MEMORY ---------------------- */
16
17 /*
18  * Extract the memory control block from o.
19  */
20 NMEM odr_extract_mem(ODR o)
21 {
22     NMEM r = o->mem;
23
24     o->mem = 0;
25     return r;
26 }
27
28 void *odr_malloc(ODR o, int size)
29 {
30     if (o && !o->mem)
31         o->mem = nmem_create();
32     return nmem_malloc(o ? o->mem : 0, size);
33 }
34
35 char *odr_strdup(ODR o, const char *str)
36 {
37     if (o && !o->mem)
38         o->mem = nmem_create();
39     return nmem_strdup(o->mem, str);
40 }
41
42 char *odr_strdupn(ODR o, const char *str, size_t n)
43 {
44     return nmem_strdupn(o->mem, str, n);
45 }
46
47 int *odr_intdup(ODR o, int v)
48 {
49     if (o && !o->mem)
50         o->mem = nmem_create();
51     return nmem_intdup(o->mem, v);
52 }
53
54 int odr_total(ODR o)
55 {
56     return o->mem ? nmem_total(o->mem) : 0;
57 }
58
59 /* ---------- memory management for data encoding ----------*/
60
61
62 int odr_grow_block(ODR b, int min_bytes)
63 {
64     int togrow;
65
66     if (!b->can_grow)
67         return -1;
68     if (!b->size)
69         togrow = 1024;
70     else
71         togrow = b->size;
72     if (togrow < min_bytes)
73         togrow = min_bytes;
74     if (b->size && !(b->buf =
75                      (unsigned char *) xrealloc(b->buf, b->size += togrow)))
76         abort();
77     else if (!b->size && !(b->buf = (unsigned char *)
78                            xmalloc(b->size = togrow)))
79         abort();
80 #ifdef ODR_DEBUG
81     fprintf(stderr, "New size for encode_buffer: %d\n", b->size);
82 #endif
83     return 0;
84 }
85
86 int odr_write(ODR o, unsigned char *buf, int bytes)
87 {
88     if (o->pos + bytes >= o->size && odr_grow_block(o, bytes))
89     {
90         odr_seterror(o, OSPACE, 40);
91         return -1;
92     }
93     memcpy(o->buf + o->pos, buf, bytes);
94     o->pos += bytes;
95     if (o->pos > o->top)
96         o->top = o->pos;
97     return 0;
98 }
99
100 int odr_seek(ODR o, int whence, int offset)
101 {
102     if (whence == ODR_S_CUR)
103         offset += o->pos;
104     else if (whence == ODR_S_END)
105         offset += o->top;
106     if (offset > o->size && odr_grow_block(o, offset - o->size))
107     {
108         odr_seterror(o, OSPACE, 41);
109         return -1;
110     }
111     o->pos = offset;
112     return 0;
113 }