diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 03c5f3c..bf39365 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,6 +11,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.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 | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.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 e589d61..c5b35e7 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -86,6 +86,18 @@ local list: { Entry } = { return require("@formats/data/msgpack") end, }, + { + name = "plist", + category = "data", + path = "data/plist", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, + load = function() + return require("@formats/data/plist") + end, + }, { name = "toml", category = "data", diff --git a/src/Formats/codecs/Json/Encode.luau b/src/Formats/codecs/Json/Encode.luau index cf556f8..78d0ac5 100644 --- a/src/Formats/codecs/Json/Encode.luau +++ b/src/Formats/codecs/Json/Encode.luau @@ -126,9 +126,6 @@ local function kind(t: { [any]: any }, emptyObject: boolean): string end return "object" end - if next(t, n) ~= nil then - return "object" - end local count = 0 for _ in next, t do count += 1 diff --git a/src/Formats/data/cbor/Codec.luau b/src/Formats/data/cbor/Codec.luau index 51ac0ae..f588c59 100644 --- a/src/Formats/data/cbor/Codec.luau +++ b/src/Formats/data/cbor/Codec.luau @@ -472,9 +472,6 @@ local function isArray(t: any, emptyMap: boolean): boolean 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 diff --git a/src/Formats/data/msgpack/Codec.luau b/src/Formats/data/msgpack/Codec.luau index 1165c4e..fd42577 100644 --- a/src/Formats/data/msgpack/Codec.luau +++ b/src/Formats/data/msgpack/Codec.luau @@ -341,9 +341,6 @@ local function isArray(t: any, emptyMap: boolean): boolean 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 diff --git a/src/Formats/data/plist/Base64.luau b/src/Formats/data/plist/Base64.luau new file mode 100644 index 0000000..115cf94 --- /dev/null +++ b/src/Formats/data/plist/Base64.luau @@ -0,0 +1,71 @@ +--!strict +--!native +-- data/plist/Base64: RFC 4648 base64 for plist (decode skips whitespace; encode wraps lines). Never throws. +local Base64 = {} + +local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +local DEC: { [number]: number } = {} +for i = 1, 64 do + DEC[string.byte(ALPHA, i)] = i - 1 +end +local ENC: { string } = {} +for i = 1, 64 do + ENC[i - 1] = string.sub(ALPHA, i, i) +end + +-- decode(s) -> buffer | nil, message (whitespace ignored; padding optional) +function Base64.decode(s: string): (buffer?, string?) + local clean = string.gsub(s, "[ \t\r\n]", "") + clean = string.gsub(clean, "=+$", "") + local n = #clean + if n % 4 == 1 then + return nil, "bad base64 length" + end + local out = buffer.create(n * 3 // 4) + local o = 0 + local acc, bits = 0, 0 + for i = 1, n do + local v = DEC[string.byte(clean, i)] + if v == nil then + return nil, "bad base64 character" + end + acc = acc * 64 + v + bits += 6 + if bits >= 8 then + bits -= 8 + local b = acc // (2 ^ bits) + buffer.writeu8(out, o, b) + o += 1 + acc -= b * 2 ^ bits + end + end + return out, nil +end + +-- encode(b, lineBytes?) -> base64 text; lineBytes > 0 puts "\n" after every lineBytes input bytes (and at the end) +function Base64.encode(b: buffer, lineBytes: number?): string + local n = buffer.len(b) + local parts = table.create(n // 3 + 2) + local per = lineBytes or 0 + local k = 0 + local i = 0 + while i < n do + local a = buffer.readu8(b, i) + local c1 = if i + 1 < n then buffer.readu8(b, i + 1) else 0 + local c2 = if i + 2 < n then buffer.readu8(b, i + 2) else 0 + local v = a * 65536 + c1 * 256 + c2 + local q = ENC[v // 262144] .. ENC[(v // 4096) % 64] + q ..= if i + 1 < n then ENC[(v // 64) % 64] else "=" + q ..= if i + 2 < n then ENC[v % 64] else "=" + k += 1 + parts[k] = q + i += 3 + if per > 0 and (i % per == 0 or i >= n) then + k += 1 + parts[k] = "\n" + end + end + return table.concat(parts) +end + +return Base64 diff --git a/src/Formats/data/plist/Binary.luau b/src/Formats/data/plist/Binary.luau new file mode 100644 index 0000000..544fe33 --- /dev/null +++ b/src/Formats/data/plist/Binary.luau @@ -0,0 +1,271 @@ +--!strict +--!native +-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in +-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte +-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, +-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles +-- are errors. Never throws: errors return nil, message. +local Types = require("@formats/Types") + +local Binary = {} + +local readu8 = buffer.readu8 +local TWO32 = 4294967296 +local EPOCH_2001 = 978307200 + +local UidMeta = { __tostring = function(u: any): string + return "UID(" .. u.uid .. ")" +end } +function Binary.uid(n: number): { uid: number } + return setmetatable({ uid = n }, UidMeta) :: any +end +function Binary.isUid(v: any): boolean + return type(v) == "table" and getmetatable(v) == UidMeta +end + +local function be(b: buffer, o: number, n: number): number + local v = 0 + for k = 0, n - 1 do + v = v * 256 + readu8(b, o + k) + end + return v +end + +local function utf8char(c: number): string + if c < 0x80 then + return string.char(c) + elseif c < 0x800 then + return string.char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return string.char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return string.char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +export type Options = { bigInts: ("number" | "string")?, maxDepth: number? } + +-- decode(buf, base, len, opts) -> value | nil, message +function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) + if len < 40 then + return nil, "truncated: shorter than header + trailer" + end + local t = base + len - 32 + local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7) + local numObjects = be(b, t + 8, 8) + local top = be(b, t + 16, 8) + local tableOff = be(b, t + 24, 8) + if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then + return nil, "bad trailer sizes" + end + if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then + return nil, "bad trailer" + end + local maxDepth = (opts and opts.maxDepth) or 512 + local cache: { [number]: any } = {} + local busy: { [number]: boolean } = {} + + local object: (idx: number, depth: number) -> (any, string?) + + -- a length nibble: 0..14, or 15 = an int object follows + local function count(o: number, nib: number): (number?, number) + if nib < 15 then + return nib, o + 1 + end + if o + 2 > len - 32 then + return nil, 0 + end + local m = readu8(b, base + o + 1) + if m // 16 ~= 1 then + return nil, 0 + end + local w = 2 ^ (m % 16) + if w > 8 or o + 2 + w > len - 32 then + return nil, 0 + end + return be(b, base + o + 2, w), o + 2 + w + end + + local function ref(at: number): number + return be(b, base + at, refSize) + end + + function object(idx: number, depth: number): (any, string?) + local cached = cache[idx] + if cached ~= nil then + return cached, nil + end + if busy[idx] then + return nil, "object references form a cycle" + end + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth + end + if idx >= numObjects then + return nil, "object reference out of range" + end + local o = be(b, base + tableOff + idx * offSize, offSize) + if o < 8 or o >= len - 32 then + return nil, "object offset out of range" + end + local marker = readu8(b, base + o) + local hi, nib = marker // 16, marker % 16 + local v: any + if marker == 0x00 then + v = Types.null + elseif marker == 0x08 then + v = false + elseif marker == 0x09 then + v = true + elseif hi == 1 then + local w = 2 ^ nib + if w > 16 or o + 1 + w > len - 32 then + return nil, "bad integer" + end + if w == 16 then + o += 8 + w = 8 + end + if w == 8 then + local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4) + if h >= 0x80000000 and nib == 3 then + v = (h - TWO32) * TWO32 + l + elseif opts and opts.bigInts == "string" and h >= 0x200000 then + -- exact decimal text of h * 2^32 + l + local digits = {} + local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } + while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + limbs[k] + limbs[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + v = table.concat(digits) + else + v = h * TWO32 + l + end + else + v = be(b, base + o + 1, w) + end + elseif hi == 2 then + if nib == 2 and o + 5 <= len - 32 then + local s = buffer.create(4) + for k = 0, 3 do + buffer.writeu8(s, k, readu8(b, base + o + 4 - k)) + end + v = buffer.readf32(s, 0) + elseif nib == 3 and o + 9 <= len - 32 then + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + v = buffer.readf64(s, 0) + else + return nil, "bad real" + end + elseif marker == 0x33 then + if o + 9 > len - 32 then + return nil, "truncated date" + end + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + local secs = buffer.readf64(s, 0) + if secs ~= secs or math.abs(secs) > 1e14 then + return nil, "bad date" + end + v = Types.Date.fromUnix(secs + EPOCH_2001) + elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local bytes = if hi == 6 then n * 2 else n + if p + bytes > len - 32 then + return nil, "string / data past the end" + end + if hi == 4 then + local d = buffer.create(bytes) + buffer.copy(d, 0, b, base + p, bytes) + v = d + elseif hi == 6 then + local parts = table.create(n) + local k = 0 + while k < n do + local u = be(b, base + p + k * 2, 2) + k += 1 + if u >= 0xD800 and u <= 0xDBFF and k < n then + local lo = be(b, base + p + k * 2, 2) + if lo >= 0xDC00 and lo <= 0xDFFF then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + k += 1 + end + end + table.insert(parts, utf8char(u)) + end + v = table.concat(parts) + else + v = buffer.readstring(b, base + p, bytes) + end + elseif hi == 8 then + if o + 2 + nib > len - 32 then + return nil, "bad UID" + end + v = Binary.uid(be(b, base + o + 1, nib + 1)) + elseif hi == 0xA or hi == 0xC or hi == 0xD then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local refs = if hi == 0xD then n * 2 else n + if p + refs * refSize > len - 32 then + return nil, "collection past the end" + end + busy[idx] = true + if hi == 0xD then + local t2 = {} + local order = table.create(n) + for k = 0, n - 1 do + local key, ke = object(ref(p + k * refSize), depth + 1) + if ke then + return nil, ke + end + if type(key) ~= "string" then + return nil, "dict key is not a string" + end + local val, ve = object(ref(p + (n + k) * refSize), depth + 1) + if ve then + return nil, ve + end + if t2[key] == nil then + table.insert(order, key) + end + t2[key] = val + end + v = Types.object(t2, order) + else + local arr = table.create(n) + for k = 0, n - 1 do + local item, ie = object(ref(p + k * refSize), depth + 1) + if ie then + return nil, ie + end + arr[k + 1] = item + end + v = arr + end + busy[idx] = nil + else + return nil, string.format("unknown object marker 0x%02x", marker) + end + cache[idx] = v + return v, nil + end + + return object(top, 0) +end + +return Binary diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau new file mode 100644 index 0000000..e8bede1 --- /dev/null +++ b/src/Formats/data/plist/init.luau @@ -0,0 +1,306 @@ +--!strict +-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/Xml; the write is +-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> +-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> +-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past +-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as . + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Json = require("@formats/codecs/Json") +local Base64 = require("@formats/data/plist/Base64") +local Binary = require("@formats/data/plist/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Plist = { + name = "plist", + category = "data", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, +} + +export type DecodeOptions = { + bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text + maxDepth: number?, -- default 512 +} +export type EncodeOptions = { + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Plist.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.sub(head, 1, 6) == "bplist" then + return 1 + end + if string.find(head, " ((opts and opts.maxDepth) or 512) then + return nil, "nested too deeply" + end + local name = node.name + if name == "dict" then + local out = Types.object() + local kids = Xml.children(node) + local i = 1 + while i <= #kids do + local k = kids[i] + if k.name ~= "key" then + return nil, "dict: expected , got <" .. k.name .. ">" + end + local v = kids[i + 1] + if not v then + return nil, "dict: without a value" + end + local val, e = xmlValue(v, opts, depth + 1) + if e then + return nil, e + end + Types.set(out, Xml.text(k), val) + i += 2 + end + return out, nil + elseif name == "array" then + local out = {} + for _, ch in Xml.children(node) do + local val, e = xmlValue(ch, opts, depth + 1) + if e then + return nil, e + end + table.insert(out, val) + end + return out, nil + elseif name == "string" then + return Xml.text(node), nil + elseif name == "integer" then + local t = string.match(Xml.text(node), "^%s*(.-)%s*$") :: string + local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$") + local n: number? + if hex then + n = tonumber(hex, 16) + if n and neg == "-" then + n = -n + end + elseif string.match(t, "^[%-%+]?%d+$") then + n = tonumber(t) + if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then + return (string.gsub(t, "^%+", "")), nil + end + end + if not n then + return nil, "bad integer " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "real" then + local t = string.lower(string.match(Xml.text(node), "^%s*(.-)%s*$") :: string) + local n = tonumber(t) + if not n then + if t == "nan" or t == "+nan" or t == "-nan" then + n = 0 / 0 + elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then + n = math.huge + elseif t == "-inf" or t == "-infinity" then + n = -math.huge + end + end + if not n then + return nil, "bad real " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "true" then + return true, nil + elseif name == "false" then + return false, nil + elseif name == "date" then + local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$"))) + if not d then + return nil, "bad date" + end + return d, nil + elseif name == "data" then + local b, e = Base64.decode(Xml.text(node)) + if not b then + return nil, e + end + return b, nil + end + return nil, "unknown element <" .. tostring(name) .. ">" +end + +function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local len = r.limit - r.base + if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then + local v, e = Binary.decode(r.buf, r.base, len, opts) + 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) + end + return v, nil + end + local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if root.name == "plist" then + local kids = Xml.children(root) + if #kids ~= 1 then + return nil, Err.new(Err.CORRUPT, " must hold exactly one value") + end + root = kids[1] + end + local v, e = xmlValue(root, opts, 0) + if e then + return nil, Err.new(Err.CORRUPT, e) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HEADER = '\n\n\n' + +local function esc(s: string): (string?, string?) + if string.find(s, "[%z\1-\8\11\12\14-\31]") then + return nil, "strings cannot contain control characters" + end + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + return (string.gsub(s, "[&<>]", { ["&"] = "&", ["<"] = "<", [">"] = ">" })), nil +end + +local function keyLess(a: any, b: any): boolean + return a < b +end + +function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local sort = not (opts and opts.sortKeys == false) + local out: { string } = { HEADER } + local err: string? = nil + local function line(level: number, s: string) + table.insert(out, string.rep("\t", level) .. s .. "\n") + end + local write: (v: any, level: number, depth: number) -> boolean + function write(v: any, level: number, depth: number): boolean + if depth > 512 then + err = "nested deeper than 512 (a cycle?)" + return false + end + local tv = type(v) + if tv == "string" then + local s, e = esc(v) + if not s then + err = e + return false + end + line(level, "" .. s .. "") + elseif tv == "boolean" then + line(level, if v then "" else "") + elseif tv == "number" then + if v == math.floor(v) and math.abs(v) < 2 ^ 63 then + line(level, "" .. string.format("%d", v) .. "") + else + local s = Json.number(v) + if not s then + s = if v ~= v then "nan" elseif v > 0 then "inf" else "-inf" + end + line(level, "" .. s .. "") + end + elseif tv == "buffer" then + line(level, "") + local maxLine = math.max(16, 76 - 8 * level) + for l in string.gmatch(Base64.encode(v, maxLine // 4 * 3), "[^\n]+") do + line(level, l) + end + line(level, "") + elseif tv == "table" and Types.Date.is(v) then + local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v))) + line(level, string.format("%04d-%02d-%02dT%02d:%02d:%02dZ", d.year :: number, d.month :: number, d.day :: number, d.hour :: number, d.minute :: number, d.second :: number)) + elseif tv == "table" and Binary.isUid(v) then + err = "UIDs can only be written to binary plists" + return false + elseif tv == "table" and v ~= Types.null then + local n = #v + local isArray = false + if not Types.isObject(v) then + local c = 0 + for _ in next, v do + c += 1 + end + isArray = c == n + end + if isArray then + if n == 0 then + line(level, "") + return true + end + line(level, "") + for k = 1, n do + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "") + 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 + end + for _, k in keys do + if type(k) ~= "string" then + err = "dict keys must be strings" + return false + end + end + if sort and not Types.isObject(v) then + table.sort(keys, keyLess) + end + if #keys == 0 then + line(level, "") + return true + end + line(level, "") + for _, k in keys do + local ks, e = esc(k) + if not ks then + err = e + return false + end + line(level + 1, "" .. ks .. "") + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "") + end + else + err = "cannot write " .. (if v == Types.null then "null" else "a " .. tv) .. " in a plist" + return false + end + return true + end + if not write(value, 0, 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + table.insert(out, "\n") + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.isUid = Binary.isUid + +return Plist diff --git a/tests/data/plist.luau b/tests/data/plist.luau new file mode 100644 index 0000000..231a20f --- /dev/null +++ b/tests/data/plist.luau @@ -0,0 +1,86 @@ +-- data/plist tests: values written by Python's plistlib as XML and binary decode to plistlib's values; our XML writer +-- reproduces plistlib's XML byte for byte; binary-only values (UIDs, 64-bit integers); a hand-written XML plist; +-- error codes; the fuzz pass (XML and binary). Fixtures: tools/fixtures/plist.py. +local T = require("@tests/T") +local F = require("@formats") +local Plist = require("@formats/data/plist") +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/plist") + +local t = T.suite("data/plist") + +t:eq(Plist.name, "plist", "name") +t:check(Plist.caps.decode and Plist.caps.encode, "caps") + +local function dec(s: string, opts: any?): (any, any) + return Plist.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function plain(v: any): any + if Plist.isUid(v) then + return { "uid", v.uid } + elseif type(v) == "table" and not Types.Date.is(v) 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.cases do + local v, err = dec(c.xml) + t:check(v ~= nil, "xml " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(v), c.canon, "xml " .. i .. ": value") + local vb, berr = dec(c.binary) + t:check(vb ~= nil, "binary " .. i .. ": " .. tostring(berr)) + t:eq(Canon.of(vb), c.canon, "binary " .. i .. ": value") + t:eq(buffer.tostring(Plist.encode(v) :: buffer), c.xml, "xml " .. i .. ": same text as plistlib") +end +for i, c in Fx.wide do + local v, err = dec(c.binary) + t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err)) + t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value") +end +do + local v = dec(Fx.extra) + t:eq(Canon.of(v), Fx.extraCanon, "hand-written plist") + t:eq(v.hex, 31, "hex integer") + local f = F.load(buffer.fromstring(Fx.cases[1].binary)) + t:check(f ~= nil, "F.load sniffs binary plists") + local fx = F.load(buffer.fromstring(Fx.cases[1].xml)) + t:eq(Canon.of(fx), Fx.cases[1].canon, "F.load sniffs XML plists over plain XML") + t:eq(dec("x"), "x", "bare root value") + local function code(s: string): string? + local _, e = dec(s) + return e and e.code + end + t:eq(code("a"), Err.CORRUPT, "key without value") + t:eq(code("x"), Err.CORRUPT, "bad integer") + t:eq(code("!!"), Err.CORRUPT, "bad base64") + t:eq(code(""), Err.CORRUPT, "unknown element") + t:eq(code("bplist00"), Err.TRUNCATED, "short binary") + local _, ne = Plist.encode({ a = F.null }) + t:eq(ne and ne.code, Err.ARG, "null cannot be written") + local _, ke = Plist.encode({ [1] = 1, x = 2 }) + t:eq(ke and ke.code, Err.ARG, "non-string key") + -- a binary plist with a cycle: array 0 -> [array 0] + local cyc = "bplist00" .. "\xa1\x00" .. "\x08" .. string.rep("\0", 6) .. "\1\1" .. "\0\0\0\0\0\0\0\1" .. "\0\0\0\0\0\0\0\0" .. "\0\0\0\0\0\0\0\10" + t:eq(code(cyc), Err.CORRUPT, "reference cycle") +end + +local samples = {} +for i = 1, 25 do + table.insert(samples, Fx.cases[i].xml) + table.insert(samples, Fx.cases[i].binary) +end +t:fuzz("decode", function(b: buffer) + return Plist.decode(Bytes.reader(b)) +end, samples, { keepHeader = 0 }) +t:fuzz("decode binary (header kept)", function(b: buffer) + return Plist.decode(Bytes.reader(b)) +end, { Fx.cases[3].binary, Fx.cases[4].binary, Fx.wide[1].binary }, { keepHeader = 8, mutations = 200, garbage = 0 }) +t:done() diff --git a/tools/fixtures/plist.py b/tools/fixtures/plist.py new file mode 100644 index 0000000..f89f1dc --- /dev/null +++ b/tools/fixtures/plist.py @@ -0,0 +1,83 @@ +# data/plist fixtures: random values written by Python's plistlib as XML (insertion order) and as binary, with the +# canonical form of plistlib's own reading (aware UTC datetimes; UIDs as ["uid", n]). +# tests/gen/plist.luau { { xml, binary, canon } } (our XML writer must reproduce xml byte for byte) +# + wide = { { binary, canon } } (UIDs, 64-bit integers: binary only) +import datetime, importlib.util, os, plistlib + +_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) + + +def rval(rng, d, wide): + r = rng.random() + if d > 3 or r < 0.5: + k = rng.randrange(8) + if k == 0: + return rng.random() < 0.5 + if k == 1: + return rng.randrange(-2 ** 31, 2 ** 31) + if k == 2: + return rng.choice([rng.randrange(-2 ** 63, 2 ** 63), rng.randrange(0, 2 ** 64)]) if wide else rng.randrange(-2 ** 53, 2 ** 53) + if k == 3: + f = rng.uniform(-1e6, 1e6) * 10 ** rng.randrange(-5, 5) + return f if not f.is_integer() else f + 0.5 + if k == 4: + return "".join(rng.choice("ab <>&\"'é中\U0001f600\n\t") for _ in range(rng.randrange(0, 12))) + if k == 5: + return rng.randbytes(rng.choice([0, 1, 2, 3, 40, 57, 58, 200])) + if k == 6: + return datetime.datetime.fromtimestamp(rng.randrange(-2 ** 31, 2 ** 33), datetime.timezone.utc) + return plistlib.UID(rng.randrange(0, 2 ** 32)) if wide else "x" + if r < 0.75: + return [rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))] + return {"".join(rng.choice("abcé <&") for _ in range(rng.randrange(0, 6))): rval(rng, d + 1, wide) for _ in range(rng.randrange(0, 6))} + + +def conv(v): + if isinstance(v, plistlib.UID): + return ["uid", 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 generate(ctx): + rng = ctx.rng(21) + cases = [] + for i in range(200): + v = rval(rng, 0, False) + if not isinstance(v, (list, dict)) and rng.random() < 0.5: + v = {"root": v} + xml = plistlib.dumps(v, fmt=plistlib.FMT_XML, sort_keys=False, aware_datetime=True) + binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, sort_keys=False, aware_datetime=True) + back = plistlib.loads(xml, aware_datetime=True) + assert C.canon(conv(plistlib.loads(binary, aware_datetime=True))) == C.canon(conv(back)) + cases.append({"xml": xml, "binary": binary, "canon": C.canon(conv(back))}) + wide = [] + for i in range(80): + v = [rval(rng, 1, True) for _ in range(4)] + binary = plistlib.dumps(v, fmt=plistlib.FMT_BINARY, aware_datetime=True) + wide.append({"binary": binary, "canon": C.canon(conv(plistlib.loads(binary, aware_datetime=True)))}) + # a hand-written XML plist with whitespace, comments, hex integers, odd reals, a bare value root + extra = b""" + + + + + hex 0x1F + neg -5 + real 2.5e3 + data + AAEC + AwQ= + + empty + date 2001-01-01T00:00:00Z + + +""" + ctx.emit("plist", {"cases": cases, "wide": wide, "extra": extra, + "extraCanon": C.canon(plistlib.loads(extra, aware_datetime=True))})