ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically): - codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder; codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url; codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err Crc32 Adler32 Base64 Md5 Input Sniff. - LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md). - Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes. C3, generic code out of format folders: - containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first, trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64 through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it. - codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position, priming and end trimming) that aac, caf and m4a each carried (~70 lines each). - codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of its own (the AND mask / alpha rule stay ICO's). - codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model), Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the fixtures' bind shapes). - README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes: FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
9c553b9d1a
commit
434a304315
283 files changed
+1877
-1660
No files matched your search
@@ -0,0 +1,425 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting
|
||||
-- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single
|
||||
-- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the
|
||||
-- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset).
|
||||
local Text = require("@formats/codecs/text/Text")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
|
||||
local tonumber = tonumber
|
||||
local concat = table.concat
|
||||
|
||||
export type Options = {
|
||||
ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are)
|
||||
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number")
|
||||
null: any?, -- the value for null (default Types.null)
|
||||
maxDepth: number?, -- nesting limit (default 1000)
|
||||
}
|
||||
|
||||
local ESC: { [number]: string } = {
|
||||
[34] = '"',
|
||||
[92] = "\\",
|
||||
[47] = "/",
|
||||
[98] = "\b",
|
||||
[102] = "\f",
|
||||
[110] = "\n",
|
||||
[114] = "\r",
|
||||
[116] = "\t",
|
||||
}
|
||||
|
||||
-- utf8 bytes of a code point (surrogates too: WTF-8)
|
||||
local utf8char = Text.utf8char
|
||||
Decode.utf8char = utf8char
|
||||
|
||||
local function hex4(s: string, i: number): number?
|
||||
local h = match(s, "^%x%x%x%x", i)
|
||||
if not h then
|
||||
return nil
|
||||
end
|
||||
return tonumber(h, 16)
|
||||
end
|
||||
|
||||
-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote.
|
||||
local function str(s: string, i: number): (string?, any, number?)
|
||||
local j = find(s, '[%z\1-\31"\\]', i + 1)
|
||||
if not j then
|
||||
return nil, "unterminated string", #s
|
||||
end
|
||||
local c = byte(s, j)
|
||||
if c == 34 then
|
||||
return sub(s, i + 1, j - 1), j + 1
|
||||
end
|
||||
local parts = {}
|
||||
local np = 0
|
||||
local start = i + 1
|
||||
while true do
|
||||
if c == 34 then
|
||||
np += 1
|
||||
parts[np] = sub(s, start, j - 1)
|
||||
return concat(parts), j + 1
|
||||
elseif c ~= 92 then
|
||||
return nil, "control character in string", j - 1
|
||||
end
|
||||
np += 1
|
||||
parts[np] = sub(s, start, j - 1)
|
||||
local e = byte(s, j + 1)
|
||||
if e == nil then
|
||||
return nil, "unterminated string", #s
|
||||
end
|
||||
local simple = ESC[e]
|
||||
if simple then
|
||||
np += 1
|
||||
parts[np] = simple
|
||||
start = j + 2
|
||||
elseif e == 117 then -- \u
|
||||
local cp = hex4(s, j + 2)
|
||||
if not cp then
|
||||
return nil, "bad \\u escape", j - 1
|
||||
end
|
||||
start = j + 6
|
||||
if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then
|
||||
local lo = hex4(s, start + 2)
|
||||
if lo and lo >= 0xDC00 and lo <= 0xDFFF then
|
||||
cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00)
|
||||
start += 6
|
||||
end
|
||||
end
|
||||
np += 1
|
||||
parts[np] = utf8char(cp)
|
||||
else
|
||||
return nil, "bad escape", j - 1
|
||||
end
|
||||
j = find(s, '[%z\1-\31"\\]', start)
|
||||
if not j then
|
||||
return nil, "unterminated string", #s
|
||||
end
|
||||
c = byte(s, j)
|
||||
end
|
||||
end
|
||||
Decode.string = str
|
||||
|
||||
-- number(s, i) -> value, next | nil, message, offset
|
||||
local function num(s: string, i: number, bigStrings: boolean): (any, any, number?)
|
||||
local p = i
|
||||
if byte(s, p) == 45 then
|
||||
p += 1
|
||||
end
|
||||
local c = byte(s, p)
|
||||
if c == 48 then
|
||||
p += 1
|
||||
elseif c and c >= 49 and c <= 57 then
|
||||
p = match(s, "^%d*()", p + 1) :: any
|
||||
else
|
||||
return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1
|
||||
end
|
||||
local int = true
|
||||
if byte(s, p) == 46 then
|
||||
local q = match(s, "^%d+()", p + 1)
|
||||
if not q then
|
||||
return nil, "bad fraction", p
|
||||
end
|
||||
p = q :: any
|
||||
int = false
|
||||
end
|
||||
c = byte(s, p)
|
||||
if c == 101 or c == 69 then
|
||||
p += 1
|
||||
c = byte(s, p)
|
||||
if c == 43 or c == 45 then
|
||||
p += 1
|
||||
end
|
||||
local q = match(s, "^%d+()", p)
|
||||
if not q then
|
||||
return nil, "bad exponent", p - 1
|
||||
end
|
||||
p = q :: any
|
||||
int = false
|
||||
end
|
||||
local text = sub(s, i, p - 1)
|
||||
local n = tonumber(text) :: number
|
||||
if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow
|
||||
local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)")
|
||||
local mv = tonumber(m) or 0
|
||||
n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge
|
||||
end
|
||||
if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then
|
||||
return text, p
|
||||
end
|
||||
return n, p
|
||||
end
|
||||
Decode.number = num
|
||||
|
||||
-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace
|
||||
-- skipped); next is the position after the value (trailing whitespace not skipped).
|
||||
function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
|
||||
local o: Options = opts or {}
|
||||
local ordered = o.ordered == true
|
||||
local bigStrings = o.bigInts == "string"
|
||||
local nullv = if o.null ~= nil then o.null else Types.null
|
||||
local maxDepth = o.maxDepth or 1000
|
||||
local object = Types.object
|
||||
|
||||
local stackT: { any } = {} -- containers
|
||||
local stackK: { any } = {} -- object: the pending key; array: the count
|
||||
local stackO: { any } = {} -- object: its key order (or true); array: false
|
||||
local depth = 0
|
||||
local n = #s
|
||||
local value: any
|
||||
|
||||
while true do
|
||||
i = match(s, "^[ \t\n\r]*()", i) :: any
|
||||
local c = byte(s, i)
|
||||
local haveValue = true
|
||||
if c == 123 then -- {
|
||||
depth += 1
|
||||
if depth > maxDepth then
|
||||
return nil, "nested deeper than " .. maxDepth, i - 1
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
|
||||
local t = {}
|
||||
c = byte(s, i)
|
||||
if c == 125 then
|
||||
i += 1
|
||||
depth -= 1
|
||||
value = object(t, {})
|
||||
elseif c == 34 then
|
||||
local k, ni, at = str(s, i)
|
||||
if k == nil then
|
||||
return nil, ni, at
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", ni) :: any
|
||||
if byte(s, i) ~= 58 then
|
||||
return nil, if i > n then "truncated object" else "expected ':'", i - 1
|
||||
end
|
||||
i += 1
|
||||
stackT[depth], stackK[depth] = t, k
|
||||
stackO[depth] = if ordered then {} else true
|
||||
haveValue = false
|
||||
else
|
||||
return nil, if c == nil then "truncated object" else "expected a key", i - 1
|
||||
end
|
||||
elseif c == 91 then -- [
|
||||
depth += 1
|
||||
if depth > maxDepth then
|
||||
return nil, "nested deeper than " .. maxDepth, i - 1
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
|
||||
if byte(s, i) == 93 then
|
||||
i += 1
|
||||
depth -= 1
|
||||
value = {}
|
||||
else
|
||||
stackT[depth], stackK[depth], stackO[depth] = {}, 0, false
|
||||
haveValue = false
|
||||
end
|
||||
elseif c == 34 then
|
||||
local v, ni, at = str(s, i)
|
||||
if v == nil then
|
||||
return nil, ni, at
|
||||
end
|
||||
value, i = v, ni
|
||||
elseif c == 116 then
|
||||
if sub(s, i, i + 3) ~= "true" then
|
||||
return nil, "bad literal", i - 1
|
||||
end
|
||||
value, i = true, i + 4
|
||||
elseif c == 102 then
|
||||
if sub(s, i, i + 4) ~= "false" then
|
||||
return nil, "bad literal", i - 1
|
||||
end
|
||||
value, i = false, i + 5
|
||||
elseif c == 110 then
|
||||
if sub(s, i, i + 3) ~= "null" then
|
||||
return nil, "bad literal", i - 1
|
||||
end
|
||||
value, i = nullv, i + 4
|
||||
elseif c == nil then
|
||||
return nil, "truncated: expected a value", n
|
||||
else
|
||||
local v, ni, at = num(s, i, bigStrings)
|
||||
if v == nil then
|
||||
return nil, ni, at
|
||||
end
|
||||
value, i = v, ni
|
||||
end
|
||||
-- attach the value to the open containers, closing them as their ends come
|
||||
while haveValue do
|
||||
if depth == 0 then
|
||||
return value, i
|
||||
end
|
||||
local t = stackT[depth]
|
||||
local ord = stackO[depth]
|
||||
if ord then
|
||||
local k = stackK[depth]
|
||||
if ord ~= true and t[k] == nil then
|
||||
table.insert(ord, k)
|
||||
end
|
||||
t[k] = value
|
||||
else
|
||||
local cnt = stackK[depth] + 1
|
||||
t[cnt] = value
|
||||
stackK[depth] = cnt
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", i) :: any
|
||||
c = byte(s, i)
|
||||
if c == 44 then -- ,
|
||||
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
|
||||
if ord then
|
||||
if byte(s, i) ~= 34 then
|
||||
return nil, if i > n then "truncated object" else "expected a key", i - 1
|
||||
end
|
||||
local k, ni, at = str(s, i)
|
||||
if k == nil then
|
||||
return nil, ni, at
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", ni) :: any
|
||||
if byte(s, i) ~= 58 then
|
||||
return nil, if i > n then "truncated object" else "expected ':'", i - 1
|
||||
end
|
||||
i += 1
|
||||
stackK[depth] = k
|
||||
end
|
||||
haveValue = false
|
||||
elseif ord and c == 125 then
|
||||
i += 1
|
||||
value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t
|
||||
stackT[depth] = nil
|
||||
depth -= 1
|
||||
elseif not ord and c == 93 then
|
||||
i += 1
|
||||
value = t
|
||||
stackT[depth] = nil
|
||||
depth -= 1
|
||||
elseif c == nil then
|
||||
return nil, if ord then "truncated object" else "truncated array", n
|
||||
else
|
||||
return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object",
|
||||
-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes.
|
||||
function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?)
|
||||
local o: Options = opts or {}
|
||||
local bigStrings = o.bigInts == "string"
|
||||
local nullv = if o.null ~= nil then o.null else Types.null
|
||||
local maxDepth = o.maxDepth or 1000
|
||||
local stack: { boolean } = {} -- true = object
|
||||
local depth = 0
|
||||
-- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value),
|
||||
-- "key" (a key expected), "done", "dead"
|
||||
local state = "value"
|
||||
local n = #s
|
||||
local function fail(msg: string, at: number): (string, any, number)
|
||||
state = "dead"
|
||||
return "error", msg, at
|
||||
end
|
||||
return function(): (string?, any, number?)
|
||||
if state == "dead" then
|
||||
return nil
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", i) :: any
|
||||
local c = byte(s, i)
|
||||
if state == "done" then
|
||||
state = "dead"
|
||||
if c ~= nil then
|
||||
return "error", "trailing data", i - 1
|
||||
end
|
||||
return nil
|
||||
end
|
||||
if state == "after" then
|
||||
local obj = stack[depth]
|
||||
if c == 44 then
|
||||
i = match(s, "^[ \t\n\r]*()", i + 1) :: any
|
||||
c = byte(s, i)
|
||||
state = if obj then "key" else "value"
|
||||
elseif c == (if obj then 125 else 93) then
|
||||
i += 1
|
||||
stack[depth] = nil
|
||||
depth -= 1
|
||||
state = if depth == 0 then "done" else "after"
|
||||
return if obj then "endObject" else "endArray", nil
|
||||
elseif c == nil then
|
||||
return fail("truncated", n)
|
||||
else
|
||||
return fail("expected ',' or a close", i - 1)
|
||||
end
|
||||
end
|
||||
if state == "first" then
|
||||
local obj = stack[depth]
|
||||
if c == (if obj then 125 else 93) then
|
||||
i += 1
|
||||
stack[depth] = nil
|
||||
depth -= 1
|
||||
state = if depth == 0 then "done" else "after"
|
||||
return if obj then "endObject" else "endArray", nil
|
||||
end
|
||||
state = if obj then "key" else "value"
|
||||
end
|
||||
if state == "key" then
|
||||
if c ~= 34 then
|
||||
return fail(if c == nil then "truncated" else "expected a key", i - 1)
|
||||
end
|
||||
local k, ni, at = str(s, i)
|
||||
if k == nil then
|
||||
return fail(ni, at :: number)
|
||||
end
|
||||
i = match(s, "^[ \t\n\r]*()", ni) :: any
|
||||
if byte(s, i) ~= 58 then
|
||||
return fail("expected ':'", i - 1)
|
||||
end
|
||||
i += 1
|
||||
state = "value"
|
||||
return "key", k
|
||||
end
|
||||
-- a value
|
||||
local after = if depth == 0 then "done" else "after"
|
||||
if c == 123 or c == 91 then
|
||||
depth += 1
|
||||
if depth > maxDepth then
|
||||
return fail("nested deeper than " .. maxDepth, i - 1)
|
||||
end
|
||||
stack[depth] = c == 123
|
||||
i += 1
|
||||
state = "first"
|
||||
return if c == 123 then "object" else "array", nil
|
||||
elseif c == 34 then
|
||||
local v, ni, at = str(s, i)
|
||||
if v == nil then
|
||||
return fail(ni, at :: number)
|
||||
end
|
||||
i = ni
|
||||
state = after
|
||||
return "value", v
|
||||
elseif c == 116 and sub(s, i, i + 3) == "true" then
|
||||
i += 4
|
||||
state = after
|
||||
return "value", true
|
||||
elseif c == 102 and sub(s, i, i + 4) == "false" then
|
||||
i += 5
|
||||
state = after
|
||||
return "value", false
|
||||
elseif c == 110 and sub(s, i, i + 3) == "null" then
|
||||
i += 4
|
||||
state = after
|
||||
return "value", nullv
|
||||
elseif c == nil then
|
||||
return fail("truncated: expected a value", n)
|
||||
end
|
||||
local v, ni, at = num(s, i, bigStrings)
|
||||
if v == nil then
|
||||
return fail(ni, at :: number)
|
||||
end
|
||||
i = ni
|
||||
state = after
|
||||
return "value", v
|
||||
end
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,307 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key
|
||||
-- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional
|
||||
-- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers)
|
||||
-- return nil, message.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Encode = {}
|
||||
|
||||
local byte, format, gsub = string.byte, string.format, string.gsub
|
||||
local floor, huge = math.floor, math.huge
|
||||
local concat = table.concat
|
||||
|
||||
export type Options = {
|
||||
indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact
|
||||
sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster)
|
||||
ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is)
|
||||
nan: ("error" | "null")?, -- NaN / inf: an error (default) or null
|
||||
emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}")
|
||||
maxDepth: number?, -- nesting limit (default 1000; also catches cycles)
|
||||
escapeSlash: boolean?, -- write / as \/ (default false)
|
||||
}
|
||||
|
||||
local ESCAPES: { [string]: string } = {
|
||||
['"'] = '\\"',
|
||||
["\\"] = "\\\\",
|
||||
["\b"] = "\\b",
|
||||
["\f"] = "\\f",
|
||||
["\n"] = "\\n",
|
||||
["\r"] = "\\r",
|
||||
["\t"] = "\\t",
|
||||
["/"] = "\\/",
|
||||
}
|
||||
for c = 0, 31 do
|
||||
local ch = string.char(c)
|
||||
if not ESCAPES[ch] then
|
||||
ESCAPES[ch] = format("\\u%04x", c)
|
||||
end
|
||||
end
|
||||
|
||||
local function utf16(cp: number): string
|
||||
if cp < 0x10000 then
|
||||
return format("\\u%04x", cp)
|
||||
end
|
||||
cp -= 0x10000
|
||||
return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024)
|
||||
end
|
||||
|
||||
-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws)
|
||||
local function asciiSeq(seq: string): string
|
||||
local out = {}
|
||||
local i, n = 1, #seq
|
||||
while i <= n do
|
||||
local c = byte(seq, i)
|
||||
local cp, len
|
||||
if c < 0xC0 then
|
||||
cp, len = c, 1
|
||||
elseif c < 0xE0 then
|
||||
cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2
|
||||
elseif c < 0xF0 then
|
||||
cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3
|
||||
else
|
||||
cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4
|
||||
end
|
||||
table.insert(out, utf16(cp))
|
||||
i += len
|
||||
end
|
||||
return concat(out)
|
||||
end
|
||||
|
||||
-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii)
|
||||
local function quote(s: string, ascii: boolean?, slash: boolean?): string
|
||||
local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]'
|
||||
if string.find(s, pat) then
|
||||
s = gsub(s, pat, ESCAPES)
|
||||
end
|
||||
if ascii and string.find(s, "[\127-\255]") then
|
||||
s = gsub(s, "\127", "\\u007f")
|
||||
s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq)
|
||||
s = gsub(s, "[\128-\191]", asciiSeq)
|
||||
end
|
||||
return '"' .. s .. '"'
|
||||
end
|
||||
Encode.quote = quote
|
||||
|
||||
local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" }
|
||||
-- number(x) -> the shortest text that reads back as x | nil for NaN / inf
|
||||
local function number(x: number): string?
|
||||
if x ~= x or x == huge or x == -huge then
|
||||
return nil
|
||||
end
|
||||
if x == floor(x) and x > -1e15 and x < 1e15 then
|
||||
if x == 0 and 1 / x < 0 then
|
||||
return "-0"
|
||||
end
|
||||
return format("%d", x)
|
||||
end
|
||||
for _, f in FLOAT_FORMATS do
|
||||
local t = format(f, x)
|
||||
if tonumber(t) == x then
|
||||
return t
|
||||
end
|
||||
end
|
||||
return format("%.17g", x)
|
||||
end
|
||||
Encode.number = number
|
||||
|
||||
local function keyLess(a: any, b: any): boolean
|
||||
local ta, tb = type(a), type(b)
|
||||
if ta ~= tb then
|
||||
return ta == "number"
|
||||
end
|
||||
return a < b
|
||||
end
|
||||
|
||||
-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object"
|
||||
local function kind(t: { [any]: any }, emptyObject: boolean): string
|
||||
if Types.isObject(t) then
|
||||
return "object"
|
||||
end
|
||||
local n = #t
|
||||
if n == 0 then
|
||||
if next(t) == nil then
|
||||
return if emptyObject then "object" else "array"
|
||||
end
|
||||
return "object"
|
||||
end
|
||||
local count = 0
|
||||
for _ in next, t do
|
||||
count += 1
|
||||
end
|
||||
return if count == n then "array" else "object"
|
||||
end
|
||||
Encode.kind = kind
|
||||
|
||||
type State = {
|
||||
out: { string },
|
||||
n: number,
|
||||
indent: string?,
|
||||
sort: boolean,
|
||||
ascii: boolean,
|
||||
slash: boolean,
|
||||
nanNull: boolean,
|
||||
emptyObject: boolean,
|
||||
maxDepth: number,
|
||||
null: any,
|
||||
err: string?,
|
||||
}
|
||||
|
||||
local function put(st: State, s: string)
|
||||
local n = st.n + 1
|
||||
st.out[n] = s
|
||||
st.n = n
|
||||
end
|
||||
|
||||
local function value(st: State, v: any, depth: number): boolean
|
||||
local tv = type(v)
|
||||
if tv == "string" then
|
||||
put(st, quote(v, st.ascii, st.slash))
|
||||
elseif tv == "number" then
|
||||
local s = number(v)
|
||||
if not s then
|
||||
if not st.nanNull then
|
||||
st.err = "cannot encode " .. tostring(v)
|
||||
return false
|
||||
end
|
||||
s = "null"
|
||||
end
|
||||
put(st, s)
|
||||
elseif tv == "boolean" then
|
||||
put(st, if v then "true" else "false")
|
||||
elseif v == nil or v == st.null or v == Types.null then
|
||||
put(st, "null")
|
||||
elseif tv == "table" then
|
||||
if Types.Date.is(v) then
|
||||
put(st, '"' .. tostring(v) .. '"')
|
||||
return true
|
||||
end
|
||||
if depth >= st.maxDepth then
|
||||
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
|
||||
return false
|
||||
end
|
||||
local ind = st.indent
|
||||
local nl, nl2 = "", ""
|
||||
if ind then
|
||||
nl = "\n" .. string.rep(ind, depth + 1)
|
||||
nl2 = "\n" .. string.rep(ind, depth)
|
||||
end
|
||||
if kind(v, st.emptyObject) == "array" then
|
||||
local n = #v
|
||||
if n == 0 then
|
||||
put(st, "[]")
|
||||
return true
|
||||
end
|
||||
put(st, "[")
|
||||
for i = 1, n do
|
||||
if i > 1 then
|
||||
put(st, ",")
|
||||
end
|
||||
if ind then
|
||||
put(st, nl)
|
||||
end
|
||||
if not value(st, v[i], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if ind then
|
||||
put(st, nl2)
|
||||
end
|
||||
put(st, "]")
|
||||
else
|
||||
local keys: { any }
|
||||
if Types.isObject(v) then
|
||||
keys = Types.keys(v)
|
||||
else
|
||||
keys = {}
|
||||
for k in next, v do
|
||||
local tk = type(k)
|
||||
if tk ~= "string" and tk ~= "number" then
|
||||
st.err = "object key of type " .. tk
|
||||
return false
|
||||
end
|
||||
table.insert(keys, k)
|
||||
end
|
||||
if st.sort then
|
||||
table.sort(keys, keyLess)
|
||||
end
|
||||
end
|
||||
if #keys == 0 then
|
||||
put(st, "{}")
|
||||
return true
|
||||
end
|
||||
put(st, "{")
|
||||
local sep = if ind then ": " else ":"
|
||||
for i, k in keys do
|
||||
if i > 1 then
|
||||
put(st, ",")
|
||||
end
|
||||
if ind then
|
||||
put(st, nl)
|
||||
end
|
||||
local ks: string
|
||||
if type(k) == "string" then
|
||||
ks = k
|
||||
elseif type(k) == "number" then
|
||||
ks = number(k) or tostring(k)
|
||||
else
|
||||
st.err = "object key of type " .. type(k)
|
||||
return false
|
||||
end
|
||||
put(st, quote(ks, st.ascii, st.slash))
|
||||
put(st, sep)
|
||||
if not value(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if ind then
|
||||
put(st, nl2)
|
||||
end
|
||||
put(st, "}")
|
||||
end
|
||||
elseif tv == "buffer" then
|
||||
st.err = "cannot encode a buffer (encode it as base64 or an array first)"
|
||||
return false
|
||||
else
|
||||
st.err = "cannot encode a " .. tv
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function state(opts: Options?, nullv: any?): State
|
||||
local o: Options = opts or {}
|
||||
local ind: string? = nil
|
||||
if type(o.indent) == "number" then
|
||||
ind = if o.indent > 0 then string.rep(" ", o.indent) else nil
|
||||
elseif type(o.indent) == "string" then
|
||||
ind = o.indent
|
||||
end
|
||||
return {
|
||||
out = {},
|
||||
n = 0,
|
||||
indent = ind,
|
||||
sort = o.sortKeys ~= false,
|
||||
ascii = o.ascii == true,
|
||||
slash = o.escapeSlash == true,
|
||||
nanNull = o.nan == "null",
|
||||
emptyObject = o.emptyTable == "object",
|
||||
maxDepth = o.maxDepth or 1000,
|
||||
null = nullv,
|
||||
err = nil,
|
||||
}
|
||||
end
|
||||
Encode.state = state
|
||||
Encode.write = value
|
||||
|
||||
-- encode(v, opts) -> text | nil, message
|
||||
function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?)
|
||||
local st = state(opts, nullv)
|
||||
if not value(st, v, 0) then
|
||||
return nil, st.err
|
||||
end
|
||||
return concat(st.out), nil
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,294 @@
|
||||
--!strict
|
||||
-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
|
||||
-- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers
|
||||
-- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so
|
||||
-- they write back as {}; opts.ordered makes every object a Types.object with its key order.
|
||||
--
|
||||
-- local Json = require("@formats/codecs/text/Json")
|
||||
-- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input
|
||||
-- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err
|
||||
-- for ev, x in Json.events(text) do ... end -- pull events without building the tree
|
||||
-- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values
|
||||
-- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring()
|
||||
--
|
||||
-- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer;
|
||||
-- writer() builds output incrementally and flush() hands back the text so far. Never throws.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Decode = require("@formats/codecs/text/Json/Decode")
|
||||
local Encode = require("@formats/codecs/text/Json/Encode")
|
||||
|
||||
local Json = {}
|
||||
|
||||
export type DecodeOptions = Decode.Options
|
||||
export type EncodeOptions = Encode.Options
|
||||
|
||||
Json.null = Types.null
|
||||
Json.object = Types.object
|
||||
Json.keys = Types.keys
|
||||
Json.set = Types.set
|
||||
|
||||
local function text(src: any): (string?, Err.Err?)
|
||||
if type(src) == "string" then
|
||||
return src, nil
|
||||
elseif type(src) == "buffer" then
|
||||
return buffer.tostring(src), nil
|
||||
end
|
||||
return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src))
|
||||
end
|
||||
|
||||
local function fail(msg: any, at: any, n: number): Err.Err
|
||||
local m = tostring(msg)
|
||||
local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n
|
||||
then Err.TRUNCATED
|
||||
elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT
|
||||
else Err.CORRUPT
|
||||
return Err.new(code, m, at)
|
||||
end
|
||||
|
||||
-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is
|
||||
-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil.
|
||||
function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local s, terr = text(src)
|
||||
if not s then
|
||||
return nil, terr
|
||||
end
|
||||
local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1
|
||||
local v, ni, at = Decode.value(s, i, opts)
|
||||
if v == nil then
|
||||
return nil, fail(ni, at, #s)
|
||||
end
|
||||
local e = string.match(s, "^[ \t\n\r]*()", ni) :: any
|
||||
if e <= #s then
|
||||
return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading
|
||||
-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left.
|
||||
function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any)
|
||||
local s, terr = text(src)
|
||||
if not s then
|
||||
return nil, terr
|
||||
end
|
||||
local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any
|
||||
if i > #s then
|
||||
return nil, nil
|
||||
end
|
||||
local v, ni, at = Decode.value(s, i, opts)
|
||||
if v == nil then
|
||||
return nil, fail(ni, at, #s)
|
||||
end
|
||||
return v, ni
|
||||
end
|
||||
|
||||
-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A
|
||||
-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end
|
||||
function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?)
|
||||
local s, terr = text(src)
|
||||
local pos = 1
|
||||
local index = 0
|
||||
local dead = false
|
||||
return function(): (number?, any, Err.Err?)
|
||||
if dead then
|
||||
return nil
|
||||
end
|
||||
index += 1
|
||||
if not s then
|
||||
dead = true
|
||||
return index, nil, terr
|
||||
end
|
||||
local v, ni = Json.decodeAt(s, pos, opts)
|
||||
if v == nil then
|
||||
dead = true
|
||||
if ni == nil then
|
||||
return nil
|
||||
end
|
||||
return index, nil, ni
|
||||
end
|
||||
pos = ni
|
||||
return index, v, nil
|
||||
end
|
||||
end
|
||||
|
||||
-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key),
|
||||
-- "value" (a scalar), and on bad input one final "error", Err.
|
||||
function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any)
|
||||
local s, terr = text(src)
|
||||
if not s then
|
||||
local done = false
|
||||
return function(): (string?, any)
|
||||
if done then
|
||||
return nil, nil
|
||||
end
|
||||
done = true
|
||||
return "error", terr
|
||||
end
|
||||
end
|
||||
local str: string = s
|
||||
local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1
|
||||
local nextEv = Decode.events(str, i, opts)
|
||||
return function(): (string?, any)
|
||||
local ev, v, at = nextEv()
|
||||
if ev == "error" then
|
||||
return ev, fail(v, at, #str)
|
||||
end
|
||||
return ev, v
|
||||
end
|
||||
end
|
||||
|
||||
-- encode(value, opts?) -> string | nil, Err
|
||||
function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?)
|
||||
local s, msg = Encode.encode(value, opts)
|
||||
if not s then
|
||||
return nil, Err.new(Err.ARG, msg or "cannot encode")
|
||||
end
|
||||
return s, nil
|
||||
end
|
||||
|
||||
Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes
|
||||
Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writer
|
||||
-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any
|
||||
-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key
|
||||
-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing.
|
||||
export type Writer = {
|
||||
err: Err.Err?,
|
||||
beginObject: (self: Writer) -> Writer,
|
||||
endObject: (self: Writer) -> Writer,
|
||||
beginArray: (self: Writer) -> Writer,
|
||||
endArray: (self: Writer) -> Writer,
|
||||
key: (self: Writer, k: string) -> Writer,
|
||||
value: (self: Writer, v: any) -> Writer,
|
||||
flush: (self: Writer) -> string,
|
||||
tostring: (self: Writer) -> (string?, Err.Err?),
|
||||
}
|
||||
|
||||
function Json.writer(opts: EncodeOptions?): Writer
|
||||
local st = Encode.state(opts)
|
||||
local ind = st.indent
|
||||
local kinds: { boolean } = {} -- true = object
|
||||
local counts: { number } = {}
|
||||
local depth = 0
|
||||
local keyDone = false -- an object's key written, its value due
|
||||
local flushed: { string } = {}
|
||||
local w: any = { err = nil }
|
||||
local function bad(msg: string)
|
||||
if not w.err then
|
||||
w.err = Err.new(Err.ARG, msg)
|
||||
end
|
||||
end
|
||||
-- before an element: a comma / newline as needed; false when the position is wrong
|
||||
local function slot(isKey: boolean): boolean
|
||||
if w.err then
|
||||
return false
|
||||
end
|
||||
if depth == 0 then
|
||||
if counts[0] and counts[0] > 0 then
|
||||
bad("one top-level value only")
|
||||
return false
|
||||
end
|
||||
counts[0] = 1
|
||||
return true
|
||||
end
|
||||
local obj = kinds[depth]
|
||||
if obj and not isKey then
|
||||
if not keyDone then
|
||||
bad("an object member needs a key first")
|
||||
return false
|
||||
end
|
||||
keyDone = false
|
||||
return true
|
||||
end
|
||||
if isKey and not obj then
|
||||
bad("key outside an object")
|
||||
return false
|
||||
end
|
||||
if isKey and keyDone then
|
||||
bad("two keys in a row")
|
||||
return false
|
||||
end
|
||||
if counts[depth] > 0 then
|
||||
table.insert(st.out, ",")
|
||||
end
|
||||
counts[depth] += 1
|
||||
if ind then
|
||||
table.insert(st.out, "\n" .. string.rep(ind, depth))
|
||||
end
|
||||
return true
|
||||
end
|
||||
local function open(obj: boolean)
|
||||
if slot(false) then
|
||||
table.insert(st.out, if obj then "{" else "[")
|
||||
depth += 1
|
||||
kinds[depth], counts[depth] = obj, 0
|
||||
end
|
||||
return w
|
||||
end
|
||||
local function close(obj: boolean)
|
||||
if w.err then
|
||||
return w
|
||||
end
|
||||
if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then
|
||||
bad(if obj then "unbalanced endObject" else "unbalanced endArray")
|
||||
return w
|
||||
end
|
||||
if ind and counts[depth] > 0 then
|
||||
table.insert(st.out, "\n" .. string.rep(ind, depth - 1))
|
||||
end
|
||||
table.insert(st.out, if obj then "}" else "]")
|
||||
depth -= 1
|
||||
return w
|
||||
end
|
||||
function w.beginObject(_self: Writer): Writer
|
||||
return open(true)
|
||||
end
|
||||
function w.beginArray(_self: Writer): Writer
|
||||
return open(false)
|
||||
end
|
||||
function w.endObject(_self: Writer): Writer
|
||||
return close(true)
|
||||
end
|
||||
function w.endArray(_self: Writer): Writer
|
||||
return close(false)
|
||||
end
|
||||
function w.key(_self: Writer, k: string): Writer
|
||||
if type(k) ~= "string" then
|
||||
bad("key must be a string")
|
||||
elseif slot(true) then
|
||||
table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":"))
|
||||
keyDone = true
|
||||
end
|
||||
return w
|
||||
end
|
||||
function w.value(_self: Writer, v: any): Writer
|
||||
if slot(false) then
|
||||
st.n = #st.out
|
||||
if not Encode.write(st, v, depth) then
|
||||
bad(st.err or "cannot encode")
|
||||
end
|
||||
end
|
||||
return w
|
||||
end
|
||||
function w.flush(_self: Writer): string
|
||||
local s = table.concat(st.out)
|
||||
table.clear(st.out)
|
||||
st.n = 0
|
||||
table.insert(flushed, s)
|
||||
return s
|
||||
end
|
||||
function w.tostring(_self: Writer): (string?, Err.Err?)
|
||||
if w.err then
|
||||
return nil, w.err
|
||||
end
|
||||
if depth ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "unclosed object / array")
|
||||
end
|
||||
return table.concat(flushed) .. table.concat(st.out), nil
|
||||
end
|
||||
return w :: Writer
|
||||
end
|
||||
|
||||
return Json
|
||||
Reference in new issue
Block a user