diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d9372b9..e251802 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -7,6 +7,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.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` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index dafa3ee..ac807b2 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -38,6 +38,18 @@ local list: { Entry } = { return require("@formats/data/json") end, }, + { + name = "msgpack", + category = "data", + path = "data/msgpack", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, + load = function() + return require("@formats/data/msgpack") + end, + }, { name = "xml", category = "data", diff --git a/src/Formats/data/msgpack/Codec.luau b/src/Formats/data/msgpack/Codec.luau new file mode 100644 index 0000000..1165c4e --- /dev/null +++ b/src/Formats/data/msgpack/Codec.luau @@ -0,0 +1,471 @@ +--!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 + if next(t, n) ~= nil then + return false + 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 diff --git a/src/Formats/data/msgpack/init.luau b/src/Formats/data/msgpack/init.luau new file mode 100644 index 0000000..ecd96f9 --- /dev/null +++ b/src/Formats/data/msgpack/init.luau @@ -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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Codec = require("@formats/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.new(if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED else Err.CORRUPT, 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 diff --git a/tests/data/msgpack.luau b/tests/data/msgpack.luau new file mode 100644 index 0000000..7b254c3 --- /dev/null +++ b/tests/data/msgpack.luau @@ -0,0 +1,96 @@ +-- data/msgpack tests: values packed by Python's msgpack decode to msgpack's own values (canonical form), re-encode to +-- the same bytes, 64-bit integers as doubles and as exact strings, timestamps / ext, streams, options, error codes, +-- and the fuzz pass. Fixtures: tools/fixtures/msgpack.py. +local T = require("@tests/T") +local Mp = require("@formats/data/msgpack") +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/msgpack") + +local t = T.suite("data/msgpack") + +t:eq(Mp.name, "msgpack", "name") +t:check(Mp.caps.decode and Mp.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 Mp.decode(Bytes.reader(b), opts) +end + +-- ext values canonicalise like the fixture's ["ext", code, data] +local function plain(v: any): any + if Mp.isExt(v) then + return { "ext", v.type, v.data } + 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[k] = plain(x) + end + return o + end + return v +end + +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 = Mp.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") + local vs = dec(c.data, { bigInts = "string" }) + t:eq(Canon.of(plain(vs)), c.canonStr, "wide " .. i .. ": exact big integers") + t:eq(Canon.of(plain(dec(Mp.encode(v) :: buffer))), c.canon, "wide " .. i .. ": round trip") +end + +-- details +do + t:eq(Mp.isExt(dec("\xd4\x05\x07")), true, "fixext1") + local d = dec("\xd6\xff\x00\x00\x00\x00") + t:check(Types.Date.is(d) and tostring(d) == "1970-01-01T00:00:00Z", "timestamp32") + t:eq(dec("\xcf\xff\xff\xff\xff\xff\xff\xff\xff", { bigInts = "string" }), "18446744073709551615", "u64 max text") + t:eq(dec("\xd3\x80\x00\x00\x00\x00\x00\x00\x00", { bigInts = "string" }), "-9223372036854775808", "i64 min text") + t:eq(dec("\xd3\xff\xff\xff\xff\xff\xff\xff\xff"), -1, "i64 -1") + t:eq(buffer.tostring(Mp.encode(-2 ^ 40) :: buffer), "\xd3\xff\xff\xff\x00\x00\x00\x00\x00", "encode i64") + t:eq(buffer.tostring(Mp.encode(1.5, { float32 = true }) :: buffer), "\xca\x3f\xc0\x00\x00", "float32") + t:eq(buffer.tostring(Mp.encode({}) :: buffer), "\x90", "empty table = array") + t:eq(buffer.tostring(Mp.encode({}, { emptyTable = "map" }) :: buffer), "\x80", "emptyTable map") + t:eq(buffer.tostring(Mp.encode(Types.object()) :: buffer), "\x80", "Types.object = map") + t:eq(buffer.tostring(Mp.encode({ b = 1, a = 2 }) :: buffer), "\x82\xa1a\x02\xa1b\x01", "plain keys sorted") + t:eq(buffer.tostring(Mp.encode("ab", { stringsAsBin = true }) :: buffer), "\xc4\x02ab", "stringsAsBin") + t:eq(buffer.tostring(Mp.encode(Mp.ext(3, buffer.fromstring("xyz"))) :: buffer), "\xc7\x03\x03xyz", "ext8") + local all = dec("\x01\x02\xa1x", { all = true }) + t:eq(#all, 3, "stream") + t:eq(buffer.tostring(Mp.encode({ 1, "x" }, { all = true }) :: buffer), "\x01\xa1x", "encode stream") + t:eq(dec("\xc0"), Types.null, "nil -> null") + local cyc = {} + cyc[1] = cyc + local _, ce = Mp.encode(cyc) + t:eq(ce and ce.code, Err.ARG, "cycle") + local function code(s: string, o: any?): string? + local _, e = dec(s, o) + return e and e.code + end + t:eq(code("\xdd\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count") + t:eq(code("\xa5ab"), Err.TRUNCATED, "short string") + t:eq(code("\xc1"), Err.CORRUPT, "reserved byte") + t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data") + t:eq(code(string.rep("\x91", 600) .. "\x01"), Err.LIMIT, "depth") +end + +local samples = {} +for i = 5, 60 do + if #Fx.safe[i].data < 3000 then + table.insert(samples, Fx.safe[i].data) + end +end +t:fuzz("decode", function(b: buffer) + return Mp.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_data_common.py b/tools/fixtures/_data_common.py index 41b4291..4ac47e8 100644 --- a/tools/fixtures/_data_common.py +++ b/tools/fixtures/_data_common.py @@ -97,3 +97,14 @@ def date_text(v): if isinstance(v, datetime.date): return "%04d-%02d-%02d" % (v.year, v.month, v.day) return "%02d:%02d:%02d%s" % (v.hour, v.minute, v.second, frac(v.microsecond)) + + +def python(ctx, packages, body): + """run body (with these helpers prepended, so canon() / date_text() exist) under a nix python with packages; + returns stdout bytes, raising with the script's stderr on failure""" + import subprocess as sp + src = open(os.path.abspath(__file__)).read() + try: + return ctx.python(packages, src + "\n" + body) + except sp.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) diff --git a/tools/fixtures/msgpack.py b/tools/fixtures/msgpack.py new file mode 100644 index 0000000..d395813 --- /dev/null +++ b/tools/fixtures/msgpack.py @@ -0,0 +1,94 @@ +# data/msgpack fixtures: random values packed by Python's msgpack (through nix): every integer width, floats, +# str / bin of every length class, nested arrays / maps (int and str keys), nil / bools, timestamps (all three +# widths) and other ext types; with the canonical form of msgpack's own unpacking. +# tests/gen/msgpack.luau { safe = { { data, canon } }, wide = { { data, canon, canonStr } } } +# safe: no integers past 2^53, no integral floats: our decode + encode must give the same bytes +# wide: 64-bit integers too (canon = as doubles, canonStr = exact text via bigInts = "string") +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) + +BODY = r''' +import msgpack, pickle, random, sys, datetime +rng = random.Random(5) +def rint(wide): + k = rng.randrange(8) + lim = [2**5, 2**7, 2**8, 2**15, 2**16, 2**31, 2**32, 2**53 - 1][k] + if wide and rng.random() < 0.4: + lim = rng.choice([2**63 - 1, 2**64 - 1]) + v = rng.randrange(0, lim + 1) + if lim == 2**63 - 1 and rng.random() < 0.5: + v = -v - 1 + return v + v = rng.randrange(-lim, lim + 1) + return v +def rstr(): + n = rng.choice([0, 1, 5, 31, 32, 200, 255, 256, 300]) + alph = "abé中\U0001f600 \n\x00" + return "".join(rng.choice(alph) for _ in range(n))[:n] +def rval(d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(9) + 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, 255, 256])) + if k == 7: + sec = rng.choice([rng.randrange(0, 2**32), rng.randrange(0, 2**34), rng.randrange(-2**35, 2**37)]) + us = rng.choice([0, rng.randrange(1000000)]) + return msgpack.Timestamp(sec, us * 1000) + return msgpack.ExtType(rng.randrange(0, 128), rng.randbytes(rng.choice([1, 2, 4, 8, 16, 3, 300]))) + if r < 0.75: + return [rval(d + 1, wide) for _ in range(rng.choice([0, 1, 3, 15, 16, 20] if d < 2 else [0, 1, 3]))] + m = {} + for _ in range(rng.choice([0, 1, 3, 15, 16, 17] if d < 2 else [0, 1, 3])): + key = rint(False) if rng.random() < 0.3 else "".join(rng.choice("abc\u00e9") for _ in range(rng.randrange(6))) + m[key] = rval(d + 1, wide) + return m +def conv(v): + if isinstance(v, msgpack.Timestamp): + return v.to_datetime() + if isinstance(v, msgpack.ExtType): + return ["ext", v.code, v.data] + if isinstance(v, list): + return [conv(x) for x in v] + if isinstance(v, dict): + return {k: conv(x) for k, x in v.items()} + return v +def cstr(v): + if isinstance(v, int) and not isinstance(v, bool) and abs(v) >= 2**53: + return str(v) + if isinstance(v, list): + return [cstr(x) for x in v] + if isinstance(v, dict): + return {k: cstr(x) for k, x in v.items()} + return v +out = {"safe": [], "wide": []} +# the 32-bit length forms, once each +for v in ["x" * 70000, b"y" * 70000, list(range(70000)), {i: i for i in range(70000)}]: + data = msgpack.packb(v, use_bin_type=True) + out["safe"].append({"data": data, "canon": canon(msgpack.unpackb(data, strict_map_key=False))}) +for i in range(250): + v = rval(0, False) + data = msgpack.packb(v, use_bin_type=True) + back = msgpack.unpackb(data, raw=False, strict_map_key=False) + out["safe"].append({"data": data, "canon": canon(conv(back))}) +for i in range(150): + v = rval(0, True) + data = msgpack.packb(v, use_bin_type=True) + back = conv(msgpack.unpackb(data, raw=False, strict_map_key=False)) + out["wide"].append({"data": data, "canon": canon(back), "canonStr": canon(cstr(back))}) +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def generate(ctx): + out = pickle.loads(C.python(ctx, ["msgpack"], BODY)) + ctx.emit("msgpack", out)