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 File Reference

Bounded, two-pass JSON parsing and iterative DOM operations. More...

#include "jsonbourne.h"
#include <stdlib.h>
#include <string.h>
Include dependency graph for jsonbourne.c:

Go to the source code of this file.

Data Structures

struct  jsonbourne_pool
 Two-region arena shared by measurement and materialization. More...
struct  jsonbourne_read_ctx
 Per-call parser state; no mutable global state or input modification is needed. More...
struct  jsonbourne_read_frame
 One open container, replacing an equivalent recursive parser call. More...
struct  jsonbourne_walk_frame
 Suspended container traversal with constant-space sibling-cycle detection. More...
struct  jsonbourne_write_ctx
 One output sink used unchanged for measuring and writing JSON text. More...
struct  jsonbourne_copy_frame
 Per-depth destination append state, separate from source-walker frames. More...
struct  jsonbourne_copy_ctx
 Copy visitor state; the arena layout is shared with the parser. More...

Macros

#define JSONBOURNE_READ_FLAG_MASK
 Derive the accepted bits from named options so flag remaps cannot stale this mask.
#define JSONBOURNE_ZERO   {0}
 C11 aggregate zero-initializer without byte-copying object representations.
#define JSONBOURNE_ALIGNOF(type)
 Required C11 alignment for an arena's typed record region.
Reader diagnostic text

Display strings kept separate from machine-readable error codes.

Centralizing text lets wording change without touching control flow. Every macro remains one source line so each message has one editing location.

#define JSONBOURNE_READ_SUCCESS_MSG   "JSONbourne found zero errors and is now insufferable at parties."
 Message for successful validation.
#define JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR_MSG   "The comma and closing bracket have both rage-quit this syntax rave."
 Missing container separator/closure diagnostic.
#define JSONBOURNE_READ_ERROR_EXPECTED_COLON_MSG   "This key and value eloped without filing the mandatory colon paperwork."
 Missing key/value separator diagnostic.
#define JSONBOURNE_READ_ERROR_EXPECTED_KEY_MSG   "That member name needs quotes, not a fake moustache and a convincing backstory."
 Invalid member-name diagnostic.
#define JSONBOURNE_READ_ERROR_INVALID_ESCAPE_MSG   "That string escape tried to clear Unicode customs with a counterfeit surrogate."
 Invalid escape/surrogate diagnostic.
#define JSONBOURNE_READ_ERROR_INVALID_NUMBER_MSG   "That alleged number has been banned from every calculator in three dimensions."
 Invalid numeric-token diagnostic.
#define JSONBOURNE_READ_ERROR_LITERAL_MSG   "Wishful thinking in a trench coat is still not a JSON value."
 Invalid true/false/null token diagnostic.
#define JSONBOURNE_READ_ERROR_UNEXPECTED_END_MSG   "Your input rolled the end credits while the document was still introducing itself."
 Premature end-of-input diagnostic.
#define JSONBOURNE_READ_ERROR_INVALID_STRING_MSG   "An unescaped control character is rearranging the furniture inside your string."
 Disallowed string control-byte diagnostic.
#define JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION_MSG   "Your DOM ordered a penthouse and the allocator delivered a shoebox with no floor."
 Allocation failure or insufficient caller-storage diagnostic.
#define JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT_MSG   "Your document is finished but the trailing input has launched an unsolicited podcast."
 Non-trivia input remaining after the root diagnostic.
#define JSONBOURNE_READ_ERROR_DEPTH_MSG   "Your containers nested past the depth limit and filed for their own postcode."
 Nesting-limit diagnostic.
#define JSONBOURNE_READ_ERROR_INVALID_COMMENT_MSG   "Your block comment swallowed the entire document while waiting for its missing */."
 Unterminated block-comment diagnostic.
#define JSONBOURNE_READ_ERROR_UNKNOWN_MSG   "Your JSON structure belongs in a modern-art museum, not in this parser."
 Generic diagnostic, also used for unrecognized codes.
#define JSONBOURNE_READ_ERROR_INVALID_UTF8_MSG   "UTF-8 cannot decode whatever experimental keyboard jazz these bytes are performing."
 Invalid Unicode scalar encoding diagnostic.
#define JSONBOURNE_READ_ERROR_LIMIT_MSG   "Your resource or arithmetic limit refuses to finance infinity's latest shopping spree."
 Resource-budget or arithmetic-limit diagnostic.
#define JSONBOURNE_READ_ERROR_INVALID_PARAMETER_MSG   "Your arguments, flags or buffer layout have turned this call into a constitutional crisis."
 Invalid API arguments or buffer-layout diagnostic.

Enumerations

enum  jsonbourne_event { JSONBOURNE_EVENT_VAL , JSONBOURNE_EVENT_KEY , JSONBOURNE_EVENT_ELEM , JSONBOURNE_EVENT_END }
 Shared traversal protocol so writing and cloning use identical structural checks. More...

Functions

uint32_t jsonbourne_version (void)
 Query the linked implementation rather than the including header.
