From: Sebastian Harl Date: Wed, 17 Sep 2014 09:22:54 +0000 (+0200) Subject: utils strbuf: Exponentially increase the buffer size. X-Git-Tag: sysdb-0.5.0~31 X-Git-Url: https://git.tokkee.org/?p=sysdb.git;a=commitdiff_plain;h=28f5b4d2480d80440c8a444b5ee9c16f8b926947 utils strbuf: Exponentially increase the buffer size. That'll make sure that lots of small writes don't result in lots of memory reallocations. --- diff --git a/src/utils/strbuf.c b/src/utils/strbuf.c index ecc0531..d8a95ac 100644 --- a/src/utils/strbuf.c +++ b/src/utils/strbuf.c @@ -25,6 +25,7 @@ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include "sysdb.h" #include "utils/strbuf.h" #include @@ -65,11 +66,18 @@ struct sdb_strbuf { static int strbuf_resize(sdb_strbuf_t *buf, size_t new_size) { + size_t tmp_size; char *tmp; if (new_size <= buf->pos) return -1; + tmp_size = SDB_MAX(buf->size, buf->min_size); + if (! tmp_size) + tmp_size = 64; + while (tmp_size < new_size) + tmp_size *= 2; + tmp = realloc(buf->string, new_size); if (! tmp) return -1; @@ -231,15 +239,8 @@ sdb_strbuf_memappend(sdb_strbuf_t *buf, const void *data, size_t n) assert((buf->size == 0) || (buf->string[buf->pos] == '\0')); - if (buf->pos + n + 1 >= buf->size) { - size_t newsize = buf->size * 2; - - if (! newsize) - newsize = 64; - while (buf->pos + n + 1 >= newsize) - newsize *= 2; - - if (strbuf_resize(buf, newsize)) + if (buf->pos + n + 1 > buf->size) { + if (strbuf_resize(buf, buf->pos + n + 1)) return -1; }