Files
rosetta/src/Formats/data/toml/Encode.luau
T
4DBugandClaude Opus 5.5 434a304315 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:25:03 -05:00

215 lines
5.6 KiB
Luau

--!strict
-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables
-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as
-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date
-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil,
-- message.
local Types = require("@formats/Types")
local Json = require("@formats/codecs/text/Json")
local Encode = {}
local format, gsub, find = string.format, string.gsub, string.find
export type Options = {
inline: boolean?, -- write every sub-table as an inline table (default false: [sections])
indent: (number | string)?, -- indent keys of nested sections (default none)
}
local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" }
for c = 0, 31 do
local ch = string.char(c)
if not ESC[ch] then
ESC[ch] = format("\\u%04X", c)
end
end
local function quote(str: string): string
return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"'
end
Encode.quote = quote
local function keyText(k: string): string
if find(k, "^[%w_%-]+$") then
return k
end
return quote(k)
end
-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays
local function isMap(t: { [any]: any }): boolean
if Types.isObject(t) then
return true
end
local n = #t
if n == 0 then
return next(t) ~= nil
end
local count = 0
for _ in next, t do
count += 1
end
return count ~= n
end
local function isDate(v: any): boolean
return Types.Date.is(v)
end
-- an array of tables: non-empty, every element a map
local function isAot(v: any): boolean
if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then
return false
end
for _, x in v do
if type(x) ~= "table" or isDate(x) or not isMap(x) then
return false
end
end
return true
end
local function keysOf(t: { [any]: any }): ({ string }?, string?)
local keys = Types.keys(t)
for _, k in keys do
if type(k) ~= "string" then
return nil, "table key of type " .. type(k)
end
end
return keys :: any, nil
end
type State = { seen: { [any]: boolean }, err: string? }
local inlineValue: (st: State, v: any) -> string?
local function scalar(st: State, v: any): string?
local tv = type(v)
if v == Types.null then
st.err = "TOML has no null"
return nil
elseif tv == "string" then
return quote(v)
elseif tv == "boolean" then
return if v then "true" else "false"
elseif tv == "number" then
if v ~= v then
return "nan"
elseif v == math.huge then
return "inf"
elseif v == -math.huge then
return "-inf"
elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then
return format("%d", v)
end
local t = Json.number(v) :: string
if not find(t, "[%.eEn]") then
t ..= ".0"
end
return t
elseif tv == "table" and isDate(v) then
return tostring(v)
elseif tv == "table" then
return inlineValue(st, v)
end
st.err = "cannot encode a " .. tv
return nil
end
function inlineValue(st: State, v: any): string?
if st.seen[v] then
st.err = "a table contains itself"
return nil
end
st.seen[v] = true
local parts = {}
if isMap(v) then
local keys, kerr = keysOf(v)
if not keys then
st.err = kerr
return nil
end
for _, k in keys do
local s = scalar(st, v[k])
if not s then
return nil
end
table.insert(parts, keyText(k) .. " = " .. s)
end
st.seen[v] = nil
return if #parts == 0 then "{}" else "{ " .. table.concat(parts, ", ") .. " }"
end
for i = 1, #v do
local s = scalar(st, v[i])
if not s then
return nil
end
parts[i] = s
end
st.seen[v] = nil
return "[" .. table.concat(parts, ", ") .. "]"
end
local function section(st: State, t: any, path: string, out: { string }, inlineAll: boolean, ind: string, depth: number): boolean
if st.seen[t] then
st.err = "a table contains itself"
return false
end
st.seen[t] = true
local keys, kerr = keysOf(t)
if not keys then
st.err = kerr
return false
end
local pad = string.rep(ind, depth)
local subs = {}
for _, k in keys do
local v = t[k]
if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then
table.insert(subs, k)
else
local s = scalar(st, v)
if not s then
return false
end
table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n")
end
end
for _, k in subs do
local v = t[k]
local p = (if path == "" then "" else path .. ".") .. keyText(k)
if isMap(v) then
table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[" .. p .. "]\n")
if not section(st, v, p, out, inlineAll, ind, depth + 1) then
return false
end
else
for _, el in v do
table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[[" .. p .. "]]\n")
if not section(st, el, p, out, inlineAll, ind, depth + 1) then
return false
end
end
end
end
st.seen[t] = nil
return true
end
-- encode(t, opts) -> text | nil, message
function Encode.encode(t: any, opts: Options?): (string?, string?)
if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then
return nil, "the top level must be a table with string keys"
end
local o: Options = opts or {}
local ind = if type(o.indent) == "number" then string.rep(" ", o.indent) elseif type(o.indent) == "string" then o.indent else ""
local st: State = { seen = {}, err = nil }
local out = {}
if not section(st, t, "", out, o.inline == true, ind, 0) then
return nil, st.err
end
return table.concat(out), nil
end
return Encode