Files
ziran/std/json_document.zi
T
waozi 4838ce9b2f Improve runtimes, add an experimental direct backend, and prune Ziran tests
Prepare short portable helpers and scalar record reads, improve JSON SIMD scanning, expose one-line execution, and publish qualified Alpha benchmark artifacts. Add the experimental verified lowered execution, serialization and Linux x86-64 backend with source maps.

Physically remove 263 redundant test entry points and unused helpers, migrate retained helpers to Ziran, and execute the full retained suite without sharding. Allow ignored backup state for the managed physical Alpha workflow.

Local validation: all 268 retained tests passed across the full run and corrected targeted reruns; bootstrap matches. Current assembly verifier, x86-64, executor and serializer tests passed. Website examples and all 4661 local links passed. Six Alpha JSON/text workloads retain verified artifacts, raw samples and explicit unsupported Wasm diagnostics. The mobile sub-500 ns target remains pending.
2026-11-11 18:46:34 -03:00

904 lines
36 KiB
Ziran

// JSON documents read into a tree that programs query, change and write
// back. Nodes live in the document's vector and are named by their index;
// -1 names no node, and every query accepts it.
//
// document: JsonDocument
// if !JsonRead(*document, text) { print("%\n", document.error) }
// levels := JsonMember(*document, document.root, "levels")
// level := JsonFirst(*document, levels)
// while level >= 0 {
// number, ok := JsonInteger(*document, JsonMember(*document, level, "number"))
// level = JsonNext(*document, level)
// }
// JsonSet(*document, document.root, "count", JsonNewInteger(*document, 3))
// saved := JsonWrite(*document, document.root, JsonPythonStyle(1))
//
// JsonWrite lays text out as Python's json.dumps does for the same style:
// separators, indentation, empty containers, ensure_ascii escapes and
// sort_keys. Numbers keep the text they were read with unless python_floats
// is enabled in the style. Strings without
// escapes are views of the text that was read, so keep that text alive
// while the document is used. Objects keep every member in order; a
// repeated name is answered by its last member, as Python's dict reads it.
using Vectors :: #import "vec"
FloatText :: #import "float_text"
JsonBytes :: #import "json_bytes"
JsonWriter :: #import "std/json_quote"
JsonKind :: enum u8 { Missing :: 0; Null :: 1; False :: 2; True :: 3; Number :: 4; String :: 5; Array :: 6; Object :: 7; }
JsonEraser :: #type (context: *void, bytes: []u8) -> void;
JsonNoErase :: (context: *void, bytes: []u8) { unused context; unused bytes }
JsonNode :: struct {
kind: JsonKind
// A number's text, or a string's decoded value.
text: string
// Escaped/generated/deep-copied bytes are owned, never a self-referential
// string view. Use the public accessors for either representation.
owned_text: Vec(u8)
// The member name, when the node belongs to an object.
key: string
owned_key: Vec(u8)
first: s32
last: s32
next: s32
count: s32
}
JsonDocument :: struct {
nodes: Vec(JsonNode)
root: s32
// Why the last JsonRead failed, and the byte offset where it did.
error: string
error_at: s64
erase: JsonEraser
erase_context: *void
}
JsonStyle :: struct {
// Spaces per level; below zero writes everything on one line.
indent: s32
item_separator: string
key_separator: string
// Writes every non-ASCII character as \uXXXX, as ensure_ascii does.
ascii: bool
sort_keys: bool
// Canonicalize decimal/exponent tokens as Python binary64 JSON floats.
// Integer tokens (including arbitrarily long ones) always keep their text.
python_floats: bool
}
// The style of Python's json.dumps(value, indent=INDENT); a negative INDENT
// stands for indent=None. ASCII escapes are on, as ensure_ascii's default.
JsonPythonStyle :: (indent: s32 = -1, ascii: bool = true, sort_keys: bool = false, python_floats: bool = false) -> JsonStyle {
style: JsonStyle
style.indent = indent
style.item_separator = ifx indent < 0 then ", " else ","
style.key_separator = ": "
style.ascii = ascii
style.sort_keys = sort_keys
style.python_floats = python_floats
return style
}
// One line with separators=(',', ':').
JsonCompactStyle :: (ascii: bool = true, sort_keys: bool = false) -> JsonStyle {
style := JsonPythonStyle(-1, ascii, sort_keys)
style.item_separator = ","
style.key_separator = ":"
return style
}
#scope_file
MAX_DEPTH :: 512;
Reader :: struct {
text: string
at: s64
error: string
}
Add :: (document: *JsonDocument, kind: JsonKind, text: string) -> s32 {
at := document.nodes.count
if at >= 2147483647 || !VecResize(document.nodes, at + 1) {
document.error = "out of memory reading JSON"
return -1
}
document.nodes[at].kind = kind
document.nodes[at].text = text
document.nodes[at].first = -1
document.nodes[at].last = -1
document.nodes[at].next = -1
return cast(s32)at
}
EraseBuffer :: (document: *JsonDocument, bytes: *Vec(u8)) {
owned: Vec(u8)
VecSwap(owned, <<bytes)
if document.erase != null && owned.count > 0 {
document.erase(document.erase_context, VecSlice(owned, 0, owned.count))
}
}
CopyBytesInto :: (document: *JsonDocument, node: s32, key: bool, output: *Vec(u8)) -> bool {
if output == null || node < 0 || node >= document.nodes.count { return false }
if output == *document.nodes[node].owned_text || output == *document.nodes[node].owned_key { return false }
count := ifx key then document.nodes[node].owned_key.count else document.nodes[node].owned_text.count
length := ifx count > 0 then count else (ifx key then document.nodes[node].key.count else document.nodes[node].text.count)
if length > 9223372036854775807 - output.count || !VecReserve(<<output, output.count + length) { return false }
if count > 0 {
for at: 0..count - 1 {
byte := ifx key then document.nodes[node].owned_key[at] else document.nodes[node].owned_text[at]
if !VecPush(<<output, byte) { return false }
}
return true
}
return BuilderAppend(<<output, ifx key then document.nodes[node].key else document.nodes[node].text)
}
EqualText :: (document: *JsonDocument, node: s32, key: bool, value: string) -> bool {
count := ifx key then document.nodes[node].owned_key.count else document.nodes[node].owned_text.count
if count == 0 { return (ifx key then document.nodes[node].key else document.nodes[node].text) == value }
if count != value.count { return false }
for at: 0..count - 1 {
byte := ifx key then document.nodes[node].owned_key[at] else document.nodes[node].owned_text[at]
if byte != value[at] { return false }
}
return true
}
Link :: (document: *JsonDocument, parent: s32, child: s32) {
document.nodes[child].next = -1
if document.nodes[parent].last < 0 {
document.nodes[parent].first = child
} else {
document.nodes[document.nodes[parent].last].next = child
}
document.nodes[parent].last = child
document.nodes[parent].count += 1
}
Skip :: (reader: *Reader) {
while reader.at < reader.text.count {
byte := reader.text[reader.at]
if byte != 32 && byte != 9 && byte != 10 && byte != 13 { return }
reader.at += 1
}
}
Fail :: (reader: *Reader, message: string) -> s32 {
if reader.error.count == 0 { reader.error = message }
return -1
}
Digit :: (byte: u8) -> bool { return byte >= #char "0" && byte <= #char "9" }
HexValue :: (byte: u8) -> s32 {
if byte >= #char "0" && byte <= #char "9" { return cast(s32)(byte - #char "0") }
if byte >= #char "a" && byte <= #char "f" { return cast(s32)(byte - #char "a") + 10 }
if byte >= #char "A" && byte <= #char "F" { return cast(s32)(byte - #char "A") + 10 }
return -1
}
Hex4 :: (reader: *Reader, at: s64) -> s32 {
if at + 4 > reader.text.count { return -1 }
value: s32 = 0
index: s64 = 0
while index < 4 {
digit := HexValue(reader.text[at + index])
if digit < 0 { return -1 }
value = value * 16 + digit
index += 1
}
return value
}
PutCodePoint :: (bytes: *Vec(u8), point: s32) -> bool {
if point < 128 {
return VecPush(<<bytes, cast(u8)point)
} else if point < 2048 {
return VecPush(<<bytes, cast(u8)(192 | (point >> 6))) &&
VecPush(<<bytes, cast(u8)(128 | (point & 63)))
} else if point < 65536 {
return VecPush(<<bytes, cast(u8)(224 | (point >> 12))) &&
VecPush(<<bytes, cast(u8)(128 | ((point >> 6) & 63))) &&
VecPush(<<bytes, cast(u8)(128 | (point & 63)))
} else {
return VecPush(<<bytes, cast(u8)(240 | (point >> 18))) &&
VecPush(<<bytes, cast(u8)(128 | ((point >> 12) & 63))) &&
VecPush(<<bytes, cast(u8)(128 | ((point >> 6) & 63))) &&
VecPush(<<bytes, cast(u8)(128 | (point & 63)))
}
}
// Reads the string starting at the opening quote; the text is a view when
// it has no escapes.
ReadString :: (reader: *Reader, text: string, ok: *bool, bytes: *Vec(u8)) -> string {
<<ok = false
start := reader.at + 1
at := JsonBytes.JsonStringRunEnd(reader.text, start)
plain := true
while at < reader.text.count {
byte := reader.text[at]
if byte == #char "\"" { break }
if byte < 32 { Fail(reader, "control character in a string"); reader.at = at; return "" }
if byte == #char "\\" { plain = false; at += 1 }
at = JsonBytes.JsonStringRunEnd(reader.text, at + 1)
}
if at >= reader.text.count { Fail(reader, "unterminated string"); reader.at = at; return "" }
if plain {
reader.at = at + 1
<<ok = true
return text[start:at]
}
// Reserve before the first decoded private byte exists. Growth must not
// leave old plaintext allocations outside the registered eraser's reach.
if !VecReserve(<<bytes, at - start) { Fail(reader, "out of memory reading JSON"); return "" }
at = start
while reader.text[at] != #char "\"" {
byte := reader.text[at]
if byte != #char "\\" {
if !VecPush(<<bytes, byte) { Fail(reader, "out of memory reading JSON"); return "" }
at += 1
continue
}
escape := reader.text[at + 1]
at += 2
saved := true
if escape == #char "\"" || escape == #char "\\" || escape == #char "/" { saved = VecPush(<<bytes, escape) }
else if escape == #char "b" { saved = VecPush(<<bytes, cast(u8)8) }
else if escape == #char "f" { saved = VecPush(<<bytes, cast(u8)12) }
else if escape == #char "n" { saved = VecPush(<<bytes, cast(u8)10) }
else if escape == #char "r" { saved = VecPush(<<bytes, cast(u8)13) }
else if escape == #char "t" { saved = VecPush(<<bytes, cast(u8)9) }
else if escape == #char "u" {
point := Hex4(reader, at)
if point < 0 { Fail(reader, "invalid \\u escape"); reader.at = at; return "" }
at += 4
// A high surrogate followed by a low one is one character; a
// lone surrogate keeps its own code, as Python's str does.
if point >= 55296 && point < 56320 && at + 6 <= reader.text.count &&
reader.text[at] == #char "\\" && reader.text[at + 1] == #char "u" {
low := Hex4(reader, at + 2)
if low >= 56320 && low < 57344 {
point = 65536 + ((point - 55296) << 10) + (low - 56320)
at += 6
}
}
saved = PutCodePoint(bytes, point)
} else {
Fail(reader, "invalid escape")
reader.at = at - 1
return ""
}
if !saved { Fail(reader, "out of memory reading JSON"); return "" }
}
reader.at = at + 1
<<ok = true
return ""
}
ReadNumber :: (reader: *Reader, document: *JsonDocument) -> s32 {
text := reader.text
start := reader.at
at := start
if at < text.count && text[at] == #char "-" { at += 1 }
if at >= text.count || !Digit(text[at]) { return Fail(reader, "invalid number") }
if text[at] == #char "0" { at += 1 } else { while at < text.count && Digit(text[at]) { at += 1 } }
if at < text.count && text[at] == #char "." {
at += 1
if at >= text.count || !Digit(text[at]) { reader.at = at; return Fail(reader, "invalid number") }
while at < text.count && Digit(text[at]) { at += 1 }
}
if at < text.count && (text[at] == #char "e" || text[at] == #char "E") {
at += 1
if at < text.count && (text[at] == #char "+" || text[at] == #char "-") { at += 1 }
if at >= text.count || !Digit(text[at]) { reader.at = at; return Fail(reader, "invalid number") }
while at < text.count && Digit(text[at]) { at += 1 }
}
reader.at = at
return Add(document, .Number, text[start:at])
}
Literal :: (reader: *Reader, word: string) -> bool {
if reader.at + word.count > reader.text.count { return false }
if reader.text[reader.at:reader.at + word.count] != word { return false }
reader.at += word.count
return true
}
ReadValue :: (reader: *Reader, document: *JsonDocument, depth: s32) -> s32 {
Skip(reader)
if reader.at >= reader.text.count { return Fail(reader, "expected a value") }
if depth > MAX_DEPTH { return Fail(reader, "too deeply nested") }
byte := reader.text[reader.at]
if byte == #char "{" {
object := Add(document, .Object, "")
if object < 0 { return Fail(reader, document.error) }
reader.at += 1
Skip(reader)
if reader.at < reader.text.count && reader.text[reader.at] == #char "}" { reader.at += 1; return object }
while true {
Skip(reader)
if reader.at >= reader.text.count || reader.text[reader.at] != #char "\"" { return Fail(reader, "expected a member name") }
ok := false
key_bytes: Vec(u8)
defer { EraseBuffer(document, *key_bytes) }
key := ReadString(reader, reader.text, *ok, *key_bytes)
if !ok { return -1 }
Skip(reader)
if reader.at >= reader.text.count || reader.text[reader.at] != #char ":" { return Fail(reader, "expected ':'") }
reader.at += 1
value := ReadValue(reader, document, depth + 1)
if value < 0 { return -1 }
document.nodes[value].key = key
VecSwap(document.nodes[value].owned_key, key_bytes)
Link(document, object, value)
Skip(reader)
if reader.at >= reader.text.count { return Fail(reader, "unterminated object") }
if reader.text[reader.at] == #char "," { reader.at += 1; continue }
if reader.text[reader.at] == #char "}" { reader.at += 1; return object }
return Fail(reader, "expected ',' or '}'")
}
}
if byte == #char "[" {
array := Add(document, .Array, "")
if array < 0 { return Fail(reader, document.error) }
reader.at += 1
Skip(reader)
if reader.at < reader.text.count && reader.text[reader.at] == #char "]" { reader.at += 1; return array }
while true {
value := ReadValue(reader, document, depth + 1)
if value < 0 { return -1 }
Link(document, array, value)
Skip(reader)
if reader.at >= reader.text.count { return Fail(reader, "unterminated array") }
if reader.text[reader.at] == #char "," { reader.at += 1; continue }
if reader.text[reader.at] == #char "]" { reader.at += 1; return array }
return Fail(reader, "expected ',' or ']'")
}
}
if byte == #char "\"" {
ok := false
bytes: Vec(u8)
defer { EraseBuffer(document, *bytes) }
text := ReadString(reader, reader.text, *ok, *bytes)
if !ok { return -1 }
node := Add(document, .String, text)
if node < 0 { return Fail(reader, document.error) }
VecSwap(document.nodes[node].owned_text, bytes)
return node
}
if byte == #char "-" || Digit(byte) { return ReadNumber(reader, document) }
if Literal(reader, "true") { return Add(document, .True, "") }
if Literal(reader, "false") { return Add(document, .False, "") }
if Literal(reader, "null") { return Add(document, .Null, "") }
return Fail(reader, "expected a value")
}
// A string the caller owns: the borrow checker cannot follow text kept in
// the node vector back to its storage.
Copy :: (text: string) -> string {
bytes: Vec(u8)
BuilderAppend(bytes, text)
return BuilderFinish(bytes)
}
#scope_export
// Register an optional owner-supplied eraser before building/copying private
// text. It receives actual owned bytes, including failed partial strings.
// Call JsonReset before the document leaves scope; borrowed source bytes stay
// the caller's responsibility. No cryptographic dependency lives in JSON.
JsonSetEraser :: (document: *JsonDocument, erase: JsonEraser, context: *void = null) {
document.erase = erase
document.erase_context = context
}
JsonReset :: (document: *JsonDocument) {
if document == null { return }
for at: 0..document.nodes.count - 1 {
EraseBuffer(document, *document.nodes[at].owned_text)
EraseBuffer(document, *document.nodes[at].owned_key)
}
VecClear(document.nodes)
document.root = -1
document.error = ""
document.error_at = 0
}
// Reads TEXT as the document's root, after clearing it. False, with error
// and error_at set, when TEXT is not one complete JSON value.
JsonRead :: (document: *JsonDocument, text: string, erase: JsonEraser = JsonNoErase,
erase_context: *void = null) -> bool {
if document == null { return false }
JsonReset(document)
JsonSetEraser(document, erase, erase_context)
reader: Reader
reader.text = text
root := ReadValue(*reader, document, 0)
if root >= 0 {
Skip(*reader)
if reader.at < text.count { root = Fail(*reader, "extra data after the value") }
}
if root < 0 {
JsonReset(document)
document.error = reader.error
if document.error == "" { document.error = "out of memory reading JSON" }
document.error_at = reader.at
return false
}
document.root = root
return true
}
JsonKindOf :: (document: *JsonDocument, node: s32) -> JsonKind {
if node < 0 || node >= document.nodes.count { return .Missing }
return document.nodes[node].kind
}
// The number of elements or members.
JsonCount :: (document: *JsonDocument, node: s32) -> s32 {
if node < 0 || node >= document.nodes.count { return 0 }
return document.nodes[node].count
}
// The first element or member, then each next one, then -1.
JsonFirst :: (document: *JsonDocument, node: s32) -> s32 {
if node < 0 || node >= document.nodes.count { return -1 }
return document.nodes[node].first
}
JsonNext :: (document: *JsonDocument, node: s32) -> s32 {
if node < 0 || node >= document.nodes.count { return -1 }
return document.nodes[node].next
}
// A member's name.
JsonKey :: (document: *JsonDocument, node: s32) -> Text {
if node < 0 || node >= document.nodes.count { return .{} }
bytes: Vec(u8)
if !CopyBytesInto(document, node, true, *bytes) { EraseBuffer(document, *bytes); return .{} }
return BuilderFinish(bytes)
}
JsonKeyInto :: (document: *JsonDocument, node: s32, output: *Vec(u8)) -> bool {
return CopyBytesInto(document, node, true, output)
}
// The object's last member named KEY, or -1.
JsonMember :: (document: *JsonDocument, object: s32, key: string) -> s32 {
if JsonKindOf(document, object) != .Object { return -1 }
found: s32 = -1
child := document.nodes[object].first
while child >= 0 {
if EqualText(document, child, true, key) { found = child }
child = document.nodes[child].next
}
return found
}
// The array's element at INDEX, or -1.
JsonElement :: (document: *JsonDocument, array: s32, index: s32) -> s32 {
if JsonKindOf(document, array) != .Array || index < 0 { return -1 }
child := document.nodes[array].first
at: s32 = 0
while child >= 0 && at < index {
child = document.nodes[child].next
at += 1
}
return child
}
// A string's value; "" for anything else.
JsonString :: (document: *JsonDocument, node: s32) -> Text {
if JsonKindOf(document, node) != .String { return .{} }
bytes: Vec(u8)
if !CopyBytesInto(document, node, false, *bytes) { EraseBuffer(document, *bytes); return .{} }
return BuilderFinish(bytes)
}
JsonStringInto :: (document: *JsonDocument, node: s32, output: *Vec(u8)) -> bool {
return JsonKindOf(document, node) == .String && CopyBytesInto(document, node, false, output)
}
// Whether NODE is the string VALUE, without copying it.
JsonIs :: (document: *JsonDocument, node: s32, value: string) -> bool {
if JsonKindOf(document, node) != .String { return false }
return EqualText(document, node, false, value)
}
// A number's text as written; "" for anything else.
JsonNumberText :: (document: *JsonDocument, node: s32) -> Text {
if JsonKindOf(document, node) != .Number { return .{} }
bytes: Vec(u8)
if !CopyBytesInto(document, node, false, *bytes) { EraseBuffer(document, *bytes); return .{} }
return BuilderFinish(bytes)
}
JsonNumberTextInto :: (document: *JsonDocument, node: s32, output: *Vec(u8)) -> bool {
return JsonKindOf(document, node) == .Number && CopyBytesInto(document, node, false, output)
}
// A whole number in the signed 64-bit range, without a fraction or exponent.
// Returns false for overflow; the document retains the original number text.
JsonInteger :: (document: *JsonDocument, node: s32) -> (value: s64, ok: bool) {
if JsonKindOf(document, node) != .Number { return 0, false }
bytes: Vec(u8)
defer { EraseBuffer(document, *bytes) }
if !CopyBytesInto(document, node, false, *bytes) { return 0, false }
text := TextView(VecSlice(bytes, 0, bytes.count))
if text.count == 0 { return 0, false }
negative := text[0] == #char "-"
at: s64 = ifx negative then 1 else 0
if at == text.count { return 0, false }
// Accumulate negatively so the minimum s64 never needs to be negated.
value: s64 = 0
while at < text.count {
if !Digit(text[at]) { return 0, false }
digit := cast(s64)(text[at] - #char "0")
if value < -922337203685477580 ||
(value == -922337203685477580 && digit > (ifx negative then 8 else 7)) { return 0, false }
value = value * 10 - digit
at += 1
}
return ifx negative then value else -value, true
}
JsonBool :: (document: *JsonDocument, node: s32) -> (value: bool, ok: bool) {
kind := JsonKindOf(document, node)
return kind == .True, kind == .True || kind == .False
}
JsonNewNull :: (document: *JsonDocument) -> s32 { return Add(document, .Null, "") }
JsonNewBool :: (document: *JsonDocument, value: bool) -> s32 {
return Add(document, ifx value then JsonKind.True else JsonKind.False, "")
}
JsonNewInteger :: (document: *JsonDocument, value: s64) -> s32 {
digits: [24]u8
at: s64 = 24
magnitude: u64 = ifx value < 0 then cast(u64)(-(value + 1)) + 1 else cast(u64)value
while true {
at -= 1
digits[at] = cast(u8)(48 + cast(s32)(magnitude % 10))
magnitude = magnitude / 10
if magnitude == 0 { break }
}
if value < 0 { at -= 1; digits[at] = #char "-" }
text: Vec(u8)
defer { EraseBuffer(document, *text) }
if !VecReserve(text, 24) { document.error = "out of memory creating JSON integer"; return -1 }
while at < 24 {
if !VecPush(text, digits[at]) { document.error = "out of memory creating JSON integer"; return -1 }
at += 1
}
node := Add(document, .Number, "")
if node >= 0 { VecSwap(document.nodes[node].owned_text, text) }
return node
}
// A number written as TEXT, which must be a valid JSON number.
JsonNewNumber :: (document: *JsonDocument, text: string) -> s32 { return Add(document, .Number, text) }
JsonNewString :: (document: *JsonDocument, value: string) -> s32 { return Add(document, .String, value) }
// Own VALUE when the caller's string storage will end before this document.
// JsonNewString above deliberately retains its borrowed-input contract.
JsonNewStringCopy :: (document: *JsonDocument, value: string) -> s32 {
bytes: Vec(u8)
defer { EraseBuffer(document, *bytes) }
if !VecReserve(bytes, value.count) || !BuilderAppend(bytes, value) {
document.error = "out of memory copying JSON string"
return -1
}
node := Add(document, .String, "")
if node >= 0 { VecSwap(document.nodes[node].owned_text, bytes) }
return node
}
JsonNewArray :: (document: *JsonDocument) -> s32 { return Add(document, .Array, "") }
JsonNewObject :: (document: *JsonDocument) -> s32 { return Add(document, .Object, "") }
// Adds CHILD, a node not yet in any container, to the end of ARRAY.
JsonAppend :: (document: *JsonDocument, array: s32, child: s32) -> bool {
if JsonKindOf(document, array) != .Array || JsonKindOf(document, child) == .Missing { return false }
document.nodes[child].key = ""
EraseBuffer(document, *document.nodes[child].owned_key)
Link(document, array, child)
return true
}
// Sets OBJECT's member KEY to CHILD, a node not yet in any container: a
// present member is replaced where it stands, as a Python dict keeps its
// place, and a new one goes last.
JsonSet :: (document: *JsonDocument, object: s32, key: string, child: s32) -> bool {
if JsonKindOf(document, object) != .Object || JsonKindOf(document, child) == .Missing { return false }
document.nodes[child].key = key
EraseBuffer(document, *document.nodes[child].owned_key)
previous: s32 = -1
at := document.nodes[object].first
while at >= 0 {
if EqualText(document, at, true, key) {
document.nodes[child].next = document.nodes[at].next
if previous < 0 { document.nodes[object].first = child } else { document.nodes[previous].next = child }
if document.nodes[object].last == at { document.nodes[object].last = child }
// Later members with the same name go, as a dict holds one.
Unlink(document, object, key, child)
return true
}
previous = at
at = document.nodes[at].next
}
Link(document, object, child)
return true
}
// Like JsonSet, with a document-owned copy of KEY. Use this when the caller's
// key storage will be released before the document is written.
JsonSetCopy :: (document: *JsonDocument, object: s32, key: string, child: s32) -> bool {
if JsonKindOf(document, object) != .Object || JsonKindOf(document, child) == .Missing { return false }
bytes: Vec(u8)
defer { EraseBuffer(document, *bytes) }
if !VecReserve(bytes, key.count) || !BuilderAppend(bytes, key) { document.error = "out of memory copying JSON key"; return false }
if !JsonSet(document, object, key, child) { return false }
document.nodes[child].key = ""
VecSwap(document.nodes[child].owned_key, bytes)
return true
}
#scope_file
// Removes every member named KEY after KEEP.
Unlink :: (document: *JsonDocument, object: s32, key: string, keep: s32) {
previous := keep
at := document.nodes[keep].next
while at >= 0 {
next := document.nodes[at].next
if EqualText(document, at, true, key) {
document.nodes[previous].next = next
if document.nodes[object].last == at { document.nodes[object].last = previous }
document.nodes[object].count -= 1
} else {
previous = at
}
at = next
}
}
#scope_export
// Removes every member named KEY; false when there was none.
JsonRemove :: (document: *JsonDocument, object: s32, key: string) -> bool {
if JsonKindOf(document, object) != .Object { return false }
removed := false
previous: s32 = -1
at := document.nodes[object].first
while at >= 0 {
next := document.nodes[at].next
if EqualText(document, at, true, key) {
if previous < 0 { document.nodes[object].first = next } else { document.nodes[previous].next = next }
if document.nodes[object].last == at { document.nodes[object].last = previous }
document.nodes[object].count -= 1
removed = true
} else {
previous = at
}
at = next
}
return removed
}
// Empties an array or object.
JsonClear :: (document: *JsonDocument, node: s32) {
kind := JsonKindOf(document, node)
if kind != .Array && kind != .Object { return }
document.nodes[node].first = -1
document.nodes[node].last = -1
document.nodes[node].count = 0
}
// A deep copy of SOURCE's NODE as a new node of TARGET, which may be the
// same document; returns it, or -1 for a missing node.
JsonCopy :: (target: *JsonDocument, source: *JsonDocument, node: s32) -> s32 {
kind := JsonKindOf(source, node)
if kind == .Missing { return -1 }
copy := Add(target, kind, "")
if copy < 0 { return -1 }
bytes: Vec(u8)
defer { EraseBuffer(target, *bytes) }
if !CopyBytesInto(source, node, false, *bytes) { target.error = "out of memory copying JSON"; return -1 }
VecSwap(target.nodes[copy].owned_text, bytes)
child := source.nodes[node].first
while child >= 0 {
inner := JsonCopy(target, source, child)
if inner < 0 { return -1 }
if !CopyBytesInto(source, child, true, *bytes) { target.error = "out of memory copying JSON"; return -1 }
VecSwap(target.nodes[inner].owned_key, bytes)
Link(target, copy, inner)
child = source.nodes[child].next
}
return copy
}
#scope_export
// Appends VALUE as a quoted JSON string, escaped as json.dumps escapes it.
JsonQuoteInto :: (output: *Vec(u8), value: string, ascii: bool) -> bool {
return JsonWriter.JsonQuoteInto(output,value,ascii)
}
JsonQuote :: (value: string, ascii: bool = true) -> Text {
return JsonWriter.JsonQuote(value,ascii)
}
#scope_file
ByteAt :: (document: *JsonDocument, node: s32, key: bool, at: s64) -> u8 {
if key {
if document.nodes[node].owned_key.count > 0 { return document.nodes[node].owned_key[at] }
return document.nodes[node].key[at]
}
if document.nodes[node].owned_text.count > 0 { return document.nodes[node].owned_text[at] }
return document.nodes[node].text[at]
}
ByteCount :: (document: *JsonDocument, node: s32, key: bool) -> s64 {
if key {
if document.nodes[node].owned_key.count > 0 { return document.nodes[node].owned_key.count }
return document.nodes[node].key.count
}
if document.nodes[node].owned_text.count > 0 { return document.nodes[node].owned_text.count }
return document.nodes[node].text.count
}
KeyBeforeNodes :: (document: *JsonDocument, left: s32, right: s32) -> bool {
a := ByteCount(document, left, true)
b := ByteCount(document, right, true)
at: s64 = 0
while at < a && at < b {
x := ByteAt(document, left, true, at)
y := ByteAt(document, right, true, at)
if x != y { return x < y }
at += 1
}
return a < b
}
QuoteNode :: (output: *Vec(u8), document: *JsonDocument, node: s32, key: bool, ascii: bool) -> bool {
bytes: Vec(u8)
defer { EraseBuffer(document, *bytes) }
if !CopyBytesInto(document, node, key, *bytes) { document.error = "out of memory writing JSON"; return false }
return JsonQuoteInto(output, TextView(VecSlice(bytes, 0, bytes.count)), ascii)
}
Line :: (output: *Vec(u8), style: JsonStyle, depth: s32) -> bool {
if !VecPush(<<output, cast(u8)10) { return false }
spaces: s64 = cast(s64)style.indent * depth
while spaces > 0 { if !VecPush(<<output, #char " ") { return false }; spaces -= 1 }
return true
}
// A conservative bound, computed before private output bytes exist. Reserving
// once prevents allocator relocation from leaving old plaintext behind.
SizeAdd :: (total: *s64, amount: s64) -> bool {
if amount < 0 || amount > 9223372036854775807 - <<total { return false }
<<total += amount
return true
}
MeasureNode :: (document: *JsonDocument, node: s32, style: JsonStyle, depth: s32, total: *s64) -> bool {
if depth > MAX_DEPTH || JsonKindOf(document, node) == .Missing { return false }
kind := document.nodes[node].kind
length := ByteCount(document, node, false)
if kind == .String {
if length > (9223372036854775807 - 2) / 6 { return false }
return SizeAdd(total, 2 + length * 6)
}
if kind == .Number { return SizeAdd(total, length) && (!style.python_floats || SizeAdd(total, 64)) }
if kind == .Null || kind == .True || kind == .False { return SizeAdd(total, 5) }
if !SizeAdd(total, 2) { return false }
child := document.nodes[node].first
visited: s64 = 0
while child >= 0 {
visited += 1
if visited > document.nodes.count || JsonKindOf(document, child) == .Missing { return false }
if !SizeAdd(total, style.item_separator.count) { return false }
if style.indent >= 0 && !SizeAdd(total, 1 + cast(s64)style.indent * (depth + 1)) { return false }
if kind == .Object {
keyLength := ByteCount(document, child, true)
if keyLength > (9223372036854775807 - 2) / 6 ||
!SizeAdd(total, 2 + keyLength * 6) || !SizeAdd(total, style.key_separator.count) { return false }
}
if !MeasureNode(document, child, style, depth + 1, total) { return false }
child = document.nodes[child].next
}
return style.indent < 0 || SizeAdd(total, 1 + cast(s64)style.indent * depth)
}
WriteNode :: (output: *Vec(u8), document: *JsonDocument, node: s32, style: JsonStyle, depth: s32) -> bool {
kind := document.nodes[node].kind
if kind == .Null { return BuilderAppend(<<output, "null") }
if kind == .True { return BuilderAppend(<<output, "true") }
if kind == .False { return BuilderAppend(<<output, "false") }
if kind == .Number {
bytes: Vec(u8)
formatted: Vec(u8)
defer { EraseBuffer(document, *bytes); EraseBuffer(document, *formatted) }
if !CopyBytesInto(document, node, false, *bytes) { return false }
text := TextView(VecSlice(bytes, 0, bytes.count))
if style.python_floats {
at: s64 = 0
floating: bool = false
while at < text.count {
if text[at] == #char "." || text[at] == #char "e" || text[at] == #char "E" { floating = true; break }
at += 1
}
if floating {
value, ok := FloatText.ParseFloat64(text)
if ok {
if !FloatText.Float64ReprInto(value, *formatted) { return false }
repr := TextView(VecSlice(formatted, 0, formatted.count))
if repr == "inf" { return BuilderAppend(<<output, "Infinity") }
if repr == "-inf" { return BuilderAppend(<<output, "-Infinity") }
return BuilderAppend(<<output, repr)
}
}
}
return BuilderAppend(<<output, text)
}
if kind == .String { return QuoteNode(output, document, node, false, style.ascii) }
object := kind == .Object
if document.nodes[node].count == 0 { return BuilderAppend(<<output, ifx object then "{}" else "[]") }
if !VecPush(<<output, ifx object then #char "{" else #char "[") { return false }
members: Vec(s32)
child := document.nodes[node].first
while child >= 0 {
if !VecPush(members, child) { return false }
child = document.nodes[child].next
}
if object && style.sort_keys {
sorted: s64 = 1
while sorted < members.count {
moving := members[sorted]
at := sorted
while at > 0 && KeyBeforeNodes(document, moving, members[at - 1]) {
members[at] = members[at - 1]
at -= 1
}
members[at] = moving
sorted += 1
}
}
index: s64 = 0
while index < members.count {
child = members[index]
if index > 0 && !BuilderAppend(<<output, style.item_separator) { return false }
if style.indent >= 0 && !Line(output, style, depth + 1) { return false }
if object && (!QuoteNode(output, document, child, true, style.ascii) ||
!BuilderAppend(<<output, style.key_separator)) { return false }
if !WriteNode(output, document, child, style, depth + 1) { return false }
index += 1
}
if style.indent >= 0 && !Line(output, style, depth) { return false }
return VecPush(<<output, ifx object then #char "}" else #char "]")
}
#scope_export
// NODE and everything in it as JSON text in STYLE, without a final newline.
JsonWrite :: (document: *JsonDocument, node: s32, style: JsonStyle) -> Text {
output: Vec(u8)
if !JsonWriteInto(*output, document, node, style) { EraseBuffer(document, *output); return .{} }
return BuilderFinish(output)
}
// Append to caller-owned storage. It must not back this document's borrowed
// input, or be one of its owned node buffers. Discard partial output on error.
// Sensitive callers start with empty/wiped storage or pre-reserve its lifetime
// maximum; they erase their own output and borrowed input after use.
JsonWriteInto :: (output: *Vec(u8), document: *JsonDocument, node: s32, style: JsonStyle) -> bool {
if output == null || JsonKindOf(document, node) == .Missing { return false }
document.error = ""
size: s64 = output.count
if !MeasureNode(document, node, style, 0, *size) || !VecReserve(<<output, size) ||
!WriteNode(output, document, node, style, 0) {
document.error = "out of memory or invalid tree writing JSON"
return false
}
return true
}