formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 08:18:01 -05:00
commit ccb06775c5
226 files changed
+8409

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
# build outputs (tools/build.py) and generated test fixtures (tools/fixtures.py)
/build/
/tests/gen/
# Rojo
/*.rbxm
/*.rbxmx
/*.rbxl
/*.rbxlx
sourcemap.json
__pycache__/
+7
View File
@@ -0,0 +1,7 @@
{
"languageMode": "nonstrict",
"aliases": {
"formats": "./src/Formats",
"tests": "./tests"
}
}
+76
View File
@@ -0,0 +1,76 @@
# formats-luau
Read, write and convert file formats in pure Luau, from one source tree that runs on **Roblox** (Luau, native code
generation) and on **LuaJIT / LÖVE** (through `tools/build.py`). Every format of a category maps onto one standard type
(`src/Formats/Types.luau`): a PNG and a WebP both load as an `Image`, every audio format opens as the same streaming
`Decoder`.
Status: foundation. Formats so far: PNG (read / write). Codecs: DEFLATE (inflate + compressor, zlib, gzip). See
[docs/FORMATS.md](docs/FORMATS.md) (generated) for the capability matrix.
```luau
local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats")
local img, err = F.load(src) -- src: buffer | string | path (hosts with files)
if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7"
local buf = F.save(img, nil, { format = "png" }) -- a buffer; F.save(img, "out.png") writes a file
local s = F.saveString(img, { format = "png" })
local out = F.convert(src, "png", { level = 9 })
local img2 = F.image.load(src) -- category facades: F.image / audio / video / model / font / ...
for _, f in F.formats() do print(f.name, f.caps.decode, f.caps.encode) end
```
Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err.code` is one of the `F.Err` codes).
## Runtimes
| Runtime | How | Files |
|---|---|---|
| Roblox | `python3 -I tools/build.py roblox`, then `rojo build` / `rojo serve` (`default.project.json` mounts `build/roblox/Formats`) | none: pass buffers / strings; `F.host.toEditableImage(img)` |
| LuaJIT | `python3 -I tools/build.py luajit`; `package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path` | `io.open` |
| LÖVE | the LuaJIT build, copied into the game | `love.filesystem` (+ `io`); `F.host.toImageData(img)`, `F.host.fromImageData(id)`, `F.host.toSoundData(audio or decoder)` |
| luau CLI | `luau` with the `.luaurc` alias `@formats` (`src/` directly) | none |
The LuaJIT build supplies the Luau standard library pieces it needs from `compat/luajit.lua` (unsigned `bit32`,
`buffer` on FFI memory, `table.create`, `math.clamp`, `string.split`, `utf8`, ...), required by each module, without
touching globals (`require("formats._compat").install()` puts `buffer` / `bit32` / `utf8` / `typeof` in `_G` if a
game wants them).
## Development
```sh
bash tools/test.sh # fixtures, registry, build, every test under luau --codegen -O2 and LuaJIT, lint
bash tools/test.sh png # one test (both runtimes), no lint
bash tools/lint.sh # globals, headers, requires, native-throw, layers, deps, contract, registry
bash tools/bench.sh # throughput on both runtimes (pin it: taskset -c 2 bash tools/bench.sh)
python3 -I tools/build.py # build/roblox + build/luajit
python3 -I tools/gen_registry.py # src/Formats/Registry.luau + docs/FORMATS.md from the format folders
python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py
```
Tools: python3, and through nix: `luau` (+ `luau-analyze`), `luajit`, `darklua` 0.19, `rojo` (each script finds them
on PATH or runs them with `nix shell nixpkgs#<tool>`).
Layout, layering, the format contract, how to add a format or absorb a repo: [docs/STYLE.md](docs/STYLE.md).
```
src/Formats/ init.luau (API) Types.luau Registry.luau (generated) core/ host/ codecs/ containers/
<category>/<fmt>/ ops/
compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, fixtures/, gen/) docs/ licenses/
```
## Performance (one Zen 5 core, `taskset -c 2 bash tools/bench.sh`)
| | luau --codegen -O2 | LuaJIT 2.1 |
|---|---|---|
| inflate, 6 MB text + binary (exact size) | ~330 MB/s | ~470 MB/s |
| zlib (inflate + Adler-32) | ~170 MB/s | ~280 MB/s |
| CRC-32 | ~310 MB/s | ~520 MB/s |
| PNG decode 1024x768 RGBA | ~52 MB/s | ~30-75 MB/s |
| deflate compress -6 | ~12 MB/s | ~8-20 MB/s |
LuaJIT numbers vary between runs: its trace recorder is randomised, and about one run in ten picks a slower trace
layout for a loop (inflate then runs at ~190 MB/s). Unpinned runs on this hybrid CPU also differ 2x between core types.
## Licence
See [licenses/NOTICE.md](licenses/NOTICE.md).
+630
View File
@@ -0,0 +1,630 @@
-- compat/luajit.lua: the Luau standard library pieces formats-luau uses, for LuaJIT 2.1 (plain luajit and LÖVE).
-- tools/build.py copies this file to build/luajit/formats/_compat.lua, and every built module starts with
-- local __compat = require("formats._compat") local buffer, bit32, utf8, typeof, type, __iter = ...
-- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string
-- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing.
--
-- Semantics follow Luau (checked by tests/compat.luau under both runtimes):
-- bit32 unsigned 32-bit results; shift counts outside -31..31 give 0; extract/replace/countlz/countrz/byteswap
-- (fractional operands: see the bit32 section).
-- buffer fixed-size byte arrays on FFI memory, little-endian, zero-filled; out-of-bounds access throws
-- "buffer access out of bounds" like Luau. A buffer is a table { p = uint8_t*, n = length } with a
-- private metatable: typeof(b) and the injected type(b) return "buffer".
-- __iter Luau's generalized iteration (`for k, v in t do`): build.py rewrites such loops to
-- `for k, v in __iter(t) do`. Functions pass through; arrays iterate with ipairs (JIT-compiled) when the
-- table has no keys past #t, anything else with next.
-- LuaJIT-only extensions (not in Luau; host/love uses them when present): buffer.toffi(b) -> uint8_t* (valid while b
-- is alive), buffer.fromffi(ptr, n) -> a new buffer with a copy of n bytes.
local ffi = require("ffi")
local bit = require("bit")
local floor = math.floor
local rawtype, getmetatable, setmetatable, select, error, pairs, ipairs, next = type, getmetatable, setmetatable, select, error, pairs, ipairs, next
local TWO32 = 4294967296
local M = {}
-- ---------------------------------------------------------------------------------------------------- bit32
-- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32.
-- Performance (inflate, pinned to one core): the sign fix written inline as `if r < 0 then r = r + 2^32 end` runs
-- about 45% faster than `r % 2^32`; operands are passed to bit.* as they are (no truncation step).
-- Divergence from Luau: a fractional operand is rounded by bit.tobit where Luau truncates it. The library never
-- passes fractions to bit32 (tests/compat.luau checks integers only).
do
local band, bor, bxor, bnot, lshift, rshift, arshift, bswap =
bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap
local B = {}
-- the 2- and 3-argument forms are the hot ones: no varargs on that path
function B.band(a, b, c, d, ...)
local r
if b == nil then
if a == nil then return TWO32 - 1 end
r = band(a, -1)
else
r = band(a, b)
if c ~= nil then
r = band(r, c)
if d ~= nil then
r = band(r, d)
for i = 1, select("#", ...) do r = band(r, (select(i, ...))) end
end
end
end
if r < 0 then r = r + TWO32 end
return r
end
function B.bor(a, b, c, d, ...)
local r
if b == nil then
if a == nil then return 0 end
r = band(a, -1)
else
r = bor(a, b)
if c ~= nil then
r = bor(r, c)
if d ~= nil then
r = bor(r, d)
for i = 1, select("#", ...) do r = bor(r, (select(i, ...))) end
end
end
end
if r < 0 then r = r + TWO32 end
return r
end
function B.bxor(a, b, c, d, e, f, g, h, ...)
local r
if b == nil then
if a == nil then return 0 end
r = band(a, -1)
else
r = bxor(a, b)
if c ~= nil then
r = bxor(r, c)
if d ~= nil then
r = bxor(r, d)
if e ~= nil then
r = bxor(r, e)
if f ~= nil then
r = bxor(r, f)
if g ~= nil then
r = bxor(r, g)
if h ~= nil then
r = bxor(r, h)
for i = 1, select("#", ...) do r = bxor(r, (select(i, ...))) end
end
end
end
end
end
end
end
if r < 0 then r = r + TWO32 end
return r
end
function B.btest(...)
return B.band(...) ~= 0
end
function B.bnot(a)
local r = bnot(a)
if r < 0 then r = r + TWO32 end
return r
end
function B.lshift(a, n)
if n >= 32 or n <= -32 then return 0 end
local r
if n < 0 then r = rshift(a, -n) else r = lshift(a, n) end
if r < 0 then r = r + TWO32 end
return r
end
function B.rshift(a, n)
if n >= 32 or n <= -32 then return 0 end
local r
if n < 0 then r = lshift(a, -n) else r = rshift(a, n) end
if r < 0 then r = r + TWO32 end
return r
end
function B.arshift(a, n)
if n <= -32 then return 0 end
if n >= 32 then n = 31 end
local r
if n < 0 then r = lshift(a, -n) else r = arshift(a, n) end
if r < 0 then r = r + TWO32 end
return r
end
function B.lrotate(a, n)
n = n % 32
local r = n == 0 and band(a, -1) or bor(lshift(a, n), rshift(a, 32 - n))
if r < 0 then r = r + TWO32 end
return r
end
function B.rrotate(a, n)
return B.lrotate(a, -n)
end
function B.extract(a, field, width)
width = width or 1
if field < 0 or width <= 0 or field + width > 32 then error("bit32.extract: trying to access non-existent bits", 2) end
local r = rshift(a, field)
if width < 32 then r = band(r, lshift(1, width) - 1) end
if r < 0 then r = r + TWO32 end
return r
end
function B.replace(a, v, field, width)
width = width or 1
if field < 0 or width <= 0 or field + width > 32 then error("bit32.replace: trying to access non-existent bits", 2) end
local m = width == 32 and -1 or lshift(lshift(1, width) - 1, field)
local r = bor(band(a, bnot(m)), band(lshift(v, field), m))
if r < 0 then r = r + TWO32 end
return r
end
function B.countlz(a)
a = band(a, -1)
if a == 0 then return 32 end
local n = 0
if band(a, -65536) == 0 then n = n + 16; a = lshift(a, 16) end
if band(a, -16777216) == 0 then n = n + 8; a = lshift(a, 8) end
if band(a, -268435456) == 0 then n = n + 4; a = lshift(a, 4) end
if band(a, -1073741824) == 0 then n = n + 2; a = lshift(a, 2) end
if band(a, -2147483648) == 0 then n = n + 1 end
return n
end
function B.countrz(a)
a = band(a, -1)
if a == 0 then return 32 end
local n = 0
while band(a, 1) == 0 do
a = rshift(a, 1)
n = n + 1
end
return n
end
function B.byteswap(a)
local r = bswap(a)
if r < 0 then r = r + TWO32 end
return r
end
M.bit32 = B
end
-- ---------------------------------------------------------------------------------------------------- buffer
do
ffi.cdef([[
void *memmove(void *dst, const void *src, size_t n);
void *memset(void *s, int c, size_t n);
void *calloc(size_t n, size_t size);
void free(void *p);
]])
local C = ffi.C
local u8p = ffi.typeof("uint8_t*")
local i8p = ffi.typeof("int8_t*")
local u16p, i16p = ffi.typeof("uint16_t*"), ffi.typeof("int16_t*")
local u32p, i32p = ffi.typeof("uint32_t*"), ffi.typeof("int32_t*")
local f32p, f64p = ffi.typeof("float*"), ffi.typeof("double*")
local u8arr = ffi.typeof("uint8_t[?]")
local cast, fstring, fcopy = ffi.cast, ffi.string, ffi.copy
local BUF = { __name = "buffer" }
BUF.__index = function() error("attempt to index a buffer value", 2) end
BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end
M.BUFFER_MT = BUF
-- Small buffers live in GC memory (ffi.new); big ones in calloc'd memory, so they do not count against the
-- 2 GB GC heap of non-GC64 builds (LÖVE). The GC does not see calloc'd bytes, so a full collection runs every
-- 512 MB of them.
local BIG = 262144
local external = 0
local function oob()
error("buffer access out of bounds", 3)
end
local Buf = {}
local function create(n)
if rawtype(n) ~= "number" or n < 0 then error("buffer.create: invalid size", 2) end
n = floor(n)
local mem, p
if n < BIG then
mem = u8arr(n > 0 and n or 1)
p = cast(u8p, mem)
else
external = external + n
if external > 536870912 then
external = 0
collectgarbage()
end
local raw = C.calloc(n, 1)
if raw == nil then error("buffer.create: out of memory", 2) end
mem = ffi.gc(cast(u8p, raw), C.free)
p = mem
end
-- p, n and m are raw fields, so the throwing __index only runs for misuse (b.x on a buffer)
return setmetatable({ p = p, n = n, m = mem }, BUF)
end
Buf.create = create
function Buf.len(b) return b.n end
-- reads / writes: o must satisfy 0 <= o and o + size <= n (Luau truncates a fractional offset)
function Buf.readu8(b, o)
if o < 0 or o >= b.n then oob() end
return b.p[o]
end
function Buf.readi8(b, o)
if o < 0 or o >= b.n then oob() end
return cast(i8p, b.p)[o]
end
function Buf.readu16(b, o)
if o < 0 or o + 2 > b.n then oob() end
return cast(u16p, b.p + o)[0]
end
function Buf.readi16(b, o)
if o < 0 or o + 2 > b.n then oob() end
return cast(i16p, b.p + o)[0]
end
function Buf.readu32(b, o)
if o < 0 or o + 4 > b.n then oob() end
return cast(u32p, b.p + o)[0]
end
function Buf.readi32(b, o)
if o < 0 or o + 4 > b.n then oob() end
return cast(i32p, b.p + o)[0]
end
function Buf.readf32(b, o)
if o < 0 or o + 4 > b.n then oob() end
return cast(f32p, b.p + o)[0]
end
function Buf.readf64(b, o)
if o < 0 or o + 8 > b.n then oob() end
return cast(f64p, b.p + o)[0]
end
-- integer writes wrap like Luau (300 -> 44, -1 -> 255); the double -> int conversion goes through int32 for
-- 8/16-bit stores and through int64 for 32-bit ones, so values in +-2^51 wrap correctly
function Buf.writeu8(b, o, v)
if o < 0 or o >= b.n then oob() end
b.p[o] = v
end
function Buf.writei8(b, o, v)
if o < 0 or o >= b.n then oob() end
b.p[o] = v
end
function Buf.writeu16(b, o, v)
if o < 0 or o + 2 > b.n then oob() end
cast(u16p, b.p + o)[0] = v
end
Buf.writei16 = Buf.writeu16
function Buf.writeu32(b, o, v)
if o < 0 or o + 4 > b.n then oob() end
cast(u32p, b.p + o)[0] = v % TWO32
end
Buf.writei32 = Buf.writeu32
function Buf.writef32(b, o, v)
if o < 0 or o + 4 > b.n then oob() end
cast(f32p, b.p + o)[0] = v
end
function Buf.writef64(b, o, v)
if o < 0 or o + 8 > b.n then oob() end
cast(f64p, b.p + o)[0] = v
end
function Buf.readstring(b, o, count)
if o < 0 or count < 0 or o + count > b.n then oob() end
return fstring(b.p + o, count)
end
function Buf.writestring(b, o, s, count)
count = count or #s
if count < 0 or count > #s then error("buffer.writestring: string length overflow", 2) end
if o < 0 or o + count > b.n then oob() end
fcopy(b.p + o, s, count)
end
function Buf.copy(target, toff, source, soff, count)
soff = soff or 0
if soff < 0 or soff > source.n then oob() end
count = count or (source.n - soff)
if count < 0 or soff + count > source.n or toff < 0 or toff + count > target.n then oob() end
if count > 0 then C.memmove(target.p + toff, source.p + soff, count) end
end
function Buf.fill(b, o, v, count)
if o < 0 or o > b.n then oob() end
count = count or (b.n - o)
if count < 0 or o + count > b.n then oob() end
if count > 0 then C.memset(b.p + o, v % 256, count) end
end
function Buf.tostring(b) return fstring(b.p, b.n) end
function Buf.fromstring(s)
local b = create(#s)
fcopy(b.p, s, #s)
return b
end
-- readbits / writebits: bit i of the buffer is bit (i % 8) of byte i // 8 (little-endian bit order), up to 32 bits
function Buf.readbits(b, bitOffset, bitCount)
if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end
if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end
local v, scale = 0, 1
local i = bitOffset
local e = bitOffset + bitCount
while i < e do
local byte = floor(i / 8)
local sh = i % 8
local take = 8 - sh
if take > e - i then take = e - i end
local x = bit.band(bit.rshift(b.p[byte], sh), bit.lshift(1, take) - 1)
v = v + x * scale
scale = scale * 2 ^ take
i = i + take
end
return v
end
function Buf.writebits(b, bitOffset, bitCount, value)
if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end
if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end
value = value % TWO32
local i = bitOffset
local e = bitOffset + bitCount
while i < e do
local byte = floor(i / 8)
local sh = i % 8
local take = 8 - sh
if take > e - i then take = e - i end
local m = bit.lshift(bit.lshift(1, take) - 1, sh)
local x = bit.band(bit.lshift(value % 256, sh), m)
b.p[byte] = bit.bor(bit.band(b.p[byte], bit.bnot(m)), x)
value = floor(value / 2 ^ take)
i = i + take
end
end
-- LuaJIT-only extensions
function Buf.toffi(b) return b.p end
function Buf.fromffi(ptr, n)
local b = create(n)
if n > 0 then fcopy(b.p, ptr, n) end
return b
end
M.buffer = Buf
end
-- ---------------------------------------------------------------------------------------------------- typeof / type
do
local BUF = M.BUFFER_MT
function M.type(v)
local t = rawtype(v)
if t == "table" and getmetatable(v) == BUF then
return "buffer"
end
return t
end
M.typeof = M.type
M.isbuffer = function(v) return getmetatable(v) == BUF end
end
-- ---------------------------------------------------------------------------------------------------- __iter
function M.__iter(t, s, c)
if rawtype(t) == "function" then return t, s, c end
if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end
local mt = getmetatable(t)
if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end
local n = #t
if n > 0 and next(t, n) == nil then return ipairs(t) end
return next, t, nil
end
-- ---------------------------------------------------------------------------------------------------- table
do
local okn, tnew = pcall(require, "table.new")
local okc, tclear = pcall(require, "table.clear")
if not table.create then
function table.create(n, v)
local t = okn and tnew(n, 0) or {}
if v ~= nil then for i = 1, n do t[i] = v end end
return t
end
end
table.clear = table.clear or (okc and tclear) or function(t) for k in pairs(t) do t[k] = nil end end
table.unpack = table.unpack or unpack
table.pack = table.pack or function(...) return { n = select("#", ...), ... } end
table.find = table.find or function(t, v, init)
for i = init or 1, #t do if t[i] == v then return i end end
return nil
end
table.move = table.move or function(a1, f, e, t, a2)
a2 = a2 or a1
if e >= f then
if t > f or t > e or a1 ~= a2 then
for i = 0, e - f do a2[t + i] = a1[f + i] end
else
for i = e - f, 0, -1 do a2[t + i] = a1[f + i] end
end
end
return a2
end
-- freeze is advisory on LuaJIT (no read-only tables): it only records the table for isfrozen
local frozen = setmetatable({}, { __mode = "k" })
table.freeze = table.freeze or function(t) frozen[t] = true; return t end
table.isfrozen = table.isfrozen or function(t) return frozen[t] == true end
table.clone = table.clone or function(t)
local c = {}
for k, v in pairs(t) do c[k] = v end
return setmetatable(c, getmetatable(t))
end
table.maxn = table.maxn or function(t)
local m = 0
for k in pairs(t) do if rawtype(k) == "number" and k > m then m = k end end
return m
end
end
-- ---------------------------------------------------------------------------------------------------- math
do
math.clamp = math.clamp or function(x, lo, hi)
if lo > hi then error("max must be greater than or equal to min", 2) end
if x < lo then return lo elseif x > hi then return hi end
return x
end
math.sign = math.sign or function(x)
if x > 0 then return 1 elseif x < 0 then return -1 end
return 0
end
-- Luau rounds half away from zero
math.round = math.round or function(x)
if x >= 0 then return floor(x + 0.5) end
return -floor(-x + 0.5)
end
math.lerp = math.lerp or function(a, b, t) return t == 1 and b or a + (b - a) * t end
math.map = math.map or function(x, a, b, c, d) return c + (d - c) * (x - a) / (b - a) end
math.isnan = math.isnan or function(x) return x ~= x end
math.isinf = math.isinf or function(x) return x == math.huge or x == -math.huge end
math.isfinite = math.isfinite or function(x) return x == x and x ~= math.huge and x ~= -math.huge end
-- stub: deterministic but not Roblox's Perlin noise (nothing in the library depends on its values)
math.noise = math.noise or function(x, y, z)
local s = math.sin((x or 0) * 12.9898 + (y or 0) * 78.233 + (z or 0) * 37.719) * 43758.5453
return (s - floor(s)) - 0.5
end
end
-- ---------------------------------------------------------------------------------------------------- string
string.split = string.split or function(s, sep)
sep = sep or ","
local out = {}
if sep == "" then
for i = 1, #s do out[i] = s:sub(i, i) end
return out
end
local i = 1
while true do
local a, b = s:find(sep, i, true)
if not a then
out[#out + 1] = s:sub(i)
return out
end
out[#out + 1] = s:sub(i, a - 1)
i = b + 1
end
end
-- ---------------------------------------------------------------------------------------------------- utf8
do
-- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it
local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" }
local char, byte = string.char, string.byte
local function enc(c)
if c < 0x80 then return char(c)
elseif c < 0x800 then return char(0xC0 + floor(c / 64), 0x80 + c % 64)
elseif c < 0x10000 then return char(0xE0 + floor(c / 4096), 0x80 + floor(c / 64) % 64, 0x80 + c % 64)
end
return char(0xF0 + floor(c / 262144), 0x80 + floor(c / 4096) % 64, 0x80 + floor(c / 64) % 64, 0x80 + c % 64)
end
function U.char(...)
local n = select("#", ...)
if n == 1 then return enc((...)) end
local out = {}
for i = 1, n do out[i] = enc((select(i, ...))) end
return table.concat(out)
end
-- decode at byte i: codepoint, length; nil on invalid UTF-8
local function dec(s, i)
local c = byte(s, i)
if not c then return nil end
if c < 0x80 then return c, 1 end
local n, v
if c >= 0xF0 and c < 0xF8 then n, v = 4, c % 8
elseif c >= 0xE0 then n, v = 3, c % 16
elseif c >= 0xC2 then n, v = 2, c % 32
else return nil end
if c >= 0xF8 then return nil end
for k = 1, n - 1 do
local cc = byte(s, i + k)
if not cc or cc < 0x80 or cc >= 0xC0 then return nil end
v = v * 64 + cc % 64
end
if (n == 3 and v < 0x800) or (n == 4 and (v < 0x10000 or v > 0x10FFFF)) or (v >= 0xD800 and v <= 0xDFFF) then
return nil
end
return v, n
end
function U.codes(s)
local i = 1
return function()
if i > #s then return nil end
local c, n = dec(s, i)
if not c then error("invalid UTF-8 code", 2) end
local p = i
i = i + n
return p, c
end
end
function U.codepoint(s, i, j)
i = i or 1
if i < 0 then i = #s + i + 1 end
j = j or i
if j < 0 then j = #s + j + 1 end
local out, k = {}, 0
while i <= j do
local c, n = dec(s, i)
if not c then error("invalid UTF-8 code", 2) end
k = k + 1
out[k] = c
i = i + n
end
return unpack(out, 1, k)
end
-- len(s, i, j) -> count | nil, position of the first invalid byte
function U.len(s, i, j)
i = i or 1
j = j or #s
if i < 0 then i = #s + i + 1 end
if j < 0 then j = #s + j + 1 end
local n = 0
while i <= j do
local c, l = dec(s, i)
if not c then return nil, i end
n = n + 1
i = i + l
end
return n
end
local function iscont(s, i)
local c = byte(s, i)
return c ~= nil and c >= 0x80 and c < 0xC0
end
function U.offset(s, n, i)
i = i or (n >= 0 and 1 or #s + 1)
if i < 0 then i = #s + i + 1 end
if n == 0 then
while i > 1 and iscont(s, i) do i = i - 1 end
return i
end
if iscont(s, i) then error("initial position is a continuation byte", 2) end
if n > 0 then
n = n - 1
while n > 0 and i <= #s do
i = i + 1
while iscont(s, i) do i = i + 1 end
n = n - 1
end
if n == 0 then return i end
return nil
end
while n < 0 and i > 1 do
i = i - 1
while i > 1 and iscont(s, i) do i = i - 1 end
n = n + 1
end
if n == 0 then return i end
return nil
end
function U.graphemes(s)
return U.codes(s)
end
M.utf8 = utf8 or U
end
-- install(): put the Luau globals in _G for code outside the library (a LÖVE game that wants buffer / bit32 itself)
function M.install(env)
env = env or _G
env.buffer = env.buffer or M.buffer
env.bit32 = env.bit32 or M.bit32
env.utf8 = env.utf8 or M.utf8
env.typeof = env.typeof or M.typeof
return M
end
return M
+6
View File
@@ -0,0 +1,6 @@
{
"name": "Formats",
"tree": {
"$path": "build/roblox/Formats"
}
}
+12
View File
@@ -0,0 +1,12 @@
# Formats
GENERATED by `tools/gen_registry.py` from each format's contract (`caps`) - do not edit. Every format listed here
is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build) by `bash tools/test.sh`.
| 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` |
Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
+247
View File
@@ -0,0 +1,247 @@
# formats-luau style guide
Every format looks the same: one folder, one contract, one test, one fixture generator. `bash tools/lint.sh` enforces
most of what follows (the rule names in CAPITALS are lint rules, implemented in `tools/lint_rules.py`).
The reference implementation to copy is **PNG**:
| What | Copy from |
|---|---|
| Format contract (`init.luau`) | `src/Formats/image/png/init.luau` |
| Private hot submodules (`--!native`) | `src/Formats/image/png/Decode.luau`, `src/Formats/image/png/Encode.luau` |
| Test | `tests/image/png.luau` |
| Fixture generator | `tools/fixtures/png.py` (a reference tool through nix: `tools/fixtures/_png_reference.py`) |
| A codec (layer 1) | `src/Formats/codecs/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` |
## 1. Layout and layers
```
src/Formats/
init.luau Registry.luau (generated) api (layer 6)
ops/ ops (layer 5.5) editing on the standard types
<category>/<fmt>/ formats (layer 5) image audio video model cad font archive data
vector layered subtitle music playlist
containers/ containers (layer 4) Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
codecs/ codecs (layer 3) Deflate, Lzw, Dct, Huffman-heavy algorithms
host/ host (layer 2) runtime adapters; only the api uses them
Types.luau types (layer 1) standard types + constructors
core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Huffman, Input
```
LAYERS: a module requires only what is below it. core requires core; Types requires core; codecs require core, Types
and other codecs; containers add codecs; a format may require core, Types, codecs, containers and **its own folder**,
never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/Vp8`).
Nothing but the api requires `host/`: formats are pure functions of bytes.
REQUIRE: every require is a string literal `require("@formats/<path>")` (tests and tools may also use
`require("@tests/<path>")`). No `script.X`, no `@self`, no relative paths, no computed requires: `tools/build.py` turns
these literals into Roblox instance paths and `require("formats.x.y")` for LuaJIT. `@formats/image/png` is the folder's
`init.luau`.
DEPS: a format's `deps = { ... }` lists exactly the modules outside its folder that the folder requires.
## 2. The format template
### Files
```
src/Formats/<category>/<fmt>/init.luau the contract (interpreted: never --!native)
src/Formats/<category>/<fmt>/<Private>.luau hot code, --!native allowed (Decode, Encode, Huffman tables, ...)
tests/<category>/<fmt>.luau the test (both runtimes)
tools/fixtures/<fmt>.py fixture generator (reference tools via nix) -> tests/gen/<fmt>_*.luau
```
### File header (HEADER)
```luau
--!strict
--!native -- private hot submodules only
--!optimize 2 -- optional
-- image/png/Decode: <what it is>. <Spec / port origin>. <Supports / not supported>.
```
The first comment line starts with the module path (`core/Bytes:`, `image/png:`, `image/png/Decode:`; `Formats:` for
the root). A format's `init.luau` header says what is supported and what is not, and where it came from (spec, port,
absorbed repo).
### Section order (CONTRACT)
Section markers are `-- ` + 96 dashes + ` <name>`; in a format's `init.luau` they appear in this order (requires and
contract are mandatory, the rest as needed):
`requires`, `contract`, `types`, `constants`, `sniff`, `decode`, `encode`, `open`, `extras`
### The contract
```luau
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Decode = require("@formats/image/qoi/Decode")
-- ------------------------------------------------------------------------------------------------ contract
local Qoi = {
name = "qoi", -- = the folder name
category = "image", -- = the folder category
extensions = { "qoi" }, -- lower case, no dot; the first is the canonical one
mime = { "image/qoi" },
deps = { "core/Err", "core/Bytes", "Types" }, -- exactly the requires outside the folder
caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ sniff
function Qoi.sniff(r: Bytes.Reader): number -- 0..1 from the first bytes; never consumes, never throws
return if r:peek(4) == "qoif" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
...
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
...
end
return Qoi
```
Rules:
- The six fields are **one-line literals** in the table (`tools/gen_registry.py` copies them into `Registry.luau` and
`docs/FORMATS.md` without running Luau). `caps.decode` / `caps.encode` match the functions that exist
(`decode = true` also when only `open` exists). Other caps keys are free-form facts (`animation`, `alpha`, `depths`,
`lossy`, `channels`, `streaming`, ...).
- `decode(r, opts)` gets a `core/Bytes` Reader over exactly the file (`r.buf`, `r.base`, `r.limit`: the data may sit
inside a bigger buffer; never assume offset 0). It returns the category's standard type from `Types.luau`
(`Types.Image.new(w, h)`, `Types.Scene.new()`, ...), `rgba8` for images unless `opts.native` asks for the source layout.
Fill `meta.source = { format = "<name>", ... }` with the source facts (bit depth, colour type, codec, ...).
- `encode(value, opts)` returns a buffer. Validate the value first and return `Err.ARG` for anything wrong.
- `open(r, opts)` (audio / video) returns the streaming Decoder / VideoDecoder / Demuxer from `Types.luau`. If a format
has `open` but no `decode`, `F.load` decodes the whole stream through it.
- Options are a typed table with defaults documented on each field (`level: number?, -- 0..9, default 6`).
- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module.
- No globals, no state between calls, no host access (no files, no `game`).
### Errors (Err)
Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.new(code, message, offset?)`:
| Code | When |
|---|---|
| `Err.TRUNCATED` | the data ends early (a `Bytes` reader past its end sets this itself) |
| `Err.CORRUPT` | malformed data |
| `Err.CHECKSUM` | CRC / Adler / hash mismatch |
| `Err.UNSUPPORTED` | valid data using a feature not implemented (say which) |
| `Err.LIMIT` | over `opts.maxPixels` / `opts.maxBytes` / ... (decoders must have a size limit before allocating) |
| `Err.ARG` | bad argument / option / value to encode |
| `Err.IO`, `Err.UNKNOWN_FORMAT` | used by the api |
Messages are lower case, without the format name (the api adds it: `png: CORRUPT at 0x21: bad filter type 7`).
The `Bytes` reader's errors are sticky: read a run of fields, then check `if r.err then return nil, r.err end` once.
Private submodules may return `false, "message"` or `nil, "message"`; `init.luau` turns that into an `Err`.
### Native code (NATIVE)
A Luau error unwinding through a native frame crashes Roblox Studio, even inside `pcall`. So:
- `--!native` only in private submodules (never a format's `init.luau`), and on `core/` / `codecs/` modules.
- A `--!native` module contains no `error(` / `assert(` and requires no module that does; an `@native` function body
contains none either.
- Every buffer access in native code is in range by construction: check lengths before loops (`r:need(n)`, explicit
`if p + n > limit then return nil, "truncated" end`), clamp table indexes, validate sizes against limits first.
- The fuzz pass in every test (truncations, mutations, garbage) is the safety net: it must report 0 throws.
### Performance on both runtimes
- Hot loops cache library functions in locals (`local readu8 = buffer.readu8`) and keep their own bit buffers.
- Bits / Bytes readers are for headers; inner loops read the buffer directly.
- LuaJIT runs the same code through `compat/luajit.lua` (FFI `buffer`, unsigned `bit32`). It is fastest with
straight-line code in the hottest loop: a tiny inner loop (`for k = 0, len - 1 do ... end` inside the symbol loop)
splits LuaJIT's traces; codecs/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead.
- Benchmark with `bash tools/bench.sh` pinned to one core (`taskset -c 2 bash tools/bench.sh`): on hybrid CPUs (this
machine: Zen 5 + Zen 5c) the same run differs 2x between core types.
- Avoid `string.pack` / `string.unpack` (not in LuaJIT), `\0` inside Lua patterns (LuaJIT: use `%z` or plain find),
and fractional operands to `bit32` (LuaJIT rounds where Luau truncates).
## 3. Tests
`tests/<category>/<fmt>.luau`, run by `bash tools/test.sh [filter]` under `luau --codegen -O2` **and** LuaJIT. Template:
```luau
-- image/qoi tests: <what is covered>. Fixtures: tools/fixtures/qoi.py.
local T = require("@tests/T")
local Qoi = require("@formats/image/qoi")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/qoi") -- written by tools/fixtures/qoi.py
local t = T.suite("qoi")
-- 1. the contract fields
-- 2. every fixture against the reference tool's output (pixel CRC / PSNR for lossy / PCM / mesh checksums)
for _, c in Fx.cases do
local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(img, c.name .. ": " .. tostring(err))
t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels")
end
-- 3. round trips through the encoder (lossless: equal; lossy: the reference decoder reads it, in the fixture step)
-- 4. error codes for crafted bad input (t:check(e.code == Err.CORRUPT, ...))
-- 5. the fuzz no-throw pass
t:fuzz("decode", function(b: buffer) return Qoi.decode(Bytes.reader(b)) end, samples)
t:done()
```
- `tests/T.luau`: `T.suite(name)` with `:check(cond, label)`, `:eq(got, want, label)`, `:note(fmt, ...)`,
`:fuzz(label, fn, samples, opts?)`, `:done()`; `T.rng(seed)` (the same numbers on both runtimes), `T.bytes{...}`,
`T.hex(buf)`, `T.runtime`.
- Fixtures: the luau CLI has no file I/O, so fixtures are Luau modules of string literals in `tests/gen/` (gitignored).
Write `tools/fixtures/<fmt>.py` with `def generate(ctx)` (see the header of `tools/fixtures.py`): `ctx.emit(name,
value)` writes `tests/gen/<name>.luau`; `ctx.nix("imagemagick", [...])` / `ctx.python(["pillow"], code)` run
reference tools through nix; `INPUTS = [...]` lists committed inputs (`tests/fixtures/<fmt>/`, small files with
their licence in `licenses/`). Prefer generating over committing. Keep fixture modules under ~15 MB.
- Both runtimes read the same `require("@tests/gen/<name>")`; there is no second mechanism.
- A fuzz pass is mandatory for every decoder (CONTRACT checks `:fuzz(`).
## 4. Adding a format
1. `src/Formats/<category>/<fmt>/init.luau` from the template above (copy `image/png/init.luau`), private submodules
next to it. Use `core/Bytes` for parsing, `core/Bits` / `core/Huffman` for entropy coding, `Types` constructors for
the result.
2. Shared code (a codec two formats need, a container) goes to `codecs/` or `containers/` instead, with its own test in
`tests/codecs/` / `tests/containers/`.
3. `deps = { ... }` = the requires outside the folder.
4. `python3 -I tools/gen_registry.py` (regenerates `src/Formats/Registry.luau` and `docs/FORMATS.md`; never edit those
by hand; after a merge, just rerun it).
5. `tools/fixtures/<fmt>.py` + `tests/<category>/<fmt>.luau`.
6. `bash tools/test.sh <fmt>` while working (both runtimes), then `bash tools/test.sh` (everything + lint).
7. The docs line comes from the contract (`docs/FORMATS.md`); put format notes (limits, spec deviations, bench numbers)
in the init header or `docs/<category>/<fmt>.md` if long.
Workstreams running in parallel own their folders (`<category>/<fmt>/`, their tests, their fixture generators).
`core/`, `Types.luau`, the api, `tools/`, `compat/` and this file belong to the lead: propose changes there instead of
making them (a missing `Bytes` method, a new `Types` field, a `Err` code).
## 5. Absorbing an existing repo
1. Copy the source into its place (a codec into `codecs/<Name>/`, a format into `<category>/<fmt>/`); the old repo stays
untouched (other projects use it).
2. Provenance: the module header says `Absorbed from <repo> <version> (<author / licence>)` and what changed.
3. Licence: copy the repo's licence / NOTICE into `licenses/` (`licenses/<repo>-LICENSE.txt`) and add a line to
`licenses/NOTICE.md`. Third-party ports keep their upstream licence text there too.
4. Requires: `if script then require(script.X) else require("@self/X")` becomes `require("@formats/<cat>/<fmt>/X")`;
injected dependencies (`require(Png)(Deflate)`) become direct requires of the codec.
5. Checksums / bit readers / Huffman tables the repo carries are replaced by `core/` ones when equivalent.
6. Wrap the public API in the contract: `sniff`, `decode(r: Reader, opts)` (reading from `r.buf` between `r.base` and
`r.limit`), `encode`, the standard type out, `Err` values instead of strings or throws.
7. Port the tests to `tests/<category>/<fmt>.luau` with `T`, and the fixture script to `tools/fixtures/<fmt>.py`
(`ctx.emit` instead of writing files). Both runtimes must pass.
## 6. Build notes (tools/build.py)
darklua 0.19 does most of the LuaJIT lowering (`remove_types`, `remove_attribute`, `remove_compound_assignment`,
`remove_continue`, `remove_if_expression`, `remove_interpolated_string`, `remove_floor_division`,
`convert_luau_number`) and the Roblox require conversion (`convert_require` luau -> roblox). Token passes in build.py
cover what it cannot:
- **Generalized iteration** (`for k, v in t do`): no darklua rule. Rewritten to `for k, v in __iter(t) do`
(compat: functions pass through; arrays with no keys past `#t` use `ipairs`; other tables `next`).
- **darklua bug**: `remove_if_expression` nests `elseif` branches in reverse order (`if a then 1 elseif b then 2
elseif c then 3 else 4` gives `a and 1 or (c and 3 or (b and 2 or 4))`). build.py rewrites every if-expression
`elseif` to `else if` before darklua.
- **If-expression tables**: darklua lowers `if c then x else y` to `(c and {x} or {y})[1]` unless `x` is a literal.
build.py turns it back into `(c and (x) or (y))` when `x` is provably not nil/false (numbers, strings, arithmetic).
- **Requires** become `require("formats.a.b")`; **stdlib names** come from `formats._compat` through locals injected on
the first line of each module (only the ones used: LuaJIT allows 60 upvalues per function).
- `string.format("%s", x)` with interpolation and `tostring` of floats print differently on LuaJIT (14 significant
digits); never compare formatted floats in tests.
+10
View File
@@ -0,0 +1,10 @@
# Third-party code, absorbed repositories and test data
| Where | From | Licence |
|---|---|---|
| `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) |
| `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code |
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+9
View File
@@ -0,0 +1,9 @@
PngSuite
--------
Permission to use, copy, modify and distribute these images for any
purpose and without fee is hereby granted.
(c) Willem van Schaik, 1996, 2011
+7
View File
@@ -0,0 +1,7 @@
deflate-luau contains no third-party code. It was written from the specifications:
- RFC 1951, DEFLATE Compressed Data Format Specification version 1.3 (P. Deutsch, 1996)
- RFC 1950, ZLIB Compressed Data Format Specification version 3.3 (P. Deutsch, J-L. Gailly, 1996)
- RFC 1952, GZIP file format specification version 4.3 (P. Deutsch, 1996)
The test fixtures are generated at test time by Python's zlib (tools/fixtures.py) and are not distributed.
+31
View File
@@ -0,0 +1,31 @@
--!strict
-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit.
-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format
-- module on first use (a static require, as Roblox needs). Order: category, then name.
export type Entry = {
name: string,
category: string,
path: string,
extensions: { string },
mime: { string },
deps: { string },
caps: { [string]: any },
load: () -> any,
}
local list: { Entry } = {
{
name = "png",
category = "image",
path = "image/png",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
load = function()
return require("@formats/image/png")
end,
},
}
return list
+475
View File
@@ -0,0 +1,475 @@
--!strict
-- Types: the standard value types every format of a category decodes to and encodes from, plus small constructors.
-- A PNG and a WebP both load as an Image; a WAV and an MP3 both open as an audio Decoder. Every top-level value has a
-- `kind` field ("image", "audio", "scene", ...) so F.save knows the category without a format name.
--
-- local T = require("@formats/Types")
-- local img = T.Image.new(64, 32) -- rgba8, zero-filled
-- local snd = T.Audio.new(44100, 2, 44100) -- 1 s of silent stereo f32
--
-- Shared enums are plain strings. Buffers are tightly packed, rows top to bottom, interleaved channels.
local Err = require("@formats/core/Err")
local Types = {}
export type Err = Err.Err
-- ------------------------------------------------------------------------------------------------ Image
-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the
-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each).
export type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p"
local BPP: { [string]: number } = {
rgba8 = 4,
rgba16 = 8,
rgbaf32 = 16,
rgb8 = 3,
gray8 = 1,
gray16 = 2,
graya8 = 2,
alpha8 = 1,
}
Types.BPP = table.freeze(BPP)
export type ImageMeta = {
colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ...
gamma: number?,
icc: buffer?, -- the raw ICC profile
exif: buffer?, -- the raw EXIF block (TIFF header onwards)
dpi: { x: number, y: number }?,
palette: { { number } }?, -- { r, g, b, a } 0..255 per entry, for palette sources
text: { [string]: string }?, -- tEXt / comments
source: { format: string, bitDepth: number?, colorType: string?, [string]: any }?,
[string]: any,
}
-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y
export type Frame = {
image: Image,
delay: number, -- seconds
x: number,
y: number,
dispose: "none" | "background" | "previous",
blend: "source" | "over",
}
export type Image = {
kind: "image",
width: number,
height: number,
format: PixelFormat,
pixels: buffer,
frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame)
loops: number, -- 0 = forever
meta: ImageMeta,
}
local Image = {}
-- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8)
function Image.new(width: number, height: number, format: PixelFormat?): Image
local f: PixelFormat = format or "rgba8"
local size
if f == "yuv420p" then
local cw, ch = (width + 1) // 2, (height + 1) // 2
size = width * height + 2 * cw * ch
else
size = width * height * (BPP[f] or 4)
end
return {
kind = "image",
width = width,
height = height,
format = f,
pixels = buffer.create(size),
frames = nil,
loops = 0,
meta = {},
}
end
-- bpp(format) -> bytes per pixel (nil for planar formats)
function Image.bpp(format: string): number?
return BPP[format]
end
Types.Image = Image
-- ------------------------------------------------------------------------------------------------ Audio
export type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ...
-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share)
export type Decoder = {
sampleRate: number,
channels: number,
frames: number, -- total sample frames (estimate for VBR streams without an index), 0 = unknown
duration: number, -- seconds
bitrate: number, -- bits per second (average)
tags: Tags,
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end); out (if given) is reused when big enough
read: (self: any, n: number, out: buffer?) -> (buffer, number),
seek: (self: any, seconds: number) -> (),
position: (self: any) -> number, -- seconds
}
-- a fully decoded sound (F.load / F.audio.load)
export type Audio = {
kind: "audio",
sampleRate: number,
channels: number,
frames: number,
samples: buffer, -- interleaved f32, frames * channels * 4 bytes
tags: Tags,
meta: { source: { format: string, [string]: any }?, [string]: any },
}
local Audio = {}
function Audio.new(sampleRate: number, channels: number, frames: number): Audio
return {
kind = "audio",
sampleRate = sampleRate,
channels = channels,
frames = frames,
samples = buffer.create(frames * channels * 4),
tags = {},
meta = {},
}
end
Types.Audio = Audio
-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI)
export type Module = {
kind: "music",
title: string,
format: string, -- "mod", "s3m", "xm", "it", "mid"
channels: number,
patterns: { any },
order: { number },
instruments: { any },
samples: { any },
render: (self: any, opts: any?) -> Decoder, -- every music file is also audio
meta: { [string]: any },
}
export type MidiEvent = { tick: number, type: string, channel: number?, data: { number }?, meta: any? }
export type Midi = {
kind: "midi",
format: number, -- SMF 0 / 1 / 2
division: number, -- ticks per quarter note (or SMPTE, negative)
tracks: { { events: { MidiEvent }, name: string? } },
meta: { [string]: any },
}
local Midi = {}
function Midi.new(division: number?): Midi
return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} }
end
Types.Midi = Midi
-- ------------------------------------------------------------------------------------------------ Video
export type Track = {
id: number,
kind: "video" | "audio" | "subtitle" | "data",
codec: string, -- "h264", "vp8", "mpeg1", "mjpeg", "aac", "mp3", "opus", ...
timescale: number, -- ticks per second for pts / duration
duration: number?, -- seconds
width: number?,
height: number?,
sampleRate: number?,
channels: number?,
config: buffer?, -- codec configuration (avcC, CodecPrivate, ...)
[string]: any,
}
export type Packet = { track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer }
export type Demuxer = {
tracks: { Track },
duration: number,
-- packets(trackId?) -> iterator of Packets in file order (one track, or all)
packets: (self: any, track: number?) -> () -> Packet?,
seek: ((self: any, seconds: number) -> ())?,
}
export type VideoFrame = { image: Image, pts: number, duration: number }
export type VideoDecoder = {
width: number,
height: number,
frameRate: number,
duration: number,
nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end
toRGBA: (self: any, frame: VideoFrame) -> Image,
seek: ((self: any, seconds: number) -> ())?,
audio: Decoder?, -- the first audio track, decoded
demuxer: Demuxer?,
}
-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped)
export type Accessor = {
data: buffer, -- tightly packed
type: "f32" | "u8" | "u16" | "u32" | "i8" | "i16" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
components: number, -- 1 (SCALAR) .. 4 (VEC4), 16 (MAT4)
count: number,
}
export type Primitive = {
attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_0, COLOR_0, JOINTS_0, WEIGHTS_0
indices: Accessor?,
mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip",
material: number?, -- index into scene.materials (1-based)
}
export type Mesh = { name: string?, primitives: { Primitive } }
export type Texture = { image: Image?, uri: string?, sampler: { wrapS: string?, wrapT: string?, filter: string? }? }
export type TextureRef = { texture: number, texCoord: number?, transform: { offset: { number }?, scale: { number }?, rotation: number? }? }
export type Material = {
name: string?,
baseColor: { number }, -- r, g, b, a linear 0..1
baseColorTexture: TextureRef?,
metallic: number,
roughness: number,
metallicRoughnessTexture: TextureRef?,
normalTexture: TextureRef?,
occlusionTexture: TextureRef?,
emissive: { number },
emissiveTexture: TextureRef?,
alphaMode: "opaque" | "mask" | "blend",
alphaCutoff: number,
doubleSided: boolean,
extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ...
}
export type Node = {
name: string?,
children: { number }, -- node indices (1-based)
mesh: number?,
camera: number?,
light: number?,
skin: number?,
translation: { number }?, -- TRS, or matrix (column-major 4x4), not both
rotation: { number }?, -- quaternion x, y, z, w
scale: { number }?,
matrix: { number }?,
extras: { [string]: any }?,
}
export type Camera = { type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? }
export type Light = { type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? }
export type Skin = { joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? }
export type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" }
export type Animation = { name: string?, channels: { Channel } }
export type Scene = {
kind: "scene",
nodes: { Node },
roots: { number }, -- top-level node indices
meshes: { Mesh },
materials: { Material },
textures: { Texture },
cameras: { Camera },
lights: { Light },
skins: { Skin },
animations: { Animation },
meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any },
}
local Scene = {}
function Scene.new(): Scene
return {
kind = "scene",
nodes = {},
roots = {},
meshes = {},
materials = {},
textures = {},
cameras = {},
lights = {},
skins = {},
animations = {},
meta = {},
}
end
function Scene.accessor(data: buffer, type: any, components: number, count: number): Accessor
return { data = data, type = type, components = components, count = count }
end
function Scene.material(name: string?): Material
return {
name = name,
baseColor = { 1, 1, 1, 1 },
metallic = 1,
roughness = 1,
emissive = { 0, 0, 0 },
alphaMode = "opaque",
alphaCutoff = 0.5,
doubleSided = false,
}
end
-- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF)
function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
local s = Scene.new()
s.meshes[1] = { name = name, primitives = { prim } }
s.nodes[1] = { name = name, children = {}, mesh = 1 }
s.roots[1] = 1
return s
end
Types.Scene = Scene
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
export type StepEntity = { id: number, type: string, args: { any } }
export type Cad = {
kind: "cad",
schema: string, -- "AP203", "AP214", "AP242", ...
header: { [string]: any },
entities: { [number]: StepEntity },
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Font
export type Font = {
kind: "font",
info: { family: string?, style: string?, fullName: string?, [string]: any },
unitsPerEm: number,
ascent: number,
descent: number,
lineGap: number,
glyphIndex: (self: any, codepoint: number) -> number, -- 0 = .notdef
advance: (self: any, glyph: number) -> number, -- font units
kern: (self: any, a: number, b: number) -> number,
outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo
rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8
pages: { Image }?, -- bitmap fonts (BMFont)
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Archive
export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean }
export type Archive = {
kind: "archive",
format: string,
list: (self: any) -> { ArchiveEntry },
read: (self: any, name: string) -> (buffer?, Err?),
add: (self: any, name: string, data: buffer | string, opts: any?) -> (),
write: (self: any, opts: any?) -> (buffer?, Err?),
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Data
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
-- table). XML decodes to XmlNode trees.
local nullMeta = { __tostring = function()
return "null"
end }
Types.null = table.freeze(setmetatable({}, nullMeta))
export type XmlNode = { name: string, attrs: { [string]: string }, children: { XmlNode | string }, parent: XmlNode? }
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
export type VectorPath = {
d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands
fill: Paint?,
fillRule: "nonzero" | "evenodd",
stroke: Paint?,
strokeWidth: number,
transform: { number }?, -- a, b, c, d, e, f
opacity: number,
}
export type Vector = {
kind: "vector",
width: number,
height: number,
viewBox: { number }, -- x, y, w, h
paths: { VectorPath },
meta: { [string]: any },
}
local Vector = {}
function Vector.new(width: number, height: number): Vector
return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} }
end
Types.Vector = Vector
-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite)
export type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean }
export type Layered = {
kind: "layered",
width: number,
height: number,
layers: { Layer }, -- bottom to top
frames: { { layers: { Layer }, delay: number } }?,
meta: { [string]: any },
}
local Layered = {}
function Layered.new(width: number, height: number): Layered
return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} }
end
Types.Layered = Layered
-- ------------------------------------------------------------------------------------------------ TileMap (Tiled)
export type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string? }
export type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any } }
export type TileMap = {
kind: "tilemap",
width: number,
height: number,
tileWidth: number,
tileHeight: number,
orientation: string,
tilesets: { Tileset },
layers: { TileLayer },
properties: { [string]: any },
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
export type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } }
local Subtitles = {}
function Subtitles.new(): Subtitles
return { kind = "subtitles", cues = {}, styles = {}, meta = {} }
end
Types.Subtitles = Subtitles
-- ------------------------------------------------------------------------------------------------ Playlist
-- the playlist-luau shape
export type PlaylistEntry = {
url: string,
title: string?,
duration: number?,
playable: boolean,
reason: string?,
bandwidth: number?,
codecs: string?,
attributes: { [string]: string }?,
byteRange: { length: number, offset: number? }?,
}
export type Playlist = {
kind: "playlist",
format: string, -- "m3u", "pls", "hls", "xspf"
entries: { PlaylistEntry },
warnings: { string },
title: string?,
hls: { [string]: any }?,
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ the format contract
-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md)
export type Caps = { decode: boolean, encode: boolean, [string]: any }
export type Format = {
name: string,
category: string,
extensions: { string },
mime: { string },
deps: { string },
sniff: (r: any) -> number, -- confidence 0..1 from the first bytes (a core/Bytes Reader); must not consume / throw
decode: ((r: any, opts: any?) -> (any, Err?))?,
encode: ((value: any, opts: any?) -> (buffer?, Err?))?,
open: ((r: any, opts: any?) -> (any, Err?))?, -- streaming categories (audio / video)
caps: Caps,
}
-- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to
Types.CATEGORIES = table.freeze({
image = "image",
audio = "audio",
video = "video",
model = "scene",
cad = "cad",
font = "font",
archive = "archive",
data = "data",
vector = "vector",
layered = "layered",
subtitle = "subtitles",
music = "music",
playlist = "playlist",
})
return Types
+432
View File
@@ -0,0 +1,432 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman
-- length-limited codes). Level 0 = stored blocks only.
--
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
local Huffman = require("@formats/core/Huffman")
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local floor = math.floor
local WSIZE = 32768
local HSIZE = 65536
local MAXMATCH = 258
local BLOCKSYMS = 16384 -- symbols per block
-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no
-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are
-- greedy (no lazy matching).
local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 }
local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 }
local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 }
local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 }
-- length 3..258 -> code 257..285 (index len), its extra bits and base
local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0)
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
for c = 1, 29 do
local base = LBASE[c]
local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1
for len = base, top do
LCODE[len] = 256 + c
LEXTRA[len] = LEXT[c]
LBASEOF[len] = base
end
end
local DBASE = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above
local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0)
for c = 1, 30 do
local base = DBASE[c]
local top = if c == 30 then 32768 else DBASE[c + 1] - 1
for d = base, math.min(top, 256) do
DSMALL[d] = c - 1
end
if top > 256 then
for k = math.max(base, 257), top, 128 do
DLARGE[(k - 1) // 128 + 1] = c - 1
end
end
end
local function dcode(d: number): number
if d <= 256 then
return DSMALL[d]
end
return DLARGE[(d - 1) // 128 + 1]
end
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- fixed codes
local FIXLEN = table.create(288, 0)
for i = 1, 288 do
FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8
end
local FIXDLEN = table.create(30, 5)
-- reversed (LSB-first) canonical codes for lengths
local function revCodes(lens: { number }): { number }
local codes = Huffman.codes(lens)
for i, l in lens do
if l > 0 then
codes[i] = Huffman.reverse(codes[i], l)
end
end
return codes
end
local FIXCODE = revCodes(FIXLEN)
local FIXDCODE = revCodes(FIXDLEN)
local POW = table.create(33, 0)
for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit output
type Out = { buf: buffer, op: number, acc: number, cnt: number }
local function ensure(o: Out, n: number)
if o.op + n > blen(o.buf) then
local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n))
bcopy(nb, 0, o.buf, 0, o.op)
o.buf = nb
end
end
-- put(v, n): n <= 24 bits, LSB first
local function put(o: Out, v: number, n: number)
local acc = o.acc + v * POW[o.cnt + 1]
local cnt = o.cnt + n
if cnt >= 8 then
ensure(o, 4)
local buf, op = o.buf, o.op
while cnt >= 8 do
local byte = acc % 256
writeu8(buf, op, byte)
op += 1
acc = (acc - byte) / 256
cnt -= 8
end
o.op = op
end
o.acc, o.cnt = acc, cnt
end
local function alignOut(o: Out)
if o.cnt > 0 then
put(o, 0, 8 - o.cnt)
end
end
-- ------------------------------------------------------------------------------------------------ blocks
-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals)
local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean)
local p = s
repeat
local n = math.min(65535, e - p)
local last = final and p + n >= e
put(o, if last then 1 else 0, 3)
alignOut(o)
ensure(o, 4 + n)
writeu16(o.buf, o.op, n)
writeu16(o.buf, o.op + 2, 65535 - n)
bcopy(o.buf, o.op + 4, src, p, n)
o.op += 4 + n
p += n
until p >= e
end
local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number })
for i = 1, nsym do
local l = L[i]
if l < 256 then
put(o, lcode[l + 1], llen[l + 1])
else
local len = l - 256
local c = LCODE[len]
put(o, lcode[c + 1], llen[c + 1])
local xb = LEXTRA[len]
if xb > 0 then
put(o, len - LBASEOF[len], xb)
end
local d = D[i]
local dc = dcode(d)
put(o, dcodes[dc + 1], dlen[dc + 1])
xb = DEXT[dc + 1]
if xb > 0 then
put(o, d - DBASE[dc + 1], xb)
end
end
end
put(o, lcode[257], llen[257]) -- end of block
end
local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean)
local lf = table.create(286, 0)
local df = table.create(30, 0)
local extra = 0
for i = 1, nsym do
local l = L[i]
if l < 256 then
lf[l + 1] += 1
else
local len = l - 256
lf[LCODE[len] + 1] += 1
extra += LEXTRA[len]
local dc = dcode(D[i])
df[dc + 1] += 1
extra += DEXT[dc + 1]
end
end
lf[257] = 1
local llen = Huffman.lengths(lf, 15)
local dlen = Huffman.lengths(df, 15)
local hlit = 286
while hlit > 257 and llen[hlit] == 0 do
hlit -= 1
end
local hdist = 30
while hdist > 1 and dlen[hdist] == 0 do
hdist -= 1
end
if dlen[1] == 0 and hdist == 1 then
dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes)
end
-- code-length symbols: RLE of the hlit + hdist lengths
local all = table.create(hlit + hdist, 0)
for i = 1, hlit do
all[i] = llen[i]
end
for i = 1, hdist do
all[hlit + i] = dlen[i]
end
local cs, cx = {}, {} -- symbol, extra value
local cf = table.create(19, 0)
local i = 1
local total = hlit + hdist
while i <= total do
local v = all[i]
local run = 1
while i + run <= total and all[i + run] == v do
run += 1
end
if v == 0 and run >= 3 then
local r = math.min(run, 138)
if r >= 11 then
table.insert(cs, 18)
table.insert(cx, r - 11)
cf[19] += 1
else
table.insert(cs, 17)
table.insert(cx, r - 3)
cf[18] += 1
end
i += r
elseif v ~= 0 and run >= 4 then
table.insert(cs, v)
table.insert(cx, 0)
cf[v + 1] += 1
local r = math.min(run - 1, 6)
table.insert(cs, 16)
table.insert(cx, r - 3)
cf[17] += 1
i += 1 + r
else
table.insert(cs, v)
table.insert(cx, 0)
cf[v + 1] += 1
i += 1
end
end
local clen = Huffman.lengths(cf, 7)
local hclen = 19
while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do
hclen -= 1
end
-- costs in bits
local dyn = 17 + 3 * hclen + extra
for k = 1, 19 do
dyn += cf[k] * clen[k]
end
dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7
local fix = 3 + extra
for k = 1, 286 do
dyn += lf[k] * llen[k]
fix += lf[k] * FIXLEN[k]
end
for k = 1, 30 do
dyn += df[k] * dlen[k]
fix += df[k] * 5
end
local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7
if stored <= dyn and stored <= fix then
storedBlock(o, src, s, e, final)
return
end
if fix <= dyn then
put(o, if final then 3 else 2, 3)
emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN)
return
end
put(o, if final then 5 else 4, 3)
put(o, hlit - 257, 5)
put(o, hdist - 1, 5)
put(o, hclen - 4, 4)
for k = 1, hclen do
put(o, clen[CLORDER[k] + 1], 3)
end
local ccode = revCodes(clen)
for k = 1, #cs do
local c = cs[k]
put(o, ccode[c + 1], clen[c + 1])
if c == 16 then
put(o, cx[k], 2)
elseif c == 17 then
put(o, cx[k], 3)
elseif c == 18 then
put(o, cx[k], 7)
end
end
emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen)
end
-- ------------------------------------------------------------------------------------------------ LZ77
local Compress = {}
function Compress.raw(src: buffer, off: number, len: number, level: number): buffer
local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 }
local e = off + len
if level == 0 or len == 0 then
if len == 0 then
put(o, 3, 3) -- one empty fixed block
put(o, 0, 7)
else
storedBlock(o, src, off, e, true)
end
alignOut(o)
local out = bcreate(o.op)
bcopy(out, 0, o.buf, 0, o.op)
return out
end
local maxChain = CHAIN[level]
local nice = NICE[level]
local good = GOOD[level]
local lazyMax = LAZY[level]
local head = table.create(HSIZE, -1)
local prev = table.create(WSIZE, -1)
local L = table.create(BLOCKSYMS, 0)
local D = table.create(BLOCKSYMS, 0)
local nsym = 0
local blockStart = off
local function hash(p: number): number
return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE
end
local function insert(p: number)
local h = hash(p) + 1
prev[p % WSIZE + 1] = head[h]
head[h] = p
end
-- longest match at p among earlier positions: len (0 if < 3), dist
local function find(p: number, steps: number): (number, number)
local maxLen = math.min(MAXMATCH, e - p)
if maxLen < 3 then
return 0, 0
end
local best, bestDist = 2, 0
local c = head[hash(p) + 1]
local limit = p - WSIZE
while c >= 0 and c > limit and steps > 0 do
if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then
local k = 1
while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do
k += 1
end
if k > best then
best, bestDist = k, p - c
if k >= nice or k >= maxLen then
break
end
end
end
local nc = prev[c % WSIZE + 1]
if nc >= c then
break -- the slot was reused by a newer position: the chain ends here
end
c = nc
steps -= 1
end
if best < 3 then
return 0, 0
end
return best, bestDist
end
local function flush(upto: number, final: boolean)
block(o, src, blockStart, upto, L, D, nsym, final)
nsym = 0
blockStart = upto
end
local p = off
local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed
while p < e do
local mlen, mdist = 0, 0
if p <= stop3 then
mlen, mdist = find(p, maxChain)
insert(p)
if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then
local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain)
if l2 > mlen then
-- a literal now, the longer match from p + 1
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
p += 1
insert(p)
mlen, mdist = l2, d2
end
end
end
if mlen >= 3 then
nsym += 1
L[nsym] = 256 + mlen
D[nsym] = mdist
local q = p + 1
local qe = math.min(p + mlen, stop3 + 1)
while q < qe do
insert(q)
q += 1
end
p += mlen
else
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
p += 1
end
if nsym >= BLOCKSYMS - 2 then
flush(p, p >= e)
end
end
if nsym > 0 or blockStart < e then
flush(e, true)
elseif blockStart == e and o.op == 0 and o.cnt == 0 then
put(o, 3, 3)
put(o, 0, 7)
end
alignOut(o)
local out = bcreate(o.op)
bcopy(out, 0, o.buf, 0, o.op)
return out
end
return Compress
+435
View File
@@ -0,0 +1,435 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose
-- entries are symbol * 32 + length (5 length bits instead of 4).
--
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
-- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
--
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
local Huffman = require("@formats/core/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local LITBITS, DISTBITS, CLBITS = 10, 8, 7
local LITMASK, DISTMASK, CLMASK = 1023, 255, 127
-- length codes 257..285 and distance codes 0..29: base value, extra bits
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
local DBASE = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- the order code-length code lengths are sent in
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case
local LITCAP = Huffman.capacity(288, LITBITS, 15)
local DISTCAP = Huffman.capacity(32, DISTBITS, 15)
local CLCAP = Huffman.capacity(19, CLBITS, 7)
-- fixed Huffman tables
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local FLITS, FDISTS
do
local l = bcreate(288)
bfill(l, 0, 8, 144)
bfill(l, 144, 9, 112)
bfill(l, 256, 7, 24)
bfill(l, 280, 8, 8)
FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS)
local d = bcreate(30)
bfill(d, 0, 5, 30)
FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS)
end
local Inflate = {}
-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity.
local function grow(out: buffer, op: number, need: number): (buffer, number)
local cap = math.max(blen(out) * 2, need, 1024)
local nb = bcreate(cap)
bcopy(nb, 0, out, 0, op)
return nb, cap
end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed.
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?)
local out = bcreate(cap)
local op = 0
local pos = start
local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local clt = bcreate(CLCAP * 4)
local lens = bcreate(320)
local final = 0
repeat
-- block header (3 bits); also up to 14 bits of a dynamic header
if bitcnt < 17 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
final = band(bitbuf, 1)
local btype = band(rshift(bitbuf, 1), 3)
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
if btype == 0 then
-- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer
local k = band(bitcnt, 7)
bitcnt -= k
local real = rshift(bitcnt, 3) - over
if real < 0 then
return nil, "truncated input"
end
pos -= real
bitbuf, bitcnt, over = 0, 0, 0
if pos + 4 > endpos then
return nil, "truncated input"
end
local n = readu16(src, pos)
if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then
return nil, "stored block length mismatch"
end
pos += 4
if pos + n > endpos then
return nil, "truncated input"
end
if op + n > cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + n)
end
bcopy(out, op, src, pos, n)
op += n
pos += n
continue
end
local lsub, dsub
if btype == 1 then
lt, dt = FLIT, FDIST
lsub, dsub = FLITS, FDISTS
elseif btype == 2 then
if lt == FLIT then
lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
end
local hlit = band(bitbuf, 31) + 257
local hdist = band(rshift(bitbuf, 5), 31) + 1
local hclen = band(rshift(bitbuf, 10), 15) + 4
bitbuf = rshift(bitbuf, 14)
bitcnt -= 14
if hlit > 286 or hdist > 30 then
return nil, "too many length or distance symbols"
end
bfill(lens, 0, 0, 19)
for i = 1, hclen do
if bitcnt < 3 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
writeu8(lens, CLORDER[i], band(bitbuf, 7))
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
end
if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then
return nil, "invalid code lengths set"
end
local total = hlit + hdist
local i = 0
while i < total do
if bitcnt < 14 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local e = readu32(clt, band(bitbuf, CLMASK) * 4)
local l = band(e, 31)
if l == 0 then
return nil, "invalid code lengths set"
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local sym = rshift(e, 5)
if sym < 16 then
writeu8(lens, i, sym)
i += 1
else
local rep, val
if sym == 16 then
if i == 0 then
return nil, "repeat with no first length"
end
val = readu8(lens, i - 1)
rep = 3 + band(bitbuf, 3)
bitbuf = rshift(bitbuf, 2)
bitcnt -= 2
elseif sym == 17 then
val = 0
rep = 3 + band(bitbuf, 7)
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
else
val = 0
rep = 11 + band(bitbuf, 127)
bitbuf = rshift(bitbuf, 7)
bitcnt -= 7
end
if i + rep > total then
return nil, "too many code lengths"
end
bfill(lens, i, val, rep)
i += rep
end
end
if readu8(lens, 256) == 0 then
return nil, "missing end-of-block code"
end
lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS)
dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS)
if lsub < 0 or dsub < 0 then
return nil, "invalid literal/length or distance code set"
end
else
return nil, "invalid block type"
end
local lsmask = lshift(1, lsub) - 1
local dsmask = lshift(1, dsub) - 1
-- the symbol loop
while true do
if bitcnt < 15 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local e = readu32(lt, band(bitbuf, LITMASK) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "invalid literal/length code"
end
e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "invalid literal/length code"
end
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local sym = rshift(e, 5)
if sym < 256 then
if op >= cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + 1)
end
writeu8(out, op, sym)
op += 1
elseif sym == 256 then
break
else
sym -= 256
if sym > 29 then
return nil, "invalid literal/length code"
end
-- up to 5 length extra bits + a 15-bit distance code
if bitcnt < 20 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local len = LBASE[sym]
local xb = LEXT[sym]
if xb > 0 then
len += band(bitbuf, lshift(1, xb) - 1)
bitbuf = rshift(bitbuf, xb)
bitcnt -= xb
end
e = readu32(dt, band(bitbuf, DISTMASK) * 4)
l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "invalid distance code"
end
e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "invalid distance code"
end
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local dsym = rshift(e, 5) + 1
if dsym > 30 then
return nil, "invalid distance code"
end
local dist = DBASE[dsym]
xb = DEXT[dsym]
if xb > 0 then
if bitcnt < 13 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
dist += band(bitbuf, lshift(1, xb) - 1)
bitbuf = rshift(bitbuf, xb)
bitcnt -= xb
end
if dist > op then
return nil, "invalid distance too far back"
end
if op + len > cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + len)
end
local s = op - dist
if dist >= len then
if len <= 16 and op + 16 <= cap then
-- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which
-- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones
writeu32(out, op, readu32(out, s))
writeu32(out, op + 4, readu32(out, s + 4))
writeu32(out, op + 8, readu32(out, s + 8))
writeu32(out, op + 12, readu32(out, s + 12))
elseif len <= 16 then
for k = 0, len - 1 do
writeu8(out, op + k, readu8(out, s + k))
end
else
bcopy(out, op, out, s, len)
end
op += len
elseif dist == 1 then
bfill(out, op, readu8(out, s), len)
op += len
else
-- overlapping: the pattern of period dist, copied in growing non-overlapping chunks
local rem = len
while rem > 0 do
local k = math.min(op - s, rem)
bcopy(out, op, out, s, k)
op += k
rem -= k
end
end
end
end
until final == 1
local consumed = pos + over - rshift(bitcnt, 3)
if consumed > endpos then
return nil, "truncated input"
end
return out, op, consumed
end
return Inflate
+301
View File
@@ -0,0 +1,301 @@
--!strict
-- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
-- (same author; no third-party code); the compressor is new.
--
-- local Deflate = require("@formats/codecs/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Adler32 = require("@formats/core/Adler32")
local Inflate = require("@formats/codecs/Deflate/Inflate")
local Compress = require("@formats/codecs/Deflate/Compress")
local Deflate = {}
Deflate.version = "1.1.0"
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
if type(b) ~= "buffer" then
return nil
end
return b
end
-- (offset, length) clamped to the buffer; nil for non-numbers / negative / fractional / out-of-range offsets
local function range(b: buffer, off: number?, len: number?): (number?, number)
local n = buffer.len(b)
local o = off or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, 0
end
local l = len or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, 0
end
if o + l > n then
l = n - o
end
return o, l
end
local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = toBuffer(buf)
if not b then
return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
end
local o, l = range(b, offset, length)
if not o then
return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
end
return b, o, l, nil
end
local function shrink(out: buffer, n: number): buffer
if buffer.len(out) == n then
return out
end
local b = buffer.create(n)
buffer.copy(b, 0, out, 0, n)
return b
end
local function inflateErr(msg: string, at: number?): Err.Err
local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT
return Err.new(code, "inflate: " .. msg, at)
end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
return nil, aerr
end
local exact = expectedSize ~= nil
local cap
if exact then
if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize))
end
cap = expectedSize
else
cap = math.max(1024, l * 4)
end
local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact)
if not out then
return nil, inflateErr(tostring(n), o)
end
if exact and n ~= expectedSize then
return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number))
end
return shrink(out, n), consumed
end
-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err
function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.zlib", buf, offset, length)
if not b then
return nil, aerr
end
if l < 6 then
return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o)
end
local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1)
if cmf % 16 ~= 8 or cmf // 16 > 7 then
return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o)
end
if (cmf * 256 + flg) % 31 ~= 0 then
return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o)
end
if bit32.band(flg, 0x20) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o)
end
local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize)
if not out then
return nil, consumed
end
if consumed + 4 > o + l then
return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed)
end
local want = bit32.byteswap(buffer.readu32(b, consumed))
local got = Adler32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
return out, consumed + 4
end
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length)
if not b then
return nil, aerr
end
local e = o + l
local parts, total = {}, 0
local p = o
repeat
if p + 18 > e then
if #parts > 0 then
break
end
return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p)
end
if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then
if #parts > 0 then
break -- trailing garbage after a member: ignored, as gzip -d does
end
return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p)
end
if buffer.readu8(b, p + 2) ~= 8 then
return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2)
end
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3)
end
local q = p + 10
if bit32.band(flg, 4) ~= 0 then -- FEXTRA
if q + 2 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
q += 2 + buffer.readu16(b, q)
end
for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated
if bit32.band(flg, bit) ~= 0 then
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
q += 1
end
end
if bit32.band(flg, 2) ~= 0 then -- FHCRC
q += 2
end
if q >= e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
local out, consumed = Deflate.inflate(b, q, e - q)
if not out then
return nil, consumed
end
if consumed + 8 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed)
end
local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4)
local got = Crc32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
if buffer.len(out) % 4294967296 ~= isize then
return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4)
end
table.insert(parts, out)
total += buffer.len(out)
p = consumed + 8
-- skip zero padding
local z = p
while z < e and buffer.readu8(b, z) == 0 do
z += 1
end
if z == e then
break
end
until p >= e
if #parts == 1 then
return parts[1], nil
end
local res = buffer.create(total)
local w = 0
for _, part in parts do
buffer.copy(res, w, part)
w += buffer.len(part)
end
return res, nil
end
export type CompressOptions = {
level: number?, -- 0 (stored) .. 9 (best); default 6
}
local function level(opts: CompressOptions?): number?
local lv = if opts and opts.level ~= nil then opts.level else 6
if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then
return nil
end
return lv
end
-- compress(buf, opts?) -> raw deflate buffer | nil, Err
function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9")
end
return Compress.raw(b, 0, buffer.len(b), lv), nil
end
-- zlibCompress(buf, opts?) -> zlib stream | nil, Err
function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 6)
local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3
local cmf = 0x78
local flg = flevel * 64
flg += 31 - (cmf * 256 + flg) % 31
buffer.writeu8(out, 0, cmf)
buffer.writeu8(out, 1, flg)
buffer.copy(out, 2, raw, 0, n)
buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b))))
return out, nil
end
-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err
function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 18)
buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0")
buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0)
buffer.writeu8(out, 9, 255)
buffer.copy(out, 10, raw, 0, n)
buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b)))
buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296)
return out, nil
end
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Crc32.of(b, offset, length, crc)
end
Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Adler32.of(b, offset, length, adler)
end
return Deflate
+50
View File
@@ -0,0 +1,50 @@
--!strict
--!native
-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author;
-- no third-party code). Never throws: the range is clamped.
--
-- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it)
-- Adler32.string(s, adler?) -> u32
local readu8 = buffer.readu8
-- Adler-32 of buf[off, off + len), continuing adler (default 1)
local function adler32(buf: buffer, off: number, len: number, adler: number?): number
local a0 = adler or 1
local a, b = a0 % 65536, a0 // 65536
local i, e = off, off + len
while i < e do
-- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far
-- more, but keeping the sums small keeps them exact and cheap.
local stop = math.min(e, i + 5552)
while i < stop do
a += readu8(buf, i)
b += a
i += 1
end
a %= 65521
b %= 65521
end
return b * 65536 + a
end
-- clamp (offset, length) to the buffer
local function range(buf: buffer, offset: number?, length: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(offset or 0, 0, n)
return o, math.clamp(length or (n - o), 0, n - o)
end
local Adler32 = {}
function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number
local o, l = range(buf, offset, length)
return adler32(buf, o, l, adler)
end
function Adler32.string(s: string, adler: number?): number
return adler32(buffer.fromstring(s), 0, #s, adler)
end
Adler32.raw = adler32
return Adler32
+287
View File
@@ -0,0 +1,287 @@
--!strict
--!native
-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data
-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write.
--
-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes.
-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see
-- codecs/Deflate/Inflate) and uses these for headers.
--
-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED).
--
-- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader
-- local v = br:read(5); if br.err then return nil, br.err end
-- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish()
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local readu8, blen = buffer.readu8, buffer.len
local floor = math.floor
-- 2^n for n = 0..32
local POW = table.create(33, 0)
for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
local Bits = {}
Bits.POW = POW
-- ------------------------------------------------------------------------------------------------ readers
export type BitReader = {
buf: buffer,
pos: number, -- next byte to load
limit: number,
acc: number, -- loaded, unread bits
cnt: number, -- how many
err: Err.Err?,
read: (BitReader, number) -> number,
peek: (BitReader, number) -> number,
skip: (BitReader, number) -> (),
align: (BitReader) -> (),
bytePos: (BitReader) -> number,
bitsLeft: (BitReader) -> number,
}
local function overrun(self: any)
if not self.err then
self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit)
end
end
-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant
local Lsb = {}
Lsb.__index = Lsb
local function lsbFill(self: any, n: number)
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc += readu8(self.buf, pos) * POW[cnt + 1]
pos += 1
else
overrun(self)
end
cnt += 8
end
self.acc, self.cnt, self.pos = acc, cnt, pos
end
function Lsb.read(self: any, n: number): number
if n > 24 then
local lo = Lsb.read(self, 16)
return lo + Lsb.read(self, n - 16) * 65536
end
if self.cnt < n then
lsbFill(self, n)
end
local m = POW[n + 1]
local v = self.acc % m
self.acc = (self.acc - v) / m
self.cnt -= n
return v
end
function Lsb.peek(self: any, n: number): number
if self.cnt < n then
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do -- no error for peeking past the end: the bits are zeros
if pos < self.limit then
acc += readu8(self.buf, pos) * POW[cnt + 1]
pos += 1
end
cnt += 8
end
-- keep the loaded bytes only when they are all real (zero padding past the end is not data)
if (pos - self.pos) * 8 == cnt - self.cnt then
self.acc, self.cnt, self.pos = acc, cnt, pos
end
return acc % POW[n + 1]
end
return self.acc % POW[n + 1]
end
function Lsb.skip(self: any, n: number)
while n > 24 do
Lsb.read(self, 24)
n -= 24
end
Lsb.read(self, n)
end
-- align(): drop the bits up to the next byte boundary
function Lsb.align(self: any)
local k = self.cnt % 8
if k > 0 then
Lsb.read(self, k)
end
end
-- bytePos(): the offset of the first byte not yet (even partly) consumed
function Lsb.bytePos(self: any): number
return self.pos - floor(self.cnt / 8)
end
function Lsb.bitsLeft(self: any): number
return (self.limit - self.pos) * 8 + self.cnt
end
-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant
local Msb = {}
Msb.__index = Msb
local function msbFill(self: any, n: number)
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc = acc * 256 + readu8(self.buf, pos)
pos += 1
else
acc *= 256
overrun(self)
end
cnt += 8
end
self.acc, self.cnt, self.pos = acc, cnt, pos
end
function Msb.read(self: any, n: number): number
if n > 24 then
local hi = Msb.read(self, n - 16)
return hi * 65536 + Msb.read(self, 16)
end
if self.cnt < n then
msbFill(self, n)
end
local sh = POW[self.cnt - n + 1]
local v = floor(self.acc / sh)
self.acc -= v * sh
self.cnt -= n
return v
end
function Msb.peek(self: any, n: number): number
local acc, cnt, pos = self.acc, self.cnt, self.pos
while cnt < n do
if pos < self.limit then
acc = acc * 256 + readu8(self.buf, pos)
pos += 1
else
acc *= 256
end
cnt += 8
end
-- keep the loaded bytes only when they are all real (zero padding past the end is not data)
if (pos - self.pos) * 8 == cnt - self.cnt then
self.acc, self.cnt, self.pos = acc, cnt, pos
end
return floor(acc / POW[cnt - n + 1])
end
function Msb.skip(self: any, n: number)
while n > 24 do
Msb.read(self, 24)
n -= 24
end
Msb.read(self, n)
end
function Msb.align(self: any)
local k = self.cnt % 8
if k > 0 then
Msb.read(self, k)
end
end
Msb.bytePos = Lsb.bytePos
Msb.bitsLeft = Lsb.bitsLeft
local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
local l = math.clamp(length or (n - o), 0, n - o)
return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any
end
-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader
function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Lsb, buf, offset, length)
end
function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader
return reader(Msb, buf, offset, length)
end
-- ------------------------------------------------------------------------------------------------ writers
export type BitWriter = {
out: Bytes.Writer, -- the bytes so far (whole bytes only)
acc: number,
cnt: number,
write: (BitWriter, number, number) -> (),
align: (BitWriter) -> (),
finish: (BitWriter) -> buffer,
}
local LsbW = {}
LsbW.__index = LsbW
function LsbW.write(self: any, v: number, n: number)
if n > 24 then
local lo = v % 65536
LsbW.write(self, lo, 16)
LsbW.write(self, (v - lo) / 65536, n - 16)
return
end
local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1]
local cnt = self.cnt + n
local out = self.out
while cnt >= 8 do
local byte = acc % 256
out:u8(byte)
acc = (acc - byte) / 256
cnt -= 8
end
self.acc, self.cnt = acc, cnt
end
-- align(): pad with zero bits to a byte boundary
function LsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc)
self.acc, self.cnt = 0, 0
end
end
function LsbW.finish(self: any): buffer
LsbW.align(self)
return self.out:finish()
end
local MsbW = {}
MsbW.__index = MsbW
function MsbW.write(self: any, v: number, n: number)
if n > 24 then
local lo = v % 65536
MsbW.write(self, (v - lo) / 65536, n - 16)
MsbW.write(self, lo, 16)
return
end
local acc = self.acc * POW[n + 1] + (v % POW[n + 1])
local cnt = self.cnt + n
local out = self.out
while cnt >= 8 do
local sh = POW[cnt - 8 + 1]
local byte = floor(acc / sh)
out:u8(byte)
acc -= byte * sh
cnt -= 8
end
self.acc, self.cnt = acc, cnt
end
function MsbW.align(self: any)
if self.cnt > 0 then
self.out:u8(self.acc * POW[8 - self.cnt + 1])
self.acc, self.cnt = 0, 0
end
end
function MsbW.finish(self: any): buffer
MsbW.align(self)
return self.out:finish()
end
-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter
function Bits.lsbWriter(capacity: number?): BitWriter
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any
end
function Bits.msbWriter(capacity: number?): BitWriter
return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any
end
return Bits
+537
View File
@@ -0,0 +1,537 @@
--!strict
--!native
-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a
-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers.
--
-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor
-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads:
--
-- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length)
-- local magic, w, h = r:string(4), r:u32be(), r:u32be()
-- if r.err then return nil, r.err end
-- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end
--
-- local w = Bytes.writer() -- or Bytes.writer(initialCapacity)
-- w:string("abcd"); w:u32be(width); local out = w:finish()
local Err = require("@formats/core/Err")
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring
local writeu8, writeu16, writeu32, writef32, writef64, writestring = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32, buffer.writef64, buffer.writestring
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local byteswap = bit32.byteswap
local TWO32 = 4294967296
local scratch = bcreate(8) -- reinterpret casts for big-endian floats
local Bytes = {}
-- ------------------------------------------------------------------------------------------------ Reader
local Reader = {}
Reader.__index = Reader
export type Reader = typeof(setmetatable(
{} :: {
buf: buffer,
pos: number, -- absolute offset of the next byte in buf
base: number, -- absolute offset of the reader's first byte
limit: number, -- absolute offset just past the reader's last byte
err: Err.Err?, -- sticky: the first failure
},
Reader
))
-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer
function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
local l = math.clamp(length or (n - o), 0, n - o)
return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader)
end
-- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)`
function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err)
if not self.err then
self.err = Err.new(code, message, self.pos)
end
return nil, self.err :: Err.Err
end
-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end
function Reader.need(self: Reader, n: number): boolean
if self.pos + n <= self.limit and n >= 0 then
return true
end
if not self.err then
self.err = Err.new(Err.TRUNCATED, string.format("need %d bytes, %d left", n, self.limit - self.pos), self.pos)
end
self.pos = self.limit
return false
end
function Reader.tell(self: Reader): number
return self.pos - self.base
end
function Reader.size(self: Reader): number
return self.limit - self.base
end
function Reader.remaining(self: Reader): number
return self.limit - self.pos
end
function Reader.eof(self: Reader): boolean
return self.pos >= self.limit
end
-- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED
function Reader.seek(self: Reader, offset: number): boolean
if offset < 0 or self.base + offset > self.limit then
self.pos = self.limit
if not self.err then
self.err = Err.new(Err.TRUNCATED, "seek to " .. offset .. " past the end", self.base + offset)
end
return false
end
self.pos = self.base + offset
return true
end
function Reader.skip(self: Reader, n: number): boolean
if self:need(n) then
self.pos += n
return true
end
return false
end
-- align(n): skip to the next multiple of n (relative to the reader's start)
function Reader.align(self: Reader, n: number): boolean
local r = (self.pos - self.base) % n
if r == 0 then
return true
end
return self:skip(n - r)
end
-- integers
function Reader.u8(self: Reader): number
local p = self.pos
if p + 1 > self.limit then
self:need(1)
return 0
end
self.pos = p + 1
return readu8(self.buf, p)
end
function Reader.i8(self: Reader): number
local p = self.pos
if p + 1 > self.limit then
self:need(1)
return 0
end
self.pos = p + 1
return readi8(self.buf, p)
end
function Reader.u16le(self: Reader): number
local p = self.pos
if p + 2 > self.limit then
self:need(2)
return 0
end
self.pos = p + 2
return readu16(self.buf, p)
end
function Reader.u16be(self: Reader): number
local p = self.pos
if p + 2 > self.limit then
self:need(2)
return 0
end
self.pos = p + 2
return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1)
end
function Reader.i16le(self: Reader): number
local p = self.pos
if p + 2 > self.limit then
self:need(2)
return 0
end
self.pos = p + 2
return readi16(self.buf, p)
end
function Reader.i16be(self: Reader): number
local v = self:u16be()
return if v >= 32768 then v - 65536 else v
end
function Reader.u24le(self: Reader): number
local p = self.pos
if p + 3 > self.limit then
self:need(3)
return 0
end
self.pos = p + 3
return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536
end
function Reader.u24be(self: Reader): number
local p = self.pos
if p + 3 > self.limit then
self:need(3)
return 0
end
self.pos = p + 3
return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2)
end
function Reader.u32le(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return readu32(self.buf, p)
end
function Reader.u32be(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return byteswap(readu32(self.buf, p))
end
function Reader.i32le(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return readi32(self.buf, p)
end
function Reader.i32be(self: Reader): number
local v = self:u32be()
return if v >= 2147483648 then v - TWO32 else v
end
-- 64-bit integers as doubles (exact below 2^53)
function Reader.u64le(self: Reader): number
local lo = self:u32le()
return lo + self:u32le() * TWO32
end
function Reader.u64be(self: Reader): number
local hi = self:u32be()
return hi * TWO32 + self:u32be()
end
function Reader.i64le(self: Reader): number
local lo = self:u32le()
return lo + self:i32le() * TWO32
end
function Reader.i64be(self: Reader): number
local hi = self:i32be()
return hi * TWO32 + self:u32be()
end
-- floats
local function half(h: number): number
local s = if h >= 32768 then -1 else 1
local e = bit32.band(bit32.rshift(h, 10), 31)
local m = bit32.band(h, 1023)
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
Bytes.half = half
function Reader.f16le(self: Reader): number
return half(self:u16le())
end
function Reader.f16be(self: Reader): number
return half(self:u16be())
end
function Reader.f32le(self: Reader): number
local p = self.pos
if p + 4 > self.limit then
self:need(4)
return 0
end
self.pos = p + 4
return readf32(self.buf, p)
end
function Reader.f32be(self: Reader): number
local v = self:u32be()
writeu32(scratch, 0, v)
return readf32(scratch, 0)
end
function Reader.f64le(self: Reader): number
local p = self.pos
if p + 8 > self.limit then
self:need(8)
return 0
end
self.pos = p + 8
return readf64(self.buf, p)
end
function Reader.f64be(self: Reader): number
local hi = self:u32be()
local lo = self:u32be()
writeu32(scratch, 0, lo)
writeu32(scratch, 4, hi)
return readf64(scratch, 0)
end
-- strings
function Reader.string(self: Reader, n: number): string
local p = self.pos
if n < 0 or p + n > self.limit then
self:need(n)
return ""
end
self.pos = p + n
return readstring(self.buf, p, n)
end
-- fixed(n): an n-byte field, cut at the first NUL
function Reader.fixed(self: Reader, n: number): string
local s = self:string(n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
-- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED
function Reader.cstring(self: Reader, max: number?): string
local p = self.pos
local e = if max then math.min(self.limit, p + max) else self.limit
local q = p
local buf = self.buf
while q < e and readu8(buf, q) ~= 0 do
q += 1
end
if q >= e then
self.pos = e
self:need(1)
return readstring(buf, p, e - p)
end
self.pos = q + 1
return readstring(buf, p, q - p)
end
-- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error
function Reader.match(self: Reader, s: string): boolean
local p, n = self.pos, #s
if p + n > self.limit or readstring(self.buf, p, n) ~= s then
return false
end
self.pos = p + n
return true
end
-- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error
function Reader.peek(self: Reader, n: number, at: number?): string
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
return ""
end
return readstring(self.buf, p, math.min(n, self.limit - p))
end
-- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end
function Reader.peekU8(self: Reader, at: number?): number
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
return -1
end
return readu8(self.buf, p)
end
-- bytes(n) -> a new buffer with a copy of the next n bytes
function Reader.bytes(self: Reader, n: number): buffer
local p = self.pos
if n < 0 or p + n > self.limit then
self:need(n)
return bcreate(0)
end
local b = bcreate(n)
bcopy(b, 0, self.buf, p, n)
self.pos = p + n
return b
end
-- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is
-- left, and the parent records TRUNCATED.
function Reader.slice(self: Reader, n: number): Reader
local p = self.pos
local l = math.max(0, math.min(n, self.limit - p))
if l < n then
self:need(n)
else
self.pos = p + n
end
return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader)
end
-- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without
-- moving the cursor
function Reader.sub(self: Reader, offset: number, length: number?): Reader
local o = math.clamp(self.base + offset, self.base, self.limit)
local l = math.clamp(length or (self.limit - o), 0, self.limit - o)
return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader)
end
-- ------------------------------------------------------------------------------------------------ Writer
local Writer = {}
Writer.__index = Writer
export type Writer = typeof(setmetatable(
{} :: {
buf: buffer,
pos: number, -- bytes written (the next write offset)
},
Writer
))
-- writer(capacity?) -> Writer
function Bytes.writer(capacity: number?): Writer
return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer)
end
-- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf)
function Writer.reserve(self: Writer, n: number): number
local p = self.pos
local cap = blen(self.buf)
if p + n > cap then
local nb = bcreate(math.max(cap * 2, p + n))
bcopy(nb, 0, self.buf, 0, p)
self.buf = nb
end
return p
end
function Writer.tell(self: Writer): number
return self.pos
end
function Writer.u8(self: Writer, v: number)
local p = self:reserve(1)
writeu8(self.buf, p, v)
self.pos = p + 1
end
function Writer.u16le(self: Writer, v: number)
local p = self:reserve(2)
writeu16(self.buf, p, v)
self.pos = p + 2
end
function Writer.u16be(self: Writer, v: number)
local p = self:reserve(2)
writeu8(self.buf, p, bit32.rshift(v, 8))
writeu8(self.buf, p + 1, v)
self.pos = p + 2
end
function Writer.u24le(self: Writer, v: number)
local p = self:reserve(3)
writeu16(self.buf, p, v)
writeu8(self.buf, p + 2, bit32.rshift(v, 16))
self.pos = p + 3
end
function Writer.u24be(self: Writer, v: number)
local p = self:reserve(3)
writeu8(self.buf, p, bit32.rshift(v, 16))
writeu8(self.buf, p + 1, bit32.rshift(v, 8))
writeu8(self.buf, p + 2, v)
self.pos = p + 3
end
function Writer.u32le(self: Writer, v: number)
local p = self:reserve(4)
writeu32(self.buf, p, v)
self.pos = p + 4
end
function Writer.u32be(self: Writer, v: number)
local p = self:reserve(4)
writeu32(self.buf, p, byteswap(v % TWO32))
self.pos = p + 4
end
Writer.i8 = Writer.u8
Writer.i16le = Writer.u16le
Writer.i16be = Writer.u16be
Writer.i32le = Writer.u32le
Writer.i32be = Writer.u32be
function Writer.u64le(self: Writer, v: number)
self:u32le(v % TWO32)
self:u32le(math.floor(v / TWO32) % TWO32)
end
function Writer.u64be(self: Writer, v: number)
self:u32be(math.floor(v / TWO32) % TWO32)
self:u32be(v % TWO32)
end
Writer.i64le = Writer.u64le
Writer.i64be = Writer.u64be
function Writer.f32le(self: Writer, v: number)
local p = self:reserve(4)
writef32(self.buf, p, v)
self.pos = p + 4
end
function Writer.f32be(self: Writer, v: number)
writef32(scratch, 0, v)
self:u32be(readu32(scratch, 0))
end
function Writer.f64le(self: Writer, v: number)
local p = self:reserve(8)
writef64(self.buf, p, v)
self.pos = p + 8
end
function Writer.f64be(self: Writer, v: number)
writef64(scratch, 0, v)
self:u32be(readu32(scratch, 4))
self:u32be(readu32(scratch, 0))
end
function Writer.string(self: Writer, s: string)
local n = #s
local p = self:reserve(n)
writestring(self.buf, p, s)
self.pos = p + n
end
-- cstring(s): s and a NUL
function Writer.cstring(self: Writer, s: string)
self:string(s)
self:u8(0)
end
-- bytes(b, offset?, length?): copy a buffer range
function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?)
local o = offset or 0
local n = length or (blen(b) - o)
local p = self:reserve(n)
bcopy(self.buf, p, b, o, n)
self.pos = p + n
end
function Writer.fill(self: Writer, v: number, n: number)
local p = self:reserve(n)
bfill(self.buf, p, v, n)
self.pos = p + n
end
-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos
function Writer.setU32le(self: Writer, at: number, v: number)
writeu32(self.buf, at, v)
end
function Writer.setU32be(self: Writer, at: number, v: number)
writeu32(self.buf, at, byteswap(v % TWO32))
end
function Writer.setU16le(self: Writer, at: number, v: number)
writeu16(self.buf, at, v)
end
function Writer.setU8(self: Writer, at: number, v: number)
writeu8(self.buf, at, v)
end
-- finish() -> a buffer of exactly the written bytes (the writer can keep going)
function Writer.finish(self: Writer): buffer
local b = bcreate(self.pos)
bcopy(b, 0, self.buf, 0, self.pos)
return b
end
Bytes.Reader = Reader
Bytes.Writer = Writer
return Bytes
+98
View File
@@ -0,0 +1,98 @@
--!strict
--!native
-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8.
-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author;
-- no third-party code). Never throws: the range is clamped.
--
-- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it)
-- Crc32.string(s, crc?) -> u32
local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift
local readu8, readu32 = buffer.readu8, buffer.readu32
local T0, T1, T2, T3 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0)
local T4, T5, T6, T7 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0)
for n = 0, 255 do
local c = n
for _ = 1, 8 do
if band(c, 1) ~= 0 then
c = bxor(0xEDB88320, rshift(c, 1))
else
c = rshift(c, 1)
end
end
T0[n + 1] = c
end
for n = 0, 255 do
local c = T0[n + 1]
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T1[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T2[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T3[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T4[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T5[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T6[n + 1] = c
c = bxor(T0[band(c, 255) + 1], rshift(c, 8))
T7[n + 1] = c
end
-- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion
-- happens inside), so crc(b, crc(a)) == the CRC of a .. b.
local function crc32(buf: buffer, off: number, len: number, crc: number?): number
local c = bxor(crc or 0, 0xFFFFFFFF)
local i, e = off, off + len
local e8 = e - 8
while i <= e8 do
c = bxor(c, readu32(buf, i))
local d = readu32(buf, i + 4)
c = bxor(
T7[band(c, 255) + 1],
T6[band(rshift(c, 8), 255) + 1],
T5[band(rshift(c, 16), 255) + 1],
T4[rshift(c, 24) + 1],
T3[band(d, 255) + 1],
T2[band(rshift(d, 8), 255) + 1],
T1[band(rshift(d, 16), 255) + 1],
T0[rshift(d, 24) + 1]
)
i += 8
end
local e4 = e - 4
while i <= e4 do
c = bxor(c, readu32(buf, i))
c = bxor(T3[band(c, 255) + 1], T2[band(rshift(c, 8), 255) + 1], T1[band(rshift(c, 16), 255) + 1], T0[rshift(c, 24) + 1])
i += 4
end
while i < e do
c = bxor(T0[band(bxor(c, readu8(buf, i)), 255) + 1], rshift(c, 8))
i += 1
end
return bxor(c, 0xFFFFFFFF)
end
-- clamp (offset, length) to the buffer
local function range(buf: buffer, offset: number?, length: number?): (number, number)
local n = buffer.len(buf)
local o = math.clamp(offset or 0, 0, n)
return o, math.clamp(length or (n - o), 0, n - o)
end
local Crc32 = {}
function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number
local o, l = range(buf, offset, length)
return crc32(buf, o, l, crc)
end
function Crc32.string(s: string, crc: number?): number
return crc32(buffer.fromstring(s), 0, #s, crc)
end
-- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths)
Crc32.raw = crc32
return Crc32
+58
View File
@@ -0,0 +1,58 @@
--!strict
-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data).
-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7".
-- Never throws: --!native modules may require it.
--
-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos)
-- if err.code == Err.UNSUPPORTED then ... end
local Err = {}
-- codes
Err.TRUNCATED = "TRUNCATED" -- the data ends early
Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field)
Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch
Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder
Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name
Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...)
Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option)
Err.IO = "IO" -- reading or writing a file failed, or the host has no file system
export type Err = {
code: string,
message: string,
offset: number?,
format: string?,
}
local Meta = {}
Meta.__tostring = function(e: Err): string
local s = if e.format then e.format .. ": " .. e.code else e.code
if e.offset then
s ..= string.format(" at 0x%x", e.offset)
end
return s .. ": " .. e.message
end
-- new(code, message, offset?) -> Err
function Err.new(code: string, message: string, offset: number?): Err
return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any
end
-- is(v) -> true when v is an Err
function Err.is(v: any): boolean
return type(v) == "table" and getmetatable(v) == Meta
end
-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to
-- tag errors with the format name.
function Err.wrap(e: any, format: string?): Err
if not Err.is(e) then
e = Err.new(Err.CORRUPT, tostring(e))
end
if e.format == nil then
e.format = format
end
return e
end
return table.freeze(Err)
+306
View File
@@ -0,0 +1,306 @@
--!strict
--!native
-- core/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
--
-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream:
-- entry = symbol * 32 + length a code of `length` <= P bits
-- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries)
-- entry = 0 no code (incomplete code set): the stream is corrupt
-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables
-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27.
-- The hot loops (codecs/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a
-- core/Bits reader.
--
-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values.
-- Never throws: bad code sets return -1 / nil.
local Bits = require("@formats/core/Bits")
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local bfill = buffer.fill
local MAXLEN = 16
local Huffman = {}
Huffman.MAXLEN = MAXLEN
-- 8-bit reversal
local REV = table.create(256, 0)
for i = 0, 255 do
local r, v = 0, i
for _ = 1, 8 do
r = r * 2 + v % 2
v = v // 2
end
REV[i + 1] = r
end
-- reverse(code, len) -> the low len bits of code reversed (len <= 16)
local function reverse(code: number, len: number): number
return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len)
end
Huffman.reverse = reverse
-- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen
function Huffman.capacity(nsym: number, P: number, maxLen: number): number
return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0)
end
local count = table.create(MAXLEN + 1, 0)
local nextc = table.create(MAXLEN + 1, 0)
local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number
for i = 1, MAXLEN + 1 do
count[i] = 0
end
for s = 0, n - 1 do
local l = readu8(lens, off + s)
if l > MAXLEN then
return -1
end
count[l + 1] += 1
end
count[1] = 0
local left = 1
local maxLen = 0
for l = 1, MAXLEN do
left = left * 2 - count[l + 1]
if left < 0 then
return -1
end
if count[l + 1] > 0 then
maxLen = l
end
end
local code = 0
for l = 1, MAXLEN do
code = (code + count[l]) * 2
nextc[l] = code
end
local psize = lshift(1, P)
bfill(tab, 0, 0, psize * 4)
local S = if maxLen > P then maxLen - P else 0
local ssize = lshift(1, S)
local nextSub = psize
for s = 0, n - 1 do
local l = readu8(lens, off + s)
if l > 0 then
local c = nextc[l]
nextc[l] = c + 1
local entry = s * 32 + l
if l <= P then
if msb then
-- the code is the top l bits of the P-bit index: fill every completion of the low bits
local first = lshift(c, P - l)
local last = first + lshift(1, P - l) - 1
for i = first, last do
writeu32(tab, i * 4, entry)
end
else
local step = lshift(1, l)
local i = reverse(c, l)
while i < psize do
writeu32(tab, i * 4, entry)
i += step
end
end
else
local pre, rest
if msb then
pre = rshift(c, l - P)
rest = band(c, lshift(1, l - P) - 1)
else
local rev = reverse(c, l)
pre = band(rev, psize - 1)
rest = rshift(rev, P)
end
local e = readu32(tab, pre * 4)
local sub
if e == 0 then
sub = nextSub
nextSub += ssize
bfill(tab, sub * 4, 0, ssize * 4)
writeu32(tab, pre * 4, sub * 32)
else
sub = rshift(e, 5)
end
local k = l - P -- bits of the code in the subtable index
if msb then
local first = lshift(rest, S - k)
for i = first, first + lshift(1, S - k) - 1 do
writeu32(tab, (sub + i) * 4, entry)
end
else
local step = lshift(1, k)
local i = rest
while i < ssize do
writeu32(tab, (sub + i) * 4, entry)
i += step
end
end
end
end
end
return S
end
-- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next
-- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an
-- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries.
function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number
return build(lens, off, n, tab, P, false)
end
-- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first
function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number
return build(lens, off, n, tab, P, true)
end
-- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader)
function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number
local e = readu32(tab, br:peek(P) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return -1
end
local idx = br:peek(P + S)
e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4)
l = band(e, 31)
if l == 0 then
return -1
end
end
br:skip(l)
return rshift(e, 5)
end
-- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader)
function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number
local e = readu32(tab, br:peek(P) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return -1
end
local idx = br:peek(P + S)
e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4)
l = band(e, 31)
if l == 0 then
return -1
end
end
br:skip(l)
return rshift(e, 5)
end
-- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams).
-- lengths: { number } indexed 1..n (symbol + 1), 0 = unused.
function Huffman.codes(lengths: { number }): { number }
local cnt = table.create(MAXLEN + 1, 0)
for _, l in lengths do
if l > 0 then
cnt[l + 1] += 1
end
end
local nxt = table.create(MAXLEN + 1, 0)
local code = 0
for l = 1, MAXLEN do
code = (code + cnt[l]) * 2
nxt[l + 1] = code
end
local out = table.create(#lengths, 0)
for i, l in lengths do
if l > 0 then
out[i] = nxt[l + 1]
nxt[l + 1] += 1
end
end
return out
end
-- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without
-- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1.
function Huffman.lengths(freqs: { number }, maxLen: number): { number }
local n = #freqs
local out = table.create(n, 0)
-- leaves sorted by frequency (ties by symbol, for determinism)
local syms = {}
for i = 1, n do
if freqs[i] > 0 then
table.insert(syms, i)
end
end
if #syms == 0 then
return out
end
if #syms == 1 then
out[syms[1]] = 1
return out
end
table.sort(syms, function(a: number, b: number): boolean
if freqs[a] ~= freqs[b] then
return freqs[a] < freqs[b]
end
return a < b
end)
-- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order)
local m = #syms
local weight = table.create(2 * m, 0)
local parent = table.create(2 * m, 0)
for i = 1, m do
weight[i] = freqs[syms[i]]
end
local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node
local function take(): number
if li <= m and (ni >= nn or weight[li] <= weight[ni]) then
li += 1
return li - 1
end
ni += 1
return ni - 1
end
for _ = 1, m - 1 do
local a = take()
local b = take()
weight[nn] = weight[a] + weight[b]
parent[a] = nn
parent[b] = nn
nn += 1
end
-- depths: the root is nn - 1
local depth = table.create(2 * m, 0)
for i = nn - 2, 1, -1 do
depth[i] = depth[parent[i]] + 1
end
-- count codes per length; limit (JPEG K.3: move pairs from the deepest level up)
local bl = table.create(m + maxLen + 2, 0)
local deepest = 0
for i = 1, m do
bl[depth[i]] += 1
deepest = math.max(deepest, depth[i])
end
for l = deepest, maxLen + 1, -1 do
while bl[l] > 0 do
local j = l - 2
while j > 0 and bl[j] == 0 do
j -= 1
end
bl[l] -= 2
bl[l - 1] += 1
bl[j + 1] += 2
bl[j] -= 1
end
end
-- the longest codes go to the least frequent symbols (syms is sorted ascending)
local k = 1
for l = math.min(deepest, maxLen), 1, -1 do
for _ = 1, bl[l] do
out[syms[k]] = l
k += 1
end
end
return out
end
return Huffman
+62
View File
@@ -0,0 +1,62 @@
--!strict
-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files
-- through the host adapter the API passes in (core never requires host itself).
--
-- local buf, err, name = Input.resolve(src, opts, host)
--
-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path
-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that).
-- name: the path (for the extension fallback) or opts.name. Never throws.
local Err = require("@formats/core/Err")
local Input = {}
export type HostLike = {
hasFiles: boolean,
readFile: (path: string) -> (buffer?, Err.Err?),
exists: (path: string) -> boolean,
}
-- looksLikePath(s) -> true for short strings without NUL / newline bytes
function Input.looksLikePath(s: string): boolean
return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]")
end
-- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err
function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?)
local o = opts or {}
local t = type(src)
if t == "buffer" then
return src, nil, o.name
elseif t == "string" then
local isPath = false
if o.path == true then
isPath = true
elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then
isPath = host.exists(src)
end
if isPath then
if not host then
return nil, Err.new(Err.IO, "no host to read " .. src), nil
end
local b, err = host.readFile(src)
if not b then
return nil, err, nil
end
return b, nil, src
end
return buffer.fromstring(src), nil, o.name
end
return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil
end
-- extension(name) -> the lower-case extension without the dot ("png"), or nil
function Input.extension(name: string?): string?
if not name then
return nil
end
local ext = string.match(name, "%.([%w_]+)$")
return if ext then string.lower(ext) else nil
end
return Input
+149
View File
@@ -0,0 +1,149 @@
--!strict
-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for
-- paths outside them; converts the standard types to LÖVE objects:
-- host.toImageData(img) -> love ImageData (rgba8)
-- host.fromImageData(imageData) -> Image (rgba8)
-- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit)
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Host = {}
Host.name = "love"
Host.hasFiles = true
local function love(): any
return (_G :: any).love
end
local function io(): any
return (_G :: any).io
end
-- the FFI, when the build runs on LuaJIT (always, under LÖVE); called through _G so the build leaves it alone
local function ffi(): any
local req = (_G :: any).require
local ok, m = pcall(req, "ffi")
return if ok then m else nil
end
function Host.readFile(path: string): (buffer?, Err.Err?)
local fs = love().filesystem
if fs.getInfo(path, "file") then
local s, msg = fs.read(path)
if type(s) ~= "string" then
return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg))
end
return buffer.fromstring(s)
end
local f, msg = io().open(path, "rb")
if not f then
return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg))
end
local s = f:read("*a")
f:close()
return buffer.fromstring(s)
end
-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io
function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
local s = buffer.tostring(data)
if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then
local ok, msg = love().filesystem.write(path, s)
if not ok then
return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg))
end
return true
end
local f, msg = io().open(path, "wb")
if not f then
return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg))
end
f:write(s)
f:close()
return true
end
function Host.exists(path: string): boolean
if love().filesystem.getInfo(path, "file") then
return true
end
local f = io().open(path, "rb")
if f then
f:close()
return true
end
return false
end
-- toImageData(img) -> ImageData | nil, Err
function Host.toImageData(img: any): (any, Err.Err?)
if img.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format))
end
local n = img.width * img.height * 4
local F = ffi()
local B = buffer :: any
if F and B.toffi then
local id = love().image.newImageData(img.width, img.height, "rgba8")
F.copy(id:getFFIPointer(), B.toffi(img.pixels), n)
return id
end
local bytes = love().data.newByteData(buffer.readstring(img.pixels, 0, n))
return love().image.newImageData(img.width, img.height, "rgba8", bytes)
end
-- fromImageData(imageData) -> Image (rgba8 copy)
function Host.fromImageData(id: any): Types.Image
local w, h = id:getDimensions()
local img = Types.Image.new(w, h, "rgba8")
local F = ffi()
local B = buffer :: any
if F and B.toffi and id:getFormat() == "rgba8" then
F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4)
return img
end
local s = id:getString()
buffer.writestring(img.pixels, 0, s, math.min(#s, w * h * 4))
return img
end
-- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end).
function Host.toSoundData(a: any): (any, Err.Err?)
local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate
if samples == nil then
-- a Decoder: read everything
local parts, total = {}, 0
while true do
local out, n = a:read(65536)
if n == 0 then
break
end
local copy = buffer.create(n * channels * 4)
buffer.copy(copy, 0, out, 0, n * channels * 4)
table.insert(parts, copy)
total += n
end
samples = buffer.create(total * channels * 4)
local o = 0
for _, p in parts do
buffer.copy(samples, o, p)
o += buffer.len(p)
end
frames = total
end
local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels)
local count = frames * channels
local F = ffi()
if F then
local p = F.cast("int16_t*", sd:getFFIPointer())
for i = 0, count - 1 do
local v = math.clamp(buffer.readf32(samples, i * 4), -1, 1)
p[i] = math.floor(v * 32767 + 0.5)
end
else
for i = 0, count - 1 do
sd:setSample(i, math.clamp(buffer.readf32(samples, i * 4), -1, 1))
end
end
return sd
end
return Host
+48
View File
@@ -0,0 +1,48 @@
--!strict
-- host/LuaJIT: plain LuaJIT (or any Lua with io): files through io.open.
local Err = require("@formats/core/Err")
local Host = {}
Host.name = "luajit"
Host.hasFiles = true
local function io(): any
return (_G :: any).io
end
function Host.readFile(path: string): (buffer?, Err.Err?)
local f, msg = io().open(path, "rb")
if not f then
return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg))
end
local s = f:read("*a")
f:close()
if type(s) ~= "string" then
return nil, Err.new(Err.IO, "cannot read " .. path)
end
return buffer.fromstring(s), nil
end
function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?)
local f, msg = io().open(path, "wb")
if not f then
return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg))
end
local ok, werr = f:write(buffer.tostring(data))
f:close()
if not ok then
return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(werr))
end
return true, nil
end
function Host.exists(path: string): boolean
local f = io().open(path, "rb")
if f then
f:close()
return true
end
return false
end
return Host
+21
View File
@@ -0,0 +1,21 @@
--!strict
-- host/Luau: the Luau CLI (and any embedding without io): no file system. Sources are buffers or strings.
local Err = require("@formats/core/Err")
local Host = {}
Host.name = "luau"
Host.hasFiles = false
function Host.readFile(path: string): (buffer?, Err.Err?)
return nil, Err.new(Err.IO, "no file system on this host (luau): pass a buffer or a string, not the path " .. path)
end
function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?)
return false, Err.new(Err.IO, "no file system on this host (luau): cannot write " .. path)
end
function Host.exists(_path: string): boolean
return false
end
return Host
+40
View File
@@ -0,0 +1,40 @@
--!strict
-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the
-- standard types to engine objects:
-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first)
local Err = require("@formats/core/Err")
local Host = {}
Host.name = "roblox"
Host.hasFiles = false
function Host.readFile(path: string): (buffer?, Err.Err?)
return nil, Err.new(Err.IO, "Roblox has no file system: pass a buffer or a string, not the path " .. path)
end
function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?)
return false, Err.new(Err.IO, "Roblox has no file system: cannot write " .. path .. " (use F.save(value) for a buffer)")
end
function Host.exists(_path: string): boolean
return false
end
-- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8".
function Host.toEditableImage(img: any): (any, Err.Err?)
if img.format ~= "rgba8" then
return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format))
end
local AssetService = (game :: any):GetService("AssetService")
local size = Vector2.new(img.width, img.height)
local ok, ei = pcall(function()
return AssetService:CreateEditableImage({ Size = size })
end)
if not ok or not ei then
return nil, Err.new(Err.IO, "CreateEditableImage failed: " .. tostring(ei))
end
ei:WritePixelsBuffer(Vector2.zero, size, img.pixels)
return ei
end
return Host
+43
View File
@@ -0,0 +1,43 @@
--!strict
-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE
-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system).
--
-- local host = require("@formats/host")
-- print(host.name) -- "roblox" | "love" | "luajit" | "luau"
-- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO
-- -- where there is no file system)
local Err = require("@formats/core/Err")
export type Host = {
name: string,
hasFiles: boolean,
readFile: (path: string) -> (buffer?, Err.Err?),
writeFile: (path: string, data: buffer) -> (boolean, Err.Err?),
exists: (path: string) -> boolean,
[string]: any,
}
local G = _G :: any
local name
if typeof(game) == "Instance" then
name = "roblox"
elseif G.love ~= nil and type(G.love) == "table" and G.love.filesystem ~= nil then
name = "love"
elseif G.jit ~= nil or G.io ~= nil then
name = "luajit"
else
name = "luau"
end
local host: Host
if name == "roblox" then
host = require("@formats/host/Roblox")
elseif name == "love" then
host = require("@formats/host/Love")
elseif name == "luajit" then
host = require("@formats/host/LuaJIT")
else
host = require("@formats/host/Luau")
end
local _ = Err
return host
+253
View File
@@ -0,0 +1,253 @@
--!strict
--!native
--!optimize 2
-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the
-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes.
-- Absorbed from png-luau src/Png/Decode.luau (same author).
--
-- The caller (init) has validated the header and checked that the data holds at least the expected number of
-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws.
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcopy = buffer.copy
local Decode = {}
-- Adam7: x0, y0, dx, dy per pass
local PASSES = {
{ 0, 0, 8, 8 },
{ 4, 0, 8, 8 },
{ 0, 4, 4, 8 },
{ 2, 0, 4, 4 },
{ 0, 2, 2, 4 },
{ 1, 0, 2, 2 },
{ 0, 1, 1, 2 },
}
Decode.PASSES = PASSES
local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 }
Decode.CHANNELS = CHANNELS
-- bytes per row (without the filter byte) for a pass width
function Decode.rowBytes(pw: number, channels: number, depth: number): number
return (pw * channels * depth + 7) // 8
end
-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per
-- complete pixel (at least 1). Returns true, or false + the bad filter type.
local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number)
local stride = rb + 1
for r = 0, ph - 1 do
local f = readu8(raw, p)
local cur = p + 1
if f == 0 then
-- none
elseif f == 1 then
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
end
elseif f == 2 then
if r > 0 then
local i = cur
local e4 = cur + rb - 4
while i <= e4 do
-- four bytes at once: add without carries between the byte lanes
local x, y = readu32(raw, i), readu32(raw, i - stride)
local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F)
writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080)))
i += 4
end
while i < cur + rb do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride))
i += 1
end
end
elseif f == 3 then
if r > 0 then
for i = cur, cur + bpp - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1))
end
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1))
end
else
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1))
end
end
elseif f == 4 then
if r > 0 then
-- the first pixel: a = c = 0, so Paeth picks b
for i = cur, cur + bpp - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride))
end
for i = cur + bpp, cur + rb - 1 do
local a = readu8(raw, i - bpp)
local b = readu8(raw, i - stride)
local c = readu8(raw, i - stride - bpp)
local pa = math.abs(b - c)
local pb = math.abs(a - c)
local pc = math.abs(a + b - c - c)
local v
if pa <= pb and pa <= pc then
v = a
elseif pb <= pc then
v = b
else
v = c
end
writeu8(raw, i, readu8(raw, i) + v)
end
else
-- no previous row: Paeth is sub
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
end
end
else
return false, f
end
p += stride
end
return true, 0
end
-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes.
-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none),
-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth.
local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number)
if ct == 6 then
if depth == 8 then
if ostep == 4 then
bcopy(out, oo, raw, ro, pw * 4)
else
for x = 0, pw - 1 do
writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4))
end
end
else
for x = 0, pw - 1 do
local s = ro + x * 8
local o = oo + x * ostep
writeu8(out, o, readu8(raw, s))
writeu8(out, o + 1, readu8(raw, s + 2))
writeu8(out, o + 2, readu8(raw, s + 4))
writeu8(out, o + 3, readu8(raw, s + 6))
end
end
elseif ct == 2 then
if depth == 8 then
for x = 0, pw - 1 do
local s = ro + x * 3
local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2)
local a = 255
if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then
a = 0
end
writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216)
end
else
for x = 0, pw - 1 do
local s = ro + x * 6
local r = readu8(raw, s) * 256 + readu8(raw, s + 1)
local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3)
local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5)
local a = 255
if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then
a = 0
end
writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216)
end
end
elseif ct == 3 then
if depth == 8 then
for x = 0, pw - 1 do
writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4))
end
else
local per = 8 // depth
local mask = lshift(1, depth) - 1
for x = 0, pw - 1 do
local byte = readu8(raw, ro + x // per)
local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask)
writeu32(out, oo + x * ostep, readu32(pal, idx * 4))
end
end
elseif ct == 0 then
if depth == 8 then
for x = 0, pw - 1 do
local v = readu8(raw, ro + x)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
elseif depth == 16 then
for x = 0, pw - 1 do
local hi = readu8(raw, ro + x * 2)
local v = hi * 256 + readu8(raw, ro + x * 2 + 1)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216)
end
else
local per = 8 // depth
local mask = lshift(1, depth) - 1
local scale = 255 // mask
for x = 0, pw - 1 do
local byte = readu8(raw, ro + x // per)
local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask)
local a = if v == tr then 0 else 255
writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216)
end
end
else -- ct == 4: grey + alpha
if depth == 8 then
for x = 0, pw - 1 do
local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1)
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
else
for x = 0, pw - 1 do
local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2)
writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216)
end
end
end
end
-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8).
-- Returns true, or false + message.
function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?)
local channels = CHANNELS[ct]
local bpp = math.max(1, (channels * depth) // 8)
local p = 0
if interlace == 0 then
local rb = Decode.rowBytes(w, channels, depth)
local ok, f = unfilter(raw, 0, h, rb, bpp)
if not ok then
return false, "bad filter type " .. f
end
for y = 0, h - 1 do
convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr)
end
return true, nil
end
for _, pass in PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if h > y0 then (h - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
local rb = Decode.rowBytes(pw, channels, depth)
local ok, f = unfilter(raw, p, ph, rb, bpp)
if not ok then
return false, "bad filter type " .. f
end
for r = 0, ph - 1 do
local y = y0 + r * dy
convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr)
end
p += ph * (rb + 1)
end
end
return true, nil
end
return Decode
+162
View File
@@ -0,0 +1,162 @@
--!strict
--!native
--!optimize 2
-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and
-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute
-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image.
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local bcreate, bcopy = buffer.create, buffer.copy
local Encode = {}
local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 }
-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray"
function Encode.pickColorType(px: buffer, w: number, h: number): string
local opaque, gray = true, true
for i = 0, w * h - 1 do
local o = i * 4
local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3)
if a ~= 255 then
opaque = false
end
if r ~= g or g ~= b then
gray = false
end
if not opaque and not gray then
return "rgba"
end
end
if gray then
return if opaque then "gray" else "graya"
end
return "rgb"
end
-- convert rgba8 to the colour type's packed rows (no filter bytes)
local function pack(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
if ch == 4 then
return px
end
local out = bcreate(w * h * ch)
local n = w * h
if ct == 2 then
for i = 0, n - 1 do
bcopy(out, i * 3, px, i * 4, 3)
end
elseif ct == 0 then
for i = 0, n - 1 do
writeu8(out, i, readu8(px, i * 4))
end
else -- graya
for i = 0, n - 1 do
writeu8(out, i * 2, readu8(px, i * 4))
writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3))
end
end
return out
end
local function paeth(a: number, b: number, c: number): number
local pa = math.abs(b - c)
local pb = math.abs(a - c)
local pc = math.abs(a + b - c - c)
if pa <= pb and pa <= pc then
return a
elseif pb <= pc then
return b
end
return c
end
-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first);
-- the arithmetic is inlined: this runs for every byte
local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number)
local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0
local p = s - rb
for i = 0, rb - 1 do
local x = readu8(src, s + i)
local a = if i >= bpp then readu8(src, s + i - bpp) else 0
local b, c = 0, 0
if not first then
b = readu8(src, p + i)
if i >= bpp then
c = readu8(src, p + i - bpp)
end
end
local d = if x < 128 then x else 256 - x
c0 += d
d = (x - a) % 256
c1 += if d < 128 then d else 256 - d
d = (x - b) % 256
c2 += if d < 128 then d else 256 - d
d = (x - (a + b) // 2) % 256
c3 += if d < 128 then d else 256 - d
local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c)
local pr = if pa <= pb and pa <= pc then a elseif pb <= pc then b else c
d = (x - pr) % 256
c4 += if d < 128 then d else 256 - d
end
return c0, c1, c2, c3, c4
end
-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f)
local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number)
writeu8(out, o, f)
o += 1
if f == 0 or (f == 2 and first) then
bcopy(out, o, src, s, rb)
return
end
local p = s - rb
for i = 0, rb - 1 do
local x = readu8(src, s + i)
local a = if i >= bpp then readu8(src, s + i - bpp) else 0
local pred
if f == 1 then
pred = a
elseif f == 2 then
pred = readu8(src, p + i)
elseif f == 3 then
pred = (a + (if first then 0 else readu8(src, p + i))) // 2
elseif first then
pred = a
else
local c = if i >= bpp then readu8(src, p + i - bpp) else 0
pred = paeth(a, readu8(src, p + i), c)
end
writeu8(out, o + i, x - pred)
end
end
-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of
-- |signed residuals| (the libpng heuristic)
function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
local src = pack(px, w, h, ct)
local rb = w * ch
local out = bcreate(h * (rb + 1))
for y = 0, h - 1 do
local s = y * rb
local first = y == 0
local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first)
local best, bc = 0, c0
if c1 < bc then
best, bc = 1, c1
end
if c2 < bc then
best, bc = 2, c2
end
if c3 < bc then
best, bc = 3, c3
end
if c4 < bc then
best = 4
end
apply(src, s, rb, ch, first, best, out, y * (rb + 1))
end
return out
end
return Encode
+306
View File
@@ -0,0 +1,306 @@
--!strict
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder.
-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16),
-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha
-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte).
-- Not supported: APNG animation (the default image is decoded), colour management (gAMA / cHRM / sRGB / iCCP are
-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/Deflate")
local Types = require("@formats/Types")
local Decode = require("@formats/image/png/Decode")
local Encode = require("@formats/image/png/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Png = {
name = "png",
category = "image",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
caps = { decode = true, encode = true, animation = false, alpha = true, depths = { 1, 2, 4, 8, 16 } },
}
export type DecodeOptions = {
checkCrc: boolean?, -- verify every chunk's CRC-32 (default false)
maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer)
}
export type EncodeOptions = {
level: number?, -- deflate level 0..9 (default 6)
colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one
}
-- ------------------------------------------------------------------------------------------------ constants
local SIGNATURE = "\137PNG\r\n\26\n"
local VALID = {
[0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true },
[2] = { [8] = true, [16] = true },
[3] = { [1] = true, [2] = true, [4] = true, [8] = true },
[4] = { [8] = true, [16] = true },
[6] = { [8] = true, [16] = true },
}
local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" }
local readu8, readu32 = buffer.readu8, buffer.readu32
local function be32(b: buffer, o: number): number
return bit32.byteswap(readu32(b, o))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Png.sniff(r: Bytes.Reader): number
return if r:peek(8) == SIGNATURE then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number }
-- the IHDR at r's start: Header | nil, Err
local function header(r: Bytes.Reader): (Header?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then
return nil, Err.new(Err.CORRUPT, "bad signature", o)
end
if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then
return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8)
end
local h = {
width = be32(b, o + 16),
height = be32(b, o + 20),
bitDepth = readu8(b, o + 24),
colorType = readu8(b, o + 25),
interlace = readu8(b, o + 28),
}
if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then
return nil, Err.new(Err.CORRUPT, "bad image size", o + 16)
end
local depths = VALID[h.colorType]
if not depths then
return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25)
end
if not depths[h.bitDepth] then
return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24)
end
if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then
return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26)
end
return h, nil
end
-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header)
function Png.info(r: Bytes.Reader): (Header?, Err.Err?)
return header(r)
end
function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local checkCrc = opts and opts.checkCrc or false
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local h, herr = header(r)
if not h then
return nil, herr
end
local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType
if w * ht > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
end
local b, n = r.buf, r.limit
-- chunks
local pal = buffer.create(1024)
for i = 0, 255 do
buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black
end
local palCount = 0
local tr = -1
local idat: { { number } } = {}
local idatLen = 0
local text: { [string]: string } = {}
local iccCompressed: buffer? = nil
local p = r.base + 8
local first = true
while p + 12 <= n do
local len = be32(b, p)
local typ = buffer.readstring(b, p + 4, 4)
if len > n - p - 12 then
return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p)
end
local d = p + 8
if checkCrc then
local want = be32(b, d + len)
if Crc32.raw(b, p + 4, len + 4) ~= want then
return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len)
end
end
if first and typ ~= "IHDR" then
return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p)
end
first = false
if typ == "PLTE" then
if len % 3 ~= 0 or len > 768 or len == 0 then
return nil, Err.new(Err.CORRUPT, "bad PLTE length", p)
end
palCount = len // 3
for i = 0, palCount - 1 do
local q = d + i * 3
buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000)
end
elseif typ == "tRNS" then
if ct == 3 then
for i = 0, math.min(len, 256) - 1 do
buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i))
end
elseif ct == 0 and len >= 2 then
tr = readu8(b, d) * 256 + readu8(b, d + 1)
elseif ct == 2 and len >= 6 then
local function u16(q: number): number
return readu8(b, d + q) * 256 + readu8(b, d + q + 1)
end
tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4)
end
elseif typ == "IDAT" then
table.insert(idat, { d, len })
idatLen += len
elseif typ == "tEXt" then
local s = buffer.readstring(b, d, len)
local z = string.find(s, "\0", 1, true)
if z then
text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1)
end
elseif typ == "iCCP" then
local cb = buffer.create(len)
buffer.copy(cb, 0, b, d, len)
iccCompressed = cb
elseif typ == "IEND" then
break -- a missing IEND is tolerated (truncated tail after the data)
elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then
return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p)
end
p = d + len + 4
end
if #idat == 0 then
return nil, Err.new(Err.TRUNCATED, "no image data", p)
end
if ct == 3 and palCount == 0 then
return nil, Err.new(Err.CORRUPT, "palette image without PLTE")
end
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
local expected = 0
if h.interlace == 0 then
expected = ht * (Decode.rowBytes(w, channels, depth) + 1)
else
for _, pass in Decode.PASSES do
local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4]
local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0
local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0
if pw > 0 and ph > 0 then
expected += ph * (Decode.rowBytes(pw, channels, depth) + 1)
end
end
end
local z: buffer
if #idat == 1 then
z = b
else
z = buffer.create(idatLen)
local w0 = 0
for _, c in idat do
buffer.copy(z, w0, b, c[1], c[2])
w0 += c[2]
end
end
local zo, zl = if #idat == 1 then idat[1][1] else 0, idatLen
local raw, zerr = Deflate.zlib(z, zo, zl, expected)
if not raw then
-- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows
local loose = Deflate.zlib(z, zo, zl)
if not loose or buffer.len(loose) < expected then
return nil, zerr
end
raw = loose
end
local img = Types.Image.new(w, ht, "rgba8")
local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, h.interlace, pal, tr, img.pixels)
if not ok then
return nil, Err.new(Err.CORRUPT, tostring(derr))
end
if ct == 3 then
local palette: { { number } } = {}
for i = 0, palCount - 1 do
palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
end
img.meta.palette = palette
end
if next(text) then
img.meta.text = text
end
img.meta.iccCompressed = iccCompressed
img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace }
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 }
function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "png encode: needs an rgba8 Image")
end
local w, h = img.width, img.height
if w < 1 or h < 1 or buffer.len(img.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "png encode: bad image size or pixel buffer")
end
local level = opts and opts.level or 6
if type(level) ~= "number" or level < 0 or level > 9 then
return nil, Err.new(Err.ARG, "png encode: level must be 0..9")
end
local want = opts and opts.colorType or "auto"
local ctName: string = want
if want == "auto" then
ctName = Encode.pickColorType(img.pixels, w, h)
end
local ct = CT_CODES[ctName]
if ct == nil then
return nil, Err.new(Err.ARG, "png encode: unknown colorType " .. tostring(want))
end
local raw = Encode.filter(img.pixels, w, h, ct)
local z = Deflate.zlibCompress(raw, { level = level }) :: buffer
local out = Bytes.writer(buffer.len(z) + 128)
local function chunk(typ: string, data: buffer?)
local len = if data then buffer.len(data) else 0
out:u32be(len)
local start = out:tell()
out:string(typ)
if data then
out:bytes(data)
end
out:u32be(Crc32.raw(out.buf, start, len + 4))
end
out:string(SIGNATURE)
local ihdr = Bytes.writer(13)
ihdr:u32be(w)
ihdr:u32be(h)
ihdr:u8(8)
ihdr:u8(ct)
ihdr:u8(0)
ihdr:u8(0)
ihdr:u8(0)
chunk("IHDR", ihdr:finish())
if img.meta and img.meta.text then
for k, v in img.meta.text do
local t = Bytes.writer()
t:string(k)
t:u8(0)
t:string(v)
chunk("tEXt", t:finish())
end
end
chunk("IDAT", z)
chunk("IEND", nil)
return out:finish(), nil
end
return Png
+378
View File
@@ -0,0 +1,378 @@
--!strict
-- Formats: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py).
-- Every format of a category maps onto one standard type (src/Formats/Types.luau): a PNG and a WebP both load as an
-- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension.
--
-- local F = require(Formats) -- Roblox: the ModuleScript; LuaJIT: require("formats"); luau: "@formats"
-- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err
-- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...)
-- local dec = F.audio.open(src) -- streaming decoders (audio / video)
-- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format
-- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files
-- local s = F.saveString(img, { format = "png" })
-- local buf = F.convert(src, "png", opts?) -- load + save
-- F.formats() -- the capability list (also docs/FORMATS.md)
--
-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Input = require("@formats/core/Input")
local Types = require("@formats/Types")
local Registry = require("@formats/Registry")
local host = require("@formats/host")
local F = {}
F.version = "0.1.0"
F.Err = Err
F.Types = Types
F.Bytes = Bytes
F.null = Types.null
F.host = host
F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step)
-- value.kind -> category
local KIND_CATEGORY: { [string]: string } = {
image = "image",
audio = "audio",
scene = "model",
cad = "cad",
font = "font",
archive = "archive",
vector = "vector",
tilemap = "vector",
layered = "layered",
subtitles = "subtitle",
music = "music",
midi = "music",
playlist = "playlist",
}
-- ------------------------------------------------------------------------------------------------ registry access
local loaded: { [string]: any } = {}
local function module(entry: Registry.Entry): (any, Err.Err?)
local m = loaded[entry.path]
if m then
return m
end
local ok, res = pcall(entry.load)
if not ok then
return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res))
end
loaded[entry.path] = res
return res
end
local function inCategory(entry: Registry.Entry, category: string?): boolean
return category == nil or entry.category == category
end
-- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches
local function find(key: string, category: string?): Registry.Entry?
local k = string.lower(key)
for _, e in Registry do
if e.name == k and inCategory(e, category) then
return e
end
end
for _, e in Registry do
if inCategory(e, category) and table.find(e.extensions, k) then
return e
end
end
return nil
end
-- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension
local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?)
if format then
local e = find(format, category)
if not e then
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else ""))
end
return e
end
local ext = Input.extension(name)
local best: Registry.Entry? = nil
local bestScore = 0
for _, e in Registry do
if inCategory(e, category) and (e.caps.decode or e.caps.open) then
local m = module(e)
if m and m.sniff then
local ok, score = pcall(m.sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if ext and table.find(e.extensions, ext) then
score += 0.01 -- ties go to the extension
end
if score > bestScore then
best, bestScore = e, score
end
end
end
end
end
if best then
return best
end
if ext then
local e = find(ext, category)
if e then
return e
end
end
return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else ""))
end
local function tag(value: any, formatName: string)
if type(value) == "table" then
local meta = value.meta
if type(meta) == "table" then
if meta.source == nil then
meta.source = { format = formatName }
elseif type(meta.source) == "table" and meta.source.format == nil then
meta.source.format = formatName
end
end
end
end
-- full decode through a streaming decoder (audio formats with open but no decode)
local function drain(dec: any): any
local channels = dec.channels
local parts, total = {}, 0
while true do
local out, n = dec:read(65536)
if not out or n == 0 then
break
end
local copy = buffer.create(n * channels * 4)
buffer.copy(copy, 0, out, 0, n * channels * 4)
table.insert(parts, copy)
total += n
end
local a = Types.Audio.new(dec.sampleRate, channels, total)
local o = 0
for _, p in parts do
buffer.copy(a.samples, o, p)
o += buffer.len(p)
end
a.tags = dec.tags or {}
return a
end
-- ------------------------------------------------------------------------------------------------ API
export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options
-- load(src, opts?) -> value | nil, Err
function F.load(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {}
local buf, ierr, name = Input.resolve(src, o, host)
if not buf then
return nil, ierr
end
local entry, derr = detect(buf, name, o.category, o.format)
if not entry then
return nil, derr
end
local m, merr = module(entry)
if not m then
return nil, merr
end
local value, err
if m.decode then
local ok, v, e = pcall(m.decode, Bytes.reader(buf), o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name)
end
value, err = v, e
elseif m.open then
local ok, dec, e = pcall(m.open, Bytes.reader(buf), o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
end
if dec then
value = drain(dec)
end
err = e
else
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name)
end
if value == nil then
return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name)
end
tag(value, entry.name)
return value
end
-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err
function F.open(src: any, opts: Options?): (any, Err.Err?)
local o = opts or {}
local buf, ierr, name = Input.resolve(src, o, host)
if not buf then
return nil, ierr
end
local entry, derr = detect(buf, name, o.category, o.format)
if not entry then
return nil, derr
end
local m, merr = module(entry)
if not m then
return nil, merr
end
if not m.open then
return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name)
end
local ok, dec, e = pcall(m.open, Bytes.reader(buf), o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name)
end
if dec == nil then
return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name)
end
return dec
end
-- the writable format for a value: opts.format, the destination's extension, or the source format
local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?)
local category = o.category
if category == nil and type(value) == "table" and type(value.kind) == "string" then
category = KIND_CATEGORY[value.kind]
end
local key = o.format or Input.extension(dest)
if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then
key = value.meta.source.format
end
if key == nil then
return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)")
end
local entry = find(key, category)
if not entry then
return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else ""))
end
local m, merr = module(entry)
if not m then
return nil, nil, merr
end
if not m.encode then
local alt = nil
for _, e in Registry do
if e.category == entry.category and e.caps.encode then
alt = e.name
break
end
end
return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name)
end
return entry, m, nil
end
-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err
function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
local o = opts or {}
local entry, m, err = encoderFor(value, dest, o)
if not entry then
return nil, err
end
local ok, buf, e = pcall(m.encode, value, o)
if not ok then
return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name)
end
if buf == nil then
return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name)
end
if dest then
local wok, werr = host.writeFile(dest, buf)
if not wok then
return nil, werr
end
return true
end
return buf
end
-- saveString(value, opts?) -> string | nil, Err
function F.saveString(value: any, opts: Options?): (string?, Err.Err?)
local buf, err = F.save(value, nil, opts)
if not buf then
return nil, err
end
return buffer.tostring(buf)
end
-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save.
function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?)
local o = opts or {}
local value, err = F.load(src, o)
if value == nil then
return nil, err
end
local so = table.clone(o)
so.format = format
so.category = nil
return F.save(value, o.out, so)
end
-- detect(src, opts?) -> format name | nil, Err
function F.detect(src: any, opts: Options?): (string?, Err.Err?)
local o = opts or {}
local buf, ierr, name = Input.resolve(src, o, host)
if not buf then
return nil, ierr
end
local entry, err = detect(buf, name, o.category, o.format)
if not entry then
return nil, err
end
return entry.name
end
export type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } }
-- formats(category?) -> { FormatInfo } (no format module is loaded)
function F.formats(category: string?): { FormatInfo }
local out = {}
for _, e in Registry do
if inCategory(e, category) then
table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps })
end
end
return out
end
-- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info)
function F.format(name: string): (any, Err.Err?)
local e = find(name)
if not e then
return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name)
end
return module(e)
end
-- ------------------------------------------------------------------------------------------------ category facades
-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category
local function with(opts: Options?, category: string): Options
local o = if opts then table.clone(opts) else {}
o.category = category
return o
end
for category in Types.CATEGORIES do
local cat: string = category
F[cat] = {
load = function(src: any, opts: Options?): (any, Err.Err?)
return F.load(src, with(opts, cat))
end,
open = function(src: any, opts: Options?): (any, Err.Err?)
return F.open(src, with(opts, cat))
end,
save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?)
return F.save(value, dest, with(opts, cat))
end,
formats = function(): { FormatInfo }
return F.formats(cat)
end,
}
end
F.data.null = Types.null
return F
+127
View File
@@ -0,0 +1,127 @@
--!strict
-- tests/T: the test helper every tests/**/*.luau uses, under both runtimes (luau --codegen -O2 and LuaJIT through the
-- build). A failed check throws, so the runner (tools/test.sh) sees a non-zero exit.
--
-- local T = require("@tests/T")
-- local t = T.suite("png")
-- t:check(cond, "label") -- truthy
-- t:eq(got, want, "label") -- ==, with both values in the message
-- t:fuzz("decode", function(b) return Png.decode(Bytes.reader(b)) end, samples) -- the no-throw pass
-- t:done() -- prints "png: 123 checks passed (luajit)"
local T = {}
T.runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
-- deterministic LCG (the same numbers on both runtimes): rand(n) -> 0 .. n - 1
function T.rng(seed: number): (n: number) -> number
local s = seed % 2147483648
return function(n: number): number
s = (s * 1103515245 + 12345) % 2147483648
return s % n
end
end
-- bytes({ 1, 2, 3 }) -> buffer
function T.bytes(t: { number }): buffer
local b = buffer.create(#t)
for i, v in t do
buffer.writeu8(b, i - 1, v)
end
return b
end
-- hex(buf, max?) -> "89 50 4e 47 ..."
function T.hex(b: buffer, max: number?): string
local n = math.min(buffer.len(b), max or 64)
local out = table.create(n)
for i = 0, n - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out, " ") .. (if buffer.len(b) > n then " ..." else "")
end
-- clock() -> seconds (os.clock on both runtimes)
function T.clock(): number
return os.clock()
end
local Suite = {}
Suite.__index = Suite
export type Suite = typeof(setmetatable({} :: { name: string, passed: number, t0: number }, Suite))
function T.suite(name: string): Suite
return setmetatable({ name = name, passed = 0, t0 = os.clock() }, Suite)
end
function Suite.check(self: Suite, cond: any, label: string)
if not cond then
error(string.format("FAILED [%s, %s]: %s", self.name, T.runtime, label), 2)
end
self.passed += 1
end
function Suite.eq(self: Suite, got: any, want: any, label: string)
if got ~= want then
error(string.format("FAILED [%s, %s]: %s: got %s, want %s", self.name, T.runtime, label, tostring(got), tostring(want)), 2)
end
self.passed += 1
end
-- note(fmt, ...): an indented progress line
function Suite.note(_self: Suite, fmt: string, ...: any)
print(" " .. string.format(fmt, ...))
end
-- fuzz(label, decode, samples, opts?): the no-throw pass every format test runs. For each sample (buffer or string):
-- truncations at several cuts, opts.mutations (default 8) copies with 1..4 random bytes changed, plus
-- opts.garbage (default 200) random buffers. decode(buf) may return anything except throw. Returns the counts.
function Suite.fuzz(self: Suite, label: string, decode: (buffer) -> any, samples: { any }, opts: { mutations: number?, garbage: number?, seed: number?, keepHeader: number? }?): (number, number)
local o: { mutations: number?, garbage: number?, seed: number?, keepHeader: number? } = opts or {}
local rand = T.rng(o.seed or 1234)
local tries, threw = 0, 0
local function try(b: buffer, what: string)
tries += 1
local ok, err = pcall(decode, b)
if not ok then
threw += 1
print(string.format(" THREW on %s (%s): %s", what, label, tostring(err)))
end
end
local keep = o.keepHeader or 0
for _, s in samples do
local str = if type(s) == "string" then s else buffer.tostring(s)
local n = #str
for _, cut in { 1, 2, 4, 8, 16, 33, n // 3, n // 2, n - 13, n - 4, n - 1 } do
if cut > 0 and cut < n then
try(buffer.fromstring(string.sub(str, 1, cut)), "truncation")
end
end
if n > keep then
for _ = 1, o.mutations or 8 do
local b = buffer.fromstring(str)
for _ = 1, 1 + rand(4) do
buffer.writeu8(b, keep + rand(n - keep), rand(256))
end
try(b, "mutation")
end
end
end
for _ = 1, o.garbage or 200 do
local n = rand(300)
local b = buffer.create(n)
for k = 0, n - 1 do
buffer.writeu8(b, k, rand(256))
end
try(b, "garbage")
end
self:check(threw == 0, label .. ": bad input never throws (" .. threw .. " of " .. tries .. " threw)")
self:note("%s: %d bad inputs, none threw", label, tries)
return tries, threw
end
function Suite.done(self: Suite)
print(string.format("%s: %d checks passed (%s, %.2f s)", self.name, self.passed, T.runtime, os.clock() - self.t0))
end
return T
+132
View File
@@ -0,0 +1,132 @@
-- API tests (src/Formats/init.luau): load / save / saveString / convert / open / detect / formats / format, the
-- category facades, sniff-then-extension detection, errors as Err values (never a throw), and file paths on hosts with
-- a file system (LuaJIT: a temporary file; the luau CLI has none).
local T = require("@tests/T")
local F = require("@formats")
local Err = require("@formats/core/Err")
local t = T.suite("api")
local function image(w: number, h: number): any
local img = F.Types.Image.new(w, h)
for i = 0, w * h * 4 - 1 do
buffer.writeu8(img.pixels, i, (i * 37) % 256)
end
return img
end
-- host
t:eq(F.host.name, if T.runtime == "luajit" then "luajit" else "luau", "host detected")
-- formats()
do
local all = F.formats()
t:check(#all >= 1, "formats() lists the registry")
local png
for _, f in all do
if f.name == "png" then
png = f
end
end
t:check(png and png.category == "image" and png.caps.encode and table.find(png.extensions, "png"), "png in formats()")
t:eq(#F.image.formats(), #F.formats("image"), "facade formats()")
t:eq(#F.formats("nonexistent"), 0, "unknown category")
t:check(F.format("png") and F.format("png").name == "png", "format(name)")
t:check(F.format("apng") and F.format("apng").name == "png", "format(extension)")
local _, e = F.format("nope")
t:check(e and e.code == Err.UNKNOWN_FORMAT, "format(unknown)")
end
-- save -> load round trip through buffers and strings
do
local img = image(7, 5)
local buf, err = F.save(img, nil, { format = "png" })
t:check(buf and type(buf) == "buffer", "save to a buffer: " .. tostring(err))
local back = F.load(buf)
t:check(back and back.kind == "image" and back.width == 7 and back.height == 5, "load sniffs png")
t:eq(buffer.tostring(back.pixels), buffer.tostring(img.pixels), "pixels round trip")
t:eq(back.meta.source.format, "png", "meta.source.format")
-- save without a format: the source format
local again = F.save(back)
t:check(again and type(again) == "buffer", "save uses the source format")
local s = F.saveString(back)
t:check(type(s) == "string" and string.sub(s, 2, 4) == "PNG", "saveString")
local fromString = F.load(s)
t:check(fromString and fromString.width == 7, "load a string of bytes")
t:check(F.image.load(buf) ~= nil, "F.image.load")
t:eq(F.detect(buf), "png", "detect")
local conv = F.convert(s, "png", { level = 1 })
t:check(conv and F.load(conv).width == 7, "convert")
-- format options reach the encoder
local stored = F.save(img, nil, { format = "png", level = 0 }) :: buffer
t:check(buffer.len(stored) > buffer.len(buf :: buffer), "opts.level reaches the encoder")
end
-- detection: sniff beats the extension; the extension is the fallback; category restrictions
do
local png = F.save(image(2, 2), nil, { format = "png" }) :: buffer
t:eq(F.detect(png, { name = "photo.jpg" }), "png", "content beats a wrong extension")
local _, e = F.load("not an image at all")
t:check(e and e.code == Err.UNKNOWN_FORMAT, "unknown data: " .. tostring(e))
local _, e2 = F.load(png, { category = "audio" })
t:check(e2 and e2.code == Err.UNKNOWN_FORMAT, "png is not audio")
local _, e3 = F.audio.load(png)
t:check(e3 and e3.code == Err.UNKNOWN_FORMAT, "facade restricts the category")
-- forced format on bad data: the format's error, tagged with its name
local _, e4 = F.load("garbage!", { format = "png" })
t:check(e4 and e4.format == "png" and e4.code == Err.CORRUPT, "forced format error: " .. tostring(e4))
t:check(string.find(tostring(e4), "^png: ") ~= nil, "error message names the format")
local _, e5 = F.load("x", { format = "nope" })
t:check(e5 and e5.code == Err.UNKNOWN_FORMAT, "unknown forced format")
end
-- errors are values, never throws
do
local ok, v, e = pcall(F.load, 42 :: any)
t:check(ok and v == nil and e.code == Err.ARG, "load(42)")
local ok2, v2, e2 = pcall(F.save, image(1, 1))
t:check(ok2 and v2 == nil and e2.code == Err.ARG, "save without a format")
local ok3, _, e3 = pcall(F.save, { kind = "image" } :: any, nil, { format = "png" })
t:check(ok3 and e3 and e3.code == Err.ARG, "save of a broken image")
local ok4, _, e4 = pcall(F.save, image(1, 1), nil, { format = "nope" })
t:check(ok4 and e4.code == Err.UNKNOWN_FORMAT, "save to an unknown format")
local _, e5 = F.open(F.save(image(1, 1), nil, { format = "png" }))
t:check(e5 and e5.code == Err.UNSUPPORTED, "open() of a non-streaming format")
t:fuzz("F.load", function(b: buffer)
return F.load(b)
end, { F.saveString(image(9, 4), { format = "png" }) :: string }, { mutations = 20 })
end
-- files (hosts with a file system)
if F.host.hasFiles then
local path = os.tmpname() .. ".png"
local img = image(3, 3)
local ok, err = F.save(img, path)
t:check(ok == true, "save to a path (format from the extension): " .. tostring(err))
local back = F.load(path)
t:check(back and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "load from a path")
t:check(F.image.load(path) ~= nil, "facade load from a path")
local _, e = F.load("/nonexistent/dir/x.png", { path = true })
t:check(e and e.code == Err.IO, "missing file is Err.IO")
os.remove(path)
else
local _, e = F.save(image(1, 1), "out.png")
t:check(e and e.code == Err.IO, "no file system: save to a path is Err.IO")
local _, e2 = F.load("x.png", { path = true })
t:check(e2 and e2.code == Err.IO, "no file system: load of a path is Err.IO")
end
-- Types constructors
do
local T2 = F.Types
t:eq(buffer.len(T2.Image.new(3, 2, "rgb8").pixels), 18, "Image.new rgb8")
t:eq(buffer.len(T2.Image.new(3, 3, "yuv420p").pixels), 9 + 2 * 4, "Image.new yuv420p")
local a = T2.Audio.new(8000, 2, 100)
t:check(a.kind == "audio" and buffer.len(a.samples) == 800, "Audio.new")
local sc = T2.Scene.fromPrimitive({ attributes = {}, mode = "triangles" })
t:check(sc.kind == "scene" and #sc.nodes == 1 and sc.nodes[1].mesh == 1, "Scene.fromPrimitive")
t:eq(tostring(F.null), "null", "null sentinel")
t:check(F.data.null == F.null, "F.data.null")
end
t:done()
+172
View File
@@ -0,0 +1,172 @@
-- codecs/Deflate tests: every fixture case (Python zlib, levels 0-9, every strategy, small windows, flushes, gzip
-- headers, multi-member gzip) decodes; exact-size mode; checksum vectors; the compressor round-trips every corpus at
-- every level (and its zlib / gzip framing); truncated / corrupted / random input returns nil, Err and never throws.
-- Ported from deflate-luau tests/inflate.luau. Fixtures: tools/fixtures/deflate.py.
local T = require("@tests/T")
local Deflate = require("@formats/codecs/Deflate")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/deflate")
local t = T.suite("deflate")
local function decode(kind: string, b: buffer, ...: any): (buffer?, any)
if kind == "raw" then
return Deflate.inflate(b, ...)
elseif kind == "zlib" then
return Deflate.zlib(b, ...)
else
return Deflate.gunzip(b, ...)
end
end
-- checksum vectors
t:eq(Deflate.crc32("123456789"), 0xCBF43926, "crc32 check value")
t:eq(Deflate.crc32(""), 0, "crc32 empty")
t:eq(Deflate.adler32("Wikipedia"), 0x11E60398, "adler32 Wikipedia")
t:eq(Deflate.adler32(""), 1, "adler32 empty")
do
local s = string.rep("The quick brown fox jumps over the lazy dog. ", 400)
local b = buffer.fromstring(s)
local whole = Deflate.crc32(b)
local part = Deflate.crc32(b, 0, 1001)
t:eq(Deflate.crc32(b, 1001, nil, part), whole, "crc32 continuation")
local a = Deflate.adler32(b, 0, 7000)
t:eq(Deflate.adler32(b, 7000, nil, a), Deflate.adler32(b), "adler32 continuation")
t:eq(Deflate.crc32(b, 3, 17), Deflate.crc32(string.sub(s, 4, 20)), "crc32 range")
end
-- every case decodes to its corpus
local nbytes = 0
for _, c in Fx.cases do
local want = Fx.corpora[c.corpus]
local b = buffer.fromstring(c.data)
local out, err = decode(c.kind, b)
t:check(out ~= nil, c.name .. ": " .. tostring(err))
t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs")
nbytes += #want
if c.kind == "raw" then
t:eq(err, #c.data, c.name .. ": consumed")
-- exact size, and a wrong exact size
local o2 = Deflate.inflate(b, 0, nil, #want)
t:check(o2 and buffer.tostring(o2) == want, c.name .. ": exact size")
if #want > 0 then
t:check(Deflate.inflate(b, 0, nil, #want - 1) == nil, c.name .. ": too small exact size fails")
end
t:check(Deflate.inflate(b, 0, nil, #want + 1) == nil, c.name .. ": too large exact size fails")
-- the same stream inside a bigger buffer, at an offset, with trailing bytes
local big = buffer.create(#c.data + 13)
buffer.fill(big, 0, 0xAB)
buffer.copy(big, 5, b)
local o3, e3 = Deflate.inflate(big, 5, #c.data + 8)
t:check(o3 and buffer.tostring(o3) == want and e3 == 5 + #c.data, c.name .. ": at an offset")
elseif c.kind == "zlib" then
t:eq(err, #c.data, c.name .. ": zlib consumed")
end
end
t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
-- strings are accepted
t:check(buffer.tostring((Deflate.zlib(Fx.cases[25].data))) == Fx.corpora[Fx.cases[25].corpus], "string input")
-- corrupted checksums
do
local z
for _, c in Fx.cases do
if c.kind == "zlib" and #Fx.corpora[c.corpus] > 100 then
z = c
break
end
end
local b = buffer.fromstring(z.data)
buffer.writeu8(b, buffer.len(b) - 1, bit32.bxor(buffer.readu8(b, buffer.len(b) - 1), 1))
local out, err = Deflate.zlib(b)
t:check(out == nil and Err.is(err) and err.code == Err.CHECKSUM, "zlib adler mismatch: " .. tostring(err))
for _, c in Fx.cases do
if c.kind == "gzip" and #Fx.corpora[c.corpus] > 100 then
local g = buffer.fromstring(c.data)
local n = buffer.len(g)
buffer.writeu8(g, n - 6, bit32.bxor(buffer.readu8(g, n - 6), 0x40))
local o, e = Deflate.gunzip(g)
t:check(o == nil and e and e.code == Err.CHECKSUM, c.name .. ": gzip crc mismatch: " .. tostring(e))
break
end
end
end
-- hand-made streams
do
local bytes = T.bytes
-- stored block "hi" then a fixed block with only end-of-block
local o = Deflate.inflate(bytes({ 0x00, 0x02, 0x00, 0xFD, 0xFF, 0x68, 0x69, 0x03, 0x00 }))
t:check(o and buffer.tostring(o) == "hi", "stored + fixed EOB")
t:check(Deflate.inflate(bytes({ 0x01, 0x02, 0x00, 0xFC, 0xFF, 0x68, 0x69 })) == nil, "stored NLEN mismatch")
t:check(Deflate.inflate(bytes({ 0x07 })) == nil, "block type 3")
local _, e0 = Deflate.inflate(bytes({}))
t:check(e0 and e0.code == Err.TRUNCATED, "empty input is TRUNCATED: " .. tostring(e0))
-- fixed block: a match before any output (distance too far back)
local _, e = Deflate.inflate(bytes({ 0x03, 0x02, 0x00 }))
t:check(e ~= nil and e.code == Err.CORRUPT, "distance too far back: " .. tostring(e))
t:check(Deflate.zlib(bytes({ 0x78, 0x9c })) == nil, "zlib truncated header")
t:check(Deflate.zlib(bytes({ 0x78, 0x9d, 0x03, 0, 0, 0, 0, 1 })) == nil, "zlib FCHECK")
t:check(Deflate.gunzip(bytes({ 0x1f, 0x8c, 8, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 })) == nil, "gzip magic")
local ok, r1, r2 = pcall(Deflate.inflate, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local ok2, _, r3 = pcall(Deflate.inflate, "abc", -1)
t:check(ok2 and r3.code == Err.ARG, "a bad offset returns Err.ARG")
end
-- the compressor: every corpus, every level, raw / zlib / gzip; ratio against Python zlib -6
do
local total, comp6, ref6 = 0, 0, 0
for name, data in Fx.corpora do
local b = buffer.fromstring(data)
for level = 0, 9 do
local z, err = Deflate.compress(b, { level = level })
t:check(z, name .. ": compress level " .. level .. ": " .. tostring(err))
local back, berr = Deflate.inflate(z :: buffer)
t:check(back and buffer.tostring(back) == data, string.format("%s: level %d round trip: %s", name, level, tostring(berr)))
if level == 6 then
comp6 += buffer.len(z :: buffer)
total += #data
end
end
local zl = Deflate.zlibCompress(data) :: buffer
local back = Deflate.zlib(zl)
t:check(back and buffer.tostring(back) == data, name .. ": zlibCompress round trip")
local gz = Deflate.gzip(data, { level = 9 }) :: buffer
local back2 = Deflate.gunzip(gz)
t:check(back2 and buffer.tostring(back2) == data, name .. ": gzip round trip")
end
for _, c in Fx.cases do
if c.name == c.corpus .. "/zlib6" then
ref6 += #c.data - 6
end
end
t:note("compress -6: %d -> %d bytes (%.1f%%); Python zlib -6: %d bytes", total, comp6, 100 * comp6 / total, ref6)
t:check(comp6 < ref6 * 1.25, "level 6 within 25% of zlib")
local _, e = Deflate.compress("x", { level = 11 })
t:check(e and e.code == Err.ARG, "bad level returns Err.ARG")
end
-- truncation, corruption and garbage never throw
do
local samples = {}
local kinds = {}
for i, c in Fx.cases do
if i % 9 == 0 and #c.data > 8 then
table.insert(samples, c.data)
kinds[c.data] = c.kind
end
end
t:fuzz("inflate", function(b: buffer)
return Deflate.inflate(b)
end, samples, { mutations = 6, garbage = 3000 })
t:fuzz("zlib", function(b: buffer)
return Deflate.zlib(b)
end, samples, { mutations = 3, garbage = 300 })
t:fuzz("gunzip", function(b: buffer)
return Deflate.gunzip(b)
end, samples, { mutations = 3, garbage = 300 })
end
t:done()
+275
View File
@@ -0,0 +1,275 @@
-- compat tests: the Luau semantics the library relies on, checked under both runtimes. Under luau these pin down what
-- Luau does; under LuaJIT they check compat/luajit.lua (bit32, buffer, table / math / string / utf8 additions, typeof)
-- and tools/build.py's lowering (generalized iteration, if-expression chains, continue, compound assignment, string
-- interpolation, floor division, number literals).
local T = require("@tests/T")
local t = T.suite("compat")
-- ------------------------------------------------------------------------------------------------ bit32
do
t:eq(bit32.band(0xFFFFFFFF, 0x0F0F0F0F), 0x0F0F0F0F, "band unsigned")
t:eq(bit32.band(-1), 0xFFFFFFFF, "band(-1)")
t:eq(bit32.band(), 0xFFFFFFFF, "band()")
t:eq(bit32.band(2 ^ 32 + 3, 7), 3, "band reduces mod 2^32")
t:eq(bit32.band(0xFF, 0xF0, 0x3C), 0x30, "band 3 args")
t:eq(bit32.band(0xFF, 0xF0, 0x3C, 0x20, 0x20), 0x20, "band 5 args")
t:eq(bit32.bor(0x80000000, 1), 0x80000001, "bor high bit")
t:eq(bit32.bor(), 0, "bor()")
t:eq(bit32.bor(1, 2, 4, 8, 16), 31, "bor 5 args")
t:eq(bit32.bxor(0xFFFFFFFF, 0x12345678), 0xEDCBA987, "bxor")
t:eq(bit32.bxor(1, 2, 4, 8, 16, 32, 64, 128, 256, 512), 1023, "bxor 10 args")
t:eq(bit32.bnot(0), 0xFFFFFFFF, "bnot")
t:eq(bit32.bnot(0xFFFFFFFF), 0, "bnot all")
t:eq(bit32.lshift(1, 31), 0x80000000, "lshift 31")
t:eq(bit32.lshift(1, 32), 0, "lshift 32")
t:eq(bit32.lshift(0xFFFFFFFF, 4), 0xFFFFFFF0, "lshift drops high bits")
t:eq(bit32.lshift(1, -1), 0, "lshift negative")
t:eq(bit32.lshift(8, -2), 2, "lshift negative = rshift")
t:eq(bit32.rshift(0x80000000, 31), 1, "rshift logical")
t:eq(bit32.rshift(0xFFFFFFFF, 0), 0xFFFFFFFF, "rshift 0 stays unsigned")
t:eq(bit32.rshift(2, -1), 4, "rshift negative = lshift")
t:eq(bit32.rshift(5, 40), 0, "rshift 40")
t:eq(bit32.arshift(0x80000000, 4), 0xF8000000, "arshift sign fill")
t:eq(bit32.arshift(0x80000000, 40), 0xFFFFFFFF, "arshift >= 32")
t:eq(bit32.lrotate(0x80000001, 1), 3, "lrotate")
t:eq(bit32.rrotate(3, 1), 0x80000001, "rrotate")
t:eq(bit32.extract(0xF0, 4, 4), 15, "extract")
t:eq(bit32.extract(0x80000000, 31), 1, "extract 1 bit")
t:eq(bit32.replace(0, 5, 4, 3), 80, "replace")
t:eq(bit32.countlz(1), 31, "countlz")
t:eq(bit32.countlz(0), 32, "countlz 0")
t:eq(bit32.countrz(8), 3, "countrz")
t:eq(bit32.countrz(0), 32, "countrz 0")
t:eq(bit32.byteswap(0x01020304), 0x04030201, "byteswap")
t:eq(bit32.byteswap(0x000000FF), 0xFF000000, "byteswap high")
t:check(bit32.btest(6, 2) and not bit32.btest(4, 2), "btest")
end
-- ------------------------------------------------------------------------------------------------ buffer
do
local b = buffer.create(16)
t:eq(buffer.len(b), 16, "len")
t:eq(buffer.readu32(b, 12), 0, "zero-filled")
buffer.writeu32(b, 0, 0xDEADBEEF)
t:eq(buffer.readu32(b, 0), 0xDEADBEEF, "u32 round trip")
t:eq(buffer.readu8(b, 0), 0xEF, "little-endian")
t:eq(buffer.readu16(b, 2), 0xDEAD, "u16")
t:eq(buffer.readi8(b, 3), -34, "i8 sign")
t:eq(buffer.readi16(b, 2), 0xDEAD - 65536, "i16 sign")
t:eq(buffer.readi32(b, 0), 0xDEADBEEF - 2 ^ 32, "i32 sign")
buffer.writeu8(b, 0, 300)
t:eq(buffer.readu8(b, 0), 44, "writeu8 wraps")
buffer.writeu8(b, 0, -1)
t:eq(buffer.readu8(b, 0), 255, "writeu8 -1")
buffer.writeu8(b, 0, 3.7)
t:eq(buffer.readu8(b, 0), 3, "writeu8 truncates")
buffer.writeu8(b, 0, 255 + 255)
t:eq(buffer.readu8(b, 0), 254, "writeu8 of a sum")
buffer.writeu32(b, 4, -1)
t:eq(buffer.readu32(b, 4), 0xFFFFFFFF, "writeu32 -1")
buffer.writeu32(b, 4, 2 ^ 32 + 5)
t:eq(buffer.readu32(b, 4), 5, "writeu32 wraps")
buffer.writei16(b, 8, 40000)
t:eq(buffer.readi16(b, 8), -25536, "writei16 wraps")
buffer.writeu16(b, 8, -2)
t:eq(buffer.readu16(b, 8), 65534, "writeu16 -2")
buffer.writei32(b, 8, -5)
t:eq(buffer.readi32(b, 8), -5, "i32 round trip")
buffer.writef32(b, 0, 1.5)
t:eq(buffer.readf32(b, 0), 1.5, "f32")
buffer.writef32(b, 0, 0.1)
t:check(math.abs(buffer.readf32(b, 0) - 0.1) < 1e-8 and buffer.readf32(b, 0) ~= 0.1, "f32 rounds")
buffer.writef64(b, 8, math.pi)
t:eq(buffer.readf64(b, 8), math.pi, "f64")
local nan = buffer.readf32(buffer.fromstring("\0\0\192\127"), 0)
t:check(nan ~= nan, "f32 NaN")
-- out of bounds throws (both runtimes), and nothing is written
t:check(not pcall(buffer.readu8, b, 16), "readu8 past the end throws")
t:check(not pcall(buffer.readu8, b, -1), "readu8 at -1 throws")
t:check(not pcall(buffer.readu32, b, 13), "readu32 overlapping the end throws")
t:check(not pcall(buffer.writeu16, b, 15, 0), "writeu16 overlapping the end throws")
t:check(not pcall(buffer.readstring, b, 10, 7), "readstring past the end throws")
t:check(not pcall(buffer.copy, b, 10, b, 0, 7), "copy past the end throws")
t:check(not pcall(buffer.fill, b, 10, 0, 7), "fill past the end throws")
-- strings, NULs, copy, fill
local s = buffer.fromstring("a\0b\255c")
t:eq(buffer.len(s), 5, "fromstring with NUL")
t:eq(buffer.tostring(s), "a\0b\255c", "tostring with NUL")
t:eq(buffer.readstring(s, 1, 3), "\0b\255", "readstring")
buffer.writestring(b, 0, "hello world")
t:eq(buffer.readstring(b, 0, 11), "hello world", "writestring")
buffer.writestring(b, 0, "HELLO", 2)
t:eq(buffer.readstring(b, 0, 5), "HEllo", "writestring count")
buffer.copy(b, 2, b, 0, 6) -- overlapping (memmove)
t:eq(buffer.readstring(b, 0, 8), "HEHEllo ", "copy overlapping")
local c = buffer.create(4)
buffer.copy(c, 1, s, 2)
t:eq(buffer.readstring(c, 1, 3), "b\255c", "copy default count")
buffer.fill(c, 0, 0x41)
t:eq(buffer.tostring(c), "AAAA", "fill to the end")
buffer.fill(c, 1, 0x142, 2)
t:eq(buffer.tostring(c), "ABBA", "fill value wraps")
t:eq(buffer.len(buffer.create(0)), 0, "empty buffer")
t:eq(buffer.tostring(buffer.create(0)), "", "empty tostring")
-- readbits / writebits
local bb = buffer.create(8)
buffer.writeu32(bb, 0, 0xDEADBEEF)
t:eq(buffer.readbits(bb, 4, 12), 3054, "readbits")
t:eq(buffer.readbits(bb, 0, 32), 0xDEADBEEF, "readbits 32")
t:eq(buffer.readbits(bb, 0, 0), 0, "readbits 0")
buffer.writebits(bb, 3, 7, 0x7F)
t:eq(buffer.readu32(bb, 0), 3735928831, "writebits")
buffer.writebits(bb, 30, 20, 0xABCDE)
t:eq(buffer.readbits(bb, 30, 20), 0xABCDE, "writebits across bytes")
t:check(not pcall(buffer.readbits, bb, 60, 5), "readbits past the end throws")
-- big buffers (LuaJIT: calloc'd memory)
local big = buffer.create(1000000)
buffer.writeu32(big, 999996, 0x01020304)
t:eq(buffer.readu32(big, 999996), 0x01020304, "big buffer")
t:eq(buffer.readu8(big, 500000), 0, "big buffer zero-filled")
end
-- ------------------------------------------------------------------------------------------------ typeof / type
do
local b = buffer.create(1)
t:eq(typeof(b), "buffer", "typeof buffer")
t:eq(type(b), "buffer", "type buffer")
t:eq(typeof({}), "table", "typeof table")
t:eq(type(1), "number", "type number")
t:eq(typeof(nil), "nil", "typeof nil")
t:eq(typeof("s"), "string", "typeof string")
end
-- ------------------------------------------------------------------------------------------------ table / math / string
do
local c = table.create(3, 7)
t:eq(#c, 3, "table.create size")
t:eq(c[3], 7, "table.create value")
t:eq(#table.create(5), 0, "table.create without value")
t:eq(table.find({ 5, 6, 7 }, 6), 2, "table.find")
t:eq(table.find({ 5, 6, 7 }, 8), nil, "table.find missing")
t:eq(table.find({ 5, 6, 5 }, 5, 2), 3, "table.find init")
local x = { 1, 2, a = 3 }
table.clear(x)
t:check(next(x) == nil, "table.clear")
local f = table.freeze({ 1 })
t:check(table.isfrozen(f) and not table.isfrozen({}), "freeze / isfrozen")
local cl = table.clone({ 1, 2, k = "v" })
t:check(cl[2] == 2 and cl.k == "v", "table.clone")
t:eq(table.unpack({ 1, 2, 3 }, 2, 3), 2, "table.unpack")
t:eq(select("#", table.unpack({ 1, 2, 3 })), 3, "table.unpack count")
local m = table.move({ 1, 2, 3 }, 1, 3, 2)
t:check(m[1] == 1 and m[2] == 1 and m[3] == 2 and m[4] == 3, "table.move overlapping")
t:eq(math.clamp(5, 0, 3), 3, "clamp high")
t:eq(math.clamp(-1, 0, 3), 0, "clamp low")
t:eq(math.sign(-3), -1, "sign")
t:eq(math.sign(0), 0, "sign 0")
t:eq(math.round(2.5), 3, "round half up")
t:eq(math.round(-2.5), -3, "round half away from zero")
t:eq(math.round(2.4), 2, "round down")
t:check(type(math.noise(0.5, 0.3, 0.1)) == "number", "noise is a number")
local parts = string.split("a,b,,c", ",")
t:check(#parts == 4 and parts[1] == "a" and parts[3] == "" and parts[4] == "c", "string.split")
t:eq(#string.split("", ","), 1, "split empty")
t:eq(#("x y z"):split(" "), 3, "split as a method")
t:eq(string.format("%5.1f|%d|%x|%s", 3.14159, 42, 255, "s"), " 3.1|42|ff|s", "string.format")
t:eq(math.floor(-3.5), -4, "floor")
end
-- ------------------------------------------------------------------------------------------------ utf8
do
t:eq(utf8.char(72, 228, 8364, 128512), "H\xC3\xA4\xE2\x82\xAC\xF0\x9F\x98\x80", "utf8.char")
t:eq(utf8.len("h\xC3\xA4ll\xE2\x82\xAC"), 5, "utf8.len")
local n, bad = utf8.len("a\xFFb")
t:check(n == nil and bad == 2, "utf8.len invalid")
t:eq(utf8.codepoint("\xC3\xA4"), 228, "utf8.codepoint")
t:eq(utf8.offset("h\xC3\xA4ll", 3), 4, "utf8.offset")
local cps = {}
for _, c in utf8.codes("a\xC3\xA4\xE2\x82\xAC") do
table.insert(cps, c)
end
t:check(#cps == 3 and cps[2] == 228 and cps[3] == 8364, "utf8.codes")
t:check(string.find("\xC3\xA4", utf8.charpattern) == 1, "utf8.charpattern")
end
-- ------------------------------------------------------------------------------------------------ syntax lowering
do
-- generalized iteration: arrays (in order), dictionaries, mixed, iterator functions, nested
local order = {}
for i, v in { 10, 20, 30 } do
table.insert(order, i * 100 + v)
end
t:check(order[1] == 110 and order[2] == 220 and order[3] == 330, "for over an array, in order")
local sum = 0
for k, v in { a = 1, b = 2, c = 3 } do
sum += v
t:check(type(k) == "string", "dict keys")
end
t:eq(sum, 6, "for over a dictionary")
local count = 0
for _ in { 1, 2, x = 3 } do
count += 1
end
t:eq(count, 3, "for over a mixed table visits every key")
local w = {}
for word in string.gmatch("a b c", "%a") do
table.insert(w, word)
end
t:eq(#w, 3, "for over an iterator function")
local pc = 0
for _, _ in pairs({ 1, 2 }) do
pc += 1
end
t:eq(pc, 2, "pairs untouched")
local empty = 0
for _ in {} do
empty += 1
end
t:eq(empty, 0, "for over an empty table")
-- if-expressions: chains of elseif (darklua 0.19 reverses them; build.py rewrites them)
local function grade(i: number): string
return if i <= 144 then "a" elseif i <= 256 then "b" elseif i <= 280 then "c" else "d"
end
t:check(grade(1) == "a" and grade(200) == "b" and grade(270) == "c" and grade(285) == "d", "if-expression elseif chain")
local function n3(i: number): number
return if i < 0 then -1 elseif i == 0 then 0 elseif i < 10 then 1 elseif i < 100 then 2 else 3
end
t:check(n3(-5) == -1 and n3(0) == 0 and n3(5) == 1 and n3(50) == 2 and n3(500) == 3, "numeric elseif chain")
local function falsy(c: boolean): any
return if c then nil else false
end
t:check(falsy(true) == nil and falsy(false) == false, "if-expression with falsy branches")
local function nested(a: boolean, b: boolean): number
return if a then (if b then 1 else 2) else if b then 3 else 4
end
t:check(nested(true, true) == 1 and nested(true, false) == 2 and nested(false, true) == 3 and nested(false, false) == 4, "nested if-expressions")
local v = 5
local arith = if v > 3 then v * 2 else v - 1
t:eq(arith, 10, "if-expression arithmetic")
-- continue, compound assignment, interpolation, floor division, literals
local odd = 0
for i = 1, 10 do
if i % 2 == 0 then
continue
end
odd += i
end
t:eq(odd, 25, "continue")
local s = "a"
s ..= "b"
local n = 7
n //= 2
n *= 3
n -= 1
n ^= 2
t:check(s == "ab" and n == 64, "compound assignment")
t:eq(`x={n} y={1 + 2}`, "x=64 y=3", "string interpolation")
t:eq(-7 // 2, -4, "floor division of a negative")
t:eq(7.5 // 2, 3, "floor division of a fraction")
t:eq(-7 % 3, 2, "modulo of a negative")
t:eq(0b1010 + 1_000 + 0xFF_FF, 10 + 1000 + 65535, "number literals")
t:eq(0x7FFFFFFF + 1, 2147483648, "no integer overflow")
end
t:done()
+178
View File
@@ -0,0 +1,178 @@
-- core/Bits and core/Huffman tests: LSB / MSB readers and writers round-trip random fields of 1..32 bits, align /
-- peek / bytePos, overrun is a sticky error; canonical codes, length-limited code lengths, LSB and MSB decoding tables
-- (with subtables) decode what the writers wrote; invalid code sets are rejected.
local T = require("@tests/T")
local Bits = require("@formats/core/Bits")
local Huffman = require("@formats/core/Huffman")
local Err = require("@formats/core/Err")
local t = T.suite("bits")
local rand = T.rng(7)
-- round trips
for _, kind in { "lsb", "msb" } do
local w = if kind == "lsb" then Bits.lsbWriter() else Bits.msbWriter()
local fields = {}
for i = 1, 3000 do
local n = 1 + rand(32)
local v = if n == 32 then rand(65536) * 65536 + rand(65536) else rand(2 ^ n)
fields[i] = { v, n }
w:write(v, n)
if i % 500 == 0 then
w:align()
fields[i][3] = true
end
end
local buf = w:finish()
local r = if kind == "lsb" then Bits.lsbReader(buf) else Bits.msbReader(buf)
local ok = true
for i, f in fields do
if r:peek(math.min(f[2], 24)) ~= f[1] % 2 ^ math.min(f[2], 24) and kind == "lsb" then
ok = false
end
local v = r:read(f[2])
if v ~= f[1] then
ok = false
print(" mismatch", kind, i, v, f[1], f[2])
break
end
if f[3] then
r:align()
end
end
t:check(ok, kind .. ": 3000 random fields round trip")
t:check(r.err == nil, kind .. ": no error")
r:read(16)
t:check(r.err and r.err.code == Err.TRUNCATED, kind .. ": overrun is TRUNCATED")
end
-- known bit orders
do
local lsb = Bits.lsbReader(T.bytes({ 0xB4 })) -- 1011 0100
t:eq(lsb:read(3), 4, "lsb: first field is the low bits")
t:eq(lsb:read(5), 0x16, "lsb: rest")
local msb = Bits.msbReader(T.bytes({ 0xB4 }))
t:eq(msb:read(3), 5, "msb: first field is the high bits")
t:eq(msb:read(5), 0x14, "msb: rest")
local w = Bits.msbWriter()
w:write(5, 3)
w:write(0x14, 5)
w:write(1, 1)
t:eq(T.hex(w:finish()), "b4 80", "msb writer pads with zeros")
local r = Bits.lsbReader(T.bytes({ 0xFF, 0x12, 0x34 }))
r:read(3)
t:eq(r:bytePos(), 1, "bytePos after a partial byte")
r:align()
t:eq(r:read(8), 0x12, "align then read a byte")
t:eq(r:bitsLeft(), 8, "bitsLeft")
local e = Bits.msbReader(buffer.create(0))
t:eq(e:peek(8), 0, "peek past the end is zeros")
t:check(e.err == nil, "peek past the end is not an error")
end
-- Huffman: canonical codes (RFC 1951 3.2.2 example)
do
local codes = Huffman.codes({ 3, 3, 3, 3, 3, 2, 4, 4 })
local want = { 2, 3, 4, 5, 6, 0, 14, 15 }
local ok = true
for i = 1, 8 do
ok = ok and codes[i] == want[i]
end
t:check(ok, "canonical codes (RFC 1951 example)")
t:eq(Huffman.reverse(0x91, 8), 0x89, "reverse")
t:eq(Huffman.reverse(1, 3), 4, "reverse 3 bits")
end
-- lengths: limits, Kraft equality, single symbol
local function kraft(lens: { number }): number
local s = 0
for _, l in lens do
if l > 0 then
s += 2 ^ -l
end
end
return s
end
do
local freqs = {}
for i = 1, 40 do
freqs[i] = math.floor(1.6 ^ i) -- Fibonacci-like: unlimited depth would be ~39
end
local lens = Huffman.lengths(freqs, 15)
local maxl = 0
for _, l in lens do
maxl = math.max(maxl, l)
end
t:check(maxl <= 15, "length limit 15 (got " .. maxl .. ")")
t:check(math.abs(kraft(lens) - 1) < 1e-12, "complete code")
local one = Huffman.lengths({ 0, 5, 0 }, 15)
t:check(one[1] == 0 and one[2] == 1 and one[3] == 0, "a single symbol gets length 1")
local none = Huffman.lengths({ 0, 0 }, 15)
t:check(none[1] == 0 and none[2] == 0, "no symbols")
local u = Huffman.lengths({ 1, 1, 1, 1 }, 15)
t:check(u[1] == 2 and u[4] == 2, "uniform")
end
-- decoding tables: random code sets, encode with the writer, decode through LSB and MSB tables
for trial = 1, 30 do
local nsym = 2 + rand(300)
local freqs = {}
for i = 1, nsym do
freqs[i] = if rand(4) == 0 then 0 else 1 + rand(1000) * rand(50)
end
freqs[1] += 1
freqs[2] += 1
local maxLen = if trial % 2 == 0 then 15 else 16
local lens = Huffman.lengths(freqs, maxLen)
local codes = Huffman.codes(lens)
local lensBuf = buffer.create(nsym)
for i = 1, nsym do
buffer.writeu8(lensBuf, i - 1, lens[i])
end
local P = 4 + rand(6)
local msgs = {}
for i = 1, 500 do
local s
repeat
s = rand(nsym)
until lens[s + 1] > 0
msgs[i] = s
end
for _, kind in { "lsb", "msb" } do
local tab = buffer.create(Huffman.capacity(nsym, P, maxLen) * 4)
local S = if kind == "lsb" then Huffman.buildLsb(lensBuf, 0, nsym, tab, P) else Huffman.buildMsb(lensBuf, 0, nsym, tab, P)
t:check(S >= 0, kind .. ": table built")
local w = if kind == "lsb" then Bits.lsbWriter() else Bits.msbWriter()
for _, s in msgs do
local l = lens[s + 1]
w:write(if kind == "lsb" then Huffman.reverse(codes[s + 1], l) else codes[s + 1], l)
end
local buf = w:finish()
local r = if kind == "lsb" then Bits.lsbReader(buf) else Bits.msbReader(buf)
local ok = true
for _, s in msgs do
local got = if kind == "lsb" then Huffman.decodeLsb(r, tab, P, S) else Huffman.decodeMsb(r, tab, P, S)
if got ~= s then
ok = false
break
end
end
t:check(ok, string.format("%s trial %d: %d symbols, P=%d, decode", kind, trial, nsym, P))
end
end
-- invalid code sets
do
local over = T.bytes({ 1, 1, 1 }) -- three 1-bit codes
t:eq(Huffman.buildLsb(over, 0, 3, buffer.create(1024 * 4), 8), -1, "over-subscribed")
local tooLong = T.bytes({ 17, 1 })
t:eq(Huffman.buildMsb(tooLong, 0, 2, buffer.create(1024 * 4), 8), -1, "length over 16")
local incomplete = T.bytes({ 2, 0, 0 }) -- one 2-bit code: decoding the missing ones fails
local tab = buffer.create(256 * 4)
local S = Huffman.buildMsb(incomplete, 0, 3, tab, 4)
t:check(S >= 0, "incomplete code set builds")
local r = Bits.msbReader(T.bytes({ 0xC0 }))
t:eq(Huffman.decodeMsb(r, tab, 4, S), -1, "missing code decodes to -1")
end
t:done()
+184
View File
@@ -0,0 +1,184 @@
-- core/Bytes, core/Err, core/Crc32, core/Adler32, core/Input tests: every Reader / Writer method both endians, the
-- sticky TRUNCATED error (never a throw), sub-readers without copies, Writer growth and patching.
local T = require("@tests/T")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Adler32 = require("@formats/core/Adler32")
local Input = require("@formats/core/Input")
local t = T.suite("bytes")
-- Writer -> Reader round trip of every type
do
local w = Bytes.writer(4) -- grows
w:u8(0xAB)
w:u16le(0x1234)
w:u16be(0x1234)
w:u24le(0x123456)
w:u24be(0x123456)
w:u32le(0xDEADBEEF)
w:u32be(0xDEADBEEF)
w:i8(-2)
w:i16le(-300)
w:i16be(-300)
w:i32le(-70000)
w:i32be(-70000)
w:u64le(2 ^ 40 + 7)
w:u64be(2 ^ 52 + 3)
w:i64le(-5)
w:f32le(1.5)
w:f32be(-2.25)
w:f64le(math.pi)
w:f64be(-math.pi)
w:u16le(0x3C00) -- f16 1.0
w:u16be(0xC000) -- f16 -2.0
w:string("abc")
w:cstring("zero")
w:string("fix\0\0\0")
w:fill(7, 3)
local mark = w:tell()
w:u32be(0)
w:setU32be(mark, 0xCAFEBABE)
local buf = w:finish()
t:eq(buffer.len(buf), w:tell(), "finish is exactly the written bytes")
local r = Bytes.reader(buf)
t:eq(r:u8(), 0xAB, "u8")
t:eq(r:u16le(), 0x1234, "u16le")
t:eq(r:u16be(), 0x1234, "u16be")
t:eq(r:u24le(), 0x123456, "u24le")
t:eq(r:u24be(), 0x123456, "u24be")
t:eq(r:u32le(), 0xDEADBEEF, "u32le")
t:eq(r:u32be(), 0xDEADBEEF, "u32be")
t:eq(r:i8(), -2, "i8")
t:eq(r:i16le(), -300, "i16le")
t:eq(r:i16be(), -300, "i16be")
t:eq(r:i32le(), -70000, "i32le")
t:eq(r:i32be(), -70000, "i32be")
t:eq(r:u64le(), 2 ^ 40 + 7, "u64le")
t:eq(r:u64be(), 2 ^ 52 + 3, "u64be")
t:eq(r:i64le(), -5, "i64le")
t:eq(r:f32le(), 1.5, "f32le")
t:eq(r:f32be(), -2.25, "f32be")
t:eq(r:f64le(), math.pi, "f64le")
t:eq(r:f64be(), -math.pi, "f64be")
t:eq(r:f16le(), 1, "f16le")
t:eq(r:f16be(), -2, "f16be")
t:eq(r:string(3), "abc", "string")
t:eq(r:cstring(), "zero", "cstring")
t:eq(r:fixed(6), "fix", "fixed")
t:eq(r:u8() + r:u8() + r:u8(), 21, "fill")
t:eq(r:u32be(), 0xCAFEBABE, "patched field")
t:check(r:eof() and r.err == nil, "consumed everything, no error")
t:eq(Bytes.half(0x7C00), math.huge, "f16 infinity")
t:check(Bytes.half(0x7E00) ~= Bytes.half(0x7E00), "f16 NaN")
t:eq(Bytes.half(0x0001), 2 ^ -24, "f16 subnormal")
end
-- sticky errors: reads past the end return 0 / "" and set err once, never throw
do
local r = Bytes.reader(buffer.fromstring("\1\2\3"))
t:eq(r:u16le(), 0x0201, "read within")
t:eq(r:u32le(), 0, "short read returns 0")
t:check(r.err and r.err.code == Err.TRUNCATED, "TRUNCATED")
t:eq(r.err.offset, 2, "error offset is where the read started")
local first = r.err
t:eq(r:u8(), 0, "reads after the error return 0")
t:eq(r:string(5), "", "string after the error")
t:check(r.err == first, "the first error sticks")
t:check(r:eof(), "cursor at the end")
local r2 = Bytes.reader(buffer.fromstring("abc"))
t:check(not r2:seek(4) and r2.err ~= nil, "seek past the end fails")
local r3 = Bytes.reader(buffer.fromstring("abc"))
t:eq(r3:cstring(), "abc", "unterminated cstring returns what there is")
t:check(r3.err and r3.err.code == Err.TRUNCATED, "unterminated cstring is TRUNCATED")
local r4 = Bytes.reader(buffer.fromstring("abcd"))
local nilv, e = r4:fail(Err.CORRUPT, "bad thing")
t:check(nilv == nil and e.code == Err.CORRUPT and tostring(e) == "CORRUPT at 0x0: bad thing", "fail(): " .. tostring(e))
t:check(not r4:need(5) and r4.err == e, "need keeps the first error")
-- every method on an empty reader: no throw
local empty = Bytes.reader(buffer.create(0))
for _, m in { "u8", "i8", "u16le", "u16be", "i16le", "i16be", "u24le", "u24be", "u32le", "u32be", "i32le", "i32be", "u64le", "u64be", "i64le", "i64be", "f16le", "f16be", "f32le", "f32be", "f64le", "f64be", "cstring" } do
local ok, v = pcall((Bytes.Reader :: any)[m], empty)
t:check(ok and (v == 0 or v == ""), m .. " on an empty reader")
end
local ok = pcall(function()
empty:string(-1)
empty:bytes(10)
empty:slice(10)
empty:skip(3)
empty:align(4)
end)
t:check(ok, "string / bytes / slice / skip / align on an empty reader")
end
-- ranges, sub-readers, peek, match
do
local buf = buffer.fromstring("0123456789")
local r = Bytes.reader(buf, 2, 5) -- "23456"
t:eq(r:size(), 5, "size")
t:eq(r:peek(3), "234", "peek")
t:eq(r:peekU8(4), string.byte("6"), "peekU8")
t:eq(r:peekU8(5), -1, "peekU8 past the end")
t:check(r:match("23") and r:tell() == 2, "match consumes")
t:check(not r:match("xx") and r:tell() == 2, "no match consumes nothing")
local s = r:slice(2) -- "45"
t:check(s.buf == buf and s:size() == 2 and r:tell() == 4, "slice: no copy, parent skips")
t:eq(s:string(2), "45", "slice contents")
t:eq(s:u8(), 0, "slice is bounded")
local sub = r:sub(1, 3) -- "345"
t:eq(sub:string(3), "345", "sub")
t:eq(r:tell(), 4, "sub does not move the parent")
local clamped = Bytes.reader(buf, 8, 100)
t:eq(clamped:size(), 2, "reader length clamped")
local neg = Bytes.reader(buf, -5)
t:eq(neg:size(), 10, "negative offset clamped")
local copy = Bytes.reader(buf, 1, 3):bytes(3)
t:eq(buffer.tostring(copy), "123", "bytes copies")
local a = Bytes.reader(buf)
a:skip(3)
t:check(a:align(4) and a:tell() == 4, "align")
end
-- checksums
do
t:eq(Crc32.string("123456789"), 0xCBF43926, "crc32 check value")
t:eq(Crc32.of(buffer.fromstring("xx123456789yy"), 2, 9), 0xCBF43926, "crc32 range")
t:eq(Crc32.of(buffer.fromstring("ab"), 5, 9), 0, "crc32 clamped range")
t:eq(Crc32.string("56789", Crc32.string("1234")), 0xCBF43926, "crc32 continuation")
t:eq(Adler32.string("Wikipedia"), 0x11E60398, "adler32")
t:eq(Adler32.string("pedia", Adler32.string("Wiki")), 0x11E60398, "adler32 continuation")
end
-- Input (without a host)
do
local b = buffer.create(3)
t:check(Input.resolve(b) == b, "a buffer passes through")
local fromStr = Input.resolve("abc")
t:eq(buffer.tostring(fromStr :: buffer), "abc", "a string is data without a host")
local _, e = Input.resolve(42)
t:check(e and e.code == Err.ARG, "a number is Err.ARG")
t:eq(Input.extension("a/b.PNG"), "png", "extension")
t:eq(Input.extension("noext"), nil, "no extension")
t:check(Input.looksLikePath("a/b.png") and not Input.looksLikePath("a\0b") and not Input.looksLikePath("x\ny"), "looksLikePath")
local fake = { hasFiles = true, exists = function(p: string): boolean
return p == "img.png"
end, readFile = function(_p: string): (buffer?, any)
return buffer.fromstring("PNGDATA"), nil
end }
local fb, _, name = Input.resolve("img.png", nil, fake :: any)
t:check(fb and buffer.tostring(fb) == "PNGDATA" and name == "img.png", "a path through the host")
local db = Input.resolve("img.png", { data = true }, fake :: any)
t:eq(buffer.tostring(db :: buffer), "img.png", "opts.data forces data")
end
-- Err
do
local e = Err.new(Err.CORRUPT, "bad", 16)
t:check(Err.is(e) and not Err.is({}) and not Err.is("x"), "Err.is")
t:eq(tostring(Err.wrap(e, "png")), "png: CORRUPT at 0x10: bad", "tostring with format and offset")
local w = Err.wrap("plain message", "gif")
t:check(w.code == Err.CORRUPT and w.format == "gif", "wrap a string")
end
t:done()
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 315 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 595 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 361 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 404 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 724 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 792 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 742 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 716 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 941 B

Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more