data: data/cbor (RFC 8949: indefinite lengths, half floats, tags 0/1 dates, bignums, self-describe, tagged / simple / undefined values, sequences); RFC appendix A + cbor2 fixtures, byte-exact re-encode
This commit is contained in:
1 parent
4f44e5ebe3
commit
2ef071cb16
6 files changed
+952
No files matched your search
@@ -26,6 +26,18 @@ local list: { Entry } = {
|
||||
return require("@formats/image/png")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "cbor",
|
||||
category = "data",
|
||||
path = "data/cbor",
|
||||
extensions = { "cbor" },
|
||||
mime = { "application/cbor", "application/cbor-seq" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, binary = true, ordered = true, tags = true },
|
||||
load = function()
|
||||
return require("@formats/data/cbor")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "json",
|
||||
category = "data",
|
||||
|
||||
@@ -0,0 +1,610 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil,
|
||||
-- message, offset.
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Codec = {}
|
||||
|
||||
local TWO32 = 4294967296
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ value types
|
||||
local TaggedMeta = { __tostring = function(t: any): string
|
||||
return "cbor.tag(" .. t.tag .. ")"
|
||||
end }
|
||||
local SimpleMeta = { __tostring = function(s: any): string
|
||||
return "cbor.simple(" .. s.value .. ")"
|
||||
end }
|
||||
-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret
|
||||
function Codec.tagged(tag: number, value: any): { tag: number, value: any }
|
||||
return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any
|
||||
end
|
||||
function Codec.isTagged(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == TaggedMeta
|
||||
end
|
||||
-- simple(n) -> an unassigned simple value (0..19, 32..255)
|
||||
function Codec.simple(n: number): { value: number }
|
||||
return setmetatable({ value = n }, SimpleMeta) :: any
|
||||
end
|
||||
function Codec.isSimple(v: any): boolean
|
||||
return type(v) == "table" and getmetatable(v) == SimpleMeta
|
||||
end
|
||||
Codec.undefined = table.freeze(setmetatable({}, { __tostring = function()
|
||||
return "undefined"
|
||||
end }))
|
||||
|
||||
-- decimal text of a big-endian unsigned byte string (any length)
|
||||
local function bigText(s: string): string
|
||||
local limbs = {} -- base 1e7, little-endian
|
||||
for i = 1, #s do
|
||||
local carry = string.byte(s, i)
|
||||
for k = 1, #limbs do
|
||||
local v = limbs[k] * 256 + carry
|
||||
limbs[k] = v % 10000000
|
||||
carry = v // 10000000
|
||||
end
|
||||
while carry > 0 do
|
||||
table.insert(limbs, carry % 10000000)
|
||||
carry //= 10000000
|
||||
end
|
||||
end
|
||||
if #limbs == 0 then
|
||||
return "0"
|
||||
end
|
||||
local out = { string.format("%d", limbs[#limbs]) }
|
||||
for k = #limbs - 1, 1, -1 do
|
||||
table.insert(out, string.format("%07d", limbs[k]))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
-- text + 1 for a decimal string
|
||||
local function incText(s: string): string
|
||||
local digits = table.create(#s)
|
||||
for i = 1, #s do
|
||||
digits[i] = string.byte(s, i) - 48
|
||||
end
|
||||
local i = #digits
|
||||
while i >= 1 do
|
||||
if digits[i] < 9 then
|
||||
digits[i] += 1
|
||||
break
|
||||
end
|
||||
digits[i] = 0
|
||||
i -= 1
|
||||
end
|
||||
local out = table.create(#digits)
|
||||
for k, d in digits do
|
||||
out[k] = string.char(48 + d)
|
||||
end
|
||||
return (if i == 0 then "1" else "") .. table.concat(out)
|
||||
end
|
||||
|
||||
export type DecodeOptions = {
|
||||
bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text
|
||||
null: any?, -- the value for null (default Types.null)
|
||||
undefined: any?, -- the value for undefined (default Codec.undefined)
|
||||
maxDepth: number?, -- default 512
|
||||
dates: boolean?, -- tags 0 / 1 as Types.Date (default true)
|
||||
}
|
||||
|
||||
type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean }
|
||||
|
||||
local BREAK = {} -- the 0xFF stop code, inside indefinite items
|
||||
|
||||
-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31)
|
||||
local function arg(st: St, ai: number): (number?, string?, string?)
|
||||
local r = st.r
|
||||
if ai < 24 then
|
||||
return ai, nil, nil
|
||||
elseif ai == 24 then
|
||||
return r:u8(), nil, nil
|
||||
elseif ai == 25 then
|
||||
return r:u16be(), nil, nil
|
||||
elseif ai == 26 then
|
||||
return r:u32be(), nil, nil
|
||||
elseif ai == 27 then
|
||||
local hi, lo = r:u32be(), r:u32be()
|
||||
if st.big and hi >= 0x200000 then
|
||||
return hi * TWO32 + lo, bigText(string.char(hi // 16777216, (hi // 65536) % 256, (hi // 256) % 256, hi % 256, lo // 16777216, (lo // 65536) % 256, (lo // 256) % 256, lo % 256)), nil
|
||||
end
|
||||
return hi * TWO32 + lo, nil, nil
|
||||
elseif ai == 31 then
|
||||
return nil, nil, nil
|
||||
end
|
||||
return nil, nil, "reserved additional information " .. ai
|
||||
end
|
||||
|
||||
local item: (st: St, depth: number) -> (any, string?)
|
||||
|
||||
local function chunks(st: St, major: number, depth: number): (string?, string?)
|
||||
local parts = {}
|
||||
while true do
|
||||
local r = st.r
|
||||
local ib = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if ib == 0xFF then
|
||||
return table.concat(parts), nil
|
||||
end
|
||||
if ib // 32 ~= major then
|
||||
return nil, "bad chunk in an indefinite string"
|
||||
end
|
||||
local n, _, e = arg(st, ib % 32)
|
||||
if e or n == nil then
|
||||
return nil, e or "nested indefinite string"
|
||||
end
|
||||
if r.err or not r:need(n) then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
table.insert(parts, r:string(n))
|
||||
end
|
||||
end
|
||||
|
||||
local function half(h: number): number
|
||||
local s = if h >= 32768 then -1 else 1
|
||||
local e = (h // 1024) % 32
|
||||
local m = h % 1024
|
||||
if e == 0 then
|
||||
return s * m * 2 ^ -24
|
||||
elseif e == 31 then
|
||||
return if m == 0 then s * math.huge else 0 / 0
|
||||
end
|
||||
return s * (1 + m / 1024) * 2 ^ (e - 15)
|
||||
end
|
||||
|
||||
local function tag(st: St, t: number, v: any): (any, string?)
|
||||
if t == 0 and st.dates then
|
||||
if type(v) ~= "string" then
|
||||
return nil, "tag 0 needs a text string"
|
||||
end
|
||||
local d = Types.Date.parse(v)
|
||||
if not d or not d.offset then
|
||||
return nil, "tag 0: bad date-time " .. v
|
||||
end
|
||||
return d, nil
|
||||
elseif t == 1 and st.dates then
|
||||
if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then
|
||||
return nil, "tag 1 needs a number"
|
||||
end
|
||||
return Types.Date.fromUnix(v), nil
|
||||
elseif t == 2 or t == 3 then
|
||||
if type(v) ~= "string" then
|
||||
return nil, "bignum tag needs a byte string"
|
||||
end
|
||||
local s = v :: string
|
||||
local n = 0
|
||||
for i = 1, #s do
|
||||
n = n * 256 + string.byte(s, i)
|
||||
end
|
||||
if n >= 9007199254740992 then
|
||||
-- exact text; as a number, read back from that text (correctly rounded, unlike the running sum)
|
||||
local text = bigText(s)
|
||||
if t == 3 then
|
||||
text = incText(text)
|
||||
end
|
||||
if st.big then
|
||||
return if t == 2 then text else "-" .. text, nil
|
||||
end
|
||||
local x = tonumber(text) :: number
|
||||
return if t == 2 then x else -x, nil
|
||||
end
|
||||
return if t == 2 then n else -1 - n, nil
|
||||
elseif t == 55799 then
|
||||
return v, nil
|
||||
end
|
||||
return Codec.tagged(t, v), nil
|
||||
end
|
||||
|
||||
function item(st: St, depth: number): (any, string?)
|
||||
if depth > st.maxDepth then
|
||||
return nil, "nested deeper than " .. st.maxDepth
|
||||
end
|
||||
local r = st.r
|
||||
local ib = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
local major, ai = ib // 32, ib % 32
|
||||
if major == 7 then
|
||||
if ai < 20 then
|
||||
return Codec.simple(ai), nil
|
||||
elseif ai == 20 then
|
||||
return false, nil
|
||||
elseif ai == 21 then
|
||||
return true, nil
|
||||
elseif ai == 22 then
|
||||
return st.null, nil
|
||||
elseif ai == 23 then
|
||||
return st.undef, nil
|
||||
elseif ai == 24 then
|
||||
local n = r:u8()
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if n < 32 then
|
||||
return nil, "bad two-byte simple value"
|
||||
end
|
||||
return Codec.simple(n), nil
|
||||
elseif ai == 25 then
|
||||
local h = r:u16be()
|
||||
return if r.err then nil else half(h), if r.err then "truncated" else nil
|
||||
elseif ai == 26 then
|
||||
local f = r:f32be()
|
||||
return if r.err then nil else f, if r.err then "truncated" else nil
|
||||
elseif ai == 27 then
|
||||
local f = r:f64be()
|
||||
return if r.err then nil else f, if r.err then "truncated" else nil
|
||||
elseif ai == 31 then
|
||||
return BREAK, nil
|
||||
end
|
||||
return nil, "reserved simple value"
|
||||
end
|
||||
local n, text, e = arg(st, ai)
|
||||
if e then
|
||||
return nil, e
|
||||
end
|
||||
if r.err then
|
||||
return nil, "truncated"
|
||||
end
|
||||
if major == 0 then
|
||||
if n == nil then
|
||||
return nil, "indefinite integer"
|
||||
end
|
||||
return text or n, nil
|
||||
elseif major == 1 then
|
||||
if n == nil then
|
||||
return nil, "indefinite integer"
|
||||
end
|
||||
if text then
|
||||
return "-" .. incText(text), nil
|
||||
end
|
||||
return -1 - n, nil
|
||||
elseif major == 2 or major == 3 then
|
||||
local s: string
|
||||
if n == nil then
|
||||
local c, ce = chunks(st, major, depth)
|
||||
if not c then
|
||||
return nil, ce
|
||||
end
|
||||
s = c
|
||||
else
|
||||
if not r:need(n) then
|
||||
return nil, "truncated string"
|
||||
end
|
||||
s = r:string(n)
|
||||
end
|
||||
if major == 2 then
|
||||
return buffer.fromstring(s), nil
|
||||
end
|
||||
if string.find(s, "[\128-\255]") and not utf8.len(s) then
|
||||
return nil, "invalid UTF-8 in a text string"
|
||||
end
|
||||
return s, nil
|
||||
elseif major == 4 then
|
||||
if n == nil then
|
||||
local t = {}
|
||||
while true do
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return t, nil
|
||||
end
|
||||
table.insert(t, v)
|
||||
end
|
||||
end
|
||||
if n > r:remaining() then
|
||||
return nil, "array count past the end"
|
||||
end
|
||||
local t = table.create(n)
|
||||
for k = 1, n do
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
t[k] = v
|
||||
end
|
||||
return t, nil
|
||||
elseif major == 5 then
|
||||
if n ~= nil and n * 2 > r:remaining() then
|
||||
return nil, "map count past the end"
|
||||
end
|
||||
local t = {}
|
||||
local order = {}
|
||||
local k = 0
|
||||
while n == nil or k < n do
|
||||
k += 1
|
||||
local key, ke = item(st, depth + 1)
|
||||
if ke then
|
||||
return nil, ke
|
||||
end
|
||||
if key == BREAK then
|
||||
if n == nil then
|
||||
break
|
||||
end
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
if key ~= key then
|
||||
return nil, "NaN map key"
|
||||
end
|
||||
if t[key] == nil then
|
||||
table.insert(order, key)
|
||||
end
|
||||
t[key] = v
|
||||
end
|
||||
return Types.object(t, order), nil
|
||||
else -- 6: tag
|
||||
if n == nil then
|
||||
return nil, "indefinite tag"
|
||||
end
|
||||
local v, ve = item(st, depth + 1)
|
||||
if ve then
|
||||
return nil, ve
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break"
|
||||
end
|
||||
-- bignum content arrives as a buffer: hand the tag its bytes
|
||||
if (n == 2 or n == 3) and type(v) == "buffer" then
|
||||
return tag(st, n, buffer.tostring(v))
|
||||
end
|
||||
return tag(st, n, v)
|
||||
end
|
||||
end
|
||||
|
||||
-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it)
|
||||
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local st: St = {
|
||||
r = r,
|
||||
big = o.bigInts == "string",
|
||||
null = if o.null ~= nil then o.null else Types.null,
|
||||
undef = if o.undefined ~= nil then o.undefined else Codec.undefined,
|
||||
maxDepth = o.maxDepth or 512,
|
||||
dates = o.dates ~= false,
|
||||
}
|
||||
local v, e = item(st, 0)
|
||||
if e then
|
||||
return nil, e, r.pos - r.base
|
||||
end
|
||||
if v == BREAK then
|
||||
return nil, "unexpected break", r.pos - r.base - 1
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
export type EncodeOptions = {
|
||||
compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false)
|
||||
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
|
||||
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
|
||||
dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds
|
||||
maxDepth: number?, -- default 512 (also catches cycles)
|
||||
}
|
||||
|
||||
type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? }
|
||||
|
||||
local function head(w: Bytes.Writer, major: number, n: number)
|
||||
local m = major * 32
|
||||
if n < 24 then
|
||||
w:u8(m + n)
|
||||
elseif n < 256 then
|
||||
w:u8(m + 24)
|
||||
w:u8(n)
|
||||
elseif n < 65536 then
|
||||
w:u8(m + 25)
|
||||
w:u16be(n)
|
||||
elseif n < TWO32 then
|
||||
w:u8(m + 26)
|
||||
w:u32be(n)
|
||||
elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1
|
||||
w:u8(m + 27)
|
||||
w:u32be(0xFFFFFFFF)
|
||||
w:u32be(0xFFFFFFFF)
|
||||
else
|
||||
w:u8(m + 27)
|
||||
w:u64be(n)
|
||||
end
|
||||
end
|
||||
|
||||
-- the half-float bits of x when x is exactly representable, else nil
|
||||
local function toHalf(x: number): number?
|
||||
if x ~= x then
|
||||
return 0x7E00
|
||||
end
|
||||
local sign = if x < 0 or (x == 0 and 1 / x < 0) then 0x8000 else 0
|
||||
local a = math.abs(x)
|
||||
if a == math.huge then
|
||||
return sign + 0x7C00
|
||||
end
|
||||
if a == 0 then
|
||||
return sign
|
||||
end
|
||||
local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1
|
||||
local exp = e - 1 + 15
|
||||
if exp >= 31 then
|
||||
return nil
|
||||
end
|
||||
if exp <= 0 then -- subnormal: a = mant * 2^-24
|
||||
local mant = a / 2 ^ -24
|
||||
if mant ~= math.floor(mant) or mant >= 1024 then
|
||||
return nil
|
||||
end
|
||||
return sign + mant
|
||||
end
|
||||
local frac = (m * 2 - 1) * 1024
|
||||
if frac ~= math.floor(frac) then
|
||||
return nil
|
||||
end
|
||||
return sign + exp * 1024 + frac
|
||||
end
|
||||
Codec.toHalf = toHalf
|
||||
|
||||
local function keyLess(a: any, b: any): boolean
|
||||
local ta, tb = type(a), type(b)
|
||||
if ta ~= tb then
|
||||
return ta < tb
|
||||
end
|
||||
if ta == "number" or ta == "string" then
|
||||
return a < b
|
||||
end
|
||||
return tostring(a) < tostring(b)
|
||||
end
|
||||
|
||||
local function isArray(t: any, emptyMap: boolean): boolean
|
||||
if Types.isObject(t) then
|
||||
return false
|
||||
end
|
||||
local n = #t
|
||||
if n == 0 then
|
||||
return next(t) == nil and not emptyMap
|
||||
end
|
||||
if next(t, n) ~= nil then
|
||||
return false
|
||||
end
|
||||
local c = 0
|
||||
for _ in next, t do
|
||||
c += 1
|
||||
end
|
||||
return c == n
|
||||
end
|
||||
|
||||
local scratch = buffer.create(8)
|
||||
|
||||
local function enc(st: ESt, v: any, depth: number): boolean
|
||||
local w = st.w
|
||||
local tv = type(v)
|
||||
if v == nil or v == Types.null then
|
||||
w:u8(0xF6)
|
||||
elseif v == Codec.undefined then
|
||||
w:u8(0xF7)
|
||||
elseif tv == "boolean" then
|
||||
w:u8(if v then 0xF5 else 0xF4)
|
||||
elseif tv == "number" then
|
||||
if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then
|
||||
if v >= 0 then
|
||||
head(w, 0, v)
|
||||
else
|
||||
head(w, 1, -1 - v)
|
||||
end
|
||||
else
|
||||
local h = if st.compact then toHalf(v) else nil
|
||||
if h then
|
||||
w:u8(0xF9)
|
||||
w:u16be(h)
|
||||
else
|
||||
buffer.writef32(scratch, 0, v)
|
||||
if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then
|
||||
w:u8(0xFA)
|
||||
w:f32be(v)
|
||||
else
|
||||
w:u8(0xFB)
|
||||
w:f64be(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
elseif tv == "string" then
|
||||
head(w, 3, #v)
|
||||
w:string(v)
|
||||
elseif tv == "buffer" then
|
||||
head(w, 2, buffer.len(v))
|
||||
w:bytes(v)
|
||||
elseif tv == "table" then
|
||||
if depth >= st.maxDepth then
|
||||
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
|
||||
return false
|
||||
end
|
||||
if Codec.isTagged(v) then
|
||||
if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then
|
||||
st.err = "bad tag number"
|
||||
return false
|
||||
end
|
||||
head(w, 6, v.tag)
|
||||
return enc(st, v.value, depth + 1)
|
||||
elseif Codec.isSimple(v) then
|
||||
local n = v.value
|
||||
if n < 20 then
|
||||
w:u8(0xE0 + n)
|
||||
elseif n >= 32 and n < 256 then
|
||||
w:u8(0xF8)
|
||||
w:u8(n)
|
||||
else
|
||||
st.err = "bad simple value " .. tostring(n)
|
||||
return false
|
||||
end
|
||||
elseif Types.Date.is(v) then
|
||||
if st.epoch then
|
||||
w:u8(0xC1)
|
||||
return enc(st, Types.Date.toUnix(v), depth + 1)
|
||||
end
|
||||
w:u8(0xC0)
|
||||
local s = tostring(v)
|
||||
head(w, 3, #s)
|
||||
w:string(s)
|
||||
elseif isArray(v, st.emptyMap) then
|
||||
local n = #v
|
||||
head(w, 4, n)
|
||||
for k = 1, n do
|
||||
if not enc(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
else
|
||||
local keys: { any }
|
||||
if Types.isObject(v) then
|
||||
keys = Types.keys(v)
|
||||
else
|
||||
keys = {}
|
||||
for k in next, v do
|
||||
table.insert(keys, k)
|
||||
end
|
||||
if st.sort then
|
||||
table.sort(keys, keyLess)
|
||||
end
|
||||
end
|
||||
head(w, 5, #keys)
|
||||
for _, k in keys do
|
||||
if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
st.err = "cannot encode a " .. tv
|
||||
return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- encode(v, opts) -> buffer | nil, message
|
||||
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local st: ESt = {
|
||||
w = Bytes.writer(256),
|
||||
compact = o.compactFloats == true,
|
||||
sort = o.sortKeys ~= false,
|
||||
emptyMap = o.emptyTable == "map",
|
||||
epoch = o.dates == "epoch",
|
||||
maxDepth = o.maxDepth or 512,
|
||||
err = nil,
|
||||
}
|
||||
if not enc(st, v, 0) then
|
||||
return nil, st.err
|
||||
end
|
||||
return st.w:finish(), nil
|
||||
end
|
||||
|
||||
return Codec
|
||||
@@ -0,0 +1,100 @@
|
||||
--!strict
|
||||
-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half /
|
||||
-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text,
|
||||
-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n),
|
||||
-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences
|
||||
-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats,
|
||||
-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Codec = require("@formats/data/cbor/Codec")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Cbor = {
|
||||
name = "cbor",
|
||||
category = "data",
|
||||
extensions = { "cbor" },
|
||||
mime = { "application/cbor", "application/cbor-seq" },
|
||||
deps = { "core/Err", "core/Bytes", "Types" },
|
||||
caps = { decode = true, encode = true, binary = true, ordered = true, tags = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = Codec.DecodeOptions & {
|
||||
all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item)
|
||||
}
|
||||
export type EncodeOptions = Codec.EncodeOptions & {
|
||||
all: boolean?, -- the value is an array of items, written as a sequence
|
||||
selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Cbor.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(3) == "\217\217\247" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function codeOf(e: string): string
|
||||
if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then
|
||||
return Err.TRUNCATED
|
||||
elseif string.find(e, "nested deeper", 1, true) then
|
||||
return Err.LIMIT
|
||||
end
|
||||
return Err.CORRUPT
|
||||
end
|
||||
|
||||
function Cbor.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
if o.all then
|
||||
local out = {}
|
||||
while not r:eof() do
|
||||
local v, e, at = Codec.decode(r, o)
|
||||
if e then
|
||||
return nil, Err.new(codeOf(e), e, at)
|
||||
end
|
||||
table.insert(out, v)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local v, e, at = Codec.decode(r, o)
|
||||
if e then
|
||||
return nil, Err.new(codeOf(e), e, at)
|
||||
end
|
||||
if not r:eof() then
|
||||
return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base)
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local w = Bytes.writer()
|
||||
if opts and opts.selfDescribe then
|
||||
w:string("\217\217\247")
|
||||
end
|
||||
local items = { value }
|
||||
if opts and opts.all then
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "all: expected an array of items")
|
||||
end
|
||||
items = value
|
||||
end
|
||||
for _, v in items do
|
||||
local b, e = Codec.encode(v, opts)
|
||||
if not b then
|
||||
return nil, Err.new(Err.ARG, e or "cannot encode")
|
||||
end
|
||||
w:bytes(b)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag
|
||||
Cbor.isTagged = Codec.isTagged
|
||||
Cbor.simple = Codec.simple -- simple(n) -> a simple value
|
||||
Cbor.isSimple = Codec.isSimple
|
||||
Cbor.undefined = Codec.undefined
|
||||
|
||||
return Cbor
|
||||
Reference in new issue
Block a user