merge ws/arch2: cpio ar/deb rpm .Z lz4 iso lha arj zoo cab, uu/yenc/binhex/macbinary/applesingle, d64 adf fat, bdf pcf psf fon type1 eot hershey

This commit is contained in:
4DBug committed 2026-10-31 16:44:01 -05:00
commit b5cdd77a5b
115 files changed
+17373 -29

No files matched your search

+80 -2
View File
@@ -1,8 +1,8 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), .Z (tools/fixtures/z.py), fonts
-- (glyphs per second), cab (LZX / MSZIP / Quantum), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
@@ -301,6 +301,36 @@ do
Bzip2.decompress(bz)
end)
end
do
local Lz4F = require("@formats/archive/lz4")
local LF = require("@tests/gen/lz4frame")
local LC = require("@tests/gen/lz4frame_corpora")
local frameData
for _, c in LF.cases do
if c.name == "text/BX" then
frameData = buffer.fromstring(c.data)
end
end
bench("lz4 frame decode (64K, xxh32)", 5, #LC.text, function()
Lz4F.decompress(frameData)
end)
local tb = buffer.fromstring(LC.text)
bench("lz4 frame encode (xxh32)", 5, #LC.text, function()
Lz4F.compress(tb)
end)
end
do
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
local ZC = require("@tests/gen/z")
local zc = ZC.cases[5] -- the 700 KB corpus, -b 16
local zb, zi = buffer.fromstring(zc.z), buffer.fromstring(zc.input)
bench(".Z decompress (lzw -b16)", 5, #zc.input, function()
UnixCompress.decompress(zb)
end)
bench(".Z compress (lzw -b16)", 3, #zc.input, function()
UnixCompress.compress(zi)
end)
end
do
local Lzma = require("@formats/codecs/compress/Lzma")
local LB = require("@tests/gen/lzma_bench")
@@ -1138,6 +1168,54 @@ do
jitTune(false)
end
end
-- ws-arch2 archives: the LHA family (codecs/compress/Lzh) over tools/fixtures/lha.py archives (MB/s of output)
do
local Lha = require("@formats/archive/lha")
local LF = require("@tests/gen/lha")
for _, want in { "lha114i -h2 -5", "lha114i -h2 -7", "lengths/lh1-1m.lzh", "lengths/lz5-1m.lzs", "larc333/long.lzs" } do
for _, c in LF.cases do
if c.name == want then
local a = Lha.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
local total = 0
for _, e in a:list() do
total += e.size
end
bench("lha " .. want, 3, total, function()
for _, e in a:list() do
a:read(e.name)
end
end)
end
end
end
end
-- ws-arch2 cabinets: LZX (codecs/compress/Lzx), Quantum (codecs/compress/Quantum) and MSZIP folders of
-- tools/fixtures/cab.py (MB/s of output; each run decodes the cabinet again, so the folder cache does not count)
do
local Cab = require("@formats/archive/cab")
local CF = require("@tests/gen/cab")
for _, kind in { "lzx", "quantum", "mszip" } do
local datas, total = {}, 0
for _, c in CF.cases do
local a = Cab.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
if a and a.meta.folders[1].method == kind and #c.data > 20000 then
table.insert(datas, buffer.fromstring(c.data))
for _, e in a:list() do
total += e.size
end
end
end
bench("cab " .. kind .. " (" .. #datas .. " cabinets)", 5, total, function()
for _, d in datas do
local a = Cab.decode(Bytes.reader(d)) :: any
for _, e in a:list() do
a:read(e.name)
end
end
end)
end
end
do
-- game formats (ws-game): PKWARE DCL explode (StormLib's implode streams from tools/fixtures/mpq.py), reading every
-- file of a StormLib MPQ (MB/s of file data), Freedoom's MAP01 to a Scene (tools/fixtures/wad.py: sector
+73
View File
@@ -0,0 +1,73 @@
# Shared helpers for the ws-arch2 fixture generators (archives, encodings, disk images): reference tools through nix,
# our writers' output through tools/fixtures/_arch2_ours.luau, and the standard file set those writers produce.
import os, shutil, subprocess, tempfile, zlib
def content(n, seed):
"""the bytes of _arch2_ours.luau's content(n, seed)"""
out = bytearray(n)
s = seed
for i in range(n):
s = (s * 75 + 74) % 65537
out[i] = (i // 7) % 256 if (i // 64) % 3 == 0 else s % 256
return bytes(out)
FILES = [("hello.txt", b"hello, archive\n"), ("data.bin", content(5000, 7)), ("empty.txt", b"")]
MTIME = 1700000000
def tool(pkgs, argv, cwd=None, input=None, check=True):
"""run argv with the nix packages pkgs on PATH (the host's tool when argv[0] is installed and pkgs is empty)"""
if isinstance(pkgs, str):
pkgs = [pkgs]
cmd = (["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c"] if pkgs else []) + list(argv)
r = subprocess.run(cmd, cwd=cwd, input=input, capture_output=True)
if check and r.returncode != 0:
raise RuntimeError("%s failed (%d): %s" % (" ".join(argv), r.returncode, r.stderr.decode(errors="replace")))
return r.stdout
def ours(ctx, fmt, opts=""):
"""our writer's output for the standard file set (bytes)"""
script = os.path.join(ctx.root, "tools", "fixtures", "_arch2_ours.luau")
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
exe = shutil.which("luau")
argv = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [script, "-a", fmt, opts]
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
return bytes.fromhex(out.decode().strip())
def tree(files, root):
"""write [(name, bytes)] under root (with MTIME)"""
for name, data in files:
p = os.path.join(root, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.utime(p, (MTIME, MTIME))
def read_tree(root):
"""{relative name: crc32} of the files under root"""
out = {}
for d, _, fs in os.walk(root):
for f in fs:
p = os.path.join(d, f)
if os.path.isfile(p) and not os.path.islink(p):
out[os.path.relpath(p, root)] = zlib.crc32(open(p, "rb").read())
return out
def tmpdir():
return tempfile.mkdtemp(prefix="arch2-")
def rmtree(root):
"""shutil.rmtree that first makes extracted directories writable (archives store read-only modes)"""
for d, ds, _ in os.walk(root):
for x in ds:
p = os.path.join(d, x)
if not os.path.islink(p):
os.chmod(p, 0o755)
shutil.rmtree(root, ignore_errors=True)
+50
View File
@@ -0,0 +1,50 @@
-- tools/fixtures/_arch2_ours.luau: our archive writers' output for the reference tools to read (run by the ws-arch2
-- fixture generators through `luau tools/fixtures/_arch2_ours.luau -a <format> [<options as k=v,k=v>]`). Writes the
-- standard file set (the same names and bytes as _arch2.FILES) with the format's encoder and prints the file as hex.
local F = require("@formats")
local which, optstr = ...
local function content(n: number, seed: number): buffer
local b = buffer.create(n)
local s = seed
for i = 0, n - 1 do
s = (s * 75 + 74) % 65537
-- runs and noise, so compressors have something to find
buffer.writeu8(b, i, if (i // 64) % 3 == 0 then (i // 7) % 256 else s % 256)
end
return b
end
local opts: { [string]: any } = {}
for k, v in string.gmatch(optstr or "", "([%w_]+)=([^,]*)") do
opts[k] = tonumber(v) or (if v == "true" then true elseif v == "false" then false else v)
end
local mod = F.format(which) :: any
local a = if mod.new then mod.new() else nil
local files = {
{ "hello.txt", buffer.fromstring("hello, archive\n") },
{ "data.bin", content(5000, 7) },
{ "empty.txt", buffer.create(0) },
}
if opts.single then
files = { files[2] }
end
for _, f in files do
a:add(f[1], f[2], { mtime = 1700000000, mode = 0x1A4 })
end
if opts.mac then
-- a Mac file: type / creator / flags on the data fork, a resource fork entry
local e = a._byName["hello.txt"]
e.macType, e.macCreator, e.finderFlags = "TEXT", "ttxt", 0x0100
a:add("hello.txt.rsrc", content(700, 3), { mtime = 1700000000 })
a._byName["hello.txt.rsrc"].fork = "resource"
end
local out, err = a:write(opts)
if not out then
error(tostring(err))
end
local t = table.create(buffer.len(out))
for i = 0, buffer.len(out) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(out, i))
end
print(table.concat(t))
+34
View File
@@ -0,0 +1,34 @@
-- tools/fixtures/_bitmapfonts_ours.luau: our bitmap font writers' output for the reference tools to read back (run by
-- tools/fixtures/bitmapfonts.py / psf.py after they wrote the source fonts to tests/gen/<src>.luau:
-- `luau _bitmapfonts_ours.luau -a <src> <format> [version]`): decodes each source font with its format, encodes it
-- with <format> (default bdf) and prints "<case> <hex>" lines.
local F = require("@formats")
local Bytes = require("@formats/core/Bytes")
local Deflate = require("@formats/codecs/compress/Deflate")
local srcName, outFormat, version = ...
local Src = if srcName == "psf_src" then require("@tests/gen/psf_src") else require("@tests/gen/bitmapfonts_src")
local enc = F.format(outFormat or "bdf") :: any
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
for _, c in Src.fonts do
local data = buffer.fromstring(c.data)
if c.gz then
data = Deflate.gunzip(data, 0, buffer.len(data)) :: buffer
end
local mod = F.format(c.format) :: any
local font = if mod then mod.decode(Bytes.reader(data)) else nil
if font and enc then
local out = enc.encode(font, { version = tonumber(version) })
if out then
print(c.name .. " " .. hex(out))
end
end
end
+39
View File
@@ -0,0 +1,39 @@
# FreeType's view of bitmap fonts (run by tools/fixtures/bitmapfonts.py in a nix python with freetype-py): stdin is
# JSON { fonts: [ { path, chars } ] }; prints JSON [ { glyphs: [ { cp, width, height, left, top, advance, pixels(hex) } ],
# ascent, descent, family, style, height } ] from FT_LOAD_RENDER | FT_LOAD_TARGET_MONO on the first strike.
import json, sys
import freetype
req = json.load(sys.stdin)
out = []
for f in req["fonts"]:
face = freetype.Face(f["path"])
if face.num_fixed_sizes:
face.select_size(0)
glyphs = []
unicode = any(cm.encoding == freetype.FT_ENCODING_UNICODE for cm in face.charmaps)
if not unicode and face.charmaps:
face.set_charmap(face.charmaps[0]) # Windows FNT: byte codes (compared for ASCII only)
for cp in f["chars"]:
if not unicode and cp >= 128:
continue
gi = face.get_char_index(cp)
if gi == 0:
continue
face.load_glyph(gi, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO)
g = face.glyph
bm = g.bitmap
w, h, pitch = bm.width, bm.rows, bm.pitch
buf = bm.buffer
px = bytearray(w * h)
for y in range(h):
for x in range(w):
if (buf[y * pitch + x // 8] >> (7 - x % 8)) & 1:
px[y * w + x] = 255
glyphs.append({"cp": cp, "width": w, "height": h, "left": g.bitmap_left, "top": g.bitmap_top,
"advance": g.advance.x >> 6, "pixels": px.hex()})
m = face.size
out.append({"unicode": unicode, "glyphs": glyphs, "ascent": m.ascender >> 6, "descent": -(m.descender >> 6), "height": m.height >> 6,
"family": (face.family_name or b"").decode("latin-1"), "style": (face.style_name or b"").decode("latin-1"),
"numGlyphs": face.num_glyphs})
print(json.dumps(out))
+21
View File
@@ -0,0 +1,21 @@
-- tools/fixtures/_lz4frame_encode.luau: run by tools/fixtures/lz4frame.py under the luau CLI: writes every corpus of
-- tests/gen/lz4frame_corpora as LZ4 frames with archive/lz4 (several option sets) and prints "<name> <hex>" lines for
-- the lz4 tool to decompress.
local Lz4F = require("@formats/archive/lz4")
local C = require("@tests/gen/lz4frame_corpora")
local sets = {
default = {},
b64k = { blockSize = 65536, blockChecksum = true, contentSize = true },
nocrc = { contentChecksum = false, blockSize = 262144 },
}
for name, data in C do
for sname, o in sets do
local b = assert(Lz4F.compress(data, o :: any))
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
print(name .. "/" .. sname .. " " .. table.concat(t))
end
end
+351
View File
@@ -0,0 +1,351 @@
# A small LZX compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes LZX cabinets, so the
# fixtures make them here and cabextract (the reference) must extract them to the original bytes before our decoder
# is compared with its output. Written from the LZX format description (as codecs/compress/Lzx): verbatim, aligned
# offset and uncompressed blocks of chosen sizes (spanning frames), delta-coded trees with pre-tree runs, repeated
# offsets, the E8 translation, 32 KB frames aligned to 16 bits. Hash-chain matching; not tuned for ratio or speed.
import heapq, random, struct
FRAME = 32768
SLOTS = {15: 30, 16: 32, 17: 34, 18: 36, 19: 38, 20: 42, 21: 50}
EXTRA = [0 if i < 4 else min(i // 2 - 1, 17) for i in range(51)]
BASE = []
_b = 0
for _e in EXTRA:
BASE.append(_b)
_b += 1 << _e
def slot_of(fo):
s = 0
while s + 1 < len(BASE) and BASE[s + 1] <= fo:
s += 1
return s
def lengths(freqs, maxlen):
"""length-limited Huffman code lengths (halving the frequencies until the code fits); every tree complete"""
f = list(freqs)
used = [i for i, x in enumerate(f) if x > 0]
while len(used) < 2: # a complete code needs two symbols
i = next(i for i in range(len(f)) if f[i] == 0)
f[i] = 1
used.append(i)
while True:
heap = [(f[i], i, (i,)) for i in used]
heapq.heapify(heap)
depth = {i: 0 for i in used}
k = len(f)
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
for s in a[2] + b[2]:
depth[s] += 1
heapq.heappush(heap, (a[0] + b[0], k, a[2] + b[2]))
k += 1
if max(depth.values()) <= maxlen:
out = [0] * len(f)
for s, d in depth.items():
out[s] = d
return out
f = [(x + 1) // 2 if x else 0 for x in f]
def codes(lens):
"""canonical codes (MSB first)"""
out = [0] * len(lens)
code = 0
for l in range(1, 17):
for s, x in enumerate(lens):
if x == l:
out[s] = code
code += 1
code <<= 1
return out
class Bits:
def __init__(self):
self.out = bytearray()
self.acc = 0
self.n = 0
def put(self, v, n):
for i in range(n - 1, -1, -1):
self.acc = (self.acc << 1) | ((v >> i) & 1)
self.n += 1
if self.n == 16:
self.out += struct.pack("<H", self.acc)
self.acc, self.n = 0, 0
def align(self):
if self.n:
self.put(0, 16 - self.n)
def aligned(self):
return self.n == 0
def e8(data, size):
"""the encoder's E8 translation (relative call targets to absolute), frame by frame"""
d = bytearray(data)
for base in range(0, min(len(d), FRAME * 32768), FRAME):
fs = min(FRAME, len(d) - base)
i, stop = base, base + fs - 10
while i < stop:
if d[i] == 0xE8:
rel = struct.unpack_from("<i", d, i + 1)[0]
if -i <= rel < size:
struct.pack_into("<i", d, i + 1, rel + i if rel < size - i else rel - size)
i += 5
else:
i += 1
return bytes(d)
def tokens(data, start, end, window, reps, rng, maxchain=24):
"""LZ77 tokens of data[start:end) (literal ints, or (length, offset)); matches stay inside the 32 KB frame"""
out = []
head = {}
prev = {}
def insert(p):
if p + 3 <= len(data):
k = data[p:p + 3]
prev[p] = head.get(k)
head[k] = p
for p in range(max(0, start - 4096), start):
insert(p)
p = start
r = list(reps)
while p < end:
limit = min(257, end - p, (p // FRAME + 1) * FRAME - p)
best, boff = 0, 0
if limit >= 2:
for o in r: # repeated offsets first
if o <= p:
l = 0
while l < limit and data[p + l] == data[p + l - o]:
l += 1
if l > best:
best, boff = l, o
if limit >= 3:
q = head.get(data[p:p + 3])
chain = 0
while q is not None and chain < maxchain and p - q <= window - 3:
l = 0
while l < limit and data[q + l] == data[p + l]:
l += 1
if l > best + 1:
best, boff = l, p - q
q = prev.get(q)
chain += 1
if best >= 3 or (best == 2 and boff in r):
out.append((best, boff))
if boff == r[0]:
pass
elif boff == r[1]:
r[0], r[1] = r[1], r[0]
elif boff == r[2]:
r[0], r[2] = r[2], r[0]
else:
r = [boff, r[0], r[1]]
for k in range(best):
insert(p + k)
p += best
else:
out.append(data[p])
insert(p)
p += 1
return out, r
class Tree:
"""code lengths persisting across blocks (the deltas' base)"""
def __init__(self, n):
self.lens = [0] * n
def pretree_items(prev, new, rng, runs):
"""the pre-tree symbols ((sym, extra bits, nbits) or (19, ...)) that turn prev into new"""
items = []
x = 0
n = len(new)
while x < n:
if runs and new[x] == 0:
r = 0
while x + r < n and new[x + r] == 0:
r += 1
if r >= 20:
r = min(r, 51)
items.append((18, r - 20, 5, None))
x += r
continue
if r >= 4:
r = min(r, 19)
items.append((17, r - 4, 4, None))
x += r
continue
if runs:
r = 0
while x + r < n and new[x + r] == new[x]:
r += 1
if r >= 4:
r = min(r, 5)
items.append((19, r - 4, 1, (prev[x] - new[x]) % 17))
x += r
continue
items.append(((prev[x] - new[x]) % 17, 0, 0, None))
x += 1
return items
def write_tree(bits, tree, first, last, new, rng):
items = pretree_items(tree.lens[first:last], new, rng, runs=rng.random() < 0.9)
freq = [0] * 20
for s, _, _, d in items:
freq[s] += 1
if d is not None:
freq[d] += 1
pl = lengths(freq, 15)
pc = codes(pl)
for l in pl:
bits.put(l, 4)
for s, ex, nb, d in items:
bits.put(pc[s], pl[s])
if nb:
bits.put(ex, nb)
if d is not None:
bits.put(pc[d], pl[d])
tree.lens[first:last] = new
def compress(data, wbits=16, e8size=0, seed=1, plan=None):
"""data -> (LZX stream bytes, [compressed bytes per 32 KB frame]); plan: [(block type 1..3, size)] (default:
random sizes and types)"""
rng = random.Random(seed)
window = 1 << wbits
nslots = SLOTS[wbits]
src = e8(data, e8size) if e8size else bytes(data)
if plan is None:
plan = []
left = len(src)
while left > 0:
n = min(left, rng.choice([5000, 20000, 32768, 45000, 70000, 100000]))
plan.append((rng.choice([1, 1, 2, 2, 3]) if n > 100 else 1, n))
left -= n
bits = Bits()
frames = []
frame_start = 0
main = Tree(256 + 8 * nslots)
length = Tree(249)
reps = [1, 1, 1]
pos = 0
first = True
def frame_end_check(p):
nonlocal frame_start
if p % FRAME == 0 or p == len(src):
bits.align()
frames.append(len(bits.out) - frame_start)
frame_start = len(bits.out)
for btype, size in plan:
if first:
if e8size:
bits.put(1, 1)
bits.put(e8size >> 16, 16)
bits.put(e8size & 0xFFFF, 16)
else:
bits.put(0, 1)
first = False
bits.put(btype, 3)
bits.put(size >> 8, 16)
bits.put(size & 0xFF, 8)
end = pos + size
if btype == 3:
if bits.aligned():
bits.put(0, 16)
bits.align()
for r in reps:
bits.out += struct.pack("<I", r)
while pos < end:
n = min(end, (pos // FRAME + 1) * FRAME) - pos
bits.out += src[pos:pos + n]
pos += n
frame_end_check(pos)
if size & 1:
bits.out += b"\0"
if pos % FRAME == 0 or pos == len(src): # the pad byte belongs to the frame just closed
frames[-1] += 1
frame_start += 1
continue
toks, newreps = tokens(src, pos, end, window, reps, rng)
# symbols
mf = [0] * (256 + 8 * nslots)
lf = [0] * 249
af = [0] * 8
syms = []
r = list(reps)
for t in toks:
if isinstance(t, int):
mf[t] += 1
syms.append((t,))
continue
l, o = t
if o == r[0]:
slot = 0
elif o == r[1]:
slot = 1
r[0], r[1] = r[1], r[0]
elif o == r[2]:
slot = 2
r[0], r[2] = r[2], r[0]
else:
slot = slot_of(o + 2)
r = [o, r[0], r[1]]
hdr = min(l - 2, 7)
m = 256 + slot * 8 + hdr
mf[m] += 1
ls = l - 2 - 7 if hdr == 7 else None
if ls is not None:
lf[ls] += 1
foot = None
if slot >= 3:
foot = o + 2 - BASE[slot]
if btype == 2 and EXTRA[slot] >= 3:
af[foot & 7] += 1
syms.append((m, ls, slot, foot))
assert r == newreps
reps = newreps
if btype == 2:
al = lengths(af, 7)
for x in al:
bits.put(x, 3)
ac = codes(al)
ml = lengths(mf, 16)
ll = lengths(lf, 16) if any(lf) or rng.random() < 0.5 else [0] * 249
write_tree(bits, main, 0, 256, ml[:256], rng)
write_tree(bits, main, 256, len(ml), ml[256:], rng)
write_tree(bits, length, 0, 249, ll, rng)
mc, lc = codes(ml), codes(ll)
for t, s in zip(toks, syms):
m = s[0]
bits.put(mc[m], ml[m])
if m < 256:
pos += 1
else:
_, ls, slot, foot = s
if ls is not None:
bits.put(lc[ls], ll[ls])
if slot >= 3:
ex = EXTRA[slot]
if btype == 2 and ex >= 3:
if ex > 3:
bits.put(foot >> 3, ex - 3)
bits.put(ac[foot & 7], al[foot & 7])
elif ex:
bits.put(foot, ex)
pos += t[0]
frame_end_check(pos)
return bytes(bits.out), frames
+183
View File
@@ -0,0 +1,183 @@
# A small Quantum compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes Quantum
# cabinets, so the fixtures make them here and cabextract (the reference) must extract them to the original bytes
# before our decoder is compared with its output. Written from the format description (as codecs/compress/Quantum):
# the same adaptive models, a 16-bit arithmetic encoder with underflow bits (Witten / Neal / Cleary style), position /
# length footers as raw bits placed where the decoder (16 code bits ahead) reads them, one frame per 32 KB block.
FRAME = 32768
PEXTRA = [0 if i < 4 else i // 2 - 1 for i in range(42)]
PBASE = []
_b = 0
for _e in PEXTRA:
PBASE.append(_b)
_b += 1 << _e
LEXTRA = [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]
LBASE = []
_b = 0
for _e in LEXTRA:
LBASE.append(_b)
_b += 1 << _e
class Model:
def __init__(self, first, n):
self.n = n
self.sym = [first + i for i in range(n)]
self.cum = [n - i for i in range(n)] + [0]
self.shifts = 4
def update(self, i):
"""after coding sym[i] (0-based)"""
for k in range(i + 1):
self.cum[k] += 8
if self.cum[0] > 3800:
self.rescale()
def rescale(self):
n, cum, sym = self.n, self.cum, self.sym
self.shifts -= 1
if self.shifts:
for i in range(n - 1, -1, -1):
cum[i] >>= 1
if cum[i] <= cum[i + 1]:
cum[i] = cum[i + 1] + 1
return
self.shifts = 50
for i in range(n):
cum[i] = (cum[i] - cum[i + 1] + 1) >> 1
for i in range(n - 1):
for j in range(i + 1, n):
if cum[i] < cum[j]:
cum[i], cum[j] = cum[j], cum[i]
sym[i], sym[j] = sym[j], sym[i]
for i in range(n - 1, -1, -1):
cum[i] += cum[i + 1]
class Encoder:
"""one frame: code bits (by shift position) and raw bit runs to insert at code positions"""
def __init__(self):
self.H, self.L = 0xFFFF, 0
self.code = []
self.pending = 0
self.shifts = 0
self.raws = [] # (code position, value, nbits)
def emit(self, b):
self.code.append(b)
self.code.extend([1 - b] * self.pending)
self.pending = 0
def encode(self, m, s):
i = m.sym.index(s)
rng = self.H - self.L + 1
tot = m.cum[0]
self.H = self.L + (m.cum[i] * rng) // tot - 1
self.L = self.L + (m.cum[i + 1] * rng) // tot
m.update(i)
while True:
if (self.L ^ self.H) & 0x8000 == 0:
self.emit(self.H >> 15)
elif (self.L & 0x4000) and not (self.H & 0x4000):
self.pending += 1
self.L &= 0x3FFF
self.H |= 0x4000
else:
break
self.L = (self.L << 1) & 0xFFFF
self.H = ((self.H << 1) & 0xFFFF) | 1
self.shifts += 1
def raw(self, v, n):
if n:
self.raws.append((16 + self.shifts, v, n))
def finish(self):
"""the frame's bytes: flushed code with the raw runs merged in, zero padded"""
self.pending += 1
self.emit(0 if self.L < 0x4000 else 1)
need = 16 + self.shifts
code = self.code + [0] * max(0, need - len(self.code))
bits = []
p = 0
for at, v, n in self.raws:
bits.extend(code[p:at])
p = at
bits.extend((v >> (n - 1 - k)) & 1 for k in range(n))
bits.extend(code[p:])
bits.extend([0] * (-len(bits) % 8 + 16)) # byte padding and 2 zero bytes: the decoder's lookahead stays inside
return bytes(int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8))
def slot_of(off1):
s = 0
while s + 1 < len(PBASE) and PBASE[s + 1] <= off1:
s += 1
return s
def compress(data, wbits=16, maxchain=24):
"""data -> [frame bytes] (one per 32 KB block)"""
window = 1 << wbits
slots = wbits * 2
sel = Model(0, 7)
lit = [Model(0, 64), Model(64, 64), Model(128, 64), Model(192, 64)]
m3, m4, m5, mlen = Model(0, min(slots, 24)), Model(0, min(slots, 36)), Model(0, slots), Model(0, 27)
lim3, lim4 = PBASE[m3.n - 1] + (1 << PEXTRA[m3.n - 1]), PBASE[m4.n - 1] + (1 << PEXTRA[m4.n - 1])
limw = min(window, PBASE[slots - 1] + (1 << PEXTRA[slots - 1]))
head, prev = {}, {}
frames = []
p = 0
def insert(q):
if q + 3 <= len(data):
k = data[q:q + 3]
prev[q] = head.get(k)
head[k] = q
while p < len(data):
end = min(len(data), p + FRAME)
enc = Encoder()
while p < end:
limit = min(259, end - p)
best, boff = 0, 0
if limit >= 3:
q = head.get(data[p:p + 3])
chain = 0
while q is not None and chain < maxchain and p - q <= limw:
l = 0
while l < limit and data[q + l] == data[p + l]:
l += 1
o = p - q
ok = l >= 5 or (l == 4 and o <= lim4) or (l == 3 and o <= lim3)
if ok and l > best:
best, boff = l, o
q = prev.get(q)
chain += 1
if best >= 3:
o1 = boff - 1
s = slot_of(o1)
if best == 3:
enc.encode(sel, 4)
enc.encode(m3, s)
elif best == 4:
enc.encode(sel, 5)
enc.encode(m4, s)
else:
l5 = best - 5
ls = max(i for i in range(27) if LBASE[i] <= l5)
enc.encode(sel, 6)
enc.encode(mlen, ls)
enc.raw(l5 - LBASE[ls], LEXTRA[ls])
enc.encode(m5, s)
enc.raw(o1 - PBASE[s], PEXTRA[s])
for k in range(best):
insert(p + k)
p += best
else:
b = data[p]
enc.encode(sel, b >> 6)
enc.encode(lit[b >> 6], b)
insert(p)
p += 1
frames.append(enc.finish())
return frames
+59
View File
@@ -0,0 +1,59 @@
# Amiga ADF fixtures (tools/fixtures.py): DD and HD images formatted as OFS, FFS, FFS international and OFS / FFS with
# directory cache by amitools' `xdftool` (PyPI amitools through `uvx`), filled with a tree (nested directories, an
# empty file, a file large enough for extension blocks, Latin-1 names, protection bits, a set date; amitools 0.8.1's
# `comment` command fails, so comments are not covered); each
# file read back by `xdftool read` for the reference data, protection / dates from `xdftool list`.
# The images are emitted gzip-compressed (mostly empty blocks).
# tests/gen/adf.luau { cases = { { name, gz, volume, fs, entries = { { name, size?, crc?, dir?, comment?, mtime? } } } } }
import calendar, gzip, importlib.util, os, shutil, time, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py"]
def xdf(args, cwd):
return A.tool(["uv"], ["uvx", "--from", "amitools==0.8.1", "xdftool"] + args, cwd=cwd).decode("latin-1")
def generate(ctx):
rng = ctx.rng(1985)
tmp = A.tmpdir()
try:
files = [("readme", b"Amiga readme\n" * 20), ("empty", b""), ("s/startup-sequence", b"echo hello\n"),
("deep/a/b/c/leaf.bin", rng.randbytes(1500)), ("big.bin", rng.randbytes(100000)),
("café ü", b"latin-1 name\n")]
for i, (_, d) in enumerate(files):
open(os.path.join(tmp, "f%d" % i), "wb").write(d)
cases = []
for fs, size in (("ofs", "dd"), ("ffs", "dd"), ("ffs+intl", "dd"), ("ofs+dc", "dd"), ("ffs+dc", "dd"), ("ffs", "hd")):
img = "t-%s-%s.adf" % (fs.replace("+", "_"), size)
cmd = [img, "-f", "create", "size=1760K" if size == "hd" else "size=880K", "+", "format", "Vol " + fs, fs]
dirs = set()
for i, (name, _) in enumerate(files):
parts = name.split("/")[:-1]
for k in range(1, len(parts) + 1):
d = "/".join(parts[:k])
if d not in dirs:
dirs.add(d)
cmd += ["+", "makedir", d]
cmd += ["+", "write", "f%d" % i, name]
cmd += ["+", "protect", "readme", "rw", "+", "time", "readme", "01.02.1993 10:20:30.00"]
xdf(cmd, tmp)
ents = [{"name": d + "/", "dir": True} for d in sorted(dirs)]
for i, (name, d) in enumerate(files):
out = os.path.join(tmp, "out%d" % i)
xdf([img, "read", name, out], tmp)
rd = open(out, "rb").read()
assert rd == d, (img, name)
e = {"name": name, "size": len(d), "crc": zlib.crc32(d)}
if name == "readme":
e["mtime"] = calendar.timegm((1993, 2, 1, 10, 20, 30))
ents.append(e)
cases.append({"name": img, "gz": gzip.compress(open(os.path.join(tmp, img), "rb").read(), mtime=0), "volume": "Vol " + fs,
"fs": "ofs" if fs.startswith("ofs") else "ffs", "entries": ents, "listing": xdf([img, "list"], tmp)})
ctx.emit("adf", {"cases": cases})
finally:
shutil.rmtree(tmp)
+139
View File
@@ -0,0 +1,139 @@
# ar / deb fixtures (tools/fixtures.py): GNU ar (binutils: deterministic `rcSD`, real times `rcSU`, a library of two
# `as`-assembled objects with its "/" symbol table), llvm-ar --format=bsd (#1/ names, __.SYMDEF), bsdtar arbsd, and
# Debian packages from dpkg-deb --build (-Zxz / gzip / zstd / none) plus two built here (bzip2 and lzma members, as
# older dpkg wrote them). The expected entries are the input files; the .deb data entries come from Python's tarfile.
# tests/gen/ar.luau { files = { { name, data } }, gnuD = data (GNU ar rcSD of files), archives = { { name, data,
# variant, entries = { { name, size, mtime?, crc } }, symbols? = { { name, member } }, roundtrip? } },
# debs = { { name, data, control = { [field] = value }, payload, entries = { { name, type, size, crc? } } } } }
import bz2, gzip, io, lzma, os, shutil, subprocess, tarfile, tempfile, time, zlib
MTIME = 1700000000
def sh(pkgs, script, cwd, env=None):
argv = ["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c", "sh", "-c", script]
return subprocess.run(argv, cwd=cwd, capture_output=True, check=True, env=env).stdout
def ar_member(name, data, mtime=MTIME):
h = b"%-16s%-12d%-6d%-6d%-8s%-10d`\n" % (name, mtime, 0, 0, b"100644", len(data))
return h + data + (b"\n" if len(data) % 2 else b"")
def unpack(z, m):
if z == "xz":
return lzma.decompress(m)
if z == "gzip":
return gzip.decompress(m)
if z == "zstd":
return subprocess.run(["nix", "shell", "nixpkgs#zstd", "-c", "zstd", "-d", "-c"], input=m, capture_output=True, check=True).stdout
return m
def tar_entries(raw):
out = []
with tarfile.open(fileobj=io.BytesIO(raw)) as t:
for m in t.getmembers():
e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0",
"size": m.size if m.isfile() else 0}
if m.isfile():
e["crc"] = zlib.crc32(t.extractfile(m).read())
out.append(e)
return out
def generate(ctx):
rng = ctx.rng(17)
files = [
("a.txt", b"hello, ar\n"),
("odd", b"x" * 7),
("empty", b""),
("exactly15chars_", b"fifteen"),
("sixteen_chars_16", b"sixteen"),
("a_very_long_member_name.txt", rng.randbytes(1001)),
("another-long-member-name.bin", b"long name two\n"),
]
tmp = tempfile.mkdtemp()
try:
names = [n for n, _ in files]
for n, d in files:
with open(os.path.join(tmp, n), "wb") as f:
f.write(d)
os.utime(os.path.join(tmp, n), (MTIME, MTIME))
q = " ".join(names)
archives = []
gnuD = sh(["binutils"], "ar rcSD out.a %s && cat out.a && rm out.a" % q, tmp)
ents = [{"name": n, "size": len(d), "crc": zlib.crc32(d)} for n, d in files]
timed = [dict(e, mtime=MTIME) for e in ents]
archives.append({"name": "gnu-D", "data": gnuD, "variant": "gnu", "entries": ents})
archives.append({"name": "gnu-U", "data": sh(["binutils"], "ar rcSU out.a %s && cat out.a && rm out.a" % q, tmp),
"variant": "gnu", "entries": timed})
# a library: two objects, with a symbol table
with open(os.path.join(tmp, "s1.s"), "w") as f:
f.write(".globl foo\nfoo:\n.data\n.globl bar\nbar: .long 1\n")
with open(os.path.join(tmp, "s2.s"), "w") as f:
f.write(".globl baz_with_a_long_symbol_name\nbaz_with_a_long_symbol_name:\n")
sh(["binutils"], "as -o one.o s1.s && as -o second_object_long_name.o s2.s", tmp)
objs = []
for n in ("one.o", "second_object_long_name.o"):
with open(os.path.join(tmp, n), "rb") as f:
d = f.read()
objs.append({"name": n, "size": len(d), "crc": zlib.crc32(d)})
syms = [{"name": "foo", "member": "one.o"}, {"name": "bar", "member": "one.o"},
{"name": "baz_with_a_long_symbol_name", "member": "second_object_long_name.o"}]
lib = "one.o second_object_long_name.o a.txt"
archives.append({"name": "gnu-lib", "data": sh(["binutils"], "ar rcsD out.a %s && cat out.a && rm out.a" % lib, tmp),
"variant": "gnu", "entries": objs + ents[:1], "symbols": syms})
archives.append({"name": "llvm-bsd", "data": sh(["llvm"], "llvm-ar rcSD --format=bsd out.a %s && cat out.a && rm out.a" % q, tmp),
"variant": "bsd", "entries": ents})
archives.append({"name": "llvm-bsd-lib", "data": sh(["llvm"], "llvm-ar rcsD --format=bsd out.a %s && cat out.a && rm out.a" % lib, tmp),
"variant": "bsd", "entries": objs + ents[:1], "symbols": syms})
archives.append({"name": "bsdtar-arbsd", "data": sh(["libarchive"], "bsdtar --format=arbsd -cf - %s" % q, tmp),
"variant": "bsd", "entries": timed, "roundtrip": True})
# Debian packages
pkg = os.path.join(tmp, "pkg")
os.makedirs(os.path.join(pkg, "DEBIAN"))
os.makedirs(os.path.join(pkg, "usr", "share", "doc", "hello"))
os.makedirs(os.path.join(pkg, "usr", "bin"))
control = ("Package: hello\nVersion: 1.0-1\nArchitecture: all\nMaintainer: Ada <[email protected]>\n"
"Depends: libc6 (>= 2.31)\nDescription: a greeting\n prints a greeting\n .\n and exits\n")
with open(os.path.join(pkg, "DEBIAN", "control"), "w") as f:
f.write(control)
with open(os.path.join(pkg, "usr", "bin", "hello"), "wb") as f:
f.write(b"#!/bin/sh\necho hello\n")
os.chmod(os.path.join(pkg, "usr", "bin", "hello"), 0o755)
with open(os.path.join(pkg, "usr", "share", "doc", "hello", "README"), "wb") as f:
f.write(rng.randbytes(2000))
fields = {"Package": "hello", "Version": "1.0-1", "Architecture": "all", "Maintainer": "Ada <[email protected]>",
"Depends": "libc6 (>= 2.31)", "Description": "a greeting\nprints a greeting\n.\nand exits"}
env = dict(os.environ, SOURCE_DATE_EPOCH=str(MTIME))
debs = []
for z, ext in (("xz", ".xz"), ("gzip", ".gz"), ("zstd", ".zst"), ("none", "")):
data = sh(["dpkg"], "dpkg-deb --root-owner-group -Z%s --build pkg out.deb >/dev/null && cat out.deb && rm out.deb" % z, tmp, env)
raw = None
p = 8
while p < len(data):
n = int(data[p + 48:p + 58])
if data[p:p + 8] == b"data.tar":
m = data[p + 60:p + 60 + n]
raw = unpack(z, m)
p += 60 + n + (n & 1)
debs.append({"name": "dpkg-" + z, "data": data, "control": fields, "payload": "data.tar" + ext, "entries": tar_entries(raw)})
# older compressors, assembled here: control.tar.bz2 + data.tar.bz2, control.tar.lzma + data.tar.lzma
def tar_of(root, prefix):
b = io.BytesIO()
with tarfile.open(fileobj=b, mode="w", format=tarfile.GNU_FORMAT) as t:
t.add(root, arcname=prefix, filter=lambda ti: setattr(ti, "mtime", MTIME) or ti)
return b.getvalue()
ctl = tar_of(os.path.join(pkg, "DEBIAN"), ".")
dat_dir = os.path.join(tmp, "datatree")
shutil.copytree(pkg, dat_dir, ignore=shutil.ignore_patterns("DEBIAN"))
dat = tar_of(dat_dir, ".")
alone = lambda b: lzma.compress(b, format=lzma.FORMAT_ALONE)
for name, comp, ext in (("py-bzip2", bz2.compress, ".bz2"), ("py-lzma", alone, ".lzma")):
data = b"!<arch>\n" + ar_member(b"debian-binary", b"2.0\n") + ar_member(b"control.tar" + ext.encode(), comp(ctl)) + \
ar_member(b"data.tar" + ext.encode(), comp(dat))
debs.append({"name": name, "data": data, "control": fields, "payload": "data.tar" + ext, "entries": tar_entries(dat)})
finally:
shutil.rmtree(tmp)
ctx.emit("ar", {"files": [{"name": n, "data": d} for n, d in files], "gnuD": gnuD, "archives": archives, "debs": debs})
+33
View File
@@ -0,0 +1,33 @@
# ARJ fixtures (tools/fixtures.py): archives made by the open-source ARJ 3.10 (nixpkgs#arj, run as a tool) with methods
# -m0 (stored) and -m1 .. -m4, recursing into a directory tree (-r), with an archive comment; the reference data is
# what `arj x` extracts again.
# tests/gen/arj.luau { cases = { { name, data, entries = { { name, size, crc } } } } }
import importlib.util, os, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py"]
def generate(ctx):
rng = ctx.rng(31)
tmp = A.tmpdir()
try:
work = os.path.join(tmp, "w")
A.tree(A.FILES + [("dir/sub/text.txt", b"the quick brown fox jumps over the lazy dog\n" * 400),
("dir/rand.bin", rng.randbytes(40000)), ("dir/runs.bin", b"\0" * 30000 + b"\xff" * 7000)], work)
names = [n for n, _ in A.FILES] + ["dir"]
cases = []
for m in ("0", "1", "2", "3", "4"):
arc = os.path.join(tmp, "m%s.arj" % m)
A.tool(["arj"], ["arj", "a", "-m" + m, "-r", "-y", arc] + names, cwd=work)
out = os.path.join(tmp, "x" + m)
os.makedirs(out)
A.tool(["arj"], ["arj", "x", "-y", arc], cwd=out)
ents = [{"name": n, "size": os.path.getsize(os.path.join(out, n)), "crc": c} for n, c in A.read_tree(out).items()]
cases.append({"name": "arj -m" + m, "data": open(arc, "rb").read(), "entries": ents})
ctx.emit("arj", {"cases": cases})
finally:
A.rmtree(tmp)
+99
View File
@@ -0,0 +1,99 @@
# Bitmap font fixtures (tools/fixtures.py) for font/bdf and font/pcf (and codecs/font/Bitmap): BDF fonts (Spleen 5x8,
# 12x24; BSD-2, nixpkgs#spleen), PCF fonts compiled from them by `bdftopcf` with every glyph pad / scan unit / bit and
# byte order (-p1/2/4/8, -u1/2/4, -m / -l) and with -t (terminal fonts), Tamzen PCFs (nixpkgs#tamzen) and X11
# misc-misc .pcf.gz fonts in ISO8859-1 and ISO8859-5, Windows .fnt / .fon (NE) made by FontForge from the Spleen BDFs;
# all read from the nix store at fixture time. Reference glyph
# bitmaps, offsets and advances come from FreeType (tools/fixtures/_bitmapfonts_ref.py); our BDF writer's output for
# each font (tools/fixtures/_bitmapfonts_ours.luau) is read back by FreeType and compared too.
# tests/gen/bitmapfonts.luau { fonts = { { name, format, data, gz?, ref = { glyphs = { { cp, width, height, left,
# top, advance, pixels } }, ascent, descent }, ours = { ok, detail } } } }
import gzip, importlib.util, json, os, shutil, subprocess
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_bitmapfonts_ref.py", "tools/fixtures/_bitmapfonts_ours.luau", "src/Formats/font/bdf", "src/Formats/font/pcf",
"src/Formats/font/fon"]
CHARS = [32, 33, 48, 64, 65, 87, 103, 106, 113, 126, 0xE9, 0xF1, 0x416, 0x2588, 0x2192]
def store(pkg):
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
def refs(ctx, paths):
code = open(os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ref.py")).read()
raw = ctx.python(["freetype-py"], code, input=json.dumps({"fonts": [{"path": p, "chars": CHARS} for p in paths]}).encode())
return json.loads(raw)
def generate(ctx):
spleen = os.path.join(store("spleen"), "share", "fonts", "misc")
tamzen = os.path.join(store("tamzen"), "share", "fonts", "misc")
misc = os.path.join(store("xorg.fontmiscmisc"), "share", "fonts", "X11", "misc")
tmp = A.tmpdir()
try:
items = [] # (name, format, path, gz)
for f in ("spleen-5x8.bdf", "spleen-12x24.bdf"):
items.append((f, "bdf", os.path.join(spleen, f), False))
src = os.path.join(spleen, "spleen-5x8.bdf")
for opts in (["-p1", "-u1", "-m"], ["-p2", "-u2", "-l"], ["-p4", "-u4", "-m"], ["-p8", "-u4", "-l"], ["-p4", "-u1", "-l", "-t"]):
out = os.path.join(tmp, "spleen-5x8" + "".join(opts) + ".pcf")
A.tool(["xorg.bdftopcf"], ["bdftopcf"] + opts + ["-o", out, src])
items.append(("spleen-5x8 bdftopcf " + " ".join(opts), "pcf", out, False))
out = os.path.join(tmp, "spleen-12x24.pcf")
A.tool(["xorg.bdftopcf"], ["bdftopcf", "-o", out, os.path.join(spleen, "spleen-12x24.bdf")])
items.append(("spleen-12x24 bdftopcf", "pcf", out, False))
for f in ("Tamzen7x13r.pcf", "Tamzen10x20b.pcf"):
items.append((f, "pcf", os.path.join(tamzen, f), False))
for f in ("6x13-ISO8859-1.pcf.gz", "9x18B-ISO8859-5.pcf.gz"):
items.append((f, "pcf", os.path.join(misc, f), True))
# Windows FNT / FON by FontForge from the Spleen BDFs (one strike, and a .fon with two)
for bdf, label in (("spleen-8x16.bdf", "8x16"), ("spleen-5x8.bdf", "5x8")):
fn = os.path.join(tmp, "spleen-%s.fnt" % label)
A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Generate($2, "fnt")', os.path.join(spleen, bdf), fn])
fnts = [f for f in os.listdir(tmp) if f.startswith("spleen-%s-" % label) and f.endswith(".fnt")]
items.append(("spleen-%s.fnt (fontforge)" % label, "fon", os.path.join(tmp, fnts[0]), False))
fon = os.path.join(tmp, "spleen-two.fon")
A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Import($2); Generate($3, "fon")',
os.path.join(spleen, "spleen-8x16.bdf"), os.path.join(spleen, "spleen-12x24.bdf"), fon])
items.append(("spleen 8x16 + 12x24 .fon (fontforge)", "fon", fon, False))
# FreeType reads .pcf.gz itself
rs = refs(ctx, [p for _, _, p, _ in items])
fonts = []
for (name, fmt, path, gz), ref in zip(items, rs):
for g in ref["glyphs"]:
g["pixels"] = bytes.fromhex(g["pixels"])
e = {"name": name, "format": fmt, "data": open(path, "rb").read(), "ref": ref}
if gz:
e["gz"] = True
fonts.append(e)
# our BDF writer, read back by FreeType
ctx.emit("bitmapfonts_src", {"fonts": [{k: v for k, v in f.items() if k != "ref"} for f in fonts]})
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
exe = shutil.which("luau")
argv = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ours.luau")]
r = subprocess.run(argv, capture_output=True, cwd=ctx.root)
ours = {}
for line in r.stdout.decode().splitlines():
n, h = line.rsplit(" ", 1)
p = os.path.join(tmp, "ours-%d.bdf" % len(ours))
open(p, "wb").write(bytes.fromhex(h))
ours[n] = p
names = list(ours)
back = refs(ctx, [ours[n] for n in names]) if names else []
for f in fonts:
if f["name"] in ours:
b = back[names.index(f["name"])]
want = {(g["cp"], g["width"], g["height"], g["left"], g["top"], g["advance"], g["pixels"].hex()) for g in f["ref"]["glyphs"]}
got = {(g["cp"], g["width"], g["height"], g["left"], g["top"], g["advance"], g["pixels"]) for g in b["glyphs"]}
diff = sorted(want ^ got)[:2]
f["ours"] = {"ok": want == got, "detail": "%d glyphs, %d differ %s" % (len(want), len(want ^ got), [d[:6] for d in diff])}
if not f["ref"]["unicode"]:
f["ours"] = {"ok": True, "detail": "not a Unicode font: FreeType maps byte codes, our BDF leaves them unmapped"}
else:
f["ours"] = {"ok": False, "detail": "no output: " + r.stderr.decode(errors="replace")[-300:]}
ctx.emit("bitmapfonts", {"fonts": fonts})
finally:
A.rmtree(tmp)
+247
View File
@@ -0,0 +1,247 @@
# Cabinet fixtures (tools/fixtures.py): cabinets by gcab (stored and MSZIP folders, paths), lcab (stored), our own
# minimal cabinet builder below (MSZIP blocks deflated with the previous block as the zlib dictionary, several
# folders, reserve areas, attributes, UTF-8 names; LZX and Quantum folders from the fixture compressors _lzx.py /
# _quantum.py, since no packaged tool writes them), the libmspack test cabinets read from the nix store (test data,
# not committed: normal / reserve / multi-part / mszip_lzx_qtm samples and the broken ones), and our writer's output.
# The reference data is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); every fixture
# LZX / Quantum cabinet must extract with cabextract to the original bytes, and cabextract, gcab and 7z must extract
# our writer's cabinets to the same bytes.
# tests/gen/cab.luau { cases = { { name, data, entries = { { name, size, crc, mtime } } } }, ours = { ok, log },
# spanned = { { name, data } }, bad = { { name, data } } }
import calendar, importlib.util, os, re, struct, subprocess, time, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
_s = importlib.util.spec_from_file_location("_lzx", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_lzx.py"))
L = importlib.util.module_from_spec(_s)
_s.loader.exec_module(L)
_s = importlib.util.spec_from_file_location("_quantum", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_quantum.py"))
Q = importlib.util.module_from_spec(_s)
_s.loader.exec_module(Q)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py", "tools/fixtures/_quantum.py"]
ENV = dict(os.environ, TZ="UTC")
def checksum(data, seed=0):
"""the CFDATA checksum ([MS-CAB] 2.4)"""
s = seed
n = len(data) - len(data) % 4
for i in range(0, n, 4):
s ^= struct.unpack_from("<I", data, i)[0]
t = 0
for b in data[n:]:
t = (t << 8) | b
return s ^ t
def dos(t):
y, mo, d, h, mi, s = time.gmtime(t)[:6]
return ((y - 1980) << 9) | (mo << 5) | d, (h << 11) | (mi << 5) | (s // 2)
def build(folders, reserve=None):
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(stream) -> [(payload, size)])];
reserve = (header bytes, folder size, data size)"""
hres, fres, dres = reserve or (b"", 0, 0)
flags = 4 if reserve else 0
head = 36 + (4 + len(hres) if reserve else 0)
nfiles = sum(len(f[1]) for f in folders)
files = b""
blocks = []
for fi, (typ, fl, enc) in enumerate(folders):
off = 0
stream = b""
for name, data, attr, mt in fl:
d, t = dos(mt)
files += struct.pack("<IIHHHH", len(data), off, fi, d, t, attr) + name + b"\0"
off += len(data)
stream += data
blocks.append(enc(stream))
coff = head + len(folders) * (8 + fres)
dat = coff + len(files)
folder_tab = b""
data = b""
for (typ, _, _), bl in zip(folders, blocks):
folder_tab += struct.pack("<IHH", dat + len(data), len(bl), typ) + b"\0" * fres
for payload, n in bl:
csum = checksum(struct.pack("<HH", len(payload), n), checksum(payload))
data += struct.pack("<IHH", csum, len(payload), n) + b"\x5a" * dres + payload
total = coff + len(files) + len(data)
hdr = b"MSCF" + struct.pack("<IIIIIBBHHHHH", 0, total, 0, coff, 0, 3, 1, len(folders), nfiles, flags, 0x1234, 0)
if reserve:
hdr += struct.pack("<HBB", len(hres), fres, dres) + hres
return hdr + folder_tab + files + data
def chunks(stream):
return [stream[s:s + 32768] for s in range(0, len(stream), 32768)]
def store(stream):
return [(c, len(c)) for c in chunks(stream)]
def mszip_dict(stream):
out, prev = [], b""
for chunk in chunks(stream):
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
out.append((b"CK" + c.compress(chunk) + c.flush(), len(chunk)))
prev = chunk
return out
def lzx(wbits, e8size=0, seed=1, plan=None):
def enc(stream):
data, frames = L.compress(stream, wbits, e8size, seed, plan)
out, p = [], 0
for i, n in enumerate(frames):
out.append((data[p:p + n], min(32768, len(stream) - i * 32768)))
p += n
assert p == len(data)
return out
return enc
def quantum(wbits):
def enc(stream):
frames = Q.compress(stream, wbits)
return [(f, min(32768, len(stream) - i * 32768)) for i, f in enumerate(frames)]
return enc
LIST = re.compile(r"^\s*(\d+) \| (\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d):(\d\d) \| (.*)$")
def reference(path, tmp, tag):
"""cabextract's listing (name -> mtime) and extraction (name -> size, crc)"""
listing = A.tool(["cabextract"], ["cabextract", "-l", path]).decode("utf-8", "replace")
times = {}
for line in listing.splitlines():
m = LIST.match(line)
if m:
d, mo, y, h, mi, s = (int(x) for x in m.group(2, 3, 4, 5, 6, 7))
times[m.group(8).replace("\\", "/")] = calendar.timegm((y, mo, d, h, mi, s))
out = os.path.join(tmp, "x-" + tag)
os.makedirs(out)
subprocess.run(["nix", "shell", "nixpkgs#cabextract", "-c", "cabextract", "-q", "-d", out, path], check=True,
capture_output=True, env=ENV)
ents = []
for n, c in sorted(A.read_tree(out).items()):
e = {"name": n, "size": os.path.getsize(os.path.join(out, n)), "crc": c}
if n in times:
e["mtime"] = times[n]
ents.append(e)
return ents
def mspack_cabs():
"""the libmspack source's test cabinets (nix store path of its tarball, unpacked into a temporary directory)"""
src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#libmspack.src"], check=True,
capture_output=True).stdout.decode().strip()
return src
def generate(ctx):
rng = ctx.rng(47)
tmp = A.tmpdir()
try:
work = os.path.join(tmp, "w")
text = b"the quick brown fox jumps over the lazy dog\n" * 3000
rand = rng.randbytes(70000)
A.tree(A.FILES + [("dir/sub/text.txt", text), ("dir/rand.bin", rand),
("dir/runs.bin", b"\0" * 50000 + b"\xff" * 30000)], work)
names = [n for n, _ in A.FILES] + ["dir/sub/text.txt", "dir/rand.bin", "dir/runs.bin"]
cases = []
def add(name, path):
cases.append({"name": name, "data": open(path, "rb").read(), "entries": reference(path, tmp, str(len(cases)))})
for z in ("", "-z"):
arc = os.path.join(tmp, "gcab%s.cab" % z)
A.tool(["gcab"], ["gcab", "-c"] + ([z] if z else []) + [arc] + names, cwd=work)
add("gcab " + (z or "store"), arc)
arc = os.path.join(tmp, "lcab.cab")
A.tool(["lcab"], ["lcab", "-r", "dir", "hello.txt", arc], cwd=work)
add("lcab", arc)
# our builder: MSZIP with the dictionary, two folders (stored + MSZIP), reserve areas, attributes, UTF-8
big = text + rand[:20000] + text[:50000]
cab1 = build([(1, [(b"a\\text.txt", big, 0x20, 1700000000), (b"b.bin", rand, 0x01, 1600000000)], mszip_dict)])
cab2 = build([(0, [(b"stored.txt", b"stored data " * 5000, 0x20, 1700000000)], store),
(1, [("naïve ☃.txt".encode(), text, 0x80 | 0x20, 1700000002), (b"empty", b"", 0x20, 1700000000)], mszip_dict)],
reserve=(b"HEADER-RESERVE", 6, 3))
for i, c in enumerate((cab1, cab2)):
p = os.path.join(tmp, "built%d.cab" % i)
open(p, "wb").write(c)
A.tool(["cabextract"], ["cabextract", "-t", p]) # checksums and data as cabextract reads them
add(("mszip with dictionary", "two folders, reserve, utf-8")[i], p)
# LZX (our fixture compressor, checked by cabextract): windows 2^15 .. 2^21, the three block types, E8
x86 = bytearray(rng.randbytes(90000))
for i in range(0, len(x86) - 5, 23):
x86[i] = 0xE8
x86 = bytes(x86) + text[:40000]
lzx_cases = [
("lzx 2^15 text", 15, 0, [(b"t.txt", text[:100000])], None),
("lzx 2^16 mixed", 16, 0, [(b"a.txt", text), (b"b.bin", rand[:30000]), (b"c.txt", text[:5000])], None),
("lzx 2^17 types", 17, 0, [(b"m.bin", big)], [(1, 40000), (2, 30001), (3, 7777), (2, 50000), (3, 4), (1, len(big) - 127782)]),
("lzx 2^21 e8", 21, 12000000, [(b"x86.exe", x86), (b"tail.txt", text[:3000])], None),
("lzx 2^18 e8 small", 18, 70000, [(b"s.bin", x86[:20000])], [(2, 20000)]),
]
for i, (label, wb, e8size, fl, plan) in enumerate(lzx_cases):
c = build([(3 | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], lzx(wb, e8size, 100 + i, plan))])
p = os.path.join(tmp, "lzx%d.cab" % i)
open(p, "wb").write(c)
ents = reference(p, tmp, "lzx%d" % i)
want = {n.decode(): zlib.crc32(d) for n, d in fl}
if {e["name"]: e["crc"] for e in ents} != want:
raise RuntimeError("cabextract does not extract the fixture LZX cabinet " + label)
cases.append({"name": label, "data": c, "entries": ents})
# Quantum (our fixture compressor, checked by cabextract): windows 2^10 .. 2^21, model rescaling and re-sorting
quantum_cases = [
("quantum 2^10 text", 10, [(b"q.txt", text[:20000])]),
("quantum 2^16 mixed", 16, [(b"a.txt", text[:60000]), (b"b.bin", rand[:20000]), (b"c.bin", x86[:30000])]),
("quantum 2^21 big", 21, [(b"big.bin", big)]),
]
for i, (label, wb, fl) in enumerate(quantum_cases):
c = build([(2 | (4 << 4) | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], quantum(wb))])
p = os.path.join(tmp, "qtm%d.cab" % i)
open(p, "wb").write(c)
ents = reference(p, tmp, "qtm%d" % i)
want = {n.decode(): zlib.crc32(d) for n, d in fl}
if {e["name"]: e["crc"] for e in ents} != want:
raise RuntimeError("cabextract does not extract the fixture Quantum cabinet " + label)
cases.append({"name": label, "data": c, "entries": ents})
# the libmspack test cabinets
ms = os.path.join(tmp, "ms")
os.makedirs(ms)
subprocess.run(["tar", "xzf", mspack_cabs(), "-C", ms, "--wildcards", "*/test/test_files/cabd/*.cab"], check=True)
cabd = os.path.join(ms, os.listdir(ms)[0], "test", "test_files", "cabd")
for n in ("normal_2files_1folder", "normal_2files_2folders", "normal_255c_filename", "reserve_---", "reserve_--D",
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD", "mszip_lzx_qtm"):
add("libmspack " + n, os.path.join(cabd, n + ".cab"))
spanned = [{"name": n, "data": open(os.path.join(cabd, n + ".cab"), "rb").read()}
for n in ("multi_basic_pt1", "multi_basic_pt2", "multi_basic_pt3")]
# broken cabinets cabextract fails on (crafted bad trees, loops, short headers / strings)
bad = [{"name": n, "data": open(os.path.join(cabd, n), "rb").read()} for n in sorted(os.listdir(cabd))
if n.endswith(".cab") and (n.startswith(("partial_", "bad_", "lzx-")) or (n.startswith("cve-") and "9732" not in n))]
# our writer, extracted by the reference tools
log, ok = [], True
for opts in ("compression=mszip", "compression=none", "compression=mszip,level=1"):
data = A.ours(ctx, "cab", opts)
p = os.path.join(tmp, "ours.cab")
open(p, "wb").write(data)
for tool, argv in (("cabextract", ["cabextract", "-q", "-d", "{o}", p]), ("gcab", ["gcab", "-x", "-C", "{o}", p]),
("p7zip", ["7z", "x", "-o{o}", p])):
out = os.path.join(tmp, "o-%s-%d" % (tool, len(log)))
os.makedirs(out)
r = subprocess.run(["nix", "shell", "nixpkgs#" + tool, "-c"] + [a.replace("{o}", out) for a in argv],
capture_output=True, env=ENV)
got = A.read_tree(out)
want = {n: zlib.crc32(d) for n, d in A.FILES}
good = r.returncode == 0 and got == want
ok = ok and good
log.append("%s %s: %s" % (opts, tool, "ok" if good else "FAILED %r" % (got,)))
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned, "bad": bad})
finally:
A.rmtree(tmp)
+110
View File
@@ -0,0 +1,110 @@
# cpio fixtures (tools/fixtures.py): GNU cpio (nixpkgs#cpio, --reproducible) archives of one tree in newc / crc / odc /
# bin, the bin one byte-swapped into the big-endian old binary format, bsdtar (libarchive) newc / odc archives, a crafted
# newc archive with device nodes and a bad crc sum, and a .cpio.gz. The expected entries come from os.lstat of the tree.
# tests/gen/cpio.luau { archives = { { name, data, format, gnu?, entries = { { name, type, mode, size, mtime, nlink,
# link?, crc? } } } }, devices = data, badcrc = data, gz = data }
import gzip, os, shutil, stat, struct, subprocess, tempfile, zlib
TYPES = {stat.S_IFREG: "0", stat.S_IFDIR: "5", stat.S_IFLNK: "2", stat.S_IFIFO: "6", stat.S_IFCHR: "3", stat.S_IFBLK: "4"}
def run(ctx, pkg, script, cwd):
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", script], cwd=cwd, capture_output=True, check=True).stdout
def swap_bin(data):
"""the little-endian old binary archive -> the big-endian one (every u16 header field swapped)"""
out, p = bytearray(), 0
while True:
f = struct.unpack("<13H", data[p:p + 26])
ns, fs = f[10], f[11] << 16 | f[12]
name = data[p + 26:p + 26 + ns - 1]
out += struct.pack(">13H", *f)
q = p + 26 + ns + (ns & 1)
e = q + fs + (fs & 1)
out += data[p + 26:e]
p = e
if name == b"TRAILER!!!":
return bytes(out + data[p:])
def newc(name, mode, size=0, data=b"", nlink=1, rdev=(0, 0), check=0, ino=1, crc=False):
ns = len(name) + 1
h = b"070701" + b"".join(b"%08X" % v for v in (ino, mode, 0, 0, nlink, 1600000000, size, 0, 0, rdev[0], rdev[1], ns, check))
if crc:
h = b"070702" + h[6:]
b = h + name + b"\0"
b += b"\0" * (-len(b) % 4) + data + b"\0" * (-len(data) % 4)
return b
def generate(ctx):
rng = ctx.rng(11)
files = [
("hello.txt", b"hello, cpio\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(3000)),
("exact4", b"four"),
("odd", b"x" * 7),
("d" * 60 + "/" + "e" * 80 + "/a-name-longer-than-a-hundred-bytes.txt", b"long " * 40),
("unicodé/naïve.txt", "ünïcödé".encode()),
]
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
for name, data in files:
p = os.path.join(root, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.chmod(os.path.join(root, "odd"), 0o755)
os.makedirs(os.path.join(root, "emptydir"))
os.symlink("hello.txt", os.path.join(root, "sym"))
os.symlink("dir/sub/data.bin", os.path.join(root, "dir/sublink"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "dir/hard2"))
os.mkfifo(os.path.join(root, "fifo"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False)
os.utime(root, (1650000000, 1650000000))
names = sorted(subprocess.run(["find", "."], cwd=root, capture_output=True, check=True).stdout.decode().split("\n")[:-1])
names = [n[2:] if n.startswith("./") else n for n in names]
def expected():
out = []
for n in names:
st = os.lstat(os.path.join(root, n))
t = TYPES[stat.S_IFMT(st.st_mode)]
e = {"name": n, "type": t, "mode": stat.S_IMODE(st.st_mode), "mtime": int(st.st_mtime), "nlink": st.st_nlink,
"size": st.st_size if t == "0" else 0}
if t == "2":
e["link"] = os.readlink(os.path.join(root, n))
if t == "0":
with open(os.path.join(root, n), "rb") as f:
e["crc"] = zlib.crc32(f.read())
out.append(e)
return out
want = expected()
listing = "find . | LC_ALL=C sort | "
archives = []
for fmt in ("newc", "crc", "odc", "bin"):
data = run(ctx, "cpio", listing + "cpio -o -H %s --reproducible 2>/dev/null" % fmt, root)
archives.append({"name": "gnu-" + fmt, "data": data, "format": fmt, "gnu": True, "entries": want})
archives.append({"name": "gnu-binbe", "data": swap_bin(archives[3]["data"]), "format": "binbe", "entries": want})
for fmt in ("newc", "odc"):
data = run(ctx, "libarchive", listing + "sed 's|^\\./||' | bsdtar --format=%s -n -cf - -T -" % fmt, root)
archives.append({"name": "bsdtar-" + fmt, "data": data, "format": fmt, "entries": want})
gz = gzip.compress(archives[0]["data"], mtime=0)
finally:
shutil.rmtree(tmp)
devices = b"".join([
newc(b"dev", 0o040755, nlink=2, ino=1),
newc(b"dev/null", 0o020666, rdev=(1, 3), ino=2),
newc(b"dev/sda", 0o060660, rdev=(8, 0), ino=3),
newc(b"dev/sock", 0o140755, ino=4),
newc(b"TRAILER!!!", 0, ino=0),
])
badcrc = newc(b"f", 0o100644, 3, b"abc", check=1, crc=True) + newc(b"TRAILER!!!", 0, ino=0, crc=True)
ctx.emit("cpio", {"archives": archives, "devices": devices, "badcrc": badcrc, "gz": gz})
+73
View File
@@ -0,0 +1,73 @@
# Commodore disk image fixtures (tools/fixtures.py): D64 / D71 / D81 images formatted and filled by VICE's `c1541`
# (PRG / SEQ / USR files, a multi-sector file, a deleted file, a full-ish directory), a D64 with the error-info block
# appended; every file read back by `c1541 -read` for the reference data. Our writer's D64 / D71 / D81 output
# (tools/fixtures/_arch2_ours.luau) is listed and read back by c1541.
# tests/gen/d64.luau { cases = { { name, data, disk, id, entries = { { name, size, crc, type } } } },
# ours = { { variant, ok, listing } } }
import importlib.util, os, shutil, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/d64"]
PKG = ["vice"]
def c1541(args, cwd):
return A.tool(PKG, ["c1541"] + args, cwd=cwd).decode(errors="replace")
def generate(ctx):
rng = ctx.rng(64)
tmp = A.tmpdir()
try:
files = [("hello", ",p", b"\x01\x08hello prg\n"), ("big data", ",s", rng.randbytes(9000)), ("user file", ",u", b"USR " * 100),
("exact", ",p", rng.randbytes(254 * 3)), ("one", ",p", b"\x00")]
for i, (_, _, d) in enumerate(files):
open(os.path.join(tmp, "f%d" % i), "wb").write(d)
cases = []
for kind, label in (("d64", "test disk,ab"), ("d71", "double,cd"), ("d81", "three d,ef")):
img = "t." + kind
args = ["-format", label, kind, img]
for i, (name, suf, _) in enumerate(files):
args += ["-write", "f%d" % i, name + suf]
args += ["-write", "f0", "gone", "-delete", "gone"]
c1541(args, tmp)
ents = []
for i, (name, suf, d) in enumerate(files):
out = os.path.join(tmp, "out%d" % i)
c1541([img, "-read", name + suf, out], tmp)
rd = open(out, "rb").read()
assert rd == d, (kind, name, len(rd), len(d))
ents.append({"name": name, "size": len(rd), "crc": zlib.crc32(rd), "type": {"p": "prg", "s": "seq", "u": "usr"}[suf[1]]})
data = open(os.path.join(tmp, img), "rb").read()
disk, did = label.split(",")
cases.append({"name": kind, "data": data, "disk": disk, "id": did, "entries": ents})
if kind == "d64":
cases.append({"name": "d64 with error info", "data": data + b"\x01" * 683, "disk": disk, "id": did, "entries": ents})
# many files: several directory sectors
args = ["-format", "many,mm", "d64", "many.d64"]
for i in range(30):
args += ["-write", "f0", "file%02d" % i]
c1541(args, tmp)
d0 = files[0][2]
cases.append({"name": "30 files", "data": open(os.path.join(tmp, "many.d64"), "rb").read(), "disk": "many", "id": "mm",
"entries": [{"name": "file%02d" % i, "size": len(d0), "crc": zlib.crc32(d0), "type": "prg"} for i in range(30)]})
ours = []
for variant in ("d64", "d71", "d81"):
img = os.path.join(tmp, "ours." + variant)
open(img, "wb").write(A.ours(ctx, "d64", "variant=" + variant))
listing = c1541([img, "-list"], tmp)
ok = True
for name, data in A.FILES:
if not data:
continue # c1541 reads a one-sector file with no data bytes (link 0/1) as 254 bytes
out = os.path.join(tmp, "o-" + name)
c1541([img, "-read", name + suf, out], tmp)
got = open(out, "rb").read() if os.path.exists(out) else None
ok = ok and got == data
ours.append({"variant": variant, "ok": ok, "listing": listing})
ctx.emit("d64", {"cases": cases, "ours": ours})
finally:
shutil.rmtree(tmp)
+70
View File
@@ -0,0 +1,70 @@
# Docs inputs for the archive page's encodings / disk images / LHA-ARJ-Zoo sections and the font page's bitmap and
# Type 1 sections (tools/fixtures.py; tools/docs_check.py explains the inputs): a uuencoded file (sharutils), an
# .lzh (LHa for UNIX), an .arj (arj), a .zoo (built as tools/fixtures/zoo.py does), a D64 (VICE c1541), an ADF
# (amitools xdftool), a FAT floppy (mkfs.fat + mtools), BDF / PSF from Spleen, a PCF by bdftopcf, a .fnt by FontForge,
# Latin Modern's lmr10.pfb, an EOT around DejaVu Sans Mono (built as tools/fixtures/eot.py does) and a JHF text.
# tests/gen/docs_arch2.luau { files = { [name] = bytes }, vars = { uuText = "notes.uu", ... } }
import importlib.util, json, os, shutil, subprocess
HERE = os.path.dirname(os.path.abspath(__file__))
INPUTS = ["tools/docs_check.py", "tools/fixtures/_arch2.py", "tools/fixtures/zoo.py", "tools/fixtures/eot.py", "tools/fixtures/hershey.py"]
def mod(name, path):
spec = importlib.util.spec_from_file_location(name, path)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def store(pkg):
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
def generate(ctx):
dc = mod("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
A = mod("_arch2", os.path.join(HERE, "_arch2.py"))
zoo = mod("zoo_fx", os.path.join(HERE, "zoo.py"))
eot = mod("eot_fx", os.path.join(HERE, "eot.py"))
hershey = mod("hershey_fx", os.path.join(HERE, "hershey.py"))
os.environ["MTOOLS_SKIP_CHECK"] = "1"
os.environ["TZ"] = "UTC"
files = {}
tmp = A.tmpdir()
try:
tree = [("readme.txt", b"formats-luau retro archives\n"), ("src/main.c", b"int main(void) { return 0; }\n")]
A.tree(tree, tmp)
files["notes.uu"] = A.tool(["sharutils"], ["uuencode", "readme.txt", "readme.txt"], cwd=tmp)
A.tool([], ["env", "NIXPKGS_ALLOW_UNFREE=1", "nix", "shell", "--impure", "nixpkgs#lha", "-c", "lha", "-a2o5q", "tree.lzh", "readme.txt", "src"], cwd=tmp)
files["tree.lzh"] = open(os.path.join(tmp, "tree.lzh"), "rb").read()
A.tool(["arj"], ["arj", "a", "-m1", "-r", "-y", "tree.arj", "readme.txt", "src"], cwd=tmp)
files["tree.arj"] = open(os.path.join(tmp, "tree.arj"), "rb").read()
data = tree[0][1]
files["tree.zoo"] = zoo.archive([("readme.txt", "", 1, zoo.lzw(data), len(data), zoo.crc16(data), 2, 0, None)])
A.tool(["vice"], ["c1541", "-format", "games,gd", "d64", "games.d64", "-write", "readme.txt", "readme"], cwd=tmp)
files["games.d64"] = open(os.path.join(tmp, "games.d64"), "rb").read()
A.tool(["uv"], ["uvx", "--from", "amitools==0.8.1", "xdftool", "work.adf", "-f", "create", "size=880K", "+", "format", "Work", "ffs",
"+", "makedir", "s", "+", "write", "readme.txt", "s/readme"], cwd=tmp)
files["work.adf"] = open(os.path.join(tmp, "work.adf"), "rb").read()
A.tool(["dosfstools"], ["mkfs.fat", "-C", "-F", "12", "-n", "DOCS", "floppy.img", "720"], cwd=tmp)
A.tool(["mtools"], ["mcopy", "-s", "-m", "-i", "floppy.img", "readme.txt", "src", "::/"], cwd=tmp)
files["floppy.img"] = open(os.path.join(tmp, "floppy.img"), "rb").read()
spleen = os.path.join(store("spleen"), "share", "fonts", "misc")
files["spleen-5x8.bdf"] = open(os.path.join(spleen, "spleen-5x8.bdf"), "rb").read()
A.tool(["xorg.bdftopcf"], ["bdftopcf", "-o", os.path.join(tmp, "spleen.pcf"), os.path.join(spleen, "spleen-5x8.bdf")])
files["spleen-5x8.pcf"] = open(os.path.join(tmp, "spleen.pcf"), "rb").read()
files["spleen-8x16.psfu"] = open(os.path.join(store("spleen"), "share", "consolefonts", "spleen-8x16.psfu"), "rb").read()
A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Generate($2, "fnt")', os.path.join(spleen, "spleen-8x16.bdf"), os.path.join(tmp, "spleen.fnt")])
fnt = [f for f in os.listdir(tmp) if f.endswith(".fnt")][0]
files["spleen.fnt"] = open(os.path.join(tmp, fnt), "rb").read()
files["lmr10.pfb"] = open(os.path.join(store("lmodern"), "share", "fonts", "type1", "public", "lm", "lmr10.pfb"), "rb").read()
dejavu = os.path.join(store("dejavu_fonts"), "share", "fonts", "truetype", "DejaVuSansMono.ttf")
facts = json.loads(ctx.python(["fonttools"], eot.CODE, input=json.dumps([dejavu]).encode()))[0]
files["mono.eot"] = eot.eot(open(dejavu, "rb").read(), facts, 0x00020001)
files["roman.jhf"] = (hershey.record(699, -8, 8, []) + "\n" + hershey.record(501, -9, 9, [[(0, -12), (-8, 9)], [(0, -12), (8, 9)], [(-5, 2), (5, 2)]]) + "\n").encode()
finally:
A.rmtree(tmp)
dc.emit_inputs(ctx, files, {"uuText": "notes.uu", "lzhBytes": "tree.lzh", "arjBytes": "tree.arj", "zooBytes": "tree.zoo",
"d64Bytes": "games.d64", "adfBytes": "work.adf", "floppyBytes": "floppy.img",
"bdfText": "spleen-5x8.bdf", "pcfBytes": "spleen-5x8.pcf", "psfBytes": "spleen-8x16.psfu",
"fntBytes": "spleen.fnt", "pfbBytes": "lmr10.pfb", "eotBytes": "mono.eot", "jhfText": "roman.jhf"})
+30
View File
@@ -0,0 +1,30 @@
# Docs inputs for the archive page's Cabinet section (tools/fixtures.py; tools/docs_check.py explains the inputs): an
# MSZIP cabinet of a small tree by gcab.
# tests/gen/docs_arch_cab.luau { files = { [name] = bytes }, vars = { cabBytes = "setup.cab" } }
import importlib.util, os, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
MTIME = 1767225600 # 2026-01-01T00:00:00Z
def docs_check(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = docs_check(ctx)
files = {}
with tempfile.TemporaryDirectory() as d:
os.makedirs(os.path.join(d, "bin"))
for n, data in (("readme.txt", b"formats-luau cabinet\n" * 20), ("bin/tool.dll", bytes(range(256)) * 64)):
with open(os.path.join(d, n), "wb") as f:
f.write(data)
os.utime(os.path.join(d, n), (MTIME, MTIME))
subprocess.run(["nix", "shell", "nixpkgs#gcab", "-c", "gcab", "-c", "-z", "setup.cab", "readme.txt", "bin/tool.dll"],
cwd=d, check=True, capture_output=True, env=dict(os.environ, TZ="UTC"))
files["setup.cab"] = open(os.path.join(d, "setup.cab"), "rb").read()
dc.emit_inputs(ctx, files, {"cabBytes": "setup.cab"})
+81
View File
@@ -0,0 +1,81 @@
# Docs inputs for the archive page's Unix / package sections (tools/fixtures.py; tools/docs_check.py explains the
# inputs): a newc cpio by GNU cpio, a .deb by dpkg-deb, an .rpm by rpmbuild, a .tar.Z by ncompress, an ISO image by
# xorriso (-J -R, with an El Torito boot image) and an .lz4 by the lz4 tool, all of one small tree.
# tests/gen/docs_arch_unix.luau { files = { [name] = bytes }, vars = { cpioBytes = "tree.cpio", ... } }
import importlib.util, io, os, subprocess, tarfile, tempfile
INPUTS = ["tools/docs_check.py"]
MTIME = 1767225600 # 2026-01-01T00:00:00Z
SPEC = """Name: hello
Version: 1.0
Release: 1
Summary: a greeting
License: MIT
BuildArch: noarch
%description
prints a greeting
%install
mkdir -p %{buildroot}/usr/bin
printf '#!/bin/sh\\necho hello\\n' > %{buildroot}/usr/bin/hello
chmod 755 %{buildroot}/usr/bin/hello
%files
/usr/bin/hello
"""
def docs_check(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def sh(pkgs, script, cwd, env=None):
argv = ["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c", "sh", "-c", script]
return subprocess.run(argv, cwd=cwd, capture_output=True, check=True, env=env).stdout
def generate(ctx):
dc = docs_check(ctx)
files = {}
env = dict(os.environ, SOURCE_DATE_EPOCH=str(MTIME))
with tempfile.TemporaryDirectory() as d:
tree = os.path.join(d, "tree")
os.makedirs(os.path.join(tree, "bin"))
with open(os.path.join(tree, "readme.txt"), "wb") as f:
f.write(b"formats-luau unix archives\n")
with open(os.path.join(tree, "bin", "run.sh"), "wb") as f:
f.write(b"#!/bin/sh\necho hi\n")
os.chmod(os.path.join(tree, "bin", "run.sh"), 0o755)
os.symlink("bin/run.sh", os.path.join(tree, "run"))
with open(os.path.join(tree, "boot.img"), "wb") as f:
f.write(b"\xfa\xeb\xfe" + bytes(2045))
for dirpath, dirs, fs in os.walk(tree):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
files["tree.cpio"] = sh(["cpio", "findutils"], "find readme.txt bin run | LC_ALL=C sort | cpio -o -H newc --reproducible 2>/dev/null", tree)
files["disc.iso"] = sh(["xorriso"], "xorriso -as mkisofs -quiet -no-pad -J -R -V DOCS -b boot.img -no-emul-boot -boot-load-size 4 -o - .", tree)
b = io.BytesIO()
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
for n in ("readme.txt", "bin/run.sh"):
t.add(os.path.join(tree, n), arcname=n)
files["src.tar.Z"] = subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f"], input=b.getvalue(),
capture_output=True, check=True).stdout
files["notes.txt.lz4"] = subprocess.run(["nix", "shell", "nixpkgs#lz4", "-c", "lz4", "-c"], input=b"formats-luau unix archives\n" * 8,
capture_output=True, check=True).stdout
pkg = os.path.join(d, "pkg")
os.makedirs(os.path.join(pkg, "DEBIAN"))
os.makedirs(os.path.join(pkg, "usr", "bin"))
with open(os.path.join(pkg, "DEBIAN", "control"), "w") as f:
f.write("Package: hello\nVersion: 1.0-1\nArchitecture: all\nMaintainer: Ada <[email protected]>\nDescription: a greeting\n")
with open(os.path.join(pkg, "usr", "bin", "hello"), "wb") as f:
f.write(b"#!/bin/sh\necho hello\n")
os.chmod(os.path.join(pkg, "usr", "bin", "hello"), 0o755)
files["hello.deb"] = sh(["dpkg"], "dpkg-deb --root-owner-group -Zxz --build pkg out.deb >/dev/null && cat out.deb", d, env)
with open(os.path.join(d, "hello.spec"), "w") as f:
f.write(SPEC)
sh(["rpm"], "rpmbuild --define '_topdir %s/top' --define '__os_install_post %%{nil}' --define '_build_id_links none' -bb hello.spec >/dev/null 2>&1" % d, d, env)
files["hello.rpm"] = open(os.path.join(d, "top", "RPMS", "noarch", "hello-1.0-1.noarch.rpm"), "rb").read()
dc.emit_inputs(ctx, files, {"cpioBytes": "tree.cpio", "isoBytes": "disc.iso", "tarZBytes": "src.tar.Z", "lz4Bytes": "notes.txt.lz4",
"debBytes": "hello.deb", "rpmBytes": "hello.rpm"})
+76
View File
@@ -0,0 +1,76 @@
# EOT fixtures (tools/fixtures.py): no EOT tool is packaged in nixpkgs, so Embedded OpenType files are built here per
# the W3C EOT submission (versions 1.0, 2.1 plain and XOR-obfuscated, 2.2 with an empty signature and EUDC data, one
# MTX-flagged file) around TrueType / CFF fonts (DejaVu Sans Mono from nixpkgs#dejavu_fonts, Source Sans 3 OTF from
# nixpkgs#source-sans); the header fields come from fontTools, and the inner font's facts (units per em, glyph count,
# cmap glyph ids, advances) from fontTools too.
# tests/gen/eot.luau { cases = { { name, data, version, xor, family, style, fullName, weight, fsType, upem,
# numGlyphs, glyphs = { { cp, gid, advance } } } }, mtx }
import json, os, struct, subprocess
CODE = r'''
import json, sys
from fontTools.ttLib import TTFont
out = []
for p in json.load(sys.stdin):
f = TTFont(p)
os2, head, name = f["OS/2"], f["head"], f["name"]
cmap = f.getBestCmap()
glyphs = []
order = f.getGlyphOrder()
for cp in (65, 97, 48, 0x20AC, 0x3A9):
if cp in cmap:
g = cmap[cp]
glyphs.append({"cp": cp, "gid": order.index(g), "advance": f["hmtx"][g][0]})
out.append({"panose": bytes([getattr(os2.panose, k) for k in ("bFamilyType", "bSerifStyle", "bWeight", "bProportion", "bContrast", "bStrokeVariation", "bArmStyle", "bLetterForm", "bMidline", "bXHeight")]).hex(),
"weight": os2.usWeightClass, "fsType": os2.fsType, "italic": os2.fsSelection & 1,
"ranges": [os2.ulUnicodeRange1, os2.ulUnicodeRange2, os2.ulUnicodeRange3, os2.ulUnicodeRange4],
"codepages": [getattr(os2, "ulCodePageRange1", 0), getattr(os2, "ulCodePageRange2", 0)],
"checksum": head.checkSumAdjustment, "upem": head.unitsPerEm, "numGlyphs": len(order),
"family": name.getDebugName(1) or "", "style": name.getDebugName(2) or "", "version": name.getDebugName(5) or "",
"full": name.getDebugName(4) or "", "glyphs": glyphs})
print(json.dumps(out))
'''
def store(pkg):
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
def utf16(s):
return s.encode("utf-16-le")
def eot(data, facts, version, xor=False, flags=0):
hdr = struct.pack("<IIII", 0, len(data), version, flags | (0x10000000 if xor else 0))
hdr += bytes.fromhex(facts["panose"]) + struct.pack("<BBIHH", 1, facts["italic"], facts["weight"], facts["fsType"], 0x504C)
hdr += struct.pack("<4I", *facts["ranges"]) + struct.pack("<2I", *facts["codepages"]) + struct.pack("<I", facts["checksum"]) + b"\0" * 16
for s in (facts["family"], facts["style"], facts["version"], facts["full"]):
u = utf16(s)
hdr += struct.pack("<HH", 0, len(u)) + u
if version >= 0x00020001:
u = utf16("https://example.com/")
hdr += struct.pack("<HH", 0, len(u)) + u
if version == 0x00020002:
hdr += struct.pack("<IIHH", 0x12345678, 0, 0, 0) + struct.pack("<II", 0, 4) + b"EUDC"
body = bytes(b ^ 0x50 for b in data) if xor else data
out = hdr + body
return struct.pack("<I", len(out)) + out[4:]
def generate(ctx):
dejavu = os.path.join(store("dejavu_fonts"), "share", "fonts", "truetype", "DejaVuSansMono.ttf")
otf = os.path.join(store("source-sans"), "share", "fonts", "opentype", "SourceSans3-Regular.otf")
facts = json.loads(ctx.python(["fonttools"], CODE, input=json.dumps([dejavu, otf]).encode()))
cases = []
for path, f in zip((dejavu, otf), facts):
data = open(path, "rb").read()
base = os.path.basename(path)
for label, ver, xor in (("1.0", 0x00010000, False), ("2.1", 0x00020001, False), ("2.1 xor", 0x00020001, True), ("2.2", 0x00020002, False)):
if base.endswith(".otf") and label != "2.1":
continue
cases.append({"name": "%s %s" % (base, label), "data": eot(data, f, ver, xor), "version": ver, "xor": xor,
"family": f["family"], "style": f["style"], "fullName": f["full"], "weight": f["weight"],
"fsType": f["fsType"], "upem": f["upem"], "numGlyphs": f["numGlyphs"], "glyphs": f["glyphs"],
"fontCrc": __import__("zlib").crc32(data)})
mtx = eot(open(dejavu, "rb").read()[:1000], facts[0], 0x00020001, flags=0x4)
ctx.emit("eot", {"cases": cases, "mtx": mtx})
+75
View File
@@ -0,0 +1,75 @@
# FAT disk image fixtures (tools/fixtures.py): FAT12 / FAT16 / FAT32 images made by dosfstools' `mkfs.fat` and filled
# by mtools' `mcopy -s` (long names, lower-case 8.3 names, non-ASCII names, nested directories, an empty file, files
# over many clusters), a hard-disk image with an MBR and a FAT16 partition (mkfs.fat --offset); the reference listing
# is the tree mtools extracts again (`mcopy -s`), dates under TZ=UTC. Our writer's floppies (tools/fixtures/
# _arch2_ours.luau) are checked by `fsck.fat -n` and extracted by mtools. Images are emitted gzip-compressed.
# tests/gen/fat.luau { cases = { { name, gz, bits, label?, entries = { { name, size?, crc?, dir?, mtime? } } } },
# ours = { { size, ok, fsck } } }
import gzip, importlib.util, os, shutil, struct, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/containers/Fat.luau", "src/Formats/archive/fat"]
PKGS = ["dosfstools", "mtools"]
def extract(img, out, tmp):
os.makedirs(out, exist_ok=True)
A.tool(PKGS, ["mcopy", "-s", "-n", "-m", "-i", img, "::/*", out + "/"], cwd=tmp)
return A.read_tree(out)
def generate(ctx):
os.environ["TZ"] = "UTC"
os.environ["MTOOLS_SKIP_CHECK"] = "1"
rng = ctx.rng(12)
tree = [("README.TXT", b"upper 8.3\n"), ("lower.txt", b"lower case 8.3\n"), ("Mixed Case Long Name.text", b"long\n"),
("docs/a very long file name that spans several entries.md", b"x" * 3000), ("docs/sub/deep/leaf.bin", rng.randbytes(20000)),
("empty.dat", b""), ("naïve café 日本.txt", "unicode".encode()), ("big.bin", rng.randbytes(150000))]
tmp = A.tmpdir()
try:
src = os.path.join(tmp, "src")
A.tree(tree, src)
dirs = {"docs/", "docs/sub/", "docs/sub/deep/"}
cases = []
for bits, kb, label in ((12, 1440, "FLOPPY"), (12, 720, None), (16, 16384, "SIXTEEN"), (32, 40960, "THIRTYTWO")):
img = os.path.join(tmp, "t%d-%d.img" % (bits, kb))
argv = ["mkfs.fat", "-C", "-F", str(bits)] + (["-n", label] if label else []) + [img, str(kb)]
A.tool(PKGS, argv, cwd=tmp)
items = [os.path.join(src, n) for n in os.listdir(src)]
A.tool(PKGS, ["mcopy", "-s", "-m", "-i", img] + items + ["::/"], cwd=tmp)
got = extract(img, os.path.join(tmp, "x%d-%d" % (bits, kb)), tmp)
ents = [{"name": d, "dir": True} for d in sorted(dirs)]
for n, d in tree:
assert got.get(n) == zlib.crc32(d), (img, n)
ents.append({"name": n, "size": len(d), "crc": zlib.crc32(d), "mtime": A.MTIME})
e = {"name": "fat%d %dK" % (bits, kb), "gz": gzip.compress(open(img, "rb").read(), mtime=0), "bits": bits, "entries": ents}
if label:
e["label"] = label
cases.append(e)
# a hard-disk image: MBR + a FAT16 partition at sector 2048
img = os.path.join(tmp, "hd.img")
A.tool(PKGS, ["mkfs.fat", "-C", "-F", "16", "--offset", "2048", "-n", "PART1", img, str(8192 + 1024)], cwd=tmp)
with open(img, "r+b") as f:
mbr = bytearray(512)
mbr[446:462] = struct.pack("<B3sB3sII", 0x80, b"\0\0\0", 0x06, b"\0\0\0", 2048, 8192 * 2)
mbr[510:512] = b"\x55\xaa"
f.write(mbr)
part = img + "@@1M"
A.tool(PKGS, ["mcopy", "-m", "-i", part, os.path.join(src, "README.TXT"), os.path.join(src, "big.bin"), "::/"], cwd=tmp)
got = extract(part, os.path.join(tmp, "xhd"), tmp)
cases.append({"name": "mbr fat16", "gz": gzip.compress(open(img, "rb").read(), mtime=0), "bits": 16, "label": "PART1",
"entries": [{"name": n, "size": len(d), "crc": got[n]} for n, d in tree if n in ("README.TXT", "big.bin")]})
ours = []
for size in (1440, 720):
img = os.path.join(tmp, "ours%d.img" % size)
open(img, "wb").write(A.ours(ctx, "fat", "size=%d,label=OURS" % size))
r = A.tool(PKGS, ["fsck.fat", "-n", img], cwd=tmp, check=False)
got = extract(img, os.path.join(tmp, "xo%d" % size), tmp)
ok = all(got.get(n) == zlib.crc32(d) for n, d in A.FILES)
ours.append({"size": size, "ok": ok, "fsck": r.decode(errors="replace")})
ctx.emit("fat", {"cases": cases, "ours": ours})
finally:
shutil.rmtree(tmp)
+59
View File
@@ -0,0 +1,59 @@
# Hershey JHF fixtures (tools/fixtures.py): no package in nixpkgs ships the .jhf files, so JHF text is written here in
# the distribution's layout (5-column id, 3-column count, extents and vertex pairs offset by "R", " R" pen-up, records
# wrapped at 72 columns), with glyphs of known strokes (a Roman-style "A", "H", "O" approximations and random stroke
# glyphs); the expected outlines come from the independent parser below.
# tests/gen/hershey.luau { text, glyphs = { { id, advance, cmds = { { op, x, y } } } } }
BASELINE = 9
def record(gid, left, right, strokes):
pairs = [chr(left + 82) + chr(right + 82)]
for k, s in enumerate(strokes):
if k:
pairs.append(" R")
pairs += [chr(x + 82) + chr(y + 82) for x, y in s]
body = "".join(pairs)
line = "%5d%3d" % (gid, len(pairs)) + body
return "\n".join(line[i:i + 72] for i in range(0, len(line), 72))
def parse(text):
lines = text.replace("\r", "").split("\n")
out, i = [], 0
while i < len(lines):
line = lines[i]
i += 1
if not line.strip():
continue
gid, n = int(line[:5]), int(line[5:8])
data = line[8:]
while len(data) < 2 * n:
data += lines[i]
i += 1
left, right = ord(data[0]) - 82, ord(data[1]) - 82
cmds, pen = [], False
for k in range(1, n):
a, b = data[2 * k], data[2 * k + 1]
if a == " " and b == "R":
pen = False
continue
cmds.append({"op": "lineTo" if pen else "moveTo", "x": ord(a) - 82 - left, "y": BASELINE - (ord(b) - 82)})
pen = True
out.append({"id": gid, "advance": right - left, "cmds": cmds})
return out
def generate(ctx):
rng = ctx.rng(1967)
recs = [record(699, -8, 8, []), # space
record(501, -9, 9, [[(0, -12), (-8, 9)], [(0, -12), (8, 9)], [(-5, 2), (5, 2)]]), # A
record(508, -11, 11, [[(-7, -12), (-7, 9)], [(7, -12), (7, 9)], [(-7, -2), (7, -2)]])] # H
ring = [(round(8 * __import__("math").cos(a / 10 * 6.2832)), round(-1.5 + 10 * __import__("math").sin(a / 10 * 6.2832))) for a in range(11)]
recs.append(record(515, -11, 11, [ring])) # O
for k in range(40):
strokes = []
for _ in range(1 + rng.randrange(4)):
strokes.append([(rng.randrange(-15, 16), rng.randrange(-16, 17)) for _ in range(1 + rng.randrange(30))])
recs.append(record(2000 + k, -rng.randrange(3, 12), rng.randrange(3, 12), strokes))
text = "\n".join(recs) + "\n"
ctx.emit("hershey", {"text": text, "glyphs": parse(text)})
+195
View File
@@ -0,0 +1,195 @@
# iso fixtures (tools/fixtures.py): ISO 9660 images of one tree built by xorriso (nixpkgs#xorriso: plain and Joliet
# with -rockridge off, then the mkisofs emulation -R, -J -R, an El Torito no-emulation boot image) and genisoimage (nixpkgs#cdrkit, -J -R: deep directories
# relocated to rr_moved, long names and symlink targets in CE continuation areas), plus a multi-extent file and an
# interleaved file crafted here by splitting / editing a directory record. Expected listings: the source tree (os.lstat)
# for Rock Ridge images, pycdlib (a second reader, run through nix python) for the plain and Joliet name sets.
# tests/gen/iso.luau { images = { { name, data (or same = the index of the image with the same data), tree, entries = { { name, dir, size?, crc?, mode?, link?, mtime? } } } },
# boot = { data, lba, sectors, catalog }, multi = { data, name, size, crc }, interleaved = data }
import json, os, shutil, stat, struct, subprocess, tempfile, zlib
MTIME = 1650000000
DUMP = r"""
import json, sys, io, zlib, pycdlib
path, kind = sys.argv[1], sys.argv[2]
iso = pycdlib.PyCdlib()
iso.open(path)
out = []
key = {"joliet": "joliet_path", "iso9660": "iso_path"}[kind]
for d, dirs, files in iso.walk(**{key: "/"}):
base = d.rstrip("/")
for n in dirs:
out.append({"name": (base + "/" + n).lstrip("/"), "dir": True})
for n in files:
p = base + "/" + n
b = io.BytesIO()
iso.get_file_from_iso_fp(b, **{key: p})
name = p.lstrip("/")
if ";" in name:
name = name[:name.rindex(";")]
if kind == "iso9660" and name.endswith("."):
name = name[:-1]
out.append({"name": name, "dir": False, "size": len(b.getvalue()), "crc": zlib.crc32(b.getvalue())})
iso.close()
sys.stdout.write(json.dumps(out))
"""
def sh(pkg, argv, cwd):
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c"] + argv, cwd=cwd, capture_output=True, check=True).stdout
def tree_entries(root, skip_deep=False):
out = []
for dirpath, dirs, files in os.walk(root):
dirs.sort()
for n in sorted(dirs + files):
p = os.path.join(dirpath, n)
rel = os.path.relpath(p, root)
st = os.lstat(p)
e = {"name": rel, "dir": stat.S_ISDIR(st.st_mode), "mode": stat.S_IMODE(st.st_mode), "mtime": MTIME}
if stat.S_ISLNK(st.st_mode):
e["link"] = os.readlink(p)
elif stat.S_ISREG(st.st_mode):
with open(p, "rb") as f:
d = f.read()
e["size"], e["crc"] = len(d), zlib.crc32(d)
out.append(e)
return out
def split_record(data, name, at_bytes):
"""a multi-extent copy: the directory record of name split into two records (the first flagged 0x80)"""
img = bytearray(data)
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
root_len = struct.unpack_from("<I", img, 16 * 2048 + 156 + 10)[0]
p, e = root_lba * 2048, root_lba * 2048 + root_len
while p < e:
ln = img[p]
if ln == 0:
p = (p // 2048 + 1) * 2048
continue
nl = img[p + 32]
if bytes(img[p + 33:p + 33 + nl]) == name:
rec = bytearray(img[p:p + ln])
size = struct.unpack_from("<I", rec, 10)[0]
lba = struct.unpack_from("<I", rec, 2)[0]
a, b2 = bytearray(rec), bytearray(rec)
struct.pack_into("<I", a, 10, at_bytes)
struct.pack_into(">I", a, 14, at_bytes)
a[25] |= 0x80
struct.pack_into("<I", b2, 2, lba + at_bytes // 2048)
struct.pack_into(">I", b2, 6, lba + at_bytes // 2048)
struct.pack_into("<I", b2, 10, size - at_bytes)
struct.pack_into(">I", b2, 14, size - at_bytes)
sector_end = (p // 2048 + 1) * 2048
used = sector_end
q = p + ln
while q < sector_end and img[q] != 0:
q += img[q]
assert q + ln <= sector_end, "no room in the directory sector"
img[p:q + ln] = a + b2 + img[p + ln:q]
return bytes(img), size
p += ln
raise Exception("record not found")
def set_interleave(data, name):
img = bytearray(data)
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
p = root_lba * 2048
while img[p]:
nl = img[p + 32]
if bytes(img[p + 33:p + 33 + nl]) == name:
img[p + 26], img[p + 27] = 1, 1
return bytes(img)
p += img[p]
raise Exception("record not found")
def generate(ctx):
rng = ctx.rng(29)
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
files = [
("hello.txt", b"hello, iso\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(5000)),
("big.bin", rng.randbytes(40000)),
("A File With Spaces And A Name Longer Than Sixty-Four Characters For Joliet.txt", b"long joliet\n"),
("unicodé/naïve.txt", "ünïcödé".encode()),
("run.sh", b"#!/bin/sh\necho hi\n"),
]
for n, d in files:
p = os.path.join(root, n)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(d)
os.chmod(os.path.join(root, "run.sh"), 0o755)
os.symlink("hello.txt", os.path.join(root, "link"))
os.makedirs(os.path.join(root, "emptydir"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
base_entries = tree_entries(root)
# a second tree with what only Rock Ridge holds: deep directories, a 200-byte name, a long symlink target
root2 = os.path.join(tmp, "tree2")
shutil.copytree(root, root2, symlinks=True)
deep = os.path.join(root2, *["d%d" % i for i in range(1, 11)])
os.makedirs(deep)
with open(os.path.join(deep, "deep.txt"), "wb") as f:
f.write(b"ten levels down\n")
with open(os.path.join(root2, "n" * 200), "wb") as f:
f.write(b"a 200-byte name\n")
os.symlink("/" + "/".join(["target-component-%02d" % i for i in range(16)]), os.path.join(root2, "longlink"))
for dirpath, dirs, fs in os.walk(root2):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
rr_entries = tree_entries(root2)
images = []
def dump(path, kind):
return json.loads(ctx.python(["pycdlib"], DUMP.replace("sys.argv[1], sys.argv[2]", repr(path) + ", " + repr(kind))))
def xorriso(name, args, src, tree, entries=None):
out = os.path.join(tmp, name + ".iso")
if args and args[0] == "native": # xorriso's own commands (mkisofs emulation always writes Rock Ridge)
sh("xorriso", ["xorriso", "-outdev", out, "-padding", "0"] + args[1:] + ["-map", src, "/"], tmp)
else:
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-o", out] + args + [src], tmp)
if entries is None:
entries = dump(out, tree)
images.append({"name": name, "data": open(out, "rb").read(), "tree": tree, "entries": entries})
return out
plain = xorriso("xorriso-plain", ["native", "-rockridge", "off"], root, "iso9660")
xorriso("xorriso-J", ["native", "-rockridge", "off", "-joliet", "on"], root, "joliet")
xorriso("xorriso-R", ["-R"], root, "rockridge", base_entries)
xorriso("xorriso-JR", ["-J", "-R"], root2, "rockridge", rr_entries)
out = os.path.join(tmp, "geniso.iso")
sh("cdrkit", ["genisoimage", "-quiet", "-no-pad", "-J", "-R", "-o", out, root2], tmp)
images.append({"name": "genisoimage-JR", "data": open(out, "rb").read(), "tree": "rockridge", "entries": rr_entries})
# Joliet from the -J -R image too (prefer = "joliet")
images.append({"name": "genisoimage-JR-joliet", "same": len(images), "tree": "joliet", "entries": dump(out, "joliet")})
# El Torito
bootdir = os.path.join(tmp, "boot")
shutil.copytree(root, bootdir, symlinks=True)
with open(os.path.join(bootdir, "boot.img"), "wb") as f:
f.write(b"\xfa\xeb\xfe" + bytes(2045))
out = os.path.join(tmp, "boot.iso")
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-R", "-o", out, "-b", "boot.img", "-c", "boot.cat", "-no-emul-boot",
"-boot-load-size", "4", bootdir], tmp)
bdata = open(out, "rb").read()
info = subprocess.run(["nix", "shell", "nixpkgs#xorriso", "-c", "xorriso", "-indev", out, "-report_el_torito", "plain"],
capture_output=True, text=True).stdout
# "El Torito boot img : 1 BIOS y none 0x0000 0x00 4 LBA"
row = [l for l in info.split("\n") if l.startswith("El Torito boot img")][0].split()
cat = [l for l in info.split("\n") if l.startswith("El Torito catalog")][0].split()
boot = {"data": bdata, "sectors": int(row[-2]), "lba": int(row[-1]), "bootable": row[7] == "y", "catalog": int(cat[4])}
multi, msize = split_record(open(plain, "rb").read(), b"BIG.BIN;1", 2048 * 8)
mcrc = zlib.crc32(dict(files)["big.bin"])
interleaved = set_interleave(open(plain, "rb").read(), b"HELLO.TXT;1")
finally:
shutil.rmtree(tmp)
ctx.emit("iso", {"images": images, "boot": boot, "multi": {"data": multi, "name": "BIG.BIN", "size": msize, "crc": mcrc},
"interleaved": interleaved})
+75
View File
@@ -0,0 +1,75 @@
# LHA / LZH fixtures (tools/fixtures.py): the test archives of lhasa 0.6.0's source (nixpkgs#lhasa.src, ISC; read
# from the nix store at fixture time, not committed: archives by LHarc 1.13 (lh1), LArc 3.33 (lzs / lz5 / lz4), LHA
# 2.13 / 2.55e / Amiga / OS-9 / OSK / Unix 1.14i / ExpLZH (lh0 / lh5 / lh6 / lh7, header levels 0 / 1 / 2, subdirectories,
# symlinks) and lhasa's lh1 / lz5 length tests) and archives made here by LHa for UNIX 1.14i (unfree, run as a tool:
# -o5 / -o6 / -o7 / -z, header levels 0 / 1 / 2); the reference data is what lhasa extracts (`lha -xw=`). Our writer's
# output (tools/fixtures/_arch2_ours.luau) is extracted by lhasa.
# tests/gen/lha.luau { cases = { { name, data, entries = { { name, size, crc } }, links = { { name, link } } } },
# ours = { ok, listing } }
import glob, importlib.util, os, shutil, subprocess, tarfile, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/lha"]
DIRS = ["lharc113", "larc333", "lha213", "lha255e", "lha_amiga_122", "lha_amiga_212", "lha_os9_211c", "lha_osk_201",
"lha_unix114i", "explzh_723", "lengths", "generated/lzs", "lha_x68k_213", "lh2_222", "lhmelt_16536"]
def lhasa(args, cwd):
return A.tool(["lhasa"], ["lha"] + args, cwd=cwd).decode(errors="replace")
def expected(path, tmp):
out = os.path.join(tmp, "x")
A.rmtree(out)
os.makedirs(out)
lhasa(["-xqfw=" + out, path], tmp)
ents, links = [], []
for d, _, fs in os.walk(out):
for f in fs:
p = os.path.join(d, f)
rel = os.path.relpath(p, out)
if os.path.islink(p):
links.append({"name": rel, "link": os.readlink(p)})
else:
data = open(p, "rb").read()
ents.append({"name": rel, "size": len(data), "crc": zlib.crc32(data)})
return ents, links
def generate(ctx):
src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#lhasa.src"], capture_output=True, check=True, text=True).stdout.strip()
tmp = A.tmpdir()
try:
with tarfile.open(src) as t:
t.extractall(tmp, filter="data")
root = glob.glob(os.path.join(tmp, "lhasa-*", "test", "archives"))[0]
cases = []
for d in DIRS:
for p in sorted(glob.glob(os.path.join(root, d, "*.lz[hs]"))):
try:
ents, links = expected(p, tmp)
except RuntimeError:
continue # lhasa cannot extract it here (read-only directory attributes from OS/2)
cases.append({"name": os.path.relpath(p, root), "data": open(p, "rb").read(), "entries": ents, "links": links})
# LHa for UNIX
work = os.path.join(tmp, "w")
rng = ctx.rng(5)
A.tree(A.FILES + [("dir/sub/text.txt", b"the quick brown fox " * 300), ("dir/rand.bin", rng.randbytes(70000))], work)
names = [n for n, _ in A.FILES] + ["dir"]
for level in (0, 1, 2):
for m in ("5", "6", "7", "z"):
arc = os.path.join(tmp, "u%d%s.lzh" % (level, m))
opt = ("-a%dz" % level) if m == "z" else ("-a%do%s" % (level, m))
A.tool([], ["env", "NIXPKGS_ALLOW_UNFREE=1", "nix", "shell", "--impure", "nixpkgs#lha", "-c", "lha", opt + "q", arc] + names, cwd=work)
ents, links = expected(arc, tmp)
cases.append({"name": "lha114i -h%d -%s" % (level, m), "data": open(arc, "rb").read(), "entries": ents, "links": links})
arc = os.path.join(tmp, "ours.lzh")
open(arc, "wb").write(A.ours(ctx, "lha"))
got = {e["name"]: e["crc"] for e in expected(arc, tmp)[0]}
ok = all(got.get(n) == zlib.crc32(d) for n, d in A.FILES)
ctx.emit("lha", {"cases": cases, "ours": {"ok": ok, "listing": lhasa(["-v", arc], tmp)}})
finally:
A.rmtree(tmp)
+72
View File
@@ -0,0 +1,72 @@
# LZ4 frame fixtures (tools/fixtures.py): corpora compressed by the lz4 tool 1.10 (nixpkgs#lz4) with its frame options
# (default, linked blocks -BD, 64 KB blocks -B4 with and without -BD, block checksums -BX, --content-size,
# --no-frame-crc, -9, the legacy format -l), concatenated frames and a skippable frame; and our writer's frames
# (tools/fixtures/_lz4frame_encode.luau under the luau CLI) decompressed by `lz4 -d`, as verdicts.
# tests/gen/lz4frame.luau { cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4frame_corpora.luau { [name] = bytes }
import os, shutil, struct, subprocess, tempfile
INPUTS = ["src/Formats/archive/lz4/init.luau", "src/Formats/codecs/compress/Lz4.luau", "src/Formats/codecs/compress/Xxh32.luau",
"tools/fixtures/_lz4frame_encode.luau"]
def lz4(args, data=None, path=None):
argv = ["nix", "shell", "nixpkgs#lz4", "-c", "lz4"] + args + ([path] if path else [])
return subprocess.run(argv, input=data, capture_output=True, check=True).stdout
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
text += f.read()
if len(text) >= 160000:
break
return {"empty": b"", "short": b"hello, lz4 frames\n", "text": bytes(text[:160000]), "random": rng.randbytes(20000),
"zeros": b"\0" * 300000}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
cs = corpora(ctx.rng(43))
cases = []
tmp = tempfile.mkdtemp()
try:
for name, data in cs.items():
path = os.path.join(tmp, name)
with open(path, "wb") as f:
f.write(data)
variants = [("default", ["-c"])]
if name in ("text", "zeros", "short"):
variants += [("BD", ["-c", "-BD"]), ("B4", ["-c", "-B4"]), ("B4BD", ["-c", "-B4", "-BD"]), ("BX", ["-c", "-B4", "-BX"]),
("size", ["-c", "--content-size"]), ("nocrc", ["-c", "--no-frame-crc"]), ("hc9", ["-c", "-9", "-B4", "-BD"]),
("legacy", ["-c", "-l"])]
for vname, args in variants:
cases.append({"name": name + "/" + vname, "corpus": name, "data": lz4(args, path=path)})
finally:
shutil.rmtree(tmp)
# two frames, and a skippable frame in front
two = lz4(["-c"], data=cs["short"]) + lz4(["-c", "-B4"], data=cs["text"])
cases.append({"name": "concat", "corpus": "short+text", "data": two})
skip = struct.pack("<II", 0x184D2A53, 5) + b"skip!" + lz4(["-c"], data=cs["short"])
cases.append({"name": "skippable", "corpus": "short", "data": skip})
ctx.emit("lz4frame_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4frame_encode.luau")], capture_output=True,
check=True, cwd=ctx.root).stdout.decode()
ours = []
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
try:
got = lz4(["-d", "-c"], data=bytes.fromhex(hexdata.strip()))
ok = got == cs[name.split("/")[0]]
except subprocess.CalledProcessError:
ok = False
ours.append({"name": name, "ok": ok})
ctx.emit("lz4frame", {"cases": cases, "ours": sorted(ours, key=lambda o: o["name"])})
+147
View File
@@ -0,0 +1,147 @@
# Mac encodings fixtures (tools/fixtures.py) for archive/binhex, archive/macbinary and archive/applesingle: files with
# data and resource forks, type / creator / Finder flags and dates, imported into an HFS volume by hfsutils (`hcopy -m`
# of a MacBinary we build here) and exported by hfsutils as MacBinary II (`hcopy -m`) and BinHex 4.0 (`hcopy -b`);
# AppleSingle / AppleDouble v1 and v2 built here per RFC 1740. Every case's reference listing (but AppleSingle v1's,
# which unar does not read) comes from The Unarchiver (`lsar -j`, `unar -forks visible`: names, fork sizes, type / creator, data CRCs). Our writers' output
# (tools/fixtures/_arch2_ours.luau with a resource fork) is listed and extracted by unar the same way.
# tests/gen/mac.luau { cases = { { format, name, data, entries = { { name, size, crc, macType?, macCreator? } } } },
# ours = { { format, variant?, ok, detail } } }
import importlib.util, json, os, shutil, struct, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/binhex",
"src/Formats/archive/macbinary", "src/Formats/archive/applesingle", "src/Formats/containers/MacFile.luau"]
PKGS = ["hfsutils", "unar"]
MAC_EPOCH = 2082844800
def crc16(data):
c = 0
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def macbinary(name, data, rsrc, ftype, creator, flags, mtime):
h = bytearray(128)
nm = name.encode("mac_roman")
h[1] = len(nm)
h[2:2 + len(nm)] = nm
h[65:73] = ftype + creator
h[73] = flags >> 8
struct.pack_into(">IIII", h, 83, len(data), len(rsrc), mtime + MAC_EPOCH, mtime + MAC_EPOCH)
h[101] = flags & 255
h[122], h[123] = 129, 129
struct.pack_into(">H", h, 124, crc16(bytes(h[:124])))
pad = lambda b: b + b"\0" * (-len(b) % 128)
return bytes(h) + pad(data) + pad(rsrc)
def apple(magic, version, entries):
filler = b"Macintosh " if version == 1 else b"\0" * 16
hdr = struct.pack(">II16sH", magic, version << 16, filler, len(entries))
off, tab, body = len(hdr) + 12 * len(entries), b"", b""
for i, d in entries:
tab += struct.pack(">III", i, off + len(body), len(d))
body += d
return hdr + tab + body
def listing(path, outdir, known):
"""unar's view: [{name, size, crc, rsrc, macType, macCreator}]; names unar %-escaped become the known name"""
j = json.loads(A.tool(PKGS, ["lsar", "-j", path]))
A.tool(PKGS, ["unar", "-q", "-f", "-forks", "visible", "-o", outdir, path])
out = []
for e in j["lsarContents"]:
name = raw = e["XADFileName"]
if "%" in name and "%" not in known:
name = known
rsrc = bool(e.get("XADIsResourceFork"))
if rsrc and not e.get("XADFileSize"):
continue # an empty resource fork: not an entry in our convention
fn = os.path.join(outdir, raw + (".rsrc" if rsrc else ""))
b = open(fn, "rb").read() if os.path.exists(fn) else b""
if rsrc: # unar writes the resource fork as AppleDouble: take entry 2
n = struct.unpack_from(">H", b, 24)[0]
for k in range(n):
i, o, l = struct.unpack_from(">III", b, 26 + 12 * k)
if i == 2:
b = b[o:o + l]
d = {"name": name + (".rsrc" if rsrc else ""), "size": e.get("XADFileSize", 0), "crc": zlib.crc32(b)}
if "XADFileType" in e:
d["macType"] = struct.pack(">I", e["XADFileType"]).decode("latin-1")
d["macCreator"] = struct.pack(">I", e["XADFileCreator"]).decode("latin-1")
out.append(d)
if any(e["name"].endswith(".rsrc") for e in out): # an empty data fork beside a resource fork: no entry
out = [e for e in out if e["size"] or e["name"].endswith(".rsrc")]
return out
def generate(ctx):
rng = ctx.rng(17)
files = [
("Read Me", b"Hello from the data fork\r" * 40, rng.randbytes(1500), b"TEXT", b"ttxt", 0x0100),
("Appé π", rng.randbytes(3000) + b"\x90" * 300 + b"\x90\x00\x90", b"", b"APPL", b"????", 0),
("rsrc only", b"", bytes(range(256)) * 4 + b"\x00" * 600, b"rsrc", b"RSED", 0x2000),
("runs", b"A" * 1000 + b"\x90" * 7 + b"B" * 2, b"\x90\x90", b"BINA", b"tool", 0),
]
tmp = A.tmpdir()
cases = []
try:
vol = os.path.join(tmp, "v.hfs")
with open(vol, "wb") as f:
f.truncate(4 * 1024 * 1024)
script = ["hformat -l Fixtures v.hfs >/dev/null"]
for k, (name, data, rsrc, t, c, fl) in enumerate(files):
open(os.path.join(tmp, "in%d.bin" % k), "wb").write(macbinary(name, data, rsrc, t, c, fl, A.MTIME))
script.append("hcopy -m in%d.bin :" % k)
for k, (name, *_ ) in enumerate(files):
script.append("hcopy -m ':%s' out%d.bin" % (name, k))
script.append("hcopy -b ':%s' out%d.hqx" % (name, k))
script.append("humount")
# hfsutils names are Mac OS Roman bytes: the script file is written in that encoding
script.insert(1, "hmount v.hfs >/dev/null")
open(os.path.join(tmp, "run.sh"), "wb").write(("set -e\n" + "\n".join(script) + "\n").encode("mac_roman"))
A.tool(PKGS, ["sh", "run.sh"], cwd=tmp)
for k, (name, data, rsrc, t, c, fl) in enumerate(files):
for fmt, fn in (("macbinary", "out%d.bin" % k), ("binhex", "out%d.hqx" % k)):
p = os.path.join(tmp, fn)
cases.append({"format": fmt, "name": "hfsutils %s %s" % (fmt, name), "data": open(p, "rb").read(), "entries": listing(p, os.path.join(tmp, "x" + fn), name)})
# AppleSingle v2, AppleDouble v2, AppleSingle v1
fi = t + c + struct.pack(">H", fl) + b"\0" * 22
dates = struct.pack(">iiii", A.MTIME - 946684800, A.MTIME - 946684800, -2 ** 31, -2 ** 31)
nm = name.encode("mac_roman")
for label, blob in (
("applesingle v2", apple(0x51600, 2, [(3, nm), (8, dates), (9, fi), (1, data), (2, rsrc)])),
("appledouble v2", apple(0x51607, 2, [(9, fi), (2, rsrc), (3, nm)])),
("applesingle v1", apple(0x51600, 1, [(3, nm), (7, struct.pack(">III", A.MTIME + MAC_EPOCH, A.MTIME + MAC_EPOCH, 0) + b"\0" * 4), (9, fi), (1, data), (2, rsrc)])),
):
p = os.path.join(tmp, "as%d-%s" % (k, label.replace(" ", "")))
open(p, "wb").write(blob)
if label.endswith("v1"): # unar reads version 2 only: the entries we built
ents = [{"name": name, "size": len(data), "crc": zlib.crc32(data), "macType": t.decode(), "macCreator": c.decode()}] if data or not rsrc else []
if rsrc:
ents.append({"name": name + ".rsrc", "size": len(rsrc), "crc": zlib.crc32(rsrc)})
else:
ents = listing(p, p + ".x", name)
cases.append({"format": "applesingle", "name": "%s %s" % (label, name), "data": blob, "entries": ents})
ours = []
for fmt, opts in (("binhex", "mac=true"), ("macbinary", "mac=true"), ("applesingle", "mac=true"), ("applesingle", "mac=true,double=true")):
blob = A.ours(ctx, fmt, opts)
p = os.path.join(tmp, "ours-" + fmt + opts.replace(",", "").replace("=", ""))
open(p, "wb").write(blob)
got = {e["name"]: e for e in listing(p, p + ".x", "hello.txt")}
hello, rs = A.FILES[0][1], A.content(700, 3)
want = {"hello.txt.rsrc": zlib.crc32(rs)}
if "double" not in opts:
want["hello.txt"] = zlib.crc32(hello)
ok = all(n in got and got[n]["crc"] == c for n, c in want.items()) and all(e.get("macType") == "TEXT" for e in got.values())
ours.append({"format": fmt, "variant": opts, "ok": ok, "detail": json.dumps(list(got.values()))})
ctx.emit("mac", {"cases": cases, "ours": ours})
finally:
shutil.rmtree(tmp)
+101
View File
@@ -0,0 +1,101 @@
# PSF fixtures (tools/fixtures.py): Linux console fonts from kbd (nixpkgs#kbd: PSF 2 with and without Unicode tables,
# PSF 1 with 512 glyphs), Spleen / Tamzen / Terminus / Cozette console fonts, read from the nix store at fixture time.
# FreeType does not read PSF: the reference is kbd's `psfgettable` (the Unicode table) and the independent parser
# below (header and glyph bitmaps). Our PSF 2 and PSF 1 output (tools/fixtures/_bitmapfonts_ours.luau) is read back
# by psfgettable and the parser.
# tests/gen/psf.luau { fonts = { { name, data, gz?, version, count, width, height, glyphs = { { index, pixels } },
# table = { { glyph, cp } }, ours2 = { ok, detail }, ours1? } } }
import gzip, importlib.util, os, shutil, subprocess
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_bitmapfonts_ours.luau", "src/Formats/font/psf"]
def store(pkg):
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
def parse(b):
"""(version, count, width, height, [glyph pixel bytes as 0/255]) of a PSF file"""
if b[:4] == b"\x72\xb5\x4a\x86":
_, hsize, flags, count, charsize, height, width = [int.from_bytes(b[4 + 4 * i:8 + 4 * i], "little") for i in range(7)]
ver, at = 2, hsize
else:
mode, height = b[2], b[3]
ver, at, width, count = 1, 4, 8, 512 if mode & 1 else 256
stride = (width + 7) // 8
glyphs = []
for i in range(count):
g = b[at + i * stride * height: at + (i + 1) * stride * height]
px = bytearray(width * height)
for y in range(height):
for x in range(width):
if g[y * stride + x // 8] >> (7 - x % 8) & 1:
px[y * width + x] = 255
glyphs.append(bytes(px))
return ver, count, width, height, glyphs
def table(path):
out = A.tool(["kbd"], ["psfgettable", path]).decode()
pairs = []
for line in out.splitlines():
if line.startswith("#") or not line.strip():
continue
parts = line.split()
g = int(parts[0], 16)
for p in parts[1:]:
if p.startswith("U+") and "," not in p:
pairs.append({"glyph": g, "cp": int(p[2:], 16)})
return pairs
def generate(ctx):
kbd = os.path.join(store("kbd"), "share", "consolefonts")
items = [(os.path.join(kbd, f), f) for f in ("lat9w-16.psfu.gz", "default8x16.psfu.gz", "cp866-8x16.psf.gz", "eurlatgr.psfu.gz", "iso01-12x22.psfu.gz")]
items += [(os.path.join(store("spleen"), "share", "consolefonts", "spleen-12x24.psfu"), "spleen-12x24.psfu"),
(os.path.join(store("tamzen"), "share", "consolefonts", "Tamzen8x16.psf"), "Tamzen8x16.psf"),
(os.path.join(store("terminus_font"), "share", "consolefonts", "ter-v16n.psf.gz"), "ter-v16n.psf.gz"),
(os.path.join(store("cozette"), "share", "consolefonts", "cozette.psf"), "cozette.psf")]
tmp = A.tmpdir()
try:
fonts = []
for path, name in items:
raw = open(path, "rb").read()
data = gzip.decompress(raw) if name.endswith(".gz") else raw
p = os.path.join(tmp, name.replace(".gz", ""))
open(p, "wb").write(data)
ver, count, width, height, glyphs = parse(data)
sample = sorted({0, 1, 65, 97, count // 2, count - 1})
e = {"name": name, "data": raw, "version": ver, "count": count, "width": width, "height": height,
"glyphs": [{"index": i, "pixels": glyphs[i]} for i in sample], "table": table(p)}
if name.endswith(".gz"):
e["gz"] = True
fonts.append(e)
ctx.emit("psf_src", {"fonts": [{"name": f["name"], "format": "psf", "data": f["data"], **({"gz": True} if f.get("gz") else {})} for f in fonts]})
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
exe = shutil.which("luau")
base = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ours.luau"), "-a", "psf_src", "psf"]
for ver in ("2", "1"):
r = subprocess.run(base + [ver], capture_output=True, cwd=ctx.root)
outs = dict(line.rsplit(" ", 1) for line in r.stdout.decode().splitlines())
for f in fonts:
key = "ours" + ver
if f["name"] not in outs:
if ver == "2" or (f["width"] <= 8):
f[key] = {"ok": False, "detail": "no output: " + r.stderr.decode(errors="replace")[-300:]}
continue
data = bytes.fromhex(outs[f["name"]])
p = os.path.join(tmp, "ours%s-%s" % (ver, f["name"]))
open(p, "wb").write(data)
over, ocount, ow, oh, og = parse(data)
_, _, _, _, src = parse(gzip.decompress(f["data"]) if f.get("gz") else f["data"])
same_glyphs = ow == f["width"] and oh == f["height"] and og[:f["count"]] == src
same_table = sorted((x["glyph"], x["cp"]) for x in table(p)) == sorted((x["glyph"], x["cp"]) for x in f["table"])
f[key] = {"ok": over == int(ver) and same_glyphs and same_table, "detail": "version %d, glyphs %s, table %s" % (over, same_glyphs, same_table)}
ctx.emit("psf", {"fonts": fonts})
finally:
A.rmtree(tmp)
+101
View File
@@ -0,0 +1,101 @@
# rpm fixtures (tools/fixtures.py): one package built by rpmbuild (nixpkgs#rpm) with each payload compressor (gzip,
# bzip2, xz, lzma, zstd, none), holding files, a symlink, a hard link pair, a directory and a %ghost file. The expected
# header fields and file list come from `rpm -qp --qf`, the file data from rpm2cpio's cpio stream (parsed here).
# tests/gen/rpm.luau { rpms = { { name, data, compressor, fields = { name, version, ... }, files = { { name, size,
# mode, mtime, link?, crc? } }, cpioCrc } } }
import os, shutil, subprocess, tempfile, zlib
SPEC = r"""
Name: hello
Version: 1.0
Release: 3
Epoch: 2
Summary: a greeting
License: MIT
URL: https://example.org/hello
Group: Applications/Text
BuildArch: noarch
%description
prints a greeting
and exits
%install
mkdir -p %{buildroot}/usr/bin %{buildroot}/usr/share/doc/hello %{buildroot}/var/log
printf '#!/bin/sh\necho hello\n' > %{buildroot}/usr/bin/hello
chmod 755 %{buildroot}/usr/bin/hello
python3 -c "import random; open('%{buildroot}/usr/share/doc/hello/README', 'wb').write(random.Random(3).randbytes(20000))"
printf 'a long name' > "%{buildroot}/usr/share/doc/hello/a file name with spaces and more than one hundred characters, to pass every old limit of the cpio or tar headers.txt"
ln -s hello %{buildroot}/usr/bin/hi
ln %{buildroot}/usr/bin/hello %{buildroot}/usr/bin/hello2
touch %{buildroot}/var/log/hello.log
%files
/usr/bin/hello
/usr/bin/hello2
/usr/bin/hi
%dir /usr/share/doc/hello
/usr/share/doc/hello/README
"/usr/share/doc/hello/a file name with spaces and more than one hundred characters, to pass every old limit of the cpio or tar headers.txt"
%ghost /var/log/hello.log
"""
QF = "%{NAME}\\n%{VERSION}\\n%{RELEASE}\\n%{EPOCH}\\n%{ARCH}\\n%{OS}\\n%{LICENSE}\\n%{URL}\\n%{PAYLOADCOMPRESSOR}\\n%{PAYLOADFORMAT}\\n%{SUMMARY}\\n"
FQF = "[%{FILENAMES}\\t%{FILESIZES}\\t%{FILEMODES}\\t%{FILEMTIMES}\\t%{FILELINKTOS}\\t%{FILEFLAGS}\\n]"
def cpio_files(d):
out, ino, p = {}, {}, 0
while p < len(d):
h = d[p:p + 110]
f = [int(h[6 + 8 * i:14 + 8 * i], 16) for i in range(13)]
ns, fs = f[11], f[6]
name = d[p + 110:p + 110 + ns - 1].decode()
p = (p + 110 + ns + 3) & ~3
if name == "TRAILER!!!":
out[None] = p # the archive's end (rpm2cpio pads its output with zeros)
break
out[name[2:] if name.startswith("./") else name] = f[0]
if fs:
ino[f[0]] = d[p:p + fs]
p = (p + fs + 3) & ~3
return {n: (i if n is None else ino.get(i, b"")) for n, i in out.items()} # hard links: the data of their inode
def generate(ctx):
tmp = tempfile.mkdtemp()
rpms = []
try:
with open(os.path.join(tmp, "hello.spec"), "w") as f:
f.write(SPEC)
env = dict(os.environ, SOURCE_DATE_EPOCH="1700000000")
for comp, io in (("gzip", "w9.gzdio"), ("bzip2", "w9.bzdio"), ("xz", "w6.xzdio"), ("lzma", "w6.lzdio"), ("zstd", "w19.zstdio"), ("none", "w0.ufdio")):
top = os.path.join(tmp, "top-" + comp)
subprocess.run(["nix", "shell", "nixpkgs#rpm", "nixpkgs#python3", "-c", "rpmbuild", "--define", "_topdir " + top,
"--define", "_binary_payload " + io, "--define", "__os_install_post %{nil}",
"--define", "_build_id_links none", "--define", "use_source_date_epoch_as_buildtime 1",
"--define", "clamp_mtime_to_source_date_epoch 1", "-bb", "hello.spec"],
cwd=tmp, capture_output=True, check=True, env=env)
path = os.path.join(top, "RPMS", "noarch", "hello-1.0-3.noarch.rpm")
data = open(path, "rb").read()
q = lambda fmt: subprocess.run(["nix", "shell", "nixpkgs#rpm", "-c", "rpm", "--dbpath", os.path.join(tmp, "db"), "-qp", "--qf", fmt, path],
capture_output=True, check=True).stdout.decode()
v = q(QF).split("\n")
fields = dict(zip(["name", "version", "release", "epoch", "arch", "os", "license", "url", "payloadCompressor", "payloadFormat", "summary"], v))
fields["epoch"] = int(fields["epoch"])
if comp == "none":
del fields["payloadCompressor"] # whatever rpm stores for "no compression" is checked by the test itself
raw = subprocess.run(["nix", "shell", "nixpkgs#rpm", "-c", "rpm2cpio", path], capture_output=True, check=True).stdout
content = cpio_files(raw)
files = []
for line in q(FQF).split("\n")[:-1]:
name, size, mode, mtime, link, flags = line.split("\t")
e = {"name": name.lstrip("/"), "size": int(size), "mode": int(mode) & 0xFFF, "type": int(mode) & 0xF000,
"mtime": int(mtime), "flags": int(flags)}
if link:
e["link"] = link
if e["name"] in content and e["type"] == 0x8000:
e["crc"] = zlib.crc32(content[e["name"]])
files.append(e)
rpms.append({"name": "rpmbuild-" + comp, "data": data, "compressor": comp, "fields": fields, "files": files,
"cpioCrc": zlib.crc32(raw[:content[None]]), "cpioSize": content[None]})
finally:
shutil.rmtree(tmp)
ctx.emit("rpm", {"rpms": rpms})
+79
View File
@@ -0,0 +1,79 @@
# Type 1 fixtures (tools/fixtures.py): Latin Modern PFB fonts (nixpkgs#lmodern, GUST font licence; read from the nix
# store at fixture time) and a PFA made from one of them by t1utils' `t1ascii`; reference outlines from fontTools
# (t1Lib parses and decrypts, T1CharString draws through ControlBoundsPen / AreaPen: control boxes, areas, advances),
# code points from fontTools.agl, FreeType renders of a few glyphs (PSNR in the test).
# tests/gen/type1.luau { fonts = { { name, data, upem, family, glyphs = { { name, cp?, advance, bounds?, area } },
# renders = { { cp, px, width, height, left, top, pixels } } } } }
import json, os, subprocess
CODE = r'''
import json, sys
from fontTools.t1Lib import T1Font
from fontTools.pens.areaPen import AreaPen
from fontTools.pens.boundsPen import ControlBoundsPen
from fontTools import agl
import freetype
req = json.load(sys.stdin)
out = []
for spec in req:
f = T1Font(spec["path"])
f.parse()
cs = f["CharStrings"]
fi = f.font.get("FontInfo", {})
glyphs = []
for name in spec["names"]:
if name not in cs:
continue
g = cs[name]
bp = ControlBoundsPen(cs)
g.draw(bp)
ap = AreaPen(cs)
g.draw(ap)
e = {"name": name, "advance": g.width, "area": ap.value}
if bp.bounds:
e["bounds"] = list(bp.bounds)
u = agl.toUnicode(name)
if len(u) == 1:
e["cp"] = ord(u)
glyphs.append(e)
face = freetype.Face(spec["path"])
renders = []
for ch in "AgQ&8":
face.set_pixel_sizes(0, 48)
face.load_char(ch, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING)
b = face.glyph.bitmap
px = bytearray(b.width * b.rows)
for y in range(b.rows):
for x in range(b.width):
px[y * b.width + x] = b.buffer[y * b.pitch + x]
renders.append({"cp": ord(ch), "px": 48, "width": b.width, "height": b.rows, "left": face.glyph.bitmap_left,
"top": face.glyph.bitmap_top, "pixels": px.hex()})
out.append({"family": fi.get("FamilyName", ""), "upem": round(1 / f["FontMatrix"][0]), "glyphs": glyphs, "renders": renders,
"numGlyphs": len(cs.keys())})
print(json.dumps(out))
'''
NAMES = ["A", "B", "O", "Q", "a", "g", "e", "f", "fi", "ffl", "zero", "eight", "ampersand", "Aacute", "eacute", "ccedilla",
"Lslash", "dotlessi", "quotedblleft", "emdash", "germandbls", "AE", "oe", "space", "period", "parenleft", "Ydieresis"]
def store(pkg):
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
def generate(ctx):
lm = os.path.join(store("lmodern"), "share", "fonts", "type1", "public", "lm")
t1 = store("t1utils")
paths = [(os.path.join(lm, f), f) for f in ("lmr10.pfb", "lmbx12.pfb", "lmri10.pfb", "lmtt10.pfb")]
import tempfile
tmp = tempfile.mkdtemp(prefix="type1-")
pfa = os.path.join(tmp, "lmr10.pfa")
subprocess.run([os.path.join(t1, "bin", "t1ascii"), paths[0][0], pfa], check=True, capture_output=True)
paths.append((pfa, "lmr10.pfa (t1ascii)"))
refs = json.loads(ctx.python(["fonttools", "freetype-py"], CODE, input=json.dumps([{"path": p, "names": NAMES} for p, _ in paths]).encode()))
fonts = []
for (p, name), ref in zip(paths, refs):
for r in ref["renders"]:
r["pixels"] = bytes.fromhex(r["pixels"])
fonts.append({"name": name, "data": open(p, "rb").read(), **ref})
ctx.emit("type1", {"fonts": fonts})
+61
View File
@@ -0,0 +1,61 @@
# uuencode / xxencode / base64 fixtures (tools/fixtures.py): blocks made by GNU sharutils `uuencode` (classic and -m)
# and uudeview's `uuenview` (-u, -x), alone and several in one text with mail-like text around them; our writer's uu /
# xx / base64 output (tools/fixtures/_arch2_ours.luau) decoded by `uudecode` / `uudeview`.
# tests/gen/uu.luau { cases = { { name, data, entries = { { name, size, crc, mode } } } }, gnu = { { name, data } },
# ours = { { variant, ok } } }
import importlib.util, os, shutil, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/uu"]
PKGS = ["sharutils", "uudeview"]
def generate(ctx):
tmp = A.tmpdir()
try:
A.tree(A.FILES, tmp)
for name, _ in A.FILES:
os.chmod(os.path.join(tmp, name), 0o644)
ents = {n: {"name": n, "size": len(d), "crc": zlib.crc32(d), "mode": 0o644} for n, d in A.FILES}
cases, gnu = [], []
for name, _ in A.FILES:
uu = A.tool(PKGS, ["uuencode", name, name], cwd=tmp)
b64 = A.tool(PKGS, ["uuencode", "-m", name, name], cwd=tmp)
gnu.append({"name": name, "uu": uu, "base64": b64})
cases.append({"name": "uuencode " + name, "data": uu, "entries": [ents[name]]})
cases.append({"name": "uuencode -m " + name, "data": b64, "entries": [ents[name]]})
for flag in ("-u", "-x"):
out = A.tool(PKGS, ["uuenview", flag, name], cwd=tmp)
cases.append({"name": "uuenview %s %s" % (flag, name), "data": out, "entries": [{"name": name, "size": ents[name]["size"], "crc": ents[name]["crc"]}]})
# several blocks in one mail-like text
text = b"From: someone\nSubject: files\n\nHere they are:\n\n" + gnu[0]["uu"] + b"\nand the other one\n" + gnu[1]["base64"] + b"\n-- \nsig\n"
cases.append({"name": "mail with two blocks", "data": text, "entries": [ents["hello.txt"], ents["data.bin"]]})
crlf = gnu[1]["uu"].replace(b"\n", b"\r\n")
cases.append({"name": "crlf lines", "data": crlf, "entries": [ents["data.bin"]]})
ours = []
for variant in ("uu", "xx", "base64"):
data = A.ours(ctx, "uu", "variant=" + variant)
d = A.tmpdir()
try:
# one block per file: uudecode reads the first block only
end = b"====\n" if variant == "base64" else b"end\n"
for k, block in enumerate(data.split(end)[:-1]):
p = os.path.join(d, "in%d.txt" % k)
open(p, "wb").write(block + end)
if variant != "xx":
A.tool(PKGS, ["uudecode", p], cwd=d)
if variant == "xx":
p = os.path.join(d, "all.txt")
open(p, "wb").write(data)
A.tool(PKGS, ["uudeview", "-i", "-p", d + "/", p], cwd=d)
got = A.read_tree(d)
ok = all(got.get(n) == zlib.crc32(b) for n, b in A.FILES)
ours.append({"variant": variant, "ok": ok})
finally:
shutil.rmtree(d)
ctx.emit("uu", {"cases": cases, "gnu": gnu, "ours": ours})
finally:
shutil.rmtree(tmp)
+44
View File
@@ -0,0 +1,44 @@
# yEnc fixtures (tools/fixtures.py): single-part files by uudeview's `uuenview -y`, a multi-part posting (uuenview -y
# -200 split into parts, concatenated into one text, parts in reverse order too), a text with two files; our writer's
# output (tools/fixtures/_arch2_ours.luau) decoded by `uudeview`.
# tests/gen/yenc.luau { cases = { { name, data, entries = { { name, size, crc } } } }, ours = { ok } }
import importlib.util, os, shutil, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/yenc"]
PKG = ["uudeview"]
def generate(ctx):
tmp = A.tmpdir()
try:
big = ("big.bin", ctx.rng(9).randbytes(90000))
files = A.FILES + [big, ("crit.bin", bytes(range(256)) * 3 + b"\x00\r\n=\t . " * 50)]
A.tree(files, tmp)
ent = {n: {"name": n, "size": len(d), "crc": zlib.crc32(d)} for n, d in files}
cases, texts = [], {}
for n, _ in files:
texts[n] = A.tool(PKG, ["uuenview", "-y", n], cwd=tmp)
cases.append({"name": "uuenview -y " + n, "data": texts[n], "entries": [ent[n]]})
A.tool(PKG, ["uuenview", "-y", "-200", "-od", tmp, "big.bin"], cwd=tmp)
parts = sorted(f for f in os.listdir(tmp) if f.startswith("big.") and f[4:].isdigit())
assert len(parts) >= 2, parts
bodies = [open(os.path.join(tmp, p), "rb").read() for p in parts]
cases.append({"name": "multipart (%d parts)" % len(parts), "data": b"".join(bodies), "entries": [ent["big.bin"]]})
cases.append({"name": "multipart reversed", "data": b"\n".join(reversed(bodies)), "entries": [ent["big.bin"]]})
cases.append({"name": "two files", "data": b"header text\n" + texts["hello.txt"] + b"\nbetween\n" + texts["crit.bin"], "entries": [ent["hello.txt"], ent["crit.bin"]]})
d = A.tmpdir()
try:
p = os.path.join(d, "ours.txt")
open(p, "wb").write(A.ours(ctx, "yenc"))
A.tool(PKG, ["uudeview", "-i", "-p", d + "/", p], cwd=d)
got = A.read_tree(d)
ok = all(got.get(n) == zlib.crc32(b) for n, b in A.FILES if b)
finally:
shutil.rmtree(d)
ctx.emit("yenc", {"cases": cases, "ours": {"ok": ok}, "partial": bodies[0]})
finally:
shutil.rmtree(tmp)
+45
View File
@@ -0,0 +1,45 @@
# .Z fixtures (tools/fixtures.py): Unix compress files written by ncompress 5.0 (nixpkgs#ncompress, `compress -c -f
# -b N`) from a few inputs: empty, one byte, short text, a 700 KB word corpus with incompressible stretches (the 16-bit
# table fills, the ratio check emits CLEAR codes), random bytes, and every width 10..16; a .tar.Z for the api's unwrap.
# gzip -d reads each file too (its output must be the input: a second decoder agreeing on what ncompress wrote).
# tests/gen/z.luau { cases = { { name, input, bits, z } }, tarZ = data, tarNames = { ... } }
import io, subprocess, tarfile
def compress(data, bits):
return subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f", "-b", str(bits)], input=data,
capture_output=True, check=True).stdout
def corpus(rng, size):
words = ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(2, 9))) for _ in range(3000)]
out = bytearray()
while len(out) < size:
if rng.random() < 0.002:
out += rng.randbytes(rng.randint(500, 4000)) # incompressible stretches: the ratio drops, CLEAR follows
else:
out += (" ".join(rng.choice(words) for _ in range(12)) + ".\n").encode()
return bytes(out[:size])
def generate(ctx):
rng = ctx.rng(23)
big = corpus(rng, 700000)
inputs = [("empty", b"", 16), ("one", b"A", 16), ("text", b"TOBEORNOTTOBEORTOBEORNOT#" * 40, 16),
("random", rng.randbytes(30000), 16), ("corpus16", big, 16)]
mid = big[:120000]
for bits in range(10, 16): # (-b 9 output does not round-trip through ncompress or gzip: not a valid file)
inputs.append(("corpus-b%d" % bits, mid, bits))
cases = []
for name, data, bits in inputs:
z = compress(data, bits)
back = subprocess.run(["nix", "shell", "nixpkgs#gzip", "-c", "gzip", "-d", "-c"], input=z, capture_output=True, check=True).stdout
assert back == data, "gzip -d disagrees on " + name
cases.append({"name": name, "input": data, "bits": bits, "z": z})
b = io.BytesIO()
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
for n, d in (("a.txt", b"alpha\n"), ("b/c.txt", b"gamma " * 100)):
ti = tarfile.TarInfo(n)
ti.size, ti.mtime = len(d), 1700000000
t.addfile(ti, io.BytesIO(d))
ctx.emit("z", {"cases": cases, "tarZ": compress(b.getvalue(), 16), "tarNames": ["a.txt", "b/c.txt"]})
+182
View File
@@ -0,0 +1,182 @@
# Zoo fixtures (tools/fixtures.py): no zoo archiver is packaged in nixpkgs, so the archives are assembled here per
# zoo 2.10's zoo.h layout (type 1 and type 2 directory entries, long names, directory names, a deleted entry), with
# data stored (method 0), LZW-compressed by the encoder below (method 1: 9..13-bit LSB-first codes, CLEAR 256, EOF 257)
# and lzh-compressed (method 2: the -lh5- streams of LHa for UNIX archives); The Unarchiver (`lsar -j`, `unar`)
# is the reference reader: its listing and extracted data are the expected entries.
# tests/gen/zoo.luau { cases = { { name, data, entries = { { name, size, crc } } } } }
import importlib.util, json, os, struct, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_arch2.py"]
TAG = 0xFDC4A7DC
def crc16(data):
c = 0
for b in data:
c ^= b
for _ in range(8):
c = (c >> 1) ^ 0xA001 if c & 1 else c >> 1
return c
def lzw(data):
"""zoo method 1: codes sized as the decoder (lzd.c) reads them"""
out, acc, nbits = bytearray(), 0, 0
def put(code, size):
nonlocal acc, nbits
acc |= code << nbits
nbits += size
while nbits >= 8:
out.append(acc & 255)
acc >>= 8
nbits -= 8
def reset():
return {bytes([i]): i for i in range(256)}, 258, 258, 9, True
table, enc_next, dec_next, size, first = reset()
put(256, size)
w = b""
for b in data:
wc = w + bytes([b])
if wc in table:
w = wc
continue
put(table[w], size)
if not first:
dec_next += 1
if dec_next >= (1 << size) and size < 13:
size += 1
first = False
if enc_next < 8192:
table[wc] = enc_next
enc_next += 1
w = bytes([b])
else:
put(table[bytes([b])], size) # the last code before the clear
put(256, size)
table, enc_next, dec_next, size, first = reset()
w = b""
continue
if w:
put(table[w], size)
if not first:
dec_next += 1
if dec_next >= (1 << size) and size < 13:
size += 1
put(257, size)
if nbits:
out.append(acc & 255)
return bytes(out)
def lh5_streams(ctx, files, tmp):
"""{name: (packed bytes, crc)} from LHa for UNIX -o5 level 2 archives"""
out = {}
work = os.path.join(tmp, "lh5")
A.tree(files, work)
for name, data in files:
if not data:
continue
arc = os.path.join(tmp, "one.lzh")
if os.path.exists(arc):
os.remove(arc)
A.tool([], ["env", "NIXPKGS_ALLOW_UNFREE=1", "nix", "shell", "--impure", "nixpkgs#lha", "-c", "lha", "-a2o5q", arc, name], cwd=work)
b = open(arc, "rb").read()
total = struct.unpack_from("<H", b, 0)[0]
method = b[2:7]
packed = struct.unpack_from("<I", b, 7)[0]
out[name] = (method, b[total:total + packed])
return out
def entry(name, dirname, method, packed_data, orig, crc, offset, nxt, typ=2, deleted=0, version=None):
short = (os.path.basename(name)[:12]).encode()
fixed = struct.pack("<IBBIIHHHIIBBBBIH13s", TAG, typ, method, nxt, offset, 0x5765, 0x6000, crc, orig, len(packed_data),
2, 1, deleted, 0, 0, 0, short)
if typ == 1:
return fixed
ln, dn = name.encode(), dirname.encode()
var = struct.pack("<BB", len(ln), len(dn)) + ln + dn + struct.pack("<H", 0) + bytes([0o644 & 255, 0o644 >> 8, 0x40])
var += struct.pack("<HH", 0x40 if version else 0, version or 0)
head = fixed + struct.pack("<HBH", len(var), 127, 0) + var
dcrc = crc16(head)
return fixed + struct.pack("<HBH", len(var), 127, dcrc) + var
def archive(items):
"""items: [(name, dir, method, packed, orig, crc, type, deleted, version)] -> zoo bytes"""
hdr = b"ZOO 2.10 Archive.\x1a".ljust(20, b"\0") + struct.pack("<IIiBB", TAG, 34, -34, 2, 0)
out = bytearray(hdr)
p = 34
for (name, d, method, packed, orig, crc, typ, deleted, version) in items:
size = len(entry(name, d, method, packed, orig, crc, 0, 0, typ, deleted, version))
data_at = p + size
nxt = data_at + len(packed)
out += entry(name, d, method, packed, orig, crc, data_at, nxt, typ, deleted, version) + packed
p = nxt
out += entry("", "", 0, b"", 0, 0, 0, 0, 2) # the end marker: next = 0
return bytes(out)
def unar_listing(path, tmp):
j = json.loads(A.tool(["unar"], ["lsar", "-j", path]))
out = os.path.join(tmp, "x")
A.rmtree(out)
A.tool(["unar"], ["unar", "-q", "-f", "-D", "-o", out, path])
got = A.read_tree(out)
ents = []
for e in j["lsarContents"]:
n = e["XADFileName"]
if n in got:
ents.append({"name": n, "size": e.get("XADFileSize", 0), "crc": got[n]})
return ents
def generate(ctx):
rng = ctx.rng(77)
tmp = A.tmpdir()
try:
files = A.FILES + [("text.txt", b"It was the best of times, it was the worst of times, " * 300), ("rand.bin", rng.randbytes(30000)),
("runs.bin", b"\0" * 20000 + bytes(range(256)) * 40)]
lh5 = lh5_streams(ctx, files, tmp)
cases = []
for label, method in (("stored", 0), ("lzw", 1), ("lzh", 2)):
items = []
for name, data in files:
if method == 2 and name in lh5 and lh5[name][0] == b"-lh5-":
packed, m = lh5[name][1], 2
elif method == 1:
packed, m = lzw(data), 1
else:
packed, m = data, 0
d = "dir/sub" if name == "text.txt" else ""
items.append((name, d, m, packed, len(data), crc16(data), 2, 0, None))
items.insert(1, ("gone.txt", "", 0, b"deleted", 7, crc16(b"deleted"), 2, 1, None))
p = os.path.join(tmp, label + ".zoo")
blob = archive(items)
open(p, "wb").write(blob)
ents = [e for e in unar_listing(p, tmp) if e["name"] != "gone.txt"] # unar lists deleted entries; zoo does not
src = {("dir/sub/" if n == "text.txt" else "") + n: zlib.crc32(d) for n, d in files}
assert len(ents) == len(files) and all(src[e["name"]] == e["crc"] for e in ents), (label, ents)
cases.append({"name": label, "data": blob, "entries": ents})
# type 1 entries (zoo 1.x: 8.3 names only)
items = [(n.upper()[:12], "", 0, d, len(d), crc16(d), 1, 0, None) for n, d in A.FILES[:2]]
blob = archive(items)
p = os.path.join(tmp, "type1.zoo")
open(p, "wb").write(blob)
cases.append({"name": "type 1 entries", "data": blob, "entries": unar_listing(p, tmp)})
# a big LZW file: several table resets
big = rng.randbytes(20000) + b"abcabcabd" * 20000
blob = archive([("big.bin", "", 1, lzw(big), len(big), crc16(big), 2, 0, None)])
p = os.path.join(tmp, "big.zoo")
open(p, "wb").write(blob)
cases.append({"name": "lzw table resets", "data": blob, "entries": unar_listing(p, tmp)})
ctx.emit("zoo", {"cases": cases})
finally:
A.rmtree(tmp)