]> mj.ucw.cz Git - libucw.git/blob - lib/gbuf.h
Include <stdlib.h> to get free().
[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 #include <stdlib.h>
13
14 #define BUF_T   GBUF_PREFIX(t)
15
16 typedef struct
17 {
18   uns len;
19   GBUF_TYPE *ptr;
20 }
21 BUF_T;
22
23 static inline void
24 GBUF_PREFIX(init)(BUF_T *b)
25 {
26   b->ptr = NULL;
27   b->len = 0;
28 }
29
30 static inline void
31 GBUF_PREFIX(done)(BUF_T *b)
32 {
33   if (b->ptr)
34     xfree(b->ptr);
35   b->ptr = NULL;
36   b->len = 0;
37 }
38
39 static inline void
40 GBUF_PREFIX(realloc)(BUF_T *b, uns len)
41 {
42   b->len = len;
43   if (b->ptr)
44     b->ptr = xrealloc(b->ptr, len * sizeof(GBUF_TYPE));
45   else
46     b->ptr = xmalloc(len * sizeof(GBUF_TYPE));
47 }
48
49 static inline void
50 GBUF_PREFIX(grow)(BUF_T *b, uns len)
51 {
52   if (len <= b->len)
53     return;
54   if (len < 2*b->len)                   // to ensure logarithmic cost
55     len = 2*b->len;
56   GBUF_PREFIX(realloc)(b, len);
57 }
58
59 #undef  GBUF_TYPE
60 #undef  GBUF_PREFIX