merge ws/data: codecs Json/Xml, data json xml csv ini toml yaml msgpack cbor plist
This commit is contained in:
commit
840bb6ab7e
49 files changed
+10395
-3
No files matched your search
@@ -158,6 +158,114 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/zst")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "cbor",
|
||||
category = "data",
|
||||
path = "data/cbor",
|
||||
extensions = { "cbor" },
|
||||
mime = { "application/cbor", "application/cbor-seq" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, binary = true, ordered = true, tags = true },
|
||||
load = function()
|
||||
return require("@formats/data/cbor")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "csv",
|
||||
category = "data",
|
||||
path = "data/csv",
|
||||
extensions = { "csv", "tsv" },
|
||||
mime = { "text/csv", "text/tab-separated-values" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, header = true },
|
||||
load = function()
|
||||
return require("@formats/data/csv")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ini",
|
||||
category = "data",
|
||||
path = "data/ini",
|
||||
extensions = { "ini", "cfg", "conf", "inf", "desktop" },
|
||||
mime = { "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, ordered = true },
|
||||
load = function()
|
||||
return require("@formats/data/ini")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "json",
|
||||
category = "data",
|
||||
path = "data/json",
|
||||
extensions = { "json", "jsonl", "ndjson", "geojson" },
|
||||
mime = { "application/json", "application/x-ndjson" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, ordered = true, streaming = true },
|
||||
load = function()
|
||||
return require("@formats/data/json")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "msgpack",
|
||||
category = "data",
|
||||
path = "data/msgpack",
|
||||
extensions = { "msgpack", "mpk" },
|
||||
mime = { "application/msgpack", "application/x-msgpack" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, binary = true, ordered = true },
|
||||
load = function()
|
||||
return require("@formats/data/msgpack")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "plist",
|
||||
category = "data",
|
||||
path = "data/plist",
|
||||
extensions = { "plist" },
|
||||
mime = { "application/x-plist", "application/x-bplist" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, binary = "read", ordered = true },
|
||||
load = function()
|
||||
return require("@formats/data/plist")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "toml",
|
||||
category = "data",
|
||||
path = "data/toml",
|
||||
extensions = { "toml" },
|
||||
mime = { "application/toml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, ordered = true, dates = true },
|
||||
load = function()
|
||||
return require("@formats/data/toml")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xml",
|
||||
category = "data",
|
||||
path = "data/xml",
|
||||
extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
|
||||
mime = { "application/xml", "text/xml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
|
||||
caps = { decode = true, encode = true, namespaces = true, streaming = true },
|
||||
load = function()
|
||||
return require("@formats/data/xml")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "yaml",
|
||||
category = "data",
|
||||
path = "data/yaml",
|
||||
extensions = { "yaml", "yml" },
|
||||
mime = { "application/yaml", "application/x-yaml", "text/yaml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true },
|
||||
load = function()
|
||||
return require("@formats/data/yaml")
|
||||
end,
|
||||
},
|
||||
}
|
||||
|
||||
return list
|
||||
+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,307 @@
|
||||
--!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
|
||||
@@ -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
|
||||
@@ -0,0 +1,771 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or
|
||||
-- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the
|
||||
-- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values,
|
||||
-- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities,
|
||||
-- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported:
|
||||
-- external entities / DTDs (references to them are errors), entity values containing markup (taken as text),
|
||||
-- validation. Never throws: errors are events.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Parse = {}
|
||||
|
||||
local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower
|
||||
|
||||
export type Options = {
|
||||
whitespace: boolean?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve")
|
||||
namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false)
|
||||
entities: { [string]: string }?, -- extra general entities (name -> replacement text)
|
||||
maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard)
|
||||
maxDepth: number?, -- element nesting limit (default 10000)
|
||||
}
|
||||
|
||||
local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*"
|
||||
local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" }
|
||||
|
||||
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
|
||||
Parse.utf8char = utf8char
|
||||
|
||||
local CP1252: { [number]: number } = {
|
||||
[0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020,
|
||||
[0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152,
|
||||
[0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022,
|
||||
[0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A,
|
||||
[0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178,
|
||||
}
|
||||
|
||||
local function utf16(s: string, start: number, le: boolean): (string?, string?)
|
||||
local out = table.create(#s // 2)
|
||||
local n = 0
|
||||
local i = start
|
||||
local len = #s
|
||||
while i + 1 <= len do
|
||||
local a, b = byte(s, i, i + 1)
|
||||
local u = if le then a + b * 256 else a * 256 + b
|
||||
i += 2
|
||||
if u >= 0xD800 and u <= 0xDBFF then
|
||||
if i + 1 > len then
|
||||
return nil, "truncated UTF-16 surrogate pair"
|
||||
end
|
||||
local c, d = byte(s, i, i + 1)
|
||||
local lo = if le then c + d * 256 else c * 256 + d
|
||||
if lo < 0xDC00 or lo > 0xDFFF then
|
||||
return nil, "bad UTF-16 surrogate pair"
|
||||
end
|
||||
i += 2
|
||||
u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
|
||||
elseif u >= 0xDC00 and u <= 0xDFFF then
|
||||
return nil, "bad UTF-16 surrogate pair"
|
||||
end
|
||||
n += 1
|
||||
out[n] = utf8char(u)
|
||||
end
|
||||
if i <= len then
|
||||
return nil, "odd number of bytes in UTF-16 text"
|
||||
end
|
||||
return table.concat(out), nil
|
||||
end
|
||||
|
||||
-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message
|
||||
function Parse.toUtf8(s: string): (string?, string)
|
||||
local b1, b2, b3 = byte(s, 1, 3)
|
||||
if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then
|
||||
return sub(s, 4), "utf-8"
|
||||
elseif b1 == 0xFF and b2 == 0xFE then
|
||||
local t, e = utf16(s, 3, true)
|
||||
return t, e or "utf-16le"
|
||||
elseif b1 == 0xFE and b2 == 0xFF then
|
||||
local t, e = utf16(s, 3, false)
|
||||
return t, e or "utf-16be"
|
||||
elseif b1 == 0x3C and b2 == 0 then
|
||||
local t, e = utf16(s, 1, true)
|
||||
return t, e or "utf-16le"
|
||||
elseif b1 == 0 and b2 == 0x3C then
|
||||
local t, e = utf16(s, 1, false)
|
||||
return t, e or "utf-16be"
|
||||
end
|
||||
local decl = match(s, "^<%?xml[^>]-%?>")
|
||||
local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil
|
||||
if enc then
|
||||
local e = lower(enc)
|
||||
if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then
|
||||
if find(s, "[\128-\255]") and not utf8.len(s) then
|
||||
return nil, "invalid UTF-8"
|
||||
end
|
||||
return s, e
|
||||
elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then
|
||||
local w = e == "windows-1252" or e == "cp1252"
|
||||
return (gsub(s, "[\128-\255]", function(c: string): string
|
||||
local v = byte(c)
|
||||
return utf8char(if w then CP1252[v] or v else v)
|
||||
end)), e
|
||||
elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then
|
||||
return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes
|
||||
end
|
||||
return nil, "unsupported encoding " .. enc
|
||||
end
|
||||
if find(s, "[\128-\255]") and not utf8.len(s) then
|
||||
return nil, "invalid UTF-8"
|
||||
end
|
||||
return s, "utf-8"
|
||||
end
|
||||
|
||||
-- the <?xml ...?> pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace
|
||||
local function xmlDecl(data: string): { [string]: string }?
|
||||
local p = 1
|
||||
local out: { [string]: string } = {}
|
||||
for k, key in { "version", "encoding", "standalone" } do
|
||||
local ws = match(data, "^[ \t\n]*()", p) :: any
|
||||
local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws)
|
||||
if q then
|
||||
if k > 1 and ws == p then
|
||||
return nil -- no whitespace before
|
||||
end
|
||||
if (key == "version" and not match(v, "^1%.%d+$"))
|
||||
or (key == "encoding" and not match(v, "^%a[%w%._%-]*$"))
|
||||
or (key == "standalone" and v ~= "yes" and v ~= "no")
|
||||
then
|
||||
return nil
|
||||
end
|
||||
out[key] = v
|
||||
p = e
|
||||
elseif key == "version" then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
if match(data, "^[ \t\n]*()", p) ~= #data + 1 then
|
||||
return nil
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the events iterator: next() -> event, a, b, c
|
||||
-- "decl", { version, encoding, standalone } the <?xml ...?> declaration
|
||||
-- "doctype", raw, info raw = the text between "<!DOCTYPE" and ">"; info = { name,
|
||||
-- publicId, systemId, entities }
|
||||
-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil
|
||||
-- "end", name
|
||||
-- "text", s character data, entities decoded (whitespace-only dropped
|
||||
-- unless opts.whitespace)
|
||||
-- "cdata", s "comment", s "pi", target, data
|
||||
-- "error", message, offset then the iterator ends
|
||||
-- nil at the end of the document.
|
||||
function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any)
|
||||
local o: Options = opts or {}
|
||||
local keepWs = o.whitespace == true
|
||||
local nsOn = o.namespaces == true
|
||||
local maxExp = o.maxExpansion or 1e7
|
||||
local maxDepth = o.maxDepth or 10000
|
||||
local entities: { [string]: string } = {}
|
||||
if o.entities then
|
||||
for k, v in o.entities do
|
||||
entities[k] = v
|
||||
end
|
||||
end
|
||||
local external: { [string]: boolean } = {}
|
||||
local expanded = 0
|
||||
if find(s, "\r", 1, true) then
|
||||
s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n")
|
||||
end
|
||||
local n = #s
|
||||
local i = 1
|
||||
local stack: { string } = {}
|
||||
local nsStack: { { [string]: string } } = {}
|
||||
local preserve: { boolean } = {}
|
||||
local depth = 0
|
||||
local rootSeen = false
|
||||
local rootDone = false
|
||||
local dead = false
|
||||
local pending: { any }? = nil -- an "end" queued after a self-closing start
|
||||
local errMsg: string? = nil
|
||||
local errAt = 0
|
||||
|
||||
local function fail(msg: string, at: number): (string, string, number)
|
||||
dead = true
|
||||
return "error", msg, at - 1
|
||||
end
|
||||
|
||||
-- decode entity / character references in raw text; nil on error (errMsg set)
|
||||
local decode: (raw: string, at: number, level: number) -> string?
|
||||
function decode(raw: string, at: number, level: number): string?
|
||||
if not find(raw, "&", 1, true) then
|
||||
return raw
|
||||
end
|
||||
local parts = {}
|
||||
local np = 0
|
||||
local p = 1
|
||||
while true do
|
||||
local a = find(raw, "&", p, true)
|
||||
if not a then
|
||||
break
|
||||
end
|
||||
np += 1
|
||||
parts[np] = sub(raw, p, a - 1)
|
||||
local ref, e = match(raw, "^&([^;&%s<]*);()", a)
|
||||
if not ref then
|
||||
errMsg, errAt = "bad reference (no ';')", at + a - 1
|
||||
return nil
|
||||
end
|
||||
local rep: string
|
||||
if byte(ref) == 35 then -- #
|
||||
local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "")
|
||||
if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then
|
||||
errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1
|
||||
return nil
|
||||
end
|
||||
rep = utf8char(cp)
|
||||
else
|
||||
local pre = PREDEF[ref]
|
||||
if pre then
|
||||
rep = pre
|
||||
else
|
||||
local ent = entities[ref]
|
||||
if not ent then
|
||||
errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";"
|
||||
errAt = at + a - 1
|
||||
return nil
|
||||
end
|
||||
if level > 40 then
|
||||
errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1
|
||||
return nil
|
||||
end
|
||||
local r = decode(ent, at + a - 1, level + 1)
|
||||
if not r then
|
||||
return nil
|
||||
end
|
||||
rep = r
|
||||
end
|
||||
end
|
||||
expanded += #rep
|
||||
if expanded > maxExp then
|
||||
errMsg, errAt = "entity expansion over the limit", at + a - 1
|
||||
return nil
|
||||
end
|
||||
np += 1
|
||||
parts[np] = rep
|
||||
p = e :: any
|
||||
end
|
||||
np += 1
|
||||
parts[np] = sub(raw, p)
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
local function lookupNs(prefix: string): string?
|
||||
for d = depth, 1, -1 do
|
||||
local m = nsStack[d]
|
||||
if m and m[prefix] ~= nil then
|
||||
return m[prefix]
|
||||
end
|
||||
end
|
||||
if prefix == "xml" then
|
||||
return "http://www.w3.org/XML/1998/namespace"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- a quoted literal at p -> its content, the position after it | nil
|
||||
local function literal(p: number): (string?, number)
|
||||
local q = byte(s, p)
|
||||
if q ~= 34 and q ~= 39 then
|
||||
return nil, p
|
||||
end
|
||||
local e = find(s, if q == 34 then '"' else "'", p + 1, true)
|
||||
if not e then
|
||||
return nil, p
|
||||
end
|
||||
return sub(s, p + 1, e - 1), e + 1
|
||||
end
|
||||
-- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil
|
||||
local function externalId(p: number): (string?, string?, number?)
|
||||
local kw = sub(s, p, p + 5)
|
||||
if kw == "SYSTEM" then
|
||||
local q = match(s, "^[ \t\n]+()", p + 6) :: any
|
||||
if not q then
|
||||
return nil
|
||||
end
|
||||
local sys, e = literal(q)
|
||||
if not sys then
|
||||
return nil
|
||||
end
|
||||
return "", sys, e
|
||||
elseif kw == "PUBLIC" then
|
||||
local q = match(s, "^[ \t\n]+()", p + 6) :: any
|
||||
if not q then
|
||||
return nil
|
||||
end
|
||||
local pub, e = literal(q)
|
||||
if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then
|
||||
return nil
|
||||
end
|
||||
local r = match(s, "^[ \t\n]+()", e) :: any
|
||||
if not r then
|
||||
return nil
|
||||
end
|
||||
local sys, e2 = literal(r)
|
||||
if not sys then
|
||||
return nil
|
||||
end
|
||||
return pub, sys, e2
|
||||
end
|
||||
return nil
|
||||
end
|
||||
-- check an entity value's references and expand its character references (the rest expand when used)
|
||||
local function entityValue(v: string): string?
|
||||
if find(v, "%", 1, true) then
|
||||
return nil -- parameter-entity references are not allowed in the internal subset's markup
|
||||
end
|
||||
local p = 1
|
||||
local parts = {}
|
||||
while true do
|
||||
local a = find(v, "&", p, true)
|
||||
if not a then
|
||||
table.insert(parts, sub(v, p))
|
||||
break
|
||||
end
|
||||
table.insert(parts, sub(v, p, a - 1))
|
||||
local hex = match(v, "^&#x(%x+);", a)
|
||||
local dec = match(v, "^&#(%d+);", a)
|
||||
if hex or dec then
|
||||
local cp = tonumber(hex or dec, if hex then 16 else 10) :: number
|
||||
if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then
|
||||
return nil
|
||||
end
|
||||
table.insert(parts, utf8char(cp))
|
||||
p = (find(v, ";", a, true) :: number) + 1
|
||||
else
|
||||
local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a)
|
||||
if not name then
|
||||
return nil
|
||||
end
|
||||
table.insert(parts, "&" .. name .. ";")
|
||||
p = a + #name + 2
|
||||
end
|
||||
end
|
||||
return table.concat(parts)
|
||||
end
|
||||
-- the DOCTYPE at i (just past "<!DOCTYPE"): its raw text and info { name, publicId, systemId, entities }; records
|
||||
-- the internal subset's general entities. nil, message on bad syntax.
|
||||
local function doctype(): (string?, any)
|
||||
local start = i
|
||||
local p = match(s, "^[ \t\n]+()", i) :: any
|
||||
if not p then
|
||||
return nil, "bad DOCTYPE"
|
||||
end
|
||||
local name = match(s, NAME, p)
|
||||
if not name then
|
||||
return nil, "bad DOCTYPE name"
|
||||
end
|
||||
local info: any = { name = name, entities = {} }
|
||||
p += #name
|
||||
local q = match(s, "^[ \t\n]*()", p) :: any
|
||||
if q > p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then
|
||||
local pub, sys, e = externalId(q)
|
||||
if not pub then
|
||||
return nil, "bad DOCTYPE external id"
|
||||
end
|
||||
info.publicId = if pub ~= "" then pub else nil
|
||||
info.systemId = sys
|
||||
q = match(s, "^[ \t\n]*()", e) :: any
|
||||
end
|
||||
if byte(s, q) == 91 then -- the internal subset
|
||||
q += 1
|
||||
while true do
|
||||
q = match(s, "^[ \t\n]*()", q) :: any
|
||||
local c = byte(s, q)
|
||||
if c == 93 then
|
||||
q += 1
|
||||
break
|
||||
elseif c == 37 then -- %name;
|
||||
local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q)
|
||||
if not pe then
|
||||
return nil, "bad parameter-entity reference"
|
||||
end
|
||||
q = pe :: any
|
||||
elseif sub(s, q, q + 3) == "<!--" then
|
||||
local e = find(s, "--", q + 4, true)
|
||||
if not e or byte(s, e + 2) ~= 62 then
|
||||
return nil, if e then "'--' inside a comment" else "unterminated comment in DOCTYPE"
|
||||
end
|
||||
q = e + 3
|
||||
elseif sub(s, q, q + 1) == "<?" then
|
||||
local target = match(s, NAME, q + 2)
|
||||
local e = find(s, "?>", q + 2, true)
|
||||
if not target or not e or lower(target) == "xml" then
|
||||
return nil, "bad processing instruction in DOCTYPE"
|
||||
end
|
||||
q = e + 2
|
||||
elseif sub(s, q, q + 7) == "<!ENTITY" then
|
||||
local r = match(s, "^[ \t\n]+()", q + 8) :: any
|
||||
if not r then
|
||||
return nil, "bad ENTITY declaration"
|
||||
end
|
||||
local isPe = false
|
||||
if byte(s, r) == 37 then
|
||||
isPe = true
|
||||
r = match(s, "^[ \t\n]+()", r + 1) :: any
|
||||
if not r then
|
||||
return nil, "bad ENTITY declaration"
|
||||
end
|
||||
end
|
||||
local ename = match(s, NAME, r)
|
||||
if not ename then
|
||||
return nil, "bad ENTITY name"
|
||||
end
|
||||
r = match(s, "^[ \t\n]+()", r + #ename) :: any
|
||||
if not r then
|
||||
return nil, "bad ENTITY declaration"
|
||||
end
|
||||
local val, e = literal(r)
|
||||
if val then
|
||||
local v = entityValue(val)
|
||||
if not v then
|
||||
return nil, "bad ENTITY value"
|
||||
end
|
||||
if not isPe and entities[ename] == nil then
|
||||
entities[ename] = v
|
||||
info.entities[ename] = v
|
||||
end
|
||||
r = e
|
||||
else
|
||||
local pub, _, e2 = externalId(r)
|
||||
if not pub then
|
||||
return nil, "bad ENTITY declaration"
|
||||
end
|
||||
r = e2 :: number
|
||||
local nd = match(s, "^[ \t\n]+NDATA[ \t\n]+()", r)
|
||||
if nd then
|
||||
local nn = match(s, NAME, nd)
|
||||
if not nn or isPe then
|
||||
return nil, "bad NDATA"
|
||||
end
|
||||
r = nd + #nn
|
||||
end
|
||||
if not isPe then
|
||||
external[ename] = true
|
||||
end
|
||||
end
|
||||
r = match(s, "^[ \t\n]*()", r) :: any
|
||||
if byte(s, r) ~= 62 then
|
||||
return nil, "bad ENTITY declaration"
|
||||
end
|
||||
q = r + 1
|
||||
elseif sub(s, q, q + 8) == "<!ELEMENT" or sub(s, q, q + 8) == "<!ATTLIST" or sub(s, q, q + 9) == "<!NOTATION" then
|
||||
local kw = match(s, "^<!(%u+)", q) :: string
|
||||
local r = match(s, "^[ \t\n]+()", q + 2 + #kw) :: any
|
||||
if not r or not match(s, NAME, r) then
|
||||
return nil, "bad " .. kw .. " declaration"
|
||||
end
|
||||
-- skip to the closing '>' outside quotes
|
||||
while true do
|
||||
local c2 = byte(s, r)
|
||||
if c2 == nil then
|
||||
return nil, "unterminated DOCTYPE"
|
||||
elseif c2 == 34 or c2 == 39 then
|
||||
local e = find(s, if c2 == 34 then '"' else "'", r + 1, true)
|
||||
if not e then
|
||||
return nil, "unterminated DOCTYPE"
|
||||
end
|
||||
r = e + 1
|
||||
elseif c2 == 62 then
|
||||
break
|
||||
elseif c2 == 60 then
|
||||
return nil, "bad " .. kw .. " declaration"
|
||||
else
|
||||
r += 1
|
||||
end
|
||||
end
|
||||
q = r + 1
|
||||
elseif c == nil then
|
||||
return nil, "unterminated DOCTYPE"
|
||||
else
|
||||
return nil, "bad markup in the DOCTYPE"
|
||||
end
|
||||
end
|
||||
q = match(s, "^[ \t\n]*()", q) :: any
|
||||
end
|
||||
if byte(s, q) ~= 62 then
|
||||
return nil, if q > n then "unterminated DOCTYPE" else "bad DOCTYPE"
|
||||
end
|
||||
i = q + 1
|
||||
return sub(s, start, q - 1), info
|
||||
end
|
||||
|
||||
return function(): (string?, any, any, any)
|
||||
if dead then
|
||||
return nil
|
||||
end
|
||||
if pending then
|
||||
local ev = pending
|
||||
pending = nil
|
||||
depth -= 1
|
||||
if depth == 0 then
|
||||
rootDone = true
|
||||
end
|
||||
return "end", ev[1]
|
||||
end
|
||||
while true do
|
||||
if i > n then
|
||||
dead = true
|
||||
if depth > 0 then
|
||||
return "error", "unclosed element <" .. stack[depth] .. ">", n
|
||||
end
|
||||
if not rootSeen then
|
||||
return "error", "no root element", n
|
||||
end
|
||||
return nil
|
||||
end
|
||||
local c = byte(s, i)
|
||||
if c ~= 60 then -- text
|
||||
local e = find(s, "<", i, true) or (n + 1)
|
||||
local raw = sub(s, i, e - 1)
|
||||
local start = i
|
||||
i = e
|
||||
local wsOnly = not find(raw, "[^ \t\n]")
|
||||
if depth == 0 then
|
||||
if not wsOnly then
|
||||
return fail(if rootDone then "text after the root element" else "text before the root element", start)
|
||||
end
|
||||
else
|
||||
if find(raw, "]]>", 1, true) then
|
||||
return fail("']]>' in text", start + (find(raw, "]]>", 1, true) :: number) - 1)
|
||||
end
|
||||
local bad = find(raw, "[%z\1-\8\11\12\14-\31]")
|
||||
if bad then
|
||||
return fail("control character in text", start + bad - 1)
|
||||
end
|
||||
if not wsOnly or keepWs or preserve[depth] then
|
||||
local t = decode(raw, start, 0)
|
||||
if not t then
|
||||
return fail(errMsg :: string, errAt)
|
||||
end
|
||||
return "text", t
|
||||
end
|
||||
end
|
||||
continue
|
||||
end
|
||||
local c2 = byte(s, i + 1)
|
||||
if c2 == 47 then -- </
|
||||
local name = match(s, NAME, i + 2)
|
||||
if not name then
|
||||
return fail("bad end tag", i)
|
||||
end
|
||||
local p = match(s, "^[ \t\n]*()", i + 2 + #name) :: any
|
||||
if byte(s, p) ~= 62 then
|
||||
return fail(if p > n then "unterminated end tag" else "bad end tag", p)
|
||||
end
|
||||
if depth == 0 or stack[depth] ~= name then
|
||||
return fail("mismatched end tag </" .. name .. ">" .. (if depth > 0 then " (open: <" .. stack[depth] .. ">)" else ""), i)
|
||||
end
|
||||
i = p + 1
|
||||
stack[depth] = nil
|
||||
nsStack[depth] = nil
|
||||
preserve[depth] = nil
|
||||
depth -= 1
|
||||
if depth == 0 then
|
||||
rootDone = true
|
||||
end
|
||||
return "end", name
|
||||
elseif c2 == 33 then -- <!
|
||||
if sub(s, i + 2, i + 3) == "--" then
|
||||
local e = find(s, "--", i + 4, true)
|
||||
if not e then
|
||||
return fail("unterminated comment", i)
|
||||
end
|
||||
if byte(s, e + 2) ~= 62 then
|
||||
return fail(if e + 2 > n then "unterminated comment" else "'--' inside a comment", e)
|
||||
end
|
||||
local text = sub(s, i + 4, e - 1)
|
||||
i = e + 3
|
||||
return "comment", text
|
||||
elseif sub(s, i + 2, i + 8) == "[CDATA[" then
|
||||
if depth == 0 then
|
||||
return fail("CDATA outside the root element", i)
|
||||
end
|
||||
local e = find(s, "]]>", i + 9, true)
|
||||
if not e then
|
||||
return fail("unterminated CDATA section", i)
|
||||
end
|
||||
local text = sub(s, i + 9, e - 1)
|
||||
i = e + 3
|
||||
return "cdata", text
|
||||
elseif sub(s, i + 2, i + 8) == "DOCTYPE" then
|
||||
if rootSeen then
|
||||
return fail("DOCTYPE after the root element", i)
|
||||
end
|
||||
local at = i
|
||||
i += 9
|
||||
local raw, info = doctype()
|
||||
if not raw then
|
||||
return fail(info, at)
|
||||
end
|
||||
return "doctype", raw, info
|
||||
end
|
||||
return fail("bad markup declaration", i)
|
||||
elseif c2 == 63 then -- <?
|
||||
local target = match(s, NAME, i + 2)
|
||||
if not target then
|
||||
return fail("bad processing instruction", i)
|
||||
end
|
||||
local e = find(s, "?>", i + 2 + #target, true)
|
||||
if not e then
|
||||
return fail("unterminated processing instruction", i)
|
||||
end
|
||||
local data = sub(s, i + 2 + #target, e - 1)
|
||||
if data ~= "" and not find(data, "^[ \t\n]") then
|
||||
return fail("bad processing instruction", i)
|
||||
end
|
||||
data = match(data, "^[ \t\n]*(.-)$") :: string
|
||||
local at = i
|
||||
i = e + 2
|
||||
if lower(target) == "xml" then
|
||||
if target ~= "xml" or at ~= 1 then
|
||||
return fail("misplaced XML declaration", at)
|
||||
end
|
||||
local decl = xmlDecl(data)
|
||||
if not decl then
|
||||
return fail("bad XML declaration", at)
|
||||
end
|
||||
return "decl", decl
|
||||
end
|
||||
return "pi", target, data
|
||||
end
|
||||
-- a start tag
|
||||
local name = match(s, NAME, i + 1)
|
||||
if not name then
|
||||
return fail(if i + 1 > n then "truncated tag" else "bad tag name", i + 1)
|
||||
end
|
||||
if rootDone then
|
||||
return fail("a second root element <" .. name .. ">", i)
|
||||
end
|
||||
local at = i
|
||||
local p = i + 1 + #name
|
||||
local attrs = Types.object()
|
||||
local order = {}
|
||||
local closed = false
|
||||
local nsMap: { [string]: string }? = nil
|
||||
while true do
|
||||
local q = match(s, "^[ \t\n]*()", p) :: any
|
||||
local cc = byte(s, q)
|
||||
if cc == 62 then
|
||||
p = q + 1
|
||||
break
|
||||
elseif cc == 47 then
|
||||
if byte(s, q + 1) ~= 62 then
|
||||
return fail("bad tag end", q)
|
||||
end
|
||||
p = q + 2
|
||||
closed = true
|
||||
break
|
||||
elseif cc == nil then
|
||||
return fail("truncated tag", q)
|
||||
end
|
||||
if q == p then
|
||||
return fail("missing whitespace between attributes", q)
|
||||
end
|
||||
local an = match(s, NAME, q)
|
||||
if not an then
|
||||
return fail("bad attribute name", q)
|
||||
end
|
||||
local r = match(s, "^[ \t\n]*=[ \t\n]*()", q + #an) :: any
|
||||
if not r then
|
||||
return fail("attribute " .. an .. " without a value", q)
|
||||
end
|
||||
local qc = byte(s, r)
|
||||
if qc ~= 34 and qc ~= 39 then
|
||||
return fail("unquoted attribute value", r)
|
||||
end
|
||||
local e = find(s, if qc == 34 then '"' else "'", r + 1, true)
|
||||
if not e then
|
||||
return fail("unterminated attribute value", r)
|
||||
end
|
||||
local raw = sub(s, r + 1, e - 1)
|
||||
if find(raw, "<", 1, true) then
|
||||
return fail("'<' in an attribute value", r)
|
||||
end
|
||||
if find(raw, "[%z\1-\8\11\12\14-\31]") then
|
||||
return fail("control character in an attribute value", r)
|
||||
end
|
||||
local v = decode(raw, r + 1, 0)
|
||||
if not v then
|
||||
return fail(errMsg :: string, errAt)
|
||||
end
|
||||
if find(raw, "[\t\n]") then
|
||||
-- attribute-value normalization: literal tab / newline become spaces (references stay)
|
||||
v = decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) :: string
|
||||
end
|
||||
if attrs[an] ~= nil then
|
||||
return fail("duplicate attribute " .. an, q)
|
||||
end
|
||||
attrs[an] = v
|
||||
table.insert(order, an)
|
||||
if nsOn then
|
||||
if an == "xmlns" or sub(an, 1, 6) == "xmlns:" then
|
||||
local m: { [string]: string } = nsMap or {}
|
||||
nsMap = m
|
||||
m[if an == "xmlns" then "" else sub(an, 7)] = v
|
||||
end
|
||||
end
|
||||
p = e + 1
|
||||
end
|
||||
Types.object(attrs, order)
|
||||
i = p
|
||||
depth += 1
|
||||
if depth > maxDepth then
|
||||
return fail("nested deeper than " .. maxDepth, at)
|
||||
end
|
||||
stack[depth] = name
|
||||
nsStack[depth] = nsMap :: any
|
||||
local sp = attrs["xml:space"]
|
||||
preserve[depth] = if sp == "preserve" then true elseif sp == "default" then false else (preserve[depth - 1] or false)
|
||||
rootSeen = true
|
||||
local uri: string? = nil
|
||||
if nsOn then
|
||||
local prefix = match(name, "^([^:]*):") or ""
|
||||
uri = lookupNs(prefix)
|
||||
if uri == "" then
|
||||
uri = nil
|
||||
end
|
||||
if prefix ~= "" and uri == nil then
|
||||
return fail("undeclared namespace prefix " .. prefix, at)
|
||||
end
|
||||
end
|
||||
if closed then
|
||||
stack[depth] = nil
|
||||
nsStack[depth] = nil
|
||||
preserve[depth] = nil
|
||||
pending = { name } -- depth goes down when the queued "end" is returned
|
||||
end
|
||||
return "start", name, attrs, uri
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors
|
||||
function Parse.resolve(node: any, prefix: string): string?
|
||||
local p = node
|
||||
local key = if prefix == "" then "xmlns" else "xmlns:" .. prefix
|
||||
while p do
|
||||
local a = p.attrs
|
||||
if a and a[key] ~= nil then
|
||||
local v = a[key]
|
||||
return if v == "" then nil else v
|
||||
end
|
||||
p = p.parent
|
||||
end
|
||||
if prefix == "xml" then
|
||||
return "http://www.w3.org/XML/1998/namespace"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return Parse
|
||||
@@ -0,0 +1,440 @@
|
||||
--!strict
|
||||
-- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
|
||||
-- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal
|
||||
-- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces
|
||||
-- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives
|
||||
-- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup.
|
||||
--
|
||||
-- local Xml = require("@formats/codecs/Xml")
|
||||
-- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element
|
||||
-- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end
|
||||
-- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like)
|
||||
-- local s = Xml.encode(doc, { indent = 2 })
|
||||
-- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees
|
||||
--
|
||||
-- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string },
|
||||
-- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and
|
||||
-- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI
|
||||
-- target); otherwise CDATA merges into the text and the others are dropped. Never throws.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Parse = require("@formats/codecs/Xml/Parse")
|
||||
|
||||
local Xml = {}
|
||||
|
||||
export type Node = Types.XmlNode
|
||||
export type DecodeOptions = Parse.Options & {
|
||||
comments: boolean?, -- keep comments as "#comment" nodes (default false)
|
||||
cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text)
|
||||
pi: boolean?, -- keep processing instructions as "#pi" nodes (default false)
|
||||
parents: boolean?, -- set node.parent (default true)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
indent: (number | string)?, -- pretty print elements that hold only elements (default none)
|
||||
declaration: boolean?, -- write <?xml version="1.0" encoding="UTF-8"?> (default: true for a "#document")
|
||||
selfClose: boolean?, -- <a/> for empty elements (default true)
|
||||
}
|
||||
|
||||
local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match
|
||||
|
||||
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 errCode(msg: string, at: number, n: number): string
|
||||
if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then
|
||||
return Err.TRUNCATED
|
||||
elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then
|
||||
return Err.LIMIT
|
||||
elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then
|
||||
return Err.UNSUPPORTED
|
||||
end
|
||||
return Err.CORRUPT
|
||||
end
|
||||
|
||||
-- events(src, opts?) -> iterator: event, a, b, c (see codecs/Xml/Parse: "decl", "doctype", "start" name attrs ns,
|
||||
-- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event)
|
||||
function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any)
|
||||
local s, terr = text(src)
|
||||
local u, enc = nil, ""
|
||||
if s then
|
||||
u, enc = Parse.toUtf8(s)
|
||||
end
|
||||
if not u then
|
||||
local e = terr or Err.new(if find(enc, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, enc)
|
||||
local done = false
|
||||
return function(): (string?, any, any, any)
|
||||
if done then
|
||||
return nil
|
||||
end
|
||||
done = true
|
||||
return "error", e
|
||||
end
|
||||
end
|
||||
local str: string = u
|
||||
local nextEv = Parse.events(str, opts)
|
||||
return function(): (string?, any, any, any)
|
||||
local ev, a, b, c = nextEv()
|
||||
if ev == "error" then
|
||||
return ev, Err.new(errCode(a, b, #str), a, b)
|
||||
end
|
||||
return ev, a, b, c
|
||||
end
|
||||
end
|
||||
|
||||
-- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version,
|
||||
-- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus
|
||||
-- any kept comments / PIs around it.
|
||||
function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true
|
||||
local parents = o.parents ~= false
|
||||
local doc: any = { name = "#document", attrs = Types.object(), children = {}, parent = nil }
|
||||
local cur: any = doc
|
||||
local stack = { doc }
|
||||
local depth = 1
|
||||
for ev, a, b, c in Xml.events(src, o) do
|
||||
if ev == "start" then
|
||||
local node: any = { name = a, attrs = b, children = {}, parent = if parents then cur else nil }
|
||||
if c then
|
||||
node.ns = c
|
||||
end
|
||||
table.insert(cur.children, node)
|
||||
depth += 1
|
||||
stack[depth] = node
|
||||
cur = node
|
||||
if depth == 2 then
|
||||
doc.root = node
|
||||
end
|
||||
elseif ev == "end" then
|
||||
stack[depth] = nil
|
||||
depth -= 1
|
||||
cur = stack[depth]
|
||||
elseif ev == "text" or (ev == "cdata" and not keepCdata) then
|
||||
local ch = cur.children
|
||||
local last = #ch
|
||||
if last > 0 and type(ch[last]) == "string" then
|
||||
ch[last] ..= a
|
||||
else
|
||||
ch[last + 1] = a
|
||||
end
|
||||
elseif ev == "cdata" then
|
||||
table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil })
|
||||
elseif ev == "comment" then
|
||||
if keepComments then
|
||||
table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil })
|
||||
end
|
||||
elseif ev == "pi" then
|
||||
if keepPi then
|
||||
table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = if parents then cur else nil })
|
||||
end
|
||||
elseif ev == "decl" then
|
||||
doc.declaration = a
|
||||
elseif ev == "doctype" then
|
||||
doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities }
|
||||
elseif ev == "error" then
|
||||
return nil, a
|
||||
end
|
||||
end
|
||||
return doc, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tree helpers
|
||||
-- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object;
|
||||
-- children: nodes or strings; their parent is set)
|
||||
function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node
|
||||
local a = attrs or Types.object()
|
||||
if not Types.isObject(a) then
|
||||
local keys = {}
|
||||
for k in next, a do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
table.sort(keys)
|
||||
a = Types.object(a, keys)
|
||||
end
|
||||
local node: any = { name = name, attrs = a, children = children or {} }
|
||||
for _, ch in node.children do
|
||||
if type(ch) == "table" then
|
||||
ch.parent = node
|
||||
end
|
||||
end
|
||||
return node
|
||||
end
|
||||
|
||||
-- document(root, declaration?) -> a "#document" node around root
|
||||
function Xml.document(root: Node, declaration: { [string]: string }?): Node
|
||||
local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration }
|
||||
root.parent = doc
|
||||
return doc
|
||||
end
|
||||
|
||||
-- append(parent, child) -> child (a node or a string), parent link set
|
||||
function Xml.append(parent: Node, child: any): any
|
||||
table.insert(parent.children, child)
|
||||
if type(child) == "table" then
|
||||
child.parent = parent
|
||||
end
|
||||
return child
|
||||
end
|
||||
|
||||
-- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order
|
||||
function Xml.setAttr(node: Node, name: string, value: string?)
|
||||
Types.set(node.attrs, name, value)
|
||||
end
|
||||
|
||||
-- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and
|
||||
-- the child's does), in order
|
||||
function Xml.children(node: Node, name: string?): { Node }
|
||||
local out = {}
|
||||
for _, ch in node.children do
|
||||
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
|
||||
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
|
||||
table.insert(out, ch)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- child(node, name?) -> the first matching element child, or nil
|
||||
function Xml.child(node: Node, name: string?): Node?
|
||||
for _, ch in node.children do
|
||||
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
|
||||
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
|
||||
return ch
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does
|
||||
function Xml.descendants(node: Node, name: string?): { Node }
|
||||
local out = {}
|
||||
local function walk(n: Node)
|
||||
for _, ch in n.children do
|
||||
if type(ch) == "table" and string.byte(ch.name) ~= 35 then
|
||||
if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then
|
||||
table.insert(out, ch)
|
||||
end
|
||||
walk(ch)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(node)
|
||||
return out
|
||||
end
|
||||
|
||||
-- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not)
|
||||
function Xml.text(node: any): string
|
||||
if type(node) == "string" then
|
||||
return node
|
||||
end
|
||||
if node.name == "#cdata" then
|
||||
return node.text or ""
|
||||
end
|
||||
local parts = {}
|
||||
local function walk(n: any)
|
||||
for _, ch in n.children do
|
||||
if type(ch) == "string" then
|
||||
table.insert(parts, ch)
|
||||
elseif ch.name == "#cdata" then
|
||||
table.insert(parts, ch.text or "")
|
||||
elseif string.byte(ch.name) ~= 35 then
|
||||
walk(ch)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(node)
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
-- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect")
|
||||
function Xml.prefix(name: string): string
|
||||
return match(name, "^([^:]*):") or ""
|
||||
end
|
||||
function Xml.localName(name: string): string
|
||||
return match(name, ":(.*)$") or name
|
||||
end
|
||||
|
||||
-- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its
|
||||
-- ancestors' xmlns attributes (needs parent links)
|
||||
function Xml.namespace(node: Node, prefix: string?): string?
|
||||
return Parse.resolve(node, prefix or Xml.prefix(node.name))
|
||||
end
|
||||
|
||||
-- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes
|
||||
-- (unprefixed attributes have no namespace)
|
||||
function Xml.clark(node: Node, attrName: string?): string
|
||||
local name = attrName or node.name
|
||||
local prefix = Xml.prefix(name)
|
||||
if attrName and prefix == "" then
|
||||
return name
|
||||
end
|
||||
local uri = Parse.resolve(node, prefix)
|
||||
if uri then
|
||||
return "{" .. uri .. "}" .. Xml.localName(name)
|
||||
end
|
||||
return name
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " }
|
||||
local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = "	", ["\n"] = " ", ["\r"] = " " }
|
||||
|
||||
-- escape(s) / escapeAttr(s): text / attribute-value escaping
|
||||
function Xml.escape(s: string): string
|
||||
return (gsub(s, "[&<>\r]", TEXT_ESC))
|
||||
end
|
||||
function Xml.escapeAttr(s: string): string
|
||||
return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC))
|
||||
end
|
||||
|
||||
local function badName(name: any): boolean
|
||||
return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$")
|
||||
end
|
||||
|
||||
-- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...)
|
||||
function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?)
|
||||
local o: EncodeOptions = 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
|
||||
local selfClose = o.selfClose ~= false
|
||||
local out: { string } = {}
|
||||
local err: string? = nil
|
||||
local seen: { [any]: boolean } = {}
|
||||
|
||||
local write: (n: any, depth: number) -> ()
|
||||
function write(n: any, depth: number)
|
||||
if err then
|
||||
return
|
||||
end
|
||||
if type(n) == "string" then
|
||||
table.insert(out, Xml.escape(n))
|
||||
return
|
||||
end
|
||||
if type(n) ~= "table" or type(n.name) ~= "string" then
|
||||
err = "a child is not a node or a string"
|
||||
return
|
||||
end
|
||||
if seen[n] then
|
||||
err = "a node appears twice (a cycle?)"
|
||||
return
|
||||
end
|
||||
seen[n] = true
|
||||
local name = n.name
|
||||
if name == "#comment" then
|
||||
local t = n.text or ""
|
||||
if find(t, "--", 1, true) or sub(t, -1) == "-" then
|
||||
err = "comment text contains '--'"
|
||||
return
|
||||
end
|
||||
table.insert(out, "<!--" .. t .. "-->")
|
||||
elseif name == "#cdata" then
|
||||
table.insert(out, "<![CDATA[" .. gsub(n.text or "", "]]>", "]]]]><![CDATA[>") .. "]]>")
|
||||
elseif name == "#pi" then
|
||||
if badName(n.target) or find(n.text or "", "?>", 1, true) then
|
||||
err = "bad processing instruction"
|
||||
return
|
||||
end
|
||||
table.insert(out, "<?" .. n.target .. (if n.text and n.text ~= "" then " " .. n.text else "") .. "?>")
|
||||
elseif name == "#doctype" then
|
||||
table.insert(out, "<!DOCTYPE" .. (n.text or "") .. ">")
|
||||
elseif name == "#document" then
|
||||
for i, ch in n.children do
|
||||
if i > 1 and ind then
|
||||
table.insert(out, "\n")
|
||||
end
|
||||
write(ch, 0)
|
||||
end
|
||||
else
|
||||
if badName(name) then
|
||||
err = "bad element name " .. tostring(name)
|
||||
return
|
||||
end
|
||||
table.insert(out, "<" .. name)
|
||||
local attrs = n.attrs or {}
|
||||
for _, k in Types.keys(attrs) do
|
||||
local v = attrs[k]
|
||||
if badName(k) then
|
||||
err = "bad attribute name " .. tostring(k)
|
||||
return
|
||||
end
|
||||
if type(v) == "number" or type(v) == "boolean" then
|
||||
v = tostring(v)
|
||||
elseif type(v) ~= "string" then
|
||||
err = "attribute " .. k .. " is not a string"
|
||||
return
|
||||
end
|
||||
table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"')
|
||||
end
|
||||
local ch = n.children or {}
|
||||
if #ch == 0 then
|
||||
table.insert(out, if selfClose then "/>" else "></" .. name .. ">")
|
||||
return
|
||||
end
|
||||
table.insert(out, ">")
|
||||
local pretty = ind ~= nil
|
||||
if pretty then
|
||||
for _, c in ch do
|
||||
if type(c) == "string" or c.name == "#cdata" then
|
||||
pretty = false
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, c in ch do
|
||||
if pretty then
|
||||
table.insert(out, "\n" .. string.rep(ind :: string, depth + 1))
|
||||
end
|
||||
write(c, depth + 1)
|
||||
end
|
||||
if pretty then
|
||||
table.insert(out, "\n" .. string.rep(ind :: string, depth))
|
||||
end
|
||||
table.insert(out, "</" .. name .. ">")
|
||||
end
|
||||
end
|
||||
|
||||
local decl = o.declaration
|
||||
if decl == nil then
|
||||
decl = node.name == "#document"
|
||||
end
|
||||
if decl then
|
||||
local d: any = node.declaration or {}
|
||||
table.insert(out, '<?xml version="' .. (d.version or "1.0") .. '" encoding="UTF-8"' .. (if d.standalone then ' standalone="' .. d.standalone .. '"' else "") .. "?>")
|
||||
table.insert(out, "\n")
|
||||
end
|
||||
if node.name == "#document" and node.doctype then
|
||||
local dt: any = node.doctype
|
||||
local raw = dt.raw
|
||||
if raw == nil then
|
||||
raw = " " .. (dt.name or (if node.root then node.root.name else "root"))
|
||||
if dt.publicId then
|
||||
raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"'
|
||||
elseif dt.systemId then
|
||||
raw ..= ' SYSTEM "' .. dt.systemId .. '"'
|
||||
end
|
||||
end
|
||||
table.insert(out, "<!DOCTYPE" .. raw .. ">\n")
|
||||
end
|
||||
write(node, 0)
|
||||
if err then
|
||||
return nil, Err.new(Err.ARG, err)
|
||||
end
|
||||
if ind and node.name == "#document" then
|
||||
table.insert(out, "\n")
|
||||
end
|
||||
return table.concat(out), nil
|
||||
end
|
||||
|
||||
return Xml
|
||||
@@ -0,0 +1,607 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil,
|
||||
-- message, offset.
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Codec = {}
|
||||
|
||||
local TWO32 = 4294967296
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ value types
|
||||
local TaggedMeta = { __tostring = function(t: any): string
|
||||
return "cbor.tag(" .. t.tag .. ")"
|
||||
end }
|
||||
local SimpleMeta = { __tostring = function(s: any): string
|
||||
return "cbor.simple(" .. s.value .. ")"
|
||||
end }
|
||||
-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret
|
||||
function Codec.tagged(tag: number, value: any): { tag: number, value: any }
|
||||
return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any
|
||||
end
|
||||
function Codec.isTagged(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == TaggedMeta
|
||||
end
|
||||
-- simple(n) -> an unassigned simple value (0..19, 32..255)
|
||||
function Codec.simple(n: number): { value: number }
|
||||
return setmetatable({ value = n }, SimpleMeta) :: any
|
||||
end
|
||||
function Codec.isSimple(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == SimpleMeta
|
||||
end
|
||||
Codec.undefined = table.freeze(setmetatable({}, { __tostring = function()
|
||||
return "undefined"
|
||||
end }))
|
||||
|
||||
-- decimal text of a big-endian unsigned byte string (any length)
|
||||
local function bigText(s: string): string
|
||||
local limbs = {} -- base 1e7, little-endian
|
||||
for i = 1, #s do
|
||||
local carry = string.byte(s, i)
|
||||
for k = 1, #limbs do
|
||||
local v = limbs[k] * 256 + carry
|
||||
limbs[k] = v % 10000000
|
||||
carry = v // 10000000
|
||||
end
|
||||
while carry > 0 do
|
||||
table.insert(limbs, carry % 10000000)
|
||||
carry //= 10000000
|
||||
end
|
||||
end
|
||||
if #limbs == 0 then
|
||||
return "0"
|
||||
end
|
||||
local out = { string.format("%d", limbs[#limbs]) }
|
||||
for k = #limbs - 1, 1, -1 do
|
||||
table.insert(out, string.format("%07d", limbs[k]))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
-- text + 1 for a decimal string
|
||||
local function incText(s: string): string
|
||||
local digits = table.create(#s)
|
||||
for i = 1, #s do
|
||||
digits[i] = string.byte(s, i) - 48
|
||||
end
|
||||
local i = #digits
|
||||
while i >= 1 do
|
||||
if digits[i] < 9 then
|
||||
digits[i] += 1
|
||||
break
|
||||
end
|
||||
digits[i] = 0
|
||||
i -= 1
|
||||
end
|
||||
local out = table.create(#digits)
|
||||
for k, d in digits do
|
||||
out[k] = string.char(48 + d)
|
||||
end
|
||||
return (if i == 0 then "1" else "") .. table.concat(out)
|
||||
end
|
||||
|
||||
export type DecodeOptions = {
|
||||
bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text
|
||||
null: any?, -- the value for null (default Types.null)
|
||||
undefined: any?, -- the value for undefined (default Codec.undefined)
|
||||
maxDepth: number?, -- default 512
|
||||
dates: boolean?, -- tags 0 / 1 as Types.Date (default true)
|
||||
}
|
||||
|
||||
type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean }
|
||||
|
||||
local BREAK = {} -- the 0xFF stop code, inside indefinite items
|
||||
|
||||
-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31)
|
||||
local function arg(st: St, ai: number): (number?, string?, string?)
|
||||
local r = st.r
|
||||
if ai < 24 then
|
||||
return ai, nil, nil
|
||||
elseif ai == 24 then
|
||||
return r:u8(), nil, nil
|
||||
elseif ai == 25 then
|
||||
return r:u16be(), nil, nil
|
||||
elseif ai == 26 then
|
||||
return r:u32be(), nil, nil
|
||||
elseif ai == 27 then
|
||||
local hi, lo = r:u32be(), r:u32be()
|
||||
if st.big and hi >= 0x200000 then
|
||||
return hi * TWO32 + lo, bigText(string.char(hi // 16777216, (hi // 65536) % 256, (hi // 256) % 256, hi % 256, lo // 16777216, (lo // 65536) % 256, (lo // 256) % 256, lo % 256)), nil
|
||||
end
|
||||
return hi * TWO32 + lo, nil, nil
|
||||
elseif ai == 31 then
|
||||
return nil, nil, nil
|
||||
end
|
||||
return nil, nil, "reserved additional information " .. ai
|
||||
end
|
||||
|
||||
local item: (st: St, depth: number) -> (any, string?)
|
||||
|
||||
local function chunks(st: St, major: number, depth: number): (string?, string?)
|
||||
local parts = {}
|
||||
while true do
|
||||
local r = st.r
|
||||
local ib = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if ib == 0xFF then
|
||||
return table.concat(parts), nil
|
||||
end
|
||||
if ib // 32 ~= major then
|
||||
return nil, "bad chunk in an indefinite string"
|
||||
end
|
||||
local n, _, e = arg(st, ib % 32)
|
||||
if e or n == nil then
|
||||
return nil, e or "nested indefinite string"
|
||||
end
|
||||
if r.err or not r:need(n) then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
table.insert(parts, r:string(n))
|
||||
end
|
||||
end
|
||||
|
||||
local function half(h: number): number
|
||||
local s = if h >= 32768 then -1 else 1
|
||||
local e = (h // 1024) % 32
|
||||
local m = h % 1024
|
||||
if e == 0 then
|
||||
return s * m * 2 ^ -24
|
||||
elseif e == 31 then
|
||||
return if m == 0 then s * math.huge else 0 / 0
|
||||
end
|
||||
return s * (1 + m / 1024) * 2 ^ (e - 15)
|
||||
end
|
||||
|
||||
local function tag(st: St, t: number, v: any): (any, string?)
|
||||
if t == 0 and st.dates then
|
||||
if type(v) ~= "string" then
|
||||
return nil, "tag 0 needs a text string"
|
||||
end
|
||||
local d = Types.Date.parse(v)
|
||||
if not d or not d.offset then
|
||||
return nil, "tag 0: bad date-time " .. v
|
||||
end
|
||||
return d, nil
|
||||
elseif t == 1 and st.dates then
|
||||
if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then
|
||||
return nil, "tag 1 needs a number"
|
||||
end
|
||||
return Types.Date.fromUnix(v), nil
|
||||
elseif t == 2 or t == 3 then
|
||||
if type(v) ~= "string" then
|
||||
return nil, "bignum tag needs a byte string"
|
||||
end
|
||||
local s = v :: string
|
||||
local n = 0
|
||||
for i = 1, #s do
|
||||
n = n * 256 + string.byte(s, i)
|
||||
end
|
||||
if n >= 9007199254740992 then
|
||||
-- exact text; as a number, read back from that text (correctly rounded, unlike the running sum)
|
||||
local text = bigText(s)
|
||||
if t == 3 then
|
||||
text = incText(text)
|
||||
end
|
||||
if st.big then
|
||||
return if t == 2 then text else "-" .. text, nil
|
||||
end
|
||||
local x = tonumber(text) :: number
|
||||
return if t == 2 then x else -x, nil
|
||||
end
|
||||
return if t == 2 then n else -1 - n, nil
|
||||
elseif t == 55799 then
|
||||
return v, nil
|
||||
end
|
||||
return Codec.tagged(t, v), nil
|
||||
end
|
||||
|
||||
function item(st: St, depth: number): (any, string?)
|
||||
if depth > st.maxDepth then
|
||||
return nil, "nested deeper than " .. st.maxDepth
|
||||
end
|
||||
local r = st.r
|
||||
local ib = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
local major, ai = ib // 32, ib % 32
|
||||
if major == 7 then
|
||||
if ai < 20 then
|
||||
return Codec.simple(ai), nil
|
||||
elseif ai == 20 then
|
||||
return false, nil
|
||||
elseif ai == 21 then
|
||||
return true, nil
|
||||
elseif ai == 22 then
|
||||
return st.null, nil
|
||||
elseif ai == 23 then
|
||||
return st.undef, nil
|
||||
elseif ai == 24 then
|
||||
local n = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if n < 32 then
|
||||
return nil, "bad two-byte simple value"
|
||||
end
|
||||
return Codec.simple(n), nil
|
||||
elseif ai == 25 then
|
||||
local h = r:u16be()
|
||||
return if r.err then nil else half(h), if r.err then "truncated" else nil
|
||||
elseif ai == 26 then
|
||||
local f = r:f32be()
|
||||
return if r.err then nil else f, if r.err then "truncated" else nil
|
||||
elseif ai == 27 then
|
||||
local f = r:f64be()
|
||||
return if r.err then nil else f, if r.err then "truncated" else nil
|
||||
elseif ai == 31 then
|
||||
return BREAK, nil
|
||||
end
|
||||
return nil, "reserved simple value"
|
||||
end
|
||||
local n, text, e = arg(st, ai)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if major == 0 then
|
||||
if n == nil then
|
||||
return nil, "indefinite integer"
|
||||
end
|
||||
return text or n, nil
|
||||
elseif major == 1 then
|
||||
if n == nil then
|
||||
return nil, "indefinite integer"
|
||||
end
|
||||
if text then
|
||||
return "-" .. incText(text), nil
|
||||
end
|
||||
return -1 - n, nil
|
||||
elseif major == 2 or major == 3 then
|
||||
local s: string
|
||||
if n == nil then
|
||||
local c, ce = chunks(st, major, depth)
|
||||
if not c then
|
||||
return nil, ce
|
||||
end
|
||||
s = c
|
||||
else
|
||||
if not r:need(n) then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
s = r:string(n)
|
||||
end
|
||||
if major == 2 then
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
if string.find(s, "[\128-\255]") and not utf8.len(s) then
|
||||
return nil, "invalid UTF-8 in a text string"
|
||||
end
|
||||
return s, nil
|
||||
elseif major == 4 then
|
||||
if n == nil then
|
||||
local t = {}
|
||||
while true do
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return t, nil
|
||||
end
|
||||
table.insert(t, v)
|
||||
end
|
||||
end
|
||||
if n > r:remaining() then
|
||||
return nil, "array count past the end"
|
||||
end
|
||||
local t = table.create(n)
|
||||
for k = 1, n do
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
t[k] = v
|
||||
end
|
||||
return t, nil
|
||||
elseif major == 5 then
|
||||
if n ~= nil and n * 2 > r:remaining() then
|
||||
return nil, "map count past the end"
|
||||
end
|
||||
local t = {}
|
||||
local order = {}
|
||||
local k = 0
|
||||
while n == nil or k < n do
|
||||
k += 1
|
||||
local key, ke = item(st, depth + 1)
|
||||
if ke then
|
||||
return nil, ke
|
||||
end
|
||||
if key == BREAK then
|
||||
if n == nil then
|
||||
break
|
||||
end
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
if key ~= key then
|
||||
return nil, "NaN map key"
|
||||
end
|
||||
if t[key] == nil then
|
||||
table.insert(order, key)
|
||||
end
|
||||
t[key] = v
|
||||
end
|
||||
return Types.object(t, order), nil
|
||||
else -- 6: tag
|
||||
if n == nil then
|
||||
return nil, "indefinite tag"
|
||||
end
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
-- bignum content arrives as a buffer: hand the tag its bytes
|
||||
if (n == 2 or n == 3) and type(v) == "buffer" then
|
||||
return tag(st, n, buffer.tostring(v))
|
||||
end
|
||||
return tag(st, n, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it)
|
||||
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local st: St = {
|
||||
r = r,
|
||||
big = o.bigInts == "string",
|
||||
null = if o.null ~= nil then o.null else Types.null,
|
||||
undef = if o.undefined ~= nil then o.undefined else Codec.undefined,
|
||||
maxDepth = o.maxDepth or 512,
|
||||
dates = o.dates ~= false,
|
||||
}
|
||||
local v, e = item(st, 0)
|
||||
if e then
|
||||
return nil, e, r.pos - r.base
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break", r.pos - r.base - 1
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
export type EncodeOptions = {
|
||||
compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false)
|
||||
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
|
||||
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
|
||||
dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds
|
||||
maxDepth: number?, -- default 512 (also catches cycles)
|
||||
}
|
||||
|
||||
type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? }
|
||||
|
||||
local function head(w: Bytes.Writer, major: number, n: number)
|
||||
local m = major * 32
|
||||
if n < 24 then
|
||||
w:u8(m + n)
|
||||
elseif n < 256 then
|
||||
w:u8(m + 24)
|
||||
w:u8(n)
|
||||
elseif n < 65536 then
|
||||
w:u8(m + 25)
|
||||
w:u16be(n)
|
||||
elseif n < TWO32 then
|
||||
w:u8(m + 26)
|
||||
w:u32be(n)
|
||||
elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1
|
||||
w:u8(m + 27)
|
||||
w:u32be(0xFFFFFFFF)
|
||||
w:u32be(0xFFFFFFFF)
|
||||
else
|
||||
w:u8(m + 27)
|
||||
w:u64be(n)
|
||||
end
|
||||
end
|
||||
|
||||
-- the half-float bits of x when x is exactly representable, else nil
|
||||
local function toHalf(x: number): number?
|
||||
if x ~= x then
|
||||
return 0x7E00
|
||||
end
|
||||
local sign = if x < 0 or (x == 0 and 1 / x < 0) then 0x8000 else 0
|
||||
local a = math.abs(x)
|
||||
if a == math.huge then
|
||||
return sign + 0x7C00
|
||||
end
|
||||
if a == 0 then
|
||||
return sign
|
||||
end
|
||||
local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1
|
||||
local exp = e - 1 + 15
|
||||
if exp >= 31 then
|
||||
return nil
|
||||
end
|
||||
if exp <= 0 then -- subnormal: a = mant * 2^-24
|
||||
local mant = a / 2 ^ -24
|
||||
if mant ~= math.floor(mant) or mant >= 1024 then
|
||||
return nil
|
||||
end
|
||||
return sign + mant
|
||||
end
|
||||
local frac = (m * 2 - 1) * 1024
|
||||
if frac ~= math.floor(frac) then
|
||||
return nil
|
||||
end
|
||||
return sign + exp * 1024 + frac
|
||||
end
|
||||
Codec.toHalf = toHalf
|
||||
|
||||
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
|
||||
|
||||
local function isArray(t: any, emptyMap: boolean): boolean
|
||||
if Types.isObject(t) then
|
||||
return false
|
||||
end
|
||||
local n = #t
|
||||
if n == 0 then
|
||||
return next(t) == nil and not emptyMap
|
||||
end
|
||||
local c = 0
|
||||
for _ in next, t do
|
||||
c += 1
|
||||
end
|
||||
return c == n
|
||||
end
|
||||
|
||||
local scratch = buffer.create(8)
|
||||
|
||||
local function enc(st: ESt, v: any, depth: number): boolean
|
||||
local w = st.w
|
||||
local tv = type(v)
|
||||
if v == nil or v == Types.null then
|
||||
w:u8(0xF6)
|
||||
elseif v == Codec.undefined then
|
||||
w:u8(0xF7)
|
||||
elseif tv == "boolean" then
|
||||
w:u8(if v then 0xF5 else 0xF4)
|
||||
elseif tv == "number" then
|
||||
if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then
|
||||
if v >= 0 then
|
||||
head(w, 0, v)
|
||||
else
|
||||
head(w, 1, -1 - v)
|
||||
end
|
||||
else
|
||||
local h = if st.compact then toHalf(v) else nil
|
||||
if h then
|
||||
w:u8(0xF9)
|
||||
w:u16be(h)
|
||||
else
|
||||
buffer.writef32(scratch, 0, v)
|
||||
if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then
|
||||
w:u8(0xFA)
|
||||
w:f32be(v)
|
||||
else
|
||||
w:u8(0xFB)
|
||||
w:f64be(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif tv == "string" then
|
||||
head(w, 3, #v)
|
||||
w:string(v)
|
||||
elseif tv == "buffer" then
|
||||
head(w, 2, buffer.len(v))
|
||||
w:bytes(v)
|
||||
elseif tv == "table" then
|
||||
if depth >= st.maxDepth then
|
||||
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
|
||||
return false
|
||||
end
|
||||
if Codec.isTagged(v) then
|
||||
if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then
|
||||
st.err = "bad tag number"
|
||||
return false
|
||||
end
|
||||
head(w, 6, v.tag)
|
||||
return enc(st, v.value, depth + 1)
|
||||
elseif Codec.isSimple(v) then
|
||||
local n = v.value
|
||||
if n < 20 then
|
||||
w:u8(0xE0 + n)
|
||||
elseif n >= 32 and n < 256 then
|
||||
w:u8(0xF8)
|
||||
w:u8(n)
|
||||
else
|
||||
st.err = "bad simple value " .. tostring(n)
|
||||
return false
|
||||
end
|
||||
elseif Types.Date.is(v) then
|
||||
if st.epoch then
|
||||
w:u8(0xC1)
|
||||
return enc(st, Types.Date.toUnix(v), depth + 1)
|
||||
end
|
||||
w:u8(0xC0)
|
||||
local s = tostring(v)
|
||||
head(w, 3, #s)
|
||||
w:string(s)
|
||||
elseif isArray(v, st.emptyMap) then
|
||||
local n = #v
|
||||
head(w, 4, n)
|
||||
for k = 1, n do
|
||||
if not enc(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
else
|
||||
local keys: { any }
|
||||
if Types.isObject(v) then
|
||||
keys = Types.keys(v)
|
||||
else
|
||||
keys = {}
|
||||
for k in next, v do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
if st.sort then
|
||||
table.sort(keys, keyLess)
|
||||
end
|
||||
end
|
||||
head(w, 5, #keys)
|
||||
for _, k in keys do
|
||||
if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
st.err = "cannot encode a " .. tv
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- encode(v, opts) -> buffer | nil, message
|
||||
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local st: ESt = {
|
||||
w = Bytes.writer(256),
|
||||
compact = o.compactFloats == true,
|
||||
sort = o.sortKeys ~= false,
|
||||
emptyMap = o.emptyTable == "map",
|
||||
epoch = o.dates == "epoch",
|
||||
maxDepth = o.maxDepth or 512,
|
||||
err = nil,
|
||||
}
|
||||
if not enc(st, v, 0) then
|
||||
return nil, st.err
|
||||
end
|
||||
return st.w:finish(), nil
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,100 @@
|
||||
--!strict
|
||||
-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half /
|
||||
-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text,
|
||||
-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n),
|
||||
-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences
|
||||
-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats,
|
||||
-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Codec = require("@formats/data/cbor/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Cbor = {
|
||||
name = "cbor",
|
||||
category = "data",
|
||||
extensions = { "cbor" },
|
||||
mime = { "application/cbor", "application/cbor-seq" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, binary = true, ordered = true, tags = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Codec.DecodeOptions & {
|
||||
all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item)
|
||||
}
|
||||
export type EncodeOptions = Codec.EncodeOptions & {
|
||||
all: boolean?, -- the value is an array of items, written as a sequence
|
||||
selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Cbor.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(3) == "\217\217\247" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function codeOf(e: string): string
|
||||
if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then
|
||||
return Err.TRUNCATED
|
||||
elseif string.find(e, "nested deeper", 1, true) then
|
||||
return Err.LIMIT
|
||||
end
|
||||
return Err.CORRUPT
|
||||
end
|
||||
|
||||
function Cbor.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
if o.all then
|
||||
local out = {}
|
||||
while not r:eof() do
|
||||
local v, e, at = Codec.decode(r, o)
|
||||
if e then
|
||||
return nil, Err.new(codeOf(e), e, at)
|
||||
end
|
||||
table.insert(out, v)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local v, e, at = Codec.decode(r, o)
|
||||
if e then
|
||||
return nil, Err.new(codeOf(e), e, at)
|
||||
end
|
||||
if not r:eof() then
|
||||
return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local w = Bytes.writer()
|
||||
if opts and opts.selfDescribe then
|
||||
w:string("\217\217\247")
|
||||
end
|
||||
local items = { value }
|
||||
if opts and opts.all then
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "all: expected an array of items")
|
||||
end
|
||||
items = value
|
||||
end
|
||||
for _, v in items do
|
||||
local b, e = Codec.encode(v, opts)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, e or "cannot encode")
|
||||
end
|
||||
w:bytes(b)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag
|
||||
Cbor.isTagged = Codec.isTagged
|
||||
Cbor.simple = Codec.simple -- simple(n) -> a simple value
|
||||
Cbor.isSimple = Codec.isSimple
|
||||
Cbor.undefined = Codec.undefined
|
||||
|
||||
return Cbor
|
||||
@@ -0,0 +1,316 @@
|
||||
--!strict
|
||||
-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any
|
||||
-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded
|
||||
-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column
|
||||
-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only
|
||||
-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters
|
||||
-- other than the doubled quote, multi-byte delimiters.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Csv = {
|
||||
name = "csv",
|
||||
category = "data",
|
||||
extensions = { "csv", "tsv" },
|
||||
mime = { "text/csv", "text/tab-separated-values" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, header = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |)
|
||||
quote: string?, -- the quote byte (default '"')
|
||||
header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays)
|
||||
numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string)
|
||||
maxRows: number?, -- refuse more rows (default unlimited)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
delimiter: string?, -- default ","
|
||||
quote: string?, -- default '"'
|
||||
newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv)
|
||||
quoteAll: boolean?, -- quote every field (default false: only those that need it)
|
||||
columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order)
|
||||
header: boolean?, -- keyed rows: write the header row (default true)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub
|
||||
|
||||
local function patEscape(c: string): string
|
||||
return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0"))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Csv.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(1024)
|
||||
if find(head, "%z") then
|
||||
return 0
|
||||
end
|
||||
local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)")
|
||||
if not l1 or l1 == "" then
|
||||
return 0
|
||||
end
|
||||
for _, d in { ",", "\t", ";" } do
|
||||
local _, c1 = gsub(l1, d, "")
|
||||
local _, c2 = gsub(l2, d, "")
|
||||
if c1 > 0 and c1 == c2 then
|
||||
return 0.15
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function guess(s: string, q: string): string
|
||||
local line = string.match(s, "^[^\r\n]*") or ""
|
||||
line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "")
|
||||
local best, bestN = ",", 0
|
||||
for _, d in { ",", ";", "\t", "|" } do
|
||||
local _, n = gsub(line, patEscape(d), "")
|
||||
if n > bestN then
|
||||
best, bestN = d, n
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- rows(s, opts) -> { { string } } | nil, Err
|
||||
function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local q = o.quote or '"'
|
||||
local d = o.delimiter or ","
|
||||
if d == "auto" then
|
||||
d = guess(s, q)
|
||||
end
|
||||
if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then
|
||||
return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)")
|
||||
end
|
||||
local qb, db = byte(q), byte(d)
|
||||
local stop = "[" .. patEscape(d) .. "\r\n]"
|
||||
local maxRows = o.maxRows or math.huge
|
||||
local rows: { { string } } = {}
|
||||
local row: { string } = {}
|
||||
local n = #s
|
||||
local i = 1
|
||||
local rowEmpty = true -- the current line has no field text yet (blank lines are skipped)
|
||||
while true do
|
||||
local c = byte(s, i)
|
||||
local field: string
|
||||
if c == qb then
|
||||
local k = i + 1
|
||||
local parts = {}
|
||||
while true do
|
||||
local j = find(s, q, k, true)
|
||||
if not j then
|
||||
return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1)
|
||||
end
|
||||
if byte(s, j + 1) == qb then
|
||||
table.insert(parts, sub(s, k, j))
|
||||
k = j + 2
|
||||
else
|
||||
table.insert(parts, sub(s, k, j - 1))
|
||||
i = j + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
-- text after the closing quote up to the delimiter is kept (Python's lenient reading)
|
||||
local e = find(s, stop, i) or (n + 1)
|
||||
if e > i then
|
||||
table.insert(parts, sub(s, i, e - 1))
|
||||
end
|
||||
i = e
|
||||
field = table.concat(parts)
|
||||
rowEmpty = false
|
||||
else
|
||||
local e = find(s, stop, i) or (n + 1)
|
||||
field = sub(s, i, e - 1)
|
||||
if e > i then
|
||||
rowEmpty = false
|
||||
end
|
||||
i = e
|
||||
end
|
||||
table.insert(row, field)
|
||||
c = byte(s, i)
|
||||
if c == db then
|
||||
rowEmpty = false
|
||||
i += 1
|
||||
else
|
||||
-- end of the row: CRLF / LF / CR / end of data
|
||||
if c == 13 and byte(s, i + 1) == 10 then
|
||||
i += 2
|
||||
elseif c ~= nil then
|
||||
i += 1
|
||||
end
|
||||
if not rowEmpty then
|
||||
table.insert(rows, row)
|
||||
if #rows > maxRows then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows")
|
||||
end
|
||||
end
|
||||
row = {}
|
||||
rowEmpty = true
|
||||
if i > n then
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
return rows, nil
|
||||
end
|
||||
|
||||
local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$"
|
||||
local function convert(v: string): any
|
||||
if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then
|
||||
local x = tonumber(v)
|
||||
if x then
|
||||
return x
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
if sub(s, 1, 3) == "\239\187\191" then
|
||||
s = sub(s, 4)
|
||||
end
|
||||
local rows, err = Csv.parse(s, opts)
|
||||
if not rows then
|
||||
return nil, err
|
||||
end
|
||||
local o: DecodeOptions = opts or {}
|
||||
if o.numbers then
|
||||
for _, row in rows do
|
||||
for k, v in row do
|
||||
row[k] = convert(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
if not o.header then
|
||||
return rows, nil
|
||||
end
|
||||
local names = rows[1] or {}
|
||||
local out = table.create(math.max(#rows - 1, 0))
|
||||
for k = 2, #rows do
|
||||
local row = rows[k]
|
||||
local obj = Types.object()
|
||||
for c, name in names do
|
||||
if row[c] ~= nil then
|
||||
Types.set(obj, tostring(name), row[c])
|
||||
end
|
||||
end
|
||||
out[k - 1] = obj
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function text(v: any): (string?, string?)
|
||||
local tv = type(v)
|
||||
if tv == "string" then
|
||||
return v, nil
|
||||
elseif tv == "number" then
|
||||
local s = Json.number(v)
|
||||
if not s then
|
||||
return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil
|
||||
end
|
||||
return s, nil
|
||||
elseif tv == "boolean" then
|
||||
return if v then "true" else "false", nil
|
||||
elseif v == nil or v == Types.null then
|
||||
return "", nil
|
||||
elseif tv == "table" and Types.Date.is(v) then
|
||||
return tostring(v), nil
|
||||
end
|
||||
return nil, "cannot write a " .. tv .. " as a field"
|
||||
end
|
||||
|
||||
local function isArray(t: any): boolean
|
||||
if type(t) ~= "table" or Types.isObject(t) then
|
||||
return false
|
||||
end
|
||||
local n = #t
|
||||
return n > 0 or next(t) == nil
|
||||
end
|
||||
|
||||
function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n"
|
||||
if #d ~= 1 or #q ~= 1 or d == q then
|
||||
return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes")
|
||||
end
|
||||
if type(rows) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "expected an array of rows")
|
||||
end
|
||||
local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]"
|
||||
local qq = q .. q
|
||||
local out: { string } = {}
|
||||
local function writeRow(fields: { any }, count: number): Err.Err?
|
||||
local parts = table.create(count)
|
||||
for k = 1, count do
|
||||
local s, e = text(fields[k])
|
||||
if not s then
|
||||
return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e))
|
||||
end
|
||||
if o.quoteAll or find(s, special) or (count == 1 and s == "") then
|
||||
s = q .. gsub(s, patEscape(q), qq) .. q
|
||||
end
|
||||
parts[k] = s
|
||||
end
|
||||
table.insert(out, table.concat(parts, d) .. nl)
|
||||
return nil
|
||||
end
|
||||
local keyed = rows[1] ~= nil and not isArray(rows[1])
|
||||
if keyed then
|
||||
local cols = o.columns
|
||||
if not cols then
|
||||
local seen, list = {}, {}
|
||||
for _, row in rows do
|
||||
if type(row) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "rows must be tables")
|
||||
end
|
||||
for _, k in Types.keys(row) do
|
||||
if not seen[k] then
|
||||
seen[k] = true
|
||||
table.insert(list, k)
|
||||
end
|
||||
end
|
||||
end
|
||||
cols = list
|
||||
end
|
||||
local cl = cols :: { any }
|
||||
if o.header ~= false then
|
||||
local e = writeRow(cl, #cl)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
for _, row in rows do
|
||||
local fields = table.create(#cl)
|
||||
for k, name in cl do
|
||||
fields[k] = row[name]
|
||||
end
|
||||
local e = writeRow(fields, #cl)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
else
|
||||
for _, row in rows do
|
||||
if type(row) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "rows must be arrays of fields")
|
||||
end
|
||||
local e = writeRow(row, #row)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
end
|
||||
return buffer.fromstring(table.concat(out)), nil
|
||||
end
|
||||
|
||||
return Csv
|
||||
@@ -0,0 +1,250 @@
|
||||
--!strict
|
||||
-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code.
|
||||
-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value,
|
||||
-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at
|
||||
-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a
|
||||
-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level
|
||||
-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested
|
||||
-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ini = {
|
||||
name = "ini",
|
||||
category = "data",
|
||||
extensions = { "ini", "cfg", "conf", "inf", "desktop" },
|
||||
mime = { "text/plain" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, ordered = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser)
|
||||
allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error)
|
||||
types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans
|
||||
strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
delimiter: string?, -- default " = "
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ini.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(512)
|
||||
if string.find(head, "%z") then
|
||||
return 0
|
||||
end
|
||||
local first = string.match(head, "^[%s]*([^\r\n]*)")
|
||||
while first and string.match(first, "^[;#]") do
|
||||
head = string.match(head, "^[^\n]*\n(.*)$") or ""
|
||||
first = string.match(head, "^[%s]*([^\r\n]*)")
|
||||
end
|
||||
if first and string.match(first, "^%[[^%]]+%]%s*$") then
|
||||
return 0.2
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local BOOLS: { [string]: boolean } = { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false }
|
||||
|
||||
local function typed(v: any): any
|
||||
if type(v) ~= "string" then
|
||||
return v
|
||||
end
|
||||
local b = BOOLS[string.lower(v)]
|
||||
if b ~= nil then
|
||||
return b
|
||||
end
|
||||
if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then
|
||||
local n = tonumber(v)
|
||||
if n then
|
||||
return n
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
if string.sub(s, 1, 3) == "\239\187\191" then
|
||||
s = string.sub(s, 4)
|
||||
end
|
||||
local root = Types.object()
|
||||
local cur = root
|
||||
local lastKey: string? = nil
|
||||
local lastIndent = 0
|
||||
local lastTable: any = nil
|
||||
local seenKeys: { [any]: { [string]: boolean } } = {}
|
||||
local pos = 1
|
||||
local lineStart = 0
|
||||
for line in string.gmatch(s .. "\n", "([^\n]*)\n") do
|
||||
lineStart = pos - 1
|
||||
pos += #line + 1
|
||||
line = string.gsub(line, "\r$", "")
|
||||
local indent = #(string.match(line, "^[ \t]*") :: string)
|
||||
local trimmed = string.match(line, "^%s*(.-)%s*$") :: string
|
||||
if trimmed == "" then
|
||||
lastKey = nil
|
||||
elseif string.match(trimmed, "^[;#]") then
|
||||
-- a comment line (configparser: also when indented); it does not end a continuation
|
||||
elseif lastKey and indent > lastIndent then
|
||||
-- continuation of the previous value
|
||||
local v = trimmed
|
||||
if o.inlineComments then
|
||||
v = string.match(v, "^(.-)%s+[;#]") or v
|
||||
end
|
||||
local prev = lastTable[lastKey]
|
||||
lastTable[lastKey] = (if type(prev) == "string" then prev else "") .. "\n" .. v
|
||||
elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then
|
||||
local name = string.match(trimmed, "^%[(.*)%]") :: string
|
||||
local existing = root[name]
|
||||
if existing ~= nil and type(existing) ~= "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart)
|
||||
end
|
||||
if existing and o.strict then
|
||||
return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart)
|
||||
end
|
||||
if not existing then
|
||||
existing = Types.object()
|
||||
Types.set(root, name, existing)
|
||||
end
|
||||
cur = existing
|
||||
lastKey = nil
|
||||
else
|
||||
local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$")
|
||||
if not key then
|
||||
if not o.allowNoValue then
|
||||
return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart)
|
||||
end
|
||||
key, value = trimmed, true :: any
|
||||
end
|
||||
if key == "" then
|
||||
return nil, Err.new(Err.CORRUPT, "empty key", lineStart)
|
||||
end
|
||||
if o.inlineComments and type(value) == "string" then
|
||||
value = string.match(value, "^(.-)%s+[;#]") or (if string.match(value, "^[;#]") then "" else value)
|
||||
end
|
||||
local seen = seenKeys[cur]
|
||||
if not seen then
|
||||
seen = {}
|
||||
seenKeys[cur] = seen
|
||||
end
|
||||
if seen[key :: string] and o.strict then
|
||||
return nil, Err.new(Err.CORRUPT, "duplicate key " .. key, lineStart)
|
||||
end
|
||||
seen[key :: string] = true
|
||||
if cur == root and type(root[key]) == "table" then
|
||||
return nil, Err.new(Err.CORRUPT, "top-level key " .. key .. " has the name of a section", lineStart)
|
||||
end
|
||||
Types.set(cur, key, value)
|
||||
lastKey, lastIndent, lastTable = key, indent, cur
|
||||
end
|
||||
end
|
||||
if o.types then
|
||||
for _, k in Types.keys(root) do
|
||||
local v = root[k]
|
||||
if type(v) == "table" then
|
||||
for _, k2 in Types.keys(v) do
|
||||
v[k2] = typed(v[k2])
|
||||
end
|
||||
else
|
||||
root[k] = typed(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
return root, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function text(v: any): string?
|
||||
local tv = type(v)
|
||||
if tv == "string" then
|
||||
return (string.gsub(v, "\n", "\n\t"))
|
||||
elseif tv == "number" then
|
||||
return Json.number(v) or tostring(v)
|
||||
elseif tv == "boolean" then
|
||||
return if v then "true" else "false"
|
||||
elseif v == Types.null then
|
||||
return ""
|
||||
elseif tv == "table" and Types.Date.is(v) then
|
||||
return tostring(v)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Ini.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "expected a table of sections")
|
||||
end
|
||||
local delim = (opts and opts.delimiter) or " = "
|
||||
local out: { string } = {}
|
||||
local err: string? = nil
|
||||
local function keyOk(k: any): boolean
|
||||
if type(k) ~= "string" and type(k) ~= "number" then
|
||||
err = "keys must be strings"
|
||||
return false
|
||||
end
|
||||
local ks = tostring(k)
|
||||
if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then
|
||||
err = "key " .. string.format("%q", ks) .. " cannot be written"
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
local function pairsOf(t: any, prefix: string, depth: number): boolean
|
||||
if depth > 32 then
|
||||
err = "sections nested too deeply (a cycle?)"
|
||||
return false
|
||||
end
|
||||
local subs = {}
|
||||
local lines = {}
|
||||
for _, k in Types.keys(t) do
|
||||
local v = t[k]
|
||||
if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then
|
||||
table.insert(subs, k)
|
||||
else
|
||||
if not keyOk(k) then
|
||||
return false
|
||||
end
|
||||
local s = text(v)
|
||||
if not s then
|
||||
err = "cannot write a " .. type(v) .. " value"
|
||||
return false
|
||||
end
|
||||
table.insert(lines, tostring(k) .. delim .. s .. "\n")
|
||||
end
|
||||
end
|
||||
if prefix ~= "" then
|
||||
table.insert(out, "[" .. prefix .. "]\n")
|
||||
table.move(lines, 1, #lines, #out + 1, out)
|
||||
table.insert(out, "\n")
|
||||
elseif #lines > 0 then
|
||||
table.move(lines, 1, #lines, #out + 1, out)
|
||||
table.insert(out, "\n")
|
||||
end
|
||||
for _, k in subs do
|
||||
local name = tostring(k)
|
||||
if string.find(name, "[\r\n%]]") then
|
||||
err = "section name " .. string.format("%q", name) .. " cannot be written"
|
||||
return false
|
||||
end
|
||||
if not pairsOf(t[k], if prefix == "" then name else prefix .. "." .. name, depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if not pairsOf(value, "", 0) then
|
||||
return nil, Err.new(Err.ARG, err or "cannot encode")
|
||||
end
|
||||
return buffer.fromstring(table.concat(out)), nil
|
||||
end
|
||||
|
||||
return Ini
|
||||
@@ -0,0 +1,93 @@
|
||||
--!strict
|
||||
-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/Json (which see for the value mapping and options).
|
||||
-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or
|
||||
-- pretty. JSON Lines through codecs/Json.lines. Not supported: JSON5 / comments / trailing commas.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local JsonFormat = {
|
||||
name = "json",
|
||||
category = "data",
|
||||
extensions = { "json", "jsonl", "ndjson", "geojson" },
|
||||
mime = { "application/json", "application/x-ndjson" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, ordered = true, streaming = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Json.DecodeOptions & {
|
||||
lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value)
|
||||
}
|
||||
export type EncodeOptions = Json.EncodeOptions & {
|
||||
lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function JsonFormat.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(64)
|
||||
if string.sub(head, 1, 3) == "\239\187\191" then
|
||||
head = string.sub(head, 4)
|
||||
end
|
||||
local first = string.match(head, "^[ \t\r\n]*(.)")
|
||||
if first == "{" then
|
||||
local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)")
|
||||
return if nxt == nil or nxt == '"' or nxt == "}" then 0.6 else 0.1
|
||||
elseif first == "[" then
|
||||
-- past any nested '[': a JSON value must start (TOML / INI "[section]" and "[[table]]" do not)
|
||||
local nxt = string.match(head, "^[ \t\r\n]*[%[ \t\r\n]*(.)")
|
||||
if nxt == nil or string.find('{"-0123456789tfn]', nxt, 1, true) then
|
||||
return 0.3
|
||||
end
|
||||
return 0
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function JsonFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
if opts and opts.lines then
|
||||
local out = {}
|
||||
for _, v, err in Json.lines(s, opts) do
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(out, v)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
return Json.decode(s, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function JsonFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if opts and opts.lines then
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "lines: expected an array of values")
|
||||
end
|
||||
local o = table.clone(opts) :: any
|
||||
o.indent = nil
|
||||
local parts = {}
|
||||
for i, v in value do
|
||||
local s, err = Json.encode(v, o)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
parts[i] = s .. "\n"
|
||||
end
|
||||
return buffer.fromstring(table.concat(parts)), nil
|
||||
end
|
||||
local s, err = Json.encode(value, opts)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
if opts and opts.indent then
|
||||
s ..= "\n"
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return JsonFormat
|
||||
@@ -0,0 +1,468 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with
|
||||
-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset.
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Codec = {}
|
||||
|
||||
local TWO32 = 4294967296
|
||||
|
||||
-- an extension value: { type = -128..127, data = buffer }
|
||||
local ExtMeta = { __tostring = function(e: any): string
|
||||
return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)"
|
||||
end }
|
||||
function Codec.ext(t: number, data: buffer): { type: number, data: buffer }
|
||||
return setmetatable({ type = t, data = data }, ExtMeta) :: any
|
||||
end
|
||||
function Codec.isExt(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == ExtMeta
|
||||
end
|
||||
|
||||
-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact
|
||||
local function u64text(hi: number, lo: number): string
|
||||
if hi == 0 then
|
||||
return string.format("%d", lo)
|
||||
end
|
||||
local digits = {}
|
||||
-- long division by 10 on four 16-bit limbs
|
||||
local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
|
||||
while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do
|
||||
local rem = 0
|
||||
for k = 1, 4 do
|
||||
local cur = rem * 65536 + l[k]
|
||||
l[k] = cur // 10
|
||||
rem = cur % 10
|
||||
end
|
||||
table.insert(digits, 1, string.char(48 + rem))
|
||||
end
|
||||
return table.concat(digits)
|
||||
end
|
||||
Codec.u64text = u64text
|
||||
|
||||
export type DecodeOptions = {
|
||||
bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text
|
||||
null: any?, -- the value for nil (default Types.null)
|
||||
maxDepth: number?, -- nesting limit (default 512)
|
||||
timestamps: boolean?, -- ext -1 as a Types.Date (default true)
|
||||
ordered: boolean?, -- maps as Types.object with key order (default true)
|
||||
}
|
||||
|
||||
type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean }
|
||||
|
||||
local function int64(st: St, signed: boolean): any
|
||||
local r = st.r
|
||||
local hi, lo = r:u32be(), r:u32be()
|
||||
if signed and hi >= 0x80000000 then
|
||||
-- negative: two's complement
|
||||
local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo
|
||||
if nlo == TWO32 then
|
||||
nlo = 0
|
||||
nhi += 1
|
||||
end
|
||||
if st.big and nhi >= 0x200000 then
|
||||
return "-" .. u64text(nhi, nlo)
|
||||
end
|
||||
return -(nhi * TWO32 + nlo)
|
||||
end
|
||||
if st.big and hi >= 0x200000 then
|
||||
return u64text(hi, lo)
|
||||
end
|
||||
return hi * TWO32 + lo
|
||||
end
|
||||
|
||||
local value: (st: St, depth: number) -> (any, string?)
|
||||
|
||||
local function ext(st: St, n: number): (any, string?)
|
||||
local r = st.r
|
||||
local t = r:i8()
|
||||
if r.err or not r:need(n) then
|
||||
return nil, "truncated ext"
|
||||
end
|
||||
if t == -1 and st.ts then
|
||||
local secs, ns = 0, 0
|
||||
if n == 4 then
|
||||
secs = r:u32be()
|
||||
elseif n == 8 then
|
||||
local hi, lo = r:u32be(), r:u32be()
|
||||
ns = hi // 4
|
||||
secs = (hi % 4) * TWO32 + lo
|
||||
elseif n == 12 then
|
||||
ns = r:u32be()
|
||||
secs = r:i64be()
|
||||
else
|
||||
return nil, "bad timestamp length"
|
||||
end
|
||||
if ns > 999999999 then
|
||||
return nil, "bad timestamp nanoseconds"
|
||||
end
|
||||
local d: any = Types.Date.fromUnix(secs)
|
||||
d.nanosecond = ns
|
||||
return d, nil
|
||||
end
|
||||
return Codec.ext(t, r:bytes(n)), nil
|
||||
end
|
||||
|
||||
local function array(st: St, n: number, depth: number): (any, string?)
|
||||
if n > st.r:remaining() then
|
||||
return nil, "array count past the end"
|
||||
end
|
||||
local t = table.create(n)
|
||||
for k = 1, n do
|
||||
local v, e = value(st, depth + 1)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
t[k] = v
|
||||
end
|
||||
return t, nil
|
||||
end
|
||||
|
||||
local function map(st: St, n: number, depth: number): (any, string?)
|
||||
if n * 2 > st.r:remaining() then
|
||||
return nil, "map count past the end"
|
||||
end
|
||||
local t = {}
|
||||
local order: { any }? = if st.ordered then table.create(n) else nil
|
||||
for _ = 1, n do
|
||||
local k, e = value(st, depth + 1)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
local v, e2 = value(st, depth + 1)
|
||||
if e2 then
|
||||
return nil, e2
|
||||
end
|
||||
if k ~= k then
|
||||
return nil, "NaN map key"
|
||||
end
|
||||
if order and t[k] == nil then
|
||||
table.insert(order, k)
|
||||
end
|
||||
t[k] = v
|
||||
end
|
||||
return Types.object(t, order or {}), nil
|
||||
end
|
||||
|
||||
function value(st: St, depth: number): (any, string?)
|
||||
if depth > st.maxDepth then
|
||||
return nil, "nested deeper than " .. st.maxDepth
|
||||
end
|
||||
local r = st.r
|
||||
local b = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if b < 0x80 then
|
||||
return b, nil
|
||||
elseif b >= 0xE0 then
|
||||
return b - 256, nil
|
||||
elseif b < 0x90 then
|
||||
return map(st, b - 0x80, depth)
|
||||
elseif b < 0xA0 then
|
||||
return array(st, b - 0x90, depth)
|
||||
elseif b < 0xC0 then
|
||||
local n = b - 0xA0
|
||||
if not r:need(n) then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
return r:string(n), nil
|
||||
elseif b == 0xC0 then
|
||||
return st.null, nil
|
||||
elseif b == 0xC2 then
|
||||
return false, nil
|
||||
elseif b == 0xC3 then
|
||||
return true, nil
|
||||
elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then
|
||||
local n = if b == 0xC4 then r:u8() elseif b == 0xC5 then r:u16be() else r:u32be()
|
||||
if r.err or not r:need(n) then
|
||||
return nil, "truncated bin"
|
||||
end
|
||||
return r:bytes(n), nil
|
||||
elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then
|
||||
local n = if b == 0xC7 then r:u8() elseif b == 0xC8 then r:u16be() else r:u32be()
|
||||
if r.err then
|
||||
return nil, "truncated ext"
|
||||
end
|
||||
return ext(st, n)
|
||||
elseif b == 0xCA then
|
||||
local v = r:f32be()
|
||||
return if r.err then nil else v, if r.err then "truncated" else nil
|
||||
elseif b == 0xCB then
|
||||
local v = r:f64be()
|
||||
return if r.err then nil else v, if r.err then "truncated" else nil
|
||||
elseif b >= 0xCC and b <= 0xD3 then
|
||||
local v: any
|
||||
if b == 0xCC then
|
||||
v = r:u8()
|
||||
elseif b == 0xCD then
|
||||
v = r:u16be()
|
||||
elseif b == 0xCE then
|
||||
v = r:u32be()
|
||||
elseif b == 0xCF then
|
||||
v = int64(st, false)
|
||||
elseif b == 0xD0 then
|
||||
v = r:i8()
|
||||
elseif b == 0xD1 then
|
||||
v = r:i16be()
|
||||
elseif b == 0xD2 then
|
||||
v = r:i32be()
|
||||
else
|
||||
v = int64(st, true)
|
||||
end
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
return v, nil
|
||||
elseif b >= 0xD4 and b <= 0xD8 then
|
||||
return ext(st, 2 ^ (b - 0xD4))
|
||||
elseif b >= 0xD9 and b <= 0xDB then
|
||||
local n = if b == 0xD9 then r:u8() elseif b == 0xDA then r:u16be() else r:u32be()
|
||||
if r.err or not r:need(n) then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
return r:string(n), nil
|
||||
elseif b == 0xDC or b == 0xDD then
|
||||
local n = if b == 0xDC then r:u16be() else r:u32be()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
return array(st, n, depth)
|
||||
elseif b == 0xDE or b == 0xDF then
|
||||
local n = if b == 0xDE then r:u16be() else r:u32be()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
return map(st, n, depth)
|
||||
end
|
||||
return nil, string.format("reserved type byte 0x%02x", b)
|
||||
end
|
||||
|
||||
-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it)
|
||||
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local st: St = {
|
||||
r = r,
|
||||
big = o.bigInts == "string",
|
||||
null = if o.null ~= nil then o.null else Types.null,
|
||||
maxDepth = o.maxDepth or 512,
|
||||
ts = o.timestamps ~= false,
|
||||
ordered = o.ordered ~= false,
|
||||
}
|
||||
local v, e = value(st, 0)
|
||||
if e then
|
||||
return nil, e, r.pos - r.base
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
export type EncodeOptions = {
|
||||
float32: boolean?, -- non-integer numbers as float32 (default false: float64)
|
||||
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
|
||||
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
|
||||
maxDepth: number?, -- default 512 (also catches cycles)
|
||||
stringsAsBin: boolean?, -- strings as bin (default false: str)
|
||||
}
|
||||
|
||||
type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? }
|
||||
|
||||
local function writeInt(w: Bytes.Writer, v: number)
|
||||
if v >= 0 then
|
||||
if v < 128 then
|
||||
w:u8(v)
|
||||
elseif v < 256 then
|
||||
w:u8(0xCC)
|
||||
w:u8(v)
|
||||
elseif v < 65536 then
|
||||
w:u8(0xCD)
|
||||
w:u16be(v)
|
||||
elseif v < TWO32 then
|
||||
w:u8(0xCE)
|
||||
w:u32be(v)
|
||||
else
|
||||
w:u8(0xCF)
|
||||
w:u64be(v)
|
||||
end
|
||||
else
|
||||
if v >= -32 then
|
||||
w:u8(v + 256)
|
||||
elseif v >= -128 then
|
||||
w:u8(0xD0)
|
||||
w:u8(v + 256)
|
||||
elseif v >= -32768 then
|
||||
w:u8(0xD1)
|
||||
w:u16be(v + 65536)
|
||||
elseif v >= -2147483648 then
|
||||
w:u8(0xD2)
|
||||
w:u32be(v + TWO32)
|
||||
else
|
||||
w:u8(0xD3)
|
||||
local hi = math.floor(v / TWO32)
|
||||
local lo = v - hi * TWO32
|
||||
w:u32be(hi + TWO32)
|
||||
w:u32be(lo)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number)
|
||||
if fix and n <= fixMax then
|
||||
w:u8(fix + n)
|
||||
elseif b8 and n < 256 then
|
||||
w:u8(b8)
|
||||
w:u8(n)
|
||||
elseif n < 65536 then
|
||||
w:u8(b16)
|
||||
w:u16be(n)
|
||||
else
|
||||
w:u8(b32)
|
||||
w:u32be(n)
|
||||
end
|
||||
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
|
||||
|
||||
local function isArray(t: any, emptyMap: boolean): boolean
|
||||
if Types.isObject(t) then
|
||||
return false
|
||||
end
|
||||
local n = #t
|
||||
if n == 0 then
|
||||
return next(t) == nil and not emptyMap
|
||||
end
|
||||
local c = 0
|
||||
for _ in next, t do
|
||||
c += 1
|
||||
end
|
||||
return c == n
|
||||
end
|
||||
Codec.isArray = isArray
|
||||
|
||||
local function enc(st: ESt, v: any, depth: number): boolean
|
||||
local w = st.w
|
||||
local tv = type(v)
|
||||
if v == nil or v == Types.null then
|
||||
w:u8(0xC0)
|
||||
elseif tv == "boolean" then
|
||||
w:u8(if v then 0xC3 else 0xC2)
|
||||
elseif tv == "number" then
|
||||
if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then
|
||||
writeInt(w, v)
|
||||
elseif st.f32 then
|
||||
w:u8(0xCA)
|
||||
w:f32be(v)
|
||||
else
|
||||
w:u8(0xCB)
|
||||
w:f64be(v)
|
||||
end
|
||||
elseif tv == "string" then
|
||||
if st.bin then
|
||||
lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6)
|
||||
else
|
||||
lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB)
|
||||
end
|
||||
w:string(v)
|
||||
elseif tv == "buffer" then
|
||||
lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6)
|
||||
w:bytes(v)
|
||||
elseif tv == "table" then
|
||||
if depth >= st.maxDepth then
|
||||
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
|
||||
return false
|
||||
end
|
||||
if Codec.isExt(v) then
|
||||
local n = buffer.len(v.data)
|
||||
if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then
|
||||
w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n])
|
||||
else
|
||||
lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9)
|
||||
end
|
||||
w:u8(v.type % 256)
|
||||
w:bytes(v.data)
|
||||
elseif Types.Date.is(v) then
|
||||
local t = Types.Date.toUnix(v)
|
||||
local secs = math.floor(t)
|
||||
local ns = (v :: any).nanosecond or 0
|
||||
if ns == 0 and secs >= 0 and secs < TWO32 then
|
||||
w:u8(0xD6)
|
||||
w:u8(0xFF)
|
||||
w:u32be(secs)
|
||||
elseif secs >= 0 and secs < 2 ^ 34 then
|
||||
w:u8(0xD7)
|
||||
w:u8(0xFF)
|
||||
w:u32be(ns * 4 + secs // TWO32)
|
||||
w:u32be(secs % TWO32)
|
||||
else
|
||||
w:u8(0xC7)
|
||||
w:u8(12)
|
||||
w:u8(0xFF)
|
||||
w:u32be(ns)
|
||||
local hi = math.floor(secs / TWO32)
|
||||
w:u32be(hi % TWO32)
|
||||
w:u32be(secs - hi * TWO32)
|
||||
end
|
||||
elseif isArray(v, st.emptyMap) then
|
||||
local n = #v
|
||||
lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD)
|
||||
for k = 1, n do
|
||||
if not enc(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
else
|
||||
local keys: { any }
|
||||
if Types.isObject(v) then
|
||||
keys = Types.keys(v)
|
||||
else
|
||||
keys = {}
|
||||
for k in next, v do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
if st.sort then
|
||||
table.sort(keys, keyLess)
|
||||
end
|
||||
end
|
||||
lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF)
|
||||
for _, k in keys do
|
||||
if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
st.err = "cannot encode a " .. tv
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- encode(v, opts) -> buffer | nil, message
|
||||
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local st: ESt = {
|
||||
w = Bytes.writer(256),
|
||||
f32 = o.float32 == true,
|
||||
sort = o.sortKeys ~= false,
|
||||
emptyMap = o.emptyTable == "map",
|
||||
maxDepth = o.maxDepth or 512,
|
||||
bin = o.stringsAsBin == true,
|
||||
err = nil,
|
||||
}
|
||||
if not enc(st, v, 0) then
|
||||
return nil, st.err
|
||||
end
|
||||
return st.w:finish(), nil
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,90 @@
|
||||
--!strict
|
||||
-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the
|
||||
-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as
|
||||
-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a
|
||||
-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for
|
||||
-- non-integers unless opts.float32). Not supported: nothing in the spec.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Codec = require("@formats/data/msgpack/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Msgpack = {
|
||||
name = "msgpack",
|
||||
category = "data",
|
||||
extensions = { "msgpack", "mpk" },
|
||||
mime = { "application/msgpack", "application/x-msgpack" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, binary = true, ordered = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Codec.DecodeOptions & {
|
||||
all: boolean?, -- decode every concatenated value into an array (default false: exactly one value)
|
||||
}
|
||||
export type EncodeOptions = Codec.EncodeOptions & {
|
||||
all: boolean?, -- the value is an array of values, written one after another
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Msgpack.sniff(_r: Bytes.Reader): number
|
||||
return 0 -- no magic: by extension or opts.format only
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
if o.all then
|
||||
local out = {}
|
||||
while not r:eof() do
|
||||
local v, e, at = Codec.decode(r, o)
|
||||
if e then
|
||||
return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e, at)
|
||||
end
|
||||
table.insert(out, v)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local v, e, at = Codec.decode(r, o)
|
||||
if e then
|
||||
local code = if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED
|
||||
elseif string.find(e, "nested deeper", 1, true) then Err.LIMIT
|
||||
else Err.CORRUPT
|
||||
return nil, Err.new(code, e, at)
|
||||
end
|
||||
if not r:eof() then
|
||||
return nil, Err.new(Err.CORRUPT, "trailing data after the value (opts.all reads a stream)", r.pos - r.base)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if opts and opts.all then
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "all: expected an array of values")
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
for _, v in value do
|
||||
local b, e = Codec.encode(v, opts)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, e or "cannot encode")
|
||||
end
|
||||
w:bytes(b)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
local b, e = Codec.encode(value, opts)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, e or "cannot encode")
|
||||
end
|
||||
return b, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v)
|
||||
Msgpack.ext = Codec.ext
|
||||
Msgpack.isExt = Codec.isExt
|
||||
|
||||
return Msgpack
|
||||
@@ -0,0 +1,71 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- data/plist/Base64: RFC 4648 base64 for plist <data> (decode skips whitespace; encode wraps lines). Never throws.
|
||||
local Base64 = {}
|
||||
|
||||
local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
local DEC: { [number]: number } = {}
|
||||
for i = 1, 64 do
|
||||
DEC[string.byte(ALPHA, i)] = i - 1
|
||||
end
|
||||
local ENC: { string } = {}
|
||||
for i = 1, 64 do
|
||||
ENC[i - 1] = string.sub(ALPHA, i, i)
|
||||
end
|
||||
|
||||
-- decode(s) -> buffer | nil, message (whitespace ignored; padding optional)
|
||||
function Base64.decode(s: string): (buffer?, string?)
|
||||
local clean = string.gsub(s, "[ \t\r\n]", "")
|
||||
clean = string.gsub(clean, "=+$", "")
|
||||
local n = #clean
|
||||
if n % 4 == 1 then
|
||||
return nil, "bad base64 length"
|
||||
end
|
||||
local out = buffer.create(n * 3 // 4)
|
||||
local o = 0
|
||||
local acc, bits = 0, 0
|
||||
for i = 1, n do
|
||||
local v = DEC[string.byte(clean, i)]
|
||||
if v == nil then
|
||||
return nil, "bad base64 character"
|
||||
end
|
||||
acc = acc * 64 + v
|
||||
bits += 6
|
||||
if bits >= 8 then
|
||||
bits -= 8
|
||||
local b = acc // (2 ^ bits)
|
||||
buffer.writeu8(out, o, b)
|
||||
o += 1
|
||||
acc -= b * 2 ^ bits
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- encode(b, lineBytes?) -> base64 text; lineBytes > 0 puts "\n" after every lineBytes input bytes (and at the end)
|
||||
function Base64.encode(b: buffer, lineBytes: number?): string
|
||||
local n = buffer.len(b)
|
||||
local parts = table.create(n // 3 + 2)
|
||||
local per = lineBytes or 0
|
||||
local k = 0
|
||||
local i = 0
|
||||
while i < n do
|
||||
local a = buffer.readu8(b, i)
|
||||
local c1 = if i + 1 < n then buffer.readu8(b, i + 1) else 0
|
||||
local c2 = if i + 2 < n then buffer.readu8(b, i + 2) else 0
|
||||
local v = a * 65536 + c1 * 256 + c2
|
||||
local q = ENC[v // 262144] .. ENC[(v // 4096) % 64]
|
||||
q ..= if i + 1 < n then ENC[(v // 64) % 64] else "="
|
||||
q ..= if i + 2 < n then ENC[v % 64] else "="
|
||||
k += 1
|
||||
parts[k] = q
|
||||
i += 3
|
||||
if per > 0 and (i % per == 0 or i >= n) then
|
||||
k += 1
|
||||
parts[k] = "\n"
|
||||
end
|
||||
end
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
return Base64
|
||||
@@ -0,0 +1,271 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in
|
||||
-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte
|
||||
-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs,
|
||||
-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles
|
||||
-- are errors. Never throws: errors return nil, message.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Binary = {}
|
||||
|
||||
local readu8 = buffer.readu8
|
||||
local TWO32 = 4294967296
|
||||
local EPOCH_2001 = 978307200
|
||||
|
||||
local UidMeta = { __tostring = function(u: any): string
|
||||
return "UID(" .. u.uid .. ")"
|
||||
end }
|
||||
function Binary.uid(n: number): { uid: number }
|
||||
return setmetatable({ uid = n }, UidMeta) :: any
|
||||
end
|
||||
function Binary.isUid(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == UidMeta
|
||||
end
|
||||
|
||||
local function be(b: buffer, o: number, n: number): number
|
||||
local v = 0
|
||||
for k = 0, n - 1 do
|
||||
v = v * 256 + readu8(b, o + k)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
local function utf8char(c: number): string
|
||||
if c < 0x80 then
|
||||
return string.char(c)
|
||||
elseif c < 0x800 then
|
||||
return string.char(0xC0 + c // 64, 0x80 + c % 64)
|
||||
elseif c < 0x10000 then
|
||||
return string.char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64)
|
||||
end
|
||||
return string.char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64)
|
||||
end
|
||||
|
||||
export type Options = { bigInts: ("number" | "string")?, maxDepth: number? }
|
||||
|
||||
-- decode(buf, base, len, opts) -> value | nil, message
|
||||
function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?)
|
||||
if len < 40 then
|
||||
return nil, "truncated: shorter than header + trailer"
|
||||
end
|
||||
local t = base + len - 32
|
||||
local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7)
|
||||
local numObjects = be(b, t + 8, 8)
|
||||
local top = be(b, t + 16, 8)
|
||||
local tableOff = be(b, t + 24, 8)
|
||||
if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then
|
||||
return nil, "bad trailer sizes"
|
||||
end
|
||||
if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then
|
||||
return nil, "bad trailer"
|
||||
end
|
||||
local maxDepth = (opts and opts.maxDepth) or 512
|
||||
local cache: { [number]: any } = {}
|
||||
local busy: { [number]: boolean } = {}
|
||||
|
||||
local object: (idx: number, depth: number) -> (any, string?)
|
||||
|
||||
-- a length nibble: 0..14, or 15 = an int object follows
|
||||
local function count(o: number, nib: number): (number?, number)
|
||||
if nib < 15 then
|
||||
return nib, o + 1
|
||||
end
|
||||
if o + 2 > len - 32 then
|
||||
return nil, 0
|
||||
end
|
||||
local m = readu8(b, base + o + 1)
|
||||
if m // 16 ~= 1 then
|
||||
return nil, 0
|
||||
end
|
||||
local w = 2 ^ (m % 16)
|
||||
if w > 8 or o + 2 + w > len - 32 then
|
||||
return nil, 0
|
||||
end
|
||||
return be(b, base + o + 2, w), o + 2 + w
|
||||
end
|
||||
|
||||
local function ref(at: number): number
|
||||
return be(b, base + at, refSize)
|
||||
end
|
||||
|
||||
function object(idx: number, depth: number): (any, string?)
|
||||
local cached = cache[idx]
|
||||
if cached ~= nil then
|
||||
return cached, nil
|
||||
end
|
||||
if busy[idx] then
|
||||
return nil, "object references form a cycle"
|
||||
end
|
||||
if depth > maxDepth then
|
||||
return nil, "nested deeper than " .. maxDepth
|
||||
end
|
||||
if idx >= numObjects then
|
||||
return nil, "object reference out of range"
|
||||
end
|
||||
local o = be(b, base + tableOff + idx * offSize, offSize)
|
||||
if o < 8 or o >= len - 32 then
|
||||
return nil, "object offset out of range"
|
||||
end
|
||||
local marker = readu8(b, base + o)
|
||||
local hi, nib = marker // 16, marker % 16
|
||||
local v: any
|
||||
if marker == 0x00 then
|
||||
v = Types.null
|
||||
elseif marker == 0x08 then
|
||||
v = false
|
||||
elseif marker == 0x09 then
|
||||
v = true
|
||||
elseif hi == 1 then
|
||||
local w = 2 ^ nib
|
||||
if w > 16 or o + 1 + w > len - 32 then
|
||||
return nil, "bad integer"
|
||||
end
|
||||
if w == 16 then
|
||||
o += 8
|
||||
w = 8
|
||||
end
|
||||
if w == 8 then
|
||||
local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4)
|
||||
if h >= 0x80000000 and nib == 3 then
|
||||
v = (h - TWO32) * TWO32 + l
|
||||
elseif opts and opts.bigInts == "string" and h >= 0x200000 then
|
||||
-- exact decimal text of h * 2^32 + l
|
||||
local digits = {}
|
||||
local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 }
|
||||
while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
|
||||
local rem = 0
|
||||
for k = 1, 4 do
|
||||
local cur = rem * 65536 + limbs[k]
|
||||
limbs[k] = cur // 10
|
||||
rem = cur % 10
|
||||
end
|
||||
table.insert(digits, 1, string.char(48 + rem))
|
||||
end
|
||||
v = table.concat(digits)
|
||||
else
|
||||
v = h * TWO32 + l
|
||||
end
|
||||
else
|
||||
v = be(b, base + o + 1, w)
|
||||
end
|
||||
elseif hi == 2 then
|
||||
if nib == 2 and o + 5 <= len - 32 then
|
||||
local s = buffer.create(4)
|
||||
for k = 0, 3 do
|
||||
buffer.writeu8(s, k, readu8(b, base + o + 4 - k))
|
||||
end
|
||||
v = buffer.readf32(s, 0)
|
||||
elseif nib == 3 and o + 9 <= len - 32 then
|
||||
local s = buffer.create(8)
|
||||
for k = 0, 7 do
|
||||
buffer.writeu8(s, k, readu8(b, base + o + 8 - k))
|
||||
end
|
||||
v = buffer.readf64(s, 0)
|
||||
else
|
||||
return nil, "bad real"
|
||||
end
|
||||
elseif marker == 0x33 then
|
||||
if o + 9 > len - 32 then
|
||||
return nil, "truncated date"
|
||||
end
|
||||
local s = buffer.create(8)
|
||||
for k = 0, 7 do
|
||||
buffer.writeu8(s, k, readu8(b, base + o + 8 - k))
|
||||
end
|
||||
local secs = buffer.readf64(s, 0)
|
||||
if secs ~= secs or math.abs(secs) > 1e14 then
|
||||
return nil, "bad date"
|
||||
end
|
||||
v = Types.Date.fromUnix(secs + EPOCH_2001)
|
||||
elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then
|
||||
local n, p = count(o, nib)
|
||||
if not n then
|
||||
return nil, "bad length"
|
||||
end
|
||||
local bytes = if hi == 6 then n * 2 else n
|
||||
if p + bytes > len - 32 then
|
||||
return nil, "string / data past the end"
|
||||
end
|
||||
if hi == 4 then
|
||||
local d = buffer.create(bytes)
|
||||
buffer.copy(d, 0, b, base + p, bytes)
|
||||
v = d
|
||||
elseif hi == 6 then
|
||||
local parts = table.create(n)
|
||||
local k = 0
|
||||
while k < n do
|
||||
local u = be(b, base + p + k * 2, 2)
|
||||
k += 1
|
||||
if u >= 0xD800 and u <= 0xDBFF and k < n then
|
||||
local lo = be(b, base + p + k * 2, 2)
|
||||
if lo >= 0xDC00 and lo <= 0xDFFF then
|
||||
u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
table.insert(parts, utf8char(u))
|
||||
end
|
||||
v = table.concat(parts)
|
||||
else
|
||||
v = buffer.readstring(b, base + p, bytes)
|
||||
end
|
||||
elseif hi == 8 then
|
||||
if o + 2 + nib > len - 32 then
|
||||
return nil, "bad UID"
|
||||
end
|
||||
v = Binary.uid(be(b, base + o + 1, nib + 1))
|
||||
elseif hi == 0xA or hi == 0xC or hi == 0xD then
|
||||
local n, p = count(o, nib)
|
||||
if not n then
|
||||
return nil, "bad length"
|
||||
end
|
||||
local refs = if hi == 0xD then n * 2 else n
|
||||
if p + refs * refSize > len - 32 then
|
||||
return nil, "collection past the end"
|
||||
end
|
||||
busy[idx] = true
|
||||
if hi == 0xD then
|
||||
local t2 = {}
|
||||
local order = table.create(n)
|
||||
for k = 0, n - 1 do
|
||||
local key, ke = object(ref(p + k * refSize), depth + 1)
|
||||
if ke then
|
||||
return nil, ke
|
||||
end
|
||||
if type(key) ~= "string" then
|
||||
return nil, "dict key is not a string"
|
||||
end
|
||||
local val, ve = object(ref(p + (n + k) * refSize), depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if t2[key] == nil then
|
||||
table.insert(order, key)
|
||||
end
|
||||
t2[key] = val
|
||||
end
|
||||
v = Types.object(t2, order)
|
||||
else
|
||||
local arr = table.create(n)
|
||||
for k = 0, n - 1 do
|
||||
local item, ie = object(ref(p + k * refSize), depth + 1)
|
||||
if ie then
|
||||
return nil, ie
|
||||
end
|
||||
arr[k + 1] = item
|
||||
end
|
||||
v = arr
|
||||
end
|
||||
busy[idx] = nil
|
||||
else
|
||||
return nil, string.format("unknown object marker 0x%02x", marker)
|
||||
end
|
||||
cache[idx] = v
|
||||
return v, nil
|
||||
end
|
||||
|
||||
return object(top, 0)
|
||||
end
|
||||
|
||||
return Binary
|
||||
@@ -0,0 +1,306 @@
|
||||
--!strict
|
||||
-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/Xml; the write is
|
||||
-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict ->
|
||||
-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data ->
|
||||
-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past
|
||||
-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as <integer>.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
local Base64 = require("@formats/data/plist/Base64")
|
||||
local Binary = require("@formats/data/plist/Binary")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Plist = {
|
||||
name = "plist",
|
||||
category = "data",
|
||||
extensions = { "plist" },
|
||||
mime = { "application/x-plist", "application/x-bplist" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, binary = "read", ordered = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text
|
||||
maxDepth: number?, -- default 512
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Plist.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(256)
|
||||
if string.sub(head, 1, 6) == "bplist" then
|
||||
return 1
|
||||
end
|
||||
if string.find(head, "<!DOCTYPE plist", 1, true) or string.find(head, "<plist", 1, true) then
|
||||
return 0.9
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function xmlValue(node: any, opts: DecodeOptions?, depth: number): (any, string?)
|
||||
if depth > ((opts and opts.maxDepth) or 512) then
|
||||
return nil, "nested too deeply"
|
||||
end
|
||||
local name = node.name
|
||||
if name == "dict" then
|
||||
local out = Types.object()
|
||||
local kids = Xml.children(node)
|
||||
local i = 1
|
||||
while i <= #kids do
|
||||
local k = kids[i]
|
||||
if k.name ~= "key" then
|
||||
return nil, "dict: expected <key>, got <" .. k.name .. ">"
|
||||
end
|
||||
local v = kids[i + 1]
|
||||
if not v then
|
||||
return nil, "dict: <key> without a value"
|
||||
end
|
||||
local val, e = xmlValue(v, opts, depth + 1)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
Types.set(out, Xml.text(k), val)
|
||||
i += 2
|
||||
end
|
||||
return out, nil
|
||||
elseif name == "array" then
|
||||
local out = {}
|
||||
for _, ch in Xml.children(node) do
|
||||
local val, e = xmlValue(ch, opts, depth + 1)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
table.insert(out, val)
|
||||
end
|
||||
return out, nil
|
||||
elseif name == "string" then
|
||||
return Xml.text(node), nil
|
||||
elseif name == "integer" then
|
||||
local t = string.match(Xml.text(node), "^%s*(.-)%s*$") :: string
|
||||
local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$")
|
||||
local n: number?
|
||||
if hex then
|
||||
n = tonumber(hex, 16)
|
||||
if n and neg == "-" then
|
||||
n = -n
|
||||
end
|
||||
elseif string.match(t, "^[%-%+]?%d+$") then
|
||||
n = tonumber(t)
|
||||
if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then
|
||||
return (string.gsub(t, "^%+", "")), nil
|
||||
end
|
||||
end
|
||||
if not n then
|
||||
return nil, "bad integer " .. string.sub(t, 1, 30)
|
||||
end
|
||||
return n, nil
|
||||
elseif name == "real" then
|
||||
local t = string.lower(string.match(Xml.text(node), "^%s*(.-)%s*$") :: string)
|
||||
local n = tonumber(t)
|
||||
if not n then
|
||||
if t == "nan" or t == "+nan" or t == "-nan" then
|
||||
n = 0 / 0
|
||||
elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then
|
||||
n = math.huge
|
||||
elseif t == "-inf" or t == "-infinity" then
|
||||
n = -math.huge
|
||||
end
|
||||
end
|
||||
if not n then
|
||||
return nil, "bad real " .. string.sub(t, 1, 30)
|
||||
end
|
||||
return n, nil
|
||||
elseif name == "true" then
|
||||
return true, nil
|
||||
elseif name == "false" then
|
||||
return false, nil
|
||||
elseif name == "date" then
|
||||
local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$")))
|
||||
if not d then
|
||||
return nil, "bad date"
|
||||
end
|
||||
return d, nil
|
||||
elseif name == "data" then
|
||||
local b, e = Base64.decode(Xml.text(node))
|
||||
if not b then
|
||||
return nil, e
|
||||
end
|
||||
return b, nil
|
||||
end
|
||||
return nil, "unknown element <" .. tostring(name) .. ">"
|
||||
end
|
||||
|
||||
function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local len = r.limit - r.base
|
||||
if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then
|
||||
local v, e = Binary.decode(r.buf, r.base, len, opts)
|
||||
if e then
|
||||
return nil, Err.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, e)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true })
|
||||
if not doc then
|
||||
return nil, err
|
||||
end
|
||||
local root = (doc :: any).root
|
||||
if root.name == "plist" then
|
||||
local kids = Xml.children(root)
|
||||
if #kids ~= 1 then
|
||||
return nil, Err.new(Err.CORRUPT, "<plist> must hold exactly one value")
|
||||
end
|
||||
root = kids[1]
|
||||
end
|
||||
local v, e = xmlValue(root, opts, 0)
|
||||
if e then
|
||||
return nil, Err.new(Err.CORRUPT, e)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local HEADER = '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n'
|
||||
|
||||
local function esc(s: string): (string?, string?)
|
||||
if string.find(s, "[%z\1-\8\11\12\14-\31]") then
|
||||
return nil, "strings cannot contain control characters"
|
||||
end
|
||||
s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n")
|
||||
return (string.gsub(s, "[&<>]", { ["&"] = "&", ["<"] = "<", [">"] = ">" })), nil
|
||||
end
|
||||
|
||||
local function keyLess(a: any, b: any): boolean
|
||||
return a < b
|
||||
end
|
||||
|
||||
function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local sort = not (opts and opts.sortKeys == false)
|
||||
local out: { string } = { HEADER }
|
||||
local err: string? = nil
|
||||
local function line(level: number, s: string)
|
||||
table.insert(out, string.rep("\t", level) .. s .. "\n")
|
||||
end
|
||||
local write: (v: any, level: number, depth: number) -> boolean
|
||||
function write(v: any, level: number, depth: number): boolean
|
||||
if depth > 512 then
|
||||
err = "nested deeper than 512 (a cycle?)"
|
||||
return false
|
||||
end
|
||||
local tv = type(v)
|
||||
if tv == "string" then
|
||||
local s, e = esc(v)
|
||||
if not s then
|
||||
err = e
|
||||
return false
|
||||
end
|
||||
line(level, "<string>" .. s .. "</string>")
|
||||
elseif tv == "boolean" then
|
||||
line(level, if v then "<true/>" else "<false/>")
|
||||
elseif tv == "number" then
|
||||
if v == math.floor(v) and math.abs(v) < 2 ^ 63 then
|
||||
line(level, "<integer>" .. string.format("%d", v) .. "</integer>")
|
||||
else
|
||||
local s = Json.number(v)
|
||||
if not s then
|
||||
s = if v ~= v then "nan" elseif v > 0 then "inf" else "-inf"
|
||||
end
|
||||
line(level, "<real>" .. s .. "</real>")
|
||||
end
|
||||
elseif tv == "buffer" then
|
||||
line(level, "<data>")
|
||||
local maxLine = math.max(16, 76 - 8 * level)
|
||||
for l in string.gmatch(Base64.encode(v, maxLine // 4 * 3), "[^\n]+") do
|
||||
line(level, l)
|
||||
end
|
||||
line(level, "</data>")
|
||||
elseif tv == "table" and Types.Date.is(v) then
|
||||
local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v)))
|
||||
line(level, string.format("<date>%04d-%02d-%02dT%02d:%02d:%02dZ</date>", d.year :: number, d.month :: number, d.day :: number, d.hour :: number, d.minute :: number, d.second :: number))
|
||||
elseif tv == "table" and Binary.isUid(v) then
|
||||
err = "UIDs can only be written to binary plists"
|
||||
return false
|
||||
elseif tv == "table" and v ~= Types.null then
|
||||
local n = #v
|
||||
local isArray = false
|
||||
if not Types.isObject(v) then
|
||||
local c = 0
|
||||
for _ in next, v do
|
||||
c += 1
|
||||
end
|
||||
isArray = c == n
|
||||
end
|
||||
if isArray then
|
||||
if n == 0 then
|
||||
line(level, "<array/>")
|
||||
return true
|
||||
end
|
||||
line(level, "<array>")
|
||||
for k = 1, n do
|
||||
if not write(v[k], level + 1, depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
line(level, "</array>")
|
||||
else
|
||||
local keys: { any }
|
||||
if Types.isObject(v) then
|
||||
keys = Types.keys(v)
|
||||
else
|
||||
keys = {}
|
||||
for k in next, v do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
end
|
||||
for _, k in keys do
|
||||
if type(k) ~= "string" then
|
||||
err = "dict keys must be strings"
|
||||
return false
|
||||
end
|
||||
end
|
||||
if sort and not Types.isObject(v) then
|
||||
table.sort(keys, keyLess)
|
||||
end
|
||||
if #keys == 0 then
|
||||
line(level, "<dict/>")
|
||||
return true
|
||||
end
|
||||
line(level, "<dict>")
|
||||
for _, k in keys do
|
||||
local ks, e = esc(k)
|
||||
if not ks then
|
||||
err = e
|
||||
return false
|
||||
end
|
||||
line(level + 1, "<key>" .. ks .. "</key>")
|
||||
if not write(v[k], level + 1, depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
line(level, "</dict>")
|
||||
end
|
||||
else
|
||||
err = "cannot write " .. (if v == Types.null then "null" else "a " .. tv) .. " in a plist"
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
if not write(value, 0, 0) then
|
||||
return nil, Err.new(Err.ARG, err or "cannot encode")
|
||||
end
|
||||
table.insert(out, "</plist>\n")
|
||||
return buffer.fromstring(table.concat(out)), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver)
|
||||
Plist.isUid = Binary.isUid
|
||||
|
||||
return Plist
|
||||
@@ -0,0 +1,643 @@
|
||||
--!strict
|
||||
-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with
|
||||
-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control
|
||||
-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and
|
||||
-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Decode = {}
|
||||
|
||||
local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char
|
||||
|
||||
export type Options = {
|
||||
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number")
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
local ESC: { [number]: string } = { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" }
|
||||
|
||||
-- digits with single underscores between them
|
||||
local function digitsOk(d: string, class: string): boolean
|
||||
return d ~= "" and not find(d, "__", 1, true) and byte(d, 1) ~= 95 and byte(d, #d) ~= 95 and find(d, "^[" .. class .. "_]+$") ~= nil
|
||||
end
|
||||
|
||||
function Decode.decode(s: string, opts: Options?): (any, any, number?)
|
||||
local bigStrings = opts ~= nil and opts.bigInts == "string"
|
||||
local errMsg: string = ""
|
||||
local errAt = 0
|
||||
local function fail(msg: string, at: number): nil
|
||||
errMsg, errAt = msg, at - 1
|
||||
return nil
|
||||
end
|
||||
|
||||
-- input checks: BOM, UTF-8, control characters, bare CR
|
||||
if sub(s, 1, 3) == "\239\187\191" then
|
||||
s = sub(s, 4)
|
||||
end
|
||||
do
|
||||
local bad = find(s, "[%z\1-\8\11\12\14-\31\127]")
|
||||
if bad then
|
||||
return nil, "control character", bad - 1
|
||||
end
|
||||
local cr = find(s, "\r[^\n]") or (if byte(s, #s) == 13 then #s else nil)
|
||||
if cr then
|
||||
return nil, "carriage return without a line feed", cr - 1
|
||||
end
|
||||
if find(s, "[\128-\255]") then
|
||||
if not utf8.len(s) then
|
||||
return nil, "invalid UTF-8", 0
|
||||
end
|
||||
local sur = find(s, "\237[\160-\191]")
|
||||
if sur then
|
||||
return nil, "invalid UTF-8 (surrogate)", sur - 1
|
||||
end
|
||||
end
|
||||
if find(s, "\r", 1, true) then
|
||||
s = gsub(s, "\r\n", "\n")
|
||||
end
|
||||
end
|
||||
local n = #s
|
||||
|
||||
-- table bookkeeping: kind = "explicit" | "implicit" | "dotted" | "inline"; section = where dotted tables were made
|
||||
local kinds: { [any]: string } = {}
|
||||
local sections: { [any]: number } = {}
|
||||
local aot: { [any]: boolean } = {} -- arrays of tables ([[x]]); other arrays are static
|
||||
local arrays: { [any]: boolean } = {}
|
||||
local section = 0
|
||||
local building: { any }? = nil -- tables created inside the inline table being parsed (frozen when it closes)
|
||||
|
||||
local function newTable(kind: string): any
|
||||
local t = Types.object({}, {})
|
||||
kinds[t] = kind
|
||||
if building then
|
||||
table.insert(building, t)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
local function ws(i: number): number
|
||||
return match(s, "^[ \t]*()", i) :: any
|
||||
end
|
||||
-- whitespace, newlines and comments (inside arrays)
|
||||
local function wsnl(i: number): number
|
||||
while true do
|
||||
i = match(s, "^[ \t\n]*()", i) :: any
|
||||
if byte(s, i) == 35 then
|
||||
i = find(s, "\n", i, true) or (n + 1)
|
||||
else
|
||||
return i
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function escape(p: number, parts: { string }): number?
|
||||
local e = byte(s, p + 1)
|
||||
local simple = if e then ESC[e] else nil
|
||||
if simple then
|
||||
table.insert(parts, simple)
|
||||
return p + 2
|
||||
elseif e == 117 or e == 85 then
|
||||
local len = if e == 117 then 4 else 8
|
||||
local h = match(s, "^" .. string.rep("%x", len), p + 2)
|
||||
if not h then
|
||||
return fail("bad unicode escape", p)
|
||||
end
|
||||
local cp = tonumber(h, 16) :: number
|
||||
if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then
|
||||
return fail("unicode escape is not a scalar value", p)
|
||||
end
|
||||
table.insert(parts, utf8char(cp))
|
||||
return p + 2 + len
|
||||
end
|
||||
return fail("bad escape", p)
|
||||
end
|
||||
|
||||
-- strings: value, next | nil
|
||||
local function basic(i: number): (string?, number)
|
||||
local parts = {}
|
||||
local j = i + 1
|
||||
while true do
|
||||
local p = find(s, '["\\\n]', j)
|
||||
if not p or byte(s, p) == 10 then
|
||||
return fail("unterminated string", p or n + 1), 0
|
||||
end
|
||||
table.insert(parts, sub(s, j, p - 1))
|
||||
if byte(s, p) == 34 then
|
||||
return table.concat(parts), p + 1
|
||||
end
|
||||
local nj = escape(p, parts)
|
||||
if not nj then
|
||||
return nil, 0
|
||||
end
|
||||
j = nj
|
||||
end
|
||||
end
|
||||
local function multiBasic(i: number): (string?, number)
|
||||
local j = i + 3
|
||||
if byte(s, j) == 10 then
|
||||
j += 1
|
||||
end
|
||||
local parts = {}
|
||||
while true do
|
||||
local p = find(s, '["\\]', j)
|
||||
if not p then
|
||||
return fail("unterminated multi-line string", i), 0
|
||||
end
|
||||
table.insert(parts, sub(s, j, p - 1))
|
||||
if byte(s, p) == 34 then
|
||||
if sub(s, p, p + 2) == '"""' then
|
||||
local q = p + 3
|
||||
local extra = 0
|
||||
while byte(s, q) == 34 and extra < 2 do
|
||||
extra += 1
|
||||
q += 1
|
||||
end
|
||||
if byte(s, q) == 34 then
|
||||
return fail("too many quotes", q), 0
|
||||
end
|
||||
table.insert(parts, string.rep('"', extra))
|
||||
return table.concat(parts), q
|
||||
end
|
||||
table.insert(parts, '"')
|
||||
j = p + 1
|
||||
else
|
||||
local k = match(s, "^\\[ \t]*\n[ \t\n]*()", p)
|
||||
if k then
|
||||
j = k :: any
|
||||
else
|
||||
local nj = escape(p, parts)
|
||||
if not nj then
|
||||
return nil, 0
|
||||
end
|
||||
j = nj
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local function literal(i: number): (string?, number)
|
||||
local e = find(s, "['\n]", i + 1)
|
||||
if not e or byte(s, e) == 10 then
|
||||
return fail("unterminated literal string", e or n + 1), 0
|
||||
end
|
||||
return sub(s, i + 1, e - 1), e + 1
|
||||
end
|
||||
local function multiLiteral(i: number): (string?, number)
|
||||
local j = i + 3
|
||||
if byte(s, j) == 10 then
|
||||
j += 1
|
||||
end
|
||||
local e = find(s, "'''", j, true)
|
||||
if not e then
|
||||
return fail("unterminated multi-line literal string", i), 0
|
||||
end
|
||||
local q = e + 3
|
||||
local extra = 0
|
||||
while byte(s, q) == 39 and extra < 2 do
|
||||
extra += 1
|
||||
q += 1
|
||||
end
|
||||
if byte(s, q) == 39 then
|
||||
return fail("too many quotes", q), 0
|
||||
end
|
||||
return sub(s, j, e - 1) .. string.rep("'", extra), q
|
||||
end
|
||||
|
||||
-- a (dotted) key: { parts }, next | nil
|
||||
local function key(i: number): ({ string }?, number)
|
||||
local keys = {}
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = byte(s, i)
|
||||
local k: string?
|
||||
if c == 34 then
|
||||
if sub(s, i, i + 2) == '"""' then
|
||||
return fail("multi-line string as a key", i), 0
|
||||
end
|
||||
k, i = basic(i)
|
||||
elseif c == 39 then
|
||||
if sub(s, i, i + 2) == "'''" then
|
||||
return fail("multi-line string as a key", i), 0
|
||||
end
|
||||
k, i = literal(i)
|
||||
else
|
||||
k = match(s, "^[%w_%-]+", i)
|
||||
if k then
|
||||
i += #k
|
||||
else
|
||||
return fail("expected a key", i), 0
|
||||
end
|
||||
end
|
||||
if k == nil then
|
||||
return nil, 0
|
||||
end
|
||||
table.insert(keys, k)
|
||||
i = ws(i)
|
||||
if byte(s, i) == 46 then
|
||||
i += 1
|
||||
else
|
||||
return keys, i
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- numbers and datetimes
|
||||
local function number(i: number): (any, number)
|
||||
local tok = match(s, "^[%+%-]?[%w_%.]+", i)
|
||||
if not tok then
|
||||
return fail("expected a value", i), 0
|
||||
end
|
||||
local last = byte(tok, #tok)
|
||||
if (last == 101 or last == 69) and not find(tok, "^[%+%-]?0[xob]") then
|
||||
local ext = match(s, "^[%+%-][%w_]*", i + #tok)
|
||||
if ext then
|
||||
tok ..= ext
|
||||
end
|
||||
end
|
||||
local nexti = i + #tok
|
||||
local sign, body = match(tok, "^([%+%-]?)(.*)$")
|
||||
if body == "inf" or body == "nan" then
|
||||
return (if body == "nan" then 0 / 0 elseif sign == "-" then -math.huge else math.huge), nexti
|
||||
end
|
||||
local prefix = sub(body :: string, 1, 2)
|
||||
if prefix == "0x" or prefix == "0o" or prefix == "0b" then
|
||||
if sign ~= "" then
|
||||
return fail("sign on a non-decimal integer", i), 0
|
||||
end
|
||||
local d = sub(body :: string, 3)
|
||||
local class = if prefix == "0x" then "%x" elseif prefix == "0o" then "0-7" else "01"
|
||||
if not digitsOk(d, class) then
|
||||
return fail("bad integer", i), 0
|
||||
end
|
||||
d = gsub(gsub(d, "_", ""), "^0+", "")
|
||||
local over = if prefix == "0x" then #d > 16 or (#d == 16 and (tonumber(sub(d, 1, 1), 16) :: number) >= 8)
|
||||
elseif prefix == "0o" then #d > 21
|
||||
else #d > 63
|
||||
if over then
|
||||
return fail("integer out of 64-bit range", i), 0
|
||||
end
|
||||
if d == "" then
|
||||
return 0, nexti
|
||||
end
|
||||
local v = tonumber(d, if prefix == "0x" then 16 elseif prefix == "0o" then 8 else 2) :: number
|
||||
if bigStrings and v >= 9007199254740992 then
|
||||
return prefix .. d, nexti
|
||||
end
|
||||
return v, nexti
|
||||
end
|
||||
local ip, rest = match(body :: string, "^([%d_]+)(.*)$")
|
||||
if not ip or not digitsOk(ip, "%d") then
|
||||
return fail("bad number", i), 0
|
||||
end
|
||||
local digits = gsub(ip, "_", "")
|
||||
if #digits > 1 and byte(digits, 1) == 48 then
|
||||
return fail("leading zero", i), 0
|
||||
end
|
||||
if rest == "" then
|
||||
local limit = if sign == "-" then "9223372036854775808" else "9223372036854775807"
|
||||
if #digits > 19 or (#digits == 19 and digits > limit) then
|
||||
return fail("integer out of 64-bit range", i), 0
|
||||
end
|
||||
local v = tonumber(digits) :: number
|
||||
if bigStrings and v >= 9007199254740992 then
|
||||
return (if sign == "-" then "-" else "") .. digits, nexti
|
||||
end
|
||||
return if sign == "-" then -v else v, nexti
|
||||
end
|
||||
local text = sign .. digits
|
||||
local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$")
|
||||
if frac then
|
||||
if not digitsOk(frac, "%d") then
|
||||
return fail("bad fraction", i), 0
|
||||
end
|
||||
text ..= "." .. gsub(frac, "_", "")
|
||||
rest = r2
|
||||
end
|
||||
if rest ~= "" then
|
||||
local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$")
|
||||
if not es or not digitsOk(ed, "%d") then
|
||||
return fail("bad float", i), 0
|
||||
end
|
||||
text ..= "e" .. es .. gsub(ed, "_", "")
|
||||
end
|
||||
local v = tonumber(text)
|
||||
if v == nil then
|
||||
return fail("bad float", i), 0
|
||||
end
|
||||
return v, nexti
|
||||
end
|
||||
|
||||
local function datetime(i: number): (any, number)
|
||||
local j = i
|
||||
if match(s, "^%d%d%d%d%-%d%d%-%d%d", i) then
|
||||
j = i + 10
|
||||
local c = byte(s, j)
|
||||
if (c == 84 or c == 116 or c == 32) and match(s, "^%d%d:", j + 1) then
|
||||
j += 1
|
||||
elseif c == 84 or c == 116 then
|
||||
return fail("bad datetime", i), 0
|
||||
else
|
||||
local d = Types.Date.parse(sub(s, i, j - 1))
|
||||
if not d then
|
||||
return fail("bad date", i), 0
|
||||
end
|
||||
return d, j
|
||||
end
|
||||
end
|
||||
local t = match(s, "^%d%d:%d%d:%d%d", j)
|
||||
if not t then
|
||||
return fail("bad time (seconds are required)", j), 0
|
||||
end
|
||||
j += 8
|
||||
local frac = match(s, "^%.%d+", j)
|
||||
if frac then
|
||||
j += #frac
|
||||
elseif byte(s, j) == 46 then
|
||||
return fail("bad fraction", j), 0
|
||||
end
|
||||
if j - i > 19 or match(s, "^%d%d%d%d%-", i) then
|
||||
local off = match(s, "^[Zz]", j) or match(s, "^[%+%-]%d%d:%d%d", j)
|
||||
if off then
|
||||
j += #off
|
||||
end
|
||||
end
|
||||
local d = Types.Date.parse(sub(s, i, j - 1))
|
||||
if not d then
|
||||
return fail("bad datetime", i), 0
|
||||
end
|
||||
return d, j
|
||||
end
|
||||
|
||||
local value: (i: number) -> (any, number)
|
||||
local assign: (tbl: any, keys: { string }, v: any, sid: number, at: number) -> boolean
|
||||
|
||||
local function array(i: number): (any, number)
|
||||
local arr = {}
|
||||
arrays[arr] = true
|
||||
i += 1
|
||||
while true do
|
||||
i = wsnl(i)
|
||||
local c = byte(s, i)
|
||||
if c == 93 then
|
||||
return arr, i + 1
|
||||
elseif c == nil then
|
||||
return fail("unterminated array", i), 0
|
||||
end
|
||||
local v, ni = value(i)
|
||||
if v == nil then
|
||||
return nil, 0
|
||||
end
|
||||
table.insert(arr, v)
|
||||
i = wsnl(ni)
|
||||
c = byte(s, i)
|
||||
if c == 44 then
|
||||
i += 1
|
||||
elseif c == 93 then
|
||||
return arr, i + 1
|
||||
else
|
||||
return fail(if c == nil then "unterminated array" else "expected ',' or ']'", i), 0
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function inline(i: number): (any, number)
|
||||
local outer = building
|
||||
local mine = {}
|
||||
building = mine
|
||||
local t = newTable("inline")
|
||||
section += 1
|
||||
local sid = section
|
||||
i = ws(i + 1)
|
||||
if byte(s, i) == 125 then
|
||||
building = outer
|
||||
return t, i + 1
|
||||
end
|
||||
while true do
|
||||
local keys, ni = key(i)
|
||||
if not keys then
|
||||
return nil, 0
|
||||
end
|
||||
i = ws(ni)
|
||||
if byte(s, i) ~= 61 then
|
||||
return fail("expected '='", i), 0
|
||||
end
|
||||
local v, vi = value(ws(i + 1))
|
||||
if v == nil then
|
||||
return nil, 0
|
||||
end
|
||||
if not assign(t, keys, v, sid, i) then
|
||||
return nil, 0
|
||||
end
|
||||
i = ws(vi)
|
||||
local c = byte(s, i)
|
||||
if c == 44 then
|
||||
i = ws(i + 1)
|
||||
if byte(s, i) == 125 then
|
||||
return fail("trailing comma in an inline table", i), 0
|
||||
end
|
||||
elseif c == 125 then
|
||||
break
|
||||
else
|
||||
return fail(if c == 10 then "newline in an inline table" else "expected ',' or '}'", i), 0
|
||||
end
|
||||
end
|
||||
for _, x in mine do
|
||||
kinds[x] = "inline"
|
||||
end
|
||||
building = outer
|
||||
if outer then
|
||||
for _, x in mine do
|
||||
table.insert(outer, x)
|
||||
end
|
||||
end
|
||||
return t, i + 1
|
||||
end
|
||||
|
||||
function value(i: number): (any, number)
|
||||
local c = byte(s, i)
|
||||
if c == 34 then
|
||||
if sub(s, i, i + 2) == '"""' then
|
||||
return multiBasic(i)
|
||||
end
|
||||
return basic(i)
|
||||
elseif c == 39 then
|
||||
if sub(s, i, i + 2) == "'''" then
|
||||
return multiLiteral(i)
|
||||
end
|
||||
return literal(i)
|
||||
elseif c == 116 then
|
||||
if match(s, "^true", i) and not match(s, "^[%w_%-]", i + 4) then
|
||||
return true, i + 4
|
||||
end
|
||||
elseif c == 102 then
|
||||
if match(s, "^false", i) and not match(s, "^[%w_%-]", i + 5) then
|
||||
return false, i + 5
|
||||
end
|
||||
elseif c == 91 then
|
||||
return array(i)
|
||||
elseif c == 123 then
|
||||
return inline(i)
|
||||
elseif c and ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 105 or c == 110) then
|
||||
if match(s, "^%d%d%d%d%-", i) or match(s, "^%d%d:", i) then
|
||||
return datetime(i)
|
||||
end
|
||||
return number(i)
|
||||
end
|
||||
return fail(if c == nil or c == 10 then "expected a value" else "bad value", i), 0
|
||||
end
|
||||
|
||||
function assign(tbl: any, keys: { string }, v: any, sid: number, at: number): boolean
|
||||
local t = tbl
|
||||
for j = 1, #keys - 1 do
|
||||
local k = keys[j]
|
||||
local x = t[k]
|
||||
if x == nil then
|
||||
local nt = newTable("dotted")
|
||||
sections[nt] = sid
|
||||
Types.set(t, k, nt)
|
||||
t = nt
|
||||
elseif kinds[x] == "implicit" or (kinds[x] == "dotted" and sections[x] == sid) then
|
||||
t = x
|
||||
else
|
||||
fail("cannot add to " .. k .. " with a dotted key (already defined)", at)
|
||||
return false
|
||||
end
|
||||
end
|
||||
local k = keys[#keys]
|
||||
if t[k] ~= nil then
|
||||
fail("duplicate key " .. k, at)
|
||||
return false
|
||||
end
|
||||
Types.set(t, k, v)
|
||||
return true
|
||||
end
|
||||
|
||||
-- after a key / value or a header: spaces, an optional comment, then a newline or the end
|
||||
local function eol(i: number): number?
|
||||
i = ws(i)
|
||||
local c = byte(s, i)
|
||||
if c == 35 then
|
||||
return find(s, "\n", i, true) or (n + 1)
|
||||
elseif c == 10 or c == nil then
|
||||
return i
|
||||
end
|
||||
return fail("expected the end of the line", i)
|
||||
end
|
||||
|
||||
local root = newTable("explicit")
|
||||
local cur = root
|
||||
local i = 1
|
||||
while true do
|
||||
i = ws(i)
|
||||
local c = byte(s, i)
|
||||
if c == nil then
|
||||
break
|
||||
elseif c == 10 then
|
||||
i += 1
|
||||
elseif c == 35 then
|
||||
i = find(s, "\n", i, true) or (n + 1)
|
||||
elseif c == 91 then
|
||||
local at = i
|
||||
local isAot = byte(s, i + 1) == 91
|
||||
local keys, ni = key(i + (if isAot then 2 else 1))
|
||||
if not keys then
|
||||
return nil, errMsg, errAt
|
||||
end
|
||||
ni = ws(ni)
|
||||
if isAot then
|
||||
if sub(s, ni, ni + 1) ~= "]]" then
|
||||
return nil, "expected ']]'", ni - 1
|
||||
end
|
||||
ni += 2
|
||||
else
|
||||
if byte(s, ni) ~= 93 then
|
||||
return nil, "expected ']'", ni - 1
|
||||
end
|
||||
ni += 1
|
||||
end
|
||||
-- walk to the parent
|
||||
local t = root
|
||||
for j = 1, #keys - 1 do
|
||||
local k = keys[j]
|
||||
local x = t[k]
|
||||
if x == nil then
|
||||
local nt = newTable("implicit")
|
||||
Types.set(t, k, nt)
|
||||
t = nt
|
||||
elseif kinds[x] and kinds[x] ~= "inline" then
|
||||
t = x
|
||||
elseif aot[x] then
|
||||
t = x[#x]
|
||||
else
|
||||
return nil, "cannot define a table under " .. k .. " (already defined)", at - 1
|
||||
end
|
||||
end
|
||||
local k = keys[#keys]
|
||||
local x = t[k]
|
||||
if isAot then
|
||||
local arr = x
|
||||
if arr == nil then
|
||||
arr = {}
|
||||
aot[arr] = true
|
||||
Types.set(t, k, arr)
|
||||
elseif not aot[arr] then
|
||||
return nil, "cannot define an array of tables " .. k .. " (already defined)", at - 1
|
||||
end
|
||||
local nt = newTable("explicit")
|
||||
table.insert(arr, nt)
|
||||
cur = nt
|
||||
else
|
||||
if x == nil then
|
||||
local nt = newTable("explicit")
|
||||
Types.set(t, k, nt)
|
||||
cur = nt
|
||||
elseif kinds[x] == "implicit" then
|
||||
kinds[x] = "explicit"
|
||||
cur = x
|
||||
else
|
||||
return nil, "table " .. k .. " defined twice", at - 1
|
||||
end
|
||||
end
|
||||
section += 1
|
||||
local e = eol(ni)
|
||||
if not e then
|
||||
return nil, errMsg, errAt
|
||||
end
|
||||
i = e
|
||||
else
|
||||
local at = i
|
||||
local keys, ni = key(i)
|
||||
if not keys then
|
||||
return nil, errMsg, errAt
|
||||
end
|
||||
ni = ws(ni)
|
||||
if byte(s, ni) ~= 61 then
|
||||
return nil, "expected '='", ni - 1
|
||||
end
|
||||
local v, vi = value(ws(ni + 1))
|
||||
if v == nil then
|
||||
return nil, errMsg, errAt
|
||||
end
|
||||
if not assign(cur, keys, v, section, at) then
|
||||
return nil, errMsg, errAt
|
||||
end
|
||||
local e = eol(vi)
|
||||
if not e then
|
||||
return nil, errMsg, errAt
|
||||
end
|
||||
i = e
|
||||
end
|
||||
end
|
||||
return root, nil, nil
|
||||
end
|
||||
|
||||
return Decode
|
||||
@@ -0,0 +1,214 @@
|
||||
--!strict
|
||||
-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables
|
||||
-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as
|
||||
-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date
|
||||
-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil,
|
||||
-- message.
|
||||
local Types = require("@formats/Types")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
|
||||
local Encode = {}
|
||||
|
||||
local format, gsub, find = string.format, string.gsub, string.find
|
||||
|
||||
export type Options = {
|
||||
inline: boolean?, -- write every sub-table as an inline table (default false: [sections])
|
||||
indent: (number | string)?, -- indent keys of nested sections (default none)
|
||||
}
|
||||
|
||||
local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" }
|
||||
for c = 0, 31 do
|
||||
local ch = string.char(c)
|
||||
if not ESC[ch] then
|
||||
ESC[ch] = format("\\u%04X", c)
|
||||
end
|
||||
end
|
||||
|
||||
local function quote(str: string): string
|
||||
return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"'
|
||||
end
|
||||
Encode.quote = quote
|
||||
|
||||
local function keyText(k: string): string
|
||||
if find(k, "^[%w_%-]+$") then
|
||||
return k
|
||||
end
|
||||
return quote(k)
|
||||
end
|
||||
|
||||
-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays
|
||||
local function isMap(t: { [any]: any }): boolean
|
||||
if Types.isObject(t) then
|
||||
return true
|
||||
end
|
||||
local n = #t
|
||||
if n == 0 then
|
||||
return next(t) ~= nil
|
||||
end
|
||||
local count = 0
|
||||
for _ in next, t do
|
||||
count += 1
|
||||
end
|
||||
return count ~= n
|
||||
end
|
||||
|
||||
local function isDate(v: any): boolean
|
||||
return Types.Date.is(v)
|
||||
end
|
||||
|
||||
-- an array of tables: non-empty, every element a map
|
||||
local function isAot(v: any): boolean
|
||||
if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then
|
||||
return false
|
||||
end
|
||||
for _, x in v do
|
||||
if type(x) ~= "table" or isDate(x) or not isMap(x) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function keysOf(t: { [any]: any }): ({ string }?, string?)
|
||||
local keys = Types.keys(t)
|
||||
for _, k in keys do
|
||||
if type(k) ~= "string" then
|
||||
return nil, "table key of type " .. type(k)
|
||||
end
|
||||
end
|
||||
return keys :: any, nil
|
||||
end
|
||||
|
||||
type State = { seen: { [any]: boolean }, err: string? }
|
||||
|
||||
local inlineValue: (st: State, v: any) -> string?
|
||||
|
||||
local function scalar(st: State, v: any): string?
|
||||
local tv = type(v)
|
||||
if v == Types.null then
|
||||
st.err = "TOML has no null"
|
||||
return nil
|
||||
elseif tv == "string" then
|
||||
return quote(v)
|
||||
elseif tv == "boolean" then
|
||||
return if v then "true" else "false"
|
||||
elseif tv == "number" then
|
||||
if v ~= v then
|
||||
return "nan"
|
||||
elseif v == math.huge then
|
||||
return "inf"
|
||||
elseif v == -math.huge then
|
||||
return "-inf"
|
||||
elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then
|
||||
return format("%d", v)
|
||||
end
|
||||
local t = Json.number(v) :: string
|
||||
if not find(t, "[%.eEn]") then
|
||||
t ..= ".0"
|
||||
end
|
||||
return t
|
||||
elseif tv == "table" and isDate(v) then
|
||||
return tostring(v)
|
||||
elseif tv == "table" then
|
||||
return inlineValue(st, v)
|
||||
end
|
||||
st.err = "cannot encode a " .. tv
|
||||
return nil
|
||||
end
|
||||
|
||||
function inlineValue(st: State, v: any): string?
|
||||
if st.seen[v] then
|
||||
st.err = "a table contains itself"
|
||||
return nil
|
||||
end
|
||||
st.seen[v] = true
|
||||
local parts = {}
|
||||
if isMap(v) then
|
||||
local keys, kerr = keysOf(v)
|
||||
if not keys then
|
||||
st.err = kerr
|
||||
return nil
|
||||
end
|
||||
for _, k in keys do
|
||||
local s = scalar(st, v[k])
|
||||
if not s then
|
||||
return nil
|
||||
end
|
||||
table.insert(parts, keyText(k) .. " = " .. s)
|
||||
end
|
||||
st.seen[v] = nil
|
||||
return if #parts == 0 then "{}" else "{ " .. table.concat(parts, ", ") .. " }"
|
||||
end
|
||||
for i = 1, #v do
|
||||
local s = scalar(st, v[i])
|
||||
if not s then
|
||||
return nil
|
||||
end
|
||||
parts[i] = s
|
||||
end
|
||||
st.seen[v] = nil
|
||||
return "[" .. table.concat(parts, ", ") .. "]"
|
||||
end
|
||||
|
||||
local function section(st: State, t: any, path: string, out: { string }, inlineAll: boolean, ind: string, depth: number): boolean
|
||||
if st.seen[t] then
|
||||
st.err = "a table contains itself"
|
||||
return false
|
||||
end
|
||||
st.seen[t] = true
|
||||
local keys, kerr = keysOf(t)
|
||||
if not keys then
|
||||
st.err = kerr
|
||||
return false
|
||||
end
|
||||
local pad = string.rep(ind, depth)
|
||||
local subs = {}
|
||||
for _, k in keys do
|
||||
local v = t[k]
|
||||
if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then
|
||||
table.insert(subs, k)
|
||||
else
|
||||
local s = scalar(st, v)
|
||||
if not s then
|
||||
return false
|
||||
end
|
||||
table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n")
|
||||
end
|
||||
end
|
||||
for _, k in subs do
|
||||
local v = t[k]
|
||||
local p = (if path == "" then "" else path .. ".") .. keyText(k)
|
||||
if isMap(v) then
|
||||
table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[" .. p .. "]\n")
|
||||
if not section(st, v, p, out, inlineAll, ind, depth + 1) then
|
||||
return false
|
||||
end
|
||||
else
|
||||
for _, el in v do
|
||||
table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[[" .. p .. "]]\n")
|
||||
if not section(st, el, p, out, inlineAll, ind, depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
st.seen[t] = nil
|
||||
return true
|
||||
end
|
||||
|
||||
-- encode(t, opts) -> text | nil, message
|
||||
function Encode.encode(t: any, opts: Options?): (string?, string?)
|
||||
if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then
|
||||
return nil, "the top level must be a table with string keys"
|
||||
end
|
||||
local o: Options = opts or {}
|
||||
local ind = if type(o.indent) == "number" then string.rep(" ", o.indent) elseif type(o.indent) == "string" then o.indent else ""
|
||||
local st: State = { seen = {}, err = nil }
|
||||
local out = {}
|
||||
if not section(st, t, "", out, o.inline == true, ind, 0) then
|
||||
return nil, st.err
|
||||
end
|
||||
return table.concat(out), nil
|
||||
end
|
||||
|
||||
return Encode
|
||||
@@ -0,0 +1,70 @@
|
||||
--!strict
|
||||
-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables,
|
||||
-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range
|
||||
-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules
|
||||
-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables /
|
||||
-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to
|
||||
-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral
|
||||
-- values are written as integers).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Decode = require("@formats/data/toml/Decode")
|
||||
local Encode = require("@formats/data/toml/Encode")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Toml = {
|
||||
name = "toml",
|
||||
category = "data",
|
||||
extensions = { "toml" },
|
||||
mime = { "application/toml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
|
||||
caps = { decode = true, encode = true, ordered = true, dates = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Decode.Options
|
||||
export type EncodeOptions = Encode.Options
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same,
|
||||
-- so this stays low and the extension decides
|
||||
function Toml.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(512)
|
||||
if string.find(head, "%z") then
|
||||
return 0
|
||||
end
|
||||
for line in string.gmatch(head, "[^\n]+") do
|
||||
local l = string.match(line, "^[ \t]*(.-)[ \t\r]*$") :: string
|
||||
if l ~= "" and string.sub(l, 1, 1) ~= "#" then
|
||||
if string.match(l, "^%[%[?[%w_%-%.\"' ]+%]%]?$") or string.match(l, "^[%w_%-%.\"']+[ \t]*=[ \t]*[\"'%[{%dtf%+%-in]") then
|
||||
return 0.2
|
||||
end
|
||||
return 0
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Toml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
local v, msg, at = Decode.decode(s, opts)
|
||||
if v == nil then
|
||||
local m = tostring(msg)
|
||||
local code = if string.find(m, "unterminated", 1, true) then Err.TRUNCATED else Err.CORRUPT
|
||||
return nil, Err.new(code, m, at)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Toml.encode(value: any, opts: EncodeOptions?): (buffer?, 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 buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Toml
|
||||
@@ -0,0 +1,57 @@
|
||||
--!strict
|
||||
-- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports:
|
||||
-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not
|
||||
-- supported: external entities / DTDs, validation.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local XmlFormat = {
|
||||
name = "xml",
|
||||
category = "data",
|
||||
extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
|
||||
mime = { "application/xml", "text/xml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
|
||||
caps = { decode = true, encode = true, namespaces = true, streaming = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Xml.DecodeOptions
|
||||
export type EncodeOptions = Xml.EncodeOptions
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function XmlFormat.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(64)
|
||||
if string.sub(head, 1, 3) == "\239\187\191" then
|
||||
head = string.sub(head, 4)
|
||||
end
|
||||
if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then
|
||||
return 0.5
|
||||
end
|
||||
if string.match(head, "^[ \t\r\n]*<[%a!]") then
|
||||
return 0.3
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?)
|
||||
return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(node) ~= "table" or type(node.name) ~= "string" then
|
||||
return nil, Err.new(Err.ARG, "expected an XmlNode")
|
||||
end
|
||||
local s, err = Xml.encode(node, opts)
|
||||
if not s then
|
||||
return nil, err
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return XmlFormat
|
||||
@@ -0,0 +1,339 @@
|
||||
--!strict
|
||||
-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when
|
||||
-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars
|
||||
-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as
|
||||
-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad
|
||||
-- values (cycles, functions, collection keys) return nil, message.
|
||||
local Types = require("@formats/Types")
|
||||
local Parse = require("@formats/data/yaml/Parse")
|
||||
|
||||
local Emit = {}
|
||||
|
||||
export type Options = {
|
||||
indent: number?, -- spaces per level (default 2)
|
||||
all: boolean?, -- the value is an array of documents, written with "---" separators
|
||||
explicitStart: boolean?, -- start the (first) document with "---" (default false)
|
||||
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order)
|
||||
null: any?, -- the value written as null besides Types.null
|
||||
}
|
||||
|
||||
local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub
|
||||
|
||||
local YAML11 = {
|
||||
y = true, Y = true, yes = true, Yes = true, YES = true, n = true, N = true, no = true, No = true, NO = true,
|
||||
on = true, On = true, ON = true, off = true, Off = true, OFF = true,
|
||||
}
|
||||
|
||||
local function number(x: number): string
|
||||
if x ~= x then
|
||||
return ".nan"
|
||||
elseif x == math.huge then
|
||||
return ".inf"
|
||||
elseif x == -math.huge then
|
||||
return "-.inf"
|
||||
elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then
|
||||
if x == 0 and 1 / x < 0 then
|
||||
return "-0.0"
|
||||
end
|
||||
return format("%d", x)
|
||||
end
|
||||
for _, f in { "%.15g", "%.16g", "%.17g" } do
|
||||
local t = format(f, x)
|
||||
if tonumber(t) == x then
|
||||
if not find(t, "[%.eEn]") then
|
||||
t ..= ".0"
|
||||
end
|
||||
return t
|
||||
end
|
||||
end
|
||||
return format("%.17g", x)
|
||||
end
|
||||
|
||||
local DQ: { [string]: string } = {
|
||||
["\\"] = "\\\\",
|
||||
['"'] = '\\"',
|
||||
["\n"] = "\\n",
|
||||
["\t"] = "\\t",
|
||||
["\r"] = "\\r",
|
||||
["\0"] = "\\0",
|
||||
["\27"] = "\\e",
|
||||
}
|
||||
local function dquote(s: string): string
|
||||
s = gsub(s, '[%z\1-\31\127\\"]', function(c: string): string
|
||||
return DQ[c] or format("\\x%02x", byte(c))
|
||||
end)
|
||||
-- the Unicode line / paragraph separators and NEL would be folded as line breaks: escape them
|
||||
s = gsub(s, "\226\128\168", "\\L")
|
||||
s = gsub(s, "\226\128\169", "\\P")
|
||||
s = gsub(s, "\194\133", "\\N")
|
||||
return '"' .. s .. '"'
|
||||
end
|
||||
|
||||
local function plainOk(s: string): boolean
|
||||
if s == "" or YAML11[s] then
|
||||
return false
|
||||
end
|
||||
if Parse.resolve(s, Types.null) ~= s then
|
||||
return false
|
||||
end
|
||||
if find(s, "^[%s]") or find(s, "[%s]$") then
|
||||
return false
|
||||
end
|
||||
if find(s, "^[%-%?:,%[%]{}#&%*!|>'\"%%@`]") or find(s, "^%.%.%.") then
|
||||
return false
|
||||
end
|
||||
if find(s, ": ", 1, true) or find(s, " #", 1, true) or find(s, ":$") or find(s, "[%z\1-\31\127]") then
|
||||
return false
|
||||
end
|
||||
if find(s, "\226\128\168") or find(s, "\226\128\169") or find(s, "\194\133") or find(s, "\239\187\191") then
|
||||
return false
|
||||
end
|
||||
-- not invalid UTF-8 (the reader treats the text as bytes, but other tools will not)
|
||||
if find(s, "[\128-\255]") and not utf8.len(s) then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- a string as a scalar on a line at indentation ind (for block scalars)
|
||||
local function str(s: string, ind: string, key: boolean): string
|
||||
if plainOk(s) then
|
||||
return s
|
||||
end
|
||||
if not key and find(s, "\n", 1, true) and not find(s, "[%z\1-\9\11-\31\127]") and not find(s, "[ ]\n") and not find(s, " $")
|
||||
and not find(s, "^[ \n]") and not find(s, "\226\128[\168\169]") and not find(s, "\194\133") and (not find(s, "[\128-\255]") or utf8.len(s))
|
||||
then
|
||||
local trailing = #(string.match(s, "\n*$") :: string)
|
||||
local body = string.sub(s, 1, #s - trailing)
|
||||
local chomp = if trailing == 0 then "-" elseif trailing == 1 then "" else "+"
|
||||
local lines = string.split(body, "\n")
|
||||
local out = { "|" .. chomp }
|
||||
for _, l in lines do
|
||||
table.insert(out, if l == "" then "" else ind .. l)
|
||||
end
|
||||
for _ = 2, trailing do
|
||||
table.insert(out, "")
|
||||
end
|
||||
return table.concat(out, "\n")
|
||||
end
|
||||
return dquote(s)
|
||||
end
|
||||
|
||||
local function b64(b: buffer): string
|
||||
local A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
local out = {}
|
||||
local n = buffer.len(b)
|
||||
for i = 0, n - 1, 3 do
|
||||
local a1 = buffer.readu8(b, i)
|
||||
local a2 = if i + 1 < n then buffer.readu8(b, i + 1) else 0
|
||||
local a3 = if i + 2 < n then buffer.readu8(b, i + 2) else 0
|
||||
local v = a1 * 65536 + a2 * 256 + a3
|
||||
local c1, c2, c3, c4 = v // 262144, (v // 4096) % 64, (v // 64) % 64, v % 64
|
||||
table.insert(out, string.sub(A, c1 + 1, c1 + 1) .. string.sub(A, c2 + 1, c2 + 1)
|
||||
.. (if i + 1 < n then string.sub(A, c3 + 1, c3 + 1) else "=") .. (if i + 2 < n then string.sub(A, c4 + 1, c4 + 1) else "="))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function isArray(t: { [any]: any }): boolean
|
||||
if Types.isObject(t) then
|
||||
return false
|
||||
end
|
||||
local n = #t
|
||||
if n == 0 then
|
||||
return next(t) == nil
|
||||
end
|
||||
if next(t, n) ~= nil then
|
||||
return false
|
||||
end
|
||||
local c = 0
|
||||
for _ in next, t do
|
||||
c += 1
|
||||
end
|
||||
return c == n
|
||||
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
|
||||
|
||||
type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? }
|
||||
|
||||
-- count references to tables (anchors for those seen twice); false on a cycle
|
||||
local function count(st: St, v: any, onStack: { [any]: boolean }): boolean
|
||||
if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then
|
||||
return true
|
||||
end
|
||||
if onStack[v] then
|
||||
st.err = "a cycle (YAML aliases cannot point at their own ancestors here)"
|
||||
return false
|
||||
end
|
||||
local r = st.refs[v]
|
||||
st.refs[v] = (r or 0) + 1
|
||||
if r then
|
||||
return true
|
||||
end
|
||||
onStack[v] = true
|
||||
for k, x in next, v do
|
||||
if not count(st, k, onStack) or not count(st, x, onStack) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
onStack[v] = nil
|
||||
return true
|
||||
end
|
||||
|
||||
-- scalar text for a non-collection value, or nil
|
||||
local function scalar(st: St, v: any, ind: string, key: boolean): string?
|
||||
local tv = type(v)
|
||||
if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then
|
||||
return "null"
|
||||
elseif tv == "boolean" then
|
||||
return if v then "true" else "false"
|
||||
elseif tv == "number" then
|
||||
return number(v)
|
||||
elseif tv == "string" then
|
||||
return str(v, ind, key)
|
||||
elseif tv == "buffer" then
|
||||
return "!!binary " .. b64(v)
|
||||
elseif tv == "table" and Types.Date.is(v) then
|
||||
return tostring(v)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local write: (st: St, v: any, depth: number) -> string?
|
||||
|
||||
-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline)
|
||||
function write(st: St, v: any, depth: number): string?
|
||||
local ind = string.rep(" ", st.step * (depth + 1))
|
||||
local s = scalar(st, v, ind, false)
|
||||
if s then
|
||||
return " " .. s
|
||||
end
|
||||
if type(v) ~= "table" then
|
||||
st.err = "cannot write a " .. type(v)
|
||||
return nil
|
||||
end
|
||||
local prefix = ""
|
||||
if st.refs[v] and st.refs[v] > 1 then
|
||||
local a = st.anchors[v]
|
||||
if a then
|
||||
return " *" .. a
|
||||
end
|
||||
st.nextId += 1
|
||||
a = "id" .. format("%03d", st.nextId)
|
||||
st.anchors[v] = a
|
||||
prefix = " &" .. a
|
||||
end
|
||||
local pad = string.rep(" ", st.step * depth)
|
||||
if isArray(v) and not Types.isObject(v) then
|
||||
if #v == 0 then
|
||||
return prefix .. " []"
|
||||
end
|
||||
local parts = {}
|
||||
for _, x in v do
|
||||
local t = write(st, x, depth + 1)
|
||||
if not t then
|
||||
return nil
|
||||
end
|
||||
table.insert(parts, pad .. "-" .. t)
|
||||
end
|
||||
return prefix .. "\n" .. table.concat(parts, "\n")
|
||||
end
|
||||
local keys
|
||||
if Types.isObject(v) then
|
||||
keys = Types.keys(v)
|
||||
else
|
||||
keys = {}
|
||||
for k in next, v do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
if st.sort then
|
||||
table.sort(keys, keyLess)
|
||||
end
|
||||
end
|
||||
if #keys == 0 then
|
||||
return prefix .. " {}"
|
||||
end
|
||||
local parts = {}
|
||||
for _, k in keys do
|
||||
local ks = scalar(st, k, "", true)
|
||||
if not ks or (type(k) == "table" and not Types.Date.is(k) and k ~= Types.null) then
|
||||
st.err = "mapping keys must be scalars"
|
||||
return nil
|
||||
end
|
||||
local t = write(st, v[k], depth + 1)
|
||||
if not t then
|
||||
return nil
|
||||
end
|
||||
table.insert(parts, pad .. ks .. ":" .. t)
|
||||
end
|
||||
return prefix .. "\n" .. table.concat(parts, "\n")
|
||||
end
|
||||
|
||||
local function document(st: St, v: any): string?
|
||||
local t = write(st, v, 0)
|
||||
if not t then
|
||||
return nil
|
||||
end
|
||||
-- the top level: drop the separator write() put before the first line
|
||||
if string.sub(t, 1, 1) == "\n" then
|
||||
return string.sub(t, 2)
|
||||
end
|
||||
local body = string.sub(t, 2)
|
||||
if string.sub(body, 1, 1) == "&" then
|
||||
-- "&id001\n- a": an anchored top-level collection
|
||||
return body
|
||||
end
|
||||
return body
|
||||
end
|
||||
|
||||
-- encode(v, opts) -> text | nil, message
|
||||
function Emit.encode(v: any, opts: Options?): (string?, string?)
|
||||
local o: Options = opts or {}
|
||||
local st: St = {
|
||||
out = {},
|
||||
step = math.clamp(math.floor(o.indent or 2), 1, 10),
|
||||
sort = o.sortKeys ~= false,
|
||||
null = o.null,
|
||||
refs = {},
|
||||
anchors = {},
|
||||
nextId = 0,
|
||||
err = nil,
|
||||
}
|
||||
local docs = if o.all then v else { v }
|
||||
if type(docs) ~= "table" then
|
||||
return nil, "all: expected an array of documents"
|
||||
end
|
||||
local parts = {}
|
||||
for i, d in docs do
|
||||
st.refs, st.anchors = {}, {}
|
||||
if not count(st, d, {}) then
|
||||
return nil, st.err
|
||||
end
|
||||
local t = document(st, d)
|
||||
if not t then
|
||||
return nil, st.err
|
||||
end
|
||||
local start = i > 1 or o.explicitStart
|
||||
if start then
|
||||
-- a scalar / [] / {} can share the "---" line; a collection starts on the next one
|
||||
local block = type(d) == "table" and d ~= Types.null and not Types.Date.is(d) and next(d) ~= nil
|
||||
local sep = if block and not string.find(t, "^&") then "---\n" else "--- "
|
||||
table.insert(parts, sep .. t .. "\n")
|
||||
else
|
||||
table.insert(parts, t .. "\n")
|
||||
end
|
||||
end
|
||||
return table.concat(parts), nil
|
||||
end
|
||||
|
||||
return Emit
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,77 @@
|
||||
--!strict
|
||||
-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain /
|
||||
-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as
|
||||
-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null
|
||||
-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams.
|
||||
-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables).
|
||||
-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore";
|
||||
-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Parse = require("@formats/data/yaml/Parse")
|
||||
local Emit = require("@formats/data/yaml/Emit")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Yaml = {
|
||||
name = "yaml",
|
||||
category = "data",
|
||||
extensions = { "yaml", "yml" },
|
||||
mime = { "application/yaml", "application/x-yaml", "text/yaml" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Parse.Options
|
||||
export type EncodeOptions = Emit.Options
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Yaml.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(256)
|
||||
if string.find(head, "%z") then
|
||||
return 0
|
||||
end
|
||||
if string.match(head, "^%%YAML ") then
|
||||
return 0.9
|
||||
end
|
||||
if string.match(head, "^%-%-%-[ \r\n]") then
|
||||
return 0.5
|
||||
end
|
||||
local line = string.match(head, "^[ \t\r\n]*([^\r\n]*)")
|
||||
if line and (string.match(line, "^[%w_%-\"']+[%w_%- \"']*:[ ]") or string.match(line, "^[%w_%-]+:$") or string.match(line, "^%- ")) then
|
||||
return 0.2
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err
|
||||
function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
local docs, code, msg, at = Parse.run(text, opts)
|
||||
if not docs then
|
||||
return nil, Err.new(code, msg, at)
|
||||
end
|
||||
if opts and opts.all then
|
||||
return docs, nil
|
||||
end
|
||||
local first = docs[1]
|
||||
if first == nil then
|
||||
return if opts and opts.null ~= nil then opts.null else Types.null, nil
|
||||
end
|
||||
return first, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents)
|
||||
function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local s, err = Emit.encode(value, opts)
|
||||
if not s then
|
||||
return nil, Err.new(Err.ARG, err or "cannot encode")
|
||||
end
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
|
||||
return Yaml
|
||||
Reference in new issue
Block a user