struct jsonbourne_read_limits jsonbourne_read_limits_default (void)
 Create default budgets using the linked implementation's reader limit.
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.
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.
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.
static int jsonbourne_char_is_space (unsigned char chr)
 Recognize only the four JSON whitespace bytes, independently of locale.
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.
static int jsonbourne_hex_to_digit (unsigned char chr)
 Decode an ASCII hexadecimal digit without locale-sensitive conversion.
static int jsonbourne_char_is_digit (unsigned char chr)
 Recognize the decimal digits permitted by JSON number grammar.
static int jsonbourne_char_is_id (unsigned char chr)
 Classify this reader's relaxed, ASCII-only unquoted-key alphabet.
static size_t jsonbourne_utf8_len (const unsigned char *src, size_t len)
 Validate exactly one UTF-8 scalar without reading beyond the extent.
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.
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.
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.
static int jsonbourne_skip_trivia (struct jsonbourne_read_ctx *ctx)
 Consume whitespace and enabled comments without swallowing grammar bytes.
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.
static int jsonbourne_read_hex4 (struct jsonbourne_read_ctx *ctx, uint32_t *unit)
 Consume the four hexadecimal digits following a Unicode escape marker.
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.
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.
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.
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.
static int jsonbourne_read_document (struct jsonbourne_read_ctx *ctx, jsonbourne_val **root)
 Drive one complete JSON document using explicit container frames.
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.
static void jsonbourne_read_report (const struct jsonbourne_read_ctx *ctx, jsonbourne_read_err *err)
 Normalize parser/arena failure into an optional public diagnostic.
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.
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.
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.
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.
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_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_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.
jsonbourne_val * jsonbourne_read (const void *src, size_t len)
 Read strict JSON with default limits and malloc-backed ownership.
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_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_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.
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_write_hex_num (struct jsonbourne_write_ctx *out, const char *src, size_t len)
 Convert hexadecimal magnitude text exactly using bounded decimal digits.
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_indent (struct jsonbourne_write_ctx *out, size_t depth)
 Write a configured line break and one indentation unit per nesting level.
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.
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 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.
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.
void * jsonbourne_val_write (const jsonbourne_val *val, size_t *out_len)
 Allocate minified JSON using malloc.
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_pretty (const jsonbourne_val *val, const char *indent, const char *newline, size_t *out_len)
 Allocate pretty JSON using malloc.
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.
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.
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.
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.
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.
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_val * jsonbourne_val_copy (const jsonbourne_val *val)
 Make an independently owned deep copy using malloc.
jsonbourne_str * jsonbourne_get_str (jsonbourne_val *val)
 Borrow a string payload without allocating or copying.
jsonbourne_num * jsonbourne_get_num (jsonbourne_val *val)
 Borrow the original number-token view.
jsonbourne_obj * jsonbourne_get_obj (jsonbourne_val *val)
 Borrow the ordered object payload.
jsonbourne_arr * jsonbourne_get_arr (jsonbourne_val *val)
 Borrow the ordered array payload.
int jsonbourne_is_true (const jsonbourne_val *val)
 Test the true tag without coercing numbers or strings.
int jsonbourne_is_false (const jsonbourne_val *val)
 Test the false tag without truthiness conversion.
int jsonbourne_is_null (const jsonbourne_val *val)
 Distinguish JSON null from a missing C pointer.
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.
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.
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.
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_num_to_uint (const jsonbourne_num *num, uint64_t *out)
 Convert an unsigned decimal integer token exactly, without coercion.
int jsonbourne_num_to_sint (const jsonbourne_num *num, int64_t *out)
 Convert a signed decimal integer token exactly, including INT64_MIN.
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.
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 char * jsonbourne_read_err_desc (jsonbourne_read_code code)
 Borrow human-readable diagnostic text without allocating.

Detailed Description

Bounded, two-pass JSON parsing and iterative DOM operations.

Validation and materialization deliberately share the same grammar. A counting pass establishes exact record/text requirements before one backing allocation is split into aligned records and byte strings. Writers and copies likewise reuse a single walker so their sizing and output passes agree.

Implementation invariants
Cursors never exceed their extents; arithmetic is checked before advancing. A NULL pool/output base means measurement, not allocation failure. Fixed traversal frames replace recursion, and all per-call state remains local. The API still requires accessible, stable input and DOM pointers: structural checks cannot make arbitrary addresses safe to dereference.
See also
jsonbourne.h for public ownership, argument and return-value contracts.

Definition in file jsonbourne.c.

Macro Definition Documentation

◆ JSONBOURNE_ALIGNOF

#define JSONBOURNE_ALIGNOF ( type)
Value:
_Alignof(type)

Required C11 alignment for an arena's typed record region.

Definition at line 92 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_DEPTH_MSG

#define JSONBOURNE_READ_ERROR_DEPTH_MSG   "Your containers nested past the depth limit and filed for their own postcode."

Nesting-limit diagnostic.

Definition at line 72 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_EXPECTED_COLON_MSG

