308 lines
7.5 KiB
Luau
308 lines
7.5 KiB
Luau
--!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
|
|
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
|