data: codecs/Json (RFC 8259 parse / serialize: ordered keys, Types.null, bigInts as strings, pretty / ascii, events pull tokenizer, decodeAt / lines, streaming writer); JSONTestSuite + Python json fixtures; bench lines
Types (backward compatible additions in the Data section): Types.object / isObject / set / keys (ordered objects and empty-object marking, shared by every data format), Types.Date (RFC 3339 typed dates for TOML / plist / CBOR / msgpack: new / is / valid / parse / toUnix / fromUnix), XmlNode gains optional text / target / ns fields. tools/bench.sh: also generates the json fixtures. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
ccb06775c5
commit
b6f40e0a74
10 files changed
+1818
-3
No files matched your search
+279
-2
@@ -343,12 +343,289 @@ export type Archive = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Data
|
||||
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
|
||||
-- table). XML decodes to XmlNode trees.
|
||||
-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers.
|
||||
local nullMeta = { __tostring = function()
|
||||
return "null"
|
||||
end }
|
||||
Types.null = table.freeze(setmetatable({}, nullMeta))
|
||||
export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
|
||||
|
||||
-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry
|
||||
-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked
|
||||
-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted).
|
||||
-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" })
|
||||
-- Types.set(o, "c", 3) -- assigns and appends "c" to the order
|
||||
-- for _, k in Types.keys(o) do ... end
|
||||
local OBJECT = { __object = true }
|
||||
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
|
||||
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
|
||||
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
|
||||
local o = t or {}
|
||||
if getmetatable(o) == nil then
|
||||
setmetatable(o, OBJECT)
|
||||
end
|
||||
objectMeta[o] = keys or {}
|
||||
return o
|
||||
end
|
||||
-- isObject(v) -> true for tables made by Types.object
|
||||
function Types.isObject(v: any): boolean
|
||||
return type(v) == "table" and objectMeta[v] ~= nil
|
||||
end
|
||||
-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns)
|
||||
function Types.set(o: { [any]: any }, k: any, v: any)
|
||||
local order = objectMeta[o]
|
||||
if order and o[k] == nil and v ~= nil then
|
||||
table.insert(order, k)
|
||||
end
|
||||
o[k] = v
|
||||
end
|
||||
local function keyLess(a: any, b: any): boolean
|
||||
local ta, tb = type(a), type(b)
|
||||
if ta ~= tb then
|
||||
return ta < tb
|
||||
end
|
||||
if ta == "number" or ta == "string" then
|
||||
return a < b
|
||||
end
|
||||
return tostring(a) < tostring(b)
|
||||
end
|
||||
-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
|
||||
-- sorted (numbers before strings)
|
||||
function Types.keys(t: { [any]: any }): { any }
|
||||
local order = objectMeta[t]
|
||||
local out, seen = {}, {}
|
||||
if order then
|
||||
for _, k in order do
|
||||
if t[k] ~= nil and not seen[k] then
|
||||
seen[k] = true
|
||||
table.insert(out, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
local rest = {}
|
||||
for k in next, t do
|
||||
if not seen[k] then
|
||||
table.insert(rest, k)
|
||||
end
|
||||
end
|
||||
if #rest > 0 then
|
||||
table.sort(rest, keyLess)
|
||||
table.move(rest, 1, #rest, #out + 1, out)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- Dates and times (TOML datetimes, plist <date>, CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the
|
||||
-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes
|
||||
-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...).
|
||||
export type Date = {
|
||||
kind: "datetime" | "datetime-local" | "date-local" | "time-local",
|
||||
year: number?,
|
||||
month: number?,
|
||||
day: number?,
|
||||
hour: number?,
|
||||
minute: number?,
|
||||
second: number?,
|
||||
nanosecond: number?, -- 0 .. 999999999
|
||||
offset: number?, -- minutes east of UTC
|
||||
}
|
||||
local DateMeta = {}
|
||||
local function p2(n: number): string
|
||||
return string.format("%02d", n)
|
||||
end
|
||||
local function fmtDate(d: any): string
|
||||
local s = ""
|
||||
if d.year then
|
||||
s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
|
||||
end
|
||||
if d.hour then
|
||||
if s ~= "" then
|
||||
s ..= "T"
|
||||
end
|
||||
s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
|
||||
local ns = d.nanosecond or 0
|
||||
if ns > 0 then
|
||||
local f = string.format("%09d", ns)
|
||||
s ..= "." .. (string.gsub(f, "0+$", ""))
|
||||
end
|
||||
if d.offset then
|
||||
if d.offset == 0 then
|
||||
s ..= "Z"
|
||||
else
|
||||
local o = math.abs(d.offset)
|
||||
s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60)
|
||||
end
|
||||
end
|
||||
end
|
||||
return s
|
||||
end
|
||||
DateMeta.__tostring = fmtDate
|
||||
DateMeta.__eq = function(a: any, b: any): boolean
|
||||
return fmtDate(a) == fmtDate(b) and a.kind == b.kind
|
||||
end
|
||||
local DateLib = {}
|
||||
-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm)
|
||||
local function daysFromCivil(y: number, m: number, d: number): number
|
||||
y = if m <= 2 then y - 1 else y
|
||||
local era = (if y >= 0 then y else y - 399) // 400
|
||||
local yoe = y - era * 400
|
||||
local mp = (m + 9) % 12
|
||||
local doy = (153 * mp + 2) // 5 + d - 1
|
||||
local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
|
||||
return era * 146097 + doe - 719468
|
||||
end
|
||||
local function civilFromDays(z: number): (number, number, number)
|
||||
z += 719468
|
||||
local era = (if z >= 0 then z else z - 146096) // 146097
|
||||
local doe = z - era * 146097
|
||||
local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
|
||||
local y = yoe + era * 400
|
||||
local doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
|
||||
local mp = (5 * doy + 2) // 153
|
||||
local d = doy - (153 * mp + 2) // 5 + 1
|
||||
local m = if mp < 10 then mp + 3 else mp - 9
|
||||
return (if m <= 2 then y + 1 else y), m, d
|
||||
end
|
||||
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
|
||||
-- new(fields) -> Date (kind inferred from the fields present when not given)
|
||||
function DateLib.new(f: { [string]: any }): Date
|
||||
local d: any = {}
|
||||
for k, v in f do
|
||||
d[k] = v
|
||||
end
|
||||
if d.kind == nil then
|
||||
d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local")
|
||||
elseif d.year then "date-local"
|
||||
else "time-local"
|
||||
end
|
||||
return setmetatable(d, DateMeta) :: any
|
||||
end
|
||||
-- is(v) -> true for Dates
|
||||
function DateLib.is(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == DateMeta
|
||||
end
|
||||
-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...)
|
||||
function DateLib.valid(d: Date): boolean
|
||||
if d.year then
|
||||
local y, m, dd = d.year, d.month or 0, d.day or 0
|
||||
if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then
|
||||
return false
|
||||
end
|
||||
if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if d.hour then
|
||||
if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
if d.offset and math.abs(d.offset) >= 24 * 60 then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27",
|
||||
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
|
||||
function DateLib.parse(s: string): Date?
|
||||
local d: any = {}
|
||||
local rest = s
|
||||
local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
|
||||
if y then
|
||||
d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
|
||||
rest = r1
|
||||
if rest == "" then
|
||||
return if DateLib.valid(d) then DateLib.new(d) else nil
|
||||
end
|
||||
local sep = string.sub(rest, 1, 1)
|
||||
if sep ~= "T" and sep ~= "t" and sep ~= " " then
|
||||
return nil
|
||||
end
|
||||
rest = string.sub(rest, 2)
|
||||
end
|
||||
local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$")
|
||||
if not h then
|
||||
return nil
|
||||
end
|
||||
d.hour, d.minute = tonumber(h), tonumber(mi)
|
||||
rest = r2
|
||||
local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
|
||||
if not sec then
|
||||
return nil
|
||||
end
|
||||
d.second = tonumber(sec)
|
||||
rest = r3
|
||||
local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
|
||||
if frac then
|
||||
d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
|
||||
rest = r4
|
||||
else
|
||||
d.nanosecond = 0
|
||||
end
|
||||
if rest ~= "" then
|
||||
if not d.year then
|
||||
return nil
|
||||
end
|
||||
if rest == "Z" or rest == "z" then
|
||||
d.offset = 0
|
||||
else
|
||||
local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$")
|
||||
if not sign then
|
||||
return nil
|
||||
end
|
||||
local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number
|
||||
if oh_n > 23 or om_n > 59 then
|
||||
return nil
|
||||
end
|
||||
d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1)
|
||||
end
|
||||
end
|
||||
return if DateLib.valid(d) then DateLib.new(d) else nil
|
||||
end
|
||||
-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC)
|
||||
function DateLib.toUnix(d: Date): number
|
||||
local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0
|
||||
local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60
|
||||
return s + (d.nanosecond or 0) / 1e9
|
||||
end
|
||||
-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC)
|
||||
function DateLib.fromUnix(t: number, offset: number?): Date
|
||||
local off = offset or 0
|
||||
local whole = math.floor(t)
|
||||
local ns = math.floor((t - whole) * 1e9 + 0.5)
|
||||
if ns >= 1e9 then
|
||||
whole += 1
|
||||
ns -= 1e9
|
||||
end
|
||||
local lt = whole + off * 60
|
||||
local days = lt // 86400
|
||||
local secs = lt - days * 86400
|
||||
local y, m, dd = civilFromDays(days)
|
||||
return DateLib.new({
|
||||
kind = "datetime",
|
||||
year = y,
|
||||
month = m,
|
||||
day = dd,
|
||||
hour = secs // 3600,
|
||||
minute = (secs // 60) % 60,
|
||||
second = secs % 60,
|
||||
nanosecond = ns,
|
||||
offset = off,
|
||||
})
|
||||
end
|
||||
Types.Date = table.freeze(DateLib)
|
||||
|
||||
-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with
|
||||
-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings.
|
||||
export type XmlNode = {
|
||||
name: string,
|
||||
attrs: { [string]: string },
|
||||
children: { XmlNode | string },
|
||||
parent: XmlNode?,
|
||||
text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content
|
||||
target: string?, -- "#pi": the target
|
||||
ns: string?, -- the namespace URI (opts.namespaces)
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Vector
|
||||
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/Json/Decode: the RFC 8259 parser behind codecs/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 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 function utf8char(c: number): string
|
||||
if c < 0x80 then
|
||||
return char(c)
|
||||
elseif c < 0x800 then
|
||||
return char(0xC0 + c // 64, 0x80 + c % 64)
|
||||
elseif c < 0x10000 then
|
||||
return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
|
||||
end
|
||||
return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
|
||||
end
|
||||
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,310 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/Json/Encode: the serializer behind codecs/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
|
||||
if next(t, n) ~= nil then
|
||||
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/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/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/Json/Decode")
|
||||
local Encode = require("@formats/codecs/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