#define JSONBOURNE_READ_ERROR_EXPECTED_COLON_MSG   "This key and value eloped without filing the mandatory colon paperwork."

Missing key/value separator diagnostic.

Definition at line 54 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_EXPECTED_KEY_MSG

#define JSONBOURNE_READ_ERROR_EXPECTED_KEY_MSG   "That member name needs quotes, not a fake moustache and a convincing backstory."

Invalid member-name diagnostic.

Definition at line 56 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR_MSG

#define JSONBOURNE_READ_ERROR_EXPECTED_SEPARATOR_MSG   "The comma and closing bracket have both rage-quit this syntax rave."

Missing container separator/closure diagnostic.

Definition at line 52 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_INVALID_COMMENT_MSG

#define JSONBOURNE_READ_ERROR_INVALID_COMMENT_MSG   "Your block comment swallowed the entire document while waiting for its missing */."

Unterminated block-comment diagnostic.

Definition at line 74 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_INVALID_ESCAPE_MSG

#define JSONBOURNE_READ_ERROR_INVALID_ESCAPE_MSG   "That string escape tried to clear Unicode customs with a counterfeit surrogate."

Invalid escape/surrogate diagnostic.

Definition at line 58 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_INVALID_NUMBER_MSG

#define JSONBOURNE_READ_ERROR_INVALID_NUMBER_MSG   "That alleged number has been banned from every calculator in three dimensions."

Invalid numeric-token diagnostic.

Definition at line 60 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_INVALID_PARAMETER_MSG

#define JSONBOURNE_READ_ERROR_INVALID_PARAMETER_MSG   "Your arguments, flags or buffer layout have turned this call into a constitutional crisis."

Invalid API arguments or buffer-layout diagnostic.

Definition at line 82 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_INVALID_STRING_MSG

#define JSONBOURNE_READ_ERROR_INVALID_STRING_MSG   "An unescaped control character is rearranging the furniture inside your string."

Disallowed string control-byte diagnostic.

Definition at line 66 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_INVALID_UTF8_MSG

#define JSONBOURNE_READ_ERROR_INVALID_UTF8_MSG   "UTF-8 cannot decode whatever experimental keyboard jazz these bytes are performing."

Invalid Unicode scalar encoding diagnostic.

Definition at line 78 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_LIMIT_MSG

#define JSONBOURNE_READ_ERROR_LIMIT_MSG   "Your resource or arithmetic limit refuses to finance infinity's latest shopping spree."

Resource-budget or arithmetic-limit diagnostic.

Definition at line 80 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_LITERAL_MSG

#define JSONBOURNE_READ_ERROR_LITERAL_MSG   "Wishful thinking in a trench coat is still not a JSON value."

Invalid true/false/null token diagnostic.

Definition at line 62 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION_MSG

#define JSONBOURNE_READ_ERROR_MEMORY_ALLOCATION_MSG   "Your DOM ordered a penthouse and the allocator delivered a shoebox with no floor."

Allocation failure or insufficient caller-storage diagnostic.

Definition at line 68 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT_MSG

#define JSONBOURNE_READ_ERROR_UNEXPECTED_CONTENT_MSG   "Your document is finished but the trailing input has launched an unsolicited podcast."

Non-trivia input remaining after the root diagnostic.

Definition at line 70 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_UNEXPECTED_END_MSG

#define JSONBOURNE_READ_ERROR_UNEXPECTED_END_MSG   "Your input rolled the end credits while the document was still introducing itself."

Premature end-of-input diagnostic.

Definition at line 64 of file jsonbourne.c.

◆ JSONBOURNE_READ_ERROR_UNKNOWN_MSG

#define JSONBOURNE_READ_ERROR_UNKNOWN_MSG   "Your JSON structure belongs in a modern-art museum, not in this parser."

Generic diagnostic, also used for unrecognized codes.

Definition at line 76 of file jsonbourne.c.

◆ JSONBOURNE_READ_FLAG_MASK

#define JSONBOURNE_READ_FLAG_MASK
Value:

Derive the accepted bits from named options so flag remaps cannot stale this mask.

Definition at line 86 of file jsonbourne.c.

◆ JSONBOURNE_READ_SUCCESS_MSG

#define JSONBOURNE_READ_SUCCESS_MSG   "JSONbourne found zero errors and is now insufferable at parties."

Message for successful validation.

Definition at line 50 of file jsonbourne.c.

◆ JSONBOURNE_ZERO

#define JSONBOURNE_ZERO   {0}

C11 aggregate zero-initializer without byte-copying object representations.

Definition at line 90 of file jsonbourne.c.

Enumeration Type Documentation

◆ jsonbourne_event

Shared traversal protocol so writing and cloning use identical structural checks.

Enumerator
JSONBOURNE_EVENT_VAL 

Visit a scalar or open a container at the current depth.

JSONBOURNE_EVENT_KEY 

Visit an object key before its child value.

JSONBOURNE_EVENT_ELEM 

