Add Zthes tag-set -- where was it?!
[yaz-moved-to-github.git] / odr / odr_mem.c
1 /*
2  * Copyright (c) 1995-2002, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: odr_mem.c,v 1.20 2002-07-25 12:51:08 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     return nmem_strdup(o->mem, str);
38 }
39
40 int *odr_intdup(ODR o, int v)
41 {
42     return nmem_intdup(o->mem, v);
43 }
44
45 int odr_total(ODR o)
46 {
47     return o->mem ? nmem_total(o->mem) : 0;
48 }
49
50 /* ---------- memory management for data encoding ----------*/
51
52
53 int odr_grow_block(ODR b, int min_bytes)
54 {
55     int togrow;
56
57     if (!b->can_grow)
58         return -1;
59     if (!b->size)
60         togrow = 1024;
61     else
62         togrow = b->size;
63     if (togrow < min_bytes)
64         togrow = min_bytes;
65     if (b->size && !(b->buf =
66                      (unsigned char *) xrealloc(b->buf, b->size += togrow)))
67         abort();
68     else if (!b->size && !(b->buf = (unsigned char *)
69                            xmalloc(b->size = togrow)))
70         abort();
71 #ifdef ODR_DEBUG
72     fprintf(stderr, "New size for encode_buffer: %d\n", b->size);
73 #endif
74     return 0;
75 }
76
77 int odr_write(ODR o, unsigned char *buf, int bytes)
78 {
79     if (o->pos + bytes >= o->size && odr_grow_block(o, bytes))
80     {
81         o->error = OSPACE;
82         return -1;
83     }
84     memcpy(o->buf + o->pos, buf, bytes);
85     o->pos += bytes;
86     if (o->pos > o->top)
87         o->top = o->pos;
88     return 0;
89 }
90
91 int odr_seek(ODR o, int whence, int offset)
92 {
93     if (whence == ODR_S_CUR)
94         offset += o->pos;
95     else if (whence == ODR_S_END)
96         offset += o->top;
97     if (offset > o->size && odr_grow_block(o, offset - o->size))
98     {
99         o->error = OSPACE;
100         return -1;
101     }
102     o->pos = offset;
103     return 0;
104 }