Skip to content

Commit 2da4e81

Browse files
committed
feat: dynamic buffer support
Add '_auto' counterparts for functions for automatically increasing buffers
1 parent a213eea commit 2da4e81

File tree

5 files changed

+882
-217
lines changed

5 files changed

+882
-217
lines changed

README.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,40 @@ jsonb_object(&b, buf, sizeof(buf));
3838
printf("JSON: %s", buf); // JSON: {"foo":[1,"hi",false,null]}
3939
```
4040
41+
## Automatic Buffer Management
42+
43+
For dynamic buffer management, json-build provides `_auto` counterparts for all serializer functions.
44+
These functions will automatically reallocate the buffer when more space is needed:
45+
46+
```c
47+
#include "json-build.h"
48+
#include <stdlib.h>
49+
50+
...
51+
jsonb b;
52+
char *buf = malloc(64); // Initial small buffer
53+
size_t bufsize = 64;
54+
55+
jsonb_init(&b);
56+
jsonb_object_auto(&b, &buf, &bufsize); // Note: passing pointers to buffer and size
57+
{
58+
jsonb_key_auto(&b, &buf, &bufsize, "foo", strlen("foo"));
59+
jsonb_array_auto(&b, &buf, &bufsize);
60+
{
61+
jsonb_number_auto(&b, &buf, &bufsize, 1);
62+
jsonb_string_auto(&b, &buf, &bufsize, "hi", 2);
63+
jsonb_bool_auto(&b, &buf, &bufsize, 0);
64+
jsonb_null_auto(&b, &buf, &bufsize);
65+
jsonb_array_pop_auto(&b, &buf, &bufsize);
66+
}
67+
jsonb_object_pop_auto(&b, &buf, &bufsize);
68+
}
69+
printf("JSON: %s (buffer size: %zu)\n", buf, bufsize);
70+
free(buf);
71+
```
72+
73+
**IMPORTANT**: Do not mix regular and `_auto` functions on the same buffer. Always use either the regular functions with a fixed-size buffer or the `_auto` functions with a dynamically allocated buffer throughout your code.
74+
4175
Since json-build is a single-header, header-only library, for more complex use
4276
cases you might need to define additional macros. `#define JSONB_STATIC`hides all
4377
json-build API symbols by making them static. Also, if you want to include `json-build.h`
@@ -70,9 +104,10 @@ for multiple C files, to avoid duplication of symbols you may define `JSONB_HEAD
70104
The following are the possible return codes for the builder functions:
71105
* `JSONB_OK` - operation was a success, user can proceed with the next operation
72106
* `JSONB_END` - operation was a success, JSON is complete and expects no more operations
73-
* `JSONB_ERROR_NOMEM` - buffer is not large enough
107+
* `JSONB_ERROR_NOMEM` - buffer is not large enough, or `_auto` function couldn't reallocate
74108
* `JSONB_ERROR_INPUT` - user action don't match expected next token
75109
* `JSONB_ERROR_STACK` - user action would lead to out of boundaries access, increase `JSONB_MAX_DEPTH`!
110+
* `JSONB_ERROR_OVERFLOW` - automatic buffer increase would lead to an overflow, only use with `_auto` functions
76111

77112
Its worth mentioning that all `JSONB_ERROR_` prefixed codes are negative.
78113

0 commit comments

Comments
 (0)