-- the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on Python's parse: -- null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s:, buffers b:, -- arrays [x,...], objects {k=v,...} sorted by key text, dates d. local Types = require("@rosetta/Types") local Canon = {} local function num(x: number): string if x ~= x then return "#nan" elseif x == math.huge then return "#inf" elseif x == -math.huge then return "#-inf" elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then return string.format("#%d", x) end return "#" .. string.format("%.17g", x) end local function isArray(t: { [any]: any }): boolean if Types.isObject(t) then return false end local n = #t local c = 0 for _ in next, t do c += 1 end return c == n end local function canon(v: any, out: { string }) local tv = type(v) if v == Types.null then table.insert(out, "n") elseif tv == "boolean" then table.insert(out, if v then "t" else "f") elseif tv == "number" then table.insert(out, num(v)) elseif tv == "string" then table.insert(out, "s" .. #v .. ":" .. v) elseif tv == "buffer" then table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v)) elseif tv == "table" and Types.Date.is(v) then table.insert(out, "d" .. tostring(v)) elseif tv == "table" then if isArray(v) then table.insert(out, "[") for i = 1, #v do canon(v[i], out) table.insert(out, ",") end table.insert(out, "]") else local items = {} for k, x in next, v do local ko = {} canon(k, ko) table.insert(items, { table.concat(ko), x }) end table.sort(items, function(a, b) return a[1] < b[1] end) table.insert(out, "{") for _, it in items do table.insert(out, it[1] .. "=") canon(it[2], out) table.insert(out, ",") end table.insert(out, "}") end else table.insert(out, "?" .. tv) end end function Canon.of(v: any): string local out = {} canon(v, out) return table.concat(out) end return Canon