Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
jsonbourne.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file jsonbourne.c
20 * @brief Bounded, two-pass JSON parsing and iterative DOM operations.
21 * @details Validation and materialization deliberately share the same grammar.
22 * A counting pass establishes exact record/text requirements before one backing
23 * allocation is split into aligned records and byte strings. Writers and copies
24 * likewise reuse a single walker so their sizing and output passes agree.
25 *
26 * @par Implementation invariants
27 * Cursors never exceed their extents; arithmetic is checked before advancing.
28 * A NULL pool/output base means measurement, not allocation failure. Fixed
29 * traversal frames replace recursion, and all per-call state remains local.
30 * The API still requires accessible, stable input and DOM pointers: structural
31 * checks cannot make arbitrary addresses safe to dereference.
32 * @see jsonbourne.h for public ownership, argument and return-value contracts.
33 */
34#include "jsonbourne.h"
35#include <stdlib.h>
36#include <string.h>
37
38/* Don't like weird error messages? I do, that's my prerogative.
39 * Hey, you have the code given, change it as you see fit.
40 */
41
42/**
43 * @name Reader diagnostic text
44 * @brief Display strings kept separate from machine-readable error codes.
45 * @details Centralizing text lets wording change without touching control flow.
46 * Every macro remains one source line so each message has one editing location.
47 * @{
48 */
49/** @brief Message for successful validation. */
50#define JSONBOURNE_READ_SUCCESS_MSG "JSONbourne found zero errors and is now insufferable at parties."
51/** @brief Missing container separator/closure diagnostic. */
52#define JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR_MSG "The comma and closing bracket have both rage-quit this syntax rave."
53/** @brief Missing key/value separator diagnostic. */
54#define JSONBOURNE_READ_ERROR_EXPECTED_COLON_MSG "This key and value eloped without filing the mandatory colon paperwork."
55/** @brief Invalid member-name diagnostic. */
56#define JSONBOURNE_READ_ERROR_EXPECTED_KEY_MSG "That member name needs quotes, not a fake moustache and a convincing backstory."
57/** @brief Invalid escape/surrogate diagnostic. */
58#define JSONBOURNE_READ_ERROR_INVALID_ESCAPE_MSG "That string escape tried to clear Unicode customs with a counterfeit surrogate."
59/** @brief Invalid numeric-token diagnostic. */
60#define JSONBOURNE_READ_ERROR_INVALID_NUMBER_MSG "That alleged number has been banned from every calculator in three dimensions."
61/** @brief Invalid true/false/null token diagnostic. */
62#define JSONBOURNE_READ_ERROR_LITERAL_MSG "Wishful thinking in a trench coat is still not a JSON value."
63/** @brief Premature end-of-input diagnostic. */
64#define JSONBOURNE_READ_ERROR_UNEXPECTED_END_MSG "Your input rolled the end credits while the document was still introducing itself."
65/** @brief Disallowed string control-byte diagnostic. */
66#define JSONBOURNE_READ_ERROR_INVALID_STRING_MSG "An unescaped control character is rearranging the furniture inside your string."
67/** @brief Allocation failure or insufficient caller-storage diagnostic. */
68#define JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION_MSG "Your DOM ordered a penthouse and the allocator delivered a shoebox with no floor."
69/** @brief Non-trivia input remaining after the root diagnostic. */
70#define JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT_MSG "Your document is finished but the trailing input has launched an unsolicited podcast."
71/** @brief Nesting-limit diagnostic. */
72#define JSONBOURNE_READ_ERROR_DEPTH_MSG "Your containers nested past the depth limit and filed for their own postcode."
73/** @brief Unterminated block-comment diagnostic. */
74#define JSONBOURNE_READ_ERROR_INVALID_COMMENT_MSG "Your block comment swallowed the entire document while waiting for its missing */."
75/** @brief Generic diagnostic, also used for unrecognized codes. */
76#define JSONBOURNE_READ_ERROR_UNKNOWN_MSG "Your JSON structure belongs in a modern-art museum, not in this parser."
77/** @brief Invalid Unicode scalar encoding diagnostic. */
78#define JSONBOURNE_READ_ERROR_INVALID_UTF8_MSG "UTF-8 cannot decode whatever experimental keyboard jazz these bytes are performing."
79/** @brief Resource-budget or arithmetic-limit diagnostic. */
80#define JSONBOURNE_READ_ERROR_LIMIT_MSG "Your resource or arithmetic limit refuses to finance infinity's latest shopping spree."
81/** @brief Invalid API arguments or buffer-layout diagnostic. */
82#define JSONBOURNE_READ_ERROR_INVALID_PARAMETER_MSG "Your arguments, flags or buffer layout have turned this call into a constitutional crisis."
83/** @} */
84
85/** @brief Derive the accepted bits from named options so flag remaps cannot stale this mask. */
86#define JSONBOURNE_READ_FLAG_MASK \
87 (JSONBOURNE_READ_SIMPLIFIED | JSONBOURNE_READ_JSON5 | JSONBOURNE_READ_RESERVED | \
88 JSONBOURNE_READ_TRACK_LOCATION)
89/** @brief C11 aggregate zero-initializer without byte-copying object representations. */
90#define JSONBOURNE_ZERO {0}
91/** @brief Required C11 alignment for an arena's typed record region. */
92#define JSONBOURNE_ALIGNOF(type) _Alignof(type)
93
94#if !JSONBOURNE_DISABLE_SIMD && defined(__SSE2__)
95#include <emmintrin.h>
96/** @brief Compile only baseline SSE2 scanning intrinsics on compatible x86 builds. */
97#define JSONBOURNE_HAS_SSE2 1
98#elif !JSONBOURNE_DISABLE_SIMD && defined(__aarch64__) && defined(__ARM_NEON)
99#include <arm_neon.h>
100/** @brief Compile AArch64 NEON scanning without imposing extra host CPU flags. */
101#define JSONBOURNE_HAS_NEON 1
102#endif
103
105
107 struct jsonbourne_read_limits limits;
108 /* Pointer-safe defaults are ceilings, not a promise of available RAM. */
110 limits.max_input_len = (size_t)PTRDIFF_MAX;
111 limits.max_memory = (size_t)PTRDIFF_MAX;
112 limits.max_vals = SIZE_MAX;
113 limits.max_str_len = (size_t)PTRDIFF_MAX;
114 return limits;
115}
116
117/**
118 * @brief Two-region arena shared by measurement and materialization.
119 * @details Fixed-size DOM records are kept together so variable-length text
120 * cannot misalign the next record. NULL bases count bytes without writing them.
121 */
123 unsigned char *val_pool; /**< Record region, or NULL while measuring. */
124 char *str_pool; /**< Text region, or NULL while measuring. */
125 size_t val_len; /**< Record bytes counted/reserved so far. */
126 size_t str_len; /**< Text bytes counted/reserved, including terminators. */
127 size_t val_cap; /**< Maximum record bytes available in this pass. */
128 size_t str_cap; /**< Maximum text bytes available in this pass. */
129 size_t max_memory; /**< Shared bound across both regions. */
130 jsonbourne_read_code code; /**< Arena failure carried separately from grammar errors. */
131};
132
133/**
134 * @brief Reserve checked space in one arena region or merely account for it.
135 * @param[in,out] pool Arena counters, capacities and sticky error state.
136 * @param[in] len Bytes required, including any caller-supplied terminator space.
137 * @param[in] is_str Nonzero selects text; zero selects typed records.
138 * @return Region address, or NULL while measuring/on failure; inspect pool->code
139 * to distinguish a successful count from an error.
140 * @details Subtractions are guarded before use so neither capacity checks nor
141 * the combined-region budget can wrap around size_t.
142 */
143static inline void *jsonbourne_pool_take(struct jsonbourne_pool *pool, size_t len, int is_str) {
144 size_t *used = is_str ? &pool->str_len : &pool->val_len;
145 const size_t other = is_str ? pool->val_len : pool->str_len;
146 const size_t cap = is_str ? pool->str_cap : pool->val_cap;
147 void *out = NULL;
148 if (*used > cap || len > cap - *used || other > pool->max_memory ||
149 *used > pool->max_memory - other || len > pool->max_memory - other - *used) {
151 return NULL;
152 }
153 if (is_str && pool->str_pool)
154 out = pool->str_pool + *used;
155 if (!is_str && pool->val_pool)
156 out = pool->val_pool + *used;
157 *used += len;
158 return out;
159}
160
161/**
162 * @brief Account for or copy a byte extent into the text region.
163 * @param[in,out] pool Destination arena or counting state.
164 * @param[in] src Accessible source bytes; NULL is permitted only for len zero.
165 * @param[in] len Exact byte count, independent of embedded NULs.
166 * @return 1 on success, 0 when reservation fails.
167 * @note Counting skips source reads; materialization uses a bounded copy loop.
168 */
169static inline int jsonbourne_pool_copy(struct jsonbourne_pool *pool, const char *src, size_t len) {
170 char *dst = (char *)jsonbourne_pool_take(pool, len, 1);
171 size_t idx;
172 if (pool->code)
173 return 0;
174 if (dst)
175 for (idx = 0; idx < len; ++idx)
176 dst[idx] = src[idx];
177 return 1;
178}
179
180/**
181 * @brief Find bytes that need no string escaping or Unicode decoding.
182 * @param[in] src Accessible input extent; no padding or alignment is assumed.
183 * @param[in] len Available bytes.
184 * @param[in] quote Current string delimiter, which terminates the fast path.
185 * @return Prefix length containing printable ASCII other than quote/backslash.
186 * @details Vector loads require a complete 16-byte block. The scalar tail keeps
187 * page-boundary inputs safe; high-bit bytes return to strict UTF-8 validation.
188 */
189static inline size_t jsonbourne_ascii_span(const unsigned char *src, size_t len,
190 unsigned char quote) {
191 size_t pos = 0;
192#if defined(JSONBOURNE_HAS_SSE2)
193 const __m128i quotes = _mm_set1_epi8((char)quote);
194 const __m128i slashes = _mm_set1_epi8('\\');
195 const __m128i controls = _mm_set1_epi8(0x20);
196 while (len - pos >= 16) {
197 const __m128i block = _mm_loadu_si128((const __m128i *)(const void *)(src + pos));
198 /* Signed lanes also classify 0x80..0xff as below 0x20, stopping before UTF-8. */
199 const __m128i special =
200 _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(block, quotes), _mm_cmpeq_epi8(block, slashes)),
201 _mm_cmplt_epi8(block, controls));
202 const unsigned mask = (unsigned)_mm_movemask_epi8(special);
203 if (mask)
204 return pos + (size_t)__builtin_ctz(mask);
205 pos += 16;
206 }
207#elif defined(JSONBOURNE_HAS_NEON)
208 while (len - pos >= 16) {
209 const uint8x16_t block = vld1q_u8(src + pos);
210 const uint8x16_t special =
211 vorrq_u8(vorrq_u8(vceqq_u8(block, vdupq_n_u8(quote)), vceqq_u8(block, vdupq_n_u8('\\'))),
212 vorrq_u8(vcltq_u8(block, vdupq_n_u8(0x20)), vcgeq_u8(block, vdupq_n_u8(0x80))));
213 if (vmaxvq_u8(special))
214 break;
215 pos += 16;
216 }
217#endif
218 while (pos < len && src[pos] >= 0x20 && src[pos] < 0x80 && src[pos] != quote && src[pos] != '\\')
219 ++pos;
220 return pos;
221}
222
223/**
224 * @brief Recognize only the four JSON whitespace bytes, independently of locale.
225 * @param[in] chr Byte to classify.
226 * @return Nonzero for space, tab, CR or LF; zero otherwise.
227 */
228static inline int jsonbourne_char_is_space(unsigned char chr) {
229 return chr == ' ' || chr == '\t' || chr == '\r' || chr == '\n';
230}
231
232/**
233 * @brief Skip a bounded run of JSON whitespace with the available SIMD baseline.
234 * @param[in] src Accessible input extent without padding requirements.
235 * @param[in] len Bytes available for inspection.
236 * @return Whitespace prefix length, never greater than len.
237 * @note The first non-whitespace byte is left for the grammar, including UTF-8.
238 */
239static inline size_t jsonbourne_space_span(const unsigned char *src, size_t len) {
240 size_t pos = 0;
241#if defined(JSONBOURNE_HAS_SSE2)
242 while (len - pos >= 16) {
243 const __m128i block = _mm_loadu_si128((const __m128i *)(const void *)(src + pos));
244 const __m128i spaces = _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(block, _mm_set1_epi8(' ')),
245 _mm_cmpeq_epi8(block, _mm_set1_epi8('\t'))),
246 _mm_or_si128(_mm_cmpeq_epi8(block, _mm_set1_epi8('\r')),
247 _mm_cmpeq_epi8(block, _mm_set1_epi8('\n'))));
248 const unsigned mask = (unsigned)_mm_movemask_epi8(spaces);
249 if (mask != 0xffffU)
250 return pos + (size_t)__builtin_ctz((~mask) & 0xffffU);
251 pos += 16;
252 }
253#elif defined(JSONBOURNE_HAS_NEON)
254 while (len - pos >= 16) {
255 const uint8x16_t block = vld1q_u8(src + pos);
256 const uint8x16_t spaces =
257 vorrq_u8(vorrq_u8(vceqq_u8(block, vdupq_n_u8(' ')), vceqq_u8(block, vdupq_n_u8('\t'))),
258 vorrq_u8(vceqq_u8(block, vdupq_n_u8('\r')), vceqq_u8(block, vdupq_n_u8('\n'))));
259 if (vminvq_u8(spaces) != 255)
260 break;
261 pos += 16;
262 }
263#endif
264 while (pos < len && jsonbourne_char_is_space(src[pos]))
265 ++pos;
266 return pos;
267}
268
269/**
270 * @brief Decode an ASCII hexadecimal digit without locale-sensitive conversion.
271 * @param[in] chr Byte to inspect.
272 * @return Integer 0 through 15, or -1 if the byte is not a hex digit.
273 */
274static inline int jsonbourne_hex_to_digit(unsigned char chr) {
275 if (chr >= '0' && chr <= '9')
276 return chr - '0';
277 if (chr >= 'a' && chr <= 'f')
278 return chr - 'a' + 10;
279 if (chr >= 'A' && chr <= 'F')
280 return chr - 'A' + 10;
281 return -1;
282}
283
284/**
285 * @brief Recognize the decimal digits permitted by JSON number grammar.
286 * @param[in] chr Byte to inspect.
287 * @return Nonzero for ASCII 0 through 9, zero otherwise.
288 */
289static inline int jsonbourne_char_is_digit(unsigned char chr) { return chr >= '0' && chr <= '9'; }
290
291/**
292 * @brief Classify this reader's relaxed, ASCII-only unquoted-key alphabet.
293 * @param[in] chr Byte to inspect.
294 * @return Nonzero for letters, digits, underscore or dollar sign.
295 * @note This convenience alphabet is not a complete ECMAScript IdentifierName
296 * implementation; it deliberately does not imply full JSON5 conformance.
297 */
298static inline int jsonbourne_char_is_id(unsigned char chr) {
299 return (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z') ||
300 jsonbourne_char_is_digit(chr) || chr == '_' || chr == '$';
301}
302
303/**
304 * @brief Validate exactly one UTF-8 scalar without reading beyond the extent.
305 * @param[in] src First byte of a possible UTF-8 sequence.
306 * @param[in] len Available bytes, possibly fewer than a complete sequence.
307 * @return Sequence length 1 through 4, or zero for an invalid/truncated sequence.
308 * @details Lead-specific second-byte bounds reject overlong encodings, UTF-16
309 * surrogate code points and values above U+10FFFF, not just bad continuation bits.
310 */
311static inline size_t jsonbourne_utf8_len(const unsigned char *src, size_t len) {
312 unsigned char first;
313 size_t count;
314 size_t idx;
315 if (!len)
316 return 0;
317 first = src[0];
318 if (first < 0x80)
319 return 1;
320 if (first >= 0xc2 && first <= 0xdf)
321 count = 2;
322 else if (first >= 0xe0 && first <= 0xef)
323 count = 3;
324 else if (first >= 0xf0 && first <= 0xf4)
325 count = 4;
326 else
327 return 0;
328 if (len < count)
329 return 0;
330 for (idx = 1; idx < count; ++idx)
331 if ((src[idx] & 0xc0) != 0x80)
332 return 0;
333 if ((first == 0xe0 && src[1] < 0xa0) || (first == 0xed && src[1] >= 0xa0) ||
334 (first == 0xf0 && src[1] < 0x90) || (first == 0xf4 && src[1] >= 0x90))
335 return 0;
336 return count;
337}
338
339/**
340 * @brief Recognize a numeric prefix without converting or rounding its value.
341 * @param[in] src Accessible token candidate.
342 * @param[in] len Candidate extent, which may also include following input.
343 * @param[in] flg Enabled numeric spelling extensions.
344 * @param[out] read_len Consumed token bytes on success; unchanged on failure.
345 * @return 1 for a valid numeric prefix, 0 for invalid/incomplete grammar.
346 * @note The caller must check the following delimiter or require read_len == len;
347 * otherwise a valid prefix could conceal an invalid suffix.
348 */
349static inline int jsonbourne_read_num_token(const unsigned char *src, size_t len,
350 jsonbourne_read_flag flg, size_t *read_len) {
351 size_t pos = 0;
352 size_t int_pos;
353 size_t int_len;
354 size_t frac_len = 0;
355 int decimal = 0;
356 if (!len)
357 return 0;
358 if (src[pos] == '-' || src[pos] == '+') {
359 if (src[pos] == '+' && !(flg & JSONBOURNE_READ_ALLOW_PLUS_SIGN))
360 return 0;
361 if (++pos == len)
362 return 0;
363 }
365 if (len - pos >= 8 && memcmp(src + pos, "Infinity", 8) == 0) {
366 *read_len = pos + 8;
367 return 1;
368 }
369 if (len - pos >= 3 && memcmp(src + pos, "NaN", 3) == 0) {
370 *read_len = pos + 3;
371 return 1;
372 }
373 }
374 if ((flg & JSONBOURNE_READ_ALLOW_HEX_NUM) && len - pos >= 2 && src[pos] == '0' &&
375 (src[pos + 1] == 'x' || src[pos + 1] == 'X')) {
376 pos += 2;
377 int_pos = pos;
378 while (pos < len && jsonbourne_hex_to_digit(src[pos]) >= 0)
379 ++pos;
380 if (pos == int_pos)
381 return 0;
382 *read_len = pos;
383 return 1;
384 }
385 int_pos = pos;
386 while (pos < len && jsonbourne_char_is_digit(src[pos]))
387 ++pos;
388 int_len = pos - int_pos;
389 if (int_len > 1 && src[int_pos] == '0')
390 return 0;
391 if (pos < len && src[pos] == '.') {
392 size_t frac_pos = ++pos;
393 decimal = 1;
394 while (pos < len && jsonbourne_char_is_digit(src[pos]))
395 ++pos;
396 frac_len = pos - frac_pos;
397 }
398 if (!int_len && !frac_len)
399 return 0;
400 if ((!int_len || (decimal && !frac_len)) && !(flg & JSONBOURNE_READ_ALLOW_DECIMAL_POINT))
401 return 0;
402 if (pos < len && (src[pos] == 'e' || src[pos] == 'E')) {
403 size_t exp_pos;
404 ++pos;
405 if (pos < len && (src[pos] == '+' || src[pos] == '-'))
406 ++pos;
407 exp_pos = pos;
408 while (pos < len && jsonbourne_char_is_digit(src[pos]))
409 ++pos;
410 if (pos == exp_pos)
411 return 0;
412 }
413 *read_len = pos;
414 return 1;
415}
416
417/** @brief Per-call parser state; no mutable global state or input modification is needed. */
419 const unsigned char *src; /**< Immutable input extent. */
420 size_t len; /**< Total supplied bytes. */
421 size_t pos; /**< Next grammar byte, always at most len. */
422 jsonbourne_read_flag flg; /**< Validated named-option mask. */
423 size_t val_count; /**< Root and nested values consumed so far. */
424 jsonbourne_read_code code; /**< First grammar/argument failure. */
425 size_t loc_pos; /**< Input offset already scanned for locations. */
426 size_t line; /**< Current one-based LF-delimited line. */
427 size_t line_pos; /**< Offset immediately after the last scanned LF. */
428 struct jsonbourne_read_limits limits; /**< Effective per-call budgets. */
429 struct jsonbourne_pool pool; /**< Counting or materializing arena. */
430};
431
432/**
433 * @brief One open container, replacing an equivalent recursive parser call.
434 * @details state 0 permits an initial member or empty closure; state 1 expects
435 * an item after a separator; state 2 follows an item. Keeping 1 distinct from 0
436 * is what lets closure distinguish a trailing comma from an empty container.
437 */
439 void *ctn; /**< Object/array payload, NULL during measurement. */
440 void *tail; /**< Last entry for constant-time ordered appends. */
441 size_t len; /**< Completed/reserved member or element count. */
442 unsigned char type; /**< Object or array tag. */
443 unsigned char state; /**< Initial, after-separator or after-item state. */
444 unsigned char is_global; /**< Brace-less object closes at end of input. */
445};
446
447/**
448 * @brief Preserve the first grammar failure while supporting short-circuit returns.
449 * @param[in,out] ctx Read context whose code may still indicate success.
450 * @param[in] code Failure to record if no earlier grammar error exists.
451 * @return Always zero, allowing direct use in a failing parser expression.
452 */
453static inline int jsonbourne_set_read_error(struct jsonbourne_read_ctx *ctx,
455 if (!ctx->code)
456 ctx->code = code;
457 return 0;
458}
459
460/**
461 * @brief Advance a lazy location cursor instead of rescanning each node's prefix.
462 * @param[in,out] ctx Materializing read state with cached line information.
463 * @param[in] pos Requested input byte offset; must not precede ctx->loc_pos.
464 * @param[out] line One-based line number at pos.
465 * @param[out] row Zero-based byte column at pos.
466 * @note Monotonic requests keep total location bookkeeping linear in input size.
467 */
468static inline void jsonbourne_read_locate(struct jsonbourne_read_ctx *ctx, size_t pos, size_t *line,
469 size_t *row) {
470 while (ctx->loc_pos < pos) {
471 if (ctx->src[ctx->loc_pos++] == '\n') {
472 ++ctx->line;
473 ctx->line_pos = ctx->loc_pos;
474 }
475 }
476 *line = ctx->line;
477 *row = pos - ctx->line_pos;
478}
479
480/**
481 * @brief Consume whitespace and enabled comments without swallowing grammar bytes.
482 * @param[in,out] ctx Input cursor and enabled syntax options.
483 * @return 1 at the next significant byte/end, 0 for an unterminated block comment.
484 * @note A failing block comment restores its opening offset so diagnostics point
485 * at the construct that needs repair rather than merely at end of input.
486 */
487static inline int jsonbourne_skip_trivia(struct jsonbourne_read_ctx *ctx) {
488 for (;;) {
489 ctx->pos += jsonbourne_space_span(ctx->src + ctx->pos, ctx->len - ctx->pos);
490 if (!(ctx->flg & JSONBOURNE_READ_ALLOW_COMMENTS) || ctx->len - ctx->pos < 2 ||
491 ctx->src[ctx->pos] != '/')
492 return 1;
493 if (ctx->src[ctx->pos + 1] == '/') {
494 ctx->pos += 2;
495 while (ctx->pos < ctx->len && ctx->src[ctx->pos] != '\n' && ctx->src[ctx->pos] != '\r')
496 ++ctx->pos;
497 } else if (ctx->src[ctx->pos + 1] == '*') {
498 const size_t start = ctx->pos;
499 ctx->pos += 2;
500 while (ctx->len - ctx->pos >= 2 &&
501 !(ctx->src[ctx->pos] == '*' && ctx->src[ctx->pos + 1] == '/'))
502 ++ctx->pos;
503 if (ctx->len - ctx->pos < 2) {
504 ctx->pos = start;
506 }
507 ctx->pos += 2;
508 } else
509 return 1;
510 }
511}
512
513/**
514 * @brief Enforce a decoded-string budget before reserving any more text bytes.
515 * @param[in,out] ctx Parser and arena state.
516 * @param[in] start Text counter at the beginning of the current decoded string.
517 * @param[in] bytes Decoded source bytes to append when materializing.
518 * @param[in] count Number of bytes, excluding any final terminator.
519 * @return 1 if appended/counted, 0 for a string or arena limit failure.
520 * @note The budget follows decoded size, so escapes cannot bypass it.
521 */
522static inline int jsonbourne_read_str_bytes(struct jsonbourne_read_ctx *ctx, size_t start,
523 const char *bytes, size_t count) {
524 if (ctx->pool.str_len - start > ctx->limits.max_str_len ||
525 count > ctx->limits.max_str_len - (ctx->pool.str_len - start))
527 return jsonbourne_pool_copy(&ctx->pool, bytes, count);
528}
529
530/**
531 * @brief Consume the four hexadecimal digits following a Unicode escape marker.
532 * @param[in,out] ctx Cursor positioned at the first hex digit.
533 * @param[out] unit Decoded UTF-16 code unit; undefined as a result on failure.
534 * @return 1 for four valid digits, 0 with INVALID_ESCAPE otherwise.
535 * @note A code unit is not necessarily a scalar; the string reader pairs surrogates.
536 */
537static inline int jsonbourne_read_hex4(struct jsonbourne_read_ctx *ctx, uint32_t *unit) {
538 size_t idx;
539 *unit = 0;
540 if (ctx->len - ctx->pos < 4)
542 for (idx = 0; idx < 4; ++idx) {
543 const int digit = jsonbourne_hex_to_digit(ctx->src[ctx->pos]);
544 if (digit < 0)
546 *unit = (*unit << 4) | (unsigned)digit;
547 ++ctx->pos;
548 }
549 return 1;
550}
551
552/**
553 * @brief Encode a validated Unicode scalar into the decoded text arena.
554 * @param[in,out] ctx Parser/arena and decoded-string budget.
555 * @param[in] start Current string's initial text counter.
556 * @param[in] codepoint Scalar already checked for surrogate/range validity.
557 * @return 1 if its UTF-8 bytes fit, 0 on an arena/string limit.
558 * @pre codepoint is at most U+10FFFF and is not a surrogate code point.
559 */
560static inline int jsonbourne_read_utf8_encode(struct jsonbourne_read_ctx *ctx, size_t start,
561 uint32_t codepoint) {
562 char bytes[4];
563 size_t len;
564 if (codepoint < 0x80) {
565 bytes[0] = (char)codepoint;
566 len = 1;
567 } else if (codepoint < 0x800) {
568 bytes[0] = (char)(0xc0 | (codepoint >> 6));
569 bytes[1] = (char)(0x80 | (codepoint & 0x3f));
570 len = 2;
571 } else if (codepoint < 0x10000) {
572 bytes[0] = (char)(0xe0 | (codepoint >> 12));
573 bytes[1] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
574 bytes[2] = (char)(0x80 | (codepoint & 0x3f));
575 len = 3;
576 } else {
577 bytes[0] = (char)(0xf0 | (codepoint >> 18));
578 bytes[1] = (char)(0x80 | ((codepoint >> 12) & 0x3f));
579 bytes[2] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
580 bytes[3] = (char)(0x80 | (codepoint & 0x3f));
581 len = 4;
582 }
583 return jsonbourne_read_str_bytes(ctx, start, bytes, len);
584}
585
586/**
587 * @brief Decode one quoted string or enabled unquoted key through the same two passes.
588 * @param[in,out] ctx Cursor at the string/key and arena state.
589 * @param[in] key Nonzero permits the unquoted-key path when its option is enabled.
590 * @param[out] out String record, or NULL on a successful counting pass.
591 * @return 1 for a complete decoded string, 0 with parser/arena failure recorded.
592 * @details Escape decoding and raw UTF-8 validation converge on the same decoded
593 * byte budget. A separate trailing NUL is stored without counting it in len.
594 */
595static inline int jsonbourne_read_str(struct jsonbourne_read_ctx *ctx, int key,
596 jsonbourne_str **out) {
597 const size_t pos = ctx->pos;
598 const size_t start = ctx->pool.str_len;
599 const int has_loc = (ctx->flg & JSONBOURNE_READ_TRACK_LOCATION) != 0;
601 &ctx->pool, has_loc ? sizeof(struct jsonbourne_str_loc) : sizeof(struct jsonbourne_str), 0);
602 unsigned char quote;
603 int complete = 0;
604 if (ctx->pool.code)
605 return 0;
606 if (ctx->pos >= ctx->len)
608 quote = ctx->src[ctx->pos];
609 if (quote != '"' && !(quote == '\'' && (ctx->flg & JSONBOURNE_READ_ALLOW_SINGLE_QUOTED_STR))) {
610 size_t len;
611 if (!key || !(ctx->flg & JSONBOURNE_READ_ALLOW_UNQUOTED_KEY))
613 while (ctx->pos < ctx->len && jsonbourne_char_is_id(ctx->src[ctx->pos]))
614 ++ctx->pos;
615 len = ctx->pos - pos;
616 if (!len)
618 if (!jsonbourne_read_str_bytes(ctx, start, (const char *)ctx->src + pos, len))
619 return 0;
620 complete = 1;
621 } else {
622 ++ctx->pos;
623 while (ctx->pos < ctx->len) {
624 const size_t run = jsonbourne_ascii_span(ctx->src + ctx->pos, ctx->len - ctx->pos, quote);
625 unsigned char chr;
626 if (!jsonbourne_read_str_bytes(ctx, start, (const char *)ctx->src + ctx->pos, run))
627 return 0;
628 ctx->pos += run;
629 if (ctx->pos == ctx->len)
630 break;
631 chr = ctx->src[ctx->pos++];
632 if (chr == quote) {
633 complete = 1;
634 break;
635 }
636 if (chr == '\\') {
637 char decoded;
638 if (ctx->pos == ctx->len)
640 chr = ctx->src[ctx->pos++];
641 switch (chr) {
642 case '"':
643 case '\\':
644 case '/':
645 decoded = (char)chr;
646 break;
647 case 'b':
648 decoded = '\b';
649 break;
650 case 'f':
651 decoded = '\f';
652 break;
653 case 'n':
654 decoded = '\n';
655 break;
656 case 'r':
657 decoded = '\r';
658 break;
659 case 't':
660 decoded = '\t';
661 break;
662 case '\'':
665 decoded = '\'';
666 break;
667 case 'u': {
668 uint32_t codepoint;
669 if (!jsonbourne_read_hex4(ctx, &codepoint))
670 return 0;
671 /* UTF-16 halves are valid only as a pair; neither half may leak into UTF-8. */
672 if (codepoint >= 0xd800 && codepoint <= 0xdbff) {
673 uint32_t low;
674 if (ctx->len - ctx->pos < 2 || ctx->src[ctx->pos] != '\\' ||
675 ctx->src[ctx->pos + 1] != 'u')
677 ctx->pos += 2;
678 if (!jsonbourne_read_hex4(ctx, &low))
679 return 0;
680 if (low < 0xdc00 || low > 0xdfff)
682 codepoint = 0x10000 + ((codepoint - 0xd800) << 10) + low - 0xdc00;
683 } else if (codepoint >= 0xdc00 && codepoint <= 0xdfff)
685 if (!jsonbourne_read_utf8_encode(ctx, start, codepoint))
686 return 0;
687 continue;
688 }
689 case '\n':
690 case '\r':
693 if (chr == '\r' && ctx->pos < ctx->len && ctx->src[ctx->pos] == '\n')
694 ++ctx->pos;
695 continue;
696 default:
698 }
699 if (!jsonbourne_read_str_bytes(ctx, start, &decoded, 1))
700 return 0;
701 } else if (chr >= 0x80) {
702 const size_t position = ctx->pos - 1;
703 const size_t len = jsonbourne_utf8_len(ctx->src + position, ctx->len - position);
704 if (!len) {
705 ctx->pos = position;
707 }
708 if (!jsonbourne_read_str_bytes(ctx, start, (const char *)ctx->src + position, len))
709 return 0;
710 ctx->pos = position + len;
711 } else {
712 const char decoded = (char)chr;
713 if ((chr != '\n' && chr != '\r') || !(ctx->flg & JSONBOURNE_READ_ALLOW_MULTILINE_STR))
715 if (!jsonbourne_read_str_bytes(ctx, start, &decoded, 1))
716 return 0;
717 }
718 }
719 }
720 if (!complete)
722 if (!jsonbourne_pool_copy(&ctx->pool, "", 1))
723 return 0;
724 if (str) {
725 str->str = ctx->pool.str_pool + start;
726 str->len = ctx->pool.str_len - start - 1;
727 if (has_loc) {
728 jsonbourne_str_loc *extended = (jsonbourne_str_loc *)str;
729 extended->pos = pos;
730 jsonbourne_read_locate(ctx, pos, &extended->line, &extended->col);
731 }
732 }
733 *out = str;
734 return 1;
735}
736
737/**
738 * @brief Verify the token boundary separately from the token's own spelling.
739 * @param[in] ctx Input extent and comment policy.
740 * @param[in] pos Candidate end offset, no greater than ctx->len.
741 * @return Nonzero at input end or a permissible token boundary.
742 * @details Prevents a valid prefix such as true in truex, or 1 in 1abc, from
743 * being admitted as a complete scalar value.
744 */
745static inline int jsonbourne_is_delimiter(const struct jsonbourne_read_ctx *ctx, size_t pos) {
746 unsigned char chr;
747 if (pos == ctx->len)
748 return 1;
749 chr = ctx->src[pos];
750 return jsonbourne_char_is_space(chr) || chr == ',' || chr == ']' || chr == '}' ||
751 (chr == '/' && (ctx->flg & JSONBOURNE_READ_ALLOW_COMMENTS));
752}
753
754/**
755 * @brief Consume a scalar or push a new container without a recursive call.
756 * @param[in,out] ctx Read cursor, budgets and arena.
757 * @param[out] out Result record, or NULL while counting.
758 * @param[in,out] stack Fixed storage for open containers.
759 * @param[in,out] depth Number of active frames; checked before every push.
760 * @param[in] is_global Nonzero requests a brace-less object at the current cursor.
761 * @return 1 for a scalar/opened container, 0 for grammar or resource failure.
762 * @note Containers are completed by jsonbourne_read_document(), allowing nesting
763 * to consume bounded frame storage rather than the C call stack.
764 */
765static inline int jsonbourne_read_val(struct jsonbourne_read_ctx *ctx, jsonbourne_val **out,
766 struct jsonbourne_read_frame *stack, size_t *depth,
767 int is_global) {
768 const int has_loc = (ctx->flg & JSONBOURNE_READ_TRACK_LOCATION) != 0;
769 jsonbourne_val *val;
770 unsigned char chr;
771 if (ctx->val_count == ctx->limits.max_vals)
773 ++ctx->val_count;
775 &ctx->pool, has_loc ? sizeof(struct jsonbourne_val_loc) : sizeof(struct jsonbourne_val), 0);
776 if (ctx->pool.code)
777 return 0;
778 if (val) {
779 val->ptr = NULL;
780 if (has_loc) {
781 jsonbourne_val_loc *extended = (jsonbourne_val_loc *)val;
782 extended->pos = ctx->pos;
783 jsonbourne_read_locate(ctx, ctx->pos, &extended->line, &extended->col);
784 }
785 }
786 *out = val;
787 if (ctx->pos == ctx->len && !is_global)
789 chr = ctx->pos < ctx->len ? ctx->src[ctx->pos] : 0;
790 if (is_global || chr == '{' || chr == '[') {
792 const int obj = is_global || chr == '{';
793 void *ctn;
794 if (*depth == ctx->limits.max_depth || *depth == JSONBOURNE_READER_DEPTH_LIMIT)
797 &ctx->pool, obj ? sizeof(struct jsonbourne_obj) : sizeof(struct jsonbourne_arr), 0);
798 if (ctx->pool.code)
799 return 0;
800 if (val) {
802 val->ptr = ctn;
803 }
804 frame = &stack[(*depth)++];
805 frame->ctn = ctn;
806 frame->tail = NULL;
807 frame->len = 0;
808 frame->type = (unsigned char)(obj ? JSONBOURNE_TYPE_OBJ : JSONBOURNE_TYPE_ARR);
809 frame->state = 0;
810 frame->is_global = (unsigned char)is_global;
811 if (ctn) {
812 if (obj)
813 ((jsonbourne_obj *)ctn)->first = NULL;
814 else
815 ((jsonbourne_arr *)ctn)->first = NULL;
816 }
817 if (!is_global)
818 ++ctx->pos;
819 return 1;
820 }
821 if (chr == '"' || (chr == '\'' && (ctx->flg & JSONBOURNE_READ_ALLOW_SINGLE_QUOTED_STR))) {
822 jsonbourne_str *str;
823 if (!jsonbourne_read_str(ctx, 0, &str))
824 return 0;
825 if (val) {
827 val->ptr = str;
828 }
829 return 1;
830 }
831 if (chr == 't' || chr == 'f' || chr == 'n') {
832 const char *literal = chr == 't' ? "true" : chr == 'f' ? "false" : "null";
833 const size_t len = chr == 'f' ? 5 : 4;
834 if (ctx->len - ctx->pos < len || memcmp(ctx->src + ctx->pos, literal, len) != 0 ||
835 !jsonbourne_is_delimiter(ctx, ctx->pos + len))
837 ctx->pos += len;
838 if (val)
839 val->type = chr == 't' ? JSONBOURNE_TYPE_TRUE
840 : chr == 'f' ? JSONBOURNE_TYPE_FALSE
842 return 1;
843 }
844 {
845 size_t len = 0;
846 const size_t start = ctx->pool.str_len;
847 jsonbourne_num *num;
848 if (!jsonbourne_read_num_token(ctx->src + ctx->pos, ctx->len - ctx->pos, ctx->flg, &len) ||
849 !jsonbourne_is_delimiter(ctx, ctx->pos + len))
851 num = (jsonbourne_num *)jsonbourne_pool_take(&ctx->pool, sizeof(struct jsonbourne_num), 0);
852 if (ctx->pool.code ||
853 !jsonbourne_pool_copy(&ctx->pool, (const char *)ctx->src + ctx->pos, len) ||
854 !jsonbourne_pool_copy(&ctx->pool, "", 1))
855 return 0;
856 ctx->pos += len;
857 if (val) {
859 val->ptr = num;
860 num->str = ctx->pool.str_pool + start;
861 num->len = len;
862 }
863 return 1;
864 }
865}
866
867/**
868 * @brief Drive one complete JSON document using explicit container frames.
869 * @param[in,out] ctx Initialized counting or materializing read context.
870 * @param[out] root Parsed root, or NULL while counting.
871 * @return 1 only when the root and all trailing trivia consume the full input.
872 * @details The frame state distinguishes empty closure, post-separator closure
873 * and a completed item. Sharing this state machine across both passes prevents
874 * the allocator's size prediction from using a different grammar.
875 */
876static inline int jsonbourne_read_document(struct jsonbourne_read_ctx *ctx, jsonbourne_val **root) {
878 size_t depth = 0;
879 int is_global;
880 if (!jsonbourne_skip_trivia(ctx))
881 return 0;
883 (ctx->pos == ctx->len || ctx->src[ctx->pos] != '{');
884 if (!jsonbourne_read_val(ctx, root, stack, &depth, is_global))
885 return 0;
886 while (depth) {
887 struct jsonbourne_read_frame *frame = &stack[depth - 1];
888 jsonbourne_val *child = NULL;
889 jsonbourne_val **dst = &child;
890 const unsigned char close = frame->type == JSONBOURNE_TYPE_OBJ ? '}' : ']';
891 int closing;
892 if (!jsonbourne_skip_trivia(ctx))
893 return 0;
894 closing = frame->is_global ? ctx->pos == ctx->len
895 : ctx->pos < ctx->len && ctx->src[ctx->pos] == close;
896 if (frame->state == 2 && !closing) {
897 if (ctx->pos == ctx->len)
899 if (ctx->src[ctx->pos] == ',')
900 ++ctx->pos;
901 else if (!(ctx->flg & JSONBOURNE_READ_ALLOW_NO_COMMAS))
903 frame->state = 1;
904 if (!jsonbourne_skip_trivia(ctx))
905 return 0;
906 closing = frame->is_global ? ctx->pos == ctx->len
907 : ctx->pos < ctx->len && ctx->src[ctx->pos] == close;
908 }
909 if (closing) {
910 if (frame->state == 1 && !(ctx->flg & JSONBOURNE_READ_ALLOW_TRAILING_COMMAS))
912 if (frame->ctn) {
913 if (frame->type == JSONBOURNE_TYPE_OBJ)
914 ((jsonbourne_obj *)frame->ctn)->len = frame->len;
915 else
916 ((jsonbourne_arr *)frame->ctn)->len = frame->len;
917 }
918 if (!frame->is_global)
919 ++ctx->pos;
920 --depth;
921 continue;
922 }
923 if (ctx->pos == ctx->len)
925 if (frame->len == SIZE_MAX)
927 if (frame->type == JSONBOURNE_TYPE_OBJ) {
929 &ctx->pool, sizeof(struct jsonbourne_obj_entry), 0);
930 jsonbourne_str *name;
931 if (ctx->pool.code || !jsonbourne_read_str(ctx, 1, &name) || !jsonbourne_skip_trivia(ctx))
932 return 0;
933 if (ctx->pos == ctx->len)
935 if (ctx->src[ctx->pos] != ':' &&
936 !(ctx->src[ctx->pos] == '=' && (ctx->flg & JSONBOURNE_READ_ALLOW_EQUALS)))
938 ++ctx->pos;
939 if (elem) {
940 elem->key = name;
941 elem->val = NULL;
942 elem->next = NULL;
943 if (frame->tail)
944 ((jsonbourne_obj_entry *)frame->tail)->next = elem;
945 else
946 ((jsonbourne_obj *)frame->ctn)->first = elem;
947 dst = &elem->val;
948 }
949 frame->tail = elem;
950 } else {
952 &ctx->pool, sizeof(struct jsonbourne_arr_entry), 0);
953 if (ctx->pool.code)
954 return 0;
955 if (elem) {
956 elem->val = NULL;
957 elem->next = NULL;
958 if (frame->tail)
959 ((jsonbourne_arr_entry *)frame->tail)->next = elem;
960 else
961 ((jsonbourne_arr *)frame->ctn)->first = elem;
962 dst = &elem->val;
963 }
964 frame->tail = elem;
965 }
966 ++frame->len;
967 frame->state = 2;
968 if (!jsonbourne_skip_trivia(ctx) || !jsonbourne_read_val(ctx, dst, stack, &depth, 0))
969 return 0;
970 }
971 if (!jsonbourne_skip_trivia(ctx))
972 return 0;
973 if (ctx->pos != ctx->len)
975 return 1;
976}
977
978/**
979 * @brief Establish cursor/limit invariants before any grammar byte is accessed.
980 * @param[out] ctx Fresh context, also safe to report after initialization failure.
981 * @param[in] src Input bytes; NULL is valid only with len zero.
982 * @param[in] len Input extent in bytes.
983 * @param[in] flg Requested named options, checked against accepted bits.
984 * @param[in] limits Optional caller budgets; NULL selects compiled defaults.
985 * @return 1 for valid initial state, 0 with an argument/resource error recorded.
986 * @note PTRDIFF_MAX bounds keep later pointer arithmetic representable; an empty
987 * sentinel replaces NULL input so even zero-byte parser paths have a valid base.
988 */
989static inline int jsonbourne_read_ctx_init(struct jsonbourne_read_ctx *ctx, const void *src,
990 size_t len, jsonbourne_read_flag flg,
991 const jsonbourne_read_limits *limits) {
992 const struct jsonbourne_read_ctx empty = JSONBOURNE_ZERO;
993 *ctx = empty;
994 ctx->src = (const unsigned char *)src;
995 ctx->len = len;
996 ctx->flg = flg;
997 ctx->line = 1;
999 ctx->pool.val_cap = SIZE_MAX;
1000 ctx->pool.str_cap = SIZE_MAX;
1001 ctx->pool.max_memory =
1002 ctx->limits.max_memory < (size_t)PTRDIFF_MAX ? ctx->limits.max_memory : (size_t)PTRDIFF_MAX;
1003 if ((!src && len) || (flg & ~(size_t)JSONBOURNE_READ_FLAG_MASK) ||
1006 if (len > ctx->limits.max_input_len || len > (size_t)PTRDIFF_MAX)
1008 if (!src)
1009 ctx->src = (const unsigned char *)"";
1010 return 1;
1011}
1012
1013/**
1014 * @brief Normalize parser/arena failure into an optional public diagnostic.
1015 * @param[in] ctx Context after initialization or parsing, successful or failed.
1016 * @param[out] err Destination, or NULL to skip diagnostic work.
1017 * @details Coordinates are scanned only when an error must be reported, so reads
1018 * without TRACK_LOCATION do not maintain line metadata on their successful path.
1019 */
1020static inline void jsonbourne_read_report(const struct jsonbourne_read_ctx *ctx,
1021 jsonbourne_read_err *err) {
1022 size_t idx;
1023 size_t line_start = 0;
1024 if (!err)
1025 return;
1026 err->code = ctx->code ? ctx->code : ctx->pool.code;
1027 err->pos = 0;
1028 err->line = 0;
1029 err->col = 0;
1030 if (!err->code)
1031 return;
1032 err->pos = ctx->pos <= ctx->len ? ctx->pos : ctx->len;
1033 err->line = 1;
1034 for (idx = 0; ctx->src && idx < err->pos; ++idx)
1035 if (ctx->src[idx] == '\n') {
1036 ++err->line;
1037 line_start = idx + 1;
1038 }
1039 err->col = err->pos - line_start;
1040}
1041
1042/** Validate and return the exact single-allocation size without allocating. */
1044 const jsonbourne_read_limits *limits, size_t *required,
1045 jsonbourne_read_err *err) {
1046 struct jsonbourne_read_ctx ctx;
1047 jsonbourne_val *root = NULL;
1048 int success;
1049 if (required)
1050 *required = 0;
1051 /* NULL pool bases intentionally validate/count without constructing temporary nodes. */
1052 success = jsonbourne_read_ctx_init(&ctx, src, len, flg, limits) &&
1053 jsonbourne_read_document(&ctx, &root);
1054 jsonbourne_read_report(&ctx, err);
1055 if (success && required)
1056 *required = ctx.pool.val_len + ctx.pool.str_len;
1057 return success;
1058}
1059
1064
1065/**
1066 * @brief Compare numeric address distances instead of forming overflowing end pointers.
1067 * @param[in] first First extent's base address.
1068 * @param[in] first_size First extent in bytes.
1069 * @param[in] second Second extent's base address.
1070 * @param[in] second_size Second extent in bytes.
1071 * @return Nonzero when both nonempty extents overlap, zero otherwise.
1072 * @note Integer addresses also avoid relational comparison of unrelated C pointers.
1073 */
1074static inline int jsonbourne_overlap(const void *first, size_t first_size, const void *second,
1075 size_t second_size) {
1076 const uintptr_t first_addr = (uintptr_t)first;
1077 const uintptr_t second_addr = (uintptr_t)second;
1078 if (!first_size || !second_size)
1079 return 0;
1080 return first_addr <= second_addr ? second_addr - first_addr < first_size
1081 : first_addr - second_addr < second_size;
1082}
1083
1084/**
1085 * @brief Replay a successful counting pass into precisely bounded record/text regions.
1086 * @param[in,out] ctx Successful measurement state; input/options remain unchanged.
1087 * @param[out] buf Accessible backing allocation, checked for alignment and overlap.
1088 * @param[in] val_len Measured record-region bytes.
1089 * @param[in] str_len Measured text-region bytes, including terminators.
1090 * @param[out] err Optional public read result.
1091 * @return Root in buf, or NULL on layout/parsing failure.
1092 * @details Resetting cursor, counters and location cache makes this a fresh grammar
1093 * pass; exact capacities prevent it from writing beyond the measured allocation.
1094 */
1096 void *buf, size_t val_len, size_t str_len,
1097 jsonbourne_read_err *err) {
1098 jsonbourne_val *root = NULL;
1099 if ((uintptr_t)buf % JSONBOURNE_ALIGNOF(struct jsonbourne_val_loc) ||
1100 jsonbourne_overlap(ctx->src, ctx->len, buf, val_len + str_len)) {
1102 jsonbourne_read_report(ctx, err);
1103 return NULL;
1104 }
1105 ctx->pos = 0;
1106 ctx->val_count = 0;
1107 ctx->loc_pos = 0;
1108 ctx->line = 1;
1109 ctx->line_pos = 0;
1110 ctx->pool.val_pool = (unsigned char *)buf;
1111 ctx->pool.str_pool = (char *)buf + val_len;
1112 ctx->pool.val_len = 0;
1113 ctx->pool.str_len = 0;
1114 ctx->pool.val_cap = val_len;
1115 ctx->pool.str_cap = str_len;
1116 if (!jsonbourne_read_document(ctx, &root))
1117 root = NULL;
1118 jsonbourne_read_report(ctx, err);
1119 return root;
1120}
1121
1122/** Parse into aligned caller storage. On insufficient capacity, required is set. */
1124 const jsonbourne_read_limits *limits, void *buf, size_t cap,
1125 size_t *required, jsonbourne_read_err *err) {
1126 struct jsonbourne_read_ctx ctx;
1127 jsonbourne_val *root = NULL;
1128 size_t total;
1129 if (required)
1130 *required = 0;
1131 if (!jsonbourne_read_ctx_init(&ctx, src, len, flg, limits) ||
1132 !jsonbourne_read_document(&ctx, &root)) {
1133 jsonbourne_read_report(&ctx, err);
1134 return NULL;
1135 }
1136 total = ctx.pool.val_len + ctx.pool.str_len;
1137 if (required)
1138 *required = total;
1139 if (!buf || cap < total) {
1141 jsonbourne_read_report(&ctx, err);
1142 return NULL;
1143 }
1144 return jsonbourne_read_materialize(&ctx, buf, ctx.pool.val_len, ctx.pool.str_len, err);
1145}
1146
1150 void *(*alc_fn)(void *, size_t), void *alc_ctx,
1151 jsonbourne_read_err *err) {
1152 struct jsonbourne_read_ctx ctx;
1153 jsonbourne_val *root = NULL;
1154 void *buf;
1155 if (!jsonbourne_read_ctx_init(&ctx, src, len, flg, limits) ||
1156 !jsonbourne_read_document(&ctx, &root)) {
1157 jsonbourne_read_report(&ctx, err);
1158 return NULL;
1159 }
1160 buf = alc_fn ? alc_fn(alc_ctx, ctx.pool.val_len + ctx.pool.str_len)
1161 : malloc(ctx.pool.val_len + ctx.pool.str_len);
1162 if (!buf) {
1164 jsonbourne_read_report(&ctx, err);
1165 return NULL;
1166 }
1167 root = jsonbourne_read_materialize(&ctx, buf, ctx.pool.val_len, ctx.pool.str_len, err);
1168 /* There is no custom release callback here; custom arenas keep their own lifetime policy. */
1169 if (!root && !alc_fn)
1170 free(buf);
1171 return root;
1172}
1173
1175 void *(*alc_fn)(void *, size_t), void *alc_ctx,
1176 jsonbourne_read_err *err) {
1177 return jsonbourne_read_opts_with_limits(src, len, flg, NULL, alc_fn, alc_ctx, err);
1178}
1179
1180jsonbourne_val *jsonbourne_read(const void *src, size_t len) {
1181 return jsonbourne_read_opts(src, len, JSONBOURNE_READ_NOFLAG, NULL, NULL, NULL);
1182}
1183
1184/** @brief Shared traversal protocol so writing and cloning use identical structural checks. */
1186 JSONBOURNE_EVENT_VAL, /**< Visit a scalar or open a container at the current depth. */
1187 JSONBOURNE_EVENT_KEY, /**< Visit an object key before its child value. */
1188 JSONBOURNE_EVENT_ELEM, /**< Visit an array slot before its child value. */
1189 JSONBOURNE_EVENT_END /**< Close a container after its declared entries are consumed. */
1190};
1191
1192/** @brief Suspended container traversal with constant-space sibling-cycle detection. */
1194 const jsonbourne_val *val; /**< Container owning this frame. */
1195 const void *next; /**< Next unvisited member/element. */
1196 const void *slow; /**< One-step Floyd cycle cursor. */
1197 const void *fast; /**< Two-step Floyd cycle cursor. */
1198 size_t remaining; /**< Declared list entries not yet visited. */
1199 size_t idx; /**< Zero-based next entry index, used for separators. */
1200};
1201
1202/**
1203 * @brief Advance either entry type without relying on their layouts being interchangeable.
1204 * @param[in] elem Accessible entry, or NULL at list end.
1205 * @param[in] type Object tag selects object entries; array traversal uses array entries.
1206 * @return Next entry, or NULL.
1207 */
1208static inline const void *jsonbourne_next(const void *elem, size_t type) {
1209 if (!elem)
1210 return NULL;
1211 return type == JSONBOURNE_TYPE_OBJ ? (const void *)((const jsonbourne_obj_entry *)elem)->next
1212 : (const void *)((const jsonbourne_arr_entry *)elem)->next;
1213}
1214
1215/**
1216 * @brief Advance Floyd's two cursors without allocating a visited-address set.
1217 * @param[in,out] slow Cursor advanced by one sibling link.
1218 * @param[in,out] fast Cursor advanced by two sibling links.
1219 * @param[in] type Entry layout: object or array.
1220 * @return 1 if no cycle is encountered on this step, 0 if non-NULL cursors meet.
1221 * @note All linked entries must still be accessible; this validates topology,
1222 * not the validity of arbitrary pointer addresses.
1223 */
1224static inline int jsonbourne_acyclic_step(const void **slow, const void **fast, size_t type) {
1225 *slow = jsonbourne_next(*slow, type);
1226 *fast = jsonbourne_next(jsonbourne_next(*fast, type), type);
1227 return !*slow || *slow != *fast;
1228}
1229
1230/**
1231 * @brief Validate/traverse an accessible DOM with a fixed explicit stack.
1232 * @param[in] val Root value to inspect.
1233 * @param[in] visit Event sink receiving context, event, value, optional key,
1234 * depth and entry index; returning zero aborts traversal.
1235 * @param[in,out] ctx Opaque event-sink state.
1236 * @return 1 for a complete accepted traversal, 0 for malformed structure, nesting
1237 * exhaustion or a rejecting visitor.
1238 * @details Exact list lengths and Floyd cursors detect malformed sibling chains.
1239 * Cycles through value/container pointers cannot grow without bound because
1240 * every nested container also consumes one checked frame.
1241 */
1242static inline int jsonbourne_walk(const jsonbourne_val *val,
1243 int (*visit)(void *, enum jsonbourne_event,
1244 const jsonbourne_val *, const jsonbourne_str *,
1245 size_t, size_t),
1246 void *ctx) {
1248 size_t depth = 0;
1249 if (!val)
1250 return 0;
1251 for (;;) {
1252 if (val) {
1254 return 0;
1255 if (!visit(ctx, JSONBOURNE_EVENT_VAL, val, NULL, depth, 0))
1256 return 0;
1259 if (depth == JSONBOURNE_WRITER_DEPTH_LIMIT)
1260 return 0;
1261 frame = &stack[depth++];
1262 frame->val = val;
1263 if (val->type == JSONBOURNE_TYPE_OBJ) {
1264 const jsonbourne_obj *obj = (const jsonbourne_obj *)val->ptr;
1265 frame->remaining = obj->len;
1266 frame->next = obj->first;
1267 } else {
1268 const jsonbourne_arr *arr = (const jsonbourne_arr *)val->ptr;
1269 frame->remaining = arr->len;
1270 frame->next = arr->first;
1271 }
1272 frame->slow = frame->next;
1273 frame->fast = frame->next;
1274 frame->idx = 0;
1275 }
1276 }
1277 val = NULL;
1278 if (!depth)
1279 return 1;
1280 {
1281 struct jsonbourne_walk_frame *frame = &stack[depth - 1];
1282 if (!frame->remaining) {
1283 if (frame->next ||
1284 !visit(ctx, JSONBOURNE_EVENT_END, frame->val, NULL, depth - 1, frame->idx))
1285 return 0;
1286 --depth;
1287 } else {
1288 const jsonbourne_str *name = NULL;
1289 if (!frame->next)
1290 return 0;
1291 if (frame->val->type == JSONBOURNE_TYPE_OBJ) {
1292 const jsonbourne_obj_entry *elem = (const jsonbourne_obj_entry *)frame->next;
1293 name = elem->key;
1294 val = elem->val;
1295 if (!name)
1296 return 0;
1297 } else
1298 val = ((const jsonbourne_arr_entry *)frame->next)->val;
1299 if (!val)
1300 return 0;
1301 frame->next = jsonbourne_next(frame->next, frame->val->type);
1302 if (!jsonbourne_acyclic_step(&frame->slow, &frame->fast, frame->val->type))
1303 return 0;
1304 if (!visit(ctx, name ? JSONBOURNE_EVENT_KEY : JSONBOURNE_EVENT_ELEM, frame->val, name,
1305 depth, frame->idx))
1306 return 0;
1307 --frame->remaining;
1308 ++frame->idx;
1309 }
1310 }
1311 }
1312}
1313
1314/** @brief One output sink used unchanged for measuring and writing JSON text. */
1316 char *buf; /**< NULL while measuring; destination otherwise. */
1317 size_t cap; /**< Hard output capacity, including any terminator. */
1318 size_t len; /**< Bytes counted/written so far. */
1319 const char *indent; /**< Borrowed whitespace indentation string. */
1320 size_t indent_len; /**< Cached indentation byte length. */
1321 const char *newline; /**< Borrowed whitespace line separator. */
1322 size_t newline_len; /**< Cached line-separator byte length. */
1323 int pretty; /**< Nonzero enables indentation/newlines. */
1324};
1325
1326/**
1327 * @brief Reserve output bytes before optionally copying them.
1328 * @param[in,out] out Counting/writing sink with len at most cap.
1329 * @param[in] bytes Accessible source extent when writing.
1330 * @param[in] len Byte count, not inferred from string termination.
1331 * @return 1 if bytes fit, 0 without an out-of-bounds write otherwise.
1332 * @note Capacity subtraction is checked before addition, including size-only passes.
1333 */
1334static inline int jsonbourne_write_bytes(struct jsonbourne_write_ctx *out, const char *bytes,
1335 size_t len) {
1336 size_t idx;
1337 if (out->len > out->cap || len > out->cap - out->len)
1338 return 0;
1339 if (out->buf)
1340 for (idx = 0; idx < len; ++idx)
1341 out->buf[out->len + idx] = bytes[idx];
1342 out->len += len;
1343 return 1;
1344}
1345
1346/**
1347 * @brief Emit a UTF-8 string with JSON quoting and exact control-byte escaping.
1348 * @param[in,out] out Measuring/writing output sink.
1349 * @param[in] str Accessible length-aware string view, possibly containing NULs.
1350 * @return 1 for valid text that fits, 0 for invalid UTF-8/arguments or capacity.
1351 * @details Printable ASCII takes the span fast path; all remaining bytes are
1352 * escaped or validated as complete scalars, never passed through blindly.
1353 */
1354static inline int jsonbourne_write_str(struct jsonbourne_write_ctx *out,
1355 const jsonbourne_str *str) {
1356 static const char digits[] = "0123456789abcdef";
1357 size_t pos = 0;
1358 if (!str || (!str->str && str->len) || str->len > (size_t)PTRDIFF_MAX ||
1359 !jsonbourne_write_bytes(out, "\"", 1))
1360 return 0;
1361 while (pos < str->len) {
1362 const unsigned char *src = (const unsigned char *)str->str;
1363 const size_t run = jsonbourne_ascii_span(src + pos, str->len - pos, '"');
1364 unsigned char chr;
1365 if (!jsonbourne_write_bytes(out, str->str + pos, run))
1366 return 0;
1367 pos += run;
1368 if (pos == str->len)
1369 break;
1370 chr = src[pos++];
1371 if (chr == '"' || chr == '\\') {
1372 const char escaped[2] = {'\\', (char)chr};
1373 if (!jsonbourne_write_bytes(out, escaped, 2))
1374 return 0;
1375 } else if (chr < 0x20) {
1376 const char *escape = chr == '\b' ? "\\b"
1377 : chr == '\f' ? "\\f"
1378 : chr == '\n' ? "\\n"
1379 : chr == '\r' ? "\\r"
1380 : chr == '\t' ? "\\t"
1381 : NULL;
1382 if (escape) {
1383 if (!jsonbourne_write_bytes(out, escape, 2))
1384 return 0;
1385 } else {
1386 const char escaped[6] = {'\\', 'u', '0', '0', digits[chr >> 4], digits[chr & 15]};
1387 if (!jsonbourne_write_bytes(out, escaped, 6))
1388 return 0;
1389 }
1390 } else {
1391 const size_t len = jsonbourne_utf8_len(src + pos - 1, str->len - pos + 1);
1392 if (!len || !jsonbourne_write_bytes(out, str->str + pos - 1, len))
1393 return 0;
1394 pos += len - 1;
1395 }
1396 }
1397 return jsonbourne_write_bytes(out, "\"", 1);
1398}
1399
1400/**
1401 * @brief Convert hexadecimal magnitude text exactly using bounded decimal digits.
1402 * @param[in,out] out Measuring/writing output sink.
1403 * @param[in] src Validated hex digits without sign or 0x prefix.
1404 * @param[in] len Hex digit count, including any leading zeroes.
1405 * @return 1 for emitted decimal text, 0 on significant-digit/capacity limits.
1406 * @details Each input digit updates a little-endian decimal accumulator by
1407 * multiply-by-16 plus carry. This avoids floating-point loss and an unbounded
1408 * big-integer dependency; two decimal slots per hex digit are a conservative bound.
1409 */
1410static inline int jsonbourne_write_hex_num(struct jsonbourne_write_ctx *out, const char *src,
1411 size_t len) {
1412 unsigned char decimal[JSONBOURNE_MAX_HEX_DIGITS * 2];
1413 size_t used = 1;
1414 size_t pos;
1415 while (len && *src == '0') {
1416 ++src;
1417 --len;
1418 }
1419 if (len > JSONBOURNE_MAX_HEX_DIGITS)
1420 return 0;
1421 decimal[0] = 0;
1422 for (pos = 0; pos < len; ++pos) {
1423 unsigned carry = (unsigned)jsonbourne_hex_to_digit((unsigned char)src[pos]);
1424 size_t idx;
1425 for (idx = 0; idx < used; ++idx) {
1426 carry += 16U * decimal[idx];
1427 decimal[idx] = (unsigned char)(carry % 10U);
1428 carry /= 10U;
1429 }
1430 while (carry) {
1431 if (used == sizeof(decimal))
1432 return 0;
1433 decimal[used++] = (unsigned char)(carry % 10U);
1434 carry /= 10U;
1435 }
1436 }
1437 while (used) {
1438 const char digit = (char)('0' + decimal[--used]);
1439 if (!jsonbourne_write_bytes(out, &digit, 1))
1440 return 0;
1441 }
1442 return 1;
1443}
1444
1445/**
1446 * @brief Preserve strict numeric text or normalize enabled relaxed spellings.
1447 * @param[in,out] out Measuring/writing output sink.
1448 * @param[in] num Accessible token view whose full extent must form one number.
1449 * @return 1 for valid normalized output that fits, 0 otherwise.
1450 * @details Strict decimals retain every original digit. Relaxed tokens lose a
1451 * leading plus, gain missing decimal zeroes or use exact hex conversion. The
1452 * retained nonfinite policy emits zero for NaN and signed DBL_MAX text for infinity.
1453 */
1454static inline int jsonbourne_write_num(struct jsonbourne_write_ctx *out,
1455 const jsonbourne_num *num) {
1456 size_t len = 0;
1457 size_t pos = 0;
1458 const unsigned char *src;
1459 if (!num || !num->str || num->len > (size_t)PTRDIFF_MAX)
1460 return 0;
1461 if (jsonbourne_read_num_token((const unsigned char *)num->str, num->len, 0, &len) &&
1462 len == num->len)
1463 return jsonbourne_write_bytes(out, num->str, num->len);
1465 (const unsigned char *)num->str, num->len,
1467 len != num->len)
1468 return 0;
1469 src = (const unsigned char *)num->str;
1470 if (src[pos] == '+' || src[pos] == '-')
1471 ++pos;
1472 if (src[pos] == 'N')
1473 return jsonbourne_write_bytes(out, "0", 1);
1474 if (src[0] == '-' && !jsonbourne_write_bytes(out, "-", 1))
1475 return 0;
1476 if (src[pos] == 'I')
1477 return jsonbourne_write_bytes(out, "1.7976931348623158e308", 22);
1478 if (len - pos >= 2 && src[pos] == '0' && (src[pos + 1] == 'x' || src[pos + 1] == 'X'))
1479 return jsonbourne_write_hex_num(out, num->str + pos + 2, len - pos - 2);
1480 if (src[pos] == '.' && !jsonbourne_write_bytes(out, "0", 1))
1481 return 0;
1482 for (; pos < len; ++pos) {
1483 if (!jsonbourne_write_bytes(out, num->str + pos, 1))
1484 return 0;
1485 if (src[pos] == '.' && (pos + 1 == len || src[pos + 1] == 'e' || src[pos + 1] == 'E') &&
1486 !jsonbourne_write_bytes(out, "0", 1))
1487 return 0;
1488 }
1489 return 1;
1490}
1491
1492/**
1493 * @brief Write a configured line break and one indentation unit per nesting level.
1494 * @param[in,out] out Output sink with already validated formatting strings.
1495 * @param[in] depth Number of indentation units.
1496 * @return 1 if no formatting is needed or it fits, 0 on capacity exhaustion.
1497 * @note The measuring pass counts the same repeated units, including custom lengths.
1498 */
1499static inline int jsonbourne_write_indent(struct jsonbourne_write_ctx *out, size_t depth) {
1500 size_t level;
1501 if (!out->pretty)
1502 return 1;
1503 if (!jsonbourne_write_bytes(out, out->newline, out->newline_len))
1504 return 0;
1505 for (level = 0; level < depth; ++level)
1506 if (!jsonbourne_write_bytes(out, out->indent, out->indent_len))
1507 return 0;
1508 return 1;
1509}
1510
1511/**
1512 * @brief Translate shared walker events into JSON punctuation and scalar text.
1513 * @param[in,out] ctx Output sink cast from the opaque visitor context.
1514 * @param[in] event Value, key, element or container-end event.
1515 * @param[in] val Accessible current value/container.
1516 * @param[in] name Object key for key events, NULL otherwise.
1517 * @param[in] depth Current nesting/formatting level.
1518 * @param[in] idx Entry index or completed count, used to avoid trailing separators.
1519 * @return 1 if output remains valid and fits, 0 to stop traversal.
1520 */
1521static inline int jsonbourne_write_visit(void *ctx, enum jsonbourne_event event,
1522 const jsonbourne_val *val, const jsonbourne_str *name,
1523 size_t depth, size_t idx) {
1524 struct jsonbourne_write_ctx *out = (struct jsonbourne_write_ctx *)ctx;
1525 if (event == JSONBOURNE_EVENT_KEY || event == JSONBOURNE_EVENT_ELEM) {
1526 if ((idx && !jsonbourne_write_bytes(out, ",", 1)) || !jsonbourne_write_indent(out, depth))
1527 return 0;
1528 return !name || (jsonbourne_write_str(out, name) &&
1529 jsonbourne_write_bytes(out, out->pretty ? ": " : ":", out->pretty ? 2 : 1));
1530 }
1531 if (event == JSONBOURNE_EVENT_END) {
1532 if (idx && !jsonbourne_write_indent(out, depth))
1533 return 0;
1534 return jsonbourne_write_bytes(out, val->type == JSONBOURNE_TYPE_OBJ ? "}" : "]", 1);
1535 }
1536 switch (val->type) {
1538 return jsonbourne_write_str(out, (const jsonbourne_str *)val->ptr);
1540 return jsonbourne_write_num(out, (const jsonbourne_num *)val->ptr);
1542 return jsonbourne_write_bytes(out, "{", 1);
1544 return jsonbourne_write_bytes(out, "[", 1);
1546 return jsonbourne_write_bytes(out, "true", 4);
1548 return jsonbourne_write_bytes(out, "false", 5);
1550 return jsonbourne_write_bytes(out, "null", 4);
1551 default:
1552 return 0;
1553 }
1554}
1555
1556/**
1557 * @brief Initialize a counting sink and validate pretty-print whitespace.
1558 * @param[out] out Fresh writer state with a pointer-safe maximum count.
1559 * @param[in] pretty Nonzero enables formatting validation/output.
1560 * @param[in] indent Whitespace string, or NULL for two spaces.
1561 * @param[in] newline Whitespace string, or NULL for LF.
1562 * @return 1 for usable options, 0 for non-JSON whitespace in pretty formatting.
1563 * @note Arbitrary formatting bytes would turn an otherwise valid DOM into invalid
1564 * JSON, so they are rejected before output storage is allocated or touched.
1565 */
1566static inline int jsonbourne_write_ctx_init(struct jsonbourne_write_ctx *out, int pretty,
1567 const char *indent, const char *newline) {
1568 size_t idx;
1569 const struct jsonbourne_write_ctx empty = JSONBOURNE_ZERO;
1570 *out = empty;
1571 out->cap = (size_t)PTRDIFF_MAX;
1572 out->pretty = pretty;
1573 out->indent = indent ? indent : " ";
1574 out->newline = newline ? newline : "\n";
1575 out->indent_len = strlen(out->indent);
1576 out->newline_len = strlen(out->newline);
1577 if (!pretty)
1578 return 1;
1579 for (idx = 0; idx < out->indent_len; ++idx)
1580 if (!jsonbourne_char_is_space((unsigned char)out->indent[idx]))
1581 return 0;
1582 for (idx = 0; idx < out->newline_len; ++idx)
1583 if (!jsonbourne_char_is_space((unsigned char)out->newline[idx]))
1584 return 0;
1585 return 1;
1586}
1587
1588/**
1589 * @brief Measure, allocate once and replay the same traversal into exact output storage.
1590 * @param[in] val Accessible DOM, stable throughout both passes and callbacks.
1591 * @param[in] pretty Nonzero selects pretty formatting.
1592 * @param[in] indent Optional indentation string.
1593 * @param[in] newline Optional line-separator string.
1594 * @param[in] alc_fn Optional allocation callback; NULL selects malloc.
1595 * @param[in] free_fn Optional failure release; NULL selects free.
1596 * @param[in] alc_ctx Opaque callback context.
1597 * @param[out] out_len Optional NUL-inclusive size, zero unless output succeeds.
1598 * @return Caller-owned JSON text, or NULL on validation, sizing or allocation failure.
1599 * @note The final size comparison detects size drift; it does not permit callers
1600 * or allocators to mutate the DOM between passes.
1601 */
1602static inline void *jsonbourne_write_document(const jsonbourne_val *val, int pretty,
1603 const char *indent, const char *newline,
1604 void *(*alc_fn)(void *, size_t),
1605 void (*free_fn)(void *, void *), void *alc_ctx,
1606 size_t *out_len) {
1607 struct jsonbourne_write_ctx out;
1608 size_t len;
1609 char *buf;
1610 if (out_len)
1611 *out_len = 0;
1614 return NULL;
1615 len = out.len;
1616 buf = (char *)(alc_fn ? alc_fn(alc_ctx, len) : malloc(len));
1617 if (!buf)
1618 return NULL;
1619 out.buf = buf;
1620 out.cap = len;
1621 out.len = 0;
1622 if (!jsonbourne_walk(val, jsonbourne_write_visit, &out) || !jsonbourne_write_bytes(&out, "", 1) ||
1623 out.len != len) {
1624 if (free_fn)
1625 free_fn(alc_ctx, buf);
1626 else
1627 free(buf);
1628 return NULL;
1629 }
1630 if (out_len)
1631 *out_len = len;
1632 return buf;
1633}
1634
1635void *jsonbourne_val_write_opts(const jsonbourne_val *val, void *(*alc_fn)(void *, size_t),
1636 void (*free_fn)(void *, void *), void *alc_ctx, size_t *out_len) {
1637 return jsonbourne_write_document(val, 0, NULL, NULL, alc_fn, free_fn, alc_ctx, out_len);
1638}
1639
1640void *jsonbourne_val_write(const jsonbourne_val *val, size_t *out_len) {
1641 return jsonbourne_val_write_opts(val, NULL, NULL, NULL, out_len);
1642}
1643
1645 const char *newline, void *(*alc_fn)(void *, size_t),
1646 void (*free_fn)(void *, void *), void *alc_ctx,
1647 size_t *out_len) {
1648 return jsonbourne_write_document(val, 1, indent, newline, alc_fn, free_fn, alc_ctx, out_len);
1649}
1650
1652 const char *newline, size_t *out_len) {
1653 return jsonbourne_val_write_pretty_opts(val, indent, newline, NULL, NULL, NULL, out_len);
1654}
1655
1656/**
1657 * @brief Protect a short caller buffer by measuring before any output write.
1658 * @param[in] val Accessible, stable DOM root.
1659 * @param[in] pretty Nonzero enables whitespace formatting.
1660 * @param[in] indent Optional indentation string.
1661 * @param[in] newline Optional line-separator string.
1662 * @param[out] buf Destination, or NULL for a size probe.
1663 * @param[in] cap Destination capacity in bytes.
1664 * @param[out] out_len Optional required NUL-inclusive size after successful preflight.
1665 * @return 1 for complete output, 0 for failed preflight or insufficient storage.
1666 */
1667static inline int jsonbourne_write_buffer(const jsonbourne_val *val, int pretty, const char *indent,
1668 const char *newline, char *buf, size_t cap,
1669 size_t *out_len) {
1670 struct jsonbourne_write_ctx out;
1671 size_t required;
1672 if (out_len)
1673 *out_len = 0;
1676 return 0;
1677 required = out.len;
1678 if (out_len)
1679 *out_len = required;
1680 if (!buf || cap < required)
1681 return 0;
1682 out.buf = buf;
1683 out.cap = cap;
1684 out.len = 0;
1685 return jsonbourne_walk(val, jsonbourne_write_visit, &out) &&
1686 jsonbourne_write_bytes(&out, "", 1) && out.len == required;
1687}
1688
1689/** Preflight before writing; insufficient buffers are left untouched. */
1690int jsonbourne_val_write_buf(const jsonbourne_val *val, char *buf, size_t cap, size_t *out_len) {
1691 return jsonbourne_write_buffer(val, 0, NULL, NULL, buf, cap, out_len);
1692}
1693
1695 const char *newline, char *buf, size_t cap, size_t *out_len) {
1696 return jsonbourne_write_buffer(val, 1, indent, newline, buf, cap, out_len);
1697}
1698
1699/** @brief Per-depth destination append state, separate from source-walker frames. */
1701 void *ctn; /**< Destination object/array payload, NULL while measuring. */
1702 void *tail; /**< Last copied entry, preserving order without rescanning. */
1703};
1704
1705/** @brief Copy visitor state; the arena layout is shared with the parser. */
1707 struct jsonbourne_pool pool; /**< Counting or materializing destination arena. */
1708 struct jsonbourne_copy_frame frames[JSONBOURNE_WRITER_DEPTH_LIMIT]; /**< Bounded append stack. */
1709 jsonbourne_val *root; /**< Copied root after materialization. */
1710 jsonbourne_val **dst; /**< Parent/root slot awaiting the next copied value. */
1711};
1712
1713/**
1714 * @brief Validate and duplicate a decoded string instead of borrowing source text.
1715 * @param[in,out] pool Destination arena or sizing state.
1716 * @param[in] src Accessible decoded UTF-8 view.
1717 * @return Copied record, or NULL during successful counting/on failure; inspect pool->code.
1718 * @note A manually assembled DOM may contain invalid UTF-8 even if parser output
1719 * cannot, so copying revalidates rather than trusting its provenance.
1720 */
1722 const jsonbourne_str *src) {
1723 const size_t start = pool->str_len;
1724 jsonbourne_str *str;
1725 size_t pos = 0;
1726 if (!src || (!src->str && src->len) || src->len > (size_t)PTRDIFF_MAX) {
1728 return NULL;
1729 }
1730 while (pos < src->len) {
1731 const size_t len = jsonbourne_utf8_len((const unsigned char *)src->str + pos, src->len - pos);
1732 if (!len) {
1734 return NULL;
1735 }
1736 pos += len;
1737 }
1738 str = (jsonbourne_str *)jsonbourne_pool_take(pool, sizeof(struct jsonbourne_str), 0);
1739 if (pool->code || !jsonbourne_pool_copy(pool, src->str, src->len) ||
1740 !jsonbourne_pool_copy(pool, "", 1))
1741 return NULL;
1742 if (str) {
1743 str->str = pool->str_pool + start;
1744 str->len = src->len;
1745 }
1746 return str;
1747}
1748
1749/**
1750 * @brief Build copied records from the same validated events used for writing.
1751 * @param[in,out] ctx Copy visitor state and destination arena.
1752 * @param[in] event Walker event selecting entry setup or value duplication.
1753 * @param[in] src Accessible source value/container.
1754 * @param[in] name Source object key for key events, NULL otherwise.
1755 * @param[in] depth Source depth, also indexing destination append frames.
1756 * @param[in] idx Source entry index, unused because destination tails track appends.
1757 * @return 1 when duplication/counting succeeds, 0 on invalid text/number or limits.
1758 * @details Entry events choose the next destination slot before the child-value
1759 * event fills it. Measurement never dereferences those materialization-only slots.
1760 */
1761static inline int jsonbourne_copy_visit(void *ctx, enum jsonbourne_event event,
1762 const jsonbourne_val *src, const jsonbourne_str *name,
1763 size_t depth, size_t idx) {
1764 struct jsonbourne_copy_ctx *copy_ctx = (struct jsonbourne_copy_ctx *)ctx;
1765 struct jsonbourne_pool *pool = &copy_ctx->pool;
1766 (void)idx;
1767 if (event == JSONBOURNE_EVENT_END)
1768 return 1;
1769 if (event == JSONBOURNE_EVENT_KEY || event == JSONBOURNE_EVENT_ELEM) {
1770 struct jsonbourne_copy_frame *frame = &copy_ctx->frames[depth - 1];
1771 if (name) {
1773 pool, sizeof(struct jsonbourne_obj_entry), 0);
1774 jsonbourne_str *str = jsonbourne_copy_str(pool, name);
1775 if (pool->code)
1776 return 0;
1777 if (elem) {
1778 elem->key = str;
1779 elem->next = NULL;
1780 if (frame->tail)
1781 ((jsonbourne_obj_entry *)frame->tail)->next = elem;
1782 else
1783 ((jsonbourne_obj *)frame->ctn)->first = elem;
1784 frame->tail = elem;
1785 copy_ctx->dst = &elem->val;
1786 }
1787 } else {
1789 pool, sizeof(struct jsonbourne_arr_entry), 0);
1790 if (pool->code)
1791 return 0;
1792 if (elem) {
1793 elem->next = NULL;
1794 if (frame->tail)
1795 ((jsonbourne_arr_entry *)frame->tail)->next = elem;
1796 else
1797 ((jsonbourne_arr *)frame->ctn)->first = elem;
1798 frame->tail = elem;
1799 copy_ctx->dst = &elem->val;
1800 }
1801 }
1802 return 1;
1803 }
1804 {
1805 jsonbourne_val *val =
1806 (jsonbourne_val *)jsonbourne_pool_take(pool, sizeof(struct jsonbourne_val), 0);
1807 void *payload = NULL;
1808 if (pool->code)
1809 return 0;
1810 if (val) {
1811 *copy_ctx->dst = val;
1812 val->type = src->type;
1813 }
1814 switch (src->type) {
1816 payload = jsonbourne_copy_str(pool, (const jsonbourne_str *)src->ptr);
1817 break;
1818 case JSONBOURNE_TYPE_NUM: {
1819 const jsonbourne_num *num = (const jsonbourne_num *)src->ptr;
1820 const size_t start = pool->str_len;
1821 size_t len = 0;
1822 jsonbourne_num *copy;
1823 if (!num->str || num->len > (size_t)PTRDIFF_MAX ||
1825 (const unsigned char *)num->str, num->len,
1827 len != num->len)
1828 return 0;
1829 copy = (jsonbourne_num *)jsonbourne_pool_take(pool, sizeof(struct jsonbourne_num), 0);
1830 if (pool->code || !jsonbourne_pool_copy(pool, num->str, num->len) ||
1831 !jsonbourne_pool_copy(pool, "", 1))
1832 return 0;
1833 if (copy) {
1834 copy->str = pool->str_pool + start;
1835 copy->len = num->len;
1836 }
1837 payload = copy;
1838 break;
1839 }
1841 payload = jsonbourne_pool_take(pool, sizeof(struct jsonbourne_obj), 0);
1842 if (payload) {
1843 ((jsonbourne_obj *)payload)->first = NULL;
1844 ((jsonbourne_obj *)payload)->len = ((const jsonbourne_obj *)src->ptr)->len;
1845 }
1846 break;
1848 payload = jsonbourne_pool_take(pool, sizeof(struct jsonbourne_arr), 0);
1849 if (payload) {
1850 ((jsonbourne_arr *)payload)->first = NULL;
1851 ((jsonbourne_arr *)payload)->len = ((const jsonbourne_arr *)src->ptr)->len;
1852 }
1853 break;
1854 default:
1855 break;
1856 }
1857 if (pool->code)
1858 return 0;
1859 if (val)
1860 val->ptr = payload;
1861 if ((src->type == JSONBOURNE_TYPE_OBJ || src->type == JSONBOURNE_TYPE_ARR) &&
1863 copy_ctx->frames[depth].ctn = payload;
1864 copy_ctx->frames[depth].tail = NULL;
1865 }
1866 return 1;
1867 }
1868}
1869
1870jsonbourne_val *jsonbourne_val_copy_opts(const jsonbourne_val *val, void *(*alc_fn)(void *, size_t),
1871 void *alc_ctx) {
1872 struct jsonbourne_copy_ctx copy_ctx = JSONBOURNE_ZERO;
1873 size_t val_len;
1874 size_t str_len;
1875 void *buf;
1876 copy_ctx.pool.val_cap = SIZE_MAX;
1877 copy_ctx.pool.str_cap = SIZE_MAX;
1878 copy_ctx.pool.max_memory = (size_t)PTRDIFF_MAX;
1879 if (!jsonbourne_walk(val, jsonbourne_copy_visit, &copy_ctx))
1880 return NULL;
1881 val_len = copy_ctx.pool.val_len;
1882 str_len = copy_ctx.pool.str_len;
1883 buf = alc_fn ? alc_fn(alc_ctx, val_len + str_len) : malloc(val_len + str_len);
1884 if (!buf)
1885 return NULL;
1886 if ((uintptr_t)buf % JSONBOURNE_ALIGNOF(struct jsonbourne_val)) {
1887 if (!alc_fn)
1888 free(buf);
1889 return NULL;
1890 }
1891 copy_ctx.pool.val_pool = (unsigned char *)buf;
1892 copy_ctx.pool.str_pool = (char *)buf + val_len;
1893 /* Replay into independent text/record regions; source locations are intentionally omitted. */
1894 copy_ctx.pool.val_len = 0;
1895 copy_ctx.pool.str_len = 0;
1896 copy_ctx.pool.val_cap = val_len;
1897 copy_ctx.pool.str_cap = str_len;
1898 copy_ctx.dst = &copy_ctx.root;
1899 if (!jsonbourne_walk(val, jsonbourne_copy_visit, &copy_ctx)) {
1900 if (!alc_fn)
1901 free(buf);
1902 return NULL;
1903 }
1904 return copy_ctx.root;
1905}
1906
1908 return jsonbourne_val_copy_opts(val, NULL, NULL);
1909}
1910
1911/* These borrowed views inspect tags only; ownership and structural validation stay with callers. */
1913 return val && val->type == JSONBOURNE_TYPE_STR ? (jsonbourne_str *)val->ptr : NULL;
1914}
1915
1917 return val && val->type == JSONBOURNE_TYPE_NUM ? (jsonbourne_num *)val->ptr : NULL;
1918}
1919
1921 return val && val->type == JSONBOURNE_TYPE_OBJ ? (jsonbourne_obj *)val->ptr : NULL;
1922}
1923
1925 return val && val->type == JSONBOURNE_TYPE_ARR ? (jsonbourne_arr *)val->ptr : NULL;
1926}
1927
1929 return val && val->type == JSONBOURNE_TYPE_TRUE;
1930}
1931
1933 return val && val->type == JSONBOURNE_TYPE_FALSE;
1934}
1935
1937 return val && val->type == JSONBOURNE_TYPE_NULL;
1938}
1939
1940/**
1941 * @brief Share exact-byte member comparison while keeping ambiguity policy explicit.
1942 * @param[in] val Accessible object value.
1943 * @param[in] key Decoded key bytes; NULL only with len zero.
1944 * @param[in] len Key byte count, including any embedded NULs.
1945 * @param[in] unique Nonzero scans for exactly one match; zero returns the first.
1946 * @return Borrowed matching value, or NULL for absent/ambiguous/invalid traversal.
1947 * @note Unique lookup must inspect the whole declared list: a later escaped
1948 * spelling can decode to the same key as an earlier member.
1949 */
1951 const char *key, size_t len, int unique) {
1952 const jsonbourne_obj *obj;
1953 const jsonbourne_obj_entry *elem;
1954 const jsonbourne_val *found = NULL;
1955 const void *slow;
1956 const void *fast;
1957 size_t idx;
1958 if (!val || val->type != JSONBOURNE_TYPE_OBJ || !val->ptr || (!key && len) ||
1959 len > (size_t)PTRDIFF_MAX)
1960 return NULL;
1961 obj = (const jsonbourne_obj *)val->ptr;
1962 elem = obj->first;
1963 slow = elem;
1964 fast = elem;
1965 for (idx = 0; idx < obj->len; ++idx) {
1966 if (!elem || !elem->key || (!elem->key->str && elem->key->len))
1967 return NULL;
1968 if (elem->key->len == len && (!len || memcmp(elem->key->str, key, len) == 0)) {
1969 if (found)
1970 return NULL;
1971 found = elem->val;
1972 if (!unique)
1973 return found;
1974 }
1975 elem = elem->next;
1976 if (!jsonbourne_acyclic_step(&slow, &fast, JSONBOURNE_TYPE_OBJ))
1977 return NULL;
1978 }
1979 return elem ? NULL : found;
1980}
1981
1982const jsonbourne_val *jsonbourne_obj_getn(const jsonbourne_val *val, const char *key, size_t len) {
1983 return jsonbourne_obj_lookup(val, key, len, 0);
1984}
1985
1987 size_t len) {
1988 return jsonbourne_obj_lookup(val, key, len, 1);
1989}
1990
1991const jsonbourne_val *jsonbourne_arr_get(const jsonbourne_val *val, size_t idx) {
1992 const jsonbourne_arr *arr;
1993 const jsonbourne_arr_entry *elem;
1994 const void *slow;
1995 const void *fast;
1996 if (!val || val->type != JSONBOURNE_TYPE_ARR || !val->ptr)
1997 return NULL;
1998 arr = (const jsonbourne_arr *)val->ptr;
1999 if (idx >= arr->len)
2000 return NULL;
2001 elem = arr->first;
2002 slow = elem;
2003 fast = elem;
2004 while (idx-- && elem) {
2005 elem = elem->next;
2006 if (!jsonbourne_acyclic_step(&slow, &fast, JSONBOURNE_TYPE_ARR))
2007 return NULL;
2008 }
2009 return elem ? elem->val : NULL;
2010}
2011
2012/** Convert an integer token exactly; exponent/fraction/coercion are rejected. */
2013int jsonbourne_num_to_uint(const jsonbourne_num *num, uint64_t *out) {
2014 uint64_t val = 0;
2015 size_t idx;
2016 if (!num || !num->str || !num->len || !out || num->len > (size_t)PTRDIFF_MAX ||
2017 (num->len > 1 && num->str[0] == '0'))
2018 return 0;
2019 for (idx = 0; idx < num->len; ++idx) {
2020 const unsigned char chr = (unsigned char)num->str[idx];
2021 const unsigned digit = (unsigned)(chr - '0');
2022 /* Check the rearranged bound before multiplication, when overflow is still avoidable. */
2023 if (!jsonbourne_char_is_digit(chr) || val > (UINT64_MAX - digit) / 10U)
2024 return 0;
2025 val = val * 10U + digit;
2026 }
2027 *out = val;
2028 return 1;
2029}
2030
2031int jsonbourne_num_to_sint(const jsonbourne_num *num, int64_t *out) {
2032 struct jsonbourne_num magnitude;
2033 uint64_t val;
2034 int negative;
2035 if (!num || !num->str || !num->len || !out)
2036 return 0;
2037 negative = num->str[0] == '-';
2038 magnitude.str = num->str + negative;
2039 magnitude.len = num->len - (size_t)negative;
2040 if (!jsonbourne_num_to_uint(&magnitude, &val) || val > (uint64_t)INT64_MAX + (unsigned)negative)
2041 return 0;
2042 /* For INT64_MIN, val itself cannot be cast safely; val - 1 fits before negation. */
2043 *out = negative ? -(int64_t)(val - (val != 0)) - (val != 0) : (int64_t)val;
2044 return 1;
2045}
2046
2047/**
2048 * @brief Compare a decoded member name with an RFC 6901 token as escapes are read.
2049 * @param[in] name Accessible decoded key view.
2050 * @param[in] token Encoded pointer token without its leading slash.
2051 * @param[in] len Token extent in bytes.
2052 * @return 1 only for equal decoded bytes and lengths, 0 otherwise.
2053 * @details Streaming ~0/~1 decoding avoids a temporary key allocation and keeps
2054 * embedded NUL handling tied to lengths rather than string terminators.
2055 */
2056static inline int jsonbourne_ptr_key_eq(const jsonbourne_str *name, const char *token, size_t len) {
2057 size_t input = 0;
2058 size_t out = 0;
2059 if (!name || (!name->str && name->len))
2060 return 0;
2061 while (input < len) {
2062 char chr = token[input++];
2063 if (chr == '~') {
2064 if (input == len || (token[input] != '0' && token[input] != '1'))
2065 return 0;
2066 chr = token[input++] == '0' ? '~' : '/';
2067 }
2068 if (out == name->len || name->str[out++] != chr)
2069 return 0;
2070 }
2071 return out == name->len;
2072}
2073
2074/** RFC 6901 lookup. Object tokens must identify exactly one decoded member. */
2075const jsonbourne_val *jsonbourne_ptr_getn(const jsonbourne_val *val, const char *pointer,
2076 size_t len) {
2077 size_t pos = 0;
2078 if ((!pointer && len) || !val || len > (size_t)PTRDIFF_MAX)
2079 return NULL;
2080 while (pos < len) {
2081 size_t start;
2082 size_t token_len;
2083 if (pointer[pos++] != '/')
2084 return NULL;
2085 start = pos;
2086 while (pos < len && pointer[pos] != '/') {
2087 if (pointer[pos] == '~') {
2088 ++pos;
2089 if (pos == len || (pointer[pos] != '0' && pointer[pos] != '1'))
2090 return NULL;
2091 }
2092 ++pos;
2093 }
2094 token_len = pos - start;
2095 if (val->type == JSONBOURNE_TYPE_OBJ && val->ptr) {
2096 const jsonbourne_obj *obj = (const jsonbourne_obj *)val->ptr;
2097 const jsonbourne_obj_entry *elem = obj->first;
2098 const jsonbourne_val *found = NULL;
2099 const void *slow = elem;
2100 const void *fast = elem;
2101 size_t idx;
2102 for (idx = 0; idx < obj->len; ++idx) {
2103 if (!elem)
2104 return NULL;
2105 if (jsonbourne_ptr_key_eq(elem->key, pointer + start, token_len)) {
2106 if (found)
2107 return NULL;
2108 found = elem->val;
2109 }
2110 elem = elem->next;
2111 if (!jsonbourne_acyclic_step(&slow, &fast, JSONBOURNE_TYPE_OBJ))
2112 return NULL;
2113 }
2114 if (elem || !found)
2115 return NULL;
2116 val = found;
2117 } else if (val->type == JSONBOURNE_TYPE_ARR) {
2118 size_t idx = 0;
2119 size_t position;
2120 if (!token_len || (token_len > 1 && pointer[start] == '0'))
2121 return NULL;
2122 for (position = start; position < pos; ++position) {
2123 const unsigned char chr = (unsigned char)pointer[position];
2124 const unsigned digit = (unsigned)(chr - '0');
2125 if (!jsonbourne_char_is_digit(chr) || idx > (SIZE_MAX - digit) / 10U)
2126 return NULL;
2127 idx = idx * 10U + digit;
2128 }
2129 val = jsonbourne_arr_get(val, idx);
2130 if (!val)
2131 return NULL;
2132 } else
2133 return NULL;
2134 }
2135 return val;
2136}
2137
2139 /* Keep text out of parser control flow; unknown codes still receive a static fallback. */
2140 switch (code) {
2173 default:
2175 }
2176}
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
static bool start(uint32_t session)
Admit a nonzero session and discard correlation from the previous one.
static pid_t child
int jsonbourne_num_to_sint(const jsonbourne_num *num, int64_t *out)
Convert a signed decimal integer token exactly, including INT64_MIN.
int jsonbourne_is_null(const jsonbourne_val *val)
Distinguish JSON null from a missing C pointer.
const jsonbourne_val * jsonbourne_ptr_getn(const jsonbourne_val *val, const char *pointer, size_t len)
Resolve an RFC 6901 pointer without allocating decoded path tokens.
const jsonbourne_val * jsonbourne_arr_get(const jsonbourne_val *val, size_t idx)
Locate a zero-based array element by bounded linked traversal.
int jsonbourne_is_false(const jsonbourne_val *val)
Test the false tag without truthiness conversion.
const char * jsonbourne_read_err_desc(jsonbourne_read_code code)
Borrow human-readable diagnostic text without allocating.
const jsonbourne_val * jsonbourne_obj_getn(const jsonbourne_val *val, const char *key, size_t len)
Find the first exact decoded member name, including embedded NUL bytes.
int jsonbourne_num_to_uint(const jsonbourne_num *num, uint64_t *out)
Convert an unsigned decimal integer token exactly, without coercion.
jsonbourne_arr * jsonbourne_get_arr(jsonbourne_val *val)
Borrow the ordered array payload.
jsonbourne_obj * jsonbourne_get_obj(jsonbourne_val *val)
Borrow the ordered object payload.
jsonbourne_str * jsonbourne_get_str(jsonbourne_val *val)
Borrow a string payload without allocating or copying.
const jsonbourne_val * jsonbourne_obj_getn_unique(const jsonbourne_val *val, const char *key, size_t len)
Require exactly one decoded matching key instead of silently choosing.
int jsonbourne_is_true(const jsonbourne_val *val)
Test the true tag without coercing numbers or strings.
jsonbourne_num * jsonbourne_get_num(jsonbourne_val *val)
Borrow the original number-token view.
#define JSONBOURNE_VERSION_HEX
Packed major/minor/patch version for compile-time comparisons.
Definition jsonbourne.h:90
uint32_t jsonbourne_version(void)
Query the linked implementation rather than the including header.
Definition jsonbourne.c:104
#define JSONBOURNE_WRITER_DEPTH_LIMIT
Positive writer/copy nesting bound, defaulting to the reader bound.
Definition jsonbourne.h:111
#define JSONBOURNE_READER_DEPTH_LIMIT
Maximum simultaneous open reader containers; must be positive.
Definition jsonbourne.h:103
#define JSONBOURNE_MAX_HEX_DIGITS
Maximum significant hexadecimal digits converted to decimal output.
Definition jsonbourne.h:122
#define JSONBOURNE_READ_ALLOW_EXT_NUMBER
Numeric spelling extensions; does not by itself permit Infinity or NaN.
Definition jsonbourne.h:312
size_t jsonbourne_read_code
Stable storage type for a diagnostic code, separate from display text.
Definition jsonbourne.h:267
size_t jsonbourne_read_flag
Read-option bitmask; combine named options with bitwise OR.
Definition jsonbourne.h:147
@ JSONBOURNE_TYPE_TRUE
Definition jsonbourne.h:183
@ JSONBOURNE_TYPE_FALSE
Definition jsonbourne.h:184
@ JSONBOURNE_TYPE_NULL
Definition jsonbourne.h:185
@ JSONBOURNE_TYPE_NUM
Definition jsonbourne.h:180
@ JSONBOURNE_TYPE_OBJ
Definition jsonbourne.h:181
@ JSONBOURNE_TYPE_ARR
Definition jsonbourne.h:182
@ JSONBOURNE_TYPE_STR
Definition jsonbourne.h:179
@ JSONBOURNE_READ_ERROR_INVALID_NUMBER
Definition jsonbourne.h:275
@ JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR
Definition jsonbourne.h:271
@ JSONBOURNE_READ_ERROR_INVALID_UTF8
Definition jsonbourne.h:284
@ JSONBOURNE_READ_ERROR_EXPECTED_KEY
Definition jsonbourne.h:273
@ JSONBOURNE_READ_ERROR_LITERAL
Definition jsonbourne.h:276
@ JSONBOURNE_READ_ERROR_EXPECTED_COLON
Definition jsonbourne.h:272
@ JSONBOURNE_READ_ERROR_LIMIT
Definition jsonbourne.h:285
@ JSONBOURNE_READ_ERROR_DEPTH
Definition jsonbourne.h:281
@ JSONBOURNE_READ_ERROR_INVALID_PARAMETER
Definition jsonbourne.h:286
@ JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION
Definition jsonbourne.h:279
@ JSONBOURNE_READ_ERROR_UNEXPECTED_END
Definition jsonbourne.h:277
@ JSONBOURNE_READ_ERROR_INVALID_STRING
Definition jsonbourne.h:278
@ JSONBOURNE_READ_SUCCESS
Definition jsonbourne.h:270
@ JSONBOURNE_READ_ERROR_INVALID_COMMENT
Definition jsonbourne.h:282
@ JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT
Definition jsonbourne.h:280
@ JSONBOURNE_READ_ERROR_INVALID_ESCAPE
Definition jsonbourne.h:274
@ JSONBOURNE_READ_ALLOW_HEX_NUM
Definition jsonbourne.h:164
@ JSONBOURNE_READ_ALLOW_EQUALS
Definition jsonbourne.h:158
@ JSONBOURNE_READ_ALLOW_NO_COMMAS
Definition jsonbourne.h:159
@ JSONBOURNE_READ_TRACK_LOCATION
Definition jsonbourne.h:162
@ JSONBOURNE_READ_ALLOW_DECIMAL_POINT
Definition jsonbourne.h:166
@ JSONBOURNE_READ_ALLOW_TRAILING_COMMAS
Definition jsonbourne.h:155
@ JSONBOURNE_READ_ALLOW_UNQUOTED_KEY
Definition jsonbourne.h:156
@ JSONBOURNE_READ_ALLOW_COMMENTS
Definition jsonbourne.h:160
@ JSONBOURNE_READ_ALLOW_INF_AND_NAN
Definition jsonbourne.h:167
@ JSONBOURNE_READ_ALLOW_PLUS_SIGN
Definition jsonbourne.h:165
@ JSONBOURNE_READ_ALLOW_MULTILINE_STR
Definition jsonbourne.h:168
@ JSONBOURNE_READ_NOFLAG
Definition jsonbourne.h:154
@ JSONBOURNE_READ_ALLOW_GLOBAL_OBJECT
Definition jsonbourne.h:157
@ JSONBOURNE_READ_ALLOW_SINGLE_QUOTED_STR
Definition jsonbourne.h:163
jsonbourne_val * jsonbourne_read(const void *src, size_t len)
Read strict JSON with default limits and malloc-backed ownership.
jsonbourne_val * jsonbourne_read_opts_with_limits(const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits, void *(*alc_fn)(void *, size_t), void *alc_ctx, jsonbourne_read_err *err)
Validate against explicit budgets, then allocate the entire DOM once.
int jsonbourne_read_measure(const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits, size_t *required, jsonbourne_read_err *err)
Validate input and measure the exact single-allocation DOM size.
jsonbourne_val * jsonbourne_read_opts(const void *src, size_t len, jsonbourne_read_flag flg, void *(*alc_fn)(void *, size_t), void *alc_ctx, jsonbourne_read_err *err)
Read with named options and the linked implementation's default limits.
struct jsonbourne_read_limits jsonbourne_read_limits_default(void)
Create default budgets using the linked implementation's reader limit.
Definition jsonbourne.c:106
jsonbourne_val * jsonbourne_read_buf(const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits, void *buf, size_t cap, size_t *required, jsonbourne_read_err *err)
Read a DOM into aligned caller storage without heap allocation.
int jsonbourne_read_validate(const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits, jsonbourne_read_err *err)
Validate the entire extent without allocating a DOM or changing input.
void * jsonbourne_val_write_pretty_opts(const jsonbourne_val *val, const char *indent, const char *newline, void *(*alc_fn)(void *, size_t), void(*free_fn)(void *, void *), void *alc_ctx, size_t *out_len)
Validate and allocate pretty output with explicit formatting/ownership.
void * jsonbourne_val_write(const jsonbourne_val *val, size_t *out_len)
Allocate minified JSON using malloc.
int jsonbourne_val_write_buf(const jsonbourne_val *val, char *buf, size_t cap, size_t *out_len)
Preflight minified output, then write only if the caller buffer fits.
void * jsonbourne_val_write_pretty(const jsonbourne_val *val, const char *indent, const char *newline, size_t *out_len)
Allocate pretty JSON using malloc.
jsonbourne_val * jsonbourne_val_copy(const jsonbourne_val *val)
Make an independently owned deep copy using malloc.
jsonbourne_val * jsonbourne_val_copy_opts(const jsonbourne_val *val, void *(*alc_fn)(void *, size_t), void *alc_ctx)
Deep-copy a validated value into one independent allocation.
int jsonbourne_val_write_pretty_buf(const jsonbourne_val *val, const char *indent, const char *newline, char *buf, size_t cap, size_t *out_len)
Preflight pretty output without allocating storage.
void * jsonbourne_val_write_opts(const jsonbourne_val *val, void *(*alc_fn)(void *, size_t), void(*free_fn)(void *, void *), void *alc_ctx, size_t *out_len)
Validate a DOM and allocate minified JSON output.
static size_t jsonbourne_utf8_len(const unsigned char *src, size_t len)
Validate exactly one UTF-8 scalar without reading beyond the extent.
Definition jsonbourne.c:311
static int jsonbourne_write_num(struct jsonbourne_write_ctx *out, const jsonbourne_num *num)
Preserve strict numeric text or normalize enabled relaxed spellings.
static int jsonbourne_write_ctx_init(struct jsonbourne_write_ctx *out, int pretty, const char *indent, const char *newline)
Initialize a counting sink and validate pretty-print whitespace.
static int jsonbourne_write_indent(struct jsonbourne_write_ctx *out, size_t depth)
Write a configured line break and one indentation unit per nesting level.
#define JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR_MSG
Missing container separator/closure diagnostic.
Definition jsonbourne.c:52
static int jsonbourne_write_visit(void *ctx, enum jsonbourne_event event, const jsonbourne_val *val, const jsonbourne_str *name, size_t depth, size_t idx)
Translate shared walker events into JSON punctuation and scalar text.
#define JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT_MSG
Non-trivia input remaining after the root diagnostic.
Definition jsonbourne.c:70
#define JSONBOURNE_READ_ERROR_UNKNOWN_MSG
Generic diagnostic, also used for unrecognized codes.
Definition jsonbourne.c:76
#define JSONBOURNE_ALIGNOF(type)
Required C11 alignment for an arena's typed record region.
Definition jsonbourne.c:92
static int jsonbourne_char_is_digit(unsigned char chr)
Recognize the decimal digits permitted by JSON number grammar.
Definition jsonbourne.c:289
#define JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION_MSG
Allocation failure or insufficient caller-storage diagnostic.
Definition jsonbourne.c:68
static int jsonbourne_ptr_key_eq(const jsonbourne_str *name, const char *token, size_t len)
Compare a decoded member name with an RFC 6901 token as escapes are read.
static size_t jsonbourne_space_span(const unsigned char *src, size_t len)
Skip a bounded run of JSON whitespace with the available SIMD baseline.
Definition jsonbourne.c:239
static void jsonbourne_read_report(const struct jsonbourne_read_ctx *ctx, jsonbourne_read_err *err)
Normalize parser/arena failure into an optional public diagnostic.
static int jsonbourne_char_is_id(unsigned char chr)
Classify this reader's relaxed, ASCII-only unquoted-key alphabet.
Definition jsonbourne.c:298
static int jsonbourne_write_bytes(struct jsonbourne_write_ctx *out, const char *bytes, size_t len)
Reserve output bytes before optionally copying them.
static int jsonbourne_write_str(struct jsonbourne_write_ctx *out, const jsonbourne_str *str)
Emit a UTF-8 string with JSON quoting and exact control-byte escaping.
static int jsonbourne_read_str(struct jsonbourne_read_ctx *ctx, int key, jsonbourne_str **out)
Decode one quoted string or enabled unquoted key through the same two passes.
Definition jsonbourne.c:595
static int jsonbourne_read_val(struct jsonbourne_read_ctx *ctx, jsonbourne_val **out, struct jsonbourne_read_frame *stack, size_t *depth, int is_global)
Consume a scalar or push a new container without a recursive call.
Definition jsonbourne.c:765
#define JSONBOURNE_READ_ERROR_UNEXPECTED_END_MSG
Premature end-of-input diagnostic.
Definition jsonbourne.c:64
static const void * jsonbourne_next(const void *elem, size_t type)
Advance either entry type without relying on their layouts being interchangeable.
static int jsonbourne_pool_copy(struct jsonbourne_pool *pool, const char *src, size_t len)
Account for or copy a byte extent into the text region.
Definition jsonbourne.c:169
#define JSONBOURNE_READ_ERROR_LITERAL_MSG
Invalid true/false/null token diagnostic.
Definition jsonbourne.c:62
static int jsonbourne_write_hex_num(struct jsonbourne_write_ctx *out, const char *src, size_t len)
Convert hexadecimal magnitude text exactly using bounded decimal digits.
#define JSONBOURNE_READ_ERROR_EXPECTED_COLON_MSG
Missing key/value separator diagnostic.
Definition jsonbourne.c:54
#define JSONBOURNE_READ_SUCCESS_MSG
Message for successful validation.
Definition jsonbourne.c:50
static void jsonbourne_read_locate(struct jsonbourne_read_ctx *ctx, size_t pos, size_t *line, size_t *row)
Advance a lazy location cursor instead of rescanning each node's prefix.
Definition jsonbourne.c:468
jsonbourne_event
Shared traversal protocol so writing and cloning use identical structural checks.
@ JSONBOURNE_EVENT_VAL
@ JSONBOURNE_EVENT_ELEM
@ JSONBOURNE_EVENT_END
@ JSONBOURNE_EVENT_KEY
static int jsonbourne_skip_trivia(struct jsonbourne_read_ctx *ctx)
Consume whitespace and enabled comments without swallowing grammar bytes.
Definition jsonbourne.c:487
static int jsonbourne_read_num_token(const unsigned char *src, size_t len, jsonbourne_read_flag flg, size_t *read_len)
Recognize a numeric prefix without converting or rounding its value.
Definition jsonbourne.c:349
static const jsonbourne_val * jsonbourne_obj_lookup(const jsonbourne_val *val, const char *key, size_t len, int unique)
Share exact-byte member comparison while keeping ambiguity policy explicit.
#define JSONBOURNE_READ_ERROR_INVALID_COMMENT_MSG
Unterminated block-comment diagnostic.
Definition jsonbourne.c:74
static int jsonbourne_overlap(const void *first, size_t first_size, const void *second, size_t second_size)
Compare numeric address distances instead of forming overflowing end pointers.
#define JSONBOURNE_READ_ERROR_LIMIT_MSG
Resource-budget or arithmetic-limit diagnostic.
Definition jsonbourne.c:80
static int jsonbourne_char_is_space(unsigned char chr)
Recognize only the four JSON whitespace bytes, independently of locale.
Definition jsonbourne.c:228
static int jsonbourne_write_buffer(const jsonbourne_val *val, int pretty, const char *indent, const char *newline, char *buf, size_t cap, size_t *out_len)
Protect a short caller buffer by measuring before any output write.
static int jsonbourne_read_document(struct jsonbourne_read_ctx *ctx, jsonbourne_val **root)
Drive one complete JSON document using explicit container frames.
Definition jsonbourne.c:876
static int jsonbourne_walk(const jsonbourne_val *val, int(*visit)(void *, enum jsonbourne_event, const jsonbourne_val *, const jsonbourne_str *, size_t, size_t), void *ctx)
Validate/traverse an accessible DOM with a fixed explicit stack.
#define JSONBOURNE_READ_ERROR_INVALID_UTF8_MSG
Invalid Unicode scalar encoding diagnostic.
Definition jsonbourne.c:78
static void * jsonbourne_write_document(const jsonbourne_val *val, int pretty, const char *indent, const char *newline, void *(*alc_fn)(void *, size_t), void(*free_fn)(void *, void *), void *alc_ctx, size_t *out_len)
Measure, allocate once and replay the same traversal into exact output storage.
static int jsonbourne_read_hex4(struct jsonbourne_read_ctx *ctx, uint32_t *unit)
Consume the four hexadecimal digits following a Unicode escape marker.
Definition jsonbourne.c:537
static int jsonbourne_read_ctx_init(struct jsonbourne_read_ctx *ctx, const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits)
Establish cursor/limit invariants before any grammar byte is accessed.
Definition jsonbourne.c:989
static int jsonbourne_acyclic_step(const void **slow, const void **fast, size_t type)
Advance Floyd's two cursors without allocating a visited-address set.
static int jsonbourne_read_str_bytes(struct jsonbourne_read_ctx *ctx, size_t start, const char *bytes, size_t count)
Enforce a decoded-string budget before reserving any more text bytes.
Definition jsonbourne.c:522
static jsonbourne_val * jsonbourne_read_materialize(struct jsonbourne_read_ctx *ctx, void *buf, size_t val_len, size_t str_len, jsonbourne_read_err *err)
Replay a successful counting pass into precisely bounded record/text regions.
#define JSONBOURNE_READ_ERROR_INVALID_STRING_MSG
Disallowed string control-byte diagnostic.
Definition jsonbourne.c:66
#define JSONBOURNE_READ_FLAG_MASK
Derive the accepted bits from named options so flag remaps cannot stale this mask.
Definition jsonbourne.c:86
static int jsonbourne_set_read_error(struct jsonbourne_read_ctx *ctx, jsonbourne_read_code code)
Preserve the first grammar failure while supporting short-circuit returns.
Definition jsonbourne.c:453
static int jsonbourne_is_delimiter(const struct jsonbourne_read_ctx *ctx, size_t pos)
Verify the token boundary separately from the token's own spelling.
Definition jsonbourne.c:745
static int jsonbourne_hex_to_digit(unsigned char chr)
Decode an ASCII hexadecimal digit without locale-sensitive conversion.
Definition jsonbourne.c:274
#define JSONBOURNE_READ_ERROR_INVALID_NUMBER_MSG
Invalid numeric-token diagnostic.
Definition jsonbourne.c:60
#define JSONBOURNE_ZERO
C11 aggregate zero-initializer without byte-copying object representations.
Definition jsonbourne.c:90
static size_t jsonbourne_ascii_span(const unsigned char *src, size_t len, unsigned char quote)
Find bytes that need no string escaping or Unicode decoding.
Definition jsonbourne.c:189
#define JSONBOURNE_READ_ERROR_INVALID_ESCAPE_MSG
Invalid escape/surrogate diagnostic.
Definition jsonbourne.c:58
static jsonbourne_str * jsonbourne_copy_str(struct jsonbourne_pool *pool, const jsonbourne_str *src)
Validate and duplicate a decoded string instead of borrowing source text.
#define JSONBOURNE_READ_ERROR_DEPTH_MSG
Nesting-limit diagnostic.
Definition jsonbourne.c:72
#define JSONBOURNE_READ_ERROR_EXPECTED_KEY_MSG
Invalid member-name diagnostic.
Definition jsonbourne.c:56
#define JSONBOURNE_READ_ERROR_INVALID_PARAMETER_MSG
Invalid API arguments or buffer-layout diagnostic.
Definition jsonbourne.c:82
static int jsonbourne_read_utf8_encode(struct jsonbourne_read_ctx *ctx, size_t start, uint32_t codepoint)
Encode a validated Unicode scalar into the decoded text arena.
Definition jsonbourne.c:560
static int jsonbourne_copy_visit(void *ctx, enum jsonbourne_event event, const jsonbourne_val *src, const jsonbourne_str *name, size_t depth, size_t idx)
Build copied records from the same validated events used for writing.
static void * jsonbourne_pool_take(struct jsonbourne_pool *pool, size_t len, int is_str)
Reserve checked space in one arena region or merely account for it.
Definition jsonbourne.c:143
JSON reader, writer and DOM utilities for Linux C11 with a C++11-compatible API.
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
uint8_t frame[LWIR_MAX_FRAME_BYTES]
Definition lwir_mock.c:58
static size_t count
Definition pose_log.c:79
One array element in source order.
Definition jsonbourne.h:234
jsonbourne_val * val
Definition jsonbourne.h:235
jsonbourne_arr_entry * next
Definition jsonbourne.h:236
Ordered array elements; explicit length supports bounded traversal.
Definition jsonbourne.h:240
jsonbourne_arr_entry * first
Definition jsonbourne.h:241
Copy visitor state; the arena layout is shared with the parser.
jsonbourne_val ** dst
struct jsonbourne_pool pool
jsonbourne_val * root
struct jsonbourne_copy_frame frames[JSONBOURNE_WRITER_DEPTH_LIMIT]
Per-depth destination append state, separate from source-walker frames.
Original number spelling, retained so reading never rounds through a double.
Definition jsonbourne.h:208
const char * str
Definition jsonbourne.h:209
One object member; linked order and duplicate decoded keys are retained.
Definition jsonbourne.h:219
jsonbourne_obj_entry * next
Definition jsonbourne.h:222
jsonbourne_str * key
Definition jsonbourne.h:220
jsonbourne_val * val
Definition jsonbourne.h:221
Ordered object members; len must exactly match the linked-list length.
Definition jsonbourne.h:226
jsonbourne_obj_entry * first
Definition jsonbourne.h:227
Two-region arena shared by measurement and materialization.
Definition jsonbourne.c:122
unsigned char * val_pool
Definition jsonbourne.c:123
jsonbourne_read_code code
Definition jsonbourne.c:130
Per-call parser state; no mutable global state or input modification is needed.
Definition jsonbourne.c:418
struct jsonbourne_read_limits limits
Definition jsonbourne.c:428
const unsigned char * src
Definition jsonbourne.c:419
struct jsonbourne_pool pool
Definition jsonbourne.c:429
jsonbourne_read_code code
Definition jsonbourne.c:424
jsonbourne_read_flag flg
Definition jsonbourne.c:422
Optional read result; coordinates describe the parser's failure cursor.
Definition jsonbourne.h:290
jsonbourne_read_code code
Definition jsonbourne.h:291
One open container, replacing an equivalent recursive parser call.
Definition jsonbourne.c:438
unsigned char state
Definition jsonbourne.c:443
unsigned char type
Definition jsonbourne.c:442
unsigned char is_global
Definition jsonbourne.c:444
Per-read budgets checked during validation, before a DOM is allocated.
Definition jsonbourne.h:303
String view followed by optional source coordinates.
Definition jsonbourne.h:200
Decoded UTF-8 bytes; len, not strlen(), determines the string's extent.
Definition jsonbourne.h:189
const char * str
Definition jsonbourne.h:190
Value view followed by coordinates recorded only with TRACK_LOCATION.
Definition jsonbourne.h:259
Tagged DOM value; children and text borrow the root allocation's lifetime.
Definition jsonbourne.h:250
Suspended container traversal with constant-space sibling-cycle detection.
const jsonbourne_val * val
One output sink used unchanged for measuring and writing JSON text.
const char * indent
const char * newline