Visit an array slot before its child value.

JSONBOURNE_EVENT_END 

Close a container after its declared entries are consumed.

Definition at line 1185 of file jsonbourne.c.

Function Documentation

◆ jsonbourne_acyclic_step()

int jsonbourne_acyclic_step ( const void ** slow,
const void ** fast,
size_t type )
inlinestatic

Advance Floyd's two cursors without allocating a visited-address set.

Parameters
[in,out]slowCursor advanced by one sibling link.
[in,out]fastCursor advanced by two sibling links.
[in]typeEntry layout: object or array.
Returns
1 if no cycle is encountered on this step, 0 if non-NULL cursors meet.
Note
All linked entries must still be accessible; this validates topology, not the validity of arbitrary pointer addresses.

Definition at line 1224 of file jsonbourne.c.

◆ jsonbourne_ascii_span()

size_t jsonbourne_ascii_span ( const unsigned char * src,
size_t len,
unsigned char quote )
inlinestatic

Find bytes that need no string escaping or Unicode decoding.

Parameters
[in]srcAccessible input extent; no padding or alignment is assumed.
[in]lenAvailable bytes.
[in]quoteCurrent string delimiter, which terminates the fast path.
Returns
Prefix length containing printable ASCII other than quote/backslash.

Vector loads require a complete 16-byte block. The scalar tail keeps page-boundary inputs safe; high-bit bytes return to strict UTF-8 validation.

Definition at line 189 of file jsonbourne.c.

◆ jsonbourne_char_is_digit()

int jsonbourne_char_is_digit ( unsigned char chr)
inlinestatic

Recognize the decimal digits permitted by JSON number grammar.

Parameters
[in]chrByte to inspect.
Returns
Nonzero for ASCII 0 through 9, zero otherwise.

Definition at line 289 of file jsonbourne.c.

◆ jsonbourne_char_is_id()

int jsonbourne_char_is_id ( unsigned char chr)
inlinestatic

Classify this reader's relaxed, ASCII-only unquoted-key alphabet.

Parameters
[in]chrByte to inspect.
Returns
Nonzero for letters, digits, underscore or dollar sign.
Note
This convenience alphabet is not a complete ECMAScript IdentifierName implementation; it deliberately does not imply full JSON5 conformance.

Definition at line 298 of file jsonbourne.c.

◆ jsonbourne_char_is_space()

int jsonbourne_char_is_space ( unsigned char chr)
inlinestatic

Recognize only the four JSON whitespace bytes, independently of locale.

Parameters
[in]chrByte to classify.
Returns
Nonzero for space, tab, CR or LF; zero otherwise.

Definition at line 228 of file jsonbourne.c.

◆ jsonbourne_copy_str()

jsonbourne_str * jsonbourne_copy_str ( struct jsonbourne_pool * pool,
const jsonbourne_str * src )
inlinestatic

Validate and duplicate a decoded string instead of borrowing source text.

Parameters
[in,out]poolDestination arena or sizing state.
[in]srcAccessible decoded UTF-8 view.
Returns
Copied record, or NULL during successful counting/on failure; inspect pool->code.
Note
A manually assembled DOM may contain invalid UTF-8 even if parser output cannot, so copying revalidates rather than trusting its provenance.

Definition at line 1721 of file jsonbourne.c.

◆ jsonbourne_copy_visit()

int jsonbourne_copy_visit ( void * ctx,
enum jsonbourne_event event,
const jsonbourne_val * src,
const jsonbourne_str * name,
size_t depth,
size_t idx )
inlinestatic

Build copied records from the same validated events used for writing.

Parameters
[in,out]ctxCopy visitor state and destination arena.
[in]eventWalker event selecting entry setup or value duplication.
[in]srcAccessible source value/container.
[in]nameSource object key for key events, NULL otherwise.
[in]depthSource depth, also indexing destination append frames.
[in]idxSource entry index, unused because destination tails track appends.
Returns
1 when duplication/counting succeeds, 0 on invalid text/number or limits.

Entry events choose the next destination slot before the child-value event fills it. Measurement never dereferences those materialization-only slots.

Definition at line 1761 of file jsonbourne.c.

◆ jsonbourne_hex_to_digit()

int jsonbourne_hex_to_digit ( unsigned char chr)
inlinestatic

Decode an ASCII hexadecimal digit without locale-sensitive conversion.

Parameters
[in]chrByte to inspect.
Returns
Integer 0 through 15, or -1 if the byte is not a hex digit.

Definition at line 274 of file jsonbourne.c.

◆ jsonbourne_is_delimiter()

int jsonbourne_is_delimiter ( const struct jsonbourne_read_ctx * ctx,
size_t pos )
inlinestatic

Verify the token boundary separately from the token's own spelling.

Parameters
[in]ctxInput extent and comment policy.
[in]posCandidate end offset, no greater than ctx->len.
Returns
Nonzero at input end or a permissible token boundary.

Prevents a valid prefix such as true in truex, or 1 in 1abc, from being admitted as a complete scalar value.

