]> mj.ucw.cz Git - libucw.git/blob - lib/gbuf.h
0775f20cb3738bb976176a72af94918322261f9d
[libucw.git] / lib / gbuf.h
1 /*
2  *      UCW Library -- 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  *      This software may be freely distributed and used according to the terms
12  *      of the GNU Lesser General Public License.
13  */
14
15 #include <stdlib.h>
16
17 #define BUF_T   GBUF_PREFIX(t)
18
19 typedef struct
20 {
21   uns len;
22   GBUF_TYPE *ptr;
23 }
24 BUF_T;
25
26 static inline void
27 GBUF_PREFIX(init)(BUF_T *b)
28 {
29   b->ptr = NULL;
30   b->len = 0;
31 }
32
33 static inline void
34 GBUF_PREFIX(done)(BUF_T *b)
35 {
36   if (b->ptr)
37     xfree(b->ptr);
38   b->ptr = NULL;
39   b->len = 0;
40 }
41
42 static inline void
43 GBUF_PREFIX(realloc)(BUF_T *b, uns len)
44 {
45   b->len = len;
46   b->ptr = xrealloc(b->ptr, len * sizeof(GBUF_TYPE));
47 }
48
49 static inline void
50 GBUF_PREFIX(grow)(BUF_T *b, uns len)
51 {
52   if (likely(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
61 #undef  BUF_T