cesanta/frozen

json_sprinter reduce number of reallocations

ddario opened this issue · 1 comments

json_sprinter reallocates destination buffer by one character every time it's called.

It'd be nice to reduce the number of reallocations

Just a suggestion:

/** Define a minimum buffer allocation size */
#define FROZEN_ALLOC_MIN 256

static int json_sprinter(struct json_out *out, const char *str, size_t len) {
char *p = out->u.buf.buf;
size_t old_len = (p == NULL) ? 0 : out->u.buf.len;
size_t new_len = len + old_len;
if (out->u.buf.size <= (new_len + 1)) {
size_t new_size = MAX (out->u.buf.size + FROZEN_ALLOC_MIN, new_len + 1);
p = (char *) FROZEN_REALLOC (p, new_size);
if (p == NULL) {
return -1;
}

out->u.buf.size = new_size;
out->u.buf.buf = p;

}

memcpy(p + old_len, str, len);
out->u.buf.len = new_len;
p[new_len] = '\0';

return len;
}