Definition at line 745 of file jsonbourne.c.

◆ jsonbourne_next()

const void * jsonbourne_next ( const void * elem,
size_t type )
inlinestatic

Advance either entry type without relying on their layouts being interchangeable.

Parameters
[in]elemAccessible entry, or NULL at list end.
[in]typeObject tag selects object entries; array traversal uses array entries.
Returns
Next entry, or NULL.

Definition at line 1208 of file jsonbourne.c.

◆ jsonbourne_obj_lookup()

const jsonbourne_val * jsonbourne_obj_lookup ( const jsonbourne_val * val,
const char * key,
size_t len,
int unique )
inlinestatic

Share exact-byte member comparison while keeping ambiguity policy explicit.

Parameters
[in]valAccessible object value.
[in]keyDecoded key bytes; NULL only with len zero.
[in]lenKey byte count, including any embedded NULs.
[in]uniqueNonzero scans for exactly one match; zero returns the first.
Returns
Borrowed matching value, or NULL for absent/ambiguous/invalid traversal.
Note
Unique lookup must inspect the whole declared list: a later escaped spelling can decode to the same key as an earlier member.

Definition at line 1950 of file jsonbourne.c.

◆ jsonbourne_overlap()

int jsonbourne_overlap ( const void * first,
size_t first_size,
const void * second,
size_t second_size )
inlinestatic

Compare numeric address distances instead of forming overflowing end pointers.

Parameters
[in]firstFirst extent's base address.
[in]first_sizeFirst extent in bytes.
[in]secondSecond extent's base address.
[in]second_sizeSecond extent in bytes.
Returns
Nonzero when both nonempty extents overlap, zero otherwise.
Note
Integer addresses also avoid relational comparison of unrelated C pointers.

Definition at line 1074 of file jsonbourne.c.

◆ jsonbourne_pool_copy()

int jsonbourne_pool_copy ( struct jsonbourne_pool * pool,
const char * src,
size_t len )
inlinestatic

Account for or copy a byte extent into the text region.

Parameters
[in,out]poolDestination arena or counting state.
[in]srcAccessible source bytes; NULL is permitted only for len zero.
[in]lenExact byte count, independent of embedded NULs.
Returns
1 on success, 0 when reservation fails.
Note
Counting skips source reads; materialization uses a bounded copy loop.

Definition at line 169 of file jsonbourne.c.

◆ jsonbourne_pool_take()

void * jsonbourne_pool_take ( struct jsonbourne_pool * pool,
size_t len,
int is_str )
inlinestatic

Reserve checked space in one arena region or merely account for it.

Parameters
[in,out]poolArena counters, capacities and sticky error state.
[in]lenBytes required, including any caller-supplied terminator space.
[in]is_strNonzero selects text; zero selects typed records.
Returns
Region address, or NULL while measuring/on failure; inspect pool->code to distinguish a successful count from an error.

Subtractions are guarded before use so neither capacity checks nor the combined-region budget can wrap around size_t.

Definition at line 143 of file jsonbourne.c.

◆ jsonbourne_ptr_key_eq()

int jsonbourne_ptr_key_eq ( const jsonbourne_str * name,
const char * token,
size_t len )
inlinestatic

Compare a decoded member name with an RFC 6901 token as escapes are read.

Parameters
[in]nameAccessible decoded key view.
[in]tokenEncoded pointer token without its leading slash.
[in]lenToken extent in bytes.
Returns
1 only for equal decoded bytes and lengths, 0 otherwise.

Streaming ~0/~1 decoding avoids a temporary key allocation and keeps embedded NUL handling tied to lengths rather than string terminators.

Definition at line 2056 of file jsonbourne.c.

◆ jsonbourne_read_ctx_init()

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 )
inlinestatic

Establish cursor/limit invariants before any grammar byte is accessed.

Parameters
[out]ctxFresh context, also safe to report after initialization failure.
[in]srcInput bytes; NULL is valid only with len zero.
[in]lenInput extent in bytes.
[in]flgRequested named options, checked against accepted bits.
[in]limitsOptional caller budgets; NULL selects compiled defaults.
Returns
1 for valid initial state, 0 with an argument/resource error recorded.
Note
PTRDIFF_MAX bounds keep later pointer arithmetic representable; an empty sentinel replaces NULL input so even zero-byte parser paths have a valid base.

Definition at line 989 of file jsonbourne.c.

◆ jsonbourne_read_document()

int jsonbourne_read_document ( struct jsonbourne_read_ctx * ctx,
jsonbourne_val ** root )
inlinestatic

Drive one complete JSON document using explicit container frames.

Parameters
[in,out]ctxInitialized counting or materializing read context.
[out]rootParsed root, or NULL while counting.
Returns
1 only when the root and all trailing trivia consume the full input.

The frame state distinguishes empty closure, post-separator closure and a completed item. Sharing this state machine across both passes prevents the allocator's size prediction from using a different grammar.

Definition at line 876 of file jsonbourne.c.

