Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json_sprinter reduce number of reallocations #66

Open
ddario opened this issue Feb 16, 2022 · 1 comment
Open

json_sprinter reduce number of reallocations #66

ddario opened this issue Feb 16, 2022 · 1 comment

Comments

@ddario
Copy link

ddario commented Feb 16, 2022

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

It'd be nice to reduce the number of reallocations

@ddario
Copy link
Author

ddario commented Feb 16, 2022

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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant