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