]> mj.ucw.cz Git - libucw.git/blob - lib/gbuf.h
d202adb6f1b05e5e2f03fef90cf847d0f67b10a5
[libucw.git] / lib / gbuf.h
1 /*
2  *      UCW Library -- A simple growing buffer
3  *
4  *      (c) 2004, Robert Spalek <robert@ucw.cz>
5  *      (c) 2005, Martin Mares <mj@ucw.cz>
6  *
7  *      Define the following macros:
8  *
9  *      GBUF_TYPE       data type of records stored in the buffer
10  *      GBUF_PREFIX(x)  add a name prefix to all global symbols
11  *
12  *      This software may be freely distributed and used according to the terms
13  *      of the GNU Lesser General Public License.
14  */
15
16 #include <stdlib.h>
17
18 #define BUF_T   GBUF_PREFIX(t)
19
20 typedef struct
21 {
22   uns len;
23   GBUF_TYPE *ptr;
24 }
25 BUF_T;
26
27 static inline void
28 GBUF_PREFIX(init)(BUF_T *b)
29 {
30   b->ptr = NULL;
31   b->len = 0;
32 }
33
34 static inline void
35 GBUF_PREFIX(done)(BUF_T *b)
36 {
37   if (b->ptr)
38     xfree(b->ptr);
39   b->ptr = NULL;
40   b->len = 0;
41 }
42
43 static inline void
44 GBUF_PREFIX(realloc)(BUF_T *b, uns len)
45 {
46   b->len = len;
47   b->ptr = xrealloc(b->ptr, len * sizeof(GBUF_TYPE));
48 #ifdef GBUF_TRACE
49   log(L_DEBUG, STRINGIFY_EXPANDED(BUF_T) " growing to %u items", len);
50 #endif
51 }
52
53 static inline void
54 GBUF_PREFIX(grow)(BUF_T *b, uns len)
55 {
56   if (likely(len <= b->len))
57     return;
58   if (len < 2*b->len)                   // to ensure logarithmic cost
59     len = 2*b->len;
60   GBUF_PREFIX(realloc)(b, len);
61 }
62
63 #undef  GBUF_TYPE
64 #undef  GBUF_PREFIX
65 #undef  GBUF_TRACE
66 #undef  BUF_T