]> mj.ucw.cz Git - libucw.git/blob - lib/gbuf.h
- obj_parse_dump() generalized to store apart the header and the body, and
[libucw.git] / lib / gbuf.h
1 /*
2  *      A simple growing buffer
3  *
4  *      (c) 2004, Robert Spalek <robert@ucw.cz>
5  *
6  *      Define the following macros:
7  *
8  *      GBUF_TYPE       data type of records stored in the buffer
9  *      GBUF_PREFIX(x)  add a name prefix to all global symbols
10  */
11
12 #define BUF_T   GBUF_PREFIX(t)
13
14 typedef struct
15 {
16   uns len;
17   GBUF_TYPE *ptr;
18 }
19 BUF_T;
20
21 static inline void
22 GBUF_PREFIX(init)(BUF_T *b)
23 {
24   b->ptr = NULL;
25   b->len = 0;
26 }
27
28 static inline void
29 GBUF_PREFIX(done)(BUF_T *b)
30 {
31   if (b->ptr)
32     xfree(b->ptr);
33   b->ptr = NULL;
34   b->len = 0;
35 }
36
37 static inline void
38 GBUF_PREFIX(realloc)(BUF_T *b, uns len)
39 {
40   b->len = len;
41   if (b->ptr)
42     b->ptr = xrealloc(b->ptr, len * sizeof(GBUF_TYPE));
43   else
44     b->ptr = xmalloc(len * sizeof(GBUF_TYPE));
45 }
46
47 static inline void
48 GBUF_PREFIX(grow)(BUF_T *b, uns len)
49 {
50   if (len <= b->len)
51     return;
52   if (len < 2*b->len)                   // to ensure logarithmic cost
53     len = 2*b->len;
54   GBUF_PREFIX(realloc)(b, len);
55 }
56
57 #undef  GBUF_TYPE
58 #undef  GBUF_PREFIX