2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.11 1995-11-01 13:54:43 quinn
10 * Revision 1.10 1995/10/25 16:58:19 quinn
11 * Stupid bug in odr_malloc
13 * Revision 1.9 1995/10/13 16:08:08 quinn
16 * Revision 1.8 1995/09/29 17:12:24 quinn
19 * Revision 1.7 1995/09/27 15:02:59 quinn
20 * Modified function heads & prototypes.
22 * Revision 1.6 1995/08/21 09:10:41 quinn
23 * Smallish fixes to suppport new formats.
25 * Revision 1.5 1995/05/16 08:50:55 quinn
26 * License, documentation, and memory fixes
28 * Revision 1.4 1995/05/15 11:56:09 quinn
29 * More work on memory management.
31 * Revision 1.3 1995/04/18 08:15:21 quinn
32 * Added dynamic memory allocation on encoding (whew). Code is now somewhat
33 * neater. We'll make the same change for decoding one day.
35 * Revision 1.2 1995/03/17 10:17:52 quinn
36 * Added memory management.
38 * Revision 1.1 1995/03/14 10:27:40 quinn
39 * Modified makefile to use common lib
40 * Beginning to add memory management to odr
48 /* ------------------------ NIBBLE MEMORY ---------------------- */
50 #define ODR_MEM_CHUNK (10*1024)
52 typedef struct odr_memblock
58 struct odr_memblock *next;
61 static odr_memblock *freelist = 0; /* global freelist */
63 static void free_block(odr_memblock *p)
70 * acquire a block with a minimum of size free bytes.
72 static odr_memblock *get_block(int size)
76 for (r = freelist, l = 0; r; l = r, r = r->next)
86 int get = ODR_MEM_CHUNK;
90 if (!(r = xmalloc(sizeof(*r))))
92 if (!(r->buf = xmalloc(r->size = get)))
101 * Return p to the global freelist.
103 void odr_release_mem(ODR_MEM p)
116 * Extract the memory control block from o.
118 ODR_MEM odr_extract_mem(ODR o)
126 void *odr_malloc(ODR o, int size)
128 struct odr_memblock *p;
133 if (!(r = xmalloc(size)))
138 if (!p || p->size - p->top < size)
139 if (!(p = get_block(size)))
144 p->total = o->mem->total;
150 p->top += (size + (sizeof(long) - 1)) & ~(sizeof(long) - 1);
157 return o->mem ? o->mem->total : 0;
160 /* ---------- memory management for data encoding ----------*/
163 int odr_grow_block(odr_ecblock *b, int min_bytes)
173 if (togrow < min_bytes)
175 if (b->size && !(b->buf =xrealloc(b->buf, b->size += togrow)))
177 else if (!b->size && !(b->buf = xmalloc(b->size = togrow)))
180 fprintf(stderr, "New size for encode_buffer: %d\n", b->size);
185 int odr_write(ODR o, unsigned char *buf, int bytes)
187 if (o->ecb.pos + bytes >= o->ecb.size && odr_grow_block(&o->ecb, bytes))
192 memcpy(o->ecb.buf + o->ecb.pos, buf, bytes);
194 if (o->ecb.pos > o->ecb.top)
195 o->ecb.top = o->ecb.pos;
199 int odr_seek(ODR o, int whence, int offset)
201 if (whence == ODR_S_CUR)
202 offset += o->ecb.pos;
203 else if (whence == ODR_S_END)
204 offset += o->ecb.top;
205 if (offset > o->ecb.size && odr_grow_block(&o->ecb, offset - o->ecb.size))