◆ jsonbourne_read_hex4()

int jsonbourne_read_hex4 ( struct jsonbourne_read_ctx * ctx,
uint32_t * unit )
inlinestatic

Consume the four hexadecimal digits following a Unicode escape marker.

Parameters
[in,out]ctxCursor positioned at the first hex digit.
[out]unitDecoded UTF-16 code unit; undefined as a result on failure.
Returns
1 for four valid digits, 0 with INVALID_ESCAPE otherwise.
Note
A code unit is not necessarily a scalar; the string reader pairs surrogates.

Definition at line 537 of file jsonbourne.c.

◆ jsonbourne_read_locate()

void jsonbourne_read_locate ( struct jsonbourne_read_ctx * ctx,
size_t pos,
size_t * line,
size_t * row )
inlinestatic

Advance a lazy location cursor instead of rescanning each node's prefix.

Parameters
[in,out]ctxMaterializing read state with cached line information.
[in]posRequested input byte offset; must not precede ctx->loc_pos.
[out]lineOne-based line number at pos.
[out]rowZero-based byte column at pos.
Note
Monotonic requests keep total location bookkeeping linear in input size.

Definition at line 468 of file jsonbourne.c.

◆ jsonbourne_read_materialize()

jsonbourne_val * jsonbourne_read_materialize ( struct jsonbourne_read_ctx * ctx,
void * buf,
size_t val_len,
size_t str_len,
jsonbourne_read_err * err )
inlinestatic

Replay a successful counting pass into precisely bounded record/text regions.

Parameters
[in,out]ctxSuccessful measurement state; input/options remain unchanged.
[out]bufAccessible backing allocation, checked for alignment and overlap.
[in]val_lenMeasured record-region bytes.
[in]str_lenMeasured text-region bytes, including terminators.
[out]errOptional public read result.
Returns
Root in buf, or NULL on layout/parsing failure.

Resetting cursor, counters and location cache makes this a fresh grammar pass; exact capacities prevent it from writing beyond the measured allocation.

Definition at line 1095 of file jsonbourne.c.

◆ jsonbourne_read_num_token()

int jsonbourne_read_num_token ( const unsigned char * src,
size_t len,
jsonbourne_read_flag flg,
size_t * read_len )
inlinestatic

Recognize a numeric prefix without converting or rounding its value.

Parameters
[in]srcAccessible token candidate.
[in]lenCandidate extent, which may also include following input.
[in]flgEnabled numeric spelling extensions.
[out]read_lenConsumed token bytes on success; unchanged on failure.
Returns
1 for a valid numeric prefix, 0 for invalid/incomplete grammar.
Note
The caller must check the following delimiter or require read_len == len; otherwise a valid prefix could conceal an invalid suffix.

Definition at line 349 of file jsonbourne.c.

◆ jsonbourne_read_report()

void jsonbourne_read_report ( const struct jsonbourne_read_ctx * ctx,
jsonbourne_read_err * err )
inlinestatic

Normalize parser/arena failure into an optional public diagnostic.

Parameters
[in]ctxContext after initialization or parsing, successful or failed.
[out]errDestination, or NULL to skip diagnostic work.

Coordinates are scanned only when an error must be reported, so reads without TRACK_LOCATION do not maintain line metadata on their successful path.

Definition at line 1020 of file jsonbourne.c.

◆ jsonbourne_read_str()

int jsonbourne_read_str ( struct jsonbourne_read_ctx * ctx,
int key,
jsonbourne_str ** out )
inlinestatic

Decode one quoted string or enabled unquoted key through the same two passes.

Parameters
[in,out]ctxCursor at the string/key and arena state.
[in]keyNonzero permits the unquoted-key path when its option is enabled.
[out]outString record, or NULL on a successful counting pass.
Returns
1 for a complete decoded string, 0 with parser/arena failure recorded.

Escape decoding and raw UTF-8 validation converge on the same decoded byte budget. A separate trailing NUL is stored without counting it in len.

Definition at line 595 of file jsonbourne.c.

◆ jsonbourne_read_str_bytes()

int jsonbourne_read_str_bytes ( struct jsonbourne_read_ctx * ctx,
size_t start,
const char * bytes,
size_t count )
inlinestatic

Enforce a decoded-string budget before reserving any more text bytes.

Parameters
[in,out]ctxParser and arena state.
[in]startText counter at the beginning of the current decoded string.
[in]bytesDecoded source bytes to append when materializing.
[in]countNumber of bytes, excluding any final terminator.
Returns
1 if appended/counted, 0 for a string or arena limit failure.
Note
The budget follows decoded size, so escapes cannot bypass it.

Definition at line 522 of file jsonbourne.c.

◆ jsonbourne_read_utf8_encode()

int jsonbourne_read_utf8_encode ( struct jsonbourne_read_ctx * ctx,
size_t start,
uint32_t codepoint )
inlinestatic

Encode a validated Unicode scalar into the decoded text arena.

Parameters
[in,out]ctxParser/arena and decoded-string budget.
[in]startCurrent string's initial text counter.
[in]codepointScalar already checked for surrogate/range validity.
Returns
1 if its UTF-8 bytes fit, 0 on an arena/string limit.
Precondition
codepoint is at most U+10FFFF and is not a surrogate code point.

Definition at line 560 of file jsonbourne.c.

◆ jsonbourne_read_val()

int jsonbourne_read_val ( struct jsonbourne_read_ctx * ctx,
jsonbourne_val ** out,
struct jsonbourne_read_frame * stack,
size_t * depth,
int is_global )
inlinestatic

Consume a scalar or push a new container without a recursive call.

Parameters
[in,out]ctxRead cursor, budgets and arena.
[out]outResult record, or NULL while counting.
[in,out]stackFixed storage for open containers.
[in,out]depthNumber of active frames; checked before every push.
[in]is_globalNonzero requests a brace-less object at the current cursor.
Returns
1 for a scalar/opened container, 0 for grammar or resource failure.
Note
Containers are completed by jsonbourne_read_document(), allowing nesting to consume bounded frame storage rather than the C call stack.

Definition at line 765 of file jsonbourne.c.

◆ jsonbourne_set_read_error()

int jsonbourne_set_read_error ( struct jsonbourne_read_ctx * ctx,
jsonbourne_read_code code )
inlinestatic

Preserve the first grammar failure while supporting short-circuit returns.

Parameters
[in,out]ctxRead context whose code may still indicate success.
[in]codeFailure to record if no earlier grammar error exists.
Returns
Always zero, allowing direct use in a failing parser expression.

Definition at line 453 of file jsonbourne.c.

◆ jsonbourne_skip_trivia()

int jsonbourne_skip_trivia ( struct jsonbourne_read_ctx * ctx)
inlinestatic

Consume whitespace and enabled comments without swallowing grammar bytes.

Parameters
[in,out]ctxInput cursor and enabled syntax options.
Returns
1 at the next significant byte/end, 0 for an unterminated block comment.
Note
A failing block comment restores its opening offset so diagnostics point at the construct that needs repair rather than merely at end of input.

Definition at line 487 of file jsonbourne.c.

◆ jsonbourne_space_span()

size_t jsonbourne_space_span ( const unsigned char * src,
size_t len )
inlinestatic

Skip a bounded run of JSON whitespace with the available SIMD baseline.

Parameters
[in]srcAccessible input extent without padding requirements.
[in]lenBytes available for inspection.
Returns
Whitespace prefix length, never greater than len.
Note
The first non-whitespace byte is left for the grammar, including UTF-8.

Definition at line 239 of file jsonbourne.c.

◆ jsonbourne_utf8_len()

size_t jsonbourne_utf8_len ( const unsigned char * src,
size_t len )
inlinestatic

Validate exactly one UTF-8 scalar without reading beyond the extent.

Parameters
[in]srcFirst byte of a possible UTF-8 sequence.
[in]lenAvailable bytes, possibly fewer than a complete sequence.
Returns
Sequence length 1 through 4, or zero for an invalid/truncated sequence.

Lead-specific second-byte bounds reject overlong encodings, UTF-16 surrogate code points and values above U+10FFFF, not just bad continuation bits.

Definition at line 311 of file jsonbourne.c.

◆ jsonbourne_walk()

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 )
inlinestatic

Validate/traverse an accessible DOM with a fixed explicit stack.

Parameters
[in]valRoot value to inspect.
[in]visitEvent sink receiving context, event, value, optional key, depth and entry index; returning zero aborts traversal.
[in,out]ctxOpaque event-sink state.
Returns
1 for a complete accepted traversal, 0 for malformed structure, nesting exhaustion or a rejecting visitor.

Exact list lengths and Floyd cursors detect malformed sibling chains. Cycles through value/container pointers cannot grow without bound because every nested container also consumes one checked frame.

Definition at line 1242 of file jsonbourne.c.

◆ jsonbourne_write_buffer()

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 )
inlinestatic

Protect a short caller buffer by measuring before any output write.

Parameters
[in]valAccessible, stable DOM root.
[in]prettyNonzero enables whitespace formatting.
[in]indentOptional indentation string.
[in]newlineOptional line-separator string.
[out]bufDestination, or NULL for a size probe.
[in]capDestination capacity in bytes.
[out]out_lenOptional required NUL-inclusive size after successful preflight.
Returns
1 for complete output, 0 for failed preflight or insufficient storage.

Definition at line 1667 of file jsonbourne.c.

◆ jsonbourne_write_bytes()

int jsonbourne_write_bytes ( struct jsonbourne_write_ctx * out,
const char * bytes,
size_t len )
inlinestatic

Reserve output bytes before optionally copying them.

Parameters
[in,out]outCounting/writing sink with len at most cap.
[in]bytesAccessible source extent when writing.
[in]lenByte count, not inferred from string termination.
Returns
1 if bytes fit, 0 without an out-of-bounds write otherwise.
Note
Capacity subtraction is checked before addition, including size-only passes.

