From 0a730986f84a3ac4add9a27795649f115065d4df Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:50:39 -0500 Subject: [PATCH] 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 Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/data/cbor/Codec.luau | 610 +++++++++++++++++++++++++++++++ src/Formats/data/cbor/init.luau | 100 +++++ tests/data/cbor.luau | 121 ++++++ tools/fixtures/cbor.py | 108 ++++++ 6 files changed, 952 insertions(+) create mode 100644 src/Formats/data/cbor/Codec.luau create mode 100644 src/Formats/data/cbor/init.luau create mode 100644 tests/data/cbor.luau create mode 100644 tools/fixtures/cbor.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index e251802..562029f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` | | data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` | | data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ac807b2..61b78bc 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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", diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau new file mode 100644 index 0000000..51ac0ae --- /dev/null +++ b/src/Formats/data/cbor/Codec.luau @@ -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 diff --git a/src/Formats/data/cbor/init.luau b/src/Formats/data/cbor/init.luau new file mode 100644 index 0000000..c605750 --- /dev/null +++ b/src/Formats/data/cbor/init.luau @@ -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 diff --git a/tests/data/cbor.luau b/tests/data/cbor.luau new file mode 100644 index 0000000..8501da2 --- /dev/null +++ b/tests/data/cbor.luau @@ -0,0 +1,121 @@ +-- data/cbor tests: the RFC 8949 Appendix A examples and random items encoded by Python's cbor2 decode to cbor2's +-- values (canonical form), re-encode to the same bytes, big integers as doubles and exact text, indefinite lengths, +-- tags / simple values / undefined, half floats, sequences, options, error codes, and the fuzz pass. +-- Fixtures: tools/fixtures/cbor.py. +local T = require("@tests/T") +local Cbor = require("@formats/data/cbor") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Canon = require("@tests/data/Canon") +local Fx = require("@tests/gen/cbor") + +local t = T.suite("data/cbor") + +t:eq(Cbor.name, "cbor", "name") +t:check(Cbor.caps.decode and Cbor.caps.encode, "caps") + +local function dec(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Cbor.decode(Bytes.reader(b), opts) +end + +-- the fixture's view of tags / simple values / undefined +local function plain(v: any): any + if v == Cbor.undefined then + return { "undefined" } + elseif Cbor.isSimple(v) then + return { "simple", v.value } + elseif Cbor.isTagged(v) then + return { "tag", v.tag, plain(v.value) } + elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + local o = if Types.isObject(v) then Types.object() else {} + for k, x in next, v do + o[plain(k)] = plain(x) + end + return o + end + return v +end + +local nApp = 0 +for _, c in Fx.appendix do + local v, err = dec(c.data) + if c.error then + t:check(v == nil and err ~= nil, c.hex .. ": rejected like cbor2") + else + t:check(v ~= nil or err == nil, c.hex .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, c.hex .. ": value") + t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, c.hex .. ": exact") + t:eq(Canon.of(plain(dec(Cbor.encode(v) :: buffer))), c.canon, c.hex .. ": round trip") + t:eq(Canon.of(plain(dec(Cbor.encode(v, { compactFloats = true }) :: buffer))), c.canon, c.hex .. ": compact round trip") + end + nApp += 1 +end +t:note("RFC 8949 appendix A: %d examples", nApp) + +for i, c in Fx.safe do + local v, err = dec(c.data) + t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value") + local b = Cbor.encode(v) :: buffer + t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes") +end +for i, c in Fx.wide do + local v, err = dec(c.data) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") + t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, "wide " .. i .. ": exact") +end + +-- details +do + local function hex(b: buffer): string + return (string.gsub(buffer.tostring(b), ".", function(ch) + return string.format("%02x", string.byte(ch)) + end)) + end + t:eq(hex(Cbor.encode(1.5, { compactFloats = true }) :: buffer), "f93e00", "half float") + t:eq(hex(Cbor.encode(100000.0 + 0.5, { compactFloats = true }) :: buffer), "fa47c35040", "single float") + t:eq(hex(Cbor.encode(1.1) :: buffer), "fb3ff199999999999a", "double float") + t:eq(hex(Cbor.encode(-0.0, { compactFloats = true }) :: buffer), "f98000", "negative zero") + t:eq(hex(Cbor.encode(0 / 0, { compactFloats = true }) :: buffer), "f97e00", "nan") + t:eq(hex(Cbor.encode(-2 ^ 64) :: buffer), "3bffffffffffffffff", "-2^64") + t:eq(hex(Cbor.encode(Cbor.tagged(32, "x")) :: buffer), "d8206178", "tagged") + t:eq(hex(Cbor.encode(Cbor.simple(255)) :: buffer), "f8ff", "simple") + t:eq(hex(Cbor.encode(Cbor.undefined) :: buffer), "f7", "undefined") + t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z")) :: buffer), "c074323031332d30332d32315432303a30343a30305a", "date tag 0") + t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z"), { dates = "epoch" }) :: buffer), "c11a514b67b0", "date tag 1") + t:eq(hex(Cbor.encode({ 1 }, { selfDescribe = true }) :: buffer), "d9d9f78101", "self-describe") + t:eq(dec("\217\217\247\1"), 1, "self-describe stripped") + t:eq(Cbor.sniff(Bytes.reader(buffer.fromstring("\217\217\247\1"))), 1, "sniff self-describe") + t:eq(#dec("\1\2\3", { all = true }), 3, "sequence") + t:eq(hex(Cbor.encode({ 1, "a" }, { all = true }) :: buffer), "016161", "encode sequence") + local function code(s: string): string? + local _, e = dec(s) + return e and e.code + end + t:eq(code("\x9b\xff\xff\xff\xff\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count") + t:eq(code("\x5f\x61\x61\xff"), Err.CORRUPT, "text chunk in a byte string") + t:eq(code("\xff"), Err.CORRUPT, "lone break") + t:eq(code("\x1c"), Err.CORRUPT, "reserved additional info") + t:eq(code("\x62\xc3\x28"), Err.CORRUPT, "invalid UTF-8") + t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data") + t:eq(code("\xc0\x01"), Err.CORRUPT, "tag 0 on a number") + t:eq(code(string.rep("\x81", 600) .. "\x01"), Err.LIMIT, "depth") + t:eq(code("\x9f\x01"), Err.TRUNCATED, "unterminated indefinite array") +end + +local samples = {} +for _, c in Fx.appendix do + table.insert(samples, c.data) +end +for i = 1, 40 do + if #Fx.safe[i].data < 3000 then + table.insert(samples, Fx.safe[i].data) + end +end +t:fuzz("decode", function(b: buffer) + return Cbor.decode(Bytes.reader(b)) +end, samples, { mutations = 4 }) +t:done() diff --git a/tools/fixtures/cbor.py b/tools/fixtures/cbor.py new file mode 100644 index 0000000..e0f3166 --- /dev/null +++ b/tools/fixtures/cbor.py @@ -0,0 +1,108 @@ +# data/cbor fixtures: RFC 8949 Appendix A examples and random values encoded by Python's cbor2 (through nix): every +# integer width (and bignums), floats, text / byte strings, nested arrays / maps, dates (tags 0 / 1), other tags, +# simple values, undefined, indefinite-length items (written by hand), with the canonical form of cbor2's decode. +# tests/gen/cbor.luau { appendix = { { hex, data, canon } }, safe = { { data, canon } }, wide = { { data, canon, +# canonStr } } } safe: our decode + encode gives the same bytes; wide: big integers (doubles / exact text) +import importlib.util, os, pickle + +_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py")) +C = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(C) + +APPENDIX = """00 01 0a 17 1818 1819 1864 1903e8 1a000f4240 1b000000e8d4a51000 1bffffffffffffffff c249010000000000000000 +3bffffffffffffffff c349010000000000000000 20 29 3863 3903e7 f90000 f98000 f93c00 fb3ff199999999999a f93e00 f97bff +fa47c35000 fa7f7fffff fb7e37e43c8800759c f90001 f90400 f9c400 fbc010666666666666 f97c00 f97e00 f9fc00 fa7f800000 +fa7fc00000 faff800000 fb7ff0000000000000 fb7ff8000000000000 fbfff0000000000000 f4 f5 f6 f7 f0 f818 f8ff +c074323031332d30332d32315432303a30343a30305a c11a514b67b0 c1fb41d452d9ec200000 d74401020304 +d818456449455446 d82076687474703a2f2f7777772e6578616d706c652e636f6d 40 4401020304 60 6161 6449455446 62225c +62c3bc 63e6b0b4 64f0908591 80 83010203 8301820203820405 98190102030405060708090a0b0c0d0e0f101112131415161718181819 +a0 a201020304 a26161016162820203 826161a161626163 a56161614161626142616361436164614461656145 5f42010243030405ff +7f657374726561646d696e67ff 9fff 9f018202039f0405ffff 9f01820203820405ff 83018202039f0405ff 83019f0203ff820405 +9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff bf61610161629f0203ffff 826161bf61626163ff +bf6346756ef563416d7421ff""" + +BODY = r''' +import cbor2, pickle, random, sys, datetime +from collections.abc import Mapping +HEXES = sys.argv[1:] if False else HEXLIST +def conv(v): + if v is cbor2.undefined: + return ["undefined"] + if isinstance(v, cbor2.CBORSimpleValue): + return ["simple", v.value] + if isinstance(v, cbor2.CBORTag): + return ["tag", v.tag, conv(v.value)] + if isinstance(v, (list, tuple)): + return [conv(x) for x in v] + if isinstance(v, Mapping) or hasattr(v, "items"): + return {(tuple(conv(k)) if isinstance(k, list) else k): conv(x) for k, x in v.items()} + return v +def cstr(v): + if isinstance(v, cbor2.CBORTag): + return cbor2.CBORTag(v.tag, cstr(v.value)) + if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53: + return str(v) + if isinstance(v, (list, tuple)): + return [cstr(x) for x in v] + if isinstance(v, Mapping) or hasattr(v, "items"): + return {k: cstr(x) for k, x in v.items()} + return v +out = {"appendix": [], "safe": [], "wide": []} +for h in HEXES: + data = bytes.fromhex(h) + try: + v = cbor2.loads(data) + except Exception: + out["appendix"].append({"hex": h, "data": data, "error": True}) # e.g. f818: invalid since RFC 8949 + continue + if type(v).__name__ in ("Decimal", "Fraction", "UUID") or (isinstance(v, str) and h.startswith("d820")): + continue # semantic tags cbor2 interprets and we keep tagged + out["appendix"].append({"hex": h, "data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))}) +rng = random.Random(9) +def rint(wide): + lim = rng.choice([23, 24, 255, 256, 65535, 65536, 2**32 - 1, 2**32, 2**53 - 1]) + if wide and rng.random() < 0.4: + lim = rng.choice([2**64 - 1, 2**70]) + v = rng.randrange(0, lim + 1) + return -v - 1 if rng.random() < 0.5 else v +def rstr(): + return "".join(rng.choice("abé中\U0001f600 \n\x00") for _ in range(rng.choice([0, 1, 23, 24, 255, 300]))) +def rval(d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(10) + if k == 0: return None + if k == 1: return rng.random() < 0.5 + if k in (2, 3): return rint(wide) + if k == 4: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 5: return rstr() + if k == 6: return rng.randbytes(rng.choice([0, 3, 24, 256])) + if k == 7: + return datetime.datetime.fromtimestamp(rng.randrange(0, 2**33), datetime.timezone.utc) + if k == 8: + return cbor2.CBORTag(rng.choice([6, 1000, 100000]), rval(d + 1, wide)) + return rng.choice([cbor2.undefined, cbor2.CBORSimpleValue(rng.choice([0, 19, 32, 255]))]) + if r < 0.75: + return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3]))] + m = {} + for _ in range(rng.choice([0, 1, 3, 23, 24] if d < 2 else [0, 1, 3])): + key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abcé") for _ in range(rng.randrange(6))) + m[key] = rval(d + 1, wide) + return m +for i in range(250): + data = cbor2.dumps(rval(0, False)) + out["safe"].append({"data": data, "canon": canon(conv(cbor2.loads(data)))}) +for i in range(120): + data = cbor2.dumps(rval(0, True)) + v = cbor2.loads(data) + out["wide"].append({"data": data, "canon": canon(conv(v)), "canonStr": canon(conv(cstr(v)))}) +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def generate(ctx): + hexes = APPENDIX.split() + out = pickle.loads(C.python(ctx, ["cbor2"], "HEXLIST = %r\n" % hexes + BODY)) + ctx.emit("cbor", out)