Files
rosetta/src/Formats/data/msgpack/Codec.luau
T

469 lines
12 KiB
Luau

--!strict
--!native
-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with
-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset.
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Codec = {}
local TWO32 = 4294967296
-- an extension value: { type = -128..127, data = buffer }
local ExtMeta = { __tostring = function(e: any): string
return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)"
end }
function Codec.ext(t: number, data: buffer): { type: number, data: buffer }
return setmetatable({ type = t, data = data }, ExtMeta) :: any
end
function Codec.isExt(v: any): boolean
return type(v) == "table" and getmetatable(v) == ExtMeta
end
-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact
local function u64text(hi: number, lo: number): string
if hi == 0 then
return string.format("%d", lo)
end
local digits = {}
-- long division by 10 on four 16-bit limbs
local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do
local rem = 0
for k = 1, 4 do
local cur = rem * 65536 + l[k]
l[k] = cur // 10
rem = cur % 10
end
table.insert(digits, 1, string.char(48 + rem))
end
return table.concat(digits)
end
Codec.u64text = u64text
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text
null: any?, -- the value for nil (default Types.null)
maxDepth: number?, -- nesting limit (default 512)
timestamps: boolean?, -- ext -1 as a Types.Date (default true)
ordered: boolean?, -- maps as Types.object with key order (default true)
}
type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean }
local function int64(st: St, signed: boolean): any
local r = st.r
local hi, lo = r:u32be(), r:u32be()
if signed and hi >= 0x80000000 then
-- negative: two's complement
local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo
if nlo == TWO32 then
nlo = 0
nhi += 1
end
if st.big and nhi >= 0x200000 then
return "-" .. u64text(nhi, nlo)
end
return -(nhi * TWO32 + nlo)
end
if st.big and hi >= 0x200000 then
return u64text(hi, lo)
end
return hi * TWO32 + lo
end
local value: (st: St, depth: number) -> (any, string?)
local function ext(st: St, n: number): (any, string?)
local r = st.r
local t = r:i8()
if r.err or not r:need(n) then
return nil, "truncated ext"
end
if t == -1 and st.ts then
local secs, ns = 0, 0
if n == 4 then
secs = r:u32be()
elseif n == 8 then
local hi, lo = r:u32be(), r:u32be()
ns = hi // 4
secs = (hi % 4) * TWO32 + lo
elseif n == 12 then
ns = r:u32be()
secs = r:i64be()
else
return nil, "bad timestamp length"
end
if ns > 999999999 then
return nil, "bad timestamp nanoseconds"
end
local d: any = Types.Date.fromUnix(secs)
d.nanosecond = ns
return d, nil
end
return Codec.ext(t, r:bytes(n)), nil
end
local function array(st: St, n: number, depth: number): (any, string?)
if n > st.r:remaining() then
return nil, "array count past the end"
end
local t = table.create(n)
for k = 1, n do
local v, e = value(st, depth + 1)
if e then
return nil, e
end
t[k] = v
end
return t, nil
end
local function map(st: St, n: number, depth: number): (any, string?)
if n * 2 > st.r:remaining() then
return nil, "map count past the end"
end
local t = {}
local order: { any }? = if st.ordered then table.create(n) else nil
for _ = 1, n do
local k, e = value(st, depth + 1)
if e then
return nil, e
end
local v, e2 = value(st, depth + 1)
if e2 then
return nil, e2
end
if k ~= k then
return nil, "NaN map key"
end
if order and t[k] == nil then
table.insert(order, k)
end
t[k] = v
end
return Types.object(t, order or {}), nil
end
function value(st: St, depth: number): (any, string?)
if depth > st.maxDepth then
return nil, "nested deeper than " .. st.maxDepth
end
local r = st.r
local b = r:u8()
if r.err then
return nil, "truncated"
end
if b < 0x80 then
return b, nil
elseif b >= 0xE0 then
return b - 256, nil
elseif b < 0x90 then
return map(st, b - 0x80, depth)
elseif b < 0xA0 then
return array(st, b - 0x90, depth)
elseif b < 0xC0 then
local n = b - 0xA0
if not r:need(n) then
return nil, "truncated string"
end
return r:string(n), nil
elseif b == 0xC0 then
return st.null, nil
elseif b == 0xC2 then
return false, nil
elseif b == 0xC3 then
return true, nil
elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then
local n = if b == 0xC4 then r:u8() elseif b == 0xC5 then r:u16be() else r:u32be()
if r.err or not r:need(n) then
return nil, "truncated bin"
end
return r:bytes(n), nil
elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then
local n = if b == 0xC7 then r:u8() elseif b == 0xC8 then r:u16be() else r:u32be()
if r.err then
return nil, "truncated ext"
end
return ext(st, n)
elseif b == 0xCA then
local v = r:f32be()
return if r.err then nil else v, if r.err then "truncated" else nil
elseif b == 0xCB then
local v = r:f64be()
return if r.err then nil else v, if r.err then "truncated" else nil
elseif b >= 0xCC and b <= 0xD3 then
local v: any
if b == 0xCC then
v = r:u8()
elseif b == 0xCD then
v = r:u16be()
elseif b == 0xCE then
v = r:u32be()
elseif b == 0xCF then
v = int64(st, false)
elseif b == 0xD0 then
v = r:i8()
elseif b == 0xD1 then
v = r:i16be()
elseif b == 0xD2 then
v = r:i32be()
else
v = int64(st, true)
end
if r.err then
return nil, "truncated"
end
return v, nil
elseif b >= 0xD4 and b <= 0xD8 then
return ext(st, 2 ^ (b - 0xD4))
elseif b >= 0xD9 and b <= 0xDB then
local n = if b == 0xD9 then r:u8() elseif b == 0xDA then r:u16be() else r:u32be()
if r.err or not r:need(n) then
return nil, "truncated string"
end
return r:string(n), nil
elseif b == 0xDC or b == 0xDD then
local n = if b == 0xDC then r:u16be() else r:u32be()
if r.err then
return nil, "truncated"
end
return array(st, n, depth)
elseif b == 0xDE or b == 0xDF then
local n = if b == 0xDE then r:u16be() else r:u32be()
if r.err then
return nil, "truncated"
end
return map(st, n, depth)
end
return nil, string.format("reserved type byte 0x%02x", b)
end
-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it)
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
local o: DecodeOptions = opts or {}
local st: St = {
r = r,
big = o.bigInts == "string",
null = if o.null ~= nil then o.null else Types.null,
maxDepth = o.maxDepth or 512,
ts = o.timestamps ~= false,
ordered = o.ordered ~= false,
}
local v, e = value(st, 0)
if e then
return nil, e, r.pos - r.base
end
return v, nil
end
-- ------------------------------------------------------------------------------------------------ encode
export type EncodeOptions = {
float32: boolean?, -- non-integer numbers as float32 (default false: float64)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
maxDepth: number?, -- default 512 (also catches cycles)
stringsAsBin: boolean?, -- strings as bin (default false: str)
}
type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? }
local function writeInt(w: Bytes.Writer, v: number)
if v >= 0 then
if v < 128 then
w:u8(v)
elseif v < 256 then
w:u8(0xCC)
w:u8(v)
elseif v < 65536 then
w:u8(0xCD)
w:u16be(v)
elseif v < TWO32 then
w:u8(0xCE)
w:u32be(v)
else
w:u8(0xCF)
w:u64be(v)
end
else
if v >= -32 then
w:u8(v + 256)
elseif v >= -128 then
w:u8(0xD0)
w:u8(v + 256)
elseif v >= -32768 then
w:u8(0xD1)
w:u16be(v + 65536)
elseif v >= -2147483648 then
w:u8(0xD2)
w:u32be(v + TWO32)
else
w:u8(0xD3)
local hi = math.floor(v / TWO32)
local lo = v - hi * TWO32
w:u32be(hi + TWO32)
w:u32be(lo)
end
end
end
local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number)
if fix and n <= fixMax then
w:u8(fix + n)
elseif b8 and n < 256 then
w:u8(b8)
w:u8(n)
elseif n < 65536 then
w:u8(b16)
w:u16be(n)
else
w:u8(b32)
w:u32be(n)
end
end
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
return ta < tb
end
if ta == "number" or ta == "string" then
return a < b
end
return tostring(a) < tostring(b)
end
local function isArray(t: any, emptyMap: boolean): boolean
if Types.isObject(t) then
return false
end
local n = #t
if n == 0 then
return next(t) == nil and not emptyMap
end
local c = 0
for _ in next, t do
c += 1
end
return c == n
end
Codec.isArray = isArray
local function enc(st: ESt, v: any, depth: number): boolean
local w = st.w
local tv = type(v)
if v == nil or v == Types.null then
w:u8(0xC0)
elseif tv == "boolean" then
w:u8(if v then 0xC3 else 0xC2)
elseif tv == "number" then
if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then
writeInt(w, v)
elseif st.f32 then
w:u8(0xCA)
w:f32be(v)
else
w:u8(0xCB)
w:f64be(v)
end
elseif tv == "string" then
if st.bin then
lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6)
else
lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB)
end
w:string(v)
elseif tv == "buffer" then
lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6)
w:bytes(v)
elseif tv == "table" then
if depth >= st.maxDepth then
st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)"
return false
end
if Codec.isExt(v) then
local n = buffer.len(v.data)
if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then
w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n])
else
lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9)
end
w:u8(v.type % 256)
w:bytes(v.data)
elseif Types.Date.is(v) then
local t = Types.Date.toUnix(v)
local secs = math.floor(t)
local ns = (v :: any).nanosecond or 0
if ns == 0 and secs >= 0 and secs < TWO32 then
w:u8(0xD6)
w:u8(0xFF)
w:u32be(secs)
elseif secs >= 0 and secs < 2 ^ 34 then
w:u8(0xD7)
w:u8(0xFF)
w:u32be(ns * 4 + secs // TWO32)
w:u32be(secs % TWO32)
else
w:u8(0xC7)
w:u8(12)
w:u8(0xFF)
w:u32be(ns)
local hi = math.floor(secs / TWO32)
w:u32be(hi % TWO32)
w:u32be(secs - hi * TWO32)
end
elseif isArray(v, st.emptyMap) then
local n = #v
lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD)
for k = 1, n do
if not enc(st, v[k], depth + 1) then
return false
end
end
else
local keys: { any }
if Types.isObject(v) then
keys = Types.keys(v)
else
keys = {}
for k in next, v do
table.insert(keys, k)
end
if st.sort then
table.sort(keys, keyLess)
end
end
lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF)
for _, k in keys do
if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then
return false
end
end
end
else
st.err = "cannot encode a " .. tv
return false
end
return true
end
-- encode(v, opts) -> buffer | nil, message
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
local o: EncodeOptions = opts or {}
local st: ESt = {
w = Bytes.writer(256),
f32 = o.float32 == true,
sort = o.sortKeys ~= false,
emptyMap = o.emptyTable == "map",
maxDepth = o.maxDepth or 512,
bin = o.stringsAsBin == true,
err = nil,
}
if not enc(st, v, 0) then
return nil, st.err
end
return st.w:finish(), nil
end
return Codec