Definition at line 1334 of file jsonbourne.c.

◆ jsonbourne_write_ctx_init()

int jsonbourne_write_ctx_init ( struct jsonbourne_write_ctx * out,
int pretty,
const char * indent,
const char * newline )
inlinestatic

Initialize a counting sink and validate pretty-print whitespace.

Parameters
[out]outFresh writer state with a pointer-safe maximum count.
[in]prettyNonzero enables formatting validation/output.
[in]indentWhitespace string, or NULL for two spaces.
[in]newlineWhitespace string, or NULL for LF.
Returns
1 for usable options, 0 for non-JSON whitespace in pretty formatting.
Note
Arbitrary formatting bytes would turn an otherwise valid DOM into invalid JSON, so they are rejected before output storage is allocated or touched.

Definition at line 1566 of file jsonbourne.c.

◆ jsonbourne_write_document()

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 )
inlinestatic

Measure, allocate once and replay the same traversal into exact output storage.

Parameters
[in]valAccessible DOM, stable throughout both passes and callbacks.
[in]prettyNonzero selects pretty formatting.
[in]indentOptional indentation string.
[in]newlineOptional line-separator string.
[in]alc_fnOptional allocation callback; NULL selects malloc.
[in]free_fnOptional failure release; NULL selects free.
[in]alc_ctxOpaque callback context.
[out]out_lenOptional NUL-inclusive size, zero unless output succeeds.
Returns
Caller-owned JSON text, or NULL on validation, sizing or allocation failure.
Note
The final size comparison detects size drift; it does not permit callers or allocators to mutate the DOM between passes.

Definition at line 1602 of file jsonbourne.c.

◆ jsonbourne_write_hex_num()

int jsonbourne_write_hex_num ( struct jsonbourne_write_ctx * out,
const char * src,
size_t len )
inlinestatic

Convert hexadecimal magnitude text exactly using bounded decimal digits.

Parameters
[in,out]outMeasuring/writing output sink.
[in]srcValidated hex digits without sign or 0x prefix.
[in]lenHex digit count, including any leading zeroes.
Returns
1 for emitted decimal text, 0 on significant-digit/capacity limits.

Each input digit updates a little-endian decimal accumulator by multiply-by-16 plus carry. This avoids floating-point loss and an unbounded big-integer dependency; two decimal slots per hex digit are a conservative bound.

Definition at line 1410 of file jsonbourne.c.

◆ jsonbourne_write_indent()

int jsonbourne_write_indent ( struct jsonbourne_write_ctx * out,
size_t depth )
inlinestatic

Write a configured line break and one indentation unit per nesting level.

Parameters
[in,out]outOutput sink with already validated formatting strings.
[in]depthNumber of indentation units.
Returns
1 if no formatting is needed or it fits, 0 on capacity exhaustion.
Note
The measuring pass counts the same repeated units, including custom lengths.

Definition at line 1499 of file jsonbourne.c.

◆ jsonbourne_write_num()

int jsonbourne_write_num ( struct jsonbourne_write_ctx * out,
const jsonbourne_num * num )
inlinestatic

Preserve strict numeric text or normalize enabled relaxed spellings.

Parameters
[in,out]outMeasuring/writing output sink.
[in]numAccessible token view whose full extent must form one number.
Returns
1 for valid normalized output that fits, 0 otherwise.

Strict decimals retain every original digit. Relaxed tokens lose a leading plus, gain missing decimal zeroes or use exact hex conversion. The retained nonfinite policy emits zero for NaN and signed DBL_MAX text for infinity.

Definition at line 1454 of file jsonbourne.c.

◆ jsonbourne_write_str()

int jsonbourne_write_str ( struct jsonbourne_write_ctx * out,
const jsonbourne_str * str )
inlinestatic

Emit a UTF-8 string with JSON quoting and exact control-byte escaping.

Parameters
[in,out]outMeasuring/writing output sink.
[in]strAccessible length-aware string view, possibly containing NULs.
Returns
1 for valid text that fits, 0 for invalid UTF-8/arguments or capacity.

Printable ASCII takes the span fast path; all remaining bytes are escaped or validated as complete scalars, never passed through blindly.

Definition at line 1354 of file jsonbourne.c.

◆ jsonbourne_write_visit()

int jsonbourne_write_visit ( void * ctx,
enum jsonbourne_event event,
const jsonbourne_val * val,
const jsonbourne_str * name,
size_t depth,
size_t idx )
inlinestatic

Translate shared walker events into JSON punctuation and scalar text.

Parameters
[in,out]ctxOutput sink cast from the opaque visitor context.
[in]eventValue, key, element or container-end event.
[in]valAccessible current value/container.
[in]nameObject key for key events, NULL otherwise.
[in]depthCurrent nesting/formatting level.
[in]idxEntry index or completed count, used to avoid trailing separators.
Returns
1 if output remains valid and fits, 0 to stop traversal.

Definition at line 1521 of file jsonbourne.c.