rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+575
View File
@@ -0,0 +1,575 @@
--!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("@rosetta/core/Bytes")
local Types = require("@rosetta/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: { number } = table.create(#s) :: { number }
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: { string } = table.create(#digits) :: { string }
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 half = Bytes.half
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 :: number) > r:remaining() then
return nil, "array count past the end"
end
local t = table.create(n :: number)
for k = 1, n :: number 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 keyLess = Types.keyLess
local isArray = Types.isArray
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
+100
View File
@@ -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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Codec = require("@rosetta/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
+315
View File
@@ -0,0 +1,315 @@
--!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("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Json = require("@rosetta/codecs/text/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/text/Json", "core/Sniff" },
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 :: string, 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)
s = Sniff.dropBom(s)
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
+249
View File
@@ -0,0 +1,249 @@
--!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("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Json = require("@rosetta/codecs/text/Json")
-- ------------------------------------------------------------------------------------------------ contract
local Ini = {
name = "ini",
category = "data",
extensions = { "ini", "cfg", "conf", "inf", "desktop" },
mime = { "text/plain" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" },
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)
s = Sniff.dropBom(s)
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 :: string), 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 :: string) .. " 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
+91
View File
@@ -0,0 +1,91 @@
--!strict
-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/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/text/Json.lines. Not supported: JSON5 / comments / trailing commas.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Json = require("@rosetta/codecs/text/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/text/Json", "core/Sniff" },
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 = Sniff.text(r, 64)
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
+446
View File
@@ -0,0 +1,446 @@
--!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("@rosetta/core/Bytes")
local Types = require("@rosetta/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 keyLess = Types.keyLess
local isArray = Types.isArray
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
+90
View File
@@ -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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Codec = require("@rosetta/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.from(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
+60
View File
@@ -0,0 +1,60 @@
--!strict
-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and
-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and
-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib /
-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression
-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt.
-- Not supported: nothing in the format.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Nbt = require("@rosetta/codecs/text/Nbt")
-- ------------------------------------------------------------------------------------------------ contract
local NbtFormat = {
name = "nbt",
category = "data",
extensions = { "nbt", "dat", "mcstructure", "dat_old" },
mime = { "application/x-minecraft-nbt" },
deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" },
caps = { decode = true, encode = true, binary = true, ordered = true, typed = true },
}
export type DecodeOptions = Nbt.DecodeOptions
export type EncodeOptions = Nbt.EncodeOptions
-- ------------------------------------------------------------------------------------------------ sniff
function NbtFormat.sniff(r: Bytes.Reader): number
local p = Nbt.peek(r.buf, r.base, r.limit - r.base)
if not p or p.rootType ~= "compound" then
return 0
end
if p.compression ~= "none" then
return if p.firstType then 1 else 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension
end
return if p.firstType and p.firstName then 0.6 else 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
function NbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base)
if v == nil then
return nil, info
end
return v, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if value == nil then
return nil, Err.new(Err.ARG, "nothing to encode")
end
return Nbt.encode(value, opts)
end
-- ------------------------------------------------------------------------------------------------ extras
NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? }
NbtFormat.Nbt = Nbt
return NbtFormat
+271
View File
@@ -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("@rosetta/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
+306
View File
@@ -0,0 +1,306 @@
--!strict
-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
local Json = require("@rosetta/codecs/text/Json")
local Base64 = require("@rosetta/core/Base64")
local Binary = require("@rosetta/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", "core/Base64", "codecs/text/Xml", "codecs/text/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.from(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, "[&<>]", { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;" })), 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, { wrap = maxLine // 4 * 4 }), "[^\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
+63
View File
@@ -0,0 +1,63 @@
--!strict
-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over
-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt
-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent).
-- Not supported: the 1.21.5 bool(...) / uuid(...) operations.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local Nbt = require("@rosetta/codecs/text/Nbt")
-- ------------------------------------------------------------------------------------------------ contract
local SnbtFormat = {
name = "snbt",
category = "data",
extensions = { "snbt" },
mime = { "text/x-minecraft-snbt" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" },
caps = { decode = true, encode = true, ordered = true, typed = true },
}
export type DecodeOptions = { maxDepth: number? }
export type EncodeOptions = {
indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact)
quote: string?, -- '"' (default) or "'"
}
-- ------------------------------------------------------------------------------------------------ sniff
function SnbtFormat.sniff(r: Bytes.Reader): number
-- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings
local head = Sniff.text(r, 512, true)
local first = string.sub(head, 1, 1)
if first ~= "{" and first ~= "[" then
return 0
end
if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]")
or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'")
then
return 0.7
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function SnbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base))
return Nbt.parse(text, opts)
end
-- ------------------------------------------------------------------------------------------------ encode
function SnbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if value == nil then
return nil, Err.new(Err.ARG, "nothing to encode")
end
local s, e = Nbt.print(value, opts)
if not s then
return nil, e
end
return buffer.fromstring(s), nil
end
return SnbtFormat
+635
View File
@@ -0,0 +1,635 @@
--!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 Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/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 utf8char = Text.utf8char
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: { string } = {}
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 :: string)
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: string = (sign :: string) .. 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 :: string, "%d") then
return fail("bad float", i), 0
end
text ..= "e" .. es .. gsub(ed :: string, "_", "")
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
+214
View File
@@ -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("@rosetta/Types")
local Json = require("@rosetta/codecs/text/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
+70
View File
@@ -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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Decode = require("@rosetta/data/toml/Decode")
local Encode = require("@rosetta/data/toml/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Toml = {
name = "toml",
category = "data",
extensions = { "toml" },
mime = { "application/toml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" },
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
+55
View File
@@ -0,0 +1,55 @@
--!strict
-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/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("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/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/text/Xml", "core/Sniff" },
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 = Sniff.text(r, 64)
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
+299
View File
@@ -0,0 +1,299 @@
--!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("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
local Parse = require("@rosetta/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 isArray = Types.isArray
local keyLess = Types.keyLess
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 " .. Base64.encode(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
+77
View File
@@ -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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Parse = require("@rosetta/data/yaml/Parse")
local Emit = require("@rosetta/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", "core/Base64", "codecs/text/Text" },
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