X-Git-Url: http://mj.ucw.cz/gitweb/?a=blobdiff_plain;ds=inline;f=lib%2Fgbuf.h;h=daf0bfbb6b74be7729c3aa34b56e31d46cae1772;hb=e34560a76a7af3fb428604e4da3cd14cfd1bf454;hp=519a7c0fe2eb515e8c05c9e864dad6f0bb051dfb;hpb=0d8ad177d65c9a65aa75c25d38fd9729f6d25fc2;p=libucw.git diff --git a/lib/gbuf.h b/lib/gbuf.h index 519a7c0f..daf0bfbb 100644 --- a/lib/gbuf.h +++ b/lib/gbuf.h @@ -2,21 +2,21 @@ * UCW Library -- A simple growing buffer * * (c) 2004, Robert Spalek + * (c) 2005, Martin Mares * * Define the following macros: * * GBUF_TYPE data type of records stored in the buffer * GBUF_PREFIX(x) add a name prefix to all global symbols + * GBUF_TRACE(msg...) log growing of buffer [optional] * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. */ -#include - #define BUF_T GBUF_PREFIX(t) -typedef struct +typedef struct BUF_T { uns len; GBUF_TYPE *ptr; @@ -30,7 +30,7 @@ GBUF_PREFIX(init)(BUF_T *b) b->len = 0; } -static inline void +static void UNUSED GBUF_PREFIX(done)(BUF_T *b) { if (b->ptr) @@ -39,23 +39,33 @@ GBUF_PREFIX(done)(BUF_T *b) b->len = 0; } -static inline void -GBUF_PREFIX(realloc)(BUF_T *b, uns len) +static void UNUSED +GBUF_PREFIX(set_size)(BUF_T *b, uns len) { b->len = len; b->ptr = xrealloc(b->ptr, len * sizeof(GBUF_TYPE)); +#ifdef GBUF_TRACE + GBUF_TRACE(STRINGIFY_EXPANDED(BUF_T) " growing to %u items", len); +#endif } -static inline void -GBUF_PREFIX(grow)(BUF_T *b, uns len) +static void UNUSED +GBUF_PREFIX(do_grow)(BUF_T *b, uns len) { - if (len <= b->len) - return; if (len < 2*b->len) // to ensure logarithmic cost len = 2*b->len; - GBUF_PREFIX(realloc)(b, len); + GBUF_PREFIX(set_size)(b, len); +} + +static inline GBUF_TYPE * +GBUF_PREFIX(grow)(BUF_T *b, uns len) +{ + if (unlikely(len > b->len)) + GBUF_PREFIX(do_grow)(b, len); + return b->ptr; } #undef GBUF_TYPE #undef GBUF_PREFIX +#undef GBUF_TRACE #undef BUF_T