vec: merge ws/arch (codecs/Raster for SVG)

This commit is contained in:
4DBug committed 2026-10-31 08:54:57 -05:00
commit 84e5d2e4c9
66 files changed
+15049 -1

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
-- archive/7z tests: the contract and sniff; every archive 7-Zip wrote in tools/fixtures/7z.py (LZMA / LZMA2 / copy /
-- Deflate, solid and not, BCJ / ARM64 / ARM / PPC + SPARC / delta chains, plain and encoded headers) lists exactly the
-- source tree (names incl. UTF-16 surrogates, directories, empty files, mtimes) and reads every file back; unsupported
-- methods (BZip2, PPMd, BCJ2, AES) list but fail on read with Err.UNSUPPORTED naming the method; corrupt CRCs; F.load;
-- the fuzz no-throw pass.
local T = require("@tests/T")
local SevenZip = require("@formats/archive/7z")
local F = require("@formats")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/7z")
local t = T.suite("7z")
t:eq(SevenZip.name, "7z", "name")
t:eq(SevenZip.category, "archive", "category")
t:check(SevenZip.caps.decode and not SevenZip.caps.encode, "caps")
local function decode(data: string, opts: any?): (any, any)
return SevenZip.decode(Bytes.reader(buffer.fromstring(data)), opts)
end
local want: { [string]: any } = {}
for _, f in Fx.files do
want[f.name] = f
end
local nfiles = 0
for _, c in Fx.cases do
t:eq(SevenZip.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
local a, err = decode(c.data)
t:check(a, c.name .. ": " .. tostring(err))
local list = a:list()
if c.empty then
t:eq(#list, 0, c.name .. ": no entries")
continue
end
local seen = {}
for _, e in list do
local w = want[e.name]
t:check(w ~= nil, c.name .. ": unexpected entry " .. e.name)
seen[e.name] = true
t:eq(e.dir, w.dir, c.name .. ": " .. e.name .. ": dir")
t:eq(e.mtime, w.mtime, c.name .. ": " .. e.name .. ": mtime")
if not w.dir then
t:eq(e.size, #w.data, c.name .. ": " .. e.name .. ": size")
local b, rerr = a:read(e.name)
if c.unsupported and #w.data > 0 then
t:check(b == nil and rerr and rerr.code == Err.UNSUPPORTED and string.find(rerr.message, c.unsupported, 1, true) ~= nil,
c.name .. ": " .. e.name .. ": unsupported: " .. tostring(rerr))
else
t:check(b and buffer.tostring(b) == w.data, c.name .. ": " .. e.name .. ": data: " .. tostring(rerr))
nfiles += 1
end
end
end
for name in want do
t:check(seen[name], c.name .. ": missing " .. name)
end
end
t:note("%d archives, %d files read", #Fx.cases, nfiles)
-- corrupt data: a flipped byte in a stored file is a CRC error on read; a flipped header byte a header CRC error
do
local c
for _, x in Fx.cases do
if x.name == "copy" then
c = x
end
end
local s = c.data
local at = string.find(s, "deep\ndeep", 1, true) :: number
local bad = string.sub(s, 1, at - 1) .. "D" .. string.sub(s, at + 1)
local a = decode(bad)
t:check(a, "copy archive with a flipped data byte still lists")
local b, e = a:read("a/b/c/deep.txt")
t:check(b == nil and e and e.code == Err.CHECKSUM, "data CRC: " .. tostring(e))
local _, e2 = decode(string.sub(s, 1, #s - 3) .. "\0\0\0")
t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "header CRC: " .. tostring(e2))
local _, e3 = decode(string.sub(s, 1, 20))
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
local a4 = decode(bad, { checkCrc = false })
t:check(a4 and a4:read("a/b/c/deep.txt"), "checkCrc = false")
end
-- through the api
do
local c = Fx.cases[2]
local a, err = F.load(c.data)
t:check(a and a.format == "7z", "F.load: " .. tostring(err))
t:eq(F.detect(c.data), "7z", "F.detect")
local r = a:read("readme.txt")
t:check(r and buffer.tostring(r) == want["readme.txt"].data, "F.load read")
end
-- fuzz: decode + read every entry
do
local samples = {}
for _, c in Fx.cases do
if #c.data < 60000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = SevenZip.decode(Bytes.reader(b), { maxBytes = 2 ^ 21 })
if a then
for _, e in a:list() do
a:read(e.name)
end
end
return a
end, samples, { mutations = 12, garbage = 300 })
end
t:done()
+97
View File
@@ -0,0 +1,97 @@
-- archive/br tests: the contract; fixture streams (tools/fixtures/brotli.py) load as a one-entry stream archive named
-- after the file; detection through F.load (sniff + extension); sniff rejects garbage and other formats; errors as
-- Err values; the fuzz no-throw pass.
local T = require("@tests/T")
local Br = require("@formats/archive/br")
local F = require("@formats")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/brotli")
local t = T.suite("br")
-- 1. the contract
t:eq(Br.name, "br", "name")
t:eq(Br.category, "archive", "category")
t:check(Br.caps.decode and not Br.caps.encode, "caps")
-- 2. fixtures
local n = 0
for i, c in Fx.cases do
if i % 4 == 0 then
local a, err = Br.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/file.txt.br" })
t:check(a, c.name .. ": " .. tostring(err))
t:check(a.kind == "archive" and a.format == "br" and a.meta.stream, c.name .. ": a stream archive")
local list = a:list()
t:eq(#list, 1, c.name .. ": one entry")
t:eq(list[1].name, "file.txt", c.name .. ": entry name")
t:eq(list[1].size, #Fx.corpora[c.corpus], c.name .. ": entry size")
t:eq(list[1].compressedSize, #c.data, c.name .. ": compressed size")
local data = a:read("file.txt")
t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], c.name .. ": entry data")
n += 1
end
end
t:note("%d streams", n)
-- default entry name
do
local a = Br.decode(Bytes.reader(buffer.fromstring(Fx.cases[5].data)))
t:eq(a:list()[1].name, "data", "default entry name")
end
-- 3. through the api: by sniff (with and without the extension) and by format name
do
local c = Fx.cases[40]
local a, err = F.load(c.data, { name = "x.br" })
t:check(a and a.format == "br", "F.load by sniff + extension: " .. tostring(err))
t:eq(a:list()[1].name, "x", "F.load names the entry")
local a2 = F.load(c.data)
t:check(a2 and a2.format == "br", "F.load by sniff alone")
local a3 = F.archive.load(c.data, { format = "br" })
t:check(a3 and a3.format == "br", "F.archive.load with format")
t:eq(F.detect(c.data, { name = "x.br" }), "br", "F.detect")
local _, e = F.save(a3, nil, { format = "br" })
t:check(e and e.code == Err.UNSUPPORTED, "no encoder: " .. tostring(e))
end
-- 4. sniff: garbage and plain text are rejected
do
local rand = T.rng(99)
local hits = 0
for _ = 1, 300 do
local len = 16 + rand(400)
local b = buffer.create(len)
for k = 0, len - 1 do
buffer.writeu8(b, k, rand(256))
end
if Br.sniff(Bytes.reader(b)) > 0 then
hits += 1
end
end
t:note("sniff accepted %d of 300 random buffers", hits)
t:check(hits <= 3, "sniff rejects random data")
t:eq(Br.sniff(Bytes.reader(buffer.fromstring("Hello, world! This is plain text.\n"))), 0, "sniff rejects text")
t:eq(Br.sniff(Bytes.reader(buffer.create(0))), 0, "sniff of nothing")
t:check(Br.sniff(Bytes.reader(buffer.fromstring(Fx.cases[40].data))) > 0, "sniff accepts a stream")
local _, e = Br.decode(Bytes.reader(buffer.fromstring("\x1b\xff\xff")))
t:check(e and Err.is(e) and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad data: " .. tostring(e))
end
-- 5. fuzz
do
local samples = {}
for i, c in Fx.cases do
if i % 23 == 0 and #c.data > 8 then
table.insert(samples, if #c.data > 8000 then string.sub(c.data, 1, 8000) else c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Br.decode(Bytes.reader(b))
end, samples, { mutations = 4, garbage = 500 })
t:fuzz("sniff", function(b: buffer)
return Br.sniff(Bytes.reader(b))
end, samples, { mutations = 2, garbage = 300 })
end
t:done()
+65
View File
@@ -0,0 +1,65 @@
-- archive/bz2 tests: the contract, sniff, a .bz2 as a one-entry single-stream archive (entry named after the file),
-- the api path (F.load by sniff, .tar.bz2 unwrap is the api's: covered once tar exists), errors, the fuzz pass.
-- Fixtures: tools/fixtures/bzip2.py.
local T = require("@tests/T")
local Bz2 = require("@formats/archive/bz2")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local F = require("@formats")
local Fx = require("@tests/gen/bzip2")
local t = T.suite("bz2")
t:eq(Bz2.name, "bz2", "name")
t:eq(Bz2.category, "archive", "category")
t:check(Bz2.caps.decode and not Bz2.caps.encode, "caps")
for _, c in Fx.cases do
t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
end
t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("BZh9hello"))), 0, "sniff: no block magic")
t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("\x1f\x8b\x08\x00"))), 0, "sniff: gzip")
do
local c = Fx.cases[1]
for _, x in Fx.cases do
if x.name == "text/l9" then
c = x
end
end
local a, err = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.bz2" })
t:check(a, "decode: " .. tostring(err))
t:check(a.kind == "archive" and a.format == "bz2" and a.meta.stream, "a single-stream archive")
local list = a:list()
t:eq(#list, 1, "one entry")
t:eq(list[1].name, "notes.txt", "entry named after the file")
t:eq(list[1].size, #Fx.corpora.text, "entry size")
t:eq(list[1].compressedSize, #c.data, "compressed size")
t:check(buffer.tostring((a:read("notes.txt"))) == Fx.corpora.text, "read")
local _, re = a:read("nope")
t:check(re and re.code == Err.ARG, "read of a missing entry")
local _, we = a:write()
t:check(we and we.code == Err.UNSUPPORTED, "read-only")
local a2 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "x.tbz2" })
t:eq(a2:list()[1].name, "x.tar", ".tbz2 -> .tar")
local a3 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)))
t:eq(a3:list()[1].name, "data", "no name -> data")
-- through the api
local v, ferr = F.load(c.data)
t:check(v and v.kind == "archive" and v.format == "bz2", "F.load sniffs bz2: " .. tostring(ferr))
t:eq(F.detect(c.data), "bz2", "F.detect")
local _, de = Bz2.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 100))))
t:check(de and de.code == Err.TRUNCATED, "truncated: " .. tostring(de))
end
local samples = {}
for i, c in Fx.cases do
if i % 6 == 0 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Bz2.decode(Bytes.reader(b))
end, samples, { mutations = 6, garbage = 300 })
t:done()
+93
View File
@@ -0,0 +1,93 @@
-- archive/gzip tests: members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members) decode
-- to one entry with the right name / mtime / data; the writer round-trips (buffer, string, one-entry archive, several
-- entries as a .tar.gz) and keeps FNAME / MTIME; the api; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py.
local T = require("@tests/T")
local F = require("@formats")
local Gzip = require("@formats/archive/gzip")
local Deflate = require("@formats/codecs/Deflate")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/tar")
local t = T.suite("gzip")
t:eq(Gzip.name, "gzip", "name")
for _, c in Fx.gzips do
local a, err = Gzip.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
t:check(a.meta.stream, c.name .. ": single stream")
local l = a:list()
t:eq(#l, 1, c.name .. ": one entry")
t:eq(l[1].name, c.entry, c.name .. ": entry name")
t:eq(l[1].mtime, if c.mtime > 0 then c.mtime else nil, c.name .. ": mtime")
t:eq(l[1].size, c.size, c.name .. ": size")
t:eq(Crc32.of((a:read(l[1].name))), c.crc, c.name .. ": data")
t:eq(F.detect(c.data), "gzip", c.name .. ": F.detect")
end
-- the file name names the entry when there is no FNAME
do
local a = F.load(Fx.gzips[2].data, { name = "dir/notes.txt.gz" })
t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
local b = F.load(Fx.gzips[2].data, { name = "x.tgz" })
t:eq(b:list()[1].name, "x.tar", ".tgz entry is a .tar")
end
-- writing
do
local text = string.rep("gzip round trip ", 500)
for _, level in { 0, 1, 6, 9 } do
local z = Gzip.encode(text, { level = level }) :: buffer
t:eq(buffer.tostring((Deflate.gunzip(z))), text, "string level " .. level)
end
local one = Gzip.new(text, "notes.txt")
one._byName["notes.txt"].mtime = 1600000000
local z = one:write()
local back = Gzip.decode(Bytes.reader(z :: buffer))
t:eq(back:list()[1].name, "notes.txt", "FNAME written")
t:eq(back:list()[1].mtime, 1600000000, "MTIME written")
t:eq(buffer.tostring((back:read("notes.txt"))), text, "one-entry archive round trip")
-- a decoded gzip saves back as gzip (its source format)
local g = F.load(Fx.gzips[1].data)
local again = F.load(F.save(g))
t:eq(again:list()[1].name, "story.txt", "F.save(gzip) keeps the name")
-- several entries: a .tar.gz, which the api unwraps
local multi = Gzip.new()
multi:add("a.txt", "A")
multi:add("b.txt", "BB")
local tgz = multi:write()
local tar = F.load(tgz)
t:eq(tar.format, "tar", "several entries write a .tar.gz")
t:eq(tar.meta.compression, "gzip", "unwrapped")
t:eq(buffer.tostring((tar:read("b.txt"))), "BB", ".tar.gz entry")
-- any archive converts: tar -> gzip -> tar
local tb = F.convert(Fx.tars[1].data, "gzip")
local t2 = F.load(tb)
t:eq(#t2:list(), #Fx.tars[1].entries, "tar -> tar.gz -> tar")
local _, e = Gzip.encode(text, { level = 12 })
t:check(e and e.code == Err.ARG, "bad level")
local _, e2 = Gzip.encode({ kind = "image" })
t:check(e2 and e2.code == Err.ARG, "not an archive")
end
-- errors
do
local d = Fx.gzips[1].data
local _, e1 = Gzip.decode(Bytes.reader(buffer.fromstring(string.sub(d, 1, 20))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local b = buffer.fromstring(d)
buffer.writeu8(b, #d - 6, bit32.bxor(buffer.readu8(b, #d - 6), 1))
local _, e2 = Gzip.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CHECKSUM, "crc: " .. tostring(e2))
end
local samples = {}
for _, c in Fx.gzips do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
return Gzip.decode(Bytes.reader(b))
end, samples, { mutations = 20 })
t:done()
+156
View File
@@ -0,0 +1,156 @@
-- archive/tar tests: archives from Python's tarfile (ustar / GNU / pax) and GNU tar (ustar / gnu / posix / v7) list
-- the same entries as tarfile reads (names, types, sizes, links, mtimes, modes, data CRCs); the writer produces the same
-- bytes as tarfile for the same entries in all three formats and round-trips; Archive values (add / read / write,
-- conversion of a gzip / any archive to tar); .tar.gz / .tgz / .tar.bz2 / .tar.xz / .tar.zst / .tar.br load through the
-- api as the tar inside; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py.
local T = require("@tests/T")
local F = require("@formats")
local TarF = require("@formats/archive/tar")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/tar")
local t = T.suite("tar")
t:eq(TarF.name, "tar", "name")
local function check(a: any, want: any, label: string)
local list = a:list()
t:eq(#list, #want, label .. ": entry count")
local by = {}
for _, e in list do
by[e.name] = e
end
for _, w in want do
local e = by[w.name]
t:check(e, label .. ": has " .. w.name)
t:eq(e.type, w.type, label .. ": " .. w.name .. " type")
t:eq(e.size, w.size, label .. ": " .. w.name .. " size")
t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime")
t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode")
t:eq(e.link, w.link, label .. ": " .. w.name .. " link")
t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir")
if w.crc then
local b, err = a:read(w.name)
t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err))
t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
end
end
end
-- 1. reading
for _, c in Fx.tars do
local a, err = TarF.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
check(a, c.entries, c.name)
t:eq(F.detect(c.data), "tar", c.name .. ": F.detect")
t:note("%-18s %2d entries", c.name, #c.entries)
end
-- 2. writing: byte-identical to Python's tarfile (which pads to 10240-byte records)
for _, w in Fx.writes do
local list = {}
for _, e in w.entries do
table.insert(list, {
name = e.name,
data = if e.data then buffer.fromstring(e.data) else nil,
dir = e.dir,
type = e.type,
link = e.link,
mode = e.mode or (if e.dir then 0x1ED else 0x1A4),
mtime = 1700000000,
uname = "user",
gname = "group",
})
end
local a = TarF.new()
for _, e in list do
a:add(e.name, e.data or "", { dir = e.dir, mtime = e.mtime, mode = e.mode })
local ent = a._byName[e.name]
ent.type, ent.link, ent.uname, ent.gname = e.type, e.link, e.uname, e.gname
end
local out, err = a:write({ format = w.format })
t:check(out, w.format .. ": write: " .. tostring(err))
local s = buffer.tostring(out :: buffer)
local ref = w.data
t:check(#s <= #ref and string.sub(ref, 1, #s) == s and not string.find(string.sub(ref, #s + 1), "[^%z]"), w.format .. ": bytes identical to tarfile")
local back = TarF.decode(Bytes.reader(out :: buffer))
t:eq(#back:list(), #list, w.format .. ": round trip count")
for _, e in w.entries do
if e.data then
t:eq(buffer.tostring((back:read(e.name))), e.data, w.format .. ": round trip " .. e.name)
end
end
end
-- 3. Archive values: add / read / write, other archives to tar
do
local a = TarF.new()
a:add("a.txt", "alpha", { mtime = 5 })
a:add("b/", "", { dir = true })
a:add("b/c.bin", buffer.fromstring("\0\1\2"))
a:add("a.txt", "replaced")
t:eq(#a:list(), 3, "add replaces by name")
local buf = F.save(a)
t:check(buf, "F.save(tar archive) uses the source format")
local back = F.load(buf)
t:eq(buffer.tostring(back:read("a.txt")), "replaced", "read back")
t:check(back:list()[2].dir, "directory entry")
local _, e = back:read("missing")
t:check(e and e.code == Err.ARG, "missing entry")
-- a gzip (single-stream archive) converts to a tar holding its one entry
local g = F.load(Fx.gzips[1].data)
local tb = F.save(g, nil, { format = "tar" })
local ta = F.load(tb)
t:eq(ta:list()[1].name, "story.txt", "gzip -> tar entry name")
t:eq(ta:list()[1].size, Fx.gzips[1].size, "gzip -> tar entry size")
end
-- 4. compressed tars through the api
for _, w in Fx.wrapped do
local a, err = F.load(w.data, { name = w.name })
t:check(a, w.name .. ": " .. tostring(err))
t:eq(a.format, "tar", w.name .. ": unwrapped to the tar")
t:eq(a.meta.compression, w.outer, w.name .. ": meta.compression")
check(a, Fx.innerEntries, w.name)
local outer = F.load(w.data, { name = w.name, unwrap = false })
t:eq(outer.format, w.outer, w.name .. ": unwrap = false keeps the outer archive")
t:eq(outer:list()[1].name, "a.tar", w.name .. ": inner entry named after the file")
end
-- 5. errors
do
local good = Fx.tars[1].data
local b = buffer.fromstring(good)
buffer.writeu8(b, 10, buffer.readu8(b, 10) + 1)
local _, e1 = TarF.decode(Bytes.reader(b))
t:check(e1 and e1.code == Err.CORRUPT, "first header checksum: " .. tostring(e1))
local _, e2 = TarF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 700))))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated data: " .. tostring(e2))
local _, e3 = TarF.encode({ kind = "image" })
t:check(e3 and e3.code == Err.ARG, "encode a non-archive")
local u = TarF.new()
u:add(string.rep("y", 120), "x")
local _, e4 = u:write({ format = "ustar" })
t:check(e4 and e4.code == Err.ARG, "ustar cannot hold a 120-byte name without a slash")
t:eq(TarF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 1024)))), 0, "zeros are not a tar")
end
local samples = {}
for _, c in Fx.tars do
if #c.data <= 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = TarF.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
a:write()
end
return a
end, samples, { mutations = 30, keepHeader = 0 })
t:done()
+78
View File
@@ -0,0 +1,78 @@
-- archive/xz tests: the contract, sniffing (.xz magic, conservative .lzma), every xz / .lzma fixture of
-- tools/fixtures/lzma.py read as a one-entry archive (entry names from opts.name), F.load through the registry, errors,
-- and the fuzz no-throw pass.
local T = require("@tests/T")
local Xz = require("@formats/archive/xz")
local F = require("@formats")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lzma")
local t = T.suite("xz")
t:eq(Xz.name, "xz", "name")
t:eq(Xz.category, "archive", "category")
t:check(Xz.caps.decode and not Xz.caps.encode, "caps")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
local n = 0
for _, c in Fx.cases do
if c.kind == "xz" or c.kind == "alone" then
local want = Fx.corpora[c.corpus]
t:check(Xz.sniff(reader(c.data)) > 0, c.name .. ": sniff")
local a, err = Xz.decode(reader(c.data), { name = "dir/file.txt." .. (if c.kind == "xz" then "xz" else "lzma") })
t:check(a, c.name .. ": " .. tostring(err))
local list = a:list()
t:eq(#list, 1, c.name .. ": one entry")
t:eq(list[1].name, "file.txt", c.name .. ": entry name")
t:eq(list[1].size, #want, c.name .. ": size")
t:check(a.meta.stream == true, c.name .. ": meta.stream")
local b = a:read("file.txt")
t:check(b and buffer.tostring(b) == want, c.name .. ": data")
n += 1
end
end
t:note("%d xz / lzma files", n)
-- sniff: not xz
t:eq(Xz.sniff(reader("PK\3\4 hello")), 0, "zip is not xz")
t:eq(Xz.sniff(reader("")), 0, "empty")
t:eq(Xz.sniff(reader(string.rep("\0", 40))), 0, "zeros are not .lzma")
-- through the api
do
local c = Fx.cases[1]
for _, x in Fx.cases do
if x.name == "text/xz-6" then
c = x
end
end
local a, err = F.load(c.data, { name = "notes.txz" })
t:check(a and a.kind == "archive" and a.format == "xz", "F.load: " .. tostring(err))
t:eq(a:list()[1].name, "notes.tar", "txz -> tar entry name")
t:eq(F.detect(c.data), "xz", "F.detect")
local a2 = F.archive.load(c.data)
t:eq(a2:list()[1].name, "data", "unnamed entry")
local _, e2 = F.save(a2, nil, { format = "xz" })
t:check(e2 and e2.code == Err.UNSUPPORTED, "xz is read-only: " .. tostring(e2))
local _, e3 = F.load(string.sub(c.data, 1, 100), { format = "xz" })
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
end
-- fuzz
do
local samples = {}
for i, c in Fx.cases do
if (c.kind == "xz" or c.kind == "alone") and i % 5 == 0 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Xz.decode(Bytes.reader(b), { maxBytes = 2 ^ 20 })
end, samples, { mutations = 6, garbage = 400 })
end
t:done()
+90
View File
@@ -0,0 +1,90 @@
-- archive/zst tests: the contract, sniff (zstd and skippable-frame magic), decode of zstd CLI output into a one-entry
-- single-stream archive (entry name from opts.name, size, read), F.load detection by content, read-only errors, and
-- the fuzz no-throw pass. Fixtures: tools/fixtures/zstd.py (shared with tests/codecs/zstd.luau).
local T = require("@tests/T")
local F = require("@formats")
local Zst = require("@formats/archive/zst")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/zstd")
local t = T.suite("zst")
-- contract
t:eq(Zst.name, "zst", "name")
t:eq(Zst.category, "archive", "category")
t:check(Zst.caps.decode and not Zst.caps.encode, "caps")
local function case(name: string): any
for _, c in Fx.cases do
if c.name == name then
return c
end
end
error("no case " .. name)
end
-- sniff
t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("text/l3").data))), 1, "sniff zstd")
t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("skipfirst/frames").data))), 0.5, "sniff skippable frame")
t:eq(Zst.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff other")
t:eq(Zst.sniff(Bytes.reader(buffer.create(0))), 0, "sniff empty")
-- decode: one entry, named after the file
for _, name in { "text/l3", "runs/ultra22", "multi/frames", "empty/l3", "big/l19" } do
local c = case(name)
local a, err = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.zst" })
t:check(a, name .. ": " .. tostring(err))
local list = a:list()
t:eq(#list, 1, name .. ": one entry")
t:eq(list[1].name, "notes.txt", name .. ": entry name")
t:eq(list[1].size, #Fx.corpora[c.corpus], name .. ": size")
t:eq(list[1].compressedSize, #c.data, name .. ": compressedSize")
t:check(a.meta.stream == true and a.kind == "archive" and a.format == "zst", name .. ": archive fields")
local data = a:read(list[1].name)
t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], name .. ": read")
end
do
local c = case("short/l3")
local a = Zst.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
t:eq(a:list()[1].name, "data", "no name -> data")
local a2 = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "backup.tzst" }) :: any
t:eq(a2:list()[1].name, "backup.tar", ".tzst -> .tar")
local _, e = a:read("nope")
t:check(e and e.code == Err.ARG, "missing entry")
local _, we = a:write()
t:check(we and we.code == Err.UNSUPPORTED, "read-only: " .. tostring(we))
-- inside a bigger buffer (the reader's range)
local big = buffer.create(#c.data + 10)
buffer.writestring(big, 5, c.data)
local a3 = Zst.decode(Bytes.reader(big, 5, #c.data)) :: any
t:check(a3 and buffer.tostring(a3:read("data")) == Fx.corpora.short, "reader range")
end
-- the api: detection by content, the name from opts
do
local c = case("text/l5")
local a, err = F.load(c.data, { name = "x/readme.md.zst" })
t:check(a and a.format == "zst", "F.load detects zst: " .. tostring(err))
t:eq(a:list()[1].name, "readme.md", "F.load entry name")
t:eq(F.detect(c.data), "zst", "F.detect")
local _, e = F.load(string.sub(c.data, 1, 30), { format = "zst" })
t:check(e and e.code == Err.TRUNCATED, "truncated through the api: " .. tostring(e))
local _, se = F.save(a, nil, { format = "zst" })
t:check(se and se.code == Err.UNSUPPORTED, "no encoder")
end
-- fuzz
do
local samples = {}
for i, c in Fx.cases do
if i % 11 == 0 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Zst.decode(Bytes.reader(b), { maxBytes = 1e6 })
end, samples, { mutations = 10, garbage = 500 })
end
t:done()
+126
View File
@@ -0,0 +1,126 @@
-- codecs/Brotli tests: every fixture stream (reference encoder: qualities 0..11, windows 10..24, text / font / generic
-- modes, large windows) decodes to its corpus; consumedEnd; offsets inside a bigger buffer; the static dictionary;
-- hand-made streams (empty, metadata, uncompressed); maxBytes; truncated / corrupted / random input returns nil, Err
-- and never throws. Fixtures: tools/fixtures/brotli.py.
local T = require("@tests/T")
local Brotli = require("@formats/codecs/Brotli")
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/brotli")
local t = T.suite("brotli")
-- the static dictionary
do
local d = Brotli.dictionary()
t:check(d and buffer.len(d) == 122784, "dictionary size")
t:eq(buffer.readstring(d :: buffer, 0, 8), "timedown", "dictionary starts with the length-4 words")
end
-- every case
local nbytes = 0
for _, c in Fx.cases do
local want = Fx.corpora[c.corpus]
local out, e = Brotli.decompress(c.data)
t:check(out ~= nil, c.name .. ": " .. tostring(e))
if buffer.tostring(out :: buffer) ~= want then
t:check(false, c.name .. ": output differs (" .. buffer.len(out :: buffer) .. " bytes, want " .. #want .. ")")
end
t:eq(e, #c.data, c.name .. ": consumed")
nbytes += #want
end
t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
-- at an offset inside a bigger buffer, with trailing bytes
do
local c = Fx.cases[30]
local big = buffer.create(#c.data + 13)
buffer.fill(big, 0, 0xAB)
buffer.writestring(big, 5, c.data)
local out, e = Brotli.decompress(big, 5, #c.data + 8)
t:check(out and buffer.tostring(out) == Fx.corpora[c.corpus] and e == 5 + #c.data, "at an offset")
end
-- hand-made streams
do
local bytes = T.bytes
-- WBITS 16 (bit 0), ISLAST, ISLASTEMPTY: 0b110 = 6
local o, e = Brotli.decompress(bytes({ 6 }))
t:check(o and buffer.len(o) == 0 and e == 1, "empty stream: " .. tostring(e))
-- 0x3b: python brotli's empty stream (WBITS 22)
local o2 = Brotli.decompress(bytes({ 0x3b }))
t:check(o2 and buffer.len(o2) == 0, "empty stream (WBITS 22)")
local _, e0 = Brotli.decompress(bytes({}))
t:check(e0 and e0.code == Err.TRUNCATED, "empty input is TRUNCATED")
-- an uncompressed meta-block "hi": WBITS 16 [0], ISLAST 0, MNIBBLES 4 [00], MLEN-1 = 1 [1000 0000 0000 0000],
-- ISUNCOMPRESSED 1, pad, "hi", then ISLAST 1 ISLASTEMPTY 1
-- bits LSB first: 0 | 0 | 00 | 1000 | 0000 0000 0000 | 1 -> byte0 = 0b00010000 = 0x10 (bits 0..7: 0,0,0,0,1,0,0,0)
-- byte1 = 0, byte2 = bits 16..23: 0,0,0,0 (rest of nibbles) 1 (ISUNCOMPRESSED) + pad 000 = 0x10
local o3 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68, 0x69, 0x03 }))
t:check(o3 and buffer.tostring(o3) == "hi", "uncompressed meta-block")
local _, e3 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68 }))
t:check(e3 and e3.code == Err.TRUNCATED, "truncated uncompressed block: " .. tostring(e3))
-- nonzero padding at the end
local _, e4 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68, 0x69, 0x0b }))
t:check(e4 and e4.code == Err.CORRUPT, "nonzero padding: " .. tostring(e4))
-- a metadata block (MNIBBLES 3, 1 byte length, 2 bytes skipped) before the last empty one
-- bits: WBITS 0 | ISLAST 0 | MNIBBLES 11 | reserved 0 | MSKIPBYTES 01 | len-1 = 1 (8 bits) | pad | 2 bytes | 11
-- 0,0,1,1,0,1,0, then 8 bits of 1: 1,0,0,0,0,0,0,0, pad to 16 -> byte0 = 0b0 1 0 1 1 0 0 = bits0..7: 0,0,1,1,0,1,0,1
local o5 = Brotli.decompress(bytes({ 0xAC, 0x00, 0xEE, 0xEE, 0x03 }))
t:check(o5 and buffer.len(o5) == 0, "metadata block skipped")
local ok, r1, r2 = pcall(Brotli.decompress, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
end
-- maxBytes
do
local c
for _, x in Fx.cases do
if x.corpus == "english" then
c = x
break
end
end
local _, e = Brotli.decompress(c.data, nil, nil, { maxBytes = 1000 })
t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e))
local big
for _, x in Fx.cases do
if string.find(x.name, "large", 1, true) then
big = x
break
end
end
local _, e2 = Brotli.decompress(big.data, nil, nil, { largeWindow = false })
t:check(e2 and e2.code == Err.UNSUPPORTED, "largeWindow = false: " .. tostring(e2))
end
-- a corrupted stream reports CORRUPT or TRUNCATED, never a wrong success with the right CRC
do
local bad = 0
for i, c in Fx.cases do
if i % 17 == 0 and #c.data > 20 then
local b = buffer.fromstring(c.data)
buffer.writeu8(b, #c.data // 2, bit32.bxor(buffer.readu8(b, #c.data // 2), 0x5A))
local out = Brotli.decompress(b)
if out and Crc32.of(out) == Crc32.of(buffer.fromstring(Fx.corpora[c.corpus])) then
bad += 1
end
end
end
t:eq(bad, 0, "corrupted streams never decode to the original")
end
-- truncation, corruption and garbage never throw
do
local samples = {}
for i, c in Fx.cases do
if i % 11 == 0 and #c.data > 8 then
table.insert(samples, if #c.data > 20000 then string.sub(c.data, 1, 20000) else c.data)
end
end
t:fuzz("decompress", function(b: buffer)
return Brotli.decompress(b)
end, samples, { mutations = 6, garbage = 3000 })
end
t:done()
+103
View File
@@ -0,0 +1,103 @@
-- codecs/Bzip2 tests: every fixture stream (Python bz2 = libbzip2, block sizes 1..9, RLE1 run edges, block-boundary
-- runs, random / skewed data, concatenated streams with trailing garbage) decodes exactly; offsets / consumedEnd;
-- maxBytes; CRC mismatches are Err.CHECKSUM; truncations are Err.TRUNCATED; the fuzz no-throw pass.
-- Fixtures: tools/fixtures/bzip2.py.
local T = require("@tests/T")
local Bzip2 = require("@formats/codecs/Bzip2")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/bzip2")
local t = T.suite("bzip2")
t:eq(Bzip2.crc(buffer.fromstring("123456789")), 0xFC891918, "CRC-32/BZIP2 check value")
local nbytes = 0
for _, c in Fx.cases do
local want = Fx.corpora[c.corpus]
local out, consumed = Bzip2.decompress(c.data)
t:check(out ~= nil, c.name .. ": " .. tostring(consumed))
t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs")
if c.name ~= "multi/trailing" then
t:eq(consumed, #c.data, c.name .. ": consumedEnd")
end
nbytes += #want
end
t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
local function case(name: string): any
for _, c in Fx.cases do
if c.name == name then
return c
end
end
error("no case " .. name)
end
-- inside a bigger buffer, at an offset
do
local c = case("text/l9")
local big = buffer.create(#c.data + 20)
buffer.fill(big, 0, 0xAB)
buffer.writestring(big, 7, c.data)
local out, consumed = Bzip2.decompress(big, 7, #c.data + 5)
t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset")
t:eq(consumed, 7 + #c.data, "consumedEnd at an offset")
end
-- maxBytes
do
local c = case("zeros/l9")
local _, e = Bzip2.decompress(c.data, nil, nil, { maxBytes = 1000 })
t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e))
local ok = Bzip2.decompress(c.data, nil, nil, { maxBytes = 250000 })
t:check(ok ~= nil, "maxBytes = exact size")
end
-- block CRC / stream CRC mismatches
do
local c = case("text/l9")
local b = buffer.fromstring(c.data)
-- block CRC sits at bytes 10..13 (after "BZh9" + 6 magic bytes)
buffer.writeu8(b, 11, bit32.bxor(buffer.readu8(b, 11), 0x10))
local _, e = Bzip2.decompress(b)
t:check(e and e.code == Err.CHECKSUM, "block CRC mismatch: " .. tostring(e))
local s = case("one/l9")
local b2 = buffer.fromstring(s.data)
local n = buffer.len(b2)
buffer.writeu8(b2, n - 2, bit32.bxor(buffer.readu8(b2, n - 2), 0x01))
local _, e2 = Bzip2.decompress(b2)
t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "stream CRC mismatch: " .. tostring(e2))
end
-- truncation -> TRUNCATED, bad magic -> CORRUPT, bad args -> ARG
do
local c = case("text/l1")
for _, cut in { 3, 10, 40, #c.data // 2, #c.data - 3 } do
local _, e = Bzip2.decompress(string.sub(c.data, 1, cut))
t:check(e and e.code == Err.TRUNCATED, "truncated at " .. cut .. ": " .. tostring(e))
end
local _, e = Bzip2.decompress("BZx9abcdefgh")
t:check(e and e.code == Err.CORRUPT, "bad magic")
local _, e2 = Bzip2.decompress(5 :: any)
t:check(e2 and e2.code == Err.ARG, "non-buffer")
local _, e3 = Bzip2.decompress("BZh9", -1)
t:check(e3 and e3.code == Err.ARG, "bad offset")
end
-- fuzz
do
local samples = {}
for i, c in Fx.cases do
if i % 4 == 0 and #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decompress", function(b: buffer)
return Bzip2.decompress(b)
end, samples, { mutations = 12, garbage = 1000, keepHeader = 4 })
t:fuzz("decompress (no header kept)", function(b: buffer)
return Bzip2.decompress(b)
end, samples, { mutations = 4, garbage = 200 })
end
t:done()
+142
View File
@@ -0,0 +1,142 @@
-- codecs/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp /
-- pb variants, raw LZMA1 / LZMA2, .lzma files, xz with every check type, BCJ and delta filters, multiple blocks,
-- multiple streams and stream padding) decodes to its corpus; consumed offsets; checksum / size / truncation errors;
-- maxBytes; the fuzz no-throw pass. Fixtures: tools/fixtures/lzma.py.
local T = require("@tests/T")
local Lzma = require("@formats/codecs/Lzma")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lzma")
local t = T.suite("lzma")
local function decode(c: any, b: buffer, opts: any?): (buffer?, any)
if c.kind == "raw" then
return Lzma.lzma(b, 0, nil, c.props, c.size, opts)
elseif c.kind == "raw2" then
return Lzma.lzma2(b, 0, nil, nil, nil, opts)
elseif c.kind == "alone" then
return Lzma.alone(b, 0, nil, opts)
end
return Lzma.xz(b, 0, nil, opts)
end
local nbytes = 0
for _, c in Fx.cases do
local want = Fx.corpora[c.corpus]
local b = buffer.fromstring(c.data)
local out, res = decode(c, b)
t:check(out ~= nil, c.name .. ": " .. tostring(res))
t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs")
if c.kind ~= "raw" then
t:eq(res, #c.data, c.name .. ": consumed")
end
nbytes += #want
end
t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
-- at an offset inside a bigger buffer, with trailing bytes
do
for _, c in Fx.cases do
if c.kind == "xz" and c.name == "text/xz-6" then
local big = buffer.create(#c.data + 11)
buffer.fill(big, 0, 0xAB)
buffer.writestring(big, 3, c.data)
local out, res = Lzma.xz(big, 3, #c.data)
t:check(out and buffer.tostring(out) == Fx.corpora.text and res == 3 + #c.data, "xz at an offset")
end
end
end
-- errors
do
local xz, xzc
for _, c in Fx.cases do
if c.name == "text/xz-check-crc32" then
xz = c
elseif c.name == "text/xz-6" then
xzc = c
end
end
-- the check field: the last bytes before the index; flip a data bit near the end of the block instead
local b = buffer.fromstring(xzc.data)
local n = buffer.len(b)
-- footer magic
buffer.writeu8(b, n - 1, 0)
local _, e1 = Lzma.xz(b)
t:check(e1 and (e1.code == Err.CORRUPT or e1.code == Err.CHECKSUM), "bad footer: " .. tostring(e1))
-- the stream header CRC
local b2 = buffer.fromstring(xz.data)
buffer.writeu8(b2, 8, bit32.bxor(buffer.readu8(b2, 8), 1))
local _, e2 = Lzma.xz(b2)
t:check(e2 and e2.code == Err.CHECKSUM, "header crc: " .. tostring(e2))
-- the block check (CRC-32 / CRC-64): flip a byte of the check field (found from the index: the 4 / 8 bytes before
-- the index indicator, which follows the block padding)
for _, c in { xz, xzc } do
local b3 = buffer.fromstring(c.data)
local n3 = buffer.len(b3)
local backward = (buffer.readu32(b3, n3 - 8) + 1) * 4
local indexAt = n3 - 12 - backward
buffer.writeu8(b3, indexAt - 1, bit32.bxor(buffer.readu8(b3, indexAt - 1), 0x10))
local _, e3 = Lzma.xz(b3)
t:check(e3 and e3.code == Err.CHECKSUM, c.name .. ": block check: " .. tostring(e3))
end
-- truncations are TRUNCATED or CORRUPT, never a throw
local _, e4 = Lzma.xz(buffer.fromstring(string.sub(xzc.data, 1, #xzc.data // 2)))
t:check(e4 and e4.code == Err.TRUNCATED, "truncated xz: " .. tostring(e4))
-- maxBytes
local _, e5 = Lzma.xz(xzc.data, nil, nil, { maxBytes = 1000 })
t:check(e5 and e5.code == Err.LIMIT, "maxBytes: " .. tostring(e5))
local ok, r1, r2 = pcall(Lzma.xz, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local _, e6 = Lzma.lzma("\0\0\0\0\0", 0, nil, "\255")
t:check(e6 and e6.code == Err.CORRUPT, "bad props byte: " .. tostring(e6))
end
-- raw LZMA with the size known: decoding stops at the size even without an end marker
do
for _, c in Fx.cases do
if c.kind == "raw" and #Fx.corpora[c.corpus] > 1000 then
local want = Fx.corpora[c.corpus]
local out = Lzma.lzma(c.data, 0, nil, { lc = 3, lp = 0, pb = 2 }, nil)
if c.name == c.corpus .. "/raw-lc3-lp0-pb2" then
t:check(out and buffer.tostring(out) == want, c.name .. ": table props, end marker")
end
local part = Lzma.lzma(c.data, 0, nil, c.props, 500)
t:check(part and buffer.tostring(part) == string.sub(want, 1, 500), c.name .. ": a prefix by size")
end
end
end
-- fuzz
do
local samples = {}
for i, c in Fx.cases do
if i % 7 == 0 and #c.data > 16 and #c.data < 40000 then
table.insert(samples, c)
end
end
local xs, as, rs = {}, {}, {}
for _, c in samples do
if c.kind == "xz" then
table.insert(xs, c.data)
elseif c.kind == "alone" then
table.insert(as, c.data)
else
table.insert(rs, c.data)
end
end
t:fuzz("xz", function(b: buffer)
return Lzma.xz(b, 0, nil, { maxBytes = 1 * 2 ^ 20 })
end, xs, { mutations = 6, garbage = 300 })
t:fuzz("alone", function(b: buffer)
return Lzma.alone(b, 0, nil, { maxBytes = 1 * 2 ^ 20 })
end, as, { mutations = 6, garbage = 300 })
t:fuzz("lzma2", function(b: buffer)
return Lzma.lzma2(b, 0, nil, nil, nil, { maxBytes = 1 * 2 ^ 20 })
end, rs, { mutations = 4, garbage = 1000 })
t:fuzz("lzma", function(b: buffer)
return Lzma.lzma(b, 0, nil, "\93", nil, { maxBytes = 1 * 2 ^ 20 })
end, rs, { mutations = 2, garbage = 1000 })
end
t:done()
+259
View File
@@ -0,0 +1,259 @@
-- codecs/Raster tests: exact coverage of axis-aligned rectangles at fractional positions; areas of circles; random
-- polygons and curves under random transforms against an independent 12 x 12 supersampled winding-number reference
-- (both fill rules); clipping, the stroker (width, caps, joins against analytic areas), fill() compositing and paint
-- functions; malformed paths never throw. Glyph rendering against FreeType is in tests/font/ttf.luau.
local T = require("@tests/T")
local R = require("@formats/codecs/Raster")
local Types = require("@formats/Types")
local t = T.suite("raster")
local function sum(m: any): number
if not m then
return 0
end
local s = 0
for i = 0, m.width * m.height - 1 do
s += buffer.readu8(m.coverage, i)
end
return s / 255
end
local function at(m: any, x: number, y: number): number
local i, j = x - m.x, y - m.y
if i < 0 or j < 0 or i >= m.width or j >= m.height then
return 0
end
return buffer.readu8(m.coverage, j * m.width + i)
end
-- 1. rectangles: exact per-pixel coverage
do
local p = R.path():rect(1.25, 2.5, 3.5, 2)
local m = R.mask(p) :: any
t:check(m, "rect mask")
t:eq(m.x, 1, "rect x")
t:eq(m.y, 2, "rect y")
t:eq(m.width, 4, "rect width")
t:eq(m.height, 3, "rect height")
-- row 2 covers y 2.5..3 (half), columns: 1 covers 0.75, 2-3 full, 4 covers 0.75
t:eq(at(m, 1, 2), math.floor(0.75 * 0.5 * 255 + 0.5), "corner pixel")
t:eq(at(m, 2, 2), math.floor(0.5 * 255 + 0.5), "top edge pixel")
t:eq(at(m, 2, 3), 255, "interior pixel")
t:eq(at(m, 4, 3), math.floor(0.75 * 255 + 0.5), "right edge pixel")
t:check(math.abs(sum(m) - 7) < 0.02, "rect area 7: " .. sum(m))
-- reversed orientation gives the same coverage
local q = R.path():moveTo(1.25, 2.5):lineTo(1.25, 4.5):lineTo(4.75, 4.5):lineTo(4.75, 2.5):close()
t:check(math.abs(sum(R.mask(q)) - 7) < 0.02, "reversed rect")
end
-- 2. circles: area pi r^2 (cubic approximation error ~ 2.7e-4 r)
for _, r in { 3, 10.5, 40 } do
local m = R.mask(R.path():ellipse(50.3, 50.7, r, r))
local a = sum(m)
t:check(math.abs(a - math.pi * r * r) < 0.01 * math.pi * r * r + 1, string.format("circle r=%g area %.2f", r, a))
end
-- 3. random paths against a supersampled winding reference
local function wind(polys: { { number } }, px: number, py: number): number
local w = 0
for _, poly in polys do
local n = #poly
local x0, y0 = poly[n - 1], poly[n]
for i = 1, n - 1, 2 do
local x1, y1 = poly[i], poly[i + 1]
if y0 <= py then
if y1 > py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) > 0 then
w += 1
end
elseif y1 <= py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) < 0 then
w -= 1
end
x0, y0 = x1, y1
end
end
return w
end
local rand = T.rng(7)
local function rf(a: number, b: number): number
return a + (b - a) * rand(100000) / 100000
end
local worst, total, count = 0, 0, 0
for case = 1, 24 do
local p = R.path()
for _ = 1, 1 + rand(3) do
p:moveTo(rf(0, 28), rf(0, 28))
for _ = 1, 2 + rand(5) do
local k = rand(3)
if k == 0 then
p:lineTo(rf(0, 28), rf(0, 28))
elseif k == 1 then
p:quadTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28))
else
p:cubicTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28))
end
end
p:close()
end
local ang = rf(0, 6.28)
local tr = R.multiply(R.translate(rf(-5, 5), rf(-5, 5)), R.multiply(R.rotate(ang), R.scale(rf(0.5, 1.2), rf(0.5, 1.2))))
local rule = if case % 2 == 0 then "evenodd" else "nonzero"
local clip = { 0, 0, 32, 32 }
local m = R.mask(p, { transform = tr, rule = rule :: any, clip = clip, tolerance = 0.05 })
local polys = R.flatten(p, tr, 0.01)
local err, n, mx = 0, 0, 0
for y = 0, 31 do
for x = 0, 31 do
local inside = 0
for sy = 0, 11 do
for sx = 0, 11 do
local w = wind(polys, x + (sx + 0.5) / 12, y + (sy + 0.5) / 12)
if (rule == "nonzero" and w ~= 0) or (rule == "evenodd" and w % 2 == 1) then
inside += 1
end
end
end
local want = inside / 144
local got = if m then at(m, x, y) / 255 else 0
local d = math.abs(got - want)
err += d
n += 1
if d > mx then
mx = d
end
end
end
total += err
count += n
worst = math.max(worst, err / n)
-- the area rules approximate where edges of opposite winding meet inside one pixel; on average they agree
t:check(err / n < 0.015, string.format("case %d (%s): mean abs error %.4f (max %.3f)", case, rule, err / n, mx))
end
t:note("random paths: mean abs coverage error %.4f (worst case mean %.4f) vs 12x12 supersampling", total / count, worst)
-- 4. even-odd vs nonzero on two nested squares of the same orientation
do
local p = R.path():rect(0, 0, 10, 10):rect(3, 3, 4, 4)
t:check(math.abs(sum(R.mask(p)) - 100) < 0.01, "nonzero fills the hole")
t:check(math.abs(sum(R.mask(p, { rule = "evenodd" })) - 84) < 0.01, "evenodd leaves the hole")
-- opposite orientation: a hole under both rules
local q = R.path():rect(0, 0, 10, 10):moveTo(3, 3):lineTo(3, 7):lineTo(7, 7):lineTo(7, 3):close()
t:check(math.abs(sum(R.mask(q)) - 84) < 0.01, "nonzero hole with opposite winding")
end
-- 5. clipping: a shape larger than the clip, partly outside on every side
do
local m = R.mask(R.path():rect(-20.5, -3.25, 100, 50), { clip = { 0, 0, 16, 8 } }) :: any
t:check(m and m.x == 0 and m.y == 0 and m.width == 16 and m.height == 8, "clipped bounds")
t:check(math.abs(sum(m) - 128) < 0.01, "clipped area " .. sum(m))
local m2 = R.mask(R.path():moveTo(-50, 4):lineTo(60, 4.5):lineTo(60, 6):lineTo(-50, 5):close(), { clip = { 0, 0, 10, 10 } })
t:check(m2 ~= nil, "a sliver crossing the clip")
t:check(R.mask(R.path():rect(20, 20, 5, 5), { clip = { 0, 0, 10, 10 } }) == nil, "outside the clip is empty")
end
-- 6. strokes: a line of length L and width w covers L*w (butt), L*w + w^2 (square), L*w + pi w^2/4 (round)
do
local line = R.path():moveTo(5, 10):lineTo(35, 10)
local a = sum(R.mask(R.stroke(line, { width = 4 })))
t:check(math.abs(a - 120) < 0.05, "butt stroke area " .. a)
a = sum(R.mask(R.stroke(line, { width = 4, cap = "square" })))
t:check(math.abs(a - 136) < 0.05, "square cap area " .. a)
a = sum(R.mask(R.stroke(line, { width = 4, cap = "round", tolerance = 0.01 })))
t:check(math.abs(a - (120 + math.pi * 4)) < 0.3, "round cap area " .. a)
-- a closed square outline of side 20, width 2, miter joins: outer 22^2 - inner 18^2
local sq = R.path():rect(10, 10, 20, 20)
a = sum(R.mask(R.stroke(sq, { width = 2 })))
t:check(math.abs(a - (484 - 324)) < 0.1, "mitered square outline " .. a)
a = sum(R.mask(R.stroke(sq, { width = 2, join = "bevel" })))
t:check(math.abs(a - (160 - 4 * 0.5)) < 0.1, "bevelled square outline " .. a)
a = sum(R.mask(R.stroke(sq, { width = 2, join = "round", tolerance = 0.01 })))
t:check(math.abs(a - (160 - 4 * (1 - math.pi / 4))) < 0.15, "rounded square outline " .. a)
-- a sharp zig-zag past the miter limit falls back to bevels; still covered without holes
local zig = R.path():moveTo(0, 0):lineTo(20, 2):lineTo(0, 4)
t:check(sum(R.mask(R.stroke(zig, { width = 1, miterLimit = 4 }))) > 30, "zig-zag stroke")
-- a curve stroke: a circle outline of radius 10, width 1: area 2 pi r w
a = sum(R.mask(R.stroke(R.path():ellipse(20, 20, 10, 10), { width = 1, join = "round", tolerance = 0.01 })))
t:check(math.abs(a - 2 * math.pi * 10) < 1, "circle outline " .. a)
end
-- 7. fill onto an image: colours, opacity, paint functions, compositing over existing pixels
do
local img = Types.Image.new(8, 8)
t:check(R.fill(img, R.path():rect(0, 0, 4, 8), { 255, 0, 0, 255 }), "fill red")
t:eq(buffer.readu32(img.pixels, 0), 0xFF0000FF, "opaque red pixel")
t:eq(buffer.readu32(img.pixels, 4 * 5), 0, "untouched pixel")
R.fill(img, R.path():rect(2, 0, 4, 8), { 0, 0, 255, 255 }, { opacity = 0.5 })
local p = 4 * 3
t:check(buffer.readu8(img.pixels, p) == 128 and buffer.readu8(img.pixels, p + 2) == 128 and buffer.readu8(img.pixels, p + 3) == 255, "half blue over red")
p = 4 * 5
t:check(buffer.readu8(img.pixels, p + 2) == 255 and buffer.readu8(img.pixels, p + 3) == 128, "half blue over transparent")
local calls = 0
R.fill(img, R.path():rect(0, 7, 8, 1), function(x: number, _y: number)
calls += 1
return x * 30, 0, 0, 255
end)
t:eq(calls, 8, "paint function per covered pixel")
t:eq(buffer.readu8(img.pixels, (7 * 8 + 2) * 4), math.floor(2.5 * 30 + 0.5), "paint at the pixel centre")
-- a transform scaling a unit square to the whole image
local img2 = Types.Image.new(4, 4)
R.fill(img2, R.path():rect(0, 0, 1, 1), { 0, 255, 0, 255 }, { transform = R.scale(4) })
t:eq(buffer.readu32(img2.pixels, 4 * 15), 0xFF00FF00, "transformed fill")
local inv = R.invert({ 2, 0, 0, 4, 3, 5 }) :: any
local x, y = R.apply(inv, R.apply({ 2, 0, 0, 4, 3, 5 }, 7, 11))
t:check(math.abs(x - 7) < 1e-9 and math.abs(y - 11) < 1e-9, "invert")
t:check(R.fill(img2, R.path():rect(0, 0, 1, 1), function()
error("boom")
end) == false, "a failing paint function returns false")
end
-- 8. malformed paths and huge / non-finite coordinates never throw
do
local bad: { any } = {
{ { op = "moveTo" }, { op = "lineTo", 1 }, { op = "quadTo", 1, 2, "x", 4 }, { op = "close" } },
{ { op = "lineTo", 0 / 0, 1 }, { op = "lineTo", 5, 5 }, { op = "lineTo", 0, 5 } },
{ { op = "moveTo", 0, 0 }, { op = "lineTo", math.huge, 1 }, { op = "lineTo", 1, 1e300 } },
{ { op = "moveTo", -1e6, -1e6 }, { op = "lineTo", 1e6, -1e6 }, { op = "lineTo", 1e6, 1e6 } },
{ 5, "x", { op = "cubicTo" }, { op = 3 } },
{},
}
local threw = 0
for i, p in bad do
for _, rule in { "nonzero", "evenodd" } do
local ok = pcall(function()
R.mask(p, { rule = rule :: any, clip = { 0, 0, 64, 64 } })
R.mask(p, { transform = { 0 / 0, 0, 0, 1, 0, 0 } })
R.stroke(p, { width = 3, cap = "round", join = "round" })
R.fill(Types.Image.new(16, 16), p, { 1, 2, 3, 4 }, { transform = { 1e9, 0, 0, 1e9, 0, 0 } })
end)
if not ok then
threw += 1
print(" threw on bad path " .. i)
end
end
end
local _, why = R.mask(R.path():rect(0, 0, 5000, 5000), { maxPixels = 1000 })
t:eq(why, "limit", "over maxPixels")
t:check(R.mask("nope") == nil and R.mask(nil) == nil, "non-paths")
-- random command soup through the fuzz helper: bytes -> commands
t:fuzz("mask", function(b: buffer)
local cmds = {}
local ops = { "moveTo", "lineTo", "quadTo", "cubicTo", "close" }
local i = 0
while i + 1 < buffer.len(b) do
local c: any = { op = ops[buffer.readu8(b, i) % 5 + 1] }
for k = 1, 6 do
local q = i + k
c[k] = if q < buffer.len(b) then (buffer.readi8(b, q)) * 0.73 else 0
end
table.insert(cmds, c)
i += 7
end
R.mask(cmds, { rule = if buffer.len(b) % 2 == 0 then "evenodd" else "nonzero", clip = { -10, -10, 40, 40 } })
return R.stroke(cmds, { width = 2.5, cap = "square", join = "miter" })
end, { "\0\1\2\3\4\5\6\1\9\9\9\9\9\9\2\1\2\3\4\5\6\3\1\2\3\4\5\6\4" }, { garbage = 400 })
t:eq(threw, 0, "malformed paths never throw")
end
t:done()
+115
View File
@@ -0,0 +1,115 @@
-- codecs/Zstd tests: every fixture case (the zstd CLI at levels 1..19, --ultra -22, --fast, --long, small windows,
-- with / without checksum and content size, multi-frame and skippable frames, empty input) decodes to its corpus;
-- offsets / consumedEnd; XXH64 vectors; checksum, limit and error codes; truncated / corrupted / random input never
-- throws. Fixtures: tools/fixtures/zstd.py.
local T = require("@tests/T")
local Zstd = require("@formats/codecs/Zstd")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/zstd")
local t = T.suite("zstd")
-- XXH64 reference values (xxhsum -H64)
do
local function hex(s: string): string
local hi, lo = Zstd.xxh64(buffer.fromstring(s))
return string.format("%08x%08x", hi, lo)
end
t:eq(hex(""), "ef46db3751d8e999", "xxh64 empty")
t:eq(hex("a"), "d24ec4f1a98c6e5b", "xxh64 a")
t:eq(hex("abc"), "44bc2cf5ad770999", "xxh64 abc")
t:eq(hex("Nobody inspects the spammish repetition"), "fbcea83c8a378bf1", "xxh64 sentence")
t:eq(hex(string.rep("0123456789", 10)), "f80e7b96315afffa", "xxh64 100 bytes")
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, consumed = Zstd.decompress(b)
t:check(out ~= nil, c.name .. ": " .. tostring(consumed))
t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs")
t:eq(consumed, #c.data, c.name .. ": consumed")
nbytes += #want
end
t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
local function case(name: string): any
for _, c in Fx.cases do
if c.name == name then
return c
end
end
error("no case " .. name)
end
-- at an offset inside a bigger buffer, and string input
do
local c = case("text/l3")
local big = buffer.create(#c.data + 20)
buffer.fill(big, 0, 0xAB)
buffer.writestring(big, 7, c.data)
local out, consumed = Zstd.decompress(big, 7, #c.data)
t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset")
t:eq(consumed, 7 + #c.data, "consumed at an offset")
t:check(buffer.tostring((Zstd.decompress(c.data))) == Fx.corpora.text, "string input")
t:check(Zstd.isFrame(buffer.fromstring(c.data)), "isFrame")
t:check(not Zstd.isFrame(buffer.fromstring("abcd")), "isFrame on other data")
-- trailing garbage is an error, as zstd -d says
local _, e = Zstd.decompress(c.data .. "junk")
t:check(e and e.code == Err.CORRUPT, "trailing garbage: " .. tostring(e))
end
-- checksum mismatch (the last 4 bytes), and verify = false skips it
do
local c = case("text/l9")
local b = buffer.fromstring(c.data)
local n = buffer.len(b)
buffer.writeu8(b, n - 1, bit32.bxor(buffer.readu8(b, n - 1), 0x10))
local out, e = Zstd.decompress(b)
t:check(out == nil and Err.is(e) and e.code == Err.CHECKSUM, "checksum mismatch: " .. tostring(e))
local out2 = Zstd.decompress(b, nil, nil, { verify = false })
t:check(out2 and buffer.tostring(out2) == Fx.corpora.text, "verify = false")
end
-- limits and arguments
do
local c = case("text/l3")
local _, e = Zstd.decompress(c.data, nil, nil, { maxBytes = 1000 })
t:check(e and e.code == Err.LIMIT, "maxBytes with a content size: " .. tostring(e))
local s = case("text/stdin")
local _, e2 = Zstd.decompress(s.data, nil, nil, { maxBytes = 1000 })
t:check(e2 and e2.code == Err.LIMIT, "maxBytes without a content size: " .. tostring(e2))
local ok, r1, r2 = pcall(Zstd.decompress, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local _, e3 = Zstd.decompress("")
t:check(e3 and e3.code == Err.TRUNCATED, "empty input is TRUNCATED: " .. tostring(e3))
local _, e4 = Zstd.decompress("\40\181\47\253\0")
t:check(e4 and e4.code == Err.TRUNCATED, "header only: " .. tostring(e4))
-- a dictionary ID: FHD with Dictionary_ID_flag = 1, single segment, then a 1-byte dictionary id and 1-byte size
local _, e5 = Zstd.decompress("\40\181\47\253\33\7\0\1\0\0")
t:check(e5 and e5.code == Err.UNSUPPORTED, "dictionary: " .. tostring(e5))
-- reserved block type
local _, e6 = Zstd.decompress("\40\181\47\253\32\0\7\0\0")
t:check(e6 and e6.code == Err.CORRUPT, "reserved block type: " .. tostring(e6))
end
-- truncation, corruption and garbage never throw
do
local samples = {}
for i, c in Fx.cases do
if i % 5 == 0 and #c.data > 8 and #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decompress", function(b: buffer)
return Zstd.decompress(b)
end, samples, { mutations = 12, garbage = 2000 })
-- keep the frame header intact so the mutations reach the blocks
t:fuzz("decompress (blocks)", function(b: buffer)
return Zstd.decompress(b, nil, nil, { verify = false, maxBytes = 1e6 })
end, samples, { mutations = 40, garbage = 0, keepHeader = 12, seed = 99 })
end
t:done()
+165
View File
@@ -0,0 +1,165 @@
-- containers/Tar and containers/Archive tests: hand-made headers for the edge cases the reference archives do not hit
-- (base-256 numbers, the historical signed checksum, GNU 'K' long links, pax 'g' global records, pax size overrides,
-- v7 headers without magic, a missing end-of-archive marker), the writer's GNU / pax extensions (long links, fractional
-- and negative mtimes), and Archive helpers (streamName, entries of foreign archive values, failing loaders).
local T = require("@tests/T")
local Tar = require("@formats/containers/Tar")
local Archive = require("@formats/containers/Archive")
local Err = require("@formats/core/Err")
local t = T.suite("containers/tar")
-- a header block built by hand
local function hdr(fields: { [string]: any }): buffer
local h = buffer.create(512)
buffer.writestring(h, 0, fields.name or "f")
buffer.writestring(h, 100, fields.mode or "0000644\0")
buffer.writestring(h, 124, fields.size or "00000000000\0")
buffer.writestring(h, 136, fields.mtime or "00000000000\0")
buffer.writestring(h, 156, fields.type or "0")
if fields.link then
buffer.writestring(h, 157, fields.link)
end
if fields.magic ~= false then
buffer.writestring(h, 257, "ustar\00000")
end
if fields.raw then
for at, v in fields.raw do
buffer.writeu8(h, at, v)
end
end
buffer.writestring(h, 148, " ")
local sum, signed = 0, 0
for i = 0, 511 do
local v = buffer.readu8(h, i)
sum += v
signed += if v >= 128 then v - 256 else v
end
buffer.writestring(h, 148, string.format("%06o\0 ", if fields.signed then signed % 0x40000 else sum))
return h
end
local function cat(parts: { any }): buffer
local s = {}
for _, p in parts do
table.insert(s, if type(p) == "string" then p else buffer.tostring(p))
end
return buffer.fromstring(table.concat(s))
end
local function block(s: string): string
return s .. string.rep("\0", (512 - #s % 512) % 512)
end
local END = string.rep("\0", 1024)
-- base-256 size (GNU), checksum with the signed sum, no end marker
do
local raw = { [124] = 0x80 }
for i = 125, 134 do
raw[i] = 0
end
raw[135] = 5
local b = cat({ hdr({ name = "big\200", raw = raw, signed = true }), block("hello") })
local list, err = Tar.read(b)
t:check(list, "base-256 / signed checksum: " .. tostring(err))
t:eq(list[1].size, 5, "base-256 size")
t:check(Tar.valid(b, 0), "valid() accepts the signed sum")
end
-- GNU long link ('K'), pax global + per-file records, v7 header
do
local rec = "21 path=from/pax.txt\n"
local glob = "20 uname=globaluser\n"
local b = cat({
hdr({ name = "././@LongLink", type = "K", size = string.format("%011o\0", 131) }),
block(string.rep("L", 130) .. "\0"),
hdr({ name = "sym", type = "2", link = "short" }),
hdr({ name = "pax_global", type = "g", size = string.format("%011o\0", #glob) }),
block(glob),
hdr({ name = "PaxHeaders/x", type = "x", size = string.format("%011o\0", #rec + 15) }),
block(rec .. "15 size=000003\n"),
hdr({ name = "ignored-name", size = "00000000077\0" }),
block("abc"),
hdr({ name = "v7file", magic = false, size = "00000000002\0", mtime = "12345670123\0" }),
block("v7"),
END,
})
local list, err = Tar.read(b)
t:check(list, "extensions: " .. tostring(err))
t:eq(#list, 3, "meta records are not entries")
t:eq(list[1].link, string.rep("L", 130), "GNU long link")
t:eq(list[2].name, "from/pax.txt", "pax path")
t:eq(list[2].size, 3, "pax size overrides the header")
t:eq(list[2].uname, "globaluser", "pax global record")
t:eq(list[3].name, "v7file", "v7 header")
t:eq(list[3].mtime, tonumber("12345670123", 8), "octal mtime")
t:eq(list[3].uname, "globaluser", "global records apply to later entries")
end
-- errors
do
local _, e1 = Tar.read(cat({ hdr({ size = "00000002000\0" }), block("x") }))
t:check(e1 and e1.code == Err.TRUNCATED, "data past the end: " .. tostring(e1))
local _, e2 = Tar.read(cat({ hdr({ type = "x", size = "00000000010\0" }), block("garbage!"), END }))
t:check(e2 and e2.code == Err.CORRUPT, "bad pax record: " .. tostring(e2))
local good = hdr({})
local bad = cat({ good, hdr({ name = "two" }) })
buffer.writeu8(bad, 513, 77)
local _, e3 = Tar.read(bad)
t:check(e3 and e3.code == Err.CHECKSUM, "second header checksum: " .. tostring(e3))
local list = Tar.read(buffer.create(0))
t:check(list and #list == 0, "empty input is an empty archive")
end
-- writer extensions
do
local long = string.rep("n", 120)
for _, fmt in { "gnu", "pax" } do
local out = Tar.write({
{ name = long, data = buffer.fromstring("x"), mtime = -5.25 },
{ name = "l", type = "2", link = string.rep("k", 150) },
}, { format = fmt :: any }) :: buffer
local list = Tar.read(out) :: any
t:eq(list[1].name, long, fmt .. ": long name")
t:eq(list[2].link, string.rep("k", 150), fmt .. ": long link")
if fmt == "pax" then
t:eq(list[1].mtime, -5.25, "pax fractional negative mtime")
end
end
local _, e = Tar.write({ { name = "" } })
t:check(e and e.code == Err.ARG, "empty name")
end
-- Archive helpers
do
t:eq(Archive.streamName({ name = "/x/y/notes.txt.gz" }, { "gz" }), "notes.txt", "streamName strips the extension")
t:eq(Archive.streamName({ name = "a.tbz2" }, { "bz2" }), "a.tar", "streamName .tbz2")
t:eq(Archive.streamName(nil, { "gz" }), "data", "streamName default")
t:eq(Archive.streamName({ name = "plain" }, { "gz" }), "plain", "streamName without an extension")
local foreign = {
kind = "archive",
list = function()
return { { name = "a", size = 1, dir = false } }
end,
read = function()
error("boom")
end,
}
local items = Archive.entries(foreign) :: any
t:eq(#items, 1, "entries of a foreign archive")
local b, e = items[1].read()
t:check(b == nil and e and e.code == Err.CORRUPT, "a throwing read() becomes an Err")
t:check(Archive.entries({ kind = "image" }) == nil, "not an archive")
local a = Archive.new("x")
Archive.put(a, { name = "f", size = 1, dir = false, load = function()
error("bad")
end })
local _, e2 = a:read("f")
t:check(e2 and e2.code == Err.CORRUPT, "a throwing loader becomes an Err")
local _, e3 = a:write()
t:check(e3 and e3.code == Err.UNSUPPORTED, "read-only archives")
end
t:fuzz("read", function(b: buffer)
return Tar.read(b)
end, { buffer.tostring(Tar.write({ { name = string.rep("p", 130), data = buffer.fromstring("abc") }, { name = "d", dir = true } }) :: buffer) }, { mutations = 60 })
t:done()
+166
View File
@@ -0,0 +1,166 @@
-- font/bmfont tests: the text, XML and binary descriptors (an independent Python writer, glyphs rendered by FreeType)
-- decode to the reference description; each variant re-encodes to every variant and decodes back unchanged (binary:
-- byte-identical to the Python writer); Font methods (glyphIndex / advance / kern); lazy pages through opts.loadPage
-- and the page PNG (glyph crops against FreeType's bitmaps); bake() from a TrueType font; errors; the fuzz pass.
-- Fixtures: tools/fixtures/bmfont.py.
local T = require("@tests/T")
local F = require("@formats")
local Bmfont = require("@formats/font/bmfont")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/bmfont")
local t = T.suite("bmfont")
t:eq(Bmfont.name, "bmfont", "name")
local CHAR_KEYS = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }
local function sameDesc(got: any, want: any, label: string, faceQuotes: boolean)
local face = want.info.face
if not faceQuotes then
face = string.gsub(face, '"', "")
end
t:eq(got.info.face, face, label .. ": face")
for _, k in { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } do
t:eq(got.info[k], want.info[k], label .. ": info." .. k)
end
for i = 1, 4 do
t:eq(got.info.padding[i], want.info.padding[i], label .. ": padding")
end
t:eq(got.info.spacing[1] .. "," .. got.info.spacing[2], want.info.spacing[1] .. "," .. want.info.spacing[2], label .. ": spacing")
for k, v in want.common do
t:eq(got.common[k], v, label .. ": common." .. k)
end
t:eq(#got.pages, #want.pages, label .. ": pages")
t:eq(got.pages[1], want.pages[1], label .. ": page file")
t:eq(#got.chars, #want.chars, label .. ": char count")
for i, c in want.chars do
for _, k in CHAR_KEYS do
t:eq(got.chars[i][k], c[k], string.format("%s: char %d %s", label, c.id, k))
end
end
t:eq(#got.kernings, #want.kernings, label .. ": kerning count")
for i, k in want.kernings do
local g = got.kernings[i]
t:check(g[1] == k[1] and g[2] == k[2] and g[3] == k[3], label .. ": kerning " .. i)
end
end
-- 1. the three encodings
local fonts = {}
for _, v in { "text", "xml", "binary" } do
local f, err = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx[v])))
t:check(f, v .. ": " .. tostring(err))
t:eq(f.meta.variant, v, v .. ": variant")
sameDesc(f.meta.bmfont, Fx.desc, v, v ~= "text")
fonts[v] = f
t:eq(F.detect(Fx[v]), "bmfont", v .. ": F.detect")
end
-- 2. re-encode every variant to every variant
for from, f in fonts do
for _, to in { "text", "xml", "binary" } do
local b, err = Bmfont.encode(f, { variant = to :: any })
t:check(b, from .. " -> " .. to .. ": " .. tostring(err))
local back = Bmfont.decode(Bytes.reader(b :: buffer))
t:check(back and back.meta.variant == to, from .. " -> " .. to .. ": decodes")
sameDesc(back.meta.bmfont, Fx.desc, from .. " -> " .. to, from ~= "text" and to ~= "text")
if from == "binary" and to == "binary" then
t:eq(buffer.tostring(b :: buffer), Fx.binary, "binary re-encode is byte-identical to the reference writer")
end
end
end
t:eq(buffer.tostring(F.save(fonts.xml, nil, { format = "fnt" })):sub(1, 5), "<?xml", "F.save keeps the variant")
-- 3. Font methods
do
local f = fonts.text
local gA, gV = f:glyphIndex(65), f:glyphIndex(86)
t:check(gA > 0 and gV > 0, "glyphIndex")
t:eq(f:glyphIndex(0x1F600), 0, "missing glyph")
t:eq(f:advance(gA), Fx.desc.chars[gA].xadvance, "advance")
t:eq(f:kern(gA, gV), Fx.desc.kernings[2][3], "kern A V")
t:eq(f:kern(gV, gA), Fx.desc.kernings[9][3], "kern V A")
t:eq(f.unitsPerEm, 24, "size")
t:check(f:outline(gA) == nil, "bitmap fonts have no outline")
t:check(f:rasterize(gA, 24) == nil, "no pages loaded yet")
local ok, e = f:loadPages()
t:check(not ok and e and e.code == Err.ARG, "loadPages without a loader")
end
-- 4. lazy pages: the api attaches opts.loadPage; the PNG goes through F.load
do
local asked = {}
local f = F.load(Fx.binary, {
loadPage = function(file: string)
table.insert(asked, file)
return Fx.page
end,
})
t:check(f and f.pages == nil and #asked == 0, "pages are lazy")
local crcs = {}
for _, c in Fx.crops do
crcs[c.id] = c.crc
end
local n = 0
for _, c in Fx.desc.chars do
local img = f:rasterize(f:glyphIndex(c.id), 24)
t:check(img and img.format == "alpha8" and img.width == c.width, "rasterize " .. c.id)
t:eq(Crc32.of(img.pixels), crcs[c.id], "glyph crop " .. c.id .. " = FreeType's bitmap")
t:eq(img.meta.left, c.xoffset, "left")
n += 1
end
t:eq(#asked, 1, "page loaded once")
t:eq(asked[1], "karla_0.png", "page file name")
t:note("%d glyph crops from the lazily loaded page match FreeType", n)
end
-- 5. bake from a TrueType font
do
local ttf = F.font.load(Fx.ttf)
t:check(ttf, "ttf loads")
local baked, err = Bmfont.bake(ttf, { px = 20, chars = "Hello, wörld! AV" })
t:check(baked, "bake: " .. tostring(err))
t:eq(#baked.meta.bmfont.chars, 13, "unique characters baked")
t:check(baked.pages and #baked.pages == 1, "one page")
local g = baked:glyphIndex(string.byte("H"))
local a = baked:rasterize(g, 20)
local b = ttf:rasterize(ttf:glyphIndex(string.byte("H")), 20)
t:check(a and b and a.width == b.width and a.height == b.height, "baked glyph size")
t:eq(Crc32.of(a.pixels), Crc32.of(b.pixels), "baked glyph pixels = rasterize")
t:eq(a.meta.left, b.meta.left, "baked left")
t:eq(a.meta.top, b.meta.top, "baked top")
local enc = F.save(baked, nil, { format = "bmfont", variant = "binary" })
local back = F.load(enc)
t:check(back and #back.meta.bmfont.chars == 13, "baked font round trip")
-- an outline font saved as fnt is baked on the way
local fnt = F.convert(Fx.ttf, "fnt", { px = 16 })
t:check(fnt and string.sub(buffer.tostring(fnt), 1, 9) == "info face", "F.convert ttf -> fnt (text)")
end
-- 6. errors and validation
do
local _, e1 = Bmfont.decode(Bytes.reader(buffer.fromstring("BMF\2")))
t:check(e1 and e1.code == Err.UNSUPPORTED, "binary version 2: " .. tostring(e1))
local _, e2 = Bmfont.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.binary, 1, 40))))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated binary: " .. tostring(e2))
local _, e3 = Bmfont.decode(Bytes.reader(buffer.fromstring("hello")))
t:check(e3 and e3.code == Err.CORRUPT, "not a descriptor")
local f = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx.text)))
f.meta.bmfont.chars[3].x = 1.5
local _, e4 = Bmfont.encode(f)
t:check(e4 and e4.code == Err.ARG, "fractional field: " .. tostring(e4))
local _, e5 = Bmfont.encode({ kind = "image" })
t:check(e5 and e5.code == Err.ARG, "not a font")
end
t:fuzz("decode", function(b: buffer)
local f = Bmfont.decode(Bytes.reader(b))
if f then
Bmfont.encode(f, { variant = "binary" })
end
return f
end, { Fx.binary, string.sub(Fx.text, 1, 3000), string.sub(Fx.xml, 1, 3000) }, { mutations = 40 })
t:done()
+237
View File
@@ -0,0 +1,237 @@
-- font/ttf tests (and codecs/TrueType, codecs/Cff): for the imgui-luau TrueType fonts, Source Sans 3 (CFF), a
-- 'kern'-table font and a collection: metrics, names, cmap samples, advances / side bearings, outline control boxes and
-- areas against fontTools; kerning against HarfBuzz (GPOS) and FreeType ('kern'); rasterize() against FreeType's
-- unhinted renders (PSNR); the api; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py.
local T = require("@tests/T")
local F = require("@formats")
local Ttf = require("@formats/font/ttf")
local Raster = require("@formats/codecs/Raster")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/fonts")
local t = T.suite("ttf")
t:eq(Ttf.name, "ttf", "name")
t:check(table.find(Ttf.extensions, "otf") and table.find(Ttf.extensions, "ttc"), "extensions")
-- shoelace area of the flattened outline (font units)
local function area(cmds: any): number
local polys = Raster.flatten(cmds, nil, 0.02)
local a = 0
for _, p in polys do
local n = #p
local x0, y0 = p[n - 1], p[n]
for i = 1, n - 1, 2 do
a += x0 * p[i + 1] - p[i] * y0
x0, y0 = p[i], p[i + 1]
end
end
return a / 2
end
local function psnr(img: any, r: any): (number, number)
-- union of both bitmaps, aligned on the pen position
local ax0, ay0 = img.meta.left, -img.meta.top
local bx0, by0 = r.left, -r.top
local x0, y0 = math.min(ax0, bx0), math.min(ay0, by0)
local x1, y1 = math.max(ax0 + img.width, bx0 + r.w), math.max(ay0 + img.height, by0 + r.h)
local se, n, ink = 0, 0, 0
for y = y0, y1 - 1 do
for x = x0, x1 - 1 do
local a, b = 0, 0
local ix, iy = x - ax0, y - ay0
if ix >= 0 and iy >= 0 and ix < img.width and iy < img.height then
a = buffer.readu8(img.pixels, iy * img.width + ix)
end
local jx, jy = x - bx0, y - by0
if jx >= 0 and jy >= 0 and jx < r.w and jy < r.h then
b = string.byte(r.pixels, jy * r.w + jx + 1)
end
se += (a - b) * (a - b)
ink += b
n += 1
end
end
if n == 0 or se == 0 then
return 99, ink
end
return 10 * math.log10(255 * 255 / (se / n)), ink
end
local fonts: { [string]: any } = {}
local worstPsnr, sumPsnr, nPsnr = 99, 0, 0
for _, c in Fx.fonts do
local font, err = Ttf.decode(Bytes.reader(buffer.fromstring(c.data)), { index = c.index })
t:check(font, c.name .. ": decode: " .. tostring(err))
fonts[c.name] = font
t:eq(font.kind, "font", c.name .. ": kind")
t:eq(font.unitsPerEm, c.upem, c.name .. ": unitsPerEm")
t:eq(font.ascent, c.ascent, c.name .. ": ascent")
t:eq(font.descent, c.descent, c.name .. ": descent")
t:eq(font.lineGap, c.lineGap, c.name .. ": lineGap")
t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": numGlyphs")
t:eq(font.info.family, c.family, c.name .. ": family")
t:eq(font.info.style, c.style, c.name .. ": style")
t:eq(font.info.fullName, c.fullName, c.name .. ": fullName")
t:eq(font.meta.outlines, if c.cff then "cff" else "truetype", c.name .. ": outlines")
if c.weight > 0 then
t:eq(font.meta.os2.weightClass, c.weight, c.name .. ": weight")
end
for _, m in c.cmap do
t:eq(font:glyphIndex(m[1]), m[2], string.format("%s: cmap U+%04X", c.name, m[1]))
end
local maxAreaErr = 0
for _, g in c.glyphs do
local gid = g.gid
t:eq(font:advance(gid), g.adv, c.name .. ": advance " .. gid)
if not c.cff then
t:eq(font:leftSideBearing(gid), g.lsb, c.name .. ": lsb " .. gid)
end
local cmds = font:outline(gid)
t:check(cmds, c.name .. ": outline " .. gid .. ": " .. tostring(font.meta.lastError))
local x0, y0, x1, y1 = font:bounds(gid)
if g.box then
t:check(x0 ~= nil, c.name .. ": glyph " .. gid .. " has bounds")
local b = g.box
local ok = math.abs(x0 - b[1]) < 1e-6 and math.abs(y0 - b[2]) < 1e-6 and math.abs(x1 - b[3]) < 1e-6 and math.abs(y1 - b[4]) < 1e-6
t:check(ok, string.format("%s: glyph %d control box %g %g %g %g, want %g %g %g %g", c.name, gid, x0 or 0, y0, x1, y1, b[1], b[2], b[3], b[4]))
local a = area(cmds)
-- fontTools' AreaPen: positive for counter-clockwise contours, as the shoelace here
local d = math.abs(a - g.area) / math.max(1, math.abs(g.area))
maxAreaErr = math.max(maxAreaErr, d)
t:check(d < 0.002 or math.abs(a - g.area) < 2, string.format("%s: glyph %d area %.1f, want %.1f", c.name, gid, a, g.area))
else
t:check(x0 == nil, c.name .. ": empty glyph " .. gid)
end
end
for _, k in c.kern do
t:eq(font:kern(k[1], k[2]), k[3], string.format("%s: kern %d %d", c.name, k[1], k[2]))
end
local worst = 99
for _, r in c.renders do
local img = font:rasterize(r.gid, r.px)
t:check(img and img.format == "alpha8", c.name .. ": rasterize " .. r.gid)
local p, ink = psnr(img, r)
worst = math.min(worst, p)
sumPsnr += p
nPsnr += 1
t:check(p > 28 or ink == 0, string.format("%s: glyph %d at %d px: PSNR %.1f dB vs FreeType", c.name, r.gid, r.px, p))
t:check(math.abs(img.meta.advance - font:advance(r.gid) * r.px / font.unitsPerEm) < 1e-9, "advance in pixels")
end
worstPsnr = math.min(worstPsnr, worst)
t:note("%-20s %4d glyphs, %3d cmap, %3d kern pairs, area err %.5f, worst PSNR %.1f dB", c.name, #c.glyphs, #c.cmap, #c.kern, maxAreaErr, worst)
end
t:note("rasterize vs FreeType: mean PSNR %.1f dB, worst %.1f dB over %d renders", sumPsnr / nPsnr, worstPsnr, nPsnr)
-- kerning is non-trivial in at least the GPOS and 'kern' fonts
do
local nz = 0
for _, c in Fx.fonts do
for _, k in c.kern do
if k[3] ~= 0 then
nz += 1
end
end
end
t:check(nz > 20, "fixtures have non-zero kerning pairs: " .. nz)
end
-- collections
if Fx.ttc then
local b = buffer.fromstring(Fx.ttc.data)
t:eq(Ttf.count(Bytes.reader(b)), Fx.ttc.count, "collection count")
local f0 = Ttf.decode(Bytes.reader(b))
t:check(f0 and f0.meta.collection and f0.meta.collection.count == 2, "collection font 0")
local _, e = Ttf.decode(Bytes.reader(b), { index = 5 })
t:check(e and e.code == Err.ARG, "collection index out of range")
local f1 = F.load(b, { index = 1 })
t:check(f1 and f1.info.family == fonts["collection-1"].info.family, "F.load with opts.index")
end
-- the api: detection by content, the font facade
do
local c = Fx.fonts[1]
t:eq(F.detect(c.data), "ttf", "F.detect")
local f = F.font.load(c.data)
t:check(f and f.kind == "font" and f.meta.source.format == "ttf", "F.font.load")
local g = f:glyphIndex(65)
t:check(g > 0 and f:advance(g) > 0, "glyph A")
t:eq(f:glyphIndex(-1), 0, "negative code point")
t:eq(f:glyphIndex(0.5), 0, "fractional code point")
t:check(f:outline(-1) == nil and f:outline(1e9) == nil and f:rasterize(g, -3) == nil, "bad glyph / size")
local sp = f:rasterize(f:glyphIndex(32), 20)
t:check(sp and sp.width == 0, "space rasterizes to an empty image")
local _, e = F.save(f, nil, { format = "ttf" })
t:check(e and e.code == Err.UNSUPPORTED, "ttf is read-only")
end
-- errors
do
local _, e1 = Ttf.decode(Bytes.reader(buffer.fromstring("OTTO")))
t:check(e1 and e1.code == Err.TRUNCATED, "short file: " .. tostring(e1))
local _, e2 = Ttf.decode(Bytes.reader(buffer.fromstring("\0\1\0\0\0\0\0\0\0\0\0\0")))
t:check(e2 and e2.code == Err.CORRUPT, "no tables: " .. tostring(e2))
t:eq(Ttf.sniff(Bytes.reader(buffer.fromstring("wOFF"))), 0, "sniff rejects woff")
end
-- fuzz: whole-font mutations, then glyph access on whatever still parses
do
local samples = {}
for _, c in Fx.fonts do
if #c.data < 60000 then
table.insert(samples, c.data)
end
end
local rand = T.rng(99)
t:fuzz("decode + glyphs", function(b: buffer)
local f = Ttf.decode(Bytes.reader(b))
if f then
for _ = 1, 12 do
local g = rand(f.numGlyphs + 2)
f:outline(g)
f:advance(g)
f:kern(g, rand(f.numGlyphs + 1))
f:glyphIndex(rand(70000))
f:rasterize(g, 9)
end
end
return f
end, samples, { mutations = 30, garbage = 200 })
-- mutations inside the glyph data only (the header survives, so the outline parsers see the damage)
local hits = 0
local cff = Fx.fonts[#Fx.fonts - 2] -- (any font: the loop below picks the CFF one)
for _, c in Fx.fonts do
if c.cff then
cff = c
end
end
local tries = 0
for _, c in { Fx.fonts[1], cff } do
local base = buffer.fromstring(c.data)
local n = buffer.len(base)
for _ = 1, 40 do
local b = buffer.create(n)
buffer.copy(b, 0, base)
for _ = 1, 20 do
local p = n // 4 + rand(n - n // 4)
buffer.writeu8(b, p, rand(256))
end
tries += 1
local ok = pcall(function()
local f = Ttf.decode(Bytes.reader(b))
if f then
for g = 0, math.min(f.numGlyphs, 300) - 1 do
f:outline(g)
f:rasterize(g, 8)
end
hits += 1
end
end)
t:check(ok, c.name .. ": glyph-data mutation threw")
end
end
t:note("glyph-data mutations: %d fonts (%d parsed), every glyph outlined + rasterized, none threw", tries, hits)
end
t:done()
+100
View File
@@ -0,0 +1,100 @@
-- font/woff tests: every fixture font as WOFF 1.0 (fontTools, zlib tables) decodes to the same font as the sfnt itself (font/ttf, checked against
-- fontTools / FreeType in tests/font/ttf.luau): metrics, names, every glyph's outline, advance and side bearing,
-- cmap and kerning samples; rasterize works; the api detects it; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py.
local T = require("@tests/T")
local F = require("@formats")
local Woff = require("@formats/font/woff")
local Ttf = require("@formats/font/ttf")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/fonts")
local t = T.suite("woff")
t:eq(Woff.name, "woff", "name")
local function same(a: any, b: any, label: string)
for _, k in { "unitsPerEm", "ascent", "descent", "lineGap", "numGlyphs" } do
t:eq(a[k], b[k], label .. ": " .. k)
end
t:eq(a.info.family, b.info.family, label .. ": family")
t:eq(a.info.fullName, b.info.fullName, label .. ": fullName")
for g = 0, a.numGlyphs - 1 do
t:eq(a:advance(g), b:advance(g), label .. ": advance " .. g)
t:eq(a:leftSideBearing(g), b:leftSideBearing(g), label .. ": lsb " .. g)
local oa, ob = a:outline(g), b:outline(g)
t:check(oa and ob and #oa == #ob, label .. ": outline " .. g .. " command count")
for i, c in oa do
local d = ob[i]
local ok = c.op == d.op and #c == #d
for j = 1, #c do
ok = ok and c[j] == d[j]
end
if not ok then
t:check(false, string.format("%s: glyph %d command %d differs", label, g, i))
end
end
end
for cp = 0, 0x2FF do
t:eq(a:glyphIndex(cp), b:glyphIndex(cp), label .. ": cmap " .. cp)
end
local ga, gv = a:glyphIndex(65), a:glyphIndex(86)
t:eq(a:kern(ga, gv), b:kern(ga, gv), label .. ": kern A V")
end
local refs: { [string]: string } = {}
for _, c in Fx.fonts do
refs[c.name] = c.data
end
local samples = {}
local n = 0
for _, w in Fx.woff do
for _, key in { "woff" } do
local data = w[key]
local font, err = Woff.decode(Bytes.reader(buffer.fromstring(data)))
t:check(font, w.name .. " (" .. key .. "): " .. tostring(err))
t:eq(font.meta.source.format, "woff", "source format")
local ref = assert(Ttf.decode(Bytes.reader(buffer.fromstring(refs[w.name]))))
same(font, ref, w.name .. " (" .. key .. ")")
local img = font:rasterize(font:glyphIndex(65), 24)
t:check(img and img.width > 0, w.name .. ": rasterize")
n += 1
if #data < 40000 then
table.insert(samples, data)
end
t:note("%-20s %-7s %7d bytes (sfnt %d), %d glyphs identical", w.name, key, #data, #refs[w.name], font.numGlyphs)
end
end
t:check(n >= 6, "fixture count")
-- the api
do
local data = Fx.woff[1].woff
t:eq(F.detect(data), "woff", "F.detect")
local f = F.font.load(data)
t:check(f and f.kind == "font", "F.font.load")
t:eq(Woff.sniff(Bytes.reader(buffer.fromstring("wOFF"))) + Woff.sniff(Bytes.reader(buffer.fromstring("wOF2"))), 1, "sniff")
end
-- errors
do
local data = Fx.woff[1].woff
local _, e1 = Woff.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, 30))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated header: " .. tostring(e1))
local _, e2 = Woff.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, #data - 100))))
t:check(e2 ~= nil, "truncated data: " .. tostring(e2))
local _, e3 = Woff.decode(Bytes.reader(buffer.fromstring("ttcf" .. string.rep("\0", 60))))
t:check(e3 and e3.code == Err.CORRUPT, "bad signature: " .. tostring(e3))
end
t:fuzz("decode", function(b: buffer)
local f = Woff.decode(Bytes.reader(b))
if f then
for g = 0, math.min(f.numGlyphs, 40) - 1 do
f:outline(g)
f:rasterize(g, 8)
end
end
return f
end, samples, { mutations = 25, garbage = 200 })
t:done()
+100
View File
@@ -0,0 +1,100 @@
-- font/woff2 tests: every fixture font as WOFF2 (fontTools: the default glyf / loca transform, and with the hmtx transform too) decodes to the same font as the sfnt itself (font/ttf, checked against
-- fontTools / FreeType in tests/font/ttf.luau): metrics, names, every glyph's outline, advance and side bearing,
-- cmap and kerning samples; rasterize works; the api detects it; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py.
local T = require("@tests/T")
local F = require("@formats")
local Woff2 = require("@formats/font/woff2")
local Ttf = require("@formats/font/ttf")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/fonts")
local t = T.suite("woff2")
t:eq(Woff2.name, "woff2", "name")
local function same(a: any, b: any, label: string)
for _, k in { "unitsPerEm", "ascent", "descent", "lineGap", "numGlyphs" } do
t:eq(a[k], b[k], label .. ": " .. k)
end
t:eq(a.info.family, b.info.family, label .. ": family")
t:eq(a.info.fullName, b.info.fullName, label .. ": fullName")
for g = 0, a.numGlyphs - 1 do
t:eq(a:advance(g), b:advance(g), label .. ": advance " .. g)
t:eq(a:leftSideBearing(g), b:leftSideBearing(g), label .. ": lsb " .. g)
local oa, ob = a:outline(g), b:outline(g)
t:check(oa and ob and #oa == #ob, label .. ": outline " .. g .. " command count")
for i, c in oa do
local d = ob[i]
local ok = c.op == d.op and #c == #d
for j = 1, #c do
ok = ok and c[j] == d[j]
end
if not ok then
t:check(false, string.format("%s: glyph %d command %d differs", label, g, i))
end
end
end
for cp = 0, 0x2FF do
t:eq(a:glyphIndex(cp), b:glyphIndex(cp), label .. ": cmap " .. cp)
end
local ga, gv = a:glyphIndex(65), a:glyphIndex(86)
t:eq(a:kern(ga, gv), b:kern(ga, gv), label .. ": kern A V")
end
local refs: { [string]: string } = {}
for _, c in Fx.fonts do
refs[c.name] = c.data
end
local samples = {}
local n = 0
for _, w in Fx.woff do
for _, key in { "woff2", "woff2h" } do
local data = w[key]
local font, err = Woff2.decode(Bytes.reader(buffer.fromstring(data)))
t:check(font, w.name .. " (" .. key .. "): " .. tostring(err))
t:eq(font.meta.source.format, "woff2", "source format")
local ref = assert(Ttf.decode(Bytes.reader(buffer.fromstring(refs[w.name]))))
same(font, ref, w.name .. " (" .. key .. ")")
local img = font:rasterize(font:glyphIndex(65), 24)
t:check(img and img.width > 0, w.name .. ": rasterize")
n += 1
if #data < 40000 then
table.insert(samples, data)
end
t:note("%-20s %-7s %7d bytes (sfnt %d), %d glyphs identical", w.name, key, #data, #refs[w.name], font.numGlyphs)
end
end
t:check(n >= 6, "fixture count")
-- the api
do
local data = Fx.woff[1].woff2
t:eq(F.detect(data), "woff2", "F.detect")
local f = F.font.load(data)
t:check(f and f.kind == "font", "F.font.load")
t:eq(Woff2.sniff(Bytes.reader(buffer.fromstring("wOFF"))) + Woff2.sniff(Bytes.reader(buffer.fromstring("wOF2"))), 1, "sniff")
end
-- errors
do
local data = Fx.woff[1].woff2
local _, e1 = Woff2.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, 30))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated header: " .. tostring(e1))
local _, e2 = Woff2.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, #data - 100))))
t:check(e2 ~= nil, "truncated data: " .. tostring(e2))
local _, e3 = Woff2.decode(Bytes.reader(buffer.fromstring("ttcf" .. string.rep("\0", 60))))
t:check(e3 and e3.code == Err.CORRUPT, "bad signature: " .. tostring(e3))
end
t:fuzz("decode", function(b: buffer)
local f = Woff2.decode(Bytes.reader(b))
if f then
for g = 0, math.min(f.numGlyphs, 40) - 1 do
f:outline(g)
f:rasterize(g, 8)
end
end
return f
end, samples, { mutations = 25, garbage = 200 })
t:done()