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.h
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.h
20 * @brief JSON reader, writer and DOM utilities for Linux C11 with a C++11-compatible API.
21 *
22 * @details
23 * Strict parsing validates RFC 8259 grammar and Unicode scalar values in UTF-8.
24 * The input need not be terminated, aligned or padded and is never modified.
25 * Decoded strings and unchanged numeric tokens are owned by the returned DOM.
26 * Duplicate names and their order are preserved; jsonbourne_obj_getn_unique() rejects
27 * ambiguous lookups. Embedded NULs are supported through explicit byte lengths.
28 *
29 * Parsing and cloning make one allocation, released with free() when the default
30 * allocator is used. Custom allocators must provide malloc-compatible alignment
31 * and own their corresponding release policy. jsonbourne_read_buf(), jsonbourne_read_measure(),
32 * jsonbourne_read_validate() and the *_buf writers do not allocate. Input, DOM and output
33 * buffers must not overlap and must remain stable throughout each operation.
34 * Allocator callbacks must not mutate input or DOM data. Independent calls share
35 * no mutable state and may run concurrently.
36 *
37 * JSONBOURNE_READER_DEPTH_LIMIT bounds reader nesting and fixed traversal storage.
38 * JSONBOURNE_WRITER_DEPTH_LIMIT bounds writer/copy traversal and defaults to the
39 * reader limit. Both are positive hard limits, initially 999; zero does not
40 * mean unlimited. Embedded consumers should select smaller application-specific
41 * limits when compiling jsonbourne.c. Runtime limits additionally bound input,
42 * total DOM bytes, decoded string bytes and value count before allocation.
43 * SIMD is automatic for baseline x86-64 SSE2 and AArch64 NEON; define
44 * JSONBOURNE_DISABLE_SIMD=1 for a scalar build. Every vector load is within the
45 * supplied input extent. Normal -O2/-O3 suffices; no fast-math or SSSE3 is needed.
46 *
47 * Writers validate accessible DOM structures, UTF-8, numbers, list lengths and
48 * cycles. All output sizes INCLUDE the terminating NUL, matching the original
49 * API. Numbers keep their decimal spelling and precision. Relaxed hexadecimal
50 * tokens are converted exactly, up to JSONBOURNE_MAX_HEX_DIGITS significant hex
51 * digits; larger conversions fail rather than overflow. The legacy relaxed
52 * nonfinite writer policy maps NaN to 0 and infinities to signed DBL_MAX text.
53 * Compile jsonbourne.c once with the desired build options and link its object.
54 * Public names follow Yuan conventions, but the DOM layout, flag bits and
55 * writer lengths are JSONbourne-specific rather than Yuan ABI compatible.
56 * Pretty-print indentation/newlines must contain JSON whitespace only.
57 *
58 * @par Why tokens and lengths are preserved
59 * Keeping decimal text avoids rounding large integers through binary floating
60 * point. Explicit byte lengths distinguish embedded NULs from terminators, and
61 * preserving duplicate keys lets the application decide whether ambiguity is
62 * acceptable instead of silently discarding input.
63 *
64 * @pre Input, DOM nodes, linked entries and output storage must refer to valid,
65 * accessible memory for their advertised lifetimes and extents. Structural
66 * validation detects malformed lists and cycles, not arbitrary invalid pointers.
67 * @note Select compile-time options when building jsonbourne.c; defining them
68 * only in a client does not change the linked implementation's storage limits.
69 * @see jsonbourne_read_buf(), jsonbourne_read_limits_default(), jsonbourne_version()
70 */
71
72#ifndef JSONBOURNE_H
73#define JSONBOURNE_H
74
75#include <stddef.h>
76#include <stdint.h>
77
78/**
79 * @defgroup jsonbourne_config Version and Build Configuration
80 * @brief Options applied when compiling the implementation translation unit.
81 * @{
82 */
83/** @brief Major API version component. */
84#define JSONBOURNE_VERSION_MAJOR 1
85/** @brief Minor API version component. */
86#define JSONBOURNE_VERSION_MINOR 0
87/** @brief Patch version component. */
88#define JSONBOURNE_VERSION_PATCH 1
89/** @brief Packed major/minor/patch version for compile-time comparisons. */
90#define JSONBOURNE_VERSION_HEX \
91 ((JSONBOURNE_VERSION_MAJOR << 16) | (JSONBOURNE_VERSION_MINOR << 8) | JSONBOURNE_VERSION_PATCH)
92/** @brief Human-readable header version; query jsonbourne_version() for the linked object. */
93#define JSONBOURNE_VERSION_STRING "1.0.1"
94
95#ifndef JSONBOURNE_READER_DEPTH_LIMIT
96/**
97 * @brief Maximum simultaneous open reader containers; must be positive.
98 * @details A fixed stack makes nesting memory predictable without recursive
99 * calls or growth allocations. Smaller application-specific bounds save stack
100 * space even when a particular input has little nesting.
101 * @see jsonbourne_read_limits::max_depth
102 */
103#define JSONBOURNE_READER_DEPTH_LIMIT 999
104#endif
105#ifndef JSONBOURNE_WRITER_DEPTH_LIMIT
106/**
107 * @brief Positive writer/copy nesting bound, defaulting to the reader bound.
108 * @details Separate limits allow a program to inspect deeper input than it is
109 * willing to traverse for output or copying, without unbounded stack growth.
110 */
111#define JSONBOURNE_WRITER_DEPTH_LIMIT JSONBOURNE_READER_DEPTH_LIMIT
112#endif
113#if JSONBOURNE_READER_DEPTH_LIMIT < 1 || JSONBOURNE_WRITER_DEPTH_LIMIT < 1
114#error JSONbourne reader and writer depth limits must be positive
115#endif
116#ifndef JSONBOURNE_MAX_HEX_DIGITS
117/**
118 * @brief Maximum significant hexadecimal digits converted to decimal output.
119 * @details Bounds exact conversion work and its fixed scratch array; accepted
120 * settings are 16 through 16384. Leading zeroes do not consume this limit.
121 */
122#define JSONBOURNE_MAX_HEX_DIGITS 1024
123#endif
124#if JSONBOURNE_MAX_HEX_DIGITS < 16 || JSONBOURNE_MAX_HEX_DIGITS > 16384
125#error JSONBOURNE_MAX_HEX_DIGITS must be between 16 and 16384
126#endif
127#ifndef JSONBOURNE_DISABLE_SIMD
128/** @brief Set to 1 to exercise the scalar path or omit architecture-specific intrinsics. */
129#define JSONBOURNE_DISABLE_SIMD 0
130#endif
131#ifndef JSONBOURNE_API
132/** @brief Optional declaration annotation for a consumer's visibility/export policy. */
133#define JSONBOURNE_API
134#endif
135/** @} */
136
137#ifdef __cplusplus
138extern "C" {
139#endif
140
141/**
142 * @defgroup jsonbourne_dom DOM Types and Read Options
143 * @brief Length-aware views, ordered containers, diagnostics and resource limits.
144 * @{
145 */
146/** @brief Read-option bitmask; combine named options with bitwise OR. */
147typedef size_t jsonbourne_read_flag;
148/**
149 * @brief Independent reader options and convenience presets.
150 * @details Presets are unions of feature bits, not distinct parser modes.
151 * Use the names rather than persisting raw masks so code can follow flag remaps.
152 */
154 JSONBOURNE_READ_NOFLAG = 0, /**< Strict RFC 8259 input. */
155 JSONBOURNE_READ_ALLOW_TRAILING_COMMAS = 0x0002, /**< Permit a comma before container closure. */
156 JSONBOURNE_READ_ALLOW_UNQUOTED_KEY = 0x0004, /**< Permit nonempty ASCII identifier-like keys. */
157 JSONBOURNE_READ_ALLOW_GLOBAL_OBJECT = 0x0008, /**< Permit an object without outer braces. */
158 JSONBOURNE_READ_ALLOW_EQUALS = 0x0010, /**< Permit equals in place of a member colon. */
159 JSONBOURNE_READ_ALLOW_NO_COMMAS = 0x0020, /**< Permit adjacent members/elements without commas. */
160 JSONBOURNE_READ_ALLOW_COMMENTS = 0x0040, /**< Skip C-style block and line comments. */
161 JSONBOURNE_READ_RESERVED = 0x0080, /**< Accepted reserved bit with no syntax effect. */
162 JSONBOURNE_READ_TRACK_LOCATION = 0x0100, /**< Allocate location extensions for values and keys. */
163 JSONBOURNE_READ_ALLOW_SINGLE_QUOTED_STR = 0x0200, /**< Permit single quotes and escaped apostrophes. */
164 JSONBOURNE_READ_ALLOW_HEX_NUM = 0x0400, /**< Permit hexadecimal integer tokens. */
165 JSONBOURNE_READ_ALLOW_PLUS_SIGN = 0x0800, /**< Permit an explicit positive number sign. */
166 JSONBOURNE_READ_ALLOW_DECIMAL_POINT = 0x1000, /**< Permit .5 and 1. forms. */
167 JSONBOURNE_READ_ALLOW_INF_AND_NAN = 0x2000, /**< Permit signed Infinity and NaN tokens. */
168 JSONBOURNE_READ_ALLOW_MULTILINE_STR = 0x4000, /**< Permit raw CR/LF and escaped line continuations. */
169 JSONBOURNE_READ_SIMPLIFIED = 0x003e, /**< Combine the five object/spacing conveniences. */
170 JSONBOURNE_READ_JSON5 = 0x7e46 /**< JSON5-style conveniences, not full conformance. */
171 /* bitmask combining nine parsing options
172 0x0002 | 0x0004 | 0x0040 | 0x0200 | 0x0400 |
173 0x0800 | 0x1000 | 0x2000 | 0x4000 = 0x7e46
174 */
175};
176
177/** @brief Payload tag; literals need no separately allocated payload. */
178typedef enum jsonbourne_type {
179 JSONBOURNE_TYPE_STR, /**< Payload is jsonbourne_str. */
180 JSONBOURNE_TYPE_NUM, /**< Payload is jsonbourne_num. */
181 JSONBOURNE_TYPE_OBJ, /**< Payload is jsonbourne_obj. */
182 JSONBOURNE_TYPE_ARR, /**< Payload is jsonbourne_arr. */
183 JSONBOURNE_TYPE_TRUE, /**< JSON true; payload is NULL for parsed values. */
184 JSONBOURNE_TYPE_FALSE, /**< JSON false; payload is NULL for parsed values. */
185 JSONBOURNE_TYPE_NULL /**< JSON null; payload is NULL for parsed values. */
187
188/** @brief Decoded UTF-8 bytes; len, not strlen(), determines the string's extent. */
189typedef struct jsonbourne_str {
190 const char *str; /**< DOM-owned bytes; parsed strings have an additional trailing NUL. */
191 size_t len; /**< Decoded byte count, excluding the trailing NUL. */
193
194/**
195 * @brief String view followed by optional source coordinates.
196 * @pre Only cast a parsed string/key to this type when TRACK_LOCATION was enabled.
197 * @details Keeping the base first preserves ordinary string access while making
198 * location storage opt-in rather than charging every node for coordinates.
199 */
200typedef struct jsonbourne_str_loc {
201 struct jsonbourne_str str; /**< Base view; must remain the first member. */
202 size_t pos; /**< Zero-based source byte offset. */
203 size_t line; /**< One-based line number; LF advances the line. */
204 size_t col; /**< Zero-based byte column, not a Unicode character count. */
206
207/** @brief Original number spelling, retained so reading never rounds through a double. */
208typedef struct jsonbourne_num {
209 const char *str; /**< DOM-owned token bytes with an additional trailing NUL after parsing. */
210 size_t len; /**< Token byte count, excluding the trailing NUL. */
212
213/** @brief Forward name for values referenced by recursive container entries. */
215
216/** @brief Forward name allowing an object entry to link to its own type. */
218/** @brief One object member; linked order and duplicate decoded keys are retained. */
220 jsonbourne_str *key; /**< Decoded member name. */
221 jsonbourne_val *val; /**< Member value. */
222 jsonbourne_obj_entry *next; /**< Next member, or NULL for the last member. */
223};
224
225/** @brief Ordered object members; len must exactly match the linked-list length. */
226typedef struct jsonbourne_obj {
227 jsonbourne_obj_entry *first; /**< First member; NULL for an empty object. */
228 size_t len; /**< Number of members, including duplicates. */
230
231/** @brief Forward name allowing an array entry to link to its own type. */
233/** @brief One array element in source order. */
235 jsonbourne_val *val; /**< Element value. */
236 jsonbourne_arr_entry *next; /**< Next element, or NULL for the last element. */
237};
238
239/** @brief Ordered array elements; explicit length supports bounded traversal. */
240typedef struct jsonbourne_arr {
241 jsonbourne_arr_entry *first; /**< First element; NULL for an empty array. */
242 size_t len; /**< Exact number of linked elements. */
244
245/**
246 * @brief Tagged DOM value; children and text borrow the root allocation's lifetime.
247 * @note Release an allocated tree once at its root, never by freeing individual
248 * payloads or entries. Caller-buffer roots must not be passed to free().
249 */
251 void *ptr; /**< Payload selected by type; parsed literals use NULL. */
252 size_t type; /**< One of the jsonbourne_type enumerators. */
253};
254
255/**
256 * @brief Value view followed by coordinates recorded only with TRACK_LOCATION.
257 * @pre Only use this extension for parsed values created with location tracking.
258 */
259typedef struct jsonbourne_val_loc {
260 struct jsonbourne_val val; /**< Base value; must remain the first member. */
261 size_t pos; /**< Zero-based source byte offset before the value. */
262 size_t line; /**< One-based source line. */
263 size_t col; /**< Zero-based source byte column. */
265
266/** @brief Stable storage type for a diagnostic code, separate from display text. */
267typedef size_t jsonbourne_read_code;
268/** @brief Reader failures; zero denotes success and leaves error coordinates zeroed. */
270 JSONBOURNE_READ_SUCCESS = 0, /**< No read failure. */
271 JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR, /**< Missing comma/closure or disallowed trailing comma. */
272 JSONBOURNE_READ_ERROR_EXPECTED_COLON, /**< Missing permitted key/value separator. */
273 JSONBOURNE_READ_ERROR_EXPECTED_KEY, /**< Missing or invalid object member name. */
274 JSONBOURNE_READ_ERROR_INVALID_ESCAPE, /**< Invalid escape or UTF-16 surrogate pairing. */
275 JSONBOURNE_READ_ERROR_INVALID_NUMBER, /**< Invalid number spelling or token boundary. */
276 JSONBOURNE_READ_ERROR_LITERAL, /**< Invalid true, false or null spelling/boundary. */
277 JSONBOURNE_READ_ERROR_UNEXPECTED_END, /**< Input ended before the construct was complete. */
278 JSONBOURNE_READ_ERROR_INVALID_STRING, /**< Disallowed unescaped string control byte. */
279 JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION, /**< Allocation failed or caller storage is insufficient. */
280 JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT, /**< Non-trivia bytes follow a complete root value. */
281 JSONBOURNE_READ_ERROR_DEPTH, /**< Container nesting exceeds the effective bound. */
282 JSONBOURNE_READ_ERROR_INVALID_COMMENT, /**< Block comment has no closing delimiter. */
283 JSONBOURNE_READ_ERROR_UNKNOWN, /**< Generic diagnostic and unrecognized-code fallback. */
284 JSONBOURNE_READ_ERROR_INVALID_UTF8, /**< Invalid UTF-8 scalar encoding. */
285 JSONBOURNE_READ_ERROR_LIMIT, /**< Resource bound or checked arithmetic was exceeded. */
286 JSONBOURNE_READ_ERROR_INVALID_PARAMETER /**< Invalid flags, limits, input or storage alignment. */
287};
288
289/** @brief Optional read result; coordinates describe the parser's failure cursor. */
290typedef struct jsonbourne_read_err {
291 jsonbourne_read_code code; /**< Success or one of the JSONBOURNE_READ_ERROR_* codes. */
292 size_t pos; /**< Zero-based failure offset, clamped to the input extent. */
293 size_t line; /**< One-based failure line, or zero on success. */
294 size_t col; /**< Zero-based failure byte column, or zero on success. */
296
297/**
298 * @brief Per-read budgets checked during validation, before a DOM is allocated.
299 * @details Limits are literal upper bounds: zero permits none of the resource,
300 * not an unlimited amount. Start with jsonbourne_read_limits_default() so a
301 * partially initialized structure cannot accidentally prohibit useful input.
302 */
304 size_t max_depth; /**< Open containers; cannot exceed the compiled reader limit. */
305 size_t max_input_len; /**< Entire input extent in bytes, including trivia. */
306 size_t max_memory; /**< Combined DOM record and text bytes, not total process memory. */
307 size_t max_vals; /**< Root plus nested values; member keys are not values. */
308 size_t max_str_len; /**< Decoded bytes in each string/key, excluding its terminator. */
310
311/** @brief Numeric spelling extensions; does not by itself permit Infinity or NaN. */
312#define JSONBOURNE_READ_ALLOW_EXT_NUMBER \
313 (JSONBOURNE_READ_ALLOW_HEX_NUM | JSONBOURNE_READ_ALLOW_PLUS_SIGN | \
314 JSONBOURNE_READ_ALLOW_DECIMAL_POINT)
315/** @} */
316
317/**
318 * @brief Query the linked implementation rather than the including header.
319 * @return Packed major/minor/patch version in JSONBOURNE_VERSION_HEX format.
320 * @ingroup jsonbourne_config
321 */
323
324/**
325 * @defgroup jsonbourne_reader Reading and Validation
326 * @brief Strict/relaxed reads, allocation-free checks and caller-owned storage.
327 * @{
328 */
329/**
330 * @brief Create default budgets using the linked implementation's reader limit.
331 * @return Fully initialized limits with pointer-safe byte bounds and no tighter
332 * application policy for value count or individual string length.
333 * @note These defaults are not a whole-application memory budget; reduce them
334 * for inputs that must fit a particular arena or embedded workload.
335 */
337
338/**
339 * @brief Validate input and measure the exact single-allocation DOM size.
340 * @param[in] src Input bytes; NULL is permitted only when len is zero.
341 * @param[in] len Input byte count, including any trailing trivia.
342 * @param[in] flg Named read options combined with bitwise OR.
343 * @param[in] limits Optional budgets; NULL selects linked defaults.
344 * @param[out] required Optional exact allocation size; zero on failure.
345 * @param[out] err Optional diagnostic; populated on success and failure.
346 * @retval 1 The complete input is valid within all effective limits.
347 * @retval 0 Syntax, encoding, arguments or resource checks failed.
348 * @note Does not allocate or retain input pointers. The same parser is used for
349 * sizing and materialization so resource checks cannot disagree with allocation.
350 */
351JSONBOURNE_API int jsonbourne_read_measure(const void *src, size_t len, jsonbourne_read_flag flg,
352 const jsonbourne_read_limits *limits, size_t *required,
354
355/**
356 * @brief Validate the entire extent without allocating a DOM or changing input.
357 * @param[in] src Input bytes; NULL is permitted only for a zero-length extent.
358 * @param[in] len Number of input bytes to inspect.
359 * @param[in] flg Named read-option mask.
360 * @param[in] limits Optional budgets; NULL selects linked defaults.
361 * @param[out] err Optional read diagnostic.
362 * @retval 1 Valid complete input within the selected budgets.
363 * @retval 0 Invalid input, arguments, encoding or resource usage.
364 * @see jsonbourne_read_measure()
365 */
366JSONBOURNE_API int jsonbourne_read_validate(const void *src, size_t len, jsonbourne_read_flag flg,
367 const jsonbourne_read_limits *limits,
369
370/**
371 * @brief Read a DOM into aligned caller storage without heap allocation.
372 * @param[in] src Immutable input bytes, disjoint from buf.
373 * @param[in] len Input extent in bytes.
374 * @param[in] flg Named read-option mask.
375 * @param[in] limits Optional budgets; NULL selects linked defaults.
376 * @param[out] buf Storage with malloc-compatible alignment; NULL probes capacity.
377 * @param[in] cap Available bytes at buf.
378 * @param[out] required Optional exact size after successful validation, even if
379 * storage is too small; zero if validation fails.
380 * @param[out] err Optional diagnostic, including storage/alignment failures.
381 * @return Root in buf, or NULL on failure; never free this root separately.
382 * @note A missing/short buffer reports MEMORY_ALLOCATION and is not written.
383 * The arena must outlive all returned nodes, strings and borrowed views.
384 */
385JSONBOURNE_API jsonbourne_val *jsonbourne_read_buf(const void *src, size_t len,
387 const jsonbourne_read_limits *limits, void *buf,
388 size_t cap, size_t *required,
390
391/**
392 * @brief Validate against explicit budgets, then allocate the entire DOM once.
393 * @param[in] src Immutable input extent; never retained by the returned tree.
394 * @param[in] len Input size in bytes.
395 * @param[in] flg Named read-option mask.
396 * @param[in] limits Optional budgets; NULL selects linked defaults.
397 * @param[in] alc_fn Optional allocator called as alc_fn(alc_ctx, byte_count);
398 * NULL uses malloc. Returned storage must have malloc-compatible alignment.
399 * @param[in] alc_ctx Opaque allocator context, forwarded unchanged.
400 * @param[out] err Optional read diagnostic.
401 * @return Owning root, or NULL on failure; default-allocated roots use free().
402 * @note Custom allocators own their release policy, including rejected storage;
403 * no custom deallocator is available on this read interface.
404 */
406 const void *src, size_t len, jsonbourne_read_flag flg, const jsonbourne_read_limits *limits,
407 void *(*alc_fn)(void *, size_t), void *alc_ctx, jsonbourne_read_err *err);
408
409/**
410 * @brief Read with named options and the linked implementation's default limits.
411 * @param[in] src Immutable input bytes.
412 * @param[in] len Input byte count.
413 * @param[in] flg Named read-option mask.
414 * @param[in] alc_fn Optional malloc-aligned allocator; NULL uses malloc.
415 * @param[in] alc_ctx Opaque allocation context.
416 * @param[out] err Optional diagnostic.
417 * @return Root owning one allocation, or NULL on failure.
418 * @see jsonbourne_read_opts_with_limits() for custom allocator lifetime rules.
419 */
420JSONBOURNE_API jsonbourne_val *jsonbourne_read_opts(const void *src, size_t len,
422 void *(*alc_fn)(void *, size_t), void *alc_ctx,
424
425/**
426 * @brief Read strict JSON with default limits and malloc-backed ownership.
427 * @param[in] src Immutable input bytes; no trailing NUL or padding is required.
428 * @param[in] len Exact input byte count.
429 * @return Owning root released once with free(), or NULL on failure.
430 * @see jsonbourne_read_opts() when a diagnostic or relaxed syntax is needed.
431 */
432JSONBOURNE_API jsonbourne_val *jsonbourne_read(const void *src, size_t len);
433/** @} */
434
435/**
436 * @defgroup jsonbourne_writer Writing and Copying
437 * @brief Bounded iterative traversal with preflighted allocation/capacity checks.
438 * @{
439 */
440/**
441 * @brief Validate a DOM and allocate minified JSON output.
442 * @param[in] val Accessible root; must remain stable through both passes.
443 * @param[in] alc_fn Optional output allocator; NULL uses malloc.
444 * @param[in] free_fn Optional matching failure-release callback. If absent,
445 * failed output allocations are released with free().
446 * @param[in] alc_ctx Opaque context passed to allocation/release callbacks.
447 * @param[out] out_len Optional output bytes INCLUDING NUL; zero on failure.
448 * @return NUL-terminated output, or NULL for invalid DOM, limits or allocation.
449 * @note Successful output belongs to the caller and is never released here.
450 * Custom storage must be free-compatible unless free_fn supplies its release.
451 */
453 void *(*alc_fn)(void *, size_t),
454 void (*free_fn)(void *, void *), void *alc_ctx,
455 size_t *out_len);
456
457/**
458 * @brief Allocate minified JSON using malloc.
459 * @param[in] val Accessible, stable DOM root.
460 * @param[out] out_len Optional NUL-inclusive output size; zero on failure.
461 * @return Output released with free(), or NULL on failure.
462 */
463JSONBOURNE_API void *jsonbourne_val_write(const jsonbourne_val *val, size_t *out_len);
464
465/**
466 * @brief Validate and allocate pretty output with explicit formatting/ownership.
467 * @param[in] val Accessible DOM root, stable throughout both passes.
468 * @param[in] indent NUL-terminated JSON whitespace; NULL selects two spaces.
469 * @param[in] newline NUL-terminated JSON whitespace; NULL selects LF.
470 * @param[in] alc_fn Optional output allocator; NULL uses malloc.
471 * @param[in] free_fn Optional failure-release callback; NULL falls back to free().
472 * @param[in] alc_ctx Opaque allocation/release context.
473 * @param[out] out_len Optional NUL-inclusive size; zero on failure.
474 * @return Caller-owned output, or NULL on failure.
475 * @note Restricting formatting to JSON whitespace keeps pretty output valid JSON.
476 * @see jsonbourne_val_write_opts() for custom allocation release rules.
477 */
478JSONBOURNE_API void *jsonbourne_val_write_pretty_opts(const jsonbourne_val *val, const char *indent,
479 const char *newline,
480 void *(*alc_fn)(void *, size_t),
481 void (*free_fn)(void *, void *),
482 void *alc_ctx, size_t *out_len);
483
484/**
485 * @brief Allocate pretty JSON using malloc.
486 * @param[in] val Accessible, stable DOM root.
487 * @param[in] indent JSON whitespace; NULL selects two spaces.
488 * @param[in] newline JSON whitespace; NULL selects LF.
489 * @param[out] out_len Optional NUL-inclusive size; zero on failure.
490 * @return Output released with free(), or NULL on failure.
491 */
492JSONBOURNE_API void *jsonbourne_val_write_pretty(const jsonbourne_val *val, const char *indent,
493 const char *newline, size_t *out_len);
494
495/**
496 * @brief Preflight minified output, then write only if the caller buffer fits.
497 * @param[in] val Accessible DOM disjoint from the output buffer.
498 * @param[out] buf Destination; NULL measures without writing.
499 * @param[in] cap Destination capacity in bytes, including room for NUL.
500 * @param[out] out_len Optional required NUL-inclusive size; zero for an invalid DOM.
501 * @retval 1 Complete output, including NUL, was written.
502 * @retval 0 Validation failed or storage is absent/insufficient.
503 * @note A valid size probe returns 0 with the required length. Insufficient
504 * storage stays untouched because traversal is measured before the first write.
505 */
506JSONBOURNE_API int jsonbourne_val_write_buf(const jsonbourne_val *val, char *buf, size_t cap,
507 size_t *out_len);
508
509/**
510 * @brief Preflight pretty output without allocating storage.
511 * @param[in] val Accessible DOM, stable and disjoint from buf.
512 * @param[in] indent JSON whitespace; NULL selects two spaces.
513 * @param[in] newline JSON whitespace; NULL selects LF.
514 * @param[out] buf Output destination; NULL probes the required size.
515 * @param[in] cap Destination extent including terminator space.
516 * @param[out] out_len Optional required NUL-inclusive size; zero on validation failure.
517 * @retval 1 Complete pretty output was written.
518 * @retval 0 Invalid input/formatting or absent/insufficient storage.
519 * @see jsonbourne_val_write_buf() for size-probe and untouched-buffer behavior.
520 */
521JSONBOURNE_API int jsonbourne_val_write_pretty_buf(const jsonbourne_val *val, const char *indent,
522 const char *newline, char *buf, size_t cap,
523 size_t *out_len);
524
525/**
526 * @brief Deep-copy a validated value into one independent allocation.
527 * @param[in] val Accessible source DOM; no source storage is borrowed by the copy.
528 * @param[in] alc_fn Optional malloc-aligned allocator; NULL uses malloc.
529 * @param[in] alc_ctx Opaque allocation context.
530 * @return Owning copy, or NULL for invalid DOM, nesting/size limits or allocation.
531 * @note Source coordinates are deliberately not copied: they describe the
532 * original document, not the storage or provenance of the new tree.
533 * Custom allocators retain their own release policy, including rejected storage.
534 */
536jsonbourne_val_copy_opts(const jsonbourne_val *val, void *(*alc_fn)(void *, size_t), void *alc_ctx);
537
538/**
539 * @brief Make an independently owned deep copy using malloc.
540 * @param[in] val Accessible source root.
541 * @return Copy released once with free(), or NULL on failure.
542 * @see jsonbourne_val_copy_opts()
543 */
545/** @} */
546
547/**
548 * @defgroup jsonbourne_access Access and Conversion
549 * @brief Borrowed views, unambiguous lookups and exact integer conversions.
550 * @{
551 */
552/**
553 * @brief Borrow a string payload without allocating or copying.
554 * @param[in] val Value to inspect; NULL is accepted.
555 * @return String view, or NULL for a different tag/NULL value.
556 * @note The view shares the source root/arena's lifetime.
557 */
559
560/**
561 * @brief Borrow the original number-token view.
562 * @param[in] val Value to inspect; NULL is accepted.
563 * @return Number view, or NULL for a different tag/NULL value.
564 * @note No floating-point conversion or ownership transfer occurs.
565 */
567
568/**
569 * @brief Borrow the ordered object payload.
570 * @param[in] val Value to inspect; NULL is accepted.
571 * @return Object view, or NULL for a different tag/NULL value.
572 */
574
575/**
576 * @brief Borrow the ordered array payload.
577 * @param[in] val Value to inspect; NULL is accepted.
578 * @return Array view, or NULL for a different tag/NULL value.
579 */
581
582/**
583 * @brief Test the true tag without coercing numbers or strings.
584 * @param[in] val Value to inspect; NULL is accepted.
585 * @return 1 only for a non-NULL true-tagged value, otherwise 0.
586 */
588
589/**
590 * @brief Test the false tag without truthiness conversion.
591 * @param[in] val Value to inspect; NULL is accepted.
592 * @return 1 only for a non-NULL false-tagged value, otherwise 0.
593 */
595
596/**
597 * @brief Distinguish JSON null from a missing C pointer.
598 * @param[in] val Value to inspect; NULL itself is not a JSON null node.
599 * @return 1 only for a non-NULL null-tagged value, otherwise 0.
600 */
602
603/**
604 * @brief Find the first exact decoded member name, including embedded NUL bytes.
605 * @param[in] val Accessible object value.
606 * @param[in] key Decoded key bytes; NULL is accepted only when len is zero.
607 * @param[in] len Exact key byte count, not a terminator-inclusive size.
608 * @return Borrowed first-match value, or NULL for no match/invalid traversal.
609 * @note Returns immediately on a match; it does not validate the remaining list
610 * or reject duplicates. Use jsonbourne_obj_getn_unique() for configuration keys.
611 */
612JSONBOURNE_API const jsonbourne_val *jsonbourne_obj_getn(const jsonbourne_val *val, const char *key,
613 size_t len);
614
615/**
616 * @brief Require exactly one decoded matching key instead of silently choosing.
617 * @param[in] val Accessible object value.
618 * @param[in] key Decoded key bytes; NULL is accepted only when len is zero.
619 * @param[in] len Exact key byte count.
620 * @return Borrowed value, or NULL for duplicates, no match or malformed traversal.
621 * @note Comparing decoded bytes catches aliases such as "a" and "\u0061".
622 */
624 const char *key, size_t len);
625
626/**
627 * @brief Locate a zero-based array element by bounded linked traversal.
628 * @param[in] val Accessible array value.
629 * @param[in] idx Zero-based element index.
630 * @return Borrowed element, or NULL for invalid input/index/traversal.
631 * @note Lookup is linear in idx and does not validate the unvisited suffix.
632 */
634
635/**
636 * @brief Convert an unsigned decimal integer token exactly, without coercion.
637 * @param[in] num Token view; signs, fractions, exponents and leading zeroes are rejected.
638 * @param[out] out Required destination, written only on success.
639 * @retval 1 The integer fits uint64_t and was stored.
640 * @retval 0 Invalid token/arguments or overflow; out remains unchanged.
641 * @note Checking before each multiply/add avoids floating-point rounding and
642 * unsigned wraparound at UINT64_MAX.
643 */
644JSONBOURNE_API int jsonbourne_num_to_uint(const jsonbourne_num *num, uint64_t *out);
645
646/**
647 * @brief Convert a signed decimal integer token exactly, including INT64_MIN.
648 * @param[in] num Decimal integer spelling with an optional minus, but no plus.
649 * @param[out] out Required destination, written only on success.
650 * @retval 1 The integer fits int64_t and was stored.
651 * @retval 0 Invalid token/arguments or overflow; out remains unchanged.
652 * @note The negative range has one extra magnitude; conversion avoids negating
653 * INT64_MIN or overflowing an intermediate signed value.
654 */
655JSONBOURNE_API int jsonbourne_num_to_sint(const jsonbourne_num *num, int64_t *out);
656
657/**
658 * @brief Resolve an RFC 6901 pointer without allocating decoded path tokens.
659 * @param[in] val Accessible root to query.
660 * @param[in] pointer Pointer bytes, not URI-fragment notation; NULL only for len zero.
661 * @param[in] len Exact pointer byte count; zero selects the root itself.
662 * @return Borrowed result, or NULL for invalid syntax, ambiguity or a missing path.
663 * @note Object names must match uniquely after ~0/~1 decoding. Array indices
664 * are checked decimal integers without leading zeroes; '-' is not an element.
665 */
667 const char *pointer, size_t len);
668
669/**
670 * @brief Borrow human-readable diagnostic text without allocating.
671 * @param[in] code Read code; unrecognized codes select the generic diagnostic.
672 * @return Static NUL-terminated text that must not be modified or freed.
673 * @note Branch on numeric codes, not these intentionally editable messages.
674 */
676/** @} */
677
678#ifdef __cplusplus
679}
680#endif
681
682#endif
JSONBOURNE_API int jsonbourne_num_to_sint(const jsonbourne_num *num, int64_t *out)
Convert a signed decimal integer token exactly, including INT64_MIN.
JSONBOURNE_API int jsonbourne_is_null(const jsonbourne_val *val)
Distinguish JSON null from a missing C pointer.
JSONBOURNE_API 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.
JSONBOURNE_API const jsonbourne_val * jsonbourne_arr_get(const jsonbourne_val *val, size_t idx)
Locate a zero-based array element by bounded linked traversal.
JSONBOURNE_API int jsonbourne_is_false(const jsonbourne_val *val)
Test the false tag without truthiness conversion.
JSONBOURNE_API const char * jsonbourne_read_err_desc(jsonbourne_read_code code)
Borrow human-readable diagnostic text without allocating.
JSONBOURNE_API 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.
JSONBOURNE_API int jsonbourne_num_to_uint(const jsonbourne_num *num, uint64_t *out)
Convert an unsigned decimal integer token exactly, without coercion.
JSONBOURNE_API jsonbourne_arr * jsonbourne_get_arr(jsonbourne_val *val)
Borrow the ordered array payload.
JSONBOURNE_API jsonbourne_obj * jsonbourne_get_obj(jsonbourne_val *val)
Borrow the ordered object payload.
JSONBOURNE_API jsonbourne_str * jsonbourne_get_str(jsonbourne_val *val)
Borrow a string payload without allocating or copying.
JSONBOURNE_API 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.
JSONBOURNE_API int jsonbourne_is_true(const jsonbourne_val *val)
Test the true tag without coercing numbers or strings.
JSONBOURNE_API jsonbourne_num * jsonbourne_get_num(jsonbourne_val *val)
Borrow the original number-token view.
JSONBOURNE_API uint32_t jsonbourne_version(void)
Query the linked implementation rather than the including header.
Definition jsonbourne.c:104
#define JSONBOURNE_API
Optional declaration annotation for a consumer's visibility/export policy.
Definition jsonbourne.h:133
size_t jsonbourne_read_code
Stable storage type for a diagnostic code, separate from display text.
Definition jsonbourne.h:267
jsonbourne_type
Payload tag; literals need no separately allocated payload.
Definition jsonbourne.h:178
size_t jsonbourne_read_flag
Read-option bitmask; combine named options with bitwise OR.
Definition jsonbourne.h:147
jsonbourne_read_code_e
Reader failures; zero denotes success and leaves error coordinates zeroed.
Definition jsonbourne.h:269
jsonbourne_read_flag_e
Independent reader options and convenience presets.
Definition jsonbourne.h:153
@ 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_UNKNOWN
Definition jsonbourne.h:283
@ 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_JSON5
Definition jsonbourne.h:170
@ 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_RESERVED
Definition jsonbourne.h:161
@ 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_SIMPLIFIED
Definition jsonbourne.h:169
@ JSONBOURNE_READ_ALLOW_SINGLE_QUOTED_STR
Definition jsonbourne.h:163
JSONBOURNE_API jsonbourne_val * jsonbourne_read(const void *src, size_t len)
Read strict JSON with default limits and malloc-backed ownership.
JSONBOURNE_API 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.
JSONBOURNE_API 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_API 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_API 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.
JSONBOURNE_API 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.
JSONBOURNE_API 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.
JSONBOURNE_API void * jsonbourne_val_write(const jsonbourne_val *val, size_t *out_len)
Allocate minified JSON using malloc.
JSONBOURNE_API 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.
JSONBOURNE_API 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_API jsonbourne_val * jsonbourne_val_copy(const jsonbourne_val *val)
Make an independently owned deep copy using malloc.
JSONBOURNE_API 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.
JSONBOURNE_API 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.
JSONBOURNE_API 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.
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
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
Optional read result; coordinates describe the parser's failure cursor.
Definition jsonbourne.h:290
jsonbourne_read_code code
Definition jsonbourne.h:291
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
struct jsonbourne_str str
Definition jsonbourne.h:201
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
struct jsonbourne_val val
Definition jsonbourne.h:260
Tagged DOM value; children and text borrow the root allocation's lifetime.
Definition jsonbourne.h:250