568 lines
14 KiB
Luau
568 lines
14 KiB
Luau
--!strict
|
|
--!native
|
|
-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; 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 }
|
|
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
|
|
-- unassigned simple values: 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 }))
|
|
|
|
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
|
|
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")?,
|
|
null: any?, -- default Types.null
|
|
undefined: any?, -- default Codec.undefined
|
|
maxDepth: number?, -- default 512
|
|
dates: boolean?, -- default true
|
|
}
|
|
|
|
type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean }
|
|
|
|
local BREAK = {} -- 0xFF break stop code
|
|
|
|
-- additional information 31: indefinite length
|
|
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
|
|
-- read back from the exact 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
|
|
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
|
|
|
|
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?, -- default false
|
|
sortKeys: boolean?, -- default true
|
|
emptyTable: ("array" | "map")?, -- default "array"
|
|
dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch 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
|
|
|
|
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)
|
|
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
|
|
|
|
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
|