diff --git a/docs/FORMATS.md b/docs/FORMATS.md
index f68bf78..3cc3fe4 100644
--- a/docs/FORMATS.md
+++ b/docs/FORMATS.md
@@ -95,22 +95,47 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` |
| model | x3d | .x3d .x3dv .x3dz .x3dvz .x3db | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true, xml: true, classic: true | `tests/model/x3d.luau` |
| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` |
+| font | bdf | .bdf | yes | yes | bitmap: true | `tests/font/bdf.luau` |
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary", extraFiles: true | `tests/font/bmfont.luau` |
+| font | eot | .eot | yes | yes | variants: "1.0", "2.1", "2.2" | `tests/font/eot.luau` |
+| font | fon | .fon .fnt | yes | - | bitmap: true, variants: "fnt2", "fnt3", "ne", "pe" | `tests/font/fon.luau` |
+| font | hershey | .jhf | yes | - | strokes: true | `tests/font/hershey.luau` |
+| font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.luau` |
+| font | psf | .psf .psfu | yes | yes | bitmap: true, variants: "psf1", "psf2" | `tests/font/psf.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
+| font | type1 | .pfb .pfa .t1 | yes | - | outlines: "type1", variants: "pfb", "pfa" | `tests/font/type1.luau` |
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` |
+| archive | adf | .adf | yes | - | variants: "ofs", "ffs" | `tests/archive/adf.luau` |
+| archive | applesingle | .as .applesingle .appledouble | yes | yes | forks: true, variants: "applesingle", "appledouble" | `tests/archive/applesingle.luau` |
+| archive | ar | .a .ar .deb .lib | yes | yes | variants: "gnu", "bsd", deb: true | `tests/archive/ar.luau` |
+| archive | arj | .arj | yes | - | methods: "store", "arj1", "arj2", "arj3", "arj4" | `tests/archive/arj.luau` |
+| archive | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` |
| archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` |
| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` |
+| archive | cab | .cab | yes | yes | methods: "store", "mszip", "lzx", "quantum" | `tests/archive/cab.luau` |
+| archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` |
+| archive | d64 | .d64 .d71 .d81 | yes | yes | variants: "d64", "d71", "d81" | `tests/archive/d64.luau` |
+| archive | fat | .img .ima .vfd .flp .fat | yes | yes | variants: "fat12", "fat16", "fat32" | `tests/archive/fat.luau` |
| archive | grp | .grp | yes | yes | | `tests/archive/grp.luau` |
| archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` |
+| archive | iso | .iso | yes | - | extensions: "joliet", "rockridge", "eltorito" | `tests/archive/iso.luau` |
+| archive | lha | .lzh .lha .lzs | yes | yes | methods: "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" | `tests/archive/lha.luau` |
+| archive | lz4 | .lz4 .tlz4 | yes | yes | stream: true, legacy: true | `tests/archive/lz4.luau` |
+| archive | macbinary | .bin .macbin | yes | yes | forks: true, variants: "I", "II", "III" | `tests/archive/macbinary.luau` |
| archive | mpq | .mpq .w3x .w3m .sc2map .sc2data .s2ma .scm .scx | yes | - | versions: 1, 2, 3, 4, methods: "zlib", "implode", "bzip2", "lzma", "sparse", encryption: true | `tests/archive/mpq.luau` |
| archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` |
+| archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.luau` |
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
+| archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.luau` |
| archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` |
| archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
+| archive | yenc | .yenc .ync | yes | yes | multipart: true | `tests/archive/yenc.luau` |
+| archive | z | .z .taz .tz | yes | yes | stream: true, bits: 9, 16 | `tests/archive/z.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
+| archive | zoo | .zoo | yes | - | methods: "store", "lzw", "lzh" | `tests/archive/zoo.luau` |
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` |
| data | csv | .csv .tsv | yes | yes | header: true | `tests/data/csv.luau` |
@@ -187,15 +212,22 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ
- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
+ - codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
+ - codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
+ - codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft
+ - codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
+ - codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
- **entropy**
- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
- **font**
+ - codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike
- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
+ - codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- **image**
- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...):
diff --git a/docs/guide/archive.md b/docs/guide/archive.md
index 87a140b..32504c1 100644
--- a/docs/guide/archive.md
+++ b/docs/guide/archive.md
@@ -25,7 +25,7 @@ assert(F.archive.load(out):read("notes/todo.txt"))
| Field / method | Type | Meaning |
|---|---|---|
| `kind` | `"archive"` | |
-| `format` | string | `"zip"`, `"tar"`, `"7z"`, `"gzip"`, `"xz"`, `"zst"`, `"bz2"`, `"br"` |
+| `format` | string | `"zip"`, `"tar"`, `"7z"`, `"gzip"`, `"xz"`, `"zst"`, `"bz2"`, `"br"`, `"cpio"`, `"ar"`, `"rpm"`, `"z"`, `"lz4"`, `"iso"` |
| `list(self)` | `{ ArchiveEntry }` | the entries in archive order (directories included) |
| `read(self, name)` | `buffer?, Err?` | a fresh copy of the entry's bytes, decompressed (lazily, on each call) |
| `add(self, name, data, opts?)` | | add or replace an entry; `data` is a buffer or a string |
@@ -43,7 +43,7 @@ assert(F.archive.load(out):read("notes/todo.txt"))
| `mtime` | number? | modification time, Unix seconds (UTC) |
| `dir` | boolean | a directory entry |
| `crc32`, `comment` | number?, string? | zip only |
-| `mode`, `uid`, `gid`, `uname`, `gname`, `type`, `link` | | tar only (`mode` is the Unix permission bits, e.g. `420` = `0644`) |
+| `mode`, `uid`, `gid`, `uname`, `gname`, `type`, `link` | | tar, cpio, ar, rpm, iso (`mode` is the Unix permission bits, e.g. `420` = `0644`) |
## Load
@@ -85,11 +85,12 @@ Options for loading:
| Option | Formats | Meaning |
|---|---|---|
-| `unwrap` | gzip, xz, zst, bz2, br | `false`: do not open an archive inside a single-stream file (also off when `format` is given) |
+| `unwrap` | gzip, xz, zst, bz2, br, z, lz4, deb | `false`: do not open an archive inside a single-stream file or a `.deb` (also off when `format` is given) |
| `name` | single-stream | the file name, used to name the entry (set for you when loading a path) |
-| `verify` | zip | check each entry's CRC-32 on read (default `true`) |
-| `maxEntries` | tar | refuse more entries (default 1e6) |
-| `maxBytes` | bz2, br | refuse a bigger decompressed size |
+| `verify` | zip, lz4, cpio | check each entry's CRC-32 on read (zip), the XXH32 checksums (lz4), the crc sums (cpio) (default `true`) |
+| `maxEntries` | tar, cpio, ar, rpm, iso | refuse more entries (default 1e6) |
+| `prefer` | iso | the name set: `"rockridge"`, `"joliet"` or `"iso9660"` (default: the richest present) |
+| `maxBytes` | bz2, br, rpm, z, lz4 | refuse a bigger decompressed size |
A path works on hosts with a file system:
@@ -247,6 +248,168 @@ local script = assert(mpq:read("war3map.j")) -- zlib / PKWARE implo
assert(buffer.len(script) == buffer.len(assert(mpq:read("readme.txt"))))
local named = assert(F.archive.load(mpqBytes, { names = { "war3map.w3e" } }))
assert(#named:list() >= 2)
+## Unix, package and disc archives
+
+### cpio
+
+GNU cpio's and bsdtar's newc, crc, odc and old binary archives read; newc, crc and odc write (`variant`, default the
+source's). Entries carry the Unix fields: `type` (tar letters: `"0"` file, `"5"` directory, `"2"` symlink, ...),
+`mode`, `uid`, `gid`, `nlink`, `ino`, device numbers, `link`, and `hardlink` (every link of a hard-linked file reads
+its data).
+
+```luau
+local cpio = assert(F.archive.load(cpioBytes))
+local by = {}
+for _, e in cpio:list() do
+ by[e.name] = e
+end
+assert(by["bin"].dir and by["bin/run.sh"].mode == 493) -- 493 = 0755
+assert(by["run"].type == "2" and by["run"].link == "bin/run.sh") -- a symlink
+local odc = assert(cpio:write({ variant = "odc" }))
+assert(F.archive.load(odc).meta.source.variant == "odc")
+```
+
+### ar and .deb
+
+Unix `ar` archives (GNU / System V long names and symbol tables, BSD `#1/` names) read and write (`variant = "gnu"`
+or `"bsd"`); symbols land in `meta.symbols`. A `.deb` loads as its `data.tar.*` (any compression), with the ar
+archive in `meta.outer` and the control file's fields in `meta.outer.meta.control`:
+
+```luau
+local deb = assert(F.archive.load(debBytes))
+assert(deb.format == "tar" and deb.meta.container == "ar")
+assert(deb:read("./usr/bin/hello"))
+local control = deb.meta.outer.meta.control
+assert(control.Package == "hello" and control.Version == "1.0-1")
+local ar = assert(F.archive.load(debBytes, { unwrap = false })) -- the ar itself
+assert(ar:list()[1].name == "debian-binary" and ar.meta.payload == "data.tar.xz")
+```
+
+### rpm
+
+RPM packages list from their header (no decompression); the payload (gzip, bzip2, xz, lzma or zstd) is decompressed
+on the first `read`. The header fields are in `meta.rpm` (`name`, `version`, `release`, `arch`, `summary`, ... and
+every tag by number in `meta.rpm.tags`). Read only.
+
+```luau
+local rpm = assert(F.archive.load(rpmBytes))
+assert(rpm.meta.rpm.name == "hello" and rpm.meta.rpm.version == "1.0" and rpm.meta.rpm.arch == "noarch")
+assert(rpm:list()[1].name == "usr/bin/hello" and rpm:list()[1].mode == 493)
+local hello = buffer.tostring(assert(rpm:read("usr/bin/hello")))
+assert(string.find(hello, "echo hello", 1, true))
+```
+
+### .Z and .lz4
+
+Unix `compress` (`.Z`, `.taz`) and LZ4 frame (`.lz4`) files are single-stream archives like gzip: a `.tar.Z` or
+`.tar.lz4` loads as the tar. Both write: `.Z` byte for byte as ncompress (`maxBits` 9..16), `.lz4` as one frame of
+independent blocks (`blockSize`, `blockChecksum`, `contentChecksum`, `contentSize`).
+
+```luau
+local tar = assert(F.archive.load(tarZBytes))
+assert(tar.format == "tar" and tar.meta.compression == "z")
+local lz = assert(F.archive.load(lz4Bytes, { name = "notes.txt.lz4" }))
+assert(lz.meta.stream and lz:list()[1].name == "notes.txt")
+local z = assert(F.save(tar, nil, { format = "z" })) -- a tar inside
+assert(F.archive.load(z).format == "tar")
+local l4 = assert(F.save("some text", nil, { format = "lz4", blockChecksum = true }))
+assert(buffer.tostring(F.archive.load(l4):read("data")) == "some text")
+```
+
+### ISO images
+
+ISO 9660 images read with Rock Ridge names, modes and symlinks when present, else Joliet's Unicode names, else the
+plain ISO names (`prefer = "joliet"` / `"iso9660"` picks another set). `meta.iso` has the volume facts and
+`meta.boot` an El Torito boot catalog. Read only.
+
+```luau
+local iso = assert(F.archive.load(isoBytes))
+assert(iso.meta.iso.volumeId == "DOCS" and iso.meta.iso.rockRidge and iso.meta.iso.joliet)
+assert(iso.meta.boot and iso.meta.boot.bootable)
+local by = {}
+for _, e in iso:list() do
+ by[e.name] = e
+end
+assert(by["bin"].dir and by["bin/run.sh"].mode == 493 and by["run"].link == "bin/run.sh")
+assert(F.archive.load(isoBytes, { prefer = "joliet" }).meta.iso.tree == "joliet")
+```
+
+## LHA, ARJ and Zoo
+
+DOS-era archives read with their own compressors (`codecs/compress/Lzh`): LHA / LZH at header levels 0 to 3 with
+lh0, lh1, lh4 to lh7, lhx and LArc's lzs / lz5 (Unix modes, symlinks, CRC-16 checked on `read`), ARJ methods 0 to 4
+(CRC-32 checked) and Zoo's stored, LZW and lzh entries (deleted entries skipped). LHA also writes (level 2 headers,
+stored data); ARJ and Zoo are read only.
+
+```luau
+local lzh = assert(F.archive.load(lzhBytes))
+assert(lzh.format == "lha" and lzh:list()[1].method == "lh0") -- small files are stored
+assert(buffer.tostring(assert(lzh:read("readme.txt"))) == "formats-luau retro archives\n")
+local arj = assert(F.archive.load(arjBytes))
+assert(arj:read("src/main.c"))
+local zoo = assert(F.archive.load(zooBytes))
+assert(zoo:list()[1].method == "lzw" and zoo:read("readme.txt"))
+local stored = assert(F.save(lzh, nil, { format = "lha" })) -- level 2, lh0
+assert(F.archive.load(stored):list()[1].method == "lh0")
+```
+
+## Encodings
+
+Text and Mac encodings load as archives too: uuencode / xxencode / `begin-base64` blocks (`uu`), yEnc (multi-part
+postings in one text are joined), BinHex 4.0, MacBinary I / II / III and AppleSingle / AppleDouble. All of them read
+and write. Mac files keep the data fork as the entry `name` and a resource fork as `name .. ".rsrc"`
+(`fork = "resource"`), with `macType`, `macCreator` and `finderFlags`. A single-file encoding is a stream, so a
+uuencoded `.tar.gz` loads as the tar.
+
+```luau
+local uu = assert(F.archive.load(uuText))
+assert(uu:list()[1].name == "readme.txt" and uu:list()[1].mode == 420) -- 420 = 0644
+local a = F.format("binhex").new()
+a:add("Read Me", "the data fork")
+a:add("Read Me.rsrc", "resources")
+a._byName["Read Me.rsrc"].fork = "resource"
+local hqx = assert(a:write())
+local back = assert(F.archive.load(hqx))
+assert(back:list()[2].fork == "resource" and buffer.tostring(back:read("Read Me")) == "the data fork")
+local y = assert(F.save(uu, nil, { format = "yenc" }))
+assert(string.sub(buffer.tostring(y), 1, 8) == "=ybegin ")
+```
+
+## Disk images
+
+Floppy and disk images list their files: Commodore D64 / D71 / D81 (PETSCII names as VICE's c1541 shows them,
+`type` = `prg` / `seq` / `usr` / `rel`, disk name and id in `meta`), Amiga ADF (OFS / FFS, international and
+directory-cache modes, protection bits, comments, links) and FAT12 / FAT16 / FAT32 images (VFAT long names; a
+hard-disk image opens its first FAT partition, `partition` picks another). D64 and FAT floppies also write.
+
+```luau
+local d64 = assert(F.archive.load(d64Bytes))
+assert(d64.meta.disk == "games" and d64:list()[1].type == "prg")
+local adf = assert(F.archive.load(adfBytes))
+assert(adf.meta.volume == "Work" and adf.meta.fs == "ffs" and adf:read("s/readme"))
+local fat = assert(F.archive.load(floppyBytes))
+assert(fat.meta.fat == 12 and fat.meta.label == "DOCS" and fat:read("src/main.c"))
+local floppy = assert(F.save(adf, nil, { format = "fat", size = 720 })) -- copy the ADF's files to a FAT floppy
+assert(F.archive.load(floppy):read("s/readme"))
+```
+
+## Microsoft Cabinet
+
+Cabinet files (`.cab`) read with stored, MSZIP, LZX and Quantum folders; each data block's checksum is checked when
+a file of its folder is read. Entries carry the MS-DOS `attributes` (`readonly`, `executable`), `utf8` (the name flag)
+and `folder`; DOS times are local times without a zone, read as UTC. Files continued from or into another cabinet of
+a set read as `UNSUPPORTED`. Writing makes one folder, MSZIP (default, `level`) or stored (`compression = "none"`):
+
+```luau
+local cab = assert(F.archive.load(cabBytes))
+assert(cab.format == "cab" and cab.meta.folders[1].method == "mszip")
+local by = {}
+for _, e in cab:list() do
+ by[e.name] = e
+end
+assert(by["bin/tool.dll"].size == 16384 and by["readme.txt"].mtime == 1767225600)
+local out = assert(F.save(cab, nil, { format = "cab", compression = "none" }))
+assert(F.archive.load(out):list()[1].method == "store")
```
## Formats
@@ -266,6 +429,24 @@ assert(#named:list() >= 2)
| GRP (`.grp`) | yes | yes | Build engine |
| VPK (`.vpk`) | yes | yes | versions 1 / 2, multi-part reading, preload bytes; writes one directory file |
| MPQ (`.mpq`, `.w3x`, `.sc2map`, ...) | yes | - | versions 1-4 (classic tables), encryption; no Huffman / ADPCM (WAVE) sectors |
+| cpio (`.cpio`) | yes | yes | newc, crc, odc, old binary (read); hard links, symlinks, devices |
+| ar (`.a`, `.ar`, `.deb`) | yes | yes | GNU / BSD names, symbol tables; a `.deb` loads as its data tar |
+| rpm (`.rpm`) | yes | - | gzip / bzip2 / xz / lzma / zstd payloads |
+| compress (`.Z`, `.taz`) | yes | yes | single stream; 9..16-bit LZW |
+| LZ4 (`.lz4`) | yes | yes | single stream; frames, legacy frames, XXH32 checks; no dictionaries |
+| ISO 9660 (`.iso`) | yes | - | Joliet, Rock Ridge, El Torito, multi-extent; no UDF |
+| LHA (`.lzh`, `.lha`, `.lzs`) | yes | yes | levels 0-3; lh0 / lh1 / lh4-lh7 / lhx / lzs / lz5; writes stored level 2 |
+| ARJ (`.arj`) | yes | - | methods 0-4; no garbled entries, no multi-volume |
+| Zoo (`.zoo`) | yes | - | stored / LZW / lzh |
+| uuencode / xxencode (`.uu`, `.xxe`) | yes | yes | several blocks per text; GNU `begin-base64` too |
+| yEnc (`.yenc`) | yes | yes | multi-part postings in one text |
+| BinHex 4.0 (`.hqx`) | yes | yes | data and resource forks |
+| MacBinary (`.bin`) | yes | yes | I / II / III; writes III |
+| AppleSingle / AppleDouble | yes | yes | versions 1 and 2 |
+| C64 disks (`.d64`, `.d71`, `.d81`) | yes | yes | PETSCII names; no GEOS VLIR |
+| Amiga disks (`.adf`) | yes | - | OFS / FFS; no long-name (DOS 6 / 7) volumes |
+| FAT images (`.img`, `.ima`) | yes | yes | FAT12 / 16 / 32, VFAT names, MBR partitions; writes FAT12 floppies |
+| Cabinet (`.cab`) | yes | yes | stored / MSZIP / LZX / Quantum (read), stored / MSZIP (write); no spanned files |
Full capability list: [FORMATS.md](../FORMATS.md).
diff --git a/docs/guide/font.md b/docs/guide/font.md
index d784a96..a02df94 100644
--- a/docs/guide/font.md
+++ b/docs/guide/font.md
@@ -232,6 +232,46 @@ local bm = assert(F.font.load(fnt, { loadPage = function(file) return pages[file
assert(bm:rasterize(bm:glyphIndex(string.byte("H"))))
```
+## Bitmap fonts
+
+BDF, PCF, PSF (Linux console) and Windows FNT / FON fonts load as the same Font, with their glyph bitmaps in
+`font.bitmap` (`size`, `ascent`, `descent`, `glyphs[i] = { codepoint, name, width, height, left, top, advance,
+pixels }`, one byte per pixel, 0 or 255). Units are pixels: `unitsPerEm` is the pixel size, `rasterize` returns the
+glyph as stored (its `px` argument only sets `img.meta.scale`), `outline` is nil. `.pcf.gz` and `.psfu.gz` load
+through the gzip. BDF and PSF also write, from any Font: a bitmap font as it is, an outline font rasterized at `px`.
+
+```luau
+local bdf = assert(F.font.load(bdfText))
+assert(bdf.unitsPerEm == 8 and bdf.bitmap.glyphs[1].pixels)
+local g = bdf:rasterize(bdf:glyphIndex(65), 8)
+assert(g.format == "alpha8" and g.meta.advance == 5)
+local pcf = assert(F.font.load(pcfBytes))
+assert(pcf:glyphIndex(65) == bdf:glyphIndex(65))
+local psf = assert(F.font.load(psfBytes))
+assert(psf.meta.width == 8 and psf.meta.height == 16 and psf:glyphIndex(65) > 0)
+local fnt = assert(F.font.load(fntBytes))
+assert(fnt.unitsPerEm == 16)
+local console = assert(F.save(bdf, nil, { format = "psf" })) -- BDF -> PSF 2
+assert(F.font.load(console).meta.source.format == "psf")
+```
+
+## Type 1, EOT and Hershey
+
+PostScript Type 1 fonts (PFB and PFA) decrypt and run their charstrings into the same outlines as TrueType ones
+(glyph names map to Unicode through the Adobe Glyph List). EOT files unwrap the TrueType font inside (MTX-compressed
+ones are unsupported) and write. Hershey JHF fonts are stroke fonts: `outline` gives open paths (`meta.strokes`),
+`rasterize` strokes them.
+
+```luau
+local t1 = assert(F.font.load(pfbBytes))
+assert(t1.unitsPerEm == 1000 and t1.info.family == "LMRoman10")
+assert(t1:rasterize(t1:glyphIndex(string.byte("g")), 32).width > 5)
+local eot = assert(F.font.load(eotBytes))
+assert(eot.meta.eot.familyName == "DejaVu Sans Mono" and eot:glyphIndex(65) > 0)
+local jhf = assert(F.font.load(jhfText))
+assert(jhf.meta.strokes and jhf:outline(1)[1].op == "moveTo")
+```
+
## Formats
| Format | Read | Write | Notes |
@@ -240,13 +280,21 @@ assert(bm:rasterize(bm:glyphIndex(string.byte("H"))))
| woff | yes | - | |
| woff2 | yes | - | |
| bmfont (`.fnt`) | yes | yes | text, XML and binary descriptors; `bake` from any outline font |
+| bdf (`.bdf`) | yes | yes | BDF 2.1; writes Unicode BDF from any font |
+| pcf (`.pcf`, `.pcf.gz`) | yes | - | every glyph pad / bit / byte order |
+| psf (`.psf`, `.psfu`) | yes | yes | PSF 1 / 2 with Unicode tables |
+| fon (`.fon`, `.fnt`) | yes | - | Windows raster FNT 2 / 3, NE / PE .fon with several sizes |
+| type1 (`.pfb`, `.pfa`) | yes | - | Type 1 charstrings (flex, seac), StandardEncoding / custom encodings |
+| eot (`.eot`) | yes | yes | EOT 1.0 / 2.1 / 2.2, XOR; no MTX |
+| hershey (`.jhf`) | yes | - | stroke fonts |
See [FORMATS.md](../FORMATS.md) for the capability matrix.
## Gotchas
- **No hinting, no shaping.** Glyphs are rendered from the outlines without hinting; there is no GSUB (ligatures,
- contextual forms), no variable fonts (CFF2 / gvar return `UNSUPPORTED`) and no colour or bitmap glyphs.
+ contextual forms), no variable fonts (CFF2 / gvar return `UNSUPPORTED`) and no colour glyphs or embedded bitmap
+ strikes in TrueType fonts (bitmap font formats are separate: see above).
- **`px` is the em size**, not the line height. The line height is `(ascent - descent + lineGap) * px / unitsPerEm`.
- **Units differ by kind.** Outline fonts measure in font units; BMFont in pixels at its baked size. Use
`font.unitsPerEm` for both: for a BMFont, `px / unitsPerEm` is the scale relative to the baked size.
diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md
index 053798f..08a718d 100644
--- a/licenses/NOTICE.md
+++ b/licenses/NOTICE.md
@@ -48,6 +48,10 @@
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
| `tests/gen/wad` (cut down from the nix freedoom package at fixture time, not committed) | Freedoom 0.13 (freedoom.github.io) | BSD-3-Clause: [freedoom-COPYING.txt](freedoom-COPYING.txt) |
| `src/Formats/codecs/compress/Explode.luau` (the PKWARE DCL code tables and bit order) | blast.c 1.3 (Mark Adler, zlib contrib) | zlib: [blast-LICENSE.txt](blast-LICENSE.txt) |
+| `src/Formats/codecs/compress/Lzh/` (lh1 adaptive Huffman, lh4..lh7 block decoding, lzs / lz5) | lhasa 0.6.0 (Simon Howard) | ISC: [lhasa-LICENSE.txt](lhasa-LICENSE.txt) |
+| `tests/gen/lha` (read from nixpkgs#lhasa.src at fixture time, not committed) | lhasa 0.6.0 test archives | ISC (lhasa) |
+| `src/Formats/codecs/font/GlyphNames.luau` (glyph name -> Unicode table, StandardEncoding) | Adobe Glyph List For New Fonts 1.7 (via fontTools) | BSD-3-Clause: [agl-LICENSE.txt](agl-LICENSE.txt) |
+| `src/Formats/codecs/compress/UnixCompress.luau` (the .Z format and the encoder's ratio check / CLEAR rule, read from compress.c; the code is new) | ncompress 5.0 | public domain (The Unlicense): [ncompress-UNLICENSE.txt](ncompress-UNLICENSE.txt) |
| `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) |
| `src/Formats/codecs/model/Draco/` | Luau port of the Draco 1.5.7 decoder (Google): compression/{decode, mesh, attributes, entropy, bit_coders, point_cloud}, mesh/corner_table, mesh/mesh_attribute_corner_table, core/{decoder_buffer, varint_decoding, math_utils}, attributes/attribute_{quantization,octahedron}_transform | Apache-2.0: [draco-LICENSE.txt](draco-LICENSE.txt) |
| `src/Formats/model/ldraw/Colors.luau` (the built-in colour table) | the !COLOUR list of LDConfig.ldr (LDraw.org Parts Library, UPDATE 2025-05-20), reformatted | CC BY 2.0 / CC BY 4.0: [LDRAW_COLOURS.txt](LDRAW_COLOURS.txt) |
diff --git a/licenses/agl-LICENSE.txt b/licenses/agl-LICENSE.txt
new file mode 100644
index 0000000..9d53e6b
--- /dev/null
+++ b/licenses/agl-LICENSE.txt
@@ -0,0 +1,32 @@
+Copyright 2002-2019 Adobe (http://www.adobe.com/).
+
+Redistribution and use in source and binary forms, with or
+without modification, are permitted provided that the
+following conditions are met:
+
+Redistributions of source code must retain the above
+copyright notice, this list of conditions and the following
+disclaimer.
+
+Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following
+disclaimer in the documentation and/or other materials
+provided with the distribution.
+
+Neither the name of Adobe nor the names of its contributors
+may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/licenses/lhasa-LICENSE.txt b/licenses/lhasa-LICENSE.txt
new file mode 100644
index 0000000..b61c5d3
--- /dev/null
+++ b/licenses/lhasa-LICENSE.txt
@@ -0,0 +1,17 @@
+## ISC License
+
+Copyright (c) 2011-2025, Simon Howard
+
+Permission to use, copy, modify, and/or distribute this software
+for any purpose with or without fee is hereby granted, provided
+that the above copyright notice and this permission notice appear
+in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
+AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
+CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/licenses/ncompress-UNLICENSE.txt b/licenses/ncompress-UNLICENSE.txt
new file mode 100644
index 0000000..68a49da
--- /dev/null
+++ b/licenses/ncompress-UNLICENSE.txt
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to
diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau
index 28f9f8a..682bb32 100644
--- a/src/Formats/Registry.luau
+++ b/src/Formats/Registry.luau
@@ -1094,6 +1094,18 @@ local list: { Entry } = {
return require("@formats/cad/step")
end,
},
+ {
+ name = "bdf",
+ category = "font",
+ path = "font/bdf",
+ extensions = { "bdf" },
+ mime = { "application/x-font-bdf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = true, bitmap = true },
+ load = function()
+ return require("@formats/font/bdf")
+ end,
+ },
{
name = "bmfont",
category = "font",
@@ -1106,6 +1118,66 @@ local list: { Entry } = {
return require("@formats/font/bmfont")
end,
},
+ {
+ name = "eot",
+ category = "font",
+ path = "font/eot",
+ extensions = { "eot" },
+ mime = { "application/vnd.ms-fontobject" },
+ deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" },
+ caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } },
+ load = function()
+ return require("@formats/font/eot")
+ end,
+ },
+ {
+ name = "fon",
+ category = "font",
+ path = "font/fon",
+ extensions = { "fon", "fnt" },
+ mime = { "application/x-font-fnt" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } },
+ load = function()
+ return require("@formats/font/fon")
+ end,
+ },
+ {
+ name = "hershey",
+ category = "font",
+ path = "font/hershey",
+ extensions = { "jhf" },
+ mime = { "application/x-hershey-font" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" },
+ caps = { decode = true, encode = false, strokes = true },
+ load = function()
+ return require("@formats/font/hershey")
+ end,
+ },
+ {
+ name = "pcf",
+ category = "font",
+ path = "font/pcf",
+ extensions = { "pcf" },
+ mime = { "application/x-font-pcf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = false, bitmap = true },
+ load = function()
+ return require("@formats/font/pcf")
+ end,
+ },
+ {
+ name = "psf",
+ category = "font",
+ path = "font/psf",
+ extensions = { "psf", "psfu" },
+ mime = { "application/x-font-linux-psf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } },
+ load = function()
+ return require("@formats/font/psf")
+ end,
+ },
{
name = "ttf",
category = "font",
@@ -1118,6 +1190,18 @@ local list: { Entry } = {
return require("@formats/font/ttf")
end,
},
+ {
+ name = "type1",
+ category = "font",
+ path = "font/type1",
+ extensions = { "pfb", "pfa", "t1" },
+ mime = { "application/x-font-type1" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
+ caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
+ load = function()
+ return require("@formats/font/type1")
+ end,
+ },
{
name = "woff",
category = "font",
@@ -1154,6 +1238,66 @@ local list: { Entry } = {
return require("@formats/archive/7z")
end,
},
+ {
+ name = "adf",
+ category = "archive",
+ path = "archive/adf",
+ extensions = { "adf" },
+ mime = { "application/x-amiga-disk-format" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive" },
+ caps = { decode = true, encode = false, variants = { "ofs", "ffs" } },
+ load = function()
+ return require("@formats/archive/adf")
+ end,
+ },
+ {
+ name = "applesingle",
+ category = "archive",
+ path = "archive/applesingle",
+ extensions = { "as", "applesingle", "appledouble" },
+ mime = { "application/applefile", "multipart/appledouble" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" },
+ caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } },
+ load = function()
+ return require("@formats/archive/applesingle")
+ end,
+ },
+ {
+ name = "ar",
+ category = "archive",
+ path = "archive/ar",
+ extensions = { "a", "ar", "deb", "lib" },
+ mime = { "application/x-archive", "application/vnd.debian.binary-package" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
+ caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
+ load = function()
+ return require("@formats/archive/ar")
+ end,
+ },
+ {
+ name = "arj",
+ category = "archive",
+ path = "archive/arj",
+ extensions = { "arj" },
+ mime = { "application/x-arj" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" },
+ caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } },
+ load = function()
+ return require("@formats/archive/arj")
+ end,
+ },
+ {
+ name = "binhex",
+ category = "archive",
+ path = "archive/binhex",
+ extensions = { "hqx", "hcx" },
+ mime = { "application/mac-binhex40" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" },
+ caps = { decode = true, encode = true, forks = true },
+ load = function()
+ return require("@formats/archive/binhex")
+ end,
+ },
{
name = "br",
category = "archive",
@@ -1178,6 +1322,54 @@ local list: { Entry } = {
return require("@formats/archive/bz2")
end,
},
+ {
+ name = "cab",
+ category = "archive",
+ path = "archive/cab",
+ extensions = { "cab" },
+ mime = { "application/vnd.ms-cab-compressed" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" },
+ caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } },
+ load = function()
+ return require("@formats/archive/cab")
+ end,
+ },
+ {
+ name = "cpio",
+ category = "archive",
+ path = "archive/cpio",
+ extensions = { "cpio" },
+ mime = { "application/x-cpio" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
+ caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
+ load = function()
+ return require("@formats/archive/cpio")
+ end,
+ },
+ {
+ name = "d64",
+ category = "archive",
+ path = "archive/d64",
+ extensions = { "d64", "d71", "d81" },
+ mime = { "application/x-d64" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive" },
+ caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } },
+ load = function()
+ return require("@formats/archive/d64")
+ end,
+ },
+ {
+ name = "fat",
+ category = "archive",
+ path = "archive/fat",
+ extensions = { "img", "ima", "vfd", "flp", "fat" },
+ mime = { "application/x-fat-image" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" },
+ caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } },
+ load = function()
+ return require("@formats/archive/fat")
+ end,
+ },
{
name = "grp",
category = "archive",
@@ -1202,6 +1394,54 @@ local list: { Entry } = {
return require("@formats/archive/gzip")
end,
},
+ {
+ name = "iso",
+ category = "archive",
+ path = "archive/iso",
+ extensions = { "iso" },
+ mime = { "application/x-iso9660-image" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
+ caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
+ load = function()
+ return require("@formats/archive/iso")
+ end,
+ },
+ {
+ name = "lha",
+ category = "archive",
+ path = "archive/lha",
+ extensions = { "lzh", "lha", "lzs" },
+ mime = { "application/x-lzh-compressed" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" },
+ caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } },
+ load = function()
+ return require("@formats/archive/lha")
+ end,
+ },
+ {
+ name = "lz4",
+ category = "archive",
+ path = "archive/lz4",
+ extensions = { "lz4", "tlz4" },
+ mime = { "application/x-lz4" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
+ caps = { decode = true, encode = true, stream = true, legacy = true },
+ load = function()
+ return require("@formats/archive/lz4")
+ end,
+ },
+ {
+ name = "macbinary",
+ category = "archive",
+ path = "archive/macbinary",
+ extensions = { "bin", "macbin" },
+ mime = { "application/x-macbinary" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" },
+ caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } },
+ load = function()
+ return require("@formats/archive/macbinary")
+ end,
+ },
{
name = "mpq",
category = "archive",
@@ -1226,6 +1466,18 @@ local list: { Entry } = {
return require("@formats/archive/pak")
end,
},
+ {
+ name = "rpm",
+ category = "archive",
+ path = "archive/rpm",
+ extensions = { "rpm" },
+ mime = { "application/x-rpm" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
+ caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
+ load = function()
+ return require("@formats/archive/rpm")
+ end,
+ },
{
name = "tar",
category = "archive",
@@ -1238,6 +1490,18 @@ local list: { Entry } = {
return require("@formats/archive/tar")
end,
},
+ {
+ name = "uu",
+ category = "archive",
+ path = "archive/uu",
+ extensions = { "uu", "uue", "xxe", "b64" },
+ mime = { "text/x-uuencode" },
+ deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" },
+ caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } },
+ load = function()
+ return require("@formats/archive/uu")
+ end,
+ },
{
name = "vpk",
category = "archive",
@@ -1274,6 +1538,30 @@ local list: { Entry } = {
return require("@formats/archive/xz")
end,
},
+ {
+ name = "yenc",
+ category = "archive",
+ path = "archive/yenc",
+ extensions = { "yenc", "ync" },
+ mime = { "application/x-yenc" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" },
+ caps = { decode = true, encode = true, multipart = true },
+ load = function()
+ return require("@formats/archive/yenc")
+ end,
+ },
+ {
+ name = "z",
+ category = "archive",
+ path = "archive/z",
+ extensions = { "z", "taz", "tz" },
+ mime = { "application/x-compress" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
+ caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
+ load = function()
+ return require("@formats/archive/z")
+ end,
+ },
{
name = "zip",
category = "archive",
@@ -1286,6 +1574,18 @@ local list: { Entry } = {
return require("@formats/archive/zip")
end,
},
+ {
+ name = "zoo",
+ category = "archive",
+ path = "archive/zoo",
+ extensions = { "zoo" },
+ mime = { "application/x-zoo" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" },
+ caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } },
+ load = function()
+ return require("@formats/archive/zoo")
+ end,
+ },
{
name = "zst",
category = "archive",
diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau
index fd4092d..40e225b 100644
--- a/src/Formats/Types.luau
+++ b/src/Formats/Types.luau
@@ -655,8 +655,28 @@ export type Font = {
outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo
rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8
pages: { Image }?, -- bitmap fonts (BMFont)
+ bitmap: BitmapStrike?, -- bitmap fonts with per-glyph bitmaps (BDF, PCF, PSF, FON): codecs/font/Bitmap
meta: { [string]: any },
}
+-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline
+export type BitmapGlyph = {
+ codepoint: number?, -- Unicode (nil for unencoded glyphs)
+ name: string?, -- glyph name (BDF STARTCHAR, PCF glyph names, PostScript names)
+ width: number, -- bitmap width / height in pixels
+ height: number,
+ left: number, -- x of the bitmap's left column relative to the pen
+ top: number, -- y of the bitmap's top row above the baseline (BDF: BBXoff + BBh)
+ advance: number, -- pen advance in pixels
+ pixels: buffer, -- u8 per pixel (width * height, rows top down): 0 = off, 255 = on (grey fonts use 1..254)
+}
+export type BitmapStrike = {
+ size: number, -- pixel size (em height in pixels)
+ ascent: number, -- pixels above the baseline
+ descent: number, -- pixels below the baseline (positive)
+ glyphs: { BitmapGlyph }, -- glyph index i + 1 is font glyph i (glyph 0 = the default / .notdef glyph)
+ default: number?, -- glyph index (0-based) used for unmapped code points
+ map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph)
+}
-- ------------------------------------------------------------------------------------------------ Archive
export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean }
@@ -837,6 +857,7 @@ local function civilFromDays(z: number): (number, number, number)
return (if m <= 2 then y + 1 else y), m, d
end
DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian)
+DateLib.daysFromCivil = daysFromCivil -- year, month, day -> days since 1970-01-01
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
-- new(fields) -> Date (kind inferred from the fields present when not given)
function DateLib.new(f: { [string]: any }): Date
diff --git a/src/Formats/archive/adf/init.luau b/src/Formats/archive/adf/init.luau
new file mode 100644
index 0000000..ecf641c
--- /dev/null
+++ b/src/Formats/archive/adf/init.luau
@@ -0,0 +1,288 @@
+--!strict
+-- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an
+-- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international,
+-- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through
+-- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the
+-- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked
+-- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...),
+-- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are
+-- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description
+-- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk
+-- images (use the partition contents), dircache blocks (not needed to read).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Adf = {
+ name = "adf",
+ category = "archive",
+ extensions = { "adf" },
+ mime = { "application/x-amiga-disk-format" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive" },
+ caps = { decode = true, encode = false, variants = { "ofs", "ffs" } },
+}
+
+export type DecodeOptions = { maxEntries: number? } -- default 65536
+
+-- ------------------------------------------------------------------------------------------------ constants
+local BS = 512
+local HT = 72 -- hash table slots in a 512-byte block
+local T_HEADER, T_DATA, T_LIST = 2, 8, 16
+local ST_ROOT, ST_USERDIR, ST_SOFTLINK, ST_LINKDIR, ST_FILE, ST_LINKFILE = 1, 2, 3, 4, -3, -4
+local EPOCH = 252460800 -- 1978-01-01 in unix seconds
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Adf.sniff(r: Bytes.Reader): number
+ local n = r:size()
+ if n < 4 * BS or n % BS ~= 0 then
+ return 0
+ end
+ local h = r:peek(4)
+ if string.sub(h, 1, 3) ~= "DOS" or string.byte(h, 4) > 5 then
+ return 0
+ end
+ return if n == 901120 or n == 1802240 then 0.95 else 0.6
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function latin1(s: string): string
+ if not string.find(s, "[\128-\255]") then
+ return s
+ end
+ local out = table.create(#s)
+ for i = 1, #s do
+ out[i] = utf8.char(string.byte(s, i))
+ end
+ return table.concat(out)
+end
+
+type Disk = { b: buffer, base: number, blocks: number }
+
+local function u32(d: Disk, blk: number, off: number): number
+ local o = d.base + blk * BS + off
+ return buffer.readu8(d.b, o) * 16777216 + buffer.readu8(d.b, o + 1) * 65536 + buffer.readu8(d.b, o + 2) * 256 + buffer.readu8(d.b, o + 3)
+end
+
+local function i32(d: Disk, blk: number, off: number): number
+ local v = u32(d, blk, off)
+ return if v >= 0x80000000 then v - 0x100000000 else v
+end
+
+local function bstr(d: Disk, blk: number, off: number, max: number): string
+ local o = d.base + blk * BS + off
+ local n = math.min(buffer.readu8(d.b, o), max)
+ return latin1(buffer.readstring(d.b, o + 1, n))
+end
+
+local function checksumOk(d: Disk, blk: number): boolean
+ local sum = 0
+ for i = 0, BS - 4, 4 do
+ sum = (sum + u32(d, blk, i)) % 0x100000000
+ end
+ return sum == 0
+end
+
+local function date(d: Disk, blk: number, off: number): number
+ return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH
+end
+
+-- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables)
+local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?)
+ local out = {}
+ local blk = hdr
+ local seen: { [number]: boolean } = {}
+ while blk ~= 0 do
+ if blk < 2 or blk >= d.blocks or seen[blk] then
+ return nil, "bad extension block " .. blk
+ end
+ seen[blk] = true
+ if blk ~= hdr and (u32(d, blk, 0) ~= T_LIST or not checksumOk(d, blk)) then
+ return nil, "bad extension block " .. blk
+ end
+ local n = u32(d, blk, 8)
+ if n > HT then
+ return nil, "bad block count in " .. blk
+ end
+ for k = 0, n - 1 do
+ local db = u32(d, blk, 24 + (HT - 1 - k) * 4)
+ if db < 2 or db >= d.blocks then
+ return nil, "bad data block " .. db
+ end
+ table.insert(out, db)
+ if #out > maxBlocks then
+ return nil, "more data blocks than the disk has"
+ end
+ end
+ blk = u32(d, blk, BS - 8)
+ end
+ return out, nil
+end
+
+local function readFile(d: Disk, hdr: number, ofs: boolean): (buffer?, string?)
+ local size = u32(d, hdr, BS - 188)
+ if size > d.blocks * BS then
+ return nil, "file larger than the disk"
+ end
+ local list, err = dataBlocks(d, hdr, d.blocks)
+ if not list then
+ return nil, err
+ end
+ local out = buffer.create(size)
+ local o = 0
+ for _, db in list do
+ if o >= size then
+ break
+ end
+ if ofs then
+ if u32(d, db, 0) ~= T_DATA then
+ return nil, "data block " .. db .. " is not an OFS data block"
+ end
+ local n = math.min(u32(d, db, 12), 488, size - o)
+ buffer.copy(out, o, d.b, d.base + db * BS + 24, n)
+ o += n
+ else
+ local n = math.min(BS, size - o)
+ buffer.copy(out, o, d.b, d.base + db * BS, n)
+ o += n
+ end
+ end
+ if o < size then
+ return nil, "file data ends early"
+ end
+ return out, nil
+end
+
+function Adf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local n = r:size()
+ if n < 4 * BS or n % BS ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "not a whole number of 512-byte blocks")
+ end
+ local h = r:peek(4)
+ if string.sub(h, 1, 3) ~= "DOS" then
+ return nil, Err.new(Err.CORRUPT, "no DOS boot block")
+ end
+ local flags = string.byte(h, 4)
+ if flags > 5 then
+ return nil, Err.new(Err.UNSUPPORTED, "DOS\\" .. flags .. " (long names) file systems")
+ end
+ local d: Disk = { b = r.buf, base = r.base, blocks = n // BS }
+ local ofs = bit32.band(flags, 1) == 0
+ local root = (d.blocks - 1 + 2) // 2
+ if u32(d, root, 0) ~= T_HEADER or i32(d, root, BS - 4) ~= ST_ROOT then
+ return nil, Err.new(Err.CORRUPT, "no root block at " .. root)
+ end
+ if not checksumOk(d, root) then
+ return nil, Err.new(Err.CHECKSUM, "root block checksum")
+ end
+ local a = Archive.new("adf")
+ a.meta.volume = bstr(d, root, BS - 80, 30)
+ a.meta.fs = if ofs then "ofs" else "ffs"
+ a.meta.intl = flags >= 2
+ a.meta.dircache = flags >= 4
+ a.meta.dosType = flags
+ a.meta.modified = date(d, root, BS - 92)
+ a.meta.created = date(d, root, BS - 28)
+ a.meta.source = { format = "adf", fs = a.meta.fs, blocks = d.blocks }
+ local maxEntries = o.maxEntries or 65536
+ local count = 0
+ local pathOf: { [number]: string } = {}
+ local links: { { entry: any, target: number } } = {}
+ local visited: { [number]: boolean } = { [root] = true }
+
+ local function walk(dir: number, prefix: string): (boolean, Err.Err?)
+ for slot = 0, HT - 1 do
+ local blk = u32(d, dir, 24 + slot * 4)
+ while blk ~= 0 do
+ if blk < 2 or blk >= d.blocks or visited[blk] then
+ return false, Err.new(Err.CORRUPT, "bad or looping hash chain at block " .. blk)
+ end
+ visited[blk] = true
+ count += 1
+ if count > maxEntries then
+ return false, Err.new(Err.LIMIT, "more than maxEntries entries")
+ end
+ if u32(d, blk, 0) ~= T_HEADER then
+ return false, Err.new(Err.CORRUPT, "block " .. blk .. " is not a header block")
+ end
+ if not checksumOk(d, blk) then
+ return false, Err.new(Err.CHECKSUM, "header block " .. blk .. " checksum")
+ end
+ local name = prefix .. bstr(d, blk, BS - 80, 30)
+ local st = i32(d, blk, BS - 4)
+ local e: any = {
+ name = name,
+ size = 0,
+ dir = false,
+ mtime = date(d, blk, BS - 92),
+ protect = u32(d, blk, BS - 192),
+ comment = bstr(d, blk, BS - 184, 79),
+ method = "store",
+ }
+ if e.comment == "" then
+ e.comment = nil
+ end
+ if st == ST_USERDIR then
+ e.name = name .. "/"
+ e.dir = true
+ pathOf[blk] = e.name
+ Archive.put(a, e)
+ local ok, err = walk(blk, e.name)
+ if not ok then
+ return false, err
+ end
+ elseif st == ST_FILE then
+ e.size = u32(d, blk, BS - 188)
+ pathOf[blk] = name
+ local hb = blk
+ e.load = function(): (buffer?, Err.Err?)
+ local data, err = readFile(d, hb, ofs)
+ if not data then
+ return nil, Err.new(Err.CORRUPT, tostring(err))
+ end
+ return data, nil
+ end
+ Archive.put(a, e)
+ elseif st == ST_SOFTLINK then
+ local lo = d.base + blk * BS + 24
+ local s = buffer.readstring(d.b, lo, BS - 24 - 200)
+ e.link = latin1(string.match(s, "^[^%z]*") or "")
+ e.type = "symlink"
+ Archive.put(a, e)
+ elseif st == ST_LINKFILE or st == ST_LINKDIR then
+ e.type = "hardlink"
+ e.dir = st == ST_LINKDIR
+ if e.dir then
+ e.name = name .. "/"
+ end
+ Archive.put(a, e)
+ table.insert(links, { entry = e, target = u32(d, blk, BS - 44) })
+ end
+ blk = u32(d, blk, BS - 16)
+ end
+ end
+ return true, nil
+ end
+ local ok, err = walk(root, "")
+ if not ok then
+ return nil, err
+ end
+ -- hard links: the linked path, and a file link reads its target's data
+ for _, l in links do
+ local target = pathOf[l.target]
+ l.entry.hardlink = target
+ if target and not l.entry.dir then
+ local te = a._byName[target]
+ if te then
+ l.entry.size = te.size
+ l.entry.load = te.load
+ end
+ end
+ end
+ return a, nil
+end
+
+return Adf
diff --git a/src/Formats/archive/applesingle/init.luau b/src/Formats/archive/applesingle/init.luau
new file mode 100644
index 0000000..9954039
--- /dev/null
+++ b/src/Formats/archive/applesingle/init.luau
@@ -0,0 +1,190 @@
+--!strict
+-- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740):
+-- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2:
+-- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags).
+-- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the
+-- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name
+-- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds
+-- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with
+-- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS /
+-- MS-DOS / AFP info entries (kept in meta.entries as id + length).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+local MacFile = require("@formats/containers/MacFile")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local AppleSingle = {
+ name = "applesingle",
+ category = "archive",
+ extensions = { "as", "applesingle", "appledouble" },
+ mime = { "application/applefile", "multipart/appledouble" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" },
+ caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } },
+}
+
+export type DecodeOptions = { name: string?, maxBytes: number? } -- name: the file name (the api passes it)
+export type EncodeOptions = {
+ double: boolean?, -- write AppleDouble (no data fork) instead of AppleSingle (default false)
+ name: string?, -- the name of a buffer / string value (default "data")
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local SINGLE, DOUBLE = 0x00051600, 0x00051607
+local Y2K = 946684800 -- 2000-01-01 in unix seconds
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function AppleSingle.sniff(r: Bytes.Reader): number
+ local h = r:peek(8)
+ if #h < 8 then
+ return 0
+ end
+ local magic = string.sub(h, 1, 4)
+ local ver = string.sub(h, 5, 8)
+ if (magic == "\0\5\22\0" or magic == "\0\5\22\7") and (ver == "\0\1\0\0" or ver == "\0\2\0\0") then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return AppleSingle.encode(a, o)
+end
+
+local function i32(v: number): number
+ return if v >= 0x80000000 then v - 0x100000000 else v
+end
+
+function AppleSingle.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local magic, ver = r:u32be(), r:u32be()
+ r:skip(16)
+ local count = r:u16be()
+ if r.err then
+ return nil, r.err
+ end
+ if (magic ~= SINGLE and magic ~= DOUBLE) or (ver ~= 0x10000 and ver ~= 0x20000) then
+ return nil, Err.new(Err.CORRUPT, "not AppleSingle / AppleDouble")
+ end
+ local size = r:size()
+ local info: MacFile.Info = { name = "", data = buffer.create(0), rsrc = buffer.create(0), type = "\0\0\0\0", creator = "\0\0\0\0", flags = 0 }
+ local others = {}
+ local total = 0
+ for _ = 1, count do
+ local id, off, len = r:u32be(), r:u32be(), r:u32be()
+ if r.err then
+ return nil, r.err
+ end
+ if off + len > size then
+ return nil, Err.new(Err.TRUNCATED, "entry " .. id .. " past the end")
+ end
+ total += len
+ if total > (o.maxBytes or 2 ^ 30) then
+ return nil, Err.new(Err.LIMIT, "entries larger than maxBytes")
+ end
+ local e = r:sub(off, len)
+ if id == 1 then
+ info.data = e:bytes(len)
+ elseif id == 2 then
+ info.rsrc = e:bytes(len)
+ elseif id == 3 then
+ info.name = MacFile.name(e:string(len))
+ elseif id == 4 then
+ info.comment = MacFile.name(e:string(len))
+ elseif id == 8 and len >= 8 then
+ local c, m = e:u32be(), e:u32be()
+ info.created = if c == 0x80000000 then nil else i32(c) + Y2K
+ info.modified = if m == 0x80000000 then nil else i32(m) + Y2K
+ elseif id == 7 and len >= 12 and ver == 0x10000 then
+ local c, m = e:u32be(), e:u32be()
+ info.created, info.modified = MacFile.fromMac(c), MacFile.fromMac(m)
+ elseif id == 9 and len >= 10 then
+ info.type, info.creator = e:string(4), e:string(4)
+ info.flags = e:u16be()
+ else
+ table.insert(others, { id = id, length = len })
+ end
+ end
+ if info.name == "" then
+ local n = if type(o.name) == "string" then string.match(o.name, "([^/\\]+)$") else nil
+ info.name = if n then (string.match(n, "^%._(.+)$") or n) else "data"
+ end
+ local a = Archive.new("applesingle", encoder)
+ MacFile.put(a, info, magic == DOUBLE)
+ a.meta.double = magic == DOUBLE
+ a.meta.entries = others
+ a.meta.stream = magic == SINGLE and buffer.len(info.rsrc) == 0
+ a.meta.source = { format = "applesingle", variant = if magic == DOUBLE then "appledouble" else "applesingle", version = ver // 0x10000 }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function AppleSingle.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local files, err = MacFile.collect(value, o.name)
+ if not files then
+ return nil, err
+ end
+ local f = files[1]
+ if not f then
+ return nil, Err.new(Err.ARG, "nothing to encode")
+ end
+ local name = MacFile.roman(f.name)
+ local function date(t: number?): number
+ if type(t) ~= "number" then
+ return 0x80000000
+ end
+ return math.clamp(math.floor(t - Y2K), -0x80000000, 0x7FFFFFFF) % 0x100000000
+ end
+ local dates = Bytes.writer(16)
+ dates:u32be(date(f.created or f.modified))
+ dates:u32be(date(f.modified))
+ dates:u32be(0x80000000)
+ dates:u32be(0x80000000)
+ local finder = Bytes.writer(32)
+ finder:string(f.type)
+ finder:string(f.creator)
+ finder:u16be(f.flags)
+ finder:string(string.rep("\0", 22))
+ local entries: { { any } } = { { 3, buffer.fromstring(name) } }
+ if f.comment then
+ table.insert(entries, { 4, buffer.fromstring(MacFile.roman(f.comment)) })
+ end
+ table.insert(entries, { 8, dates:finish() })
+ table.insert(entries, { 9, finder:finish() })
+ if not o.double then
+ table.insert(entries, { 1, f.data })
+ end
+ if buffer.len(f.rsrc) > 0 or o.double then
+ table.insert(entries, { 2, f.rsrc })
+ end
+ local w = Bytes.writer()
+ w:u32be(if o.double then DOUBLE else SINGLE)
+ w:u32be(0x20000)
+ w:string(string.rep("\0", 16))
+ w:u16be(#entries)
+ local off = 26 + 12 * #entries
+ for _, e in entries do
+ w:u32be(e[1])
+ w:u32be(off)
+ w:u32be(buffer.len(e[2]))
+ off += buffer.len(e[2])
+ end
+ for _, e in entries do
+ w:bytes(e[2])
+ end
+ return w:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty AppleSingle Archive: a:add(name, data); add "name.rsrc" for a resource fork
+function AppleSingle.new(): any
+ local a = Archive.new("applesingle", encoder)
+ a.meta.source = { format = "applesingle" }
+ return a
+end
+
+return AppleSingle
diff --git a/src/Formats/archive/ar/init.luau b/src/Formats/archive/ar/init.luau
new file mode 100644
index 0000000..8f37d8c
--- /dev/null
+++ b/src/Formats/archive/ar/init.luau
@@ -0,0 +1,410 @@
+--!strict
+-- archive/ar: Unix ar archives ("!\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/"
+-- and "/SYM64/" symbol tables) and BSD (inline "#1/" names, the "__.SYMDEF" symbol table), read into the standard
+-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not
+-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their
+-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and
+-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed
+-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and
+-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!"), writing symbol tables (a re-written
+-- library needs ranlib), writing .deb control data (any entries write as a plain ar).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local Lzma = require("@formats/codecs/compress/Lzma")
+local Zstd = require("@formats/codecs/compress/Zstd")
+local Bzip2 = require("@formats/codecs/compress/Bzip2")
+local Archive = require("@formats/containers/Archive")
+local Tar = require("@formats/containers/Tar")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Ar = {
+ name = "ar",
+ category = "archive",
+ extensions = { "a", "ar", "deb", "lib" },
+ mime = { "application/x-archive", "application/vnd.debian.binary-package" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
+ caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
+}
+
+export type DecodeOptions = {
+ maxEntries: number?, -- default 1e6
+ maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26)
+}
+export type EncodeOptions = {
+ variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu"
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local MAGIC = "!\n"
+local HEADER = 60
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Ar.sniff(r: Bytes.Reader): number
+ if r:peek(8) == MAGIC then
+ return if r:peek(13, 68) == "debian-binary" then 1 else 0.9
+ end
+ return if r:peek(8) == "!\n" then 0.5 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
+ return function(): (buffer?, Err.Err?)
+ local out = buffer.create(n)
+ buffer.copy(out, 0, b, at, n)
+ return out, nil
+ end
+end
+
+local function decimal(s: string): number?
+ local d = string.match(s, "^%s*(%d+)%s*$")
+ return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil)
+end
+
+-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names
+local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } }
+ local out = {}
+ local w = if wide then 8 else 4
+ if n < w then
+ return out
+ end
+ local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o))
+ if count * w + w > n then
+ return out
+ end
+ local s = o + w + count * w
+ local e = o + n
+ for i = 0, count - 1 do
+ local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4)))
+ local q = s
+ while q < e and buffer.readu8(b, q) ~= 0 do
+ q += 1
+ end
+ table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off })
+ s = q + 1
+ if s > e then
+ break
+ end
+ end
+ return out
+end
+
+-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings
+local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } }
+ local out = {}
+ if n < 8 then
+ return out
+ end
+ local rb = buffer.readu32(b, o)
+ if rb % 8 ~= 0 or rb + 8 > n then
+ return out
+ end
+ local strs = o + 8 + rb
+ local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs)
+ for i = 0, rb // 8 - 1 do
+ local sx = buffer.readu32(b, o + 4 + i * 8)
+ if sx < strn then
+ local q = strs + sx
+ while q < strs + strn and buffer.readu8(b, q) ~= 0 do
+ q += 1
+ end
+ table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) })
+ end
+ end
+ return out
+end
+
+-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab)
+local function controlFields(s: string): { [string]: string }
+ local out: { [string]: string } = {}
+ local last: string? = nil
+ for line in string.gmatch(s, "([^\n]*)\n?") do
+ local c = string.sub(line, 1, 1)
+ if (c == " " or c == "\t") and last then
+ out[last] ..= "\n" .. string.sub(line, 2)
+ else
+ local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$")
+ if k then
+ out[k], last = v :: string, k
+ end
+ end
+ end
+ return out
+end
+
+-- control.tar[.ext] -> the control file's fields, or nil
+local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }?
+ local ext = string.match(name, "^control%.tar%.?(%w*)$")
+ local raw: buffer?
+ local opts: any = { maxBytes = maxBytes }
+ if ext == "" then
+ raw = buffer.create(n)
+ buffer.copy(raw :: buffer, 0, b, o, n)
+ elseif ext == "gz" then
+ raw = Deflate.gunzip(b, o, n)
+ elseif ext == "xz" then
+ raw = Lzma.xz(b, o, n, opts)
+ elseif ext == "lzma" then
+ raw = Lzma.alone(b, o, n, opts)
+ elseif ext == "zst" then
+ raw = Zstd.decompress(b, o, n, opts)
+ elseif ext == "bz2" then
+ raw = Bzip2.decompress(b, o, n, opts)
+ end
+ if not raw then
+ return nil
+ end
+ local list = Tar.read(raw)
+ for _, e in list or {} do
+ if (e.name == "./control" or e.name == "control") and e.type == "0" then
+ return controlFields(buffer.readstring(raw, e.offset, e.size))
+ end
+ end
+ return nil
+end
+
+local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
+ return Ar.encode(archive, opts)
+end
+
+function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxEntries = o.maxEntries or 1e6
+ local b, base, e = r.buf, r.base, r.limit
+ if r:peek(8) == "!\n" then
+ return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base)
+ end
+ if r:peek(8) ~= MAGIC then
+ return nil, Err.new(Err.CORRUPT, "bad magic", base)
+ end
+ local a = Archive.new("ar", encode)
+ local variant = "gnu"
+ local longNames: string? = nil
+ local symbols: { { name: string, offset: number } }? = nil
+ local offsets: { [number]: string } = {} -- header offset (from the start) -> member name
+ local count = 0
+ local p = base + 8
+ while p < e do
+ local c = buffer.readu8(b, p)
+ if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then
+ break -- trailing padding (bsdtar fills its last 10240-byte block with zeros)
+ end
+ if p + HEADER > e then
+ return nil, Err.new(Err.TRUNCATED, "member header past the end", p)
+ end
+ if buffer.readstring(b, p + 58, 2) ~= "`\n" then
+ return nil, Err.new(Err.CORRUPT, "bad member header", p + 58)
+ end
+ local rawName = buffer.readstring(b, p, 16)
+ local mtime = decimal(buffer.readstring(b, p + 16, 12))
+ local uid = decimal(buffer.readstring(b, p + 28, 6))
+ local gid = decimal(buffer.readstring(b, p + 34, 6))
+ local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$")
+ local size = decimal(buffer.readstring(b, p + 48, 10))
+ if not (mtime and uid and gid and modeS and size) then
+ return nil, Err.new(Err.CORRUPT, "bad member header field", p)
+ end
+ local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number
+ local data = p + HEADER
+ if data + size > e then
+ return nil, Err.new(Err.TRUNCATED, "member data past the end", data)
+ end
+ local nextP = data + size + size % 2
+ local name = string.gsub(rawName, " +$", "")
+ local dataSize = size
+ if string.sub(name, 1, 3) == "#1/" then
+ local n = tonumber(string.sub(name, 4))
+ if not n or n > size then
+ return nil, Err.new(Err.CORRUPT, "bad BSD name length", p)
+ end
+ name = buffer.readstring(b, data, n)
+ local z = string.find(name, "\0", 1, true)
+ if z then
+ name = string.sub(name, 1, z - 1)
+ end
+ data += n
+ dataSize -= n
+ variant = "bsd"
+ elseif name == "//" then
+ longNames = buffer.readstring(b, data, size)
+ p = nextP
+ continue
+ elseif name == "/" or name == "/SYM64/" then
+ symbols = sysvSymbols(b, data, size, name == "/SYM64/")
+ p = nextP
+ continue
+ elseif string.match(name, "^/%d+$") then
+ local off = tonumber(string.sub(name, 2)) :: number
+ if not longNames or off >= #longNames then
+ return nil, Err.new(Err.CORRUPT, "long name outside the name table", p)
+ end
+ local s = string.match(longNames, "^([^\n]*)", off + 1) :: string
+ name = string.gsub(s, "/$", "")
+ elseif string.sub(name, -1) == "/" then
+ name = string.sub(name, 1, -2)
+ end
+ if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then
+ symbols = bsdSymbols(b, data, dataSize)
+ variant = "bsd"
+ p = nextP
+ continue
+ end
+ if name == "" then
+ return nil, Err.new(Err.CORRUPT, "empty member name", p)
+ end
+ offsets[p - base] = name
+ count += 1
+ if count > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
+ end
+ Archive.put(a, {
+ name = name,
+ size = dataSize,
+ dir = false,
+ mtime = mtime,
+ uid = uid,
+ gid = gid,
+ mode = bit32.band(mode, 0xFFF),
+ armode = modeS,
+ method = "store",
+ load = if dataSize > 0 then lazy(b, data, dataSize) else nil,
+ })
+ p = nextP
+ end
+ if symbols then
+ local out = {}
+ for _, s in symbols do
+ table.insert(out, { name = s.name, member = offsets[s.offset] })
+ end
+ a.meta.symbols = out
+ end
+ a.meta.source = { format = "ar", variant = variant }
+ -- Debian packages
+ local list = a._entries
+ if list[1] and list[1].name == "debian-binary" then
+ a.meta.source.variant = "deb"
+ local v = a:read("debian-binary")
+ a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil
+ for _, ent in list do
+ if string.match(ent.name, "^data%.tar") then
+ a.meta.payload = ent.name
+ elseif string.match(ent.name, "^control%.tar") then
+ local cb = a:read(ent.name)
+ if cb then
+ a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26)
+ end
+ end
+ end
+ end
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function pad(s: string, n: number): string
+ return s .. string.rep(" ", n - #s)
+end
+
+local function header(name: string, e: any, size: number): string?
+ local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0)
+ local uid = if type(e.uid) == "number" then e.uid else 0
+ local gid = if type(e.gid) == "number" then e.gid else 0
+ local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode
+ else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4)
+ local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) }
+ local w = { 12, 6, 6, 8, 10 }
+ for i, s in f do
+ if #s > w[i] or string.find(s, "[^%d]") then
+ return nil
+ end
+ end
+ return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n"
+end
+
+function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local items = Archive.entries(archive)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive")
+ end
+ local o: EncodeOptions = opts or {}
+ local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
+ local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu")
+ if variant ~= "gnu" and variant ~= "bsd" then
+ return nil, Err.new(Err.ARG, "variant must be gnu or bsd")
+ end
+ local files = {}
+ for _, it in items do
+ local e: any = it.entry
+ if not e.dir and (e.type == nil or e.type == "0") then
+ local data, err = it.read()
+ if not data then
+ return nil, err
+ end
+ table.insert(files, { e = e, data = data })
+ end
+ end
+ local w = Bytes.writer(1024)
+ w:string(MAGIC)
+ -- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table
+ local table_: { string } = {}
+ local nameOf: { string } = {}
+ local tsize = 0
+ for i, f in files do
+ local name: string = f.e.name
+ if string.find(name, "\n") or name == "" then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar")
+ end
+ if variant == "gnu" then
+ if #name > 15 or string.find(name, "[/ ]") then
+ nameOf[i] = "/" .. tsize
+ table.insert(table_, name .. "/\n")
+ tsize += #name + 2
+ else
+ nameOf[i] = name .. "/"
+ end
+ end
+ end
+ if #table_ > 0 then
+ local t = table.concat(table_)
+ if #t % 2 == 1 then
+ t ..= "\n"
+ end
+ w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t)
+ end
+ for i, f in files do
+ local name: string = f.e.name
+ local size = buffer.len(f.data)
+ local prefix = ""
+ local field = nameOf[i]
+ if variant == "bsd" then
+ if #name > 16 or string.find(name, " ") then
+ field = "#1/" .. #name
+ prefix = name
+ else
+ field = name
+ end
+ end
+ local h = header(field, f.e, size + #prefix)
+ if not h then
+ return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header")
+ end
+ w:string(h)
+ w:string(prefix)
+ w:bytes(f.data)
+ if (size + #prefix) % 2 == 1 then
+ w:string("\n")
+ end
+ end
+ return w:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" })
+function Ar.new(): any
+ local a = Archive.new("ar", encode)
+ a.meta.source = { format = "ar", variant = "gnu" }
+ return a
+end
+
+return Ar
diff --git a/src/Formats/archive/arj/init.luau b/src/Formats/archive/arj/init.luau
new file mode 100644
index 0000000..6b4c7cf
--- /dev/null
+++ b/src/Formats/archive/arj/init.luau
@@ -0,0 +1,212 @@
+--!strict
+-- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS,
+-- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style
+-- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type
+-- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM).
+-- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files,
+-- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those
+-- entries / calls).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Lzh = require("@formats/codecs/compress/Lzh")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Arj = {
+ name = "arj",
+ category = "archive",
+ extensions = { "arj" },
+ mime = { "application/x-arj" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" },
+ caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse an entry larger than this (default 2^30)
+ maxEntries: number?, -- default 65536
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Arj.sniff(r: Bytes.Reader): number
+ local h = r:peek(4)
+ if #h == 4 and string.byte(h, 1) == 0x60 and string.byte(h, 2) == 0xEA then
+ local size = string.byte(h, 3) + string.byte(h, 4) * 256
+ return if size > 0 and size <= 2600 then 0.9 else 0
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Header = { fields: Bytes.Reader, name: string, comment: string, size: number, at: number, next: number }
+
+-- the header block at p: 60 EA, size, the basic header, its CRC-32, extended headers; nil at the end marker
+local function block(r: Bytes.Reader, p: number): (Header?, string?)
+ local h = r:sub(p, 4)
+ local id1, id2, size = h:u8(), h:u8(), h:u16le()
+ if h.err then
+ return nil, "truncated header"
+ end
+ if id1 ~= 0x60 or id2 ~= 0xEA then
+ return nil, "bad header id"
+ end
+ if size == 0 then
+ return nil, nil
+ end
+ if size > 2600 then
+ return nil, "header too large"
+ end
+ if p + 4 + size + 4 > r:size() then
+ return nil, "truncated header"
+ end
+ local crc = r:sub(p + 4 + size, 4):u32le()
+ if Crc32.of(r.buf, r.base + p + 4, size) ~= crc then
+ return nil, "checksum: header CRC-32 mismatch"
+ end
+ local f = r:sub(p + 4, size)
+ local first = f:u8()
+ if first < 30 or first > size then
+ return nil, "bad first header size"
+ end
+ f:seek(first)
+ local name = f:cstring()
+ local comment = f:cstring()
+ -- extended headers
+ local q = p + 4 + size + 4
+ local guard = 0
+ while true do
+ local e = r:sub(q, 2)
+ local n = e:u16le()
+ if e.err then
+ return nil, "truncated extended header"
+ end
+ q += 2
+ if n == 0 then
+ break
+ end
+ q += n + 4
+ guard += 1
+ if guard > 256 or q > r:size() then
+ return nil, "truncated extended header"
+ end
+ end
+ f:seek(0)
+ return { fields = f, name = name, comment = comment, size = size, at = p, next = q }, nil
+end
+
+function Arj.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxBytes = o.maxBytes or 2 ^ 30
+ local maxEntries = o.maxEntries or 65536
+ local main, err = block(r, 0)
+ if not main then
+ return nil, Err.from(err or "no main header", r.base)
+ end
+ local a = Archive.new("arj")
+ local mf = main.fields
+ mf:skip(1)
+ local version, minVersion, host = mf:u8(), mf:u8(), mf:u8()
+ local flags = mf:u8()
+ mf:skip(3)
+ local created = mf:u32le()
+ a.meta.archive = main.name
+ a.meta.comment = if main.comment ~= "" then main.comment else nil
+ a.meta.os = OS[host]
+ a.meta.created = Archive.fromDos(created)
+ a.meta.source = { format = "arj", version = version, minVersion = minVersion, flags = flags }
+ local p = main.next
+ local count = 0
+ while true do
+ local h, herr = block(r, p)
+ if herr then
+ return nil, Err.from(herr, r.base + p)
+ end
+ if not h then
+ break
+ end
+ count += 1
+ if count > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
+ end
+ local f = h.fields
+ f:skip(1)
+ f:skip(2)
+ local hostOs = f:u8()
+ local fl = f:u8()
+ local method = f:u8()
+ local ftype = f:u8()
+ f:skip(1)
+ local stamp = f:u32le()
+ local packed, size, crc = f:u32le(), f:u32le(), f:u32le()
+ f:skip(2)
+ local mode = f:u16le()
+ local dataAt = h.next
+ if dataAt + packed > r:size() then
+ return nil, Err.new(Err.TRUNCATED, "entry " .. h.name .. " data past the end", r.base + dataAt)
+ end
+ local name = string.gsub(h.name, "\\", "/")
+ local isDir = ftype == 3
+ if isDir and string.sub(name, -1) ~= "/" then
+ name ..= "/"
+ end
+ local e: any = {
+ name = name,
+ size = if isDir then 0 else size,
+ compressedSize = packed,
+ method = if method == 0 then "store" else "arj" .. method,
+ mtime = Archive.fromDos(stamp),
+ dir = isDir,
+ mode = mode,
+ os = OS[hostOs],
+ comment = if h.comment ~= "" then h.comment else nil,
+ fileType = ftype,
+ }
+ if ftype ~= 4 then -- 4: a volume label, not a file
+ if not isDir and size > 0 then
+ if size > maxBytes then
+ return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
+ end
+ local buf, at = r.buf, r.base + dataAt
+ e.load = function(): (buffer?, Err.Err?)
+ if bit32.band(fl, 0x01) ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "garbled (encrypted) entries")
+ end
+ if bit32.band(fl, 0x0C) ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "an entry split across volumes")
+ end
+ local out: buffer?, derr: string?
+ if method == 0 then
+ if packed < size then
+ return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
+ end
+ out = buffer.create(size)
+ buffer.copy(out :: buffer, 0, buf, at, size)
+ elseif method >= 1 and method <= 3 then
+ out, derr = Lzh.decode(buf, at, packed, size, "lh6")
+ elseif method == 4 then
+ out, derr = Lzh.decode(buf, at, packed, size, "arj4")
+ else
+ return nil, Err.new(Err.UNSUPPORTED, "method " .. method)
+ end
+ if not out then
+ return nil, Err.from(derr)
+ end
+ if Crc32.of(out) ~= crc then
+ return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch")
+ end
+ return out, nil
+ end
+ end
+ Archive.put(a, e)
+ end
+ p = dataAt + packed
+ end
+ return a, nil
+end
+
+return Arj
diff --git a/src/Formats/archive/binhex/init.luau b/src/Formats/archive/binhex/init.luau
new file mode 100644
index 0000000..8a15128
--- /dev/null
+++ b/src/Formats/archive/binhex/init.luau
@@ -0,0 +1,254 @@
+--!strict
+-- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name,
+-- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified:
+-- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a
+-- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file
+-- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter
+-- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with
+-- archive/macbinary), several files in one .hqx (only the first is read).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc16 = require("@formats/core/Crc16")
+local Archive = require("@formats/containers/Archive")
+local MacFile = require("@formats/containers/MacFile")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Binhex = {
+ name = "binhex",
+ category = "archive",
+ extensions = { "hqx", "hcx" },
+ mime = { "application/mac-binhex40" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" },
+ caps = { decode = true, encode = true, forks = true },
+}
+
+export type DecodeOptions = { maxBytes: number? } -- default 2^30
+export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data")
+
+-- ------------------------------------------------------------------------------------------------ constants
+local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"
+local VALUE: { [number]: number } = {}
+for i = 1, 64 do
+ VALUE[string.byte(ALPHABET, i)] = i - 1
+end
+local BANNER = "(This file must be converted with BinHex"
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Binhex.sniff(r: Bytes.Reader): number
+ local head = r:peek(2048)
+ local at = string.find(head, BANNER, 1, true)
+ if not at then
+ return 0
+ end
+ return if at == 1 then 1 else 0.8
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input)
+local function unhex(text: string, maxBytes: number): (buffer?, string?)
+ local banner = string.find(text, BANNER, 1, true)
+ if not banner then
+ return nil, "no BinHex banner"
+ end
+ local start = string.find(text, ":", banner, true)
+ if not start then
+ return nil, "truncated: no data start"
+ end
+ local raw = Bytes.writer(#text)
+ local acc, nbits = 0, 0
+ local closed = false
+ for i = start + 1, #text do
+ local c = string.byte(text, i)
+ if c == 58 then -- ":"
+ closed = true
+ break
+ end
+ local v = VALUE[c]
+ if v then
+ acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFFFF), 6), v)
+ nbits += 6
+ if nbits >= 8 then
+ nbits -= 8
+ raw:u8(bit32.band(bit32.rshift(acc, nbits), 255))
+ end
+ elseif c ~= 10 and c ~= 13 and c ~= 9 and c ~= 32 then
+ return nil, string.format("bad character 0x%02x", c)
+ end
+ end
+ if not closed then
+ return nil, "truncated: no closing colon"
+ end
+ local src = raw:finish()
+ -- RLE90: 0x90 n repeats the previous byte n - 1 more times; 0x90 0 is a literal 0x90
+ local out = Bytes.writer(buffer.len(src) * 2)
+ local n = buffer.len(src)
+ local prev = 0
+ local i = 0
+ while i < n do
+ local c = buffer.readu8(src, i)
+ if c == 0x90 and i + 1 < n then
+ local count = buffer.readu8(src, i + 1)
+ i += 2
+ if count == 0 then
+ out:u8(0x90)
+ prev = 0x90
+ else
+ if out:tell() + count > maxBytes then
+ return nil, "limit: data larger than maxBytes"
+ end
+ for _ = 2, count do
+ out:u8(prev)
+ end
+ end
+ else
+ out:u8(c)
+ prev = c
+ i += 1
+ end
+ end
+ return out:finish(), nil
+end
+
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return Binhex.encode(a, o)
+end
+
+function Binhex.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxBytes = o.maxBytes or 2 ^ 30
+ local b, err = unhex(buffer.readstring(r.buf, r.base, r.limit - r.base), maxBytes)
+ if not b then
+ return nil, Err.from(err)
+ end
+ local h = Bytes.reader(b)
+ local nameLen = h:u8()
+ local name = h:string(nameLen)
+ h:skip(1) -- version
+ local ftype, creator = h:string(4), h:string(4)
+ local flags = h:u16be()
+ local dlen, rlen = h:u32be(), h:u32be()
+ local hcrc = h:u16be()
+ if h.err then
+ return nil, h.err
+ end
+ if Crc16.ccitt(b, 0, h:tell() - 2) ~= hcrc then
+ return nil, Err.new(Err.CHECKSUM, "header CRC mismatch")
+ end
+ if dlen + rlen > maxBytes then
+ return nil, Err.new(Err.LIMIT, "forks larger than maxBytes")
+ end
+ local forks = {}
+ for k, len in { dlen, rlen } do
+ local at = h:tell()
+ local fork = h:bytes(len)
+ local crc = h:u16be()
+ if h.err then
+ return nil, h.err
+ end
+ if Crc16.ccitt(b, at, len) ~= crc then
+ return nil, Err.new(Err.CHECKSUM, (if k == 1 then "data" else "resource") .. " fork CRC mismatch")
+ end
+ forks[k] = fork
+ end
+ local a = Archive.new("binhex", encoder)
+ MacFile.put(a, { name = MacFile.name(name), data = forks[1], rsrc = forks[2], type = ftype, creator = creator, flags = flags })
+ a.meta.stream = rlen == 0
+ a.meta.source = { format = "binhex" }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local files, err = MacFile.collect(value, o.name)
+ if not files then
+ return nil, err
+ end
+ local f = files[1]
+ if not f then
+ return nil, Err.new(Err.ARG, "nothing to encode")
+ end
+ local name = MacFile.roman(f.name)
+ if #name < 1 or #name > 63 then
+ return nil, Err.new(Err.ARG, "the name must be 1..63 bytes")
+ end
+ local w = Bytes.writer()
+ w:u8(#name)
+ w:string(name)
+ w:u8(0)
+ w:string(f.type)
+ w:string(f.creator)
+ w:u16be(f.flags)
+ w:u32be(buffer.len(f.data))
+ w:u32be(buffer.len(f.rsrc))
+ local hdr = w:finish()
+ local body = Bytes.writer()
+ for _, part in { hdr, f.data, f.rsrc } do
+ body:bytes(part)
+ body:u16be(Crc16.ccitt(part, 0, buffer.len(part)))
+ end
+ local src = body:finish()
+ -- RLE90
+ local rle = Bytes.writer(buffer.len(src) + 16)
+ local n = buffer.len(src)
+ local i = 0
+ while i < n do
+ local c = buffer.readu8(src, i)
+ local run = 1
+ while i + run < n and run < 255 and buffer.readu8(src, i + run) == c do
+ run += 1
+ end
+ if c == 0x90 then
+ rle:u8(0x90)
+ rle:u8(0)
+ run = 1
+ else
+ rle:u8(c)
+ if run >= 3 then
+ rle:u8(0x90)
+ rle:u8(run)
+ else
+ run = 1
+ end
+ end
+ i += run
+ end
+ local bytes = rle:finish()
+ -- 6-bit characters, 64 to a line (the first line includes the colon)
+ local chars = { ":" }
+ local col = 1
+ local acc, nbits = 0, 0
+ local function put(v: number)
+ table.insert(chars, string.sub(ALPHABET, v + 1, v + 1))
+ col += 1
+ if col == 64 then
+ table.insert(chars, "\n")
+ col = 0
+ end
+ end
+ for k = 0, buffer.len(bytes) - 1 do
+ acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFF), 8), buffer.readu8(bytes, k))
+ nbits += 8
+ while nbits >= 6 do
+ nbits -= 6
+ put(bit32.band(bit32.rshift(acc, nbits), 63))
+ end
+ end
+ if nbits > 0 then
+ put(bit32.band(bit32.lshift(acc, 6 - nbits), 63))
+ end
+ table.insert(chars, ":\n")
+ return buffer.fromstring("(This file must be converted with BinHex 4.0)\n" .. table.concat(chars)), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork
+function Binhex.new(): any
+ local a = Archive.new("binhex", encoder)
+ a.meta.source = { format = "binhex" }
+ return a
+end
+
+return Binhex
diff --git a/src/Formats/archive/cab/Sum.luau b/src/Formats/archive/cab/Sum.luau
new file mode 100644
index 0000000..c57c2c3
--- /dev/null
+++ b/src/Formats/archive/cab/Sum.luau
@@ -0,0 +1,42 @@
+--!strict
+--!native
+--!optimize 2
+-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3
+-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format
+-- description ([MS-CAB] 2.4, CFDATA.csum).
+
+local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len
+local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift
+
+local Sum = {}
+
+-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum)
+function Sum.of(buf: buffer, off: number, len: number, seed: number): number
+ if off < 0 or len <= 0 or off + len > blen(buf) then
+ return seed
+ end
+ local s = seed
+ local p = off
+ local stop = off + len - len % 4
+ while p < stop do
+ s = bxor(s, readu32(buf, p))
+ p += 4
+ end
+ local rem = len % 4
+ local tail = 0
+ if rem == 3 then
+ tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2))
+ elseif rem == 2 then
+ tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1))
+ elseif rem == 1 then
+ tail = readu8(buf, p)
+ end
+ return bxor(s, tail)
+end
+
+-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData)
+function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number
+ return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536)
+end
+
+return Sum
diff --git a/src/Formats/archive/cab/init.luau b/src/Formats/archive/cab/init.luau
new file mode 100644
index 0000000..fa9f621
--- /dev/null
+++ b/src/Formats/archive/cab/init.luau
@@ -0,0 +1,427 @@
+--!strict
+-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and
+-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose
+-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum
+-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local
+-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM)
+-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same
+-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the
+-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a
+-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one),
+-- signed / self-extracting stubs before the header.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local Lzx = require("@formats/codecs/compress/Lzx")
+local Quantum = require("@formats/codecs/compress/Quantum")
+local Archive = require("@formats/containers/Archive")
+local Sum = require("@formats/archive/cab/Sum")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Cab = {
+ name = "cab",
+ category = "archive",
+ extensions = { "cab" },
+ mime = { "application/vnd.ms-cab-compressed" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" },
+ caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30)
+ maxEntries: number?, -- default 65535
+ verify: boolean?, -- check the data block checksums (default true)
+}
+export type EncodeOptions = {
+ compression: ("mszip" | "none")?, -- default "mszip"
+ level: number?, -- deflate level 0..9 (default 6)
+ setId: number?, -- the cabinet set id (default 0)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004
+local ATTR_UTF8 = 0x80
+local METHOD = { [0] = "store", "mszip", "quantum", "lzx" }
+local BLOCK = 32768
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Cab.sniff(r: Bytes.Reader): number
+ if r:peek(8) == "MSCF\0\0\0\0" then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Folder = {
+ dataAt: number, -- offset of the first CFDATA (relative to the reader)
+ blocks: number,
+ type: number, -- typeCompress
+ index: number,
+}
+type Block = { at: number, len: number, size: number }
+
+-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next
+-- cabinet (a block with cbUncomp 0)
+local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?)
+ local list: { Block } = {}
+ local p = f.dataAt
+ local total = 0
+ for i = 1, f.blocks do
+ local h = r:sub(p, 8)
+ local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le()
+ if h.err then
+ return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p)
+ end
+ local at = p + 8 + dataReserve
+ if at + cbData > r:size() then
+ return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p)
+ end
+ if cbUncomp == 0 then
+ return list, total, true
+ end
+ if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then
+ return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p)
+ end
+ total += cbUncomp
+ if total > maxBytes then
+ return nil, Err.new(Err.LIMIT, "folder larger than maxBytes")
+ end
+ table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp })
+ p = at + cbData
+ end
+ return list, total, false
+end
+
+-- the decompressed data of a folder's blocks
+local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?)
+ local method = bit32.band(typ, 15)
+ local out = buffer.create(total)
+ if method == 0 then
+ local o = 0
+ for _, b in list do
+ if b.len ~= b.size then
+ return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at)
+ end
+ buffer.copy(out, o, buf, b.at, b.len)
+ o += b.len
+ end
+ return out, nil
+ elseif method == 1 then
+ local spans: { { offset: number, length: number, size: number } } = {}
+ for _, b in list do
+ table.insert(spans, { offset = b.at, length = b.len, size = b.size })
+ end
+ return Deflate.mszip(buf, spans)
+ elseif method == 3 then
+ local bits = bit32.band(bit32.rshift(typ, 8), 31)
+ local n = 0
+ for _, b in list do
+ n += b.len
+ end
+ local src = buffer.create(n)
+ local o = 0
+ for _, b in list do
+ buffer.copy(src, o, buf, b.at, b.len)
+ o += b.len
+ end
+ local res, err = Lzx.decode(src, 0, n, total, bits)
+ if not res then
+ return nil, Err.from(err)
+ end
+ return res, nil
+ elseif method == 2 then
+ local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31))
+ if not res then
+ return nil, Err.from(err)
+ end
+ return res, nil
+ end
+ return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method)
+end
+
+local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
+ return Cab.encode(archive, opts)
+end
+
+function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxBytes = o.maxBytes or 2 ^ 30
+ local maxEntries = o.maxEntries or 65535
+ local verify = o.verify ~= false
+ if not r:match("MSCF") then
+ return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base)
+ end
+ r:skip(4)
+ local cbCabinet = r:u32le()
+ r:skip(4)
+ local coffFiles = r:u32le()
+ r:skip(4)
+ local minor, major = r:u8(), r:u8()
+ local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le()
+ local setId, iCabinet = r:u16le(), r:u16le()
+ local headerReserve, folderReserve, dataReserve = 0, 0, 0
+ if bit32.band(flags, FLAG_RESERVE) ~= 0 then
+ headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8()
+ end
+ local a = Archive.new("cab", encode)
+ local meta: any = a.meta
+ if headerReserve > 0 then
+ meta.reserve = r:bytes(headerReserve)
+ end
+ if bit32.band(flags, FLAG_PREV) ~= 0 then
+ meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256)
+ end
+ if bit32.band(flags, FLAG_NEXT) ~= 0 then
+ meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256)
+ end
+ if r.err then
+ return nil, r.err
+ end
+ if major ~= 1 then
+ return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor)
+ end
+ meta.setId, meta.cabinet = setId, iCabinet
+ meta.source = {
+ format = "cab",
+ version = major .. "." .. minor,
+ size = cbCabinet,
+ flags = flags,
+ reserve = { header = headerReserve, folder = folderReserve, data = dataReserve },
+ }
+ -- folders
+ local folders: { Folder } = {}
+ local methods = {}
+ for i = 1, cFolders do
+ local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le()
+ r:skip(folderReserve)
+ if r.err then
+ return nil, r.err
+ end
+ folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i }
+ local m = METHOD[bit32.band(typ, 15)]
+ methods[i] = {
+ method = m or ("type " .. bit32.band(typ, 15)),
+ window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil,
+ level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil,
+ blocks = nblocks,
+ }
+ end
+ meta.folders = methods
+ if cFiles == 0 or cFolders == 0 then
+ return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders")
+ end
+ if cFiles > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than maxEntries files")
+ end
+ -- the folder cache: the last decompressed folder
+ local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false
+ local function folderData(f: Folder): (buffer?, Err.Err?, boolean?)
+ if cachedIndex == f.index then
+ return cachedData, nil, cachedRuns
+ end
+ local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes)
+ if not list then
+ return nil, total, false
+ end
+ local data, err = inflateFolder(r.buf, list, total, f.type)
+ if not data then
+ return nil, err, false
+ end
+ cachedIndex, cachedData, cachedRuns = f.index, data, runs == true
+ return data, nil, runs
+ end
+ -- files
+ local fr = r:sub(coffFiles)
+ for _ = 1, cFiles do
+ local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le()
+ local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le()
+ local raw = fr:cstring(65536)
+ if fr.err then
+ return nil, fr.err
+ end
+ local name = string.gsub(raw, "\\", "/")
+ local spanned: string? = nil
+ local folder: Folder?
+ if iFolder == 0xFFFD or iFolder == 0xFFFF then
+ spanned = "a file continued from the previous cabinet"
+ folder = folders[1]
+ elseif iFolder == 0xFFFE then
+ spanned = "a file continued in the next cabinet"
+ folder = folders[#folders]
+ else
+ folder = folders[iFolder + 1]
+ if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then
+ spanned = "a folder continued from the previous cabinet"
+ end
+ end
+ if not folder then
+ return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder)
+ end
+ local fo = folder :: Folder
+ if size > maxBytes then
+ return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
+ end
+ local e: any = {
+ name = name,
+ size = size,
+ method = METHOD[bit32.band(fo.type, 15)] or "unknown",
+ mtime = Archive.fromDos(date * 65536 + time),
+ dir = false,
+ attributes = bit32.band(attribs, 0xFF7F),
+ utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0,
+ folder = fo.index,
+ offset = offset,
+ readonly = bit32.band(attribs, 0x01) ~= 0,
+ executable = bit32.band(attribs, 0x40) ~= 0,
+ }
+ if spanned then
+ e.spanned = true
+ end
+ if size > 0 or spanned then
+ e.load = function(): (buffer?, Err.Err?)
+ if spanned then
+ return nil, Err.new(Err.UNSUPPORTED, spanned :: string)
+ end
+ local data, err, runs = folderData(fo)
+ if not data then
+ return nil, err
+ end
+ if offset + size > buffer.len(data) then
+ if runs then
+ return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet")
+ end
+ return nil, Err.new(Err.CORRUPT, "file past the end of its folder")
+ end
+ local out = buffer.create(size)
+ buffer.copy(out, 0, data, offset, size)
+ return out, nil
+ end
+ end
+ Archive.put(a, e)
+ end
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names)
+function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local compression = o.compression or "mszip"
+ if compression ~= "mszip" and compression ~= "none" then
+ return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"")
+ end
+ local level = o.level or 6
+ if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "level must be 0..9")
+ end
+ local files, ferr = Archive.files(archive)
+ if not files then
+ return nil, ferr
+ end
+ if #files == 0 then
+ return nil, Err.new(Err.ARG, "a cabinet needs at least one file")
+ end
+ if #files > 65535 then
+ return nil, Err.new(Err.ARG, "more than 65535 files")
+ end
+ local total = 0
+ for _, f in files do
+ total += buffer.len(f.data)
+ end
+ if total > 0x7FFF8000 then
+ return nil, Err.new(Err.ARG, "more than 2 GB of data")
+ end
+ -- the folder data, in 32 KB blocks
+ local folder = buffer.create(total)
+ local p = 0
+ for _, f in files do
+ buffer.copy(folder, p, f.data, 0, buffer.len(f.data))
+ p += buffer.len(f.data)
+ end
+ local data = Bytes.writer(total // 2 + 64)
+ local nblocks = 0
+ local s = 0
+ while s < total do
+ local n = math.min(BLOCK, total - s)
+ local chunk = buffer.create(n)
+ buffer.copy(chunk, 0, folder, s, n)
+ local payload: buffer
+ if compression == "mszip" then
+ local z, zerr = Deflate.compress(chunk, { level = level })
+ if not z then
+ return nil, zerr
+ end
+ payload = buffer.create(buffer.len(z) + 2)
+ buffer.writeu16(payload, 0, 0x4B43)
+ buffer.copy(payload, 2, z, 0, buffer.len(z))
+ else
+ payload = chunk
+ end
+ local len = buffer.len(payload)
+ data:u32le(Sum.block(payload, 0, len, n))
+ data:u16le(len)
+ data:u16le(n)
+ data:bytes(payload)
+ nblocks += 1
+ s += n
+ end
+ local blob = data:finish()
+ -- names and the file table
+ local table_ = Bytes.writer(64 + #files * 32)
+ local offset = 0
+ for _, f in files do
+ local e: any = f.entry
+ local name = string.gsub(f.name, "/", "\\")
+ local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20
+ if string.find(name, "[\128-\255]") then
+ attribs = bit32.bor(attribs, ATTR_UTF8)
+ end
+ local stamp = Archive.toDos(e.mtime)
+ table_:u32le(buffer.len(f.data))
+ table_:u32le(offset)
+ table_:u16le(0)
+ table_:u16le(stamp // 65536)
+ table_:u16le(stamp % 65536)
+ table_:u16le(attribs)
+ table_:cstring(name)
+ offset += buffer.len(f.data)
+ end
+ local fileTable = table_:finish()
+ local nfolders = 1
+ local coffFiles = 36 + 8 * nfolders
+ local dataAt = coffFiles + buffer.len(fileTable)
+ local size = dataAt + buffer.len(blob)
+ local w = Bytes.writer(size)
+ w:string("MSCF")
+ w:u32le(0)
+ w:u32le(size)
+ w:u32le(0)
+ w:u32le(coffFiles)
+ w:u32le(0)
+ w:u8(3)
+ w:u8(1)
+ w:u16le(nfolders)
+ w:u16le(#files)
+ w:u16le(0)
+ w:u16le(o.setId or 0)
+ w:u16le(0)
+ w:u32le(dataAt)
+ w:u16le(nblocks)
+ w:u16le(if compression == "mszip" then 1 else 0)
+ w:bytes(fileTable)
+ w:bytes(blob)
+ return w:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" })
+function Cab.new(): any
+ local a = Archive.new("cab", encode)
+ a.meta.source = { format = "cab" }
+ return a
+end
+
+return Cab
diff --git a/src/Formats/archive/cpio/init.luau b/src/Formats/archive/cpio/init.luau
new file mode 100644
index 0000000..d4b8d50
--- /dev/null
+++ b/src/Formats/archive/cpio/init.luau
@@ -0,0 +1,172 @@
+--!strict
+-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the
+-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc
+-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters),
+-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor,
+-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1")
+-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+local Cpio = require("@formats/containers/Cpio")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local CpioFormat = {
+ name = "cpio",
+ category = "archive",
+ extensions = { "cpio" },
+ mime = { "application/x-cpio" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
+ caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
+}
+
+export type DecodeOptions = {
+ maxEntries: number?, -- default 1e6
+ verify: boolean?, -- crc archives: check the data sums (default true)
+}
+export type EncodeOptions = {
+ variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc"
+ format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default
+ block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function CpioFormat.sniff(r: Bytes.Reader): number
+ local m = r:peek(6)
+ if m == "070701" or m == "070702" or m == "070707" then
+ return 1
+ end
+ local b2 = r:peek(2)
+ if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then
+ return 0.5
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
+ return function(): (buffer?, Err.Err?)
+ local out = buffer.create(n)
+ buffer.copy(out, 0, b, at, n)
+ return out, nil
+ end
+end
+
+local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
+ return CpioFormat.encode(archive, opts)
+end
+
+function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts)
+ if not list then
+ return nil, info
+ end
+ local a = Archive.new("cpio", encode)
+ for _, e in list do
+ local data = e.type == "0" and e.size > 0
+ Archive.put(a, {
+ name = e.name,
+ size = if data then e.size else 0,
+ dir = e.dir,
+ mtime = e.mtime,
+ mode = bit32.band(e.mode, 0xFFF),
+ uid = e.uid,
+ gid = e.gid,
+ type = e.type,
+ link = e.link,
+ hardlink = e.hardlink,
+ nlink = e.nlink,
+ ino = e.ino,
+ devmajor = e.devmajor,
+ devminor = e.devminor,
+ rdevmajor = e.rdevmajor,
+ rdevminor = e.rdevminor,
+ method = "store",
+ load = if data then lazy(r.buf, e.offset, e.size) else nil,
+ })
+ end
+ a.meta.source = { format = "cpio", variant = info.format }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function num(v: any): number?
+ return if type(v) == "number" then v else nil
+end
+
+function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local items = Archive.entries(archive)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive")
+ end
+ local index: { [string]: number } = {}
+ for i, it in items do
+ index[it.entry.name] = index[it.entry.name] or i
+ end
+ -- tar hard links ("1"): the same inode as their target, which counts the links
+ local links: { [number]: number } = {}
+ local target: { [number]: number } = {}
+ for i, it in items do
+ local e: any = it.entry
+ if e.type == "1" and type(e.link) == "string" and index[e.link] then
+ local t = index[e.link]
+ target[i] = t
+ links[t] = (links[t] or 1) + 1
+ end
+ end
+ local list: { Cpio.WriteEntry } = {}
+ for i, it in items do
+ local e: any = it.entry
+ local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0"
+ local src = target[i]
+ local ino, nlink = num(e.ino), num(e.nlink)
+ if src then
+ typ, ino, nlink = "0", src, links[src]
+ elseif links[i] then
+ ino, nlink = i, links[i]
+ end
+ local data: buffer? = nil
+ if typ == "0" then
+ local b, err = (items[src or i] :: any).read()
+ if not b then
+ return nil, err
+ end
+ data = b
+ end
+ local mode = num(e.mode)
+ table.insert(list, {
+ name = e.name,
+ data = data,
+ type = typ,
+ link = if type(e.link) == "string" and typ == "2" then e.link else nil,
+ mode = if mode then bit32.band(mode, 0xFFF) else nil,
+ uid = num(e.uid),
+ gid = num(e.gid),
+ nlink = nlink,
+ mtime = num(e.mtime),
+ ino = ino,
+ devmajor = num(e.devmajor),
+ devminor = num(e.devminor),
+ rdevmajor = num(e.rdevmajor),
+ rdevminor = num(e.rdevminor),
+ })
+ end
+ -- opts.format may also be the api's format name ("cpio"): the variant default then
+ local o: any = opts or {}
+ local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
+ local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc"
+ local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own)
+ return Cpio.write(list, { format = variant, block = o.block })
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write()
+function CpioFormat.new(): any
+ local a = Archive.new("cpio", encode)
+ a.meta.source = { format = "cpio" }
+ return a
+end
+
+return CpioFormat
diff --git a/src/Formats/archive/d64/init.luau b/src/Formats/archive/d64/init.luau
new file mode 100644
index 0000000..7322c15
--- /dev/null
+++ b/src/Formats/archive/d64/init.luau
@@ -0,0 +1,424 @@
+--!strict
+-- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info
+-- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and
+-- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are
+-- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are
+-- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII
+-- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the
+-- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any
+-- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS
+-- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers'
+-- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local D64 = {
+ name = "d64",
+ category = "archive",
+ extensions = { "d64", "d71", "d81" },
+ mime = { "application/x-d64" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive" },
+ caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } },
+}
+
+export type DecodeOptions = { maxEntries: number? } -- default 4096
+export type EncodeOptions = {
+ variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64"
+ disk: string?, -- disk name (default "formats-luau" / the name read)
+ id: string?, -- two-character disk id (default "fl")
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" }
+local TYPE_CODE: { [string]: number } = { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 }
+
+type Geometry = { kind: string, tracks: number, offsets: { number }, spt: { number }, dirTrack: number, total: number }
+
+local function geometry(kind: string, tracks: number): Geometry
+ local offsets, spt = {}, {}
+ local o = 0
+ for t = 1, tracks do
+ local n
+ if kind == "d81" then
+ n = 40
+ else
+ local s = if kind == "d71" and t > 35 then t - 35 else t
+ n = if s <= 17 then 21 elseif s <= 24 then 19 elseif s <= 30 then 18 else 17
+ end
+ offsets[t], spt[t] = o, n
+ o += n * 256
+ end
+ return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = if kind == "d81" then 40 else 18, total = o }
+end
+
+-- image sizes -> geometry (sizes with the error-info block appended too)
+local function detect(len: number): Geometry?
+ for _, g in { { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } } :: { { any } } do
+ local geo = geometry(g[1] :: string, g[2] :: number)
+ local sectors = geo.total // 256
+ if len == geo.total or (g[1] ~= "d81" and len == geo.total + sectors) then
+ return geo
+ end
+ end
+ return nil
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function D64.sniff(r: Bytes.Reader): number
+ local geo = detect(r:size())
+ if not geo then
+ return 0
+ end
+ -- the BAM / header sector: dir track link and DOS version byte
+ local h = r:sub(geo.offsets[geo.dirTrack], 256)
+ local t, s, v = h:u8(), h:u8(), h:u8()
+ if geo.kind == "d81" then
+ return if t == 40 and s == 3 and v == 0x44 then 0.9 else 0.3
+ end
+ return if t == 18 and s == 1 and (v == 0x41 or v == 0) then 0.9 else 0.3
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function petscii(raw: string): string
+ local out = table.create(#raw)
+ for i = 1, #raw do
+ local c = string.byte(raw, i)
+ if c >= 0x41 and c <= 0x5A then
+ out[i] = string.char(c + 32)
+ elseif c >= 0xC1 and c <= 0xDA then
+ out[i] = string.char(c - 0x80)
+ elseif c >= 0x61 and c <= 0x7A then
+ out[i] = string.char(c - 32)
+ elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then
+ out[i] = string.char(c)
+ else
+ out[i] = utf8.char(0xE000 + c)
+ end
+ end
+ return table.concat(out)
+end
+
+local function toPetscii(name: string): string
+ local out = {}
+ if not utf8.len(name) then
+ return string.sub(name, 1, 16)
+ end
+ for _, c in utf8.codes(name) do
+ local b
+ if c >= 0x61 and c <= 0x7A then
+ b = c - 32
+ elseif c >= 0x41 and c <= 0x5A then
+ b = c + 0x80
+ elseif c >= 0xE000 and c <= 0xE0FF then
+ b = c - 0xE000
+ elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then
+ b = c
+ else
+ b = 0x3F
+ end
+ table.insert(out, string.char(b))
+ end
+ return string.sub(table.concat(out), 1, 16)
+end
+
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return D64.encode(a, o)
+end
+
+-- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops
+local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?)
+ local w = Bytes.writer()
+ local seen: { [number]: boolean } = {}
+ while t ~= 0 do
+ if t < 1 or t > geo.tracks or s >= geo.spt[t] then
+ return nil, string.format("chain leaves the disk at %d/%d", t, s)
+ end
+ local key = t * 256 + s
+ if seen[key] then
+ return nil, string.format("chain loops at %d/%d", t, s)
+ end
+ seen[key] = true
+ local o = base + geo.offsets[t] + s * 256
+ local nt, ns = buffer.readu8(b, o), buffer.readu8(b, o + 1)
+ if nt == 0 then
+ local last = math.max(ns, 1)
+ if last >= 2 then
+ w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, last - 1)))
+ end
+ else
+ w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, 254)))
+ end
+ t, s = nt, ns
+ end
+ return w:finish(), nil
+end
+
+function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local geo = detect(r:size())
+ if not geo then
+ return nil, Err.new(Err.CORRUPT, "not a D64 / D71 / D81 image size (" .. r:size() .. " bytes)")
+ end
+ local b, base = r.buf, r.base
+ local hdr = base + geo.offsets[geo.dirTrack]
+ local nameAt, idAt = if geo.kind == "d81" then 0x04 else 0x90, if geo.kind == "d81" then 0x16 else 0xA2
+ local diskRaw = buffer.readstring(b, hdr + nameAt, 16)
+ local a = Archive.new("d64", encoder)
+ a.meta.disk = petscii((string.gsub(diskRaw, "\160+$", "")))
+ a.meta.id = petscii(buffer.readstring(b, hdr + idAt, 2))
+ a.meta.variant = geo.kind
+ a.meta.tracks = geo.tracks
+ a.meta.errorInfo = r:size() ~= geo.total
+ a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks }
+ -- the directory chain
+ local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1)
+ local seen: { [number]: boolean } = {}
+ local count = 0
+ local maxEntries = o.maxEntries or 4096
+ while t ~= 0 do
+ if t < 1 or t > geo.tracks or s >= geo.spt[t] or seen[t * 256 + s] then
+ return nil, Err.new(Err.CORRUPT, string.format("bad directory sector %d/%d", t, s))
+ end
+ seen[t * 256 + s] = true
+ local so = base + geo.offsets[t] + s * 256
+ for k = 0, 7 do
+ local e = so + k * 32
+ local ft = buffer.readu8(b, e + 2)
+ local kind = bit32.band(ft, 15)
+ if ft ~= 0 and kind ~= 0 then
+ count += 1
+ if count > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than maxEntries directory entries")
+ end
+ local raw = buffer.readstring(b, e + 5, 16)
+ local name = petscii((string.gsub(raw, "\160+$", "")))
+ local base_name, n = name, 2
+ while a._byName[name] do
+ name = base_name .. ";" .. n
+ n += 1
+ end
+ local ty = TYPES[kind] or "?"
+ local entry: any = {
+ name = name,
+ rawName = raw,
+ type = ty,
+ closed = bit32.band(ft, 0x80) ~= 0,
+ locked = bit32.band(ft, 0x40) ~= 0,
+ blocks = buffer.readu16(b, e + 30),
+ dir = false,
+ method = "store",
+ }
+ if ty == "cbm" or ty == "dir" then
+ entry.size = 0
+ else
+ local data, err = chain(b, base, geo, buffer.readu8(b, e + 3), buffer.readu8(b, e + 4))
+ if not data then
+ return nil, Err.new(Err.CORRUPT, name .. ": " .. tostring(err))
+ end
+ entry.size = buffer.len(data)
+ entry.data = data
+ if ty == "rel" then
+ entry.recordLength = buffer.readu8(b, e + 23)
+ end
+ end
+ Archive.put(a, entry)
+ end
+ end
+ t, s = buffer.readu8(b, so), buffer.readu8(b, so + 1)
+ end
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- BAM layout per variant: where each track's free count + bitmap lives
+local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number)
+ -- returns (offset of the free count, offset of the bitmap, bitmap bytes)
+ local dir = geo.offsets[geo.dirTrack]
+ if geo.kind == "d81" then
+ local side = if t <= 40 then 1 else 2
+ local tt = if t <= 40 then t else t - 40
+ local o = dir + side * 256 + 0x10 + (tt - 1) * 6
+ return o, o + 1, 5
+ end
+ if t <= 35 then
+ local o = dir + 4 + (t - 1) * 4
+ return o, o + 1, 3
+ end
+ -- d71 side 2: counts at 18/0 0xDD.., bitmaps on track 53 sector 0
+ return dir + 0xDD + (t - 36), geo.offsets[53] + (t - 36) * 3, 3
+end
+
+local function setFree(geo: Geometry, img: buffer, t: number, s: number, free: boolean)
+ local co, bo = bamEntry(geo, img, t)
+ local byte = bo + bit32.rshift(s, 3)
+ local mask = bit32.lshift(1, bit32.band(s, 7))
+ local cur = buffer.readu8(img, byte)
+ local isFree = bit32.band(cur, mask) ~= 0
+ if free and not isFree then
+ buffer.writeu8(img, byte, bit32.bor(cur, mask))
+ buffer.writeu8(img, co, buffer.readu8(img, co) + 1)
+ elseif not free and isFree then
+ buffer.writeu8(img, byte, bit32.band(cur, bit32.bnot(mask)))
+ buffer.writeu8(img, co, buffer.readu8(img, co) - 1)
+ end
+end
+
+function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local variant = o.variant or (if type(value) == "table" and type(value.meta) == "table" and value.meta.variant then value.meta.variant else "d64")
+ if variant ~= "d64" and variant ~= "d71" and variant ~= "d81" then
+ return nil, Err.new(Err.ARG, "variant must be d64, d71 or d81")
+ end
+ local files, err = Archive.files(value, "data")
+ if not files then
+ return nil, err
+ end
+ local geo = geometry(variant, if variant == "d64" then 35 elseif variant == "d71" then 70 else 80)
+ local img = buffer.create(geo.total)
+ local dirT = geo.dirTrack
+ local dir = geo.offsets[dirT]
+ local diskName = toPetscii(o.disk or (if type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" then value.meta.disk else "formats-luau"))
+ local id = toPetscii(o.id or "fl")
+ local function pad16(s: string): string
+ return s .. string.rep("\160", 16 - #s)
+ end
+ -- header / BAM
+ local firstDir
+ if variant == "d81" then
+ buffer.writestring(img, dir, "\40\3\68\0")
+ buffer.writestring(img, dir + 4, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "3D" .. "\160\160")
+ for side = 1, 2 do
+ local bo = dir + side * 256
+ buffer.writestring(img, bo, if side == 1 then "\40\2\68\187" else "\0\255\68\187")
+ buffer.writestring(img, bo + 4, string.sub(id .. " ", 1, 2) .. "\192\0")
+ end
+ firstDir = 3
+ else
+ buffer.writestring(img, dir, "\18\1\65" .. (if variant == "d71" then "\128" else "\0"))
+ buffer.writestring(img, dir + 0x90, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "2A" .. "\160\160\160\160")
+ firstDir = 1
+ end
+ for t = 1, geo.tracks do
+ for s = 0, geo.spt[t] - 1 do
+ setFree(geo, img, t, s, true)
+ end
+ end
+ -- system sectors: the header / BAM sectors and the first directory sector
+ local used = { [dirT * 256 + 0] = true, [dirT * 256 + firstDir] = true }
+ if variant == "d81" then
+ used[dirT * 256 + 1], used[dirT * 256 + 2] = true, true
+ elseif variant == "d71" then
+ for s = 0, geo.spt[53] - 1 do
+ used[53 * 256 + s] = true
+ end
+ end
+ for k in used do
+ setFree(geo, img, k // 256, k % 256, false)
+ end
+ local maxDirSectors = geo.spt[dirT] - firstDir
+ if #files > maxDirSectors * 8 then
+ return nil, Err.new(Err.LIMIT, "too many files for one directory track")
+ end
+ -- allocation: tracks nearest the directory track first, interleave 10
+ local order = {}
+ for d = 1, geo.tracks do
+ for _, t in { dirT - d, dirT + d } do
+ if t >= 1 and t <= geo.tracks and t ~= dirT and not (variant == "d71" and t == 53) then
+ table.insert(order, t)
+ end
+ end
+ end
+ local ti, lastS = 1, -10
+ local function alloc(): (number?, number?)
+ while ti <= #order do
+ local t = order[ti]
+ local n = geo.spt[t]
+ for k = 0, n - 1 do
+ local s = (lastS + 10 + k) % n
+ if not used[t * 256 + s] then
+ used[t * 256 + s] = true
+ setFree(geo, img, t, s, false)
+ lastS = s
+ return t, s
+ end
+ end
+ ti += 1
+ lastS = -10
+ end
+ return nil, nil
+ end
+ local dirSector, slot = firstDir, 0
+ local dirSectors = { firstDir }
+ for _, f in files do
+ local data = f.data
+ local n = buffer.len(data)
+ local blocks = math.max(1, math.ceil(n / 254))
+ local first_t, first_s = 0, 0
+ local prev = -1
+ for k = 0, blocks - 1 do
+ local t, s = alloc()
+ if not t or not s then
+ return nil, Err.new(Err.LIMIT, "disk full")
+ end
+ local so = geo.offsets[t] + s * 256
+ if prev < 0 then
+ first_t, first_s = t, s
+ else
+ buffer.writeu8(img, prev, t)
+ buffer.writeu8(img, prev + 1, s)
+ end
+ local len = math.min(254, n - k * 254)
+ if len > 0 then
+ buffer.copy(img, so + 2, data, k * 254, len)
+ end
+ buffer.writeu8(img, so + 1, if k == blocks - 1 then len + 1 else 0)
+ prev = so
+ end
+ if slot == 8 then
+ -- next directory sector on the directory track (interleave 3)
+ local nextS = nil
+ for k = 0, geo.spt[dirT] - 1 do
+ local s = (dirSector + 3 + k) % geo.spt[dirT]
+ if not used[dirT * 256 + s] then
+ nextS = s
+ break
+ end
+ end
+ if not nextS then
+ return nil, Err.new(Err.LIMIT, "directory full")
+ end
+ used[dirT * 256 + nextS] = true
+ setFree(geo, img, dirT, nextS, false)
+ buffer.writeu8(img, dir + dirSector * 256, dirT)
+ buffer.writeu8(img, dir + dirSector * 256 + 1, nextS)
+ dirSector, slot = nextS, 0
+ table.insert(dirSectors, nextS)
+ end
+ local e = dir + dirSector * 256 + slot * 32
+ local ty: number = if type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] then TYPE_CODE[f.entry.type] :: number else 2
+ buffer.writeu8(img, e + 2, 0x80 + ty)
+ buffer.writeu8(img, e + 3, first_t)
+ buffer.writeu8(img, e + 4, first_s)
+ local raw = if type(f.entry.rawName) == "string" and #f.entry.rawName == 16 then (string.gsub(f.entry.rawName, "\160+$", "")) else toPetscii(f.name)
+ buffer.writestring(img, e + 5, pad16(raw))
+ buffer.writeu16(img, e + 30, blocks)
+ slot += 1
+ end
+ buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF)
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" })
+function D64.new(variant: string?): any
+ local a = Archive.new("d64", encoder)
+ a.meta.variant = variant or "d64"
+ a.meta.source = { format = "d64" }
+ return a
+end
+
+return D64
diff --git a/src/Formats/archive/fat/init.luau b/src/Formats/archive/fat/init.luau
new file mode 100644
index 0000000..4815642
--- /dev/null
+++ b/src/Formats/archive/fat/init.luau
@@ -0,0 +1,124 @@
+--!strict
+-- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the
+-- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3
+-- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the
+-- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy
+-- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a
+-- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+local Fat = require("@formats/containers/Fat")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local FatFormat = {
+ name = "fat",
+ category = "archive",
+ extensions = { "img", "ima", "vfd", "flp", "fat" },
+ mime = { "application/x-fat-image" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" },
+ caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } },
+}
+
+export type DecodeOptions = {
+ partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself)
+ maxEntries: number?, -- default 65536
+}
+export type EncodeOptions = {
+ size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440)
+ label: string?, -- volume label
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function FatFormat.sniff(r: Bytes.Reader): number
+ if r:remaining() < 512 then
+ return 0
+ end
+ local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos)
+ if not v then
+ return 0
+ end
+ return if v.partition then 0.6 else 0.8
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return FatFormat.encode(a, o)
+end
+
+function FatFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition })
+ if not v then
+ return nil, Err.from(err)
+ end
+ local list, lerr = Fat.list(v, o.maxEntries)
+ if not list then
+ return nil, Err.from(lerr)
+ end
+ local a = Archive.new("fat", encoder)
+ for _, e in list do
+ local entry = e
+ Archive.put(a, {
+ name = e.name,
+ size = e.size,
+ dir = e.dir,
+ mtime = e.mtime,
+ attr = e.attr,
+ shortName = e.shortName,
+ method = "store",
+ load = if e.dir or e.size == 0 then nil else function(): (buffer?, Err.Err?)
+ local b, rerr = Fat.read(v :: Fat.Volume, entry)
+ if not b then
+ return nil, Err.from(rerr)
+ end
+ return b, nil
+ end,
+ })
+ end
+ a.meta.fat = v.bits
+ a.meta.label = v.label
+ a.meta.oem = v.oem
+ a.meta.partition = v.partition
+ a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local items = Archive.entries(value)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive")
+ end
+ local files: { Fat.WriteFile } = {}
+ for _, it in items do
+ local e: any = it.entry
+ local data: buffer? = nil
+ if not e.dir then
+ local b, err = it.read()
+ if not b then
+ return nil, err
+ end
+ data = b
+ end
+ table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime })
+ end
+ local img, err = Fat.write(files, { size = o.size, label = o.label })
+ if not img then
+ return nil, if string.match(tostring(err), "^limit") then Err.from(err) else Err.new(Err.ARG, tostring(err))
+ end
+ return img, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" })
+function FatFormat.new(): any
+ local a = Archive.new("fat", encoder)
+ a.meta.source = { format = "fat" }
+ return a
+end
+
+return FatFormat
diff --git a/src/Formats/archive/iso/init.luau b/src/Formats/archive/iso/init.luau
new file mode 100644
index 0000000..0354aa4
--- /dev/null
+++ b/src/Formats/archive/iso/init.luau
@@ -0,0 +1,75 @@
+--!strict
+-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660:
+-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories;
+-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files.
+-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts
+-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El
+-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one.
+-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored
+-- bytes), multi-session images (the first session).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Archive = require("@formats/containers/Archive")
+local Iso9660 = require("@formats/containers/Iso9660")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Iso = {
+ name = "iso",
+ category = "archive",
+ extensions = { "iso" },
+ mime = { "application/x-iso9660-image" },
+ deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
+ caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
+}
+
+export type DecodeOptions = {
+ prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
+ maxEntries: number?, -- default 1e6
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Iso.sniff(r: Bytes.Reader): number
+ return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts)
+ if not list then
+ return nil, info
+ end
+ local a = Archive.new("iso")
+ local b, limit = r.buf, r.limit
+ for _, e in list do
+ local data = e.type == "0" and e.size > 0
+ Archive.put(a, {
+ name = e.name,
+ size = e.size,
+ dir = e.dir,
+ mtime = e.mtime,
+ type = e.type,
+ mode = e.mode,
+ uid = e.uid,
+ gid = e.gid,
+ nlink = e.nlink,
+ link = e.link,
+ rdev = e.rdev,
+ hidden = e.hidden,
+ method = if e.zisofs then "zisofs" else "store",
+ load = if data
+ then function(): (buffer?, Err.Err?)
+ return Iso9660.extract(b, e, limit)
+ end
+ else nil,
+ })
+ end
+ a.meta.boot = info.boot
+ info.boot = nil
+ a.meta.iso = info
+ a.meta.source = { format = "iso", tree = info.tree }
+ return a, nil
+end
+
+return Iso
diff --git a/src/Formats/archive/lha/init.luau b/src/Formats/archive/lha/init.luau
new file mode 100644
index 0000000..fcd33b9
--- /dev/null
+++ b/src/Formats/archive/lha/init.luau
@@ -0,0 +1,434 @@
+--!strict
+-- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their
+-- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS
+-- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7,
+-- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read.
+-- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower
+-- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header
+-- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu
+-- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc),
+-- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or
+-- at the first header found in the first 64 KB).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc16 = require("@formats/core/Crc16")
+local Lzh = require("@formats/codecs/compress/Lzh")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Lha = {
+ name = "lha",
+ category = "archive",
+ extensions = { "lzh", "lha", "lzs" },
+ mime = { "application/x-lzh-compressed" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" },
+ caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse an entry larger than this (default 2^30)
+ maxEntries: number?, -- default 65536
+}
+export type EncodeOptions = {}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local METHODS: { [string]: boolean } = {
+ ["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true,
+ ["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true,
+ ["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true,
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+local function isHeader(s: string): boolean
+ if #s < 22 then
+ return false
+ end
+ local m = string.sub(s, 3, 7)
+ local level = string.byte(s, 21)
+ return METHODS[m] == true and level <= 3
+end
+
+function Lha.sniff(r: Bytes.Reader): number
+ if isHeader(r:peek(22)) then
+ return 0.95
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them)
+local function path(s: string): string
+ s = string.gsub(s, "[\\\255]", "/")
+ local parts = {}
+ for part in string.gmatch(s, "[^/]+") do
+ if part ~= "." and part ~= ".." then
+ table.insert(parts, part)
+ end
+ end
+ return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "")
+end
+
+type Header = {
+ method: string,
+ packed: number,
+ size: number,
+ mtime: number?,
+ level: number,
+ name: string,
+ dir: string?,
+ crc: number?,
+ mode: number?,
+ uid: number?,
+ gid: number?,
+ uname: string?,
+ gname: string?,
+ attr: number?,
+ comment: string?,
+ os: string?,
+ dataAt: number,
+}
+
+-- the extended headers from offset p (size field width w), until a zero size; returns the end offset
+local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?)
+ local size = first
+ local guard = 0
+ while size ~= 0 do
+ guard += 1
+ if guard > 4096 or size < w + 1 or p + size > limit then
+ return nil, "bad extended header"
+ end
+ local e = r:sub(p, size)
+ local kind = e:u8()
+ local body = size - 1 - w
+ if kind == 0x01 then
+ h.name = e:string(body)
+ elseif kind == 0x02 then
+ h.dir = e:string(body)
+ elseif kind == 0x3F or kind == 0x71 then
+ h.comment = e:string(body)
+ elseif kind == 0x40 and body >= 2 then
+ h.attr = e:u16le()
+ elseif kind == 0x50 and body >= 2 then
+ h.mode = e:u16le()
+ elseif kind == 0x51 and body >= 4 then
+ h.gid, h.uid = e:u16le(), e:u16le()
+ elseif kind == 0x52 then
+ h.gname = e:string(body)
+ elseif kind == 0x53 then
+ h.uname = e:string(body)
+ elseif kind == 0x54 and body >= 4 then
+ h.mtime = e:u32le()
+ elseif kind == 0x42 and body >= 16 then
+ h.packed, h.size = e:u64le(), e:u64le()
+ end
+ e:seek(size - w)
+ local nextSize = if w == 2 then e:u16le() else e:u32le()
+ if e.err then
+ return nil, "truncated extended header"
+ end
+ p += size
+ size = nextSize
+ end
+ return p, nil
+end
+
+local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386",
+ [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt",
+ [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" }
+
+-- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker
+local function header(r: Bytes.Reader, p: number): (Header?, string?)
+ local limit = r:size()
+ if p >= limit or r:sub(p, 1):u8() == 0 then
+ return nil, nil
+ end
+ if p + 22 > limit then
+ return nil, "truncated header"
+ end
+ local s = r:sub(p, 26)
+ local b0 = s:u8()
+ s:u8()
+ local method = s:string(5)
+ local packed, size, stamp = s:u32le(), s:u32le(), s:u32le()
+ s:u8()
+ local level = s:u8()
+ if not METHODS[method] then
+ return nil, "bad method " .. method
+ end
+ local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 }
+ if level == 0 or level == 1 then
+ local hsize = b0 + 2
+ if p + hsize > limit or hsize < 24 then
+ return nil, "truncated header"
+ end
+ local hr = r:sub(p + 21, hsize - 21)
+ local nlen = hr:u8()
+ h.name = hr:string(nlen)
+ h.crc = hr:u16le()
+ h.mtime = Archive.fromDos(stamp)
+ if level == 0 then
+ -- an optional Unix extension: 'U', mtime, mode, uid, gid
+ if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then
+ h.os = if hr:u8() == 0x55 then "unix" else "os68k"
+ h.mtime = hr:u32le()
+ h.mode = hr:u16le()
+ h.uid, h.gid = hr:u16le(), hr:u16le()
+ end
+ h.dataAt = p + hsize
+ else
+ h.os = OS[hr:u8()]
+ local first = r:sub(p + hsize - 2, 2):u16le()
+ local e, err = extended(r, p + hsize, 2, first, h, limit)
+ if not e then
+ return nil, err
+ end
+ h.packed = packed - (e - (p + hsize))
+ h.dataAt = e
+ end
+ if hr.err then
+ return nil, "truncated header"
+ end
+ elseif level == 2 then
+ local total = r:sub(p, 2):u16le()
+ local hr = r:sub(p + 21, 5)
+ h.crc = hr:u16le()
+ local osByte = hr:u8()
+ h.os = OS[osByte]
+ if osByte == 0x4B then
+ total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates)
+ end
+ local first = hr:u16le()
+ h.mtime = stamp
+ local e, err = extended(r, p + 26, 2, first, h, limit)
+ if not e or hr.err then
+ return nil, err or "truncated header"
+ end
+ h.dataAt = p + total
+ if total < 26 or h.dataAt > limit then
+ return nil, "bad level 2 header size"
+ end
+ elseif level == 3 then
+ local hr = r:sub(p + 21, 11)
+ h.crc = hr:u16le()
+ h.os = OS[hr:u8()]
+ local total = hr:u32le()
+ local first = hr:u32le()
+ h.mtime = stamp
+ local e, err = extended(r, p + 32, 4, first, h, limit)
+ if not e or hr.err then
+ return nil, err or "truncated header"
+ end
+ h.dataAt = p + total
+ if total < 32 or h.dataAt > limit then
+ return nil, "bad level 3 header size"
+ end
+ else
+ return nil, "unsupported: header level " .. level
+ end
+ return h, nil
+end
+
+local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" }
+
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return Lha.encode(a, o)
+end
+
+function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxBytes = o.maxBytes or 2 ^ 30
+ local maxEntries = o.maxEntries or 65536
+ local p = 0
+ -- a self-extracting stub: find the first header
+ if not isHeader(r:peek(22)) then
+ local head = r:peek(65536)
+ local at = nil
+ for k = 1, #head - 22 do
+ if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then
+ at = k - 1
+ break
+ end
+ end
+ if not at then
+ return nil, Err.new(Err.CORRUPT, "no LHA header")
+ end
+ p = at
+ end
+ local a = Archive.new("lha", encoder)
+ local count = 0
+ local levels = {}
+ while true do
+ local h, err = header(r, p)
+ if err then
+ return nil, Err.from(err, r.base + p)
+ end
+ if not h then
+ break
+ end
+ count += 1
+ if count > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
+ end
+ levels[h.level] = true
+ if h.packed < 0 or h.dataAt + h.packed > r:size() then
+ return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt)
+ end
+ -- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do
+ local os = h.os
+ if os == nil or os == "msdos" or os == "atari" or os == "os2" then
+ if not string.find(h.name .. (h.dir or ""), "%l") then
+ h.name = string.lower(h.name)
+ h.dir = if h.dir then string.lower(h.dir) else nil
+ end
+ end
+ -- the full path (a Unix symlink "name|target" may be split across the directory and file name headers)
+ local name = path(h.name)
+ if h.dir and h.dir ~= "" then
+ local d = path(h.dir)
+ if string.sub(d, -1) ~= "/" then
+ d ..= "/"
+ end
+ name = d .. name
+ end
+ local link: string? = nil
+ local bar = string.find(name, "|", 1, true)
+ if bar then
+ name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1)
+ end
+ local isDir = h.method == "lhd"
+ if isDir and link == nil and string.sub(name, -1) ~= "/" then
+ name ..= "/"
+ end
+ local e: any = {
+ name = name,
+ size = if isDir or link then 0 else h.size,
+ compressedSize = h.packed,
+ method = h.method,
+ mtime = h.mtime,
+ dir = isDir and link == nil,
+ mode = h.mode,
+ uid = h.uid,
+ gid = h.gid,
+ uname = h.uname,
+ gname = h.gname,
+ attr = h.attr,
+ comment = h.comment,
+ os = h.os,
+ level = h.level,
+ crc = h.crc,
+ }
+ if link then
+ e.link = link
+ e.type = "symlink"
+ elseif not isDir and h.size > 0 then
+ if h.size > maxBytes then
+ return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
+ end
+ local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc
+ local buf, base = r.buf, r.base
+ e.load = function(): (buffer?, Err.Err?)
+ local out: buffer?, derr: string?
+ if method == "lh0" or method == "lz4" then
+ if packed < size then
+ return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
+ end
+ out = buffer.create(size)
+ buffer.copy(out :: buffer, 0, buf, base + at, size)
+ elseif LZH_METHOD[method] then
+ out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method])
+ else
+ return nil, Err.new(Err.UNSUPPORTED, "method " .. method)
+ end
+ if not out then
+ return nil, Err.from(derr)
+ end
+ if crc and Crc16.arc(out, 0, size) ~= crc then
+ return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch")
+ end
+ return out, nil
+ end
+ end
+ Archive.put(a, e)
+ p = h.dataAt + h.packed
+ end
+ a.meta.source = { format = "lha", levels = levels }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local items = Archive.entries(value)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive")
+ end
+ local out = Bytes.writer()
+ for _, it in items do
+ local e: any = it.entry
+ local data = buffer.create(0)
+ if not e.dir then
+ local b, err = it.read()
+ if not b then
+ return nil, err
+ end
+ data = b
+ end
+ local full = string.gsub(e.name, "/+$", "")
+ local dirPart, base = string.match(full, "^(.*/)([^/]*)$")
+ if not dirPart then
+ dirPart, base = "", full
+ end
+ if e.dir then
+ dirPart, base = full .. "/", ""
+ end
+ local h = Bytes.writer()
+ h:u16le(0) -- total size, patched
+ h:string(if e.dir then "-lhd-" else "-lh0-")
+ h:u32le(buffer.len(data))
+ h:u32le(buffer.len(data))
+ h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0)
+ h:u8(0x20)
+ h:u8(2)
+ h:u16le(Crc16.arc(data, 0, buffer.len(data)))
+ h:u8(0x55) -- 'U'nix
+ -- extended headers: [type][body][size of the next one]; the first size ends the base header
+ local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } }
+ if dirPart ~= "" then
+ table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) })
+ end
+ if type(e.mode) == "number" then
+ local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000)
+ table.insert(exts, { 0x50, string.char(m % 256, m // 256) })
+ end
+ h:u16le(#exts[1][2] + 3)
+ for i, x in exts do
+ h:u8(x[1])
+ h:string(x[2])
+ h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0)
+ end
+ local hb = h:finish()
+ local total = buffer.len(hb)
+ if total > 65535 then
+ return nil, Err.new(Err.ARG, "header too long for " .. e.name)
+ end
+ buffer.writeu16(hb, 0, total)
+ -- the header CRC covers the whole header with its own field zero
+ local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27
+ buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total))
+ out:bytes(hb)
+ out:bytes(data)
+ end
+ out:u8(0)
+ return out:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data)
+function Lha.new(): any
+ local a = Archive.new("lha", encoder)
+ a.meta.source = { format = "lha" }
+ return a
+end
+
+return Lha
diff --git a/src/Formats/archive/lz4/init.luau b/src/Formats/archive/lz4/init.luau
new file mode 100644
index 0000000..099edf0
--- /dev/null
+++ b/src/Formats/archive/lz4/init.luau
@@ -0,0 +1,353 @@
+--!strict
+-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the
+-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api
+-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy
+-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed
+-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified
+-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks
+-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size;
+-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported:
+-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Lz4 = require("@formats/codecs/compress/Lz4")
+local Xxh32 = require("@formats/codecs/compress/Xxh32")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Lz4Format = {
+ name = "lz4",
+ category = "archive",
+ extensions = { "lz4", "tlz4" },
+ mime = { "application/x-lz4" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
+ caps = { decode = true, encode = true, stream = true, legacy = true },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse output larger than this (default 2^30)
+ verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked)
+ name: string?, -- the file name (the api passes it): names the entry
+}
+export type EncodeOptions = {
+ blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool)
+ blockChecksum: boolean?, -- default false
+ contentChecksum: boolean?, -- default true
+ contentSize: boolean?, -- store the content size (default false)
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local MAGIC = 0x184D2204
+local LEGACY = 0x184C2102
+local LEGACY_BLOCK = 8 * 1048576
+local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 }
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Lz4Format.sniff(r: Bytes.Reader): number
+ local m = r:peek(4)
+ if m == "\4\34\77\24" then
+ return 1
+ elseif m == "\2\33\76\24" then
+ return 0.9
+ elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then
+ -- a skippable frame (zstd shares the magic): an LZ4 frame after it
+ local h = r:peek(4, 4)
+ if #h == 4 then
+ local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216
+ if r:peek(4, 8 + n) == "\4\34\77\24" then
+ return 1
+ end
+ end
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function skippable(m: number): boolean
+ return m >= 0x184D2A50 and m <= 0x184D2A5F
+end
+
+type Out = { buf: buffer, n: number, max: number }
+
+-- room for k more bytes in the output (doubling, up to max) | false
+local function room(out: Out, k: number): boolean
+ local need = out.n + k
+ if need > out.max then
+ return false
+ end
+ if need > buffer.len(out.buf) then
+ local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max))
+ buffer.copy(nb, 0, out.buf, 0, out.n)
+ out.buf = nb
+ end
+ return true
+end
+
+-- one LZ4 frame at p -> the input offset after it | nil, Err
+local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?)
+ if p + 7 > e then
+ return nil, Err.new(Err.TRUNCATED, "frame header past the end", p)
+ end
+ local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5)
+ if bit32.rshift(flg, 6) ~= 1 then
+ return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4)
+ end
+ if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then
+ return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4)
+ end
+ local independent = bit32.band(flg, 0x20) ~= 0
+ local blockSum = bit32.band(flg, 0x10) ~= 0
+ local hasSize = bit32.band(flg, 0x08) ~= 0
+ local contentSum = bit32.band(flg, 0x04) ~= 0
+ local hasDict = bit32.band(flg, 0x01) ~= 0
+ local bmax = SIZES[bit32.rshift(bd, 4)]
+ if not bmax then
+ return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5)
+ end
+ local q = p + 6
+ local size: number? = nil
+ if hasSize then
+ if q + 8 > e then
+ return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
+ end
+ size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296
+ q += 8
+ end
+ if hasDict then
+ return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q)
+ end
+ if q + 1 > e then
+ return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
+ end
+ local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255)
+ if hc ~= buffer.readu8(b, q) then
+ return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q)
+ end
+ q += 1
+ if size and out.n + size > out.max then
+ return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p)
+ end
+ local start = out.n
+ while true do
+ if q + 4 > e then
+ return nil, Err.new(Err.TRUNCATED, "block header past the end", q)
+ end
+ local bs = buffer.readu32(b, q)
+ q += 4
+ if bs == 0 then
+ break
+ end
+ local raw = bit32.band(bs, 0x80000000) ~= 0
+ local n = bit32.band(bs, 0x7FFFFFFF)
+ if n > bmax then
+ return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4)
+ end
+ if q + n + (if blockSum then 4 else 0) > e then
+ return nil, Err.new(Err.TRUNCATED, "block past the end", q)
+ end
+ if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then
+ return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n)
+ end
+ if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then
+ return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
+ end
+ if raw then
+ buffer.copy(out.buf, out.n, b, q, n)
+ out.n += n
+ else
+ local lim = math.min(out.n + bmax, buffer.len(out.buf))
+ local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start)
+ if not dEnd then
+ if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then
+ return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
+ end
+ return nil, Err.from(msg, q)
+ end
+ out.n = dEnd
+ end
+ q += n + (if blockSum then 4 else 0)
+ end
+ if contentSum then
+ if q + 4 > e then
+ return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q)
+ end
+ if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then
+ return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q)
+ end
+ q += 4
+ end
+ if size and out.n - start ~= size then
+ return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6)
+ end
+ return q, nil
+end
+
+-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows
+local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?)
+ local q = p + 4
+ while q + 4 <= e do
+ local n = buffer.readu32(b, q)
+ if n == MAGIC or n == LEGACY or skippable(n) then
+ break
+ end
+ q += 4
+ if q + n > e then
+ return nil, Err.new(Err.TRUNCATED, "block past the end", q)
+ end
+ if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then
+ return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
+ end
+ local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf))
+ local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim)
+ if not dEnd then
+ return nil, Err.from(msg, q)
+ end
+ out.n = dEnd
+ q += n
+ end
+ return q, nil
+end
+
+-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err
+function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
+ local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length)
+ if not b then
+ return nil, aerr
+ end
+ local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
+ local verify = not (opts and opts.verify == false)
+ local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes }
+ local p, e = o, o + n
+ local frames = 0
+ while p + 4 <= e do
+ local m = buffer.readu32(b, p)
+ local q, err
+ if m == MAGIC then
+ q, err = frame(b, p, e, out, verify)
+ frames += 1
+ elseif m == LEGACY then
+ q, err = legacy(b, p, e, out)
+ frames += 1
+ elseif skippable(m) then
+ if p + 8 > e then
+ return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
+ end
+ q = p + 8 + buffer.readu32(b, p + 4)
+ if q > e then
+ return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
+ end
+ elseif frames > 0 then
+ break -- trailing data after the frames (as lz4 -d, which warns)
+ else
+ return nil, Err.new(Err.CORRUPT, "bad magic", p)
+ end
+ if not q then
+ return nil, err
+ end
+ p = q :: number
+ end
+ if frames == 0 then
+ return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o)
+ end
+ local res = buffer.create(out.n)
+ buffer.copy(res, 0, out.buf, 0, out.n)
+ return res, nil
+end
+
+local function encode(value: any, opts: any?): (buffer?, Err.Err?)
+ return Lz4Format.encode(value, opts)
+end
+
+function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local n = r.limit - r.base
+ local out, err = Lz4Format.decompress(r.buf, r.base, n, o)
+ if not out then
+ return nil, err
+ end
+ local a = Archive.new("lz4", encode)
+ a.meta.stream = true
+ a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" }
+ local name = Archive.streamName(o, { "lz4" })
+ local stem, ext = string.match(name, "^(.+)%.(%w+)$")
+ if stem and ext and string.lower(ext) == "tlz4" then
+ name = stem .. ".tar"
+ end
+ Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out })
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+-- compress(data, opts?) -> one LZ4 frame | nil, Err
+function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil)
+ if not b then
+ return nil, aerr
+ end
+ local op: EncodeOptions = opts or {}
+ local bsize = op.blockSize or 4194304
+ local bd = nil
+ for k, v in SIZES do
+ if v == bsize then
+ bd = k
+ end
+ end
+ if not bd then
+ return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304")
+ end
+ local blockSum = op.blockChecksum == true
+ local contentSum = op.contentChecksum ~= false
+ local withSize = op.contentSize == true
+ local w = Bytes.writer(n + n // 200 + 64)
+ w:u32le(MAGIC)
+ local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0)
+ w:u8(flg)
+ w:u8(bd * 16)
+ if withSize then
+ w:u32le(n % 4294967296)
+ w:u32le(n // 4294967296)
+ end
+ local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255)
+ w:u8(hc)
+ local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1))))
+ local p = o
+ while p < o + n do
+ local k = math.min(bsize, o + n - p)
+ local c = Lz4.encodeInto(b, p, k, scratch, 0)
+ local at = w.pos
+ if c < k then
+ w:u32le(c)
+ local q = w:reserve(c)
+ buffer.copy(w.buf, q, scratch, 0, c)
+ w.pos = q + c
+ else
+ w:u32le(k + 0x80000000)
+ local q = w:reserve(k)
+ buffer.copy(w.buf, q, b, p, k)
+ w.pos = q + k
+ end
+ if blockSum then
+ local len = w.pos - at - 4
+ w:u32le(Xxh32.hash(w.buf, at + 4, len))
+ end
+ p += k
+ end
+ w:u32le(0)
+ if contentSum then
+ w:u32le(Xxh32.hash(b, o, n))
+ end
+ return w:finish(), nil
+end
+
+-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame
+function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local data, err = Archive.streamData(value)
+ if not data then
+ return nil, err
+ end
+ return Lz4Format.compress(data, opts)
+end
+
+return Lz4Format
diff --git a/src/Formats/archive/macbinary/init.luau b/src/Formats/archive/macbinary/init.luau
new file mode 100644
index 0000000..75e3eba
--- /dev/null
+++ b/src/Formats/archive/macbinary/init.luau
@@ -0,0 +1,201 @@
+--!strict
+-- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags,
+-- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III
+-- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its
+-- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry
+-- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime /
+-- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the
+-- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc16 = require("@formats/core/Crc16")
+local Archive = require("@formats/containers/Archive")
+local MacFile = require("@formats/containers/MacFile")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local MacBinary = {
+ name = "macbinary",
+ category = "archive",
+ extensions = { "bin", "macbin" },
+ mime = { "application/x-macbinary" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" },
+ caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } },
+}
+
+export type DecodeOptions = { maxBytes: number? } -- default 2^30
+export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data")
+
+-- ------------------------------------------------------------------------------------------------ sniff
+-- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o
+local function version(b: buffer, o: number, len: number): string?
+ if len < 128 then
+ return nil
+ end
+ local u8 = function(i: number): number
+ return buffer.readu8(b, o + i)
+ end
+ if u8(0) ~= 0 or u8(74) ~= 0 then
+ return nil
+ end
+ local nameLen = u8(1)
+ if nameLen < 1 or nameLen > 63 then
+ return nil
+ end
+ local function be32(i: number): number
+ return u8(i) * 16777216 + u8(i + 1) * 65536 + u8(i + 2) * 256 + u8(i + 3)
+ end
+ local dlen, rlen = be32(83), be32(87)
+ if dlen > 0x7FFFFFFF or rlen > 0x7FFFFFFF then
+ return nil
+ end
+ local crc = u8(124) * 256 + u8(125)
+ if crc == Crc16.ccitt(b, o, 124) and (crc ~= 0 or u8(122) >= 129) then
+ return if buffer.readstring(b, o + 102, 4) == "mBIN" then "III" else "II"
+ end
+ if buffer.readstring(b, o + 102, 4) == "mBIN" then
+ return nil -- III with a bad CRC
+ end
+ -- MacBinary I: byte 82 zero, bytes 99..125 zero, the forks within the file
+ if u8(82) ~= 0 then
+ return nil
+ end
+ for i = 99, 125 do
+ if u8(i) ~= 0 then
+ return nil
+ end
+ end
+ local need = 128 + math.ceil(dlen / 128) * 128 + rlen
+ return if need <= len + 127 then "I" else nil
+end
+
+function MacBinary.sniff(r: Bytes.Reader): number
+ local n = math.min(r:remaining(), 128)
+ if n < 128 then
+ return 0
+ end
+ local v = version(r.buf, r.base + r.pos, r.limit - r.base - r.pos)
+ return if v == "III" then 0.95 elseif v == "II" then 0.8 elseif v == "I" then 0.3 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return MacBinary.encode(a, o)
+end
+
+local function pad(n: number): number
+ return math.ceil(n / 128) * 128
+end
+
+function MacBinary.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local len = r.limit - r.base
+ local v = version(r.buf, r.base, len)
+ if not v then
+ if len >= 128 and buffer.readstring(r.buf, r.base + 102, 4) == "mBIN" then
+ return nil, Err.new(Err.CHECKSUM, "header CRC mismatch")
+ end
+ return nil, Err.new(if len < 128 then Err.TRUNCATED else Err.CORRUPT, "not a MacBinary header")
+ end
+ local h = r:sub(0, 128)
+ h:seek(1)
+ local name = h:string(h:u8())
+ h:seek(65)
+ local ftype, creator = h:string(4), h:string(4)
+ local flagsHi = h:u8()
+ h:seek(83)
+ local dlen, rlen = h:u32be(), h:u32be()
+ local created, modified = h:u32be(), h:u32be()
+ local commentLen = h:u16be()
+ local flagsLo = h:u8()
+ h:seek(120)
+ local secondary = h:u16be()
+ if v == "I" then
+ commentLen, flagsLo, secondary = 0, 0, 0
+ end
+ if dlen + rlen > (o.maxBytes or 2 ^ 30) then
+ return nil, Err.new(Err.LIMIT, "forks larger than maxBytes")
+ end
+ r:seek(128 + pad(secondary))
+ local data = r:bytes(dlen)
+ r:seek(128 + pad(secondary) + pad(dlen))
+ local rsrc = r:bytes(rlen)
+ local comment: string? = nil
+ if commentLen > 0 and r:seek(128 + pad(secondary) + pad(dlen) + pad(rlen)) then
+ comment = MacFile.name(r:string(math.min(commentLen, r:remaining())))
+ end
+ if r.err then
+ return nil, r.err
+ end
+ local a = Archive.new("macbinary", encoder)
+ MacFile.put(a, {
+ name = MacFile.name(name),
+ data = data,
+ rsrc = rsrc,
+ type = ftype,
+ creator = creator,
+ flags = flagsHi * 256 + flagsLo,
+ created = MacFile.fromMac(created),
+ modified = MacFile.fromMac(modified),
+ comment = comment,
+ })
+ a.meta.stream = rlen == 0
+ a.meta.source = { format = "macbinary", version = v }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function MacBinary.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local files, err = MacFile.collect(value, o.name)
+ if not files then
+ return nil, err
+ end
+ local f = files[1]
+ if not f then
+ return nil, Err.new(Err.ARG, "nothing to encode")
+ end
+ local name = MacFile.roman(f.name)
+ if #name < 1 or #name > 63 then
+ return nil, Err.new(Err.ARG, "the name must be 1..63 bytes")
+ end
+ local dlen, rlen = buffer.len(f.data), buffer.len(f.rsrc)
+ local comment = if f.comment then MacFile.roman(f.comment) else ""
+ local out = buffer.create(128 + pad(dlen) + pad(rlen) + #comment)
+ buffer.writeu8(out, 1, #name)
+ buffer.writestring(out, 2, name)
+ buffer.writestring(out, 65, f.type)
+ buffer.writestring(out, 69, f.creator)
+ buffer.writeu8(out, 73, bit32.rshift(f.flags, 8))
+ local function be32(at: number, v: number)
+ buffer.writeu32(out, at, bit32.byteswap(v))
+ end
+ be32(83, dlen)
+ be32(87, rlen)
+ be32(91, MacFile.toMac(f.created or f.modified))
+ be32(95, MacFile.toMac(f.modified))
+ buffer.writeu8(out, 99, bit32.rshift(#comment, 8))
+ buffer.writeu8(out, 100, bit32.band(#comment, 255))
+ buffer.writeu8(out, 101, bit32.band(f.flags, 255))
+ buffer.writestring(out, 102, "mBIN")
+ buffer.writeu8(out, 122, 130)
+ buffer.writeu8(out, 123, 129)
+ local crc = Crc16.ccitt(out, 0, 124)
+ buffer.writeu8(out, 124, bit32.rshift(crc, 8))
+ buffer.writeu8(out, 125, bit32.band(crc, 255))
+ buffer.copy(out, 128, f.data)
+ buffer.copy(out, 128 + pad(dlen), f.rsrc)
+ buffer.writestring(out, 128 + pad(dlen) + pad(rlen), comment)
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty MacBinary Archive: a:add(name, data); add "name.rsrc" for a resource fork
+function MacBinary.new(): any
+ local a = Archive.new("macbinary", encoder)
+ a.meta.source = { format = "macbinary" }
+ return a
+end
+
+return MacBinary
diff --git a/src/Formats/archive/rpm/init.luau b/src/Formats/archive/rpm/init.luau
new file mode 100644
index 0000000..3c248ce
--- /dev/null
+++ b/src/Formats/archive/rpm/init.luau
@@ -0,0 +1,333 @@
+--!strict
+-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature
+-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in
+-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with
+-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload
+-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed
+-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not
+-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package
+-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio"
+-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local Lzma = require("@formats/codecs/compress/Lzma")
+local Zstd = require("@formats/codecs/compress/Zstd")
+local Bzip2 = require("@formats/codecs/compress/Bzip2")
+local Archive = require("@formats/containers/Archive")
+local Cpio = require("@formats/containers/Cpio")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Rpm = {
+ name = "rpm",
+ category = "archive",
+ extensions = { "rpm" },
+ mime = { "application/x-rpm" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
+ caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- the largest decompressed payload (default 2^30)
+ maxEntries: number?, -- default 1e6
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local LEAD_MAGIC = "\237\171\238\219"
+local HEADER_MAGIC = "\142\173\232\1"
+local RPMFILE_GHOST = 64
+
+-- the tags meta.rpm names
+local NAMES: { [number]: string } = {
+ [1000] = "name",
+ [1001] = "version",
+ [1002] = "release",
+ [1003] = "epoch",
+ [1004] = "summary",
+ [1005] = "description",
+ [1006] = "buildtime",
+ [1007] = "buildhost",
+ [1009] = "size",
+ [1010] = "distribution",
+ [1011] = "vendor",
+ [1014] = "license",
+ [1015] = "packager",
+ [1016] = "group",
+ [1020] = "url",
+ [1021] = "os",
+ [1022] = "arch",
+ [1044] = "sourcerpm",
+ [1047] = "provides",
+ [1049] = "requires",
+ [1124] = "payloadFormat",
+ [1125] = "payloadCompressor",
+ [1126] = "payloadFlags",
+ [5009] = "longsize",
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Rpm.sniff(r: Bytes.Reader): number
+ return if r:peek(4) == LEAD_MAGIC then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- a header structure at p -> { [tag] = value }, end offset | nil, Err
+local function header(b: buffer, p: number, e: number): (any, any)
+ if p + 16 > e then
+ return nil, Err.new(Err.TRUNCATED, "header past the end", p)
+ end
+ if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then
+ return nil, Err.new(Err.CORRUPT, "bad header magic", p)
+ end
+ local n = bit32.byteswap(buffer.readu32(b, p + 8))
+ local hsize = bit32.byteswap(buffer.readu32(b, p + 12))
+ local index = p + 16
+ local store = index + n * 16
+ if n > 0x10000 or hsize > 0x10000000 then
+ return nil, Err.new(Err.LIMIT, "header too large", p)
+ end
+ if store + hsize > e then
+ return nil, Err.new(Err.TRUNCATED, "header data past the end", p)
+ end
+ local tags: { [number]: any } = {}
+ local se = store + hsize
+ for i = 0, n - 1 do
+ local q = index + i * 16
+ local tag = bit32.byteswap(buffer.readu32(b, q))
+ local typ = bit32.byteswap(buffer.readu32(b, q + 4))
+ local off = bit32.byteswap(buffer.readu32(b, q + 8))
+ local count = bit32.byteswap(buffer.readu32(b, q + 12))
+ local d = store + off
+ if off > hsize then
+ return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
+ end
+ local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0
+ if width > 0 then
+ if d + count * width > se then
+ return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
+ end
+ local v = table.create(count)
+ for k = 0, count - 1 do
+ local x = d + k * width
+ v[k + 1] = if width == 1 then buffer.readu8(b, x)
+ elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1))
+ elseif width == 4 then bit32.byteswap(buffer.readu32(b, x))
+ else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4))
+ end
+ tags[tag] = v
+ elseif typ == 7 then
+ if d + count > se then
+ return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
+ end
+ tags[tag] = buffer.readstring(b, d, count)
+ elseif typ == 6 or typ == 8 or typ == 9 then
+ local v = {}
+ local s = d
+ local want = if typ == 6 then 1 else count
+ if want > hsize then
+ return nil, Err.new(Err.CORRUPT, "bad string count", q)
+ end
+ for _ = 1, want do
+ local z = s
+ while z < se and buffer.readu8(b, z) ~= 0 do
+ z += 1
+ end
+ if z >= se then
+ return nil, Err.new(Err.CORRUPT, "unterminated string", s)
+ end
+ table.insert(v, buffer.readstring(b, s, z - s))
+ s = z + 1
+ end
+ tags[tag] = if typ == 6 then v[1] else v
+ end
+ end
+ return tags, se
+end
+
+-- the file list of the header: { name, size, mode, mtime, link, user, group, flags }
+local function files(tags: { [number]: any }): { any }
+ local names: { string } = {}
+ local bn, dn, di = tags[1117], tags[1118], tags[1116]
+ if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then
+ for i, base in bn do
+ local d = dn[(di[i] or 0) + 1]
+ names[i] = (if type(d) == "string" then d else "") .. base
+ end
+ elseif type(tags[1027]) == "table" then
+ names = tags[1027]
+ end
+ local sizes = tags[5008] or tags[1028] or {}
+ local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {}
+ local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {}
+ local out = {}
+ for i, n in names do
+ table.insert(out, {
+ name = n,
+ size = sizes[i] or 0,
+ mode = modes[i] or 0,
+ mtime = mtimes[i] or 0,
+ link = if links[i] and links[i] ~= "" then links[i] else nil,
+ user = users[i],
+ group = groups[i],
+ flags = flags[i] or 0,
+ })
+ end
+ return out
+end
+
+local function strip(name: string): string
+ return (string.gsub(name, "^%.?/+", ""))
+end
+
+-- the payload: decompressed, then its cpio entries by stripped name
+local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?)
+ local n = e - p
+ local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 }
+ local raw: buffer?, err: any
+ local m = if n >= 6 then buffer.readstring(b, p, 6) else ""
+ if string.sub(m, 1, 2) == "\31\139" then
+ raw, err = Deflate.gunzip(b, p, n)
+ elseif m == "\253" .. "7zXZ\0" then
+ raw, err = Lzma.xz(b, p, n, opts)
+ elseif string.sub(m, 1, 3) == "BZh" then
+ raw, err = Bzip2.decompress(b, p, n, opts)
+ elseif string.sub(m, 1, 4) == "\40\181\47\253" then
+ raw, err = Zstd.decompress(b, p, n, opts)
+ elseif compressor == "lzma" then
+ raw, err = Lzma.alone(b, p, n, opts)
+ elseif string.sub(m, 1, 5) == "07070" then
+ raw = buffer.create(n)
+ buffer.copy(raw :: buffer, 0, b, p, n)
+ else
+ return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p)
+ end
+ if not raw then
+ return nil, err
+ end
+ if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then
+ return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)")
+ end
+ local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries })
+ if not list then
+ return nil, cerr
+ end
+ local by = {}
+ for _, ent in list do
+ by[strip(ent.name)] = ent
+ end
+ return { buf = raw, by = by }, nil
+end
+
+function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local b, base, e = r.buf, r.base, r.limit
+ if e - base < 96 then
+ return nil, Err.new(Err.TRUNCATED, "lead past the end", base)
+ end
+ if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then
+ return nil, Err.new(Err.CORRUPT, "bad lead magic", base)
+ end
+ local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5)
+ local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7))
+ local leadName = buffer.readstring(b, base + 10, 66)
+ leadName = string.match(leadName, "^[^%z]*") :: string
+ if major < 3 then
+ return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4)
+ end
+ local sig, sigEnd = header(b, base + 96, e)
+ if not sig then
+ return nil, sigEnd
+ end
+ local hp = base + (sigEnd - base + 7) // 8 * 8
+ local tags, hEnd = header(b, hp, e)
+ if not tags then
+ return nil, hEnd
+ end
+ local a = Archive.new("rpm")
+ local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } }
+ for tag, key in NAMES do
+ local v = tags[tag]
+ if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value
+ v = v[1]
+ end
+ info[key] = v
+ end
+ a.meta.rpm = info
+ a.meta.source = { format = "rpm", compressor = info.payloadCompressor }
+ if info.payloadFormat and info.payloadFormat ~= "cpio" then
+ return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd)
+ end
+ local cache: any = nil
+ local cacheErr: Err.Err? = nil
+ local function entry(name: string): (any, Err.Err?)
+ if not cache and not cacheErr then
+ cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o)
+ end
+ if not cache then
+ return nil, cacheErr
+ end
+ local ent = cache.by[name]
+ if not ent then
+ return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload")
+ end
+ return ent, nil
+ end
+ local list = files(tags)
+ if #list > (o.maxEntries or 1e6) then
+ return nil, Err.new(Err.LIMIT, "too many files")
+ end
+ for _, f in list do
+ if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then
+ continue
+ end
+ local name = strip(f.name)
+ local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0"
+ local data = typ == "0" and f.size > 0
+ Archive.put(a, {
+ name = name,
+ size = if data then f.size else 0,
+ dir = typ == "5",
+ mtime = f.mtime,
+ mode = bit32.band(f.mode, 0xFFF),
+ type = typ,
+ link = if typ == "2" then f.link else nil,
+ uname = f.user,
+ gname = f.group,
+ method = if info.payloadCompressor then info.payloadCompressor else "store",
+ load = if data
+ then function(): (buffer?, Err.Err?)
+ local ent, err = entry(name)
+ if not ent then
+ return nil, err
+ end
+ local out = buffer.create(ent.size)
+ buffer.copy(out, 0, cache.buf, ent.offset, ent.size)
+ return out, nil
+ end
+ else nil,
+ })
+ end
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err
+function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
+ local a, err = Rpm.decode(r, opts)
+ if not a then
+ return nil, err
+ end
+ local p = r.base + 96
+ local _, sigEnd = header(r.buf, p, r.limit)
+ local hp = r.base + (sigEnd - r.base + 7) // 8 * 8
+ local _, hEnd = header(r.buf, hp, r.limit)
+ local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {})
+ if not pl then
+ return nil, perr
+ end
+ return pl.buf, nil
+end
+
+return Rpm
diff --git a/src/Formats/archive/uu/init.luau b/src/Formats/archive/uu/init.luau
new file mode 100644
index 0000000..4d64f01
--- /dev/null
+++ b/src/Formats/archive/uu/init.luau
@@ -0,0 +1,276 @@
+--!strict
+-- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin " block of a
+-- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode);
+-- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each
+-- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and
+-- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils
+-- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings
+-- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Base64 = require("@formats/core/Base64")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Uu = {
+ name = "uu",
+ category = "archive",
+ extensions = { "uu", "uue", "xxe", "b64" },
+ mime = { "text/x-uuencode" },
+ deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" },
+ caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } },
+}
+
+export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
+export type EncodeOptions = {
+ variant: ("uu" | "xx" | "base64")?, -- default "uu"
+ mode: number?, -- file mode when the entry has none (default 0o644)
+ name: string?, -- the name of a buffer / string value (default "data")
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+local XX_VALUE: { [number]: number } = {}
+for i = 1, 64 do
+ XX_VALUE[string.byte(XX, i)] = i - 1
+end
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Uu.sniff(r: Bytes.Reader): number
+ local head = r:peek(4096)
+ if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then
+ return 0.9
+ end
+ if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then
+ return 0.5
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the value of character c in a variant, or nil
+local function value(c: number, xx: boolean): number?
+ if xx then
+ return XX_VALUE[c]
+ end
+ if c >= 32 and c <= 96 then
+ return bit32.band(c - 32, 63)
+ end
+ return nil
+end
+
+-- does a data line fit the variant: every character valid and the length matching the count character
+local function fits(line: string, xx: boolean): boolean
+ local n = value(string.byte(line, 1) or 0, xx)
+ if not n then
+ return false
+ end
+ local need = math.ceil(n / 3) * 4
+ if #line - 1 < need or #line - 1 > need + 2 then
+ return false
+ end
+ for i = 2, need + 1 do
+ if not value(string.byte(line, i), xx) then
+ return false
+ end
+ end
+ return true
+end
+
+-- decode the uu / xx lines of a block into a buffer (nil, message on a bad line)
+local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?)
+ local total = 0
+ for _, l in lines do
+ total += value(string.byte(l, 1) or 0, xx) or 0
+ end
+ if total > maxBytes then
+ return nil, "limit: data larger than maxBytes"
+ end
+ local out = buffer.create(total)
+ local o = 0
+ for li, l in lines do
+ local n = value(string.byte(l, 1) or 0, xx) or 0
+ local p = 2
+ local left = n
+ while left > 0 do
+ local a = value(string.byte(l, p) or 0, xx)
+ local b = value(string.byte(l, p + 1) or 0, xx)
+ local c = value(string.byte(l, p + 2) or 0, xx) or 0
+ local d = value(string.byte(l, p + 3) or 0, xx) or 0
+ if not a or not b then
+ return nil, "bad character in line " .. li
+ end
+ local v = a * 262144 + b * 4096 + c * 64 + d
+ for k = 2, 0, -1 do
+ if left > 0 then
+ buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255))
+ o += 1
+ left -= 1
+ end
+ end
+ p += 4
+ end
+ end
+ return out, nil
+end
+
+type Block = { name: string, mode: number, variant: string, data: buffer }
+
+local function parse(text: string, maxBytes: number): ({ Block }?, string?)
+ local lines = string.split(text, "\n")
+ local blocks: { Block } = {}
+ local i = 1
+ while i <= #lines do
+ local line = string.gsub(lines[i], "\r$", "")
+ local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$")
+ if not b64 then
+ mode, name = string.match(line, "^begin ([0-7]+) (.+)$")
+ end
+ if mode and name then
+ local body: { string } = {}
+ local closed = false
+ i += 1
+ while i <= #lines do
+ local l = string.gsub(lines[i], "\r$", "")
+ if (b64 and l == "====") or (not b64 and l == "end") then
+ closed = true
+ break
+ end
+ table.insert(body, l)
+ i += 1
+ end
+ if not closed then
+ return nil, "truncated: block " .. name .. " has no end line"
+ end
+ local data, variant
+ if b64 then
+ local d, err = Base64.decode(table.concat(body))
+ if not d then
+ return nil, "block " .. name .. ": " .. tostring(err)
+ end
+ data, variant = d, "base64"
+ else
+ -- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines
+ local data_lines: { string } = {}
+ for _, l in body do
+ if l ~= "" then
+ table.insert(data_lines, l)
+ end
+ end
+ local uuOk, xxOk = true, true
+ for _, l in data_lines do
+ uuOk = uuOk and fits(l, false)
+ xxOk = xxOk and fits(l, true)
+ end
+ local xx = xxOk and not uuOk
+ if not uuOk and not xxOk then
+ return nil, "block " .. name .. ": lines are neither uuencode nor xxencode"
+ end
+ local d, err = decodeLines(data_lines, xx, maxBytes)
+ if not d then
+ return nil, err
+ end
+ data, variant = d, if xx then "xx" else "uu"
+ end
+ table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data })
+ end
+ i += 1
+ end
+ if #blocks == 0 then
+ return nil, "no begin line"
+ end
+ return blocks, nil
+end
+
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return Uu.encode(a, o)
+end
+
+function Uu.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30)
+ if not blocks then
+ return nil, Err.from(err)
+ end
+ local a = Archive.new("uu", encoder)
+ for _, b in blocks do
+ Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data })
+ end
+ a.meta.stream = #a:list() == 1
+ a.meta.source = { format = "uu", variant = blocks[1].variant }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function encodeLines(data: buffer, xx: boolean, out: { string })
+ local n = buffer.len(data)
+ local function ch(v: number): string
+ if xx then
+ return string.sub(XX, v + 1, v + 1)
+ end
+ return if v == 0 then "`" else string.char(v + 32)
+ end
+ local p = 0
+ while p < n do
+ local len = math.min(45, n - p)
+ local parts = { ch(len) }
+ for q = p, p + len - 1, 3 do
+ local b0 = buffer.readu8(data, q)
+ local b1 = if q + 1 < p + len then buffer.readu8(data, q + 1) else 0
+ local b2 = if q + 2 < p + len then buffer.readu8(data, q + 2) else 0
+ local v = b0 * 65536 + b1 * 256 + b2
+ table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63)))
+ end
+ table.insert(out, table.concat(parts))
+ p += len
+ end
+ table.insert(out, ch(0))
+end
+
+function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local variant = o.variant or "uu"
+ if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then
+ return nil, Err.new(Err.ARG, "variant must be uu, xx or base64")
+ end
+ local files, err = Archive.files(value, o.name)
+ if not files then
+ return nil, err
+ end
+ if #files == 0 then
+ return nil, Err.new(Err.ARG, "nothing to encode")
+ end
+ local out: { string } = {}
+ for _, f in files do
+ if string.find(f.name, "[\r\n]") then
+ return nil, Err.new(Err.ARG, "file names may not contain line breaks")
+ end
+ local mode = if type(f.entry.mode) == "number" then f.entry.mode else (o.mode or 0x1A4)
+ local m = string.format("%o", bit32.band(mode, 0xFFF))
+ if variant == "base64" then
+ table.insert(out, "begin-base64 " .. m .. " " .. f.name)
+ local s = Base64.encode(f.data)
+ for p = 1, #s, 60 do
+ table.insert(out, string.sub(s, p, p + 59))
+ end
+ table.insert(out, "====")
+ else
+ table.insert(out, "begin " .. m .. " " .. f.name)
+ encodeLines(f.data, variant == "xx", out)
+ table.insert(out, "end")
+ end
+ end
+ return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant })
+function Uu.new(): any
+ local a = Archive.new("uu", encoder)
+ a.meta.source = { format = "uu" }
+ return a
+end
+
+return Uu
diff --git a/src/Formats/archive/yenc/init.luau b/src/Formats/archive/yenc/init.luau
new file mode 100644
index 0000000..23997cb
--- /dev/null
+++ b/src/Formats/archive/yenc/init.luau
@@ -0,0 +1,277 @@
+--!strict
+-- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive:
+-- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart
+-- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified
+-- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a
+-- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one
+-- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space
+-- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Yenc = {
+ name = "yenc",
+ category = "archive",
+ extensions = { "yenc", "ync" },
+ mime = { "application/x-yenc" },
+ deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" },
+ caps = { decode = true, encode = true, multipart = true },
+}
+
+export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
+export type EncodeOptions = {
+ line: number?, -- characters per line (default 128)
+ name: string?, -- the name of a buffer / string value (default "data")
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Yenc.sniff(r: Bytes.Reader): number
+ local head = r:peek(4096)
+ if string.match(head, "^=ybegin ") then
+ return 0.95
+ end
+ return if string.find(head, "\n=ybegin [^\n]*name=") then 0.6 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- key=value fields of a keyword line; name= runs to the end of the line
+local function fields(line: string): { [string]: string }
+ local f: { [string]: string } = {}
+ local s, name = string.match(line, "^(.-)name=(.*)$")
+ if s then
+ f.name = string.gsub(name :: string, "%s+$", "")
+ line = s
+ end
+ for k, v in string.gmatch(line, "(%w+)=(%S+)") do
+ f[k] = v
+ end
+ return f
+end
+
+-- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out)
+local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number
+ local lim = buffer.len(out)
+ local esc = false
+ for p = i, j - 1 do
+ local c = buffer.readu8(src, p)
+ if c == 13 or c == 10 then
+ continue
+ end
+ if c == 61 and not esc then
+ esc = true
+ continue
+ end
+ if esc then
+ c -= 64
+ esc = false
+ end
+ if o < lim then
+ buffer.writeu8(out, o, (c - 42) % 256)
+ end
+ o += 1
+ end
+ return o
+end
+
+-- count the decoded bytes of the data lines [i, j)
+local function countData(src: buffer, i: number, j: number): number
+ local n, esc = 0, false
+ for p = i, j - 1 do
+ local c = buffer.readu8(src, p)
+ if c ~= 13 and c ~= 10 then
+ if c == 61 and not esc then
+ esc = true
+ else
+ esc = false
+ n += 1
+ end
+ end
+ end
+ return n
+end
+
+type Part = { first: number, last: number, from: number, to: number, pcrc: number?, part: number? }
+type File = { name: string, size: number, crc: number?, parts: { Part }, total: number? }
+
+local function hex(s: string?): number?
+ return if s and string.match(s, "^%x+$") and #s <= 8 then tonumber(s, 16) else nil
+end
+
+local function parse(b: buffer, base: number, limit: number): ({ File }?, string?)
+ local files: { File } = {}
+ local byName: { [string]: File } = {}
+ local p = base
+ local cur: File? = nil
+ local part: Part? = nil
+ while p < limit do
+ local nl = p
+ while nl < limit and buffer.readu8(b, nl) ~= 10 do
+ nl += 1
+ end
+ local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y"
+ if isKey then
+ local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "")
+ local kw = string.match(line, "^=y(%a+)")
+ local f = fields(line)
+ if kw == "begin" then
+ local name = f.name
+ local size = tonumber(f.size or "")
+ if not name or name == "" or not size or size < 0 then
+ return nil, "=ybegin without name or size"
+ end
+ local file: File? = byName[name]
+ if not file then
+ local nf: File = { name = name :: string, size = size, parts = {}, total = tonumber(f.total or "") }
+ byName[name] = nf
+ table.insert(files, nf)
+ file = nf
+ end
+ cur = file
+ part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") }
+ elseif kw == "part" and part then
+ local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "")
+ if not first or not last or first < 1 or last < first - 1 then
+ return nil, "bad =ypart range"
+ end
+ part.first, part.last = first - 1, last
+ part.from, part.to = nl + 1, nl + 1
+ elseif kw == "end" and part and cur then
+ part.pcrc = hex(f.pcrc32)
+ if f.crc32 then
+ cur.crc = hex(f.crc32)
+ end
+ local size = tonumber(f.size or "")
+ if size and size ~= part.last - part.first then
+ return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")"
+ end
+ table.insert(cur.parts, part)
+ part = nil
+ end
+ elseif part then
+ part.to = nl + 1
+ end
+ p = nl + 1
+ end
+ if part then
+ return nil, "truncated: no =yend"
+ end
+ if #files == 0 then
+ return nil, "no =ybegin line"
+ end
+ return files, nil
+end
+
+local function encoder(a: any, o: any?): (buffer?, Err.Err?)
+ return Yenc.encode(a, o)
+end
+
+function Yenc.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxBytes = o.maxBytes or 2 ^ 30
+ local b = r.buf
+ local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b)))
+ if not files then
+ return nil, Err.from(perr)
+ end
+ local a = Archive.new("yenc", encoder)
+ local incomplete = {}
+ for _, f in files do
+ if f.size > maxBytes then
+ return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes")
+ end
+ local out = buffer.create(f.size)
+ local covered = 0
+ for _, pt in f.parts do
+ local n = countData(b, pt.from, pt.to)
+ if n ~= pt.last - pt.first or pt.last > f.size then
+ return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first))
+ end
+ local tmp = buffer.create(n)
+ decodeData(b, pt.from, pt.to, tmp, 0)
+ if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then
+ return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch")
+ end
+ buffer.copy(out, pt.first, tmp, 0, n)
+ covered += n
+ end
+ local whole = covered == f.size
+ if whole and f.crc and Crc32.of(out) ~= f.crc then
+ return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch")
+ end
+ if not whole then
+ table.insert(incomplete, f.name)
+ end
+ Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole })
+ end
+ a.meta.stream = #files == 1
+ a.meta.incomplete = if #incomplete > 0 then incomplete else nil
+ a.meta.source = { format = "yenc" }
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local lineLen = o.line or 128
+ if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then
+ return nil, Err.new(Err.ARG, "line must be 2..997")
+ end
+ local files, err = Archive.files(value, o.name)
+ if not files then
+ return nil, err
+ end
+ if #files == 0 then
+ return nil, Err.new(Err.ARG, "nothing to encode")
+ end
+ local w = Bytes.writer()
+ for _, f in files do
+ if string.find(f.name, "[\r\n]") then
+ return nil, Err.new(Err.ARG, "file names may not contain line breaks")
+ end
+ local data = f.data
+ local n = buffer.len(data)
+ w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name))
+ local col = 0
+ for i = 0, n - 1 do
+ local c = (buffer.readu8(data, i) + 42) % 256
+ local critical = c == 0 or c == 10 or c == 13 or c == 61
+ if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then
+ critical = true
+ elseif not critical and c == 46 and col == 0 then
+ critical = true
+ end
+ if critical then
+ w:u8(61)
+ w:u8((c + 64) % 256)
+ col += 2
+ else
+ w:u8(c)
+ col += 1
+ end
+ if col >= lineLen and i < n - 1 then
+ w:string("\r\n")
+ col = 0
+ end
+ end
+ if n > 0 then
+ w:string("\r\n")
+ end
+ w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data)))
+ end
+ return w:finish(), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line })
+function Yenc.new(): any
+ local a = Archive.new("yenc", encoder)
+ a.meta.source = { format = "yenc" }
+ return a
+end
+
+return Yenc
diff --git a/src/Formats/archive/z/init.luau b/src/Formats/archive/z/init.luau
new file mode 100644
index 0000000..c1a13a5
--- /dev/null
+++ b/src/Formats/archive/z/init.luau
@@ -0,0 +1,98 @@
+--!strict
+-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one
+-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a
+-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed,
+-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is
+-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local UnixCompress = require("@formats/codecs/compress/UnixCompress")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Z = {
+ name = "z",
+ category = "archive",
+ extensions = { "z", "taz", "tz" },
+ mime = { "application/x-compress" },
+ deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
+ caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse output larger than this (default 2^30)
+ name: string?, -- the file name (the api passes it): names the entry
+}
+export type EncodeOptions = {
+ maxBits: number?, -- 9..16 (compress -b), default 16
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Z.sniff(r: Bytes.Reader): number
+ if r:peek(2) ~= "\31\157" then
+ return 0
+ end
+ local f = r:peekU8(2)
+ return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the entry name: the file name without .Z; .taz / .tz name a tar
+local function entryName(opts: DecodeOptions): string
+ local name = Archive.streamName(opts, { "z" })
+ local stem, ext = string.match(name, "^(.+)%.(%w+)$")
+ if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then
+ return stem .. ".tar"
+ end
+ return name
+end
+
+local function encode(value: any, opts: any?): (buffer?, Err.Err?)
+ return Z.encode(value, opts)
+end
+
+function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local n = r.limit - r.base
+ local out, err = UnixCompress.decompress(r.buf, r.base, n, o)
+ if not out then
+ return nil, err
+ end
+ local a = Archive.new("z", encode)
+ a.meta.stream = true
+ a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 }
+ Archive.put(a, {
+ name = entryName(o),
+ size = buffer.len(out),
+ compressedSize = n,
+ method = "lzw",
+ dir = false,
+ data = out,
+ })
+ return a, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local data, err = Archive.streamData(value)
+ if not data then
+ return nil, err
+ end
+ return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits })
+end
+
+-- ------------------------------------------------------------------------------------------------ extras
+-- new(data?, name?) -> a .Z Archive holding one entry
+function Z.new(data: (buffer | string)?, name: string?): any
+ local a = Archive.new("z", encode)
+ a.meta.stream = true
+ a.meta.source = { format = "z" }
+ if data then
+ a:add(name or "data", data)
+ end
+ return a
+end
+
+return Z
diff --git a/src/Formats/archive/zoo/init.luau b/src/Formats/archive/zoo/init.luau
new file mode 100644
index 0000000..1782cdd
--- /dev/null
+++ b/src/Formats/archive/zoo/init.luau
@@ -0,0 +1,197 @@
+--!strict
+-- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of
+-- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers),
+-- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit
+-- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read
+-- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not
+-- supported: writing, file generations beyond keeping the newest (older versions of a name get ";").
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Crc16 = require("@formats/core/Crc16")
+local Lzw = require("@formats/codecs/compress/Lzw")
+local Lzh = require("@formats/codecs/compress/Lzh")
+local Archive = require("@formats/containers/Archive")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Zoo = {
+ name = "zoo",
+ category = "archive",
+ extensions = { "zoo" },
+ mime = { "application/x-zoo" },
+ deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" },
+ caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } },
+}
+
+export type DecodeOptions = {
+ maxBytes: number?, -- refuse an entry larger than this (default 2^30)
+ maxEntries: number?, -- default 65536
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local TAG = 0xFDC4A7DC
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Zoo.sniff(r: Bytes.Reader): number
+ local h = r:peek(24)
+ if #h < 24 then
+ return 0
+ end
+ local tag = string.byte(h, 21) + string.byte(h, 22) * 256 + string.byte(h, 23) * 65536 + string.byte(h, 24) * 16777216
+ if tag ~= TAG then
+ return 0
+ end
+ return if string.sub(h, 1, 4) == "ZOO " then 1 else 0.8
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Zoo.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxBytes = o.maxBytes or 2 ^ 30
+ local maxEntries = o.maxEntries or 65536
+ local h = r:sub(0, 34)
+ local text = h:string(20)
+ local tag, start = h:u32le(), h:u32le()
+ h:skip(4)
+ local major, minor = h:u8(), h:u8()
+ if h.err then
+ return nil, h.err
+ end
+ if tag ~= TAG then
+ return nil, Err.new(Err.CORRUPT, "no zoo tag")
+ end
+ local a = Archive.new("zoo")
+ a.meta.text = string.match(text, "^[^%z\26]*")
+ a.meta.source = { format = "zoo", version = major .. "." .. minor }
+ local p = start
+ local count = 0
+ local seen: { [number]: boolean } = {}
+ local size = r:size()
+ while true do
+ if seen[p] or p < 34 or p + 51 > size then
+ return nil, Err.new(if p + 51 > size then Err.TRUNCATED else Err.CORRUPT, "bad directory entry offset " .. p)
+ end
+ seen[p] = true
+ local e = r:sub(p, size - p)
+ local etag = e:u32le()
+ local etype, method = e:u8(), e:u8()
+ local nextP, dataAt = e:u32le(), e:u32le()
+ local date, time = e:u16le(), e:u16le()
+ local crc = e:u16le()
+ local orig, packed = e:u32le(), e:u32le()
+ e:skip(2)
+ local deleted = e:u8()
+ e:skip(1)
+ local commentAt, commentLen = e:u32le(), e:u16le()
+ local fname = e:fixed(13)
+ if e.err then
+ return nil, e.err
+ end
+ if etag ~= TAG then
+ return nil, Err.new(Err.CORRUPT, "bad directory entry tag", r.base + p)
+ end
+ if nextP == 0 then
+ break
+ end
+ count += 1
+ if count > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
+ end
+ local name, dir = fname, ""
+ local entry: any = {}
+ if etype == 2 then
+ local varLen = e:u16le()
+ e:skip(3) -- tz, dir_crc
+ if varLen > 0 then
+ local v = e:slice(varLen)
+ local nlen, dlen = v:u8(), v:u8()
+ local lname = v:string(nlen)
+ dir = v:string(dlen)
+ if nlen > 0 then
+ name = string.match(lname, "^[^%z]*") or lname
+ end
+ if v:remaining() >= 2 then
+ entry.system = v:u16le()
+ end
+ if v:remaining() >= 3 then
+ local f0, f1, f2 = v:u8(), v:u8(), v:u8()
+ local attr = f0 + f1 * 256 + f2 * 65536
+ if bit32.band(attr, 0x400000) ~= 0 then
+ entry.mode = bit32.band(attr, 0xFFFF)
+ end
+ end
+ if v:remaining() >= 4 then
+ local vflag, ver = v:u16le(), v:u16le()
+ if bit32.band(vflag, 0x40) ~= 0 then
+ entry.version = ver
+ end
+ end
+ end
+ if e.err then
+ return nil, e.err
+ end
+ end
+ dir = string.match(dir, "^[^%z]*") or dir
+ dir = string.gsub(dir, "\\", "/")
+ local full = if dir ~= "" then (string.gsub(dir, "/+$", "")) .. "/" .. name else name
+ full = string.gsub(full, "^/+", "")
+ if deleted == 0 then
+ local key = full
+ if a._byName[key] then
+ key = full .. ";" .. tostring(entry.version or count)
+ end
+ entry.name = key
+ entry.size = orig
+ entry.compressedSize = packed
+ entry.method = if method == 0 then "store" elseif method == 1 then "lzw" elseif method == 2 then "lzh" else "method" .. method
+ entry.mtime = Archive.fromDos(date * 65536 + time)
+ entry.dir = false
+ if commentLen > 0 and commentAt + commentLen <= size then
+ entry.comment = r:sub(commentAt, commentLen):string(commentLen)
+ end
+ if dataAt + packed > size then
+ return nil, Err.new(Err.TRUNCATED, full .. ": data past the end")
+ end
+ if orig > maxBytes then
+ return nil, Err.new(Err.LIMIT, full .. ": larger than maxBytes")
+ end
+ if orig > 0 then
+ local buf, at = r.buf, r.base + dataAt
+ entry.load = function(): (buffer?, Err.Err?)
+ local out: buffer?, derr: string?
+ if method == 0 then
+ if packed < orig then
+ return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
+ end
+ out = buffer.create(orig)
+ buffer.copy(out :: buffer, 0, buf, at, orig)
+ elseif method == 1 then
+ local ob = buffer.create(orig)
+ local n, lerr = Lzw.decode(buf, at, packed, ob, 0, orig, "zoo")
+ if n ~= orig then
+ return nil, Err.from(lerr or "corrupt: LZW data ends early")
+ end
+ out = ob
+ elseif method == 2 then
+ out, derr = Lzh.decode(buf, at, packed, orig, "lh5")
+ else
+ return nil, Err.new(Err.UNSUPPORTED, "packing method " .. method)
+ end
+ if not out then
+ return nil, Err.from(derr)
+ end
+ if Crc16.arc(out, 0, orig) ~= crc then
+ return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch")
+ end
+ return out, nil
+ end
+ end
+ Archive.put(a, entry)
+ end
+ p = nextP
+ end
+ return a, nil
+end
+
+return Zoo
diff --git a/src/Formats/codecs/compress/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau
index 456464f..5927590 100644
--- a/src/Formats/codecs/compress/Deflate/Inflate.luau
+++ b/src/Formats/codecs/compress/Deflate/Inflate.luau
@@ -64,10 +64,19 @@ end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and
-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing).
+-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it,
+-- distances may reach into it, and outLen includes it (cap does not).
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
-function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?)
- local out = bcreate(cap)
+function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?)
local op = 0
+ if dict then
+ op = blen(dict)
+ cap += op
+ end
+ local out = bcreate(cap)
+ if dict then
+ bcopy(out, 0, dict, 0, op)
+ end
local pos = start
local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer
diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau
index fd25c71..46ea9fe 100644
--- a/src/Formats/codecs/compress/Deflate/init.luau
+++ b/src/Formats/codecs/compress/Deflate/init.luau
@@ -6,6 +6,8 @@
-- local Deflate = require("@formats/codecs/compress/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
+-- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary
+-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained)
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
@@ -43,7 +45,9 @@ end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
-function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
+-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may
+-- reach into it; the result holds only the new bytes.
+function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
return nil, aerr
@@ -58,10 +62,20 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?,
else
cap = math.max(1024, l * 4)
end
- local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact)
+ if dict ~= nil and type(dict) ~= "buffer" then
+ return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer")
+ end
+ local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict)
if not out then
return nil, inflateErr(tostring(n), o)
end
+ if dict then
+ local d = buffer.len(dict)
+ n -= d
+ local res = buffer.create(n)
+ buffer.copy(res, 0, out, d, n)
+ out = res
+ end
if exact and n ~= expectedSize then
return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number))
end
@@ -295,6 +309,40 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E
return out, nil
end
+-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x
+-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that
+-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the
+-- blocks' output concatenated.
+function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?)
+ local total = 0
+ for _, b in blocks do
+ if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then
+ return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range")
+ end
+ total += b.size
+ end
+ local out = buffer.create(total)
+ local o = 0
+ for _, b in blocks do
+ if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then
+ return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset)
+ end
+ local dict: buffer? = nil
+ if o > 0 then
+ local d = math.min(o, 32768)
+ dict = buffer.create(d)
+ buffer.copy(dict :: buffer, 0, out, o - d, d)
+ end
+ local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict)
+ if not part then
+ return nil, err
+ end
+ buffer.copy(out, o, part, 0, b.size)
+ o += b.size
+ end
+ return out, nil
+end
+
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
diff --git a/src/Formats/codecs/compress/Lzh/init.luau b/src/Formats/codecs/compress/Lzh/init.luau
new file mode 100644
index 0000000..dd37bf6
--- /dev/null
+++ b/src/Formats/codecs/compress/Lzh/init.luau
@@ -0,0 +1,626 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
+-- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset
+-- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5")
+-- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length
+-- offset prefixes, 4 KB window
+-- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes)
+-- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman)
+-- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill
+-- them (spaces; lz5's pattern), and offsets before the start of the output read that fill.
+-- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c,
+-- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead
+-- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description).
+--
+-- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message
+--
+-- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes
+-- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7.
+local Huffman = require("@formats/codecs/entropy/Huffman")
+
+local Lzh = {}
+
+local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32
+local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
+local floor = math.floor
+
+-- ------------------------------------------------------------------------------------------------ bit reader
+-- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and
+-- over counts them
+type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number }
+
+local function reader(src: buffer, off: number, len: number): Reader
+ return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 }
+end
+
+local function fill(r: Reader)
+ while r.cnt <= 24 do
+ local b = 0
+ if r.pos < r.limit then
+ b = readu8(r.src, r.pos)
+ r.pos += 1
+ else
+ r.over += 8
+ end
+ r.acc = r.acc * 256 + b
+ r.cnt += 8
+ end
+end
+
+local function peek(r: Reader, n: number): number
+ if r.cnt < n then
+ fill(r)
+ end
+ return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n
+end
+
+local function skip(r: Reader, n: number)
+ if r.cnt < n then
+ fill(r)
+ end
+ r.cnt -= n
+ r.acc = r.acc % 2 ^ r.cnt
+end
+
+local function bits(r: Reader, n: number): number
+ if n == 0 then
+ return 0
+ end
+ local v = peek(r, n)
+ skip(r, n)
+ return v
+end
+
+-- ------------------------------------------------------------------------------------------------ static Huffman
+type Table = { tab: buffer, P: number, S: number, single: number }
+
+local function newTable(nsym: number, P: number): Table
+ return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 }
+end
+
+local function build(t: Table, lens: buffer, n: number): boolean
+ t.single = -1
+ local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P)
+ if S < 0 then
+ return false
+ end
+ t.S = S
+ return true
+end
+
+local function decodeSym(r: Reader, t: Table): number
+ if t.single >= 0 then
+ return t.single
+ end
+ local P, S = t.P, t.S
+ local e = readu32(t.tab, peek(r, P) * 4)
+ local l = band(e, 31)
+ if l == 0 then
+ if e == 0 then
+ return -1
+ end
+ local idx = peek(r, P + S)
+ e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4)
+ l = band(e, 31)
+ if l == 0 then
+ return -1
+ end
+ end
+ skip(r, l)
+ return rshift(e, 5)
+end
+
+local lens = buffer.create(512)
+
+local function lengthValue(r: Reader): number
+ local len = bits(r, 3)
+ if len == 7 then
+ while bits(r, 1) == 1 do
+ len += 1
+ if len > 16 then
+ return 17
+ end
+ end
+ end
+ return len
+end
+
+-- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table
+local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean
+ local n = bits(r, nbits)
+ if n == 0 then
+ t.single = bits(r, nbits)
+ return true
+ end
+ n = math.min(n, maxN)
+ buffer.fill(lens, 0, 0, 512)
+ local i = 0
+ while i < n do
+ local l = lengthValue(r)
+ if l > 16 then
+ return false
+ end
+ writeu8(lens, i, l)
+ if i == special then
+ local z = bits(r, 2)
+ i += z -- zeros (already zero)
+ end
+ i += 1
+ end
+ return build(t, lens, math.min(i, maxN))
+end
+
+local function readCodes(r: Reader, temp: Table, codes: Table): boolean
+ local n = bits(r, 9)
+ if n == 0 then
+ codes.single = bits(r, 9)
+ return true
+ end
+ n = math.min(n, 510)
+ buffer.fill(lens, 0, 0, 512)
+ local i = 0
+ while i < n do
+ local c = decodeSym(r, temp)
+ if c < 0 then
+ return false
+ end
+ if c <= 2 then
+ local count = if c == 0 then 1 elseif c == 1 then bits(r, 4) + 3 else bits(r, 9) + 20
+ i += count
+ else
+ if c - 2 > 16 then
+ return false
+ end
+ writeu8(lens, i, c - 2)
+ i += 1
+ end
+ end
+ return build(codes, lens, n)
+end
+
+local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 }
+
+local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string?
+ local r = reader(src, off, len)
+ local obits = OFFSET_BITS[method]
+ local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8)
+ local o = 0
+ local remaining = 0
+ while o < n do
+ if remaining == 0 then
+ remaining = bits(r, 16)
+ if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then
+ return if r.over > 0 then "truncated" else "bad Huffman table"
+ end
+ if r.over > 32 then
+ return "truncated"
+ end
+ if remaining == 0 then
+ return "empty block"
+ end
+ end
+ remaining -= 1
+ local c = decodeSym(r, codes)
+ if c < 0 then
+ return "bad code"
+ end
+ if c < 256 then
+ writeu8(out, o, c)
+ o += 1
+ else
+ local count = c - 256 + 3
+ local p = decodeSym(r, offs)
+ if p < 0 then
+ return "bad offset code"
+ end
+ if p > 1 then
+ p = lshift(1, p - 1) + bits(r, p - 1)
+ end
+ local from = o - p - 1
+ for _ = 1, count do
+ if o >= n then
+ break
+ end
+ writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20)
+ o += 1
+ from += 1
+ end
+ end
+ if r.over > 32 then
+ return "truncated"
+ end
+ end
+ return nil
+end
+
+-- ------------------------------------------------------------------------------------------------ lh1
+local NUM_CODES = 314
+local NUM_NODES = NUM_CODES * 2 - 1
+local REORDER = 32 * 1024
+local FDIST = { 1, 3, 8, 12, 24, 16 }
+
+local offsetLookup = table.create(256, 0)
+local offsetLength = table.create(64, 0)
+do
+ local code, offset = 0, 0
+ for i, count in FDIST do
+ local l = i - 1 + 3
+ local iter = lshift(1, 8 - l)
+ for _ = 1, count do
+ for k = 0, iter - 1 do
+ offsetLookup[code + k + 1] = offset
+ end
+ offsetLength[offset + 1] = l
+ code += iter
+ offset += 1
+ end
+ end
+end
+
+local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string?
+ local r = reader(src, off, len)
+ -- node arrays (0-based indexes stored at [i + 1])
+ local leaf = table.create(NUM_NODES, false)
+ local child = table.create(NUM_NODES, 0)
+ local parent = table.create(NUM_NODES, 0)
+ local freq = table.create(NUM_NODES, 0)
+ local group = table.create(NUM_NODES, 0)
+ local leafNodes = table.create(NUM_CODES, 0)
+ local groups = table.create(NUM_NODES, 0)
+ local leader = table.create(NUM_NODES, 0)
+ local numGroups = 0
+ local function initGroups()
+ for i = 0, NUM_NODES - 1 do
+ groups[i + 1] = i
+ end
+ numGroups = 0
+ end
+ local function allocGroup(): number
+ local g = groups[numGroups + 1]
+ numGroups += 1
+ return g
+ end
+ local function freeGroup(g: number)
+ numGroups -= 1
+ groups[numGroups + 1] = g
+ end
+ initGroups()
+ do
+ local ni = NUM_NODES - 1
+ local lg = allocGroup()
+ for i = 0, NUM_CODES - 1 do
+ leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg
+ leader[lg + 1] = ni
+ leafNodes[i + 1] = ni
+ ni -= 1
+ end
+ local c = NUM_NODES - 1
+ while ni >= 0 do
+ leaf[ni + 1], child[ni + 1] = false, c
+ parent[c + 1], parent[c] = ni, ni
+ freq[ni + 1] = freq[c + 1] + freq[c]
+ if freq[ni + 1] == freq[ni + 2] then
+ group[ni + 1] = group[ni + 2]
+ else
+ group[ni + 1] = allocGroup()
+ end
+ leader[group[ni + 1] + 1] = ni
+ ni -= 1
+ c -= 2
+ end
+ end
+ local function makeLeader(ni: number): number
+ local g = group[ni + 1]
+ local li = leader[g + 1]
+ if li == ni then
+ return ni
+ end
+ leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1]
+ child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1]
+ for _, x in { ni, li } do
+ if leaf[x + 1] then
+ leafNodes[child[x + 1] + 1] = x
+ else
+ parent[child[x + 1] + 1] = x
+ parent[child[x + 1]] = x
+ end
+ end
+ return li
+ end
+ local function incrementNode(ni: number)
+ freq[ni + 1] += 1
+ if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then
+ leader[group[ni + 1] + 1] += 1
+ if freq[ni + 1] == freq[ni] then
+ group[ni + 1] = group[ni]
+ else
+ group[ni + 1] = allocGroup()
+ leader[group[ni + 1] + 1] = ni
+ end
+ elseif freq[ni + 1] == freq[ni] then
+ freeGroup(group[ni + 1])
+ group[ni + 1] = group[ni]
+ end
+ end
+ local function reconstruct()
+ -- leaves to the front, halved
+ local li = 0
+ for i = 0, NUM_NODES - 1 do
+ if leaf[i + 1] then
+ leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], (freq[i + 1] + 1) // 2
+ li += 1
+ end
+ end
+ local lp = NUM_CODES - 1
+ local c = NUM_NODES - 1
+ local i = NUM_NODES - 1
+ while i >= 0 do
+ while c - i < 2 do
+ leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1]
+ leafNodes[child[i + 1] + 1] = i
+ i -= 1
+ lp -= 1
+ end
+ local f = freq[c + 1] + freq[c]
+ while lp >= 0 and f >= freq[lp + 1] do
+ leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1]
+ leafNodes[child[i + 1] + 1] = i
+ i -= 1
+ lp -= 1
+ end
+ leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c
+ parent[c + 1], parent[c] = i, i
+ i -= 1
+ c -= 2
+ end
+ initGroups()
+ local g = allocGroup()
+ group[1] = g
+ leader[g + 1] = 0
+ for k = 1, NUM_NODES - 1 do
+ if freq[k + 1] == freq[k] then
+ group[k + 1] = group[k]
+ else
+ g = allocGroup()
+ group[k + 1] = g
+ leader[g + 1] = k
+ end
+ end
+ end
+ local o = 0
+ while o < n do
+ local ni = 0
+ local guard = 0
+ while not leaf[ni + 1] do
+ ni = child[ni + 1] - bits(r, 1)
+ guard += 1
+ if guard > NUM_NODES or ni < 0 then
+ return "bad tree"
+ end
+ end
+ local code = child[ni + 1]
+ -- increment_for_code
+ if freq[1] >= REORDER then
+ reconstruct()
+ end
+ freq[1] += 1
+ local x = leafNodes[code + 1]
+ while x ~= 0 do
+ x = makeLeader(x)
+ incrementNode(x)
+ x = parent[x + 1]
+ end
+ if code < 256 then
+ writeu8(out, o, code)
+ o += 1
+ else
+ local future = peek(r, 8)
+ local hi = offsetLookup[future + 1]
+ skip(r, offsetLength[hi + 1])
+ local offset = hi * 64 + bits(r, 6)
+ local count = code - 256 + 3
+ local from = o - offset - 1
+ for _ = 1, count do
+ if o >= n then
+ break
+ end
+ writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20)
+ o += 1
+ from += 1
+ end
+ end
+ if r.over > 32 then
+ return "truncated"
+ end
+ end
+ return nil
+end
+
+-- ------------------------------------------------------------------------------------------------ LArc lzs / lz5
+-- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances)
+local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string?
+ local r = reader(src, off, len)
+ local ring = buffer.create(2048)
+ buffer.fill(ring, 0, 0x20)
+ local rp = 2048 - 17
+ local o = 0
+ while o < n do
+ if bits(r, 1) == 1 then
+ local b = bits(r, 8)
+ writeu8(out, o, b)
+ writeu8(ring, rp, b)
+ rp = (rp + 1) % 2048
+ o += 1
+ else
+ local pos = bits(r, 11)
+ local l = bits(r, 4) + 2
+ for k = 0, l - 1 do
+ if o >= n then
+ break
+ end
+ local b = readu8(ring, (pos + k) % 2048)
+ writeu8(out, o, b)
+ writeu8(ring, rp, b)
+ rp = (rp + 1) % 2048
+ o += 1
+ end
+ end
+ if r.over > 32 then
+ return "truncated"
+ end
+ end
+ return nil
+end
+
+local LZ5_INIT = buffer.create(4096)
+do
+ local p = 0
+ for i = 0, 255 do
+ for _ = 1, 13 do
+ writeu8(LZ5_INIT, p, i)
+ p += 1
+ end
+ end
+ for i = 0, 255 do
+ writeu8(LZ5_INIT, p, i)
+ p += 1
+ end
+ for i = 0, 255 do
+ writeu8(LZ5_INIT, p, 255 - i)
+ p += 1
+ end
+ p += 128
+ for _ = 1, 110 do
+ writeu8(LZ5_INIT, p, 0x20)
+ p += 1
+ end
+end
+
+local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string?
+ local ring = buffer.create(4096)
+ buffer.copy(ring, 0, LZ5_INIT)
+ local rp = 4096 - 18
+ local p = off
+ local limit = math.min(off + len, buffer.len(src))
+ local o = 0
+ while o < n do
+ if p >= limit then
+ return "truncated"
+ end
+ local flags = readu8(src, p)
+ p += 1
+ for bit = 0, 7 do
+ if o >= n then
+ break
+ end
+ if band(flags, lshift(1, bit)) ~= 0 then
+ if p >= limit then
+ return "truncated"
+ end
+ local b = readu8(src, p)
+ p += 1
+ writeu8(out, o, b)
+ writeu8(ring, rp, b)
+ rp = (rp + 1) % 4096
+ o += 1
+ else
+ if p + 2 > limit then
+ return "truncated"
+ end
+ local c0, c1 = readu8(src, p), readu8(src, p + 1)
+ p += 2
+ local start = lshift(band(c1, 0xF0), 4) + c0
+ local l = band(c1, 15) + 3
+ for k = 0, l - 1 do
+ if o >= n then
+ break
+ end
+ local b = readu8(ring, (start + k) % 4096)
+ writeu8(out, o, b)
+ writeu8(ring, rp, b)
+ rp = (rp + 1) % 4096
+ o += 1
+ end
+ end
+ end
+ end
+ return nil
+end
+
+-- ------------------------------------------------------------------------------------------------ ARJ method 4
+local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string?
+ local r = reader(src, off, len)
+ local function prefixed(start: number, stop: number): number
+ local plus, pwr = 0, lshift(1, start)
+ local width = start
+ while width < stop do
+ if bits(r, 1) == 0 then
+ break
+ end
+ plus += pwr
+ pwr *= 2
+ width += 1
+ end
+ return (if width ~= 0 then bits(r, width) else 0) + plus
+ end
+ local o = 0
+ while o < n do
+ local c = prefixed(0, 7)
+ if c == 0 then
+ writeu8(out, o, bits(r, 8))
+ o += 1
+ else
+ local count = c - 1 + 3
+ local pos = prefixed(9, 13)
+ local from = o - pos - 1
+ for _ = 1, count do
+ if o >= n then
+ break
+ end
+ writeu8(out, o, if from >= 0 then readu8(out, from) else 0)
+ o += 1
+ from += 1
+ end
+ end
+ if r.over > 32 then
+ return "truncated"
+ end
+ end
+ return nil
+end
+
+-- ------------------------------------------------------------------------------------------------ api
+Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" }
+
+-- decode(src, off, len, outSize, method) -> buffer | nil, message
+function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?)
+ if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then
+ return nil, "bad arguments"
+ end
+ local out = buffer.create(outSize)
+ if outSize == 0 then
+ return out, nil
+ end
+ local err: string?
+ if OFFSET_BITS[method] then
+ err = decodeNew(src, off, len, out, outSize, method)
+ elseif method == "lh1" then
+ err = decodeLh1(src, off, len, out, outSize)
+ elseif method == "lzs" then
+ err = decodeLzs(src, off, len, out, outSize)
+ elseif method == "lz5" then
+ err = decodeLz5(src, off, len, out, outSize)
+ elseif method == "arj4" then
+ err = decodeArj4(src, off, len, out, outSize)
+ else
+ return nil, "unsupported: method " .. tostring(method)
+ end
+ if err then
+ return nil, err
+ end
+ return out, nil
+end
+
+return Lzh
diff --git a/src/Formats/codecs/compress/Lzw/init.luau b/src/Formats/codecs/compress/Lzw/init.luau
index a399b9f..a4584f4 100644
--- a/src/Formats/codecs/compress/Lzw/init.luau
+++ b/src/Formats/codecs/compress/Lzw/init.luau
@@ -8,9 +8,11 @@
-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code
-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is
-- detected by its first bytes (0x00 then an odd byte) and decoded too.
+-- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only).
--
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff")
+-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo")
-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer
-- local codes = Lzw.encode(data, off, len, "tiff")
--
@@ -24,13 +26,14 @@ local blen = buffer.len
local Lzw = {}
-local MAX_CODES = 4096
+local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF)
+local TABLE = 8192 -- the tables hold 13-bit codes (Zoo)
-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield)
-local prefix = buffer.create(MAX_CODES * 2) -- u16: the code this entry extends
-local suffix = buffer.create(MAX_CODES) -- u8: its last byte
-local first = buffer.create(MAX_CODES) -- u8: its first byte
-local length = buffer.create(MAX_CODES * 2) -- u16: its length
+local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends
+local suffix = buffer.create(TABLE) -- u8: its last byte
+local first = buffer.create(TABLE) -- u8: its first byte
+local length = buffer.create(TABLE * 2) -- u16: its length
-- ------------------------------------------------------------------------------------------------ decode
-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim)
@@ -66,6 +69,10 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
local msb = variant == "tiff"
local early = 0 -- 1 for TIFF's early change
local min = minCodeSize or 8
+ local maxCodes, maxBits = MAX_CODES, 12
+ if variant == "zoo" then
+ min, maxCodes, maxBits = 8, TABLE, 13
+ end
if msb then
min = 8
early = 1
@@ -94,7 +101,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
local p = off
local acc, nb = 0, 0
while true do
- -- refill (at most 12 + 7 bits held: below 2^20)
+ -- refill (at most 13 + 7 bits held: below 2^21)
while nb < size do
if p >= e then
return o - outOff, "truncated"
@@ -140,14 +147,14 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
if c < nextc then
l = readu16(length, c * 2)
emit(out, o, c, l, lim)
- if nextc < MAX_CODES then
+ if nextc < maxCodes then
writeu16(prefix, nextc * 2, prev)
writeu8(suffix, nextc, readu8(first, c))
writeu8(first, nextc, readu8(first, prev))
writeu16(length, nextc * 2, readu16(length, prev * 2) + 1)
nextc += 1
end
- elseif c == nextc and nextc < MAX_CODES then
+ elseif c == nextc and nextc < maxCodes then
-- KwKwK: the new entry is prev + first(prev)
local f = readu8(first, prev)
writeu16(prefix, nextc * 2, prev)
@@ -163,7 +170,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
o = math.min(o + l, lim)
prev = c
end
- if nextc + early >= lshift(1, size) and size < 12 then
+ if nextc + early >= lshift(1, size) and size < maxBits then
size += 1
mask = lshift(1, size) - 1
end
diff --git a/src/Formats/codecs/compress/Lzx.luau b/src/Formats/codecs/compress/Lzx.luau
new file mode 100644
index 0000000..35a57fc
--- /dev/null
+++ b/src/Formats/codecs/compress/Lzx.luau
@@ -0,0 +1,449 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
+-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and
+-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19),
+-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the
+-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets
+-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification
+-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from
+-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants).
+--
+-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message
+--
+-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact
+-- uncompressed size. Never throws: bad or truncated data returns nil, message.
+local Huffman = require("@formats/codecs/entropy/Huffman")
+
+local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
+local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32
+local writeu8, writei32 = buffer.writeu8, buffer.writei32
+local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
+
+local Lzx = {}
+
+local FRAME = 32768
+local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6
+local MAXMAIN = 256 + 8 * 50
+local NLEN = 249
+local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder)
+
+-- position slots: footer bits and base of each formatted offset slot
+local EXTRA = table.create(51, 0)
+local BASE = table.create(51, 0)
+do
+ local b = 0
+ for i = 0, 50 do
+ local e = if i < 4 then 0 else math.min(i // 2 - 1, 17)
+ EXTRA[i + 1] = e
+ BASE[i + 1] = b
+ b += lshift(1, e)
+ end
+end
+local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 }
+
+-- ------------------------------------------------------------------------------------------------ bit reader
+-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the
+-- end, zero words are read and over counts their bits.
+type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number }
+
+local function refill(s: State)
+ while s.cnt <= 16 do
+ local p = s.pos
+ local w = 0
+ if p + 2 <= s.stop then
+ w = readu16(s.src, p)
+ s.pos = p + 2
+ elseif p < s.stop then
+ w = readu8(s.src, p)
+ s.pos = p + 1
+ s.over += 8
+ else
+ s.over += 16
+ end
+ s.bb = bor(s.bb, lshift(w, 16 - s.cnt))
+ s.cnt += 16
+ end
+end
+
+-- bits(s, n) -> the next n (1..17) bits
+local function bits(s: State, n: number): number
+ if s.cnt < n then
+ refill(s)
+ end
+ local v = rshift(s.bb, 32 - n)
+ s.bb = lshift(s.bb, n)
+ s.cnt -= n
+ return v
+end
+
+-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code
+local function sym(s: State, tab: buffer, P: number, S: number): number
+ if s.cnt < 16 then
+ refill(s)
+ end
+ local e = readu32(tab, rshift(s.bb, 32 - P) * 4)
+ local l = band(e, 31)
+ if l == 0 then
+ if e == 0 then
+ return -1
+ end
+ e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4)
+ l = band(e, 31)
+ if l == 0 then
+ return -1
+ end
+ end
+ s.bb = lshift(s.bb, l)
+ s.cnt -= l
+ return rshift(e, 5)
+end
+
+-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree
+local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean
+ for i = 0, 19 do
+ writeu8(preLens, i, bits(s, 4))
+ end
+ local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP)
+ if S < 0 then
+ return false
+ end
+ local cap = blen(lens)
+ local x = first
+ while x < last do
+ local z = sym(s, pre, PREP, S)
+ if z < 0 then
+ return false
+ end
+ if z == 17 or z == 18 then
+ local run = if z == 17 then bits(s, 4) + 4 else bits(s, 5) + 20
+ for _ = 1, run do
+ if x < cap then
+ writeu8(lens, x, 0)
+ end
+ x += 1
+ end
+ elseif z == 19 then
+ local run = bits(s, 1) + 4
+ local d = sym(s, pre, PREP, S)
+ if d < 0 or d > 16 then
+ return false
+ end
+ local v = (readu8(lens, x) - d + 17) % 17
+ for _ = 1, run do
+ if x < cap then
+ writeu8(lens, x, v)
+ end
+ x += 1
+ end
+ else
+ writeu8(lens, x, (readu8(lens, x) - z + 17) % 17)
+ x += 1
+ end
+ end
+ return true
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative)
+local function translate(out: buffer, n: number, size: number)
+ local base = 0
+ local frame = 0
+ while base < n and frame < 32768 do
+ local fs = math.min(FRAME, n - base)
+ if fs > 10 then
+ local i = base
+ local stop = base + fs - 10
+ while i < stop do
+ if readu8(out, i) == 0xE8 then
+ local abs = readi32(out, i + 1)
+ if abs >= -i and abs < size then
+ writei32(out, i + 1, if abs >= 0 then abs - i else abs + size)
+ end
+ i += 5
+ else
+ i += 1
+ end
+ end
+ end
+ base += fs
+ frame += 1
+ end
+end
+
+function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?)
+ local nslots = SLOTS[windowBits]
+ if not nslots then
+ return nil, "unsupported: LZX window 2^" .. tostring(windowBits)
+ end
+ if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then
+ return nil, "bad arguments"
+ end
+ local windowSize = lshift(1, windowBits)
+ local mainN = 256 + 8 * nslots
+ local out = bcreate(outSize)
+ local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20)
+ local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4)
+ local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4)
+ local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4)
+ local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4)
+ local s: State = { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 }
+ local R0: number, R1: number, R2: number = 1, 1, 1
+ local intel = 0
+ local started = false
+ local btype, bremain, bsize = 0, 0, 0
+ local mainS, lenS, alignS = 0, 0, 0
+ local op = 0
+ while op < outSize do
+ local frameEnd = math.min(op + FRAME, outSize)
+ while op < frameEnd do
+ if bremain == 0 then
+ -- a new block
+ if btype == 3 and band(bsize, 1) == 1 then
+ s.pos += 1
+ end
+ if not started then
+ started = true
+ if bits(s, 1) == 1 then
+ local hi = bits(s, 16)
+ intel = hi * 65536 + bits(s, 16)
+ end
+ end
+ btype = bits(s, 3)
+ local hi = bits(s, 16)
+ bsize = hi * 256 + bits(s, 8)
+ bremain = bsize
+ if s.over > s.cnt then
+ return nil, "truncated input"
+ end
+ if bsize == 0 then
+ return nil, "empty block"
+ end
+ if btype == 2 then
+ for i = 0, 7 do
+ writeu8(alignLens, i, bits(s, 3))
+ end
+ alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP)
+ if alignS < 0 then
+ return nil, "bad aligned offset tree"
+ end
+ end
+ if btype == 1 or btype == 2 then
+ if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then
+ return nil, "bad main tree"
+ end
+ mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP)
+ if mainS < 0 then
+ return nil, "bad main tree"
+ end
+ if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then
+ return nil, "bad length tree"
+ end
+ lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP)
+ if lenS < 0 then
+ return nil, "bad length tree"
+ end
+ elseif btype == 3 then
+ -- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes
+ local k = s.cnt % 16
+ if k == 0 then
+ k = 16
+ end
+ local p = s.pos - (s.cnt - k) // 8
+ s.bb, s.cnt = 0, 0
+ if s.over > 0 or p + 12 > s.stop then
+ return nil, "truncated uncompressed block"
+ end
+ R0 = readu32(src, p)
+ R1 = readu32(src, p + 4)
+ R2 = readu32(src, p + 8)
+ s.pos = p + 12
+ else
+ return nil, "bad block type " .. btype
+ end
+ if s.over > s.cnt then
+ return nil, "truncated input"
+ end
+ end
+ local runEnd = op + math.min(bremain, frameEnd - op)
+ if btype == 3 then
+ local n = runEnd - op
+ local p = s.pos
+ if p + n > s.stop then
+ return nil, "truncated uncompressed block"
+ end
+ bcopy(out, op, src, p, n)
+ s.pos = p + n
+ op += n
+ bremain -= n
+ else
+ local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over
+ local stop = s.stop
+ local aligned = btype == 2
+ local start = op
+ while op < runEnd do
+ -- refill to at least 17 bits
+ while cnt <= 16 do
+ local w = 0
+ if pos + 2 <= stop then
+ w = readu16(src, pos)
+ pos += 2
+ elseif pos < stop then
+ w = readu8(src, pos)
+ pos += 1
+ over += 8
+ else
+ over += 16
+ end
+ bb = bor(bb, lshift(w, 16 - cnt))
+ cnt += 16
+ end
+ local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4)
+ local l = band(e, 31)
+ if l == 0 then
+ if e == 0 then
+ return nil, "bad main code"
+ end
+ e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4)
+ l = band(e, 31)
+ if l == 0 then
+ return nil, "bad main code"
+ end
+ end
+ bb = lshift(bb, l)
+ cnt -= l
+ local m = rshift(e, 5)
+ if m < 256 then
+ writeu8(out, op, m)
+ op += 1
+ else
+ m -= 256
+ local len = band(m, 7)
+ if len == 7 then
+ while cnt <= 16 do
+ local w = 0
+ if pos + 2 <= stop then
+ w = readu16(src, pos)
+ pos += 2
+ else
+ over += 16
+ end
+ bb = bor(bb, lshift(w, 16 - cnt))
+ cnt += 16
+ end
+ local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4)
+ local ll = band(le, 31)
+ if ll == 0 then
+ if le == 0 then
+ return nil, "bad length code"
+ end
+ le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4)
+ ll = band(le, 31)
+ if ll == 0 then
+ return nil, "bad length code"
+ end
+ end
+ bb = lshift(bb, ll)
+ cnt -= ll
+ len += rshift(le, 5)
+ end
+ len += 2
+ local slot = rshift(m, 3)
+ local dist: number
+ if slot == 0 then
+ dist = R0
+ elseif slot == 1 then
+ dist = R1
+ R1 = R0
+ R0 = dist
+ elseif slot == 2 then
+ dist = R2
+ R2 = R0
+ R0 = dist
+ else
+ local ex = EXTRA[slot + 1]
+ dist = BASE[slot + 1] - 2
+ if ex > 0 then
+ while cnt <= 16 do
+ local w = 0
+ if pos + 2 <= stop then
+ w = readu16(src, pos)
+ pos += 2
+ else
+ over += 16
+ end
+ bb = bor(bb, lshift(w, 16 - cnt))
+ cnt += 16
+ end
+ if aligned and ex >= 3 then
+ if ex > 3 then
+ dist += lshift(rshift(bb, 35 - ex), 3)
+ bb = lshift(bb, ex - 3)
+ cnt -= ex - 3
+ while cnt <= 16 do
+ local w = 0
+ if pos + 2 <= stop then
+ w = readu16(src, pos)
+ pos += 2
+ else
+ over += 16
+ end
+ bb = bor(bb, lshift(w, 16 - cnt))
+ cnt += 16
+ end
+ end
+ local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4)
+ local al = band(ae, 31)
+ if al == 0 then
+ return nil, "bad aligned offset code"
+ end
+ bb = lshift(bb, al)
+ cnt -= al
+ dist += rshift(ae, 5)
+ else
+ dist += rshift(bb, 32 - ex)
+ bb = lshift(bb, ex)
+ cnt -= ex
+ end
+ end
+ R2 = R1
+ R1 = R0
+ R0 = dist
+ end
+ if dist < 1 or dist > op or dist > windowSize then
+ return nil, "match offset before the start of the data"
+ end
+ if op + len > runEnd then
+ return nil, "match past the end of its block or frame"
+ end
+ local from = op - dist
+ if dist >= len then
+ bcopy(out, op, out, from, len)
+ else
+ for k = 0, len - 1 do
+ writeu8(out, op + k, readu8(out, from + k))
+ end
+ end
+ op += len
+ end
+ end
+ s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over
+ bremain -= op - start
+ end
+ end
+ -- the end of a frame: realign to 16 bits
+ local k = s.cnt % 16
+ s.bb = lshift(s.bb, k)
+ s.cnt -= k
+ if s.over > s.cnt then
+ return nil, "truncated input"
+ end
+ end
+ if intel ~= 0 then
+ translate(out, outSize, intel)
+ end
+ return out, nil
+end
+
+return Lzx
diff --git a/src/Formats/codecs/compress/Quantum.luau b/src/Formats/codecs/compress/Quantum.luau
new file mode 100644
index 0000000..ec833ce
--- /dev/null
+++ b/src/Formats/codecs/compress/Quantum.luau
@@ -0,0 +1,251 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft
+-- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with
+-- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the
+-- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the
+-- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and
+-- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the
+-- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the
+-- models and the window persist across the frames of a folder. Written from the public descriptions of the format
+-- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack.
+--
+-- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message
+--
+-- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is
+-- their total. Never throws: bad or truncated data returns nil, message.
+
+local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
+local floor = math.floor
+
+local Quantum = {}
+
+-- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer)
+local PBASE = table.create(42, 0)
+local PEXTRA = table.create(42, 0)
+do
+ local b = 0
+ for i = 0, 41 do
+ local e = if i < 4 then 0 else i // 2 - 1
+ PEXTRA[i + 1] = e
+ PBASE[i + 1] = b
+ b += lshift(1, e)
+ end
+end
+local 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 }
+local LBASE = table.create(27, 0)
+do
+ local b = 0
+ for i = 1, 27 do
+ LBASE[i] = b
+ b += lshift(1, LEXTRA[i])
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ models
+-- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0)
+type Model = { n: number, sym: { number }, cum: { number }, shifts: number }
+
+local function model(first: number, n: number): Model
+ local sym = table.create(n, 0)
+ local cum = table.create(n + 1, 0)
+ for i = 1, n do
+ sym[i] = first + i - 1
+ cum[i] = n - i + 1
+ end
+ cum[n + 1] = 0
+ return { n = n, sym = sym, cum = cum, shifts = 4 }
+end
+
+local function rescale(m: Model)
+ local n, sym, cum = m.n, m.sym, m.cum
+ m.shifts -= 1
+ if m.shifts > 0 then
+ for i = n, 1, -1 do
+ local c = rshift(cum[i], 1)
+ if c <= cum[i + 1] then
+ c = cum[i + 1] + 1
+ end
+ cum[i] = c
+ end
+ return
+ end
+ m.shifts = 50
+ -- cumulative -> halved frequencies (rounded up: no symbol drops to zero)
+ for i = 1, n do
+ cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1)
+ end
+ -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's)
+ for i = 1, n - 1 do
+ for j = i + 1, n do
+ if cum[i] < cum[j] then
+ cum[i], cum[j] = cum[j], cum[i]
+ sym[i], sym[j] = sym[j], sym[i]
+ end
+ end
+ end
+ for i = n, 1, -1 do
+ cum[i] += cum[i + 1]
+ end
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the coder and bit reader of one frame
+type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean }
+
+local function bit(c: Coder): number
+ if c.cnt == 0 then
+ local p = c.pos
+ if p < c.stop then
+ c.acc = readu8(c.src, p)
+ c.pos = p + 1
+ else
+ c.acc = 0
+ c.over += 1
+ end
+ c.cnt = 8
+ end
+ c.cnt -= 1
+ return band(rshift(c.acc, c.cnt), 1)
+end
+
+-- raw(c, n) -> the next n (0..19) bits, most significant first
+local function raw(c: Coder, n: number): number
+ local v = 0
+ for _ = 1, n do
+ v = v * 2 + bit(c)
+ end
+ return v
+end
+
+local function symbol(c: Coder, m: Model): number
+ local cum = m.cum
+ local H, L, C = c.H, c.L, c.C
+ local range = H - L + 1
+ local total = cum[1]
+ if range <= 0 or C < L or C > H then
+ -- only corrupt registers get here (the decoder keeps L <= C <= H)
+ c.bad = true
+ return 0
+ end
+ local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF)
+ local n = m.n
+ local i = 2
+ while i <= n and cum[i] > f do
+ i += 1
+ end
+ -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1])
+ local s = m.sym[i - 1]
+ H = L + floor(cum[i - 1] * range / total) - 1
+ L = L + floor(cum[i] * range / total)
+ for k = 1, i - 1 do
+ cum[k] += 8
+ end
+ if cum[1] > 3800 then
+ rescale(m)
+ end
+ while true do
+ if band(bxor(L, H), 0x8000) ~= 0 then
+ if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then
+ -- underflow: L and H straddle the middle
+ C = bxor(C, 0x4000)
+ L = band(L, 0x3FFF)
+ H = bor(H, 0x4000)
+ else
+ break
+ end
+ end
+ L = band(lshift(L, 1), 0xFFFF)
+ H = bor(band(lshift(H, 1), 0xFFFF), 1)
+ C = bor(band(lshift(C, 1), 0xFFFF), bit(c))
+ end
+ c.H, c.L, c.C = H, L, C
+ return s
+end
+
+function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?)
+ if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then
+ return nil, "unsupported: Quantum window 2^" .. tostring(windowBits)
+ end
+ if outSize < 0 or outSize % 1 ~= 0 then
+ return nil, "bad output size"
+ end
+ local total = 0
+ for _, b in blocks do
+ if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then
+ return nil, "bad block range"
+ end
+ total += b.size
+ end
+ if total ~= outSize then
+ return nil, "block sizes do not add up to the output size"
+ end
+ local window = lshift(1, windowBits)
+ local slots = windowBits * 2
+ local selector = model(0, 7)
+ local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) }
+ local m3 = model(0, math.min(slots, 24))
+ local m4 = model(0, math.min(slots, 36))
+ local m5 = model(0, slots)
+ local mlen = model(0, 27)
+ local out = bcreate(outSize)
+ local op = 0
+ for _, b in blocks do
+ local frameEnd = op + b.size
+ local c: Coder = { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false }
+ c.C = raw(c, 16)
+ while op < frameEnd do
+ local sel = symbol(c, selector)
+ if c.bad then
+ return nil, "bad arithmetic code"
+ end
+ if sel < 4 then
+ writeu8(out, op, symbol(c, lit[sel + 1]))
+ op += 1
+ else
+ local len, slot
+ if sel == 4 then
+ len = 3
+ slot = symbol(c, m3)
+ elseif sel == 5 then
+ len = 4
+ slot = symbol(c, m4)
+ elseif sel == 6 then
+ local ls = symbol(c, mlen)
+ len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5
+ slot = symbol(c, m5)
+ else
+ return nil, "bad selector"
+ end
+ local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1
+ if dist > op or dist > window then
+ return nil, "match offset before the start of the data"
+ end
+ if op + len > frameEnd then
+ return nil, "match past the end of its frame"
+ end
+ local from = op - dist
+ if dist >= len then
+ bcopy(out, op, out, from, len)
+ else
+ for k = 0, len - 1 do
+ writeu8(out, op + k, readu8(out, from + k))
+ end
+ end
+ op += len
+ end
+ if c.bad then
+ return nil, "bad arithmetic code"
+ end
+ if c.over > 4 then
+ return nil, "truncated frame"
+ end
+ end
+ end
+ return out, nil
+end
+
+return Quantum
diff --git a/src/Formats/codecs/compress/UnixCompress.luau b/src/Formats/codecs/compress/UnixCompress.luau
new file mode 100644
index 0000000..7f54dd8
--- /dev/null
+++ b/src/Formats/codecs/compress/UnixCompress.luau
@@ -0,0 +1,319 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
+-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are
+-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the
+-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width
+-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder
+-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked
+-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read
+-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws.
+--
+-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file
+-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+
+local UnixCompress = {}
+
+export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30)
+export type EncodeOptions = { maxBits: number? } -- 9..16, default 16
+
+local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
+local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
+local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
+
+local MAXCODES = 65536
+local CHECK_GAP = 10000
+
+-- decoder tables (per call state lives in locals; the tables are reused: decode never yields)
+local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends
+local suffix = bcreate(MAXCODES) -- u8: its last byte
+local first = bcreate(MAXCODES) -- u8: its first byte
+local length = bcreate(MAXCODES * 4) -- u32: its length
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err
+function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
+ local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len)
+ if not b then
+ return nil, aerr
+ end
+ local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
+ if n < 3 then
+ return nil, Err.new(Err.TRUNCATED, "header past the end", o)
+ end
+ if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then
+ return nil, Err.new(Err.CORRUPT, "bad magic", o)
+ end
+ local flags = readu8(b, o + 2)
+ local maxbits = band(flags, 0x1F)
+ local block = band(flags, 0x80) ~= 0
+ if maxbits < 9 or maxbits > 16 then
+ return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2)
+ end
+ if band(flags, 0x60) ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2)
+ end
+ local maxmax = lshift(1, maxbits)
+ for i = 0, 255 do
+ writeu32(prefix, i * 4, 0)
+ writeu8(suffix, i, i)
+ writeu8(first, i, i)
+ writeu32(length, i * 4, 1)
+ end
+ local cap = math.min(math.max(n * 3, 1024), maxBytes)
+ local out = bcreate(cap)
+ local op = 0
+ local totalBits = (n - 3) * 8
+ local base = o + 3
+ local pos = 0 -- bit position from the first code
+ local gbase = 0 -- where the current group sequence starts
+ local nbits = 9
+ local mask = 511
+ local maxcode = 511
+ local freeEnt = if block then 257 else 256
+ local prev = -1
+ while pos + nbits <= totalBits do
+ if freeEnt > maxcode then
+ local g = nbits * 8
+ pos = gbase + (pos - gbase + g - 1) // g * g
+ gbase = pos
+ nbits += 1
+ maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1
+ mask = lshift(1, nbits) - 1
+ continue
+ end
+ -- the code: up to 23 bits from three bytes
+ local q = base + rshift(pos, 3)
+ local acc = readu8(b, q)
+ if q + 1 < o + n then
+ acc = bor(acc, lshift(readu8(b, q + 1), 8))
+ end
+ if q + 2 < o + n then
+ acc = bor(acc, lshift(readu8(b, q + 2), 16))
+ end
+ local c = band(rshift(acc, band(pos, 7)), mask)
+ pos += nbits
+ if c == 256 and block then
+ local g = nbits * 8
+ pos = gbase + (pos - gbase + g - 1) // g * g
+ gbase = pos
+ nbits = 9
+ mask = 511
+ maxcode = 511
+ freeEnt = 257
+ prev = -1
+ continue
+ end
+ local l
+ if prev < 0 then
+ if c >= 256 then
+ return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3))
+ end
+ l = 1
+ elseif c < freeEnt then
+ l = readu32(length, c * 4)
+ elseif c == freeEnt then
+ l = readu32(length, prev * 4) + 1
+ else
+ return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
+ end
+ if op + l > cap then
+ if op + l > maxBytes then
+ return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes")
+ end
+ local ncap = math.min(math.max(cap * 2, op + l), maxBytes)
+ local nb = bcreate(ncap)
+ bcopy(nb, 0, out, 0, op)
+ out, cap = nb, ncap
+ end
+ -- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it
+ if prev >= 0 and freeEnt < maxmax then
+ local f = if c == freeEnt then readu8(first, prev) else readu8(first, c)
+ writeu32(prefix, freeEnt * 4, prev)
+ writeu8(suffix, freeEnt, f)
+ writeu8(first, freeEnt, readu8(first, prev))
+ writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1)
+ freeEnt += 1
+ elseif prev >= 0 then
+ if c == freeEnt then
+ return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
+ end
+ end
+ local p = op + l - 1
+ local k = c
+ while p >= op do
+ writeu8(out, p, readu8(suffix, k))
+ k = readu32(prefix, k * 4)
+ p -= 1
+ end
+ op += l
+ prev = c
+ end
+ local res = bcreate(op)
+ bcopy(res, 0, out, 0, op)
+ return res, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
+local hkey = bcreate(HSIZE * 4)
+local hval = bcreate(HSIZE * 4)
+
+-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err
+function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len)
+ if not b then
+ return nil, aerr
+ end
+ local maxbits = (opts and opts.maxBits) or 16
+ if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "maxBits must be 9..16")
+ end
+ -- at most 17 bits per input byte, plus group padding (< one group per width change / clear)
+ local cap = 3 + n * 2 + 64
+ local out = bcreate(cap)
+ writeu8(out, 0, 0x1F)
+ writeu8(out, 1, 0x9D)
+ writeu8(out, 2, bor(maxbits, 0x80))
+ local outbits = 24
+ local boff = 24
+ local acc, nb = 0, 0 -- pending bits not yet written (below 2^24)
+ local nbits = 9
+ local extcode = 513
+ local maxmax = lshift(1, maxbits)
+ local stcode = true
+ local freeEnt = 257
+ local ratio = 0
+ local checkpoint = CHECK_GAP
+ buffer.fill(hkey, 0, 0, HSIZE * 4)
+ local function put(code: number)
+ acc = bor(acc, lshift(code, nb))
+ nb += nbits
+ outbits += nbits
+ while nb >= 8 do
+ local q = rshift(outbits - nb, 3)
+ if q < cap then
+ writeu8(out, q, band(acc, 255))
+ end
+ acc = rshift(acc, 8)
+ nb -= 8
+ end
+ end
+ local function align()
+ -- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros
+ local g = nbits * 8
+ local nbits2 = boff + (outbits - boff + g - 1) // g * g
+ if nb > 0 then
+ local q = rshift(outbits - nb, 3)
+ if q < cap then
+ writeu8(out, q, band(acc, 255))
+ end
+ end
+ acc, nb = 0, 0
+ outbits = nbits2
+ boff = nbits2
+ end
+ if n == 0 then
+ local res = bcreate(3)
+ bcopy(res, 0, out, 0, 3)
+ return res, nil
+ end
+ local ent = readu8(b, o)
+ local e = o + n
+ local i = o + 1
+ -- checks happen with a one-byte current string, right after an output (and at the start)
+ local function checks(consumed: number)
+ if freeEnt >= extcode then
+ if nbits < maxbits then
+ align()
+ nbits += 1
+ extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits)
+ else
+ extcode = math.huge
+ stcode = false
+ end
+ end
+ if not stcode and consumed >= checkpoint then
+ checkpoint = consumed + CHECK_GAP
+ local outBytes = rshift(outbits, 3)
+ local rat
+ if consumed > 0x7FFFFF then
+ local d = rshift(outBytes, 8)
+ rat = if d == 0 then 0x7FFFFFFF else consumed // d
+ else
+ rat = (consumed * 256) // outBytes
+ end
+ if rat >= ratio then
+ ratio = rat
+ else
+ ratio = 0
+ buffer.fill(hkey, 0, 0, HSIZE * 4)
+ put(256)
+ align()
+ nbits = 9
+ extcode = 513
+ freeEnt = 257
+ stcode = true
+ end
+ end
+ end
+ checks(1)
+ while i < e do
+ local c = readu8(b, i)
+ i += 1
+ local key = ent * 256 + c + 1
+ local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1)
+ local found = -1
+ while true do
+ local k = readu32(hkey, h * 4)
+ if k == 0 then
+ break
+ elseif k == key then
+ found = readu32(hval, h * 4)
+ break
+ end
+ h = band(h + 1, HSIZE - 1)
+ end
+ if found >= 0 then
+ ent = found
+ else
+ put(ent)
+ if stcode then
+ writeu32(hkey, h * 4, key)
+ writeu32(hval, h * 4, freeEnt)
+ freeEnt += 1
+ end
+ ent = c
+ checks(i - o)
+ end
+ if rshift(outbits, 3) + 8 > cap then
+ -- grow (rare: only incompressible input passes 2 bytes per byte)
+ local ncap = cap * 2
+ local nbuf = bcreate(ncap)
+ bcopy(nbuf, 0, out, 0, cap)
+ out, cap = nbuf, ncap
+ end
+ end
+ put(ent)
+ if nb > 0 then
+ local q = rshift(outbits - nb, 3)
+ if q < cap then
+ writeu8(out, q, band(acc, 255))
+ end
+ end
+ local size = rshift(outbits + 7, 3)
+ local res = bcreate(size)
+ bcopy(res, 0, out, 0, math.min(size, cap))
+ return res, nil
+end
+
+-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file
+function UnixCompress.isCompress(b: buffer, o: number?): boolean
+ local p = o or 0
+ return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D
+end
+
+return UnixCompress
diff --git a/src/Formats/codecs/compress/Xxh32.luau b/src/Formats/codecs/compress/Xxh32.luau
new file mode 100644
index 0000000..121a6f8
--- /dev/null
+++ b/src/Formats/codecs/compress/Xxh32.luau
@@ -0,0 +1,72 @@
+--!strict
+--!native
+--!optimize 2
+-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
+-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
+-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer).
+--
+-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1
+local Xxh32 = {}
+
+local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift
+local readu8, readu32 = buffer.readu8, buffer.readu32
+
+local T32 = 4294967296
+local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1
+
+-- a * b mod 2^32 (a, b below 2^32)
+local function mul(a: number, b: number): number
+ local a0 = a % 65536
+ local a1 = (a - a0) / 65536
+ return (a0 * b + ((a1 * b) % 65536) * 65536) % T32
+end
+
+local function rotl(x: number, r: number): number
+ return bor(lshift(x, r), rshift(x, 32 - r))
+end
+
+local function round(acc: number, lane: number): number
+ return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1)
+end
+
+-- hash(buf, offset?, length?, seed?) -> XXH32
+function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number
+ local n0 = buffer.len(b)
+ local o = math.clamp(offset or 0, 0, n0)
+ local n = math.clamp(length or (n0 - o), 0, n0 - o)
+ local s = (seed or 0) % T32
+ local p = o
+ local e = o + n
+ local h
+ if n >= 16 then
+ local v1 = (s + P1 + P2) % T32
+ local v2 = (s + P2) % T32
+ local v3 = s
+ local v4 = (s - P1) % T32
+ local last = e - 16
+ while p <= last do
+ v1 = round(v1, readu32(b, p))
+ v2 = round(v2, readu32(b, p + 4))
+ v3 = round(v3, readu32(b, p + 8))
+ v4 = round(v4, readu32(b, p + 12))
+ p += 16
+ end
+ h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32
+ else
+ h = (s + P5) % T32
+ end
+ h = (h + n) % T32
+ while p + 4 <= e do
+ h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4)
+ p += 4
+ end
+ while p < e do
+ h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1)
+ p += 1
+ end
+ h = mul(bxor(h, rshift(h, 15)), P2)
+ h = mul(bxor(h, rshift(h, 13)), P3)
+ return bxor(h, rshift(h, 16))
+end
+
+return Xxh32
diff --git a/src/Formats/codecs/font/Bitmap.luau b/src/Formats/codecs/font/Bitmap.luau
new file mode 100644
index 0000000..edda49f
--- /dev/null
+++ b/src/Formats/codecs/font/Bitmap.luau
@@ -0,0 +1,220 @@
+--!strict
+-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike
+-- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels
+-- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's
+-- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored,
+-- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an
+-- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row
+-- packing every bitmap font format shares. New code.
+--
+-- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } })
+-- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized
+-- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255
+-- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer)
+--
+-- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0).
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+
+local Bitmap = {}
+
+local readu8, writeu8 = buffer.readu8, buffer.writeu8
+
+-- ------------------------------------------------------------------------------------------------ bits
+-- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left
+-- pixel unless lsbFirst); bytes past the end of buf read as 0
+function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer
+ local out = buffer.create(math.max(0, w * h))
+ local n = buffer.len(b)
+ for y = 0, h - 1 do
+ local row = off + y * stride
+ for x = 0, w - 1 do
+ local p = row + bit32.rshift(x, 3)
+ if p >= 0 and p < n then
+ local byte = readu8(b, p)
+ local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7)
+ if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then
+ writeu8(out, y * w + x, 255)
+ end
+ end
+ end
+ end
+ return out
+end
+
+-- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on
+function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer
+ local s = stride or math.ceil(w / 8)
+ local out = buffer.create(math.max(0, s * h))
+ local n = buffer.len(px)
+ for y = 0, h - 1 do
+ for x = 0, w - 1 do
+ local i = y * w + x
+ if i < n and readu8(px, i) >= 128 then
+ local p = y * s + bit32.rshift(x, 3)
+ local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7)
+ writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn)))
+ end
+ end
+ end
+ return out
+end
+
+-- ------------------------------------------------------------------------------------------------ font
+local Face = {}
+Face.__index = Face
+
+function Face.glyphIndex(self: any, cp: number): number
+ return self._index[cp] or 0
+end
+
+function Face.advance(self: any, g: number): number
+ local gl = self.bitmap.glyphs[g + 1]
+ return if gl then gl.advance else 0
+end
+
+function Face.kern(_self: any, _a: number, _b: number): number
+ return 0
+end
+
+function Face.outline(_self: any, _g: number): { any }?
+ return nil
+end
+
+-- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size)
+function Face.rasterize(self: any, g: number, px: number?): Types.Image?
+ local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1]
+ if not gl or gl.width < 0 or gl.height < 0 then
+ return nil
+ end
+ local img = Types.Image.new(gl.width, gl.height, "alpha8")
+ local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels))
+ if n > 0 then
+ buffer.copy(img.pixels, 0, gl.pixels, 0, n)
+ end
+ img.meta.left = gl.left
+ img.meta.top = gl.top
+ img.meta.advance = gl.advance
+ img.meta.glyph = g
+ img.meta.scale = if type(px) == "number" and self.bitmap.size > 0 then px / self.bitmap.size else 1
+ return img
+end
+
+-- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike)
+function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any
+ local index: { [number]: number } = {}
+ for i, gl in strike.glyphs do
+ local cp = gl.codepoint
+ if cp and index[cp] == nil then
+ index[cp] = i - 1
+ end
+ end
+ if strike.map then
+ for cp, g in strike.map do
+ if index[cp] == nil and g >= 0 and g < #strike.glyphs then
+ index[cp] = g
+ end
+ end
+ end
+ local f = setmetatable({
+ kind = "font",
+ info = info or {},
+ unitsPerEm = strike.size,
+ ascent = strike.ascent,
+ descent = -strike.descent,
+ lineGap = 0,
+ numGlyphs = #strike.glyphs,
+ bitmap = strike,
+ meta = meta or {},
+ _index = index,
+ }, Face)
+ if strike.default then
+ setmetatable(index, { __index = function()
+ return strike.default
+ end })
+ end
+ return f
+end
+
+-- ------------------------------------------------------------------------------------------------ strike
+export type StrikeOptions = {
+ px: number?, -- pixel size for outline fonts (default 16)
+ chars: (string | { number })?, -- code points for outline fonts (default 32..126)
+ threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128)
+}
+
+local function codepoints(chars: (string | { number })?): { number }
+ if type(chars) == "table" then
+ return chars
+ end
+ local out = {}
+ if type(chars) == "string" then
+ for _, c in utf8.codes(chars) do
+ table.insert(out, c)
+ end
+ return out
+ end
+ for c = 32, 126 do
+ table.insert(out, c)
+ end
+ return out
+end
+
+-- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px
+function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?)
+ if type(font) ~= "table" or font.kind ~= "font" then
+ return nil, Err.new(Err.ARG, "expected a Font")
+ end
+ if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then
+ return font.bitmap, nil
+ end
+ if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
+ return nil, Err.new(Err.ARG, "font has no glyphs to rasterize")
+ end
+ local o: StrikeOptions = opts or {}
+ local px = o.px or 16
+ if type(px) ~= "number" or px < 1 or px > 1024 then
+ return nil, Err.new(Err.ARG, "px must be 1..1024")
+ end
+ local threshold = o.threshold or 128
+ local upm = if type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 then font.unitsPerEm else px
+ local scale = px / upm
+ local ascent = math.ceil((font.ascent or upm) * scale)
+ local descent = math.ceil(math.abs(font.descent or 0) * scale)
+ local glyphs: { Types.BitmapGlyph } = {}
+ local function add(cp: number?, g: number)
+ local ok, img = pcall(font.rasterize, font, g, px)
+ local adv = 0
+ local aok, a = pcall(font.advance, font, g)
+ if aok and type(a) == "number" then
+ adv = math.floor(a * scale + 0.5)
+ end
+ local gl: Types.BitmapGlyph = { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) }
+ if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then
+ local n = img.width * img.height
+ local pxs = buffer.create(n)
+ for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do
+ if readu8(img.pixels, i) >= threshold then
+ writeu8(pxs, i, 255)
+ end
+ end
+ gl.width, gl.height, gl.pixels = img.width, img.height, pxs
+ gl.left = math.floor(img.meta.left or 0)
+ gl.top = math.floor(img.meta.top or 0)
+ if type(img.meta.advance) == "number" then
+ gl.advance = math.floor(img.meta.advance + 0.5)
+ end
+ end
+ table.insert(glyphs, gl)
+ end
+ add(nil, 0)
+ for _, cp in codepoints(o.chars) do
+ local ok, g = pcall(font.glyphIndex, font, cp)
+ if ok and type(g) == "number" and g > 0 then
+ add(cp, g)
+ end
+ end
+ return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil
+end
+
+return Bitmap
diff --git a/src/Formats/codecs/font/GlyphNames.luau b/src/Formats/codecs/font/GlyphNames.luau
new file mode 100644
index 0000000..4130e91
--- /dev/null
+++ b/src/Formats/codecs/font/GlyphNames.luau
@@ -0,0 +1,154 @@
+--!strict
+-- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
+-- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause:
+-- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and
+-- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name).
+-- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding.
+--
+-- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown)
+-- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef)
+local GlyphNames = {}
+
+-- AGLFN: "name hex" pairs
+local AGL = "" ..
+ "A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " ..
+ "Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " ..
+ "106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " ..
+ "2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " ..
+ "Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " ..
+ "F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " ..
+ "25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " ..
+ "CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " ..
+ "Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " ..
+ "Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " ..
+ "4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " ..
+ "Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " ..
+ "D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " ..
+ "250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " ..
+ "251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " ..
+ "2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " ..
+ "255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " ..
+ "2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " ..
+ "2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " ..
+ "Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " ..
+ "16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " ..
+ "Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " ..
+ "1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " ..
+ "Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " ..
+ "103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " ..
+ "3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " ..
+ "aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " ..
+ "21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " ..
+ "2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " ..
+ "asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " ..
+ "braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " ..
+ "caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " ..
+ "A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " ..
+ "colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " ..
+ "dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " ..
+ "dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " ..
+ "237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " ..
+ "egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " ..
+ "14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " ..
+ "etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " ..
+ "FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " ..
+ "215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " ..
+ "gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " ..
+ "greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " ..
+ "hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " ..
+ "iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " ..
+ "integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " ..
+ "invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " ..
+ "129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " ..
+ "140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " ..
+ "longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " ..
+ "B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " ..
+ "39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " ..
+ "obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " ..
+ "omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " ..
+ "2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " ..
+ "ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " ..
+ "parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " ..
+ "perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " ..
+ "220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " ..
+ "BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " ..
+ "201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " ..
+ "reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " ..
+ "2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " ..
+ "seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " ..
+ "263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " ..
+ "tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " ..
+ "tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " ..
+ "25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " ..
+ "FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " ..
+ "universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " ..
+ "upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " ..
+ "weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " ..
+ "1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " ..
+ ""
+
+-- StandardEncoding: 256 names, "-" = .notdef
+local STD = "" ..
+ "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " ..
+ "dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " ..
+ "zero one two three four five six seven eight nine colon semicolon less equal greater question at A " ..
+ "B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " ..
+ "underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " ..
+ "asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " ..
+ "sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " ..
+ "guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " ..
+ "quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " ..
+ "circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " ..
+ "- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " ..
+ "- - - dotlessi - - lslash oslash oe germandbls - - - - " ..
+ ""
+
+local byName: { [string]: number }? = nil
+
+local function load(): { [string]: number }
+ local t: { [string]: number } = {}
+ for name, hex in string.gmatch(AGL, "(%S+) (%x+)") do
+ t[name] = tonumber(hex, 16) :: number
+ end
+ byName = t
+ return t
+end
+
+local STANDARD: { [number]: string } = {}
+do
+ local i = 0
+ for name in string.gmatch(STD, "%S+") do
+ if name ~= "-" then
+ STANDARD[i] = name
+ end
+ i += 1
+ end
+end
+GlyphNames.STANDARD = STANDARD
+
+-- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil
+function GlyphNames.unicode(name: string): number?
+ local base = string.match(name, "^([^%.]+)") or name
+ local t = byName or load()
+ local v = t[base]
+ if v then
+ return v
+ end
+ local hex = string.match(base, "^uni(%x%x%x%x)")
+ if hex then
+ local c = tonumber(hex, 16) :: number
+ return if c >= 0xD800 and c < 0xE000 then nil else c
+ end
+ hex = string.match(base, "^u(%x%x%x%x%x?%x?)$")
+ if hex then
+ local c = tonumber(hex, 16) :: number
+ return if c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) then nil else c
+ end
+ local first = string.match(base, "^([^_]+)_")
+ if first then
+ return GlyphNames.unicode(first)
+ end
+ return nil
+end
+
+return GlyphNames
diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau
index 53817b3..41c955a 100644
--- a/src/Formats/containers/Archive.luau
+++ b/src/Formats/containers/Archive.luau
@@ -13,6 +13,7 @@
-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
+local Tar = require("@formats/containers/Tar")
local Archive = {}
@@ -183,6 +184,89 @@ function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buff
return out, nil
end
+-- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value,
+-- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take.
+function Archive.files(value: any, name: string?): ({ { name: string, data: buffer, entry: any } }?, Err.Err?)
+ if type(value) == "buffer" or type(value) == "string" then
+ local b = if type(value) == "string" then buffer.fromstring(value) else value
+ return { { name = name or "data", data = b, entry = { name = name or "data", size = buffer.len(b), dir = false } } }, nil
+ end
+ local items = Archive.entries(value)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
+ end
+ local out = {}
+ for _, it in items do
+ if not it.entry.dir then
+ local b, err = it.read()
+ if not b then
+ return nil, err
+ end
+ table.insert(out, { name = it.entry.name, data = b, entry = it.entry })
+ end
+ end
+ return out, nil
+end
+
+-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or
+-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err
+function Archive.streamData(value: any): (buffer?, Err.Err?)
+ if type(value) == "buffer" then
+ return value, nil
+ elseif type(value) == "string" then
+ return buffer.fromstring(value), nil
+ end
+ local items = Archive.entries(value)
+ if not items then
+ return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
+ end
+ if #items == 1 and not items[1].entry.dir then
+ return items[1].read()
+ end
+ local list = {}
+ for _, it in items do
+ local e: any = it.entry
+ local data: buffer? = nil
+ if not e.dir and (e.type == nil or e.type == "0") then
+ local b, err = it.read()
+ if not b then
+ return nil, err
+ end
+ data = b
+ end
+ local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil
+ table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode })
+ end
+ return Tar.write(list)
+end
+
+-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store
+-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date
+function Archive.fromDos(stamp: number): number?
+ local time, date = stamp % 65536, stamp // 65536
+ local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31)
+ if date == 0 or m < 1 or m > 12 or d < 1 then
+ return nil
+ end
+ local secs = bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2
+ return Types.Date.daysFromCivil(y, m, d) * 86400 + secs
+end
+
+-- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31)
+function Archive.toDos(t: number?): number
+ if type(t) ~= "number" or t ~= t or t < 315532800 then
+ return 0x210000 -- 1980-01-01 00:00
+ end
+ local s = math.floor(t)
+ local days = s // 86400
+ local rem = s - days * 86400
+ local y, m, d = Types.Date.civilFromDays(days)
+ if y > 2107 then
+ y, m, d, rem = 2107, 12, 31, 86398
+ end
+ return ((y - 1980) * 512 + m * 32 + d) * 65536 + (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2
+end
+
-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension
-- (".tgz" -> ".tar"), else "data"
function Archive.streamName(opts: any?, exts: { string }): string
diff --git a/src/Formats/containers/Cpio.luau b/src/Formats/containers/Cpio.luau
new file mode 100644
index 0000000..55c9ec6
--- /dev/null
+++ b/src/Formats/containers/Cpio.luau
@@ -0,0 +1,440 @@
+--!strict
+-- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment),
+-- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the
+-- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the
+-- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar
+-- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks
+-- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as
+-- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The
+-- archive formats (archive/cpio, archive/rpm's payload) build on it.
+--
+-- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err
+-- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" })
+--
+-- Never throws: bad data returns nil, Err.
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+
+local Cpio = {}
+
+export type Entry = {
+ name: string,
+ size: number, -- data bytes (a symlink's target length; a hard link: the shared data's size)
+ mode: number, -- the whole st_mode (file type bits included)
+ type: string, -- tar type letters: "0" file, "5" directory, "2" symlink, "3" char device, "4" block device, "6" fifo, "s" socket
+ dir: boolean,
+ uid: number,
+ gid: number,
+ nlink: number,
+ mtime: number,
+ ino: number,
+ devmajor: number,
+ devminor: number,
+ rdevmajor: number,
+ rdevminor: number,
+ link: string?, -- symlink target
+ hardlink: string?, -- the first entry of this entry's hard link group (for the later links)
+ offset: number, -- absolute offset of the data in the buffer
+ check: number?, -- crc format: the stored byte sum
+}
+export type ReadOptions = {
+ maxEntries: number?, -- default 1e6
+ verify: boolean?, -- crc format: check the byte sums (default true)
+}
+export type Info = { format: string } -- "newc" | "crc" | "odc" | "bin" | "binbe"
+
+local S_IFMT = 0xF000
+local TYPES: { [number]: string } = {
+ [0x8000] = "0",
+ [0x4000] = "5",
+ [0xA000] = "2",
+ [0x2000] = "3",
+ [0x6000] = "4",
+ [0x1000] = "6",
+ [0xC000] = "s",
+}
+local MODES: { [string]: number } = {}
+for m, t in TYPES do
+ MODES[t] = m
+end
+Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits
+Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter
+
+local TRAILER = "TRAILER!!!"
+
+-- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset
+function Cpio.format(b: buffer, o: number): string?
+ local n = buffer.len(b)
+ if o + 6 <= n then
+ local m = buffer.readstring(b, o, 6)
+ if m == "070701" then
+ return "newc"
+ elseif m == "070702" then
+ return "crc"
+ elseif m == "070707" then
+ return "odc"
+ end
+ end
+ if o + 2 <= n then
+ local v = buffer.readu16(b, o)
+ if v == 0x71C7 then
+ return "bin"
+ elseif v == 0xC771 then
+ return "binbe"
+ end
+ end
+ return nil
+end
+
+-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits
+local function num(b: buffer, o: number, n: number, base: number): number?
+ local s = buffer.readstring(b, o, n)
+ if base == 16 then
+ if not string.find(s, "^%x+$") then
+ return nil
+ end
+ elseif not string.find(s, "^[0-7]+$") then
+ return nil
+ end
+ return tonumber(s, base)
+end
+
+-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32)
+function Cpio.checksum(b: buffer, o: number, n: number): number
+ local s = 0
+ local i = o
+ local e = o + n
+ while i + 4 <= e do
+ local v = buffer.readu32(b, i)
+ s += bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24)
+ i += 4
+ end
+ while i < e do
+ s += buffer.readu8(b, i)
+ i += 1
+ end
+ return s % 4294967296
+end
+
+-- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err
+local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?)
+ local h: any = {}
+ local nameAt
+ if fmt == "newc" or fmt == "crc" then
+ if p + 110 > e then
+ return nil, Err.new(Err.TRUNCATED, "header past the end", p)
+ end
+ local f = {} :: { number }
+ for i = 1, 13 do
+ local v = num(b, p + 6 + (i - 1) * 8, 8, 16)
+ if not v then
+ return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8)
+ end
+ f[i] = v
+ end
+ h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7]
+ h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13]
+ nameAt = p + 110
+ elseif fmt == "odc" then
+ if p + 76 > e then
+ return nil, Err.new(Err.TRUNCATED, "header past the end", p)
+ end
+ local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 }
+ local f = {} :: { number }
+ local q = p + 6
+ for i, w in widths do
+ local v = num(b, q, w, 8)
+ if not v then
+ return nil, Err.new(Err.CORRUPT, "bad header field", q)
+ end
+ f[i] = v
+ q += w
+ end
+ h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10]
+ h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255)
+ h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255)
+ nameAt = p + 76
+ else
+ if p + 26 > e then
+ return nil, Err.new(Err.TRUNCATED, "header past the end", p)
+ end
+ local be = fmt == "binbe"
+ local function u16(i: number): number
+ local v = buffer.readu16(b, p + i * 2)
+ return if be then bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) else v
+ end
+ local dev, rdev = u16(1), u16(7)
+ h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6)
+ h.mtime = u16(8) * 65536 + u16(9)
+ h.namesize = u16(10)
+ h.size = u16(11) * 65536 + u16(12)
+ h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255)
+ h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255)
+ nameAt = p + 26
+ end
+ if h.namesize < 1 or nameAt + h.namesize > e then
+ return nil, Err.new(if h.namesize < 1 then Err.CORRUPT else Err.TRUNCATED, "bad name size", nameAt)
+ end
+ h.nameAt = nameAt
+ return h, nil
+end
+
+-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
+function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
+ local o = offset or 0
+ local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
+ local maxEntries = (opts and opts.maxEntries) or 1e6
+ local verify = not (opts and opts.verify == false)
+ local fmt = Cpio.format(b, o)
+ if not fmt or o >= e then
+ return nil, Err.new(Err.CORRUPT, "not a cpio archive", o)
+ end
+ local align = if fmt == "newc" or fmt == "crc" then 4 elseif fmt == "odc" then 1 else 2
+ local out: { Entry } = {}
+ local groups: { [string]: { Entry } } = {}
+ local p = o
+ while true do
+ if p >= e then
+ return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p)
+ end
+ if Cpio.format(b, p) ~= fmt then
+ return nil, Err.new(Err.CORRUPT, "bad header magic", p)
+ end
+ local h, herr = header(b, p, e, fmt)
+ if not h then
+ return nil, herr
+ end
+ local name = buffer.readstring(b, h.nameAt, h.namesize)
+ local z = string.find(name, "\0", 1, true)
+ if z then
+ name = string.sub(name, 1, z - 1)
+ end
+ local data = h.nameAt + h.namesize
+ data = o + (data - o + align - 1) // align * align
+ if name == TRAILER then
+ break
+ end
+ if data + h.size > e then
+ return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data)
+ end
+ local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0"
+ local entry: Entry = {
+ name = name,
+ size = h.size,
+ mode = h.mode,
+ type = typ,
+ dir = typ == "5",
+ uid = h.uid,
+ gid = h.gid,
+ nlink = h.nlink,
+ mtime = h.mtime,
+ ino = h.ino,
+ devmajor = h.devmajor,
+ devminor = h.devminor,
+ rdevmajor = h.rdevmajor,
+ rdevminor = h.rdevminor,
+ link = if typ == "2" then buffer.readstring(b, data, h.size) else nil,
+ hardlink = nil,
+ offset = data,
+ check = if fmt == "crc" then h.check else nil,
+ }
+ if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then
+ return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data)
+ end
+ if typ == "0" and h.nlink > 1 then
+ local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino
+ local g = groups[key]
+ if not g then
+ g = {}
+ groups[key] = g
+ else
+ entry.hardlink = g[1].name
+ end
+ table.insert(g, entry)
+ end
+ table.insert(out, entry)
+ if #out > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
+ end
+ p = data + h.size
+ p = o + (p - o + align - 1) // align * align
+ end
+ -- hard links: the links stored without data read the group's data (newc / crc keep it on the last link)
+ for _, g in groups do
+ local holder: Entry? = nil
+ for _, x in g do
+ if x.size > 0 then
+ holder = x
+ end
+ end
+ if holder then
+ for _, x in g do
+ if x.size == 0 then
+ x.size, x.offset = holder.size, holder.offset
+ end
+ end
+ end
+ end
+ return out, { format = fmt }
+end
+
+-- ------------------------------------------------------------------------------------------------ writing
+export type WriteEntry = {
+ name: string,
+ data: buffer?, -- file data (a symlink: its target, else taken from link)
+ mode: number?, -- st_mode; permission bits alone get the type bits from type / dir (default 0o644 / 0o755)
+ type: string?, -- a type letter (see Entry.type); default "0" ("5" for dir)
+ dir: boolean?,
+ link: string?, -- symlink target
+ uid: number?,
+ gid: number?,
+ nlink: number?, -- default 1 (2 for directories)
+ mtime: number?, -- unix seconds (default 0)
+ ino: number?, -- default: the entry's index (1, 2, ...); hard links share one
+ devmajor: number?,
+ devminor: number?,
+ rdevmajor: number?,
+ rdevminor: number?,
+}
+export type WriteOptions = {
+ format: ("newc" | "crc" | "odc")?, -- default "newc"
+ block: number?, -- pad the archive to a multiple of this many bytes (default 512; 1 = no padding)
+}
+
+local function hex8(v: number): string?
+ if v < 0 or v % 1 ~= 0 or v >= 4294967296 then
+ return nil
+ end
+ return string.format("%08X", v)
+end
+
+local function oct(v: number, w: number): string?
+ if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then
+ return nil
+ end
+ local s = string.format("%o", v)
+ return string.rep("0", w - #s) .. s
+end
+
+-- write(entries, opts?) -> buffer | nil, Err
+function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
+ local fmt = (opts and opts.format) or "newc"
+ if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then
+ return nil, Err.new(Err.ARG, "format must be newc, crc or odc")
+ end
+ local block = (opts and opts.block) or 512
+ if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then
+ return nil, Err.new(Err.ARG, "block must be a positive integer")
+ end
+ -- newc / crc: a hard link group's data goes on its last link only
+ local last: { [string]: number } = {}
+ local prepared: { any } = table.create(#entries)
+ for i, e in entries do
+ if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
+ return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
+ end
+ local typ = e.type or (if e.dir then "5" else "0")
+ local tbits = MODES[typ]
+ if not tbits then
+ return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ))
+ end
+ local mode = e.mode or (if typ == "5" then 0x1ED elseif typ == "2" then 0x1FF else 0x1A4)
+ if bit32.band(mode, S_IFMT) == 0 then
+ mode = bit32.bor(mode, tbits)
+ end
+ local data = e.data
+ if typ == "2" and not data then
+ data = buffer.fromstring(e.link or "")
+ elseif typ ~= "0" and typ ~= "2" then
+ data = nil
+ end
+ local nlink = e.nlink or (if typ == "5" then 2 else 1)
+ local ino = e.ino or i
+ local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ }
+ prepared[i] = p
+ if typ == "0" and nlink > 1 then
+ last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i
+ end
+ end
+ local w = Bytes.writer(1024)
+ local function put(name: string, p: any, data: buffer): Err.Err?
+ local e = p.e
+ local namesize = #name + 1
+ local size = buffer.len(data)
+ if fmt == "odc" then
+ local dev = (e.devmajor or 0) * 256 + (e.devminor or 0)
+ local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0)
+ local fields = {
+ oct(dev, 6),
+ oct(p.ino, 6),
+ oct(p.mode, 6),
+ oct(e.uid or 0, 6),
+ oct(e.gid or 0, 6),
+ oct(p.nlink, 6),
+ oct(rdev, 6),
+ oct(math.floor(e.mtime or 0), 11),
+ oct(namesize, 6),
+ oct(size, 11),
+ }
+ for k = 1, 10 do
+ if not fields[k] then
+ return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header")
+ end
+ end
+ w:string("070707" .. table.concat(fields :: { string }))
+ w:string(name)
+ w:u8(0)
+ w:bytes(data)
+ else
+ local check = if fmt == "crc" and p.typ == "0" then Cpio.checksum(data, 0, size) else 0
+ local fields = {
+ hex8(p.ino),
+ hex8(p.mode),
+ hex8(e.uid or 0),
+ hex8(e.gid or 0),
+ hex8(p.nlink),
+ hex8(math.floor(e.mtime or 0)),
+ hex8(size),
+ hex8(e.devmajor or 0),
+ hex8(e.devminor or 0),
+ hex8(e.rdevmajor or 0),
+ hex8(e.rdevminor or 0),
+ hex8(namesize),
+ hex8(check),
+ }
+ for k = 1, 13 do
+ if not fields[k] then
+ return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header")
+ end
+ end
+ w:string((if fmt == "crc" then "070702" else "070701") .. table.concat(fields :: { string }))
+ w:string(name)
+ w:u8(0)
+ w:fill(0, (4 - (110 + namesize) % 4) % 4)
+ w:bytes(data)
+ w:fill(0, (4 - size % 4) % 4)
+ end
+ return nil
+ end
+ for i, p in prepared do
+ local data = p.data
+ if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then
+ local e = p.e
+ if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then
+ data = buffer.create(0)
+ end
+ end
+ local err = put(p.e.name, p, data)
+ if err then
+ return nil, err
+ end
+ end
+ local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0))
+ if err then
+ return nil, err
+ end
+ w:fill(0, (block - w.pos % block) % block)
+ return w:finish(), nil
+end
+
+return Cpio
diff --git a/src/Formats/containers/Fat.luau b/src/Formats/containers/Fat.luau
new file mode 100644
index 0000000..efb7d7f
--- /dev/null
+++ b/src/Formats/containers/Fat.luau
@@ -0,0 +1,707 @@
+--!strict
+-- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories
+-- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names,
+-- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images
+-- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from
+-- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout.
+--
+-- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message
+-- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/")
+-- local data, err = Fat.read(vol, entry) -- buffer | nil, message
+-- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image
+--
+-- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by
+-- the cluster count (loops are errors).
+local Archive = require("@formats/containers/Archive")
+
+local Fat = {}
+
+local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
+
+export type Volume = {
+ b: buffer,
+ base: number, -- byte offset of the volume (partition) in b
+ limit: number,
+ bps: number, -- bytes per sector
+ spc: number, -- sectors per cluster
+ fatOffset: number, -- byte offset of the first FAT (relative to base)
+ fatSize: number, -- bytes per FAT
+ rootOffset: number, -- FAT12 / 16: the fixed root directory
+ rootEntries: number,
+ rootCluster: number, -- FAT32
+ dataOffset: number, -- byte offset of cluster 2
+ clusters: number, -- data clusters
+ bits: number, -- 12 / 16 / 32
+ label: string?,
+ oem: string,
+ media: number,
+ partition: number?,
+}
+
+export type Entry = {
+ name: string,
+ dir: boolean,
+ size: number,
+ mtime: number?,
+ cluster: number,
+ attr: number,
+ shortName: string,
+}
+
+-- ------------------------------------------------------------------------------------------------ open
+local function bpbAt(b: buffer, o: number, len: number): (Volume?, string?)
+ if len < 512 then
+ return nil, "truncated: smaller than a boot sector"
+ end
+ local jump = readu8(b, o)
+ local bps = readu16(b, o + 11)
+ local spc = readu8(b, o + 13)
+ if (jump ~= 0xEB and jump ~= 0xE9 and jump ~= 0xE8) or (bps ~= 512 and bps ~= 1024 and bps ~= 2048 and bps ~= 4096) then
+ return nil, "no FAT boot sector"
+ end
+ if spc == 0 or bit32.band(spc, spc - 1) ~= 0 then
+ return nil, "bad sectors per cluster"
+ end
+ local reserved, nfats, rootEntries = readu16(b, o + 14), readu8(b, o + 16), readu16(b, o + 17)
+ local total = readu16(b, o + 19)
+ if total == 0 then
+ total = readu32(b, o + 32)
+ end
+ local fatSectors = readu16(b, o + 22)
+ local fat32 = fatSectors == 0
+ if fat32 then
+ fatSectors = readu32(b, o + 36)
+ end
+ if reserved == 0 or nfats == 0 or fatSectors == 0 or total == 0 then
+ return nil, "bad BPB"
+ end
+ local rootSectors = math.ceil(rootEntries * 32 / bps)
+ local dataSector = reserved + nfats * fatSectors + rootSectors
+ if dataSector >= total then
+ return nil, "bad BPB: no data area"
+ end
+ local clusters = (total - dataSector) // spc
+ local bits = if clusters < 4085 then 12 elseif clusters < 65525 then 16 else 32
+ if fat32 and bits ~= 32 then
+ bits = 32 -- some small FAT32 volumes (mkfs.fat -F 32 on tiny images) are FAT32 regardless of the count
+ end
+ if total * bps > len then
+ -- images cut short at the last used sector are common: allow, reads past the end fail
+ total = len // bps
+ end
+ local labelAt = if bits == 32 then 71 else 43
+ local sig = readu8(b, o + (if bits == 32 then 66 else 38))
+ local label: string? = if sig == 0x29 then (string.gsub(buffer.readstring(b, o + labelAt, 11), " +$", "")) else nil
+ if label == "NO NAME" or label == "" then
+ label = nil
+ end
+ return {
+ b = b,
+ base = o,
+ limit = o + len,
+ bps = bps,
+ spc = spc,
+ fatOffset = reserved * bps,
+ fatSize = fatSectors * bps,
+ rootOffset = (reserved + nfats * fatSectors) * bps,
+ rootEntries = rootEntries,
+ rootCluster = if bits == 32 then readu32(b, o + 44) else 0,
+ dataOffset = dataSector * bps,
+ clusters = clusters,
+ bits = bits,
+ label = label,
+ oem = buffer.readstring(b, o + 3, 8),
+ media = readu8(b, o + 21),
+ }, nil
+end
+
+export type OpenOptions = { partition: number? } -- 1..4: the MBR partition (default: the first FAT one)
+
+local FAT_TYPES = { [0x01] = true, [0x04] = true, [0x06] = true, [0x0B] = true, [0x0C] = true, [0x0E] = true, [0x11] = true, [0x14] = true, [0x16] = true, [0x1B] = true, [0x1C] = true, [0x1E] = true }
+
+function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Volume?, string?)
+ local o: OpenOptions = opts or {}
+ off = math.max(0, off)
+ len = math.min(len, buffer.len(b) - off)
+ if len < 512 then
+ return nil, "truncated: smaller than a boot sector"
+ end
+ if not o.partition then
+ local v = bpbAt(b, off, len)
+ if v then
+ return v, nil
+ end
+ end
+ -- an MBR: 0x55AA and four partition entries
+ if readu8(b, off + 510) ~= 0x55 or readu8(b, off + 511) ~= 0xAA then
+ return nil, "no FAT boot sector and no partition table"
+ end
+ for i = 1, 4 do
+ local e = off + 446 + (i - 1) * 16
+ local ptype = readu8(b, e + 4)
+ local lba, count = readu32(b, e + 8), readu32(b, e + 12)
+ if (o.partition == i or (not o.partition and FAT_TYPES[ptype])) and ptype ~= 0 then
+ if lba * 512 >= len then
+ return nil, "truncated: partition " .. i .. " starts past the end"
+ end
+ local v, err = bpbAt(b, off + lba * 512, math.min(count * 512, len - lba * 512))
+ if v then
+ v.partition = i
+ end
+ return v, err
+ end
+ end
+ return nil, if o.partition then "no partition " .. o.partition else "no FAT partition"
+end
+
+-- ------------------------------------------------------------------------------------------------ chains
+local function nextCluster(v: Volume, c: number): number
+ local f = v.base + v.fatOffset
+ if v.bits == 12 then
+ local p = f + c + c // 2
+ if p + 1 >= v.limit then
+ return 0xFFFFFFF
+ end
+ local w = readu16(v.b, p)
+ local n = if c % 2 == 0 then bit32.band(w, 0xFFF) else bit32.rshift(w, 4)
+ return if n >= 0xFF8 then 0xFFFFFFF elseif n == 0xFF7 then 0xFFFFFF7 else n
+ elseif v.bits == 16 then
+ local p = f + c * 2
+ if p + 2 > v.limit then
+ return 0xFFFFFFF
+ end
+ local n = readu16(v.b, p)
+ return if n >= 0xFFF8 then 0xFFFFFFF elseif n == 0xFFF7 then 0xFFFFFF7 else n
+ end
+ local p = f + c * 4
+ if p + 4 > v.limit then
+ return 0xFFFFFFF
+ end
+ return bit32.band(readu32(v.b, p), 0x0FFFFFFF)
+end
+
+-- the clusters of a chain (nil, message when it leaves the volume or loops)
+local function chainOf(v: Volume, first: number, maxClusters: number): ({ number }?, string?)
+ local out = {}
+ local c = first
+ while c >= 2 and c < 0xFFFFFF7 do
+ if c >= v.clusters + 2 then
+ return nil, "cluster " .. c .. " outside the volume"
+ end
+ table.insert(out, c)
+ if #out > maxClusters then
+ return nil, "cluster chain loops"
+ end
+ c = nextCluster(v, c)
+ end
+ if c == 0xFFFFFF7 then
+ return nil, "bad cluster in a chain"
+ end
+ return out, nil
+end
+
+local function clusterOffset(v: Volume, c: number): number
+ return v.base + v.dataOffset + (c - 2) * v.spc * v.bps
+end
+
+-- the bytes of a chain, up to size bytes (nil = the whole chain)
+local function readChain(v: Volume, first: number, size: number?): (buffer?, string?)
+ local csize = v.spc * v.bps
+ local maxClusters = if size then math.ceil(size / csize) + 1 else v.clusters
+ local list, err = chainOf(v, first, math.min(maxClusters, v.clusters + 1))
+ if not list then
+ return nil, err
+ end
+ local total = if size then size else #list * csize
+ if #list * csize < total then
+ return nil, "file data ends early (chain of " .. #list .. " clusters for " .. total .. " bytes)"
+ end
+ local out = buffer.create(total)
+ local o = 0
+ for _, c in list do
+ local n = math.min(csize, total - o)
+ if n <= 0 then
+ break
+ end
+ local at = clusterOffset(v, c)
+ if at + n > v.limit then
+ return nil, "truncated: cluster " .. c .. " past the end of the image"
+ end
+ buffer.copy(out, o, v.b, at, n)
+ o += n
+ end
+ return out, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ directories
+local function latin1(s: string): string
+ if not string.find(s, "[\128-\255]") then
+ return s
+ end
+ local out = table.create(#s)
+ for i = 1, #s do
+ out[i] = utf8.char(string.byte(s, i))
+ end
+ return table.concat(out)
+end
+
+local function shortChecksum(raw: string): number
+ local sum = 0
+ for i = 1, 11 do
+ sum = (bit32.rshift(sum, 1) + bit32.lshift(bit32.band(sum, 1), 7) + string.byte(raw, i)) % 256
+ end
+ return sum
+end
+
+local function ucs2(b: buffer, o: number, n: number, out: { number })
+ for k = 0, n - 1 do
+ table.insert(out, readu16(b, o + k * 2))
+ end
+end
+
+-- the entries of one directory's bytes
+local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry }
+ local lfn: { [number]: { number } } = {}
+ local lfnSum, lfnCount = -1, 0
+ local subdirs = {}
+ for p = 0, buffer.len(d) - 32, 32 do
+ local first = readu8(d, p)
+ if first == 0 then
+ break
+ end
+ local attr = readu8(d, p + 11)
+ if first == 0xE5 then
+ lfn, lfnSum, lfnCount = {}, -1, 0
+ elseif attr == 0x0F then
+ local seq = bit32.band(first, 0x3F)
+ if bit32.band(first, 0x40) ~= 0 then
+ lfn, lfnCount = {}, seq
+ lfnSum = readu8(d, p + 13)
+ end
+ if seq >= 1 and seq <= 20 and readu8(d, p + 13) == lfnSum then
+ local chars = {}
+ ucs2(d, p + 1, 5, chars)
+ ucs2(d, p + 14, 6, chars)
+ ucs2(d, p + 28, 2, chars)
+ lfn[seq] = chars
+ end
+ else
+ local raw = buffer.readstring(d, p, 11)
+ if first == 0x05 then
+ raw = "\229" .. string.sub(raw, 2)
+ end
+ local long: string? = nil
+ if lfnCount > 0 and lfnSum == shortChecksum(buffer.readstring(d, p, 11)) then
+ local cps = {}
+ local complete = true
+ for s = 1, lfnCount do
+ if not lfn[s] then
+ complete = false
+ break
+ end
+ for _, c in lfn[s] do
+ if c == 0 or c == 0xFFFF then
+ break
+ end
+ table.insert(cps, c)
+ end
+ end
+ if complete then
+ local parts = table.create(#cps)
+ for i, c in cps do
+ parts[i] = utf8.char(if c >= 0xD800 and c < 0xE000 then 0xFFFD else c)
+ end
+ long = table.concat(parts)
+ end
+ end
+ lfn, lfnSum, lfnCount = {}, -1, 0
+ local nt = readu8(d, p + 12)
+ local base = string.gsub(string.sub(raw, 1, 8), " +$", "")
+ local ext = string.gsub(string.sub(raw, 9, 11), " +$", "")
+ if bit32.band(nt, 0x08) ~= 0 then
+ base = string.lower(base)
+ end
+ if bit32.band(nt, 0x10) ~= 0 then
+ ext = string.lower(ext)
+ end
+ local short = latin1(if ext ~= "" then base .. "." .. ext else base)
+ local isDir = bit32.band(attr, 0x10) ~= 0
+ local isLabel = bit32.band(attr, 0x08) ~= 0
+ if not isLabel and short ~= "." and short ~= ".." then
+ local name = prefix .. (long or short)
+ local cluster = readu16(d, p + 26) + readu16(d, p + 20) * 65536
+ local e: Entry = {
+ name = if isDir then name .. "/" else name,
+ dir = isDir,
+ size = if isDir then 0 else readu32(d, p + 28),
+ mtime = Archive.fromDos(readu16(d, p + 24) * 65536 + readu16(d, p + 22)),
+ cluster = cluster,
+ attr = attr,
+ shortName = short,
+ }
+ table.insert(out, e)
+ if isDir then
+ table.insert(subdirs, e)
+ end
+ end
+ end
+ end
+ return subdirs
+end
+
+-- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents)
+function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?)
+ local out: { Entry } = {}
+ local limit = maxEntries or 65536
+ local root: buffer?, err: string?
+ if v.bits == 32 then
+ root, err = readChain(v, v.rootCluster, nil)
+ else
+ local n = v.rootEntries * 32
+ if v.base + v.rootOffset + n > v.limit then
+ return nil, "truncated: root directory past the end"
+ end
+ root = buffer.create(n)
+ buffer.copy(root :: buffer, 0, v.b, v.base + v.rootOffset, n)
+ end
+ if not root then
+ return nil, err
+ end
+ local seen: { [number]: boolean } = {}
+ local function walk(d: buffer, prefix: string, depth: number): string?
+ if depth > 64 then
+ return "directories nested too deep"
+ end
+ local start = #out
+ local subdirs = parseDir(d, prefix, out)
+ if #out > limit then
+ return "limit: more than maxEntries entries"
+ end
+ local _ = start
+ for _, s in subdirs do
+ if s.cluster >= 2 then
+ if seen[s.cluster] then
+ return "directory loop at cluster " .. s.cluster
+ end
+ seen[s.cluster] = true
+ local sd, serr = readChain(v, s.cluster, nil)
+ if not sd then
+ return s.name .. ": " .. tostring(serr)
+ end
+ local werr = walk(sd, s.name, depth + 1)
+ if werr then
+ return werr
+ end
+ end
+ end
+ return nil
+ end
+ local werr = walk(root :: buffer, "", 0)
+ if werr then
+ return nil, werr
+ end
+ return out, nil
+end
+
+-- read(vol, entry) -> the file's bytes
+function Fat.read(v: Volume, e: Entry): (buffer?, string?)
+ if e.dir or e.size == 0 then
+ return buffer.create(0), nil
+ end
+ if e.cluster < 2 then
+ return nil, "file without clusters"
+ end
+ return readChain(v, e.cluster, e.size)
+end
+
+-- ------------------------------------------------------------------------------------------------ write
+export type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? }
+export type WriteOptions = {
+ size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440)
+ label: string?, -- volume label (default none)
+ serial: number?, -- volume serial number (default 0x12345678)
+}
+
+local GEOMETRY = {
+ [360] = { sectors = 720, spc = 2, root = 112, media = 0xFD, fat = 2, spt = 9, heads = 2 },
+ [720] = { sectors = 1440, spc = 2, root = 112, media = 0xF9, fat = 3, spt = 9, heads = 2 },
+ [1200] = { sectors = 2400, spc = 1, root = 224, media = 0xF9, fat = 7, spt = 15, heads = 2 },
+ [1440] = { sectors = 2880, spc = 1, root = 224, media = 0xF0, fat = 9, spt = 18, heads = 2 },
+ [2880] = { sectors = 5760, spc = 2, root = 240, media = 0xF0, fat = 9, spt = 36, heads = 2 },
+}
+
+local VALID83 = "^[%w!#%$%%&'%(%)%-@%^_`{}~]+$"
+
+local function toDos(t: number?): (number, number)
+ local v = Archive.toDos(t)
+ return v // 65536, v % 65536
+end
+
+type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number }
+
+-- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed
+local function shortName(name: string, used: { [string]: boolean }): (string, number, boolean)
+ local base, ext = string.match(name, "^(.*)%.([^%.]*)$")
+ if not base or base == "" then
+ base, ext = name, ""
+ end
+ local b, e = base :: string, ext :: string
+ -- a plain 8.3 name, all upper or all lower case per part: no long name needed
+ if #b <= 8 and #e <= 3 and string.match(b, VALID83) and (e == "" or string.match(e, VALID83)) then
+ local bu, eu = string.upper(b), string.upper(e)
+ local nt = 0
+ local ok = true
+ if b ~= bu then
+ if b == string.lower(b) then
+ nt = bit32.bor(nt, 0x08)
+ else
+ ok = false
+ end
+ end
+ if e ~= eu then
+ if e == string.lower(e) then
+ nt = bit32.bor(nt, 0x10)
+ else
+ ok = false
+ end
+ end
+ local raw = bu .. string.rep(" ", 8 - #bu) .. eu .. string.rep(" ", 3 - #eu)
+ if ok and not used[raw] then
+ used[raw] = true
+ return raw, nt, false
+ end
+ end
+ local function clean(s: string): string
+ s = string.upper((string.gsub(s, "[%s%.]", "")))
+ return (string.gsub(s, "[^%w!#%$%%&'%(%)%-@%^_`{}~]", "_"))
+ end
+ local cb, ce = clean(b), string.sub(clean(e), 1, 3)
+ if cb == "" then
+ cb = "_"
+ end
+ for n = 1, 999999 do
+ local tail = "~" .. n
+ local raw = string.sub(cb, 1, 8 - #tail) .. tail
+ raw = raw .. string.rep(" ", 8 - #raw) .. ce .. string.rep(" ", 3 - #ce)
+ if not used[raw] then
+ used[raw] = true
+ return raw, 0, true
+ end
+ end
+ return " ___", 0, true
+end
+
+-- the directory entries (32 bytes each) of a node's children
+local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label: string?): buffer
+ local w = {}
+ local function entry(raw: string, attr: number, nt: number, cluster: number, size: number, mtime: number?)
+ local e = buffer.create(32)
+ buffer.writestring(e, 0, raw)
+ buffer.writeu8(e, 11, attr)
+ buffer.writeu8(e, 12, nt)
+ local date, time = toDos(mtime)
+ buffer.writeu16(e, 14, time)
+ buffer.writeu16(e, 16, date)
+ buffer.writeu16(e, 18, date)
+ buffer.writeu16(e, 22, time)
+ buffer.writeu16(e, 24, date)
+ buffer.writeu16(e, 26, cluster)
+ buffer.writeu32(e, 28, size)
+ table.insert(w, e)
+ end
+ if isRoot and label then
+ local l = string.sub(string.upper(label), 1, 11)
+ entry(l .. string.rep(" ", 11 - #l), 0x08, 0, 0, 0, n.mtime)
+ end
+ if not isRoot then
+ entry(". ", 0x10, 0, n.cluster, 0, n.mtime)
+ entry(".. ", 0x10, 0, parentCluster, 0, n.mtime)
+ end
+ local used: { [string]: boolean } = {}
+ for _, c in n.children do
+ local raw, nt, needLong = shortName(c.name, used)
+ if needLong then
+ local cps = {}
+ if utf8.len(c.name) then
+ for _, cp in utf8.codes(c.name) do
+ table.insert(cps, if cp > 0xFFFF then 0x5F else cp)
+ end
+ else
+ for i = 1, #c.name do
+ table.insert(cps, (string.byte(c.name, i)))
+ end
+ end
+ local count = math.ceil(#cps / 13)
+ local sum = shortChecksum(raw)
+ for s = count, 1, -1 do
+ local e = buffer.create(32)
+ buffer.writeu8(e, 0, if s == count then bit32.bor(s, 0x40) else s)
+ buffer.writeu8(e, 11, 0x0F)
+ buffer.writeu8(e, 13, sum)
+ local slots = { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 }
+ for k = 1, 13 do
+ local i = (s - 1) * 13 + k
+ local v = if i <= #cps then cps[i] elseif i == #cps + 1 then 0 else 0xFFFF
+ buffer.writeu16(e, slots[k], v)
+ end
+ table.insert(w, e)
+ end
+ end
+ entry(raw, if c.dir then 0x10 else 0x20, nt, c.cluster, if c.dir then 0 else buffer.len(c.data or buffer.create(0)), c.mtime)
+ end
+ local out = buffer.create(#w * 32)
+ for i, e in w do
+ buffer.copy(out, (i - 1) * 32, e)
+ end
+ return out
+end
+
+-- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths)
+function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?)
+ local o: WriteOptions = opts or {}
+ local g = GEOMETRY[o.size or 1440]
+ if not g then
+ return nil, "size must be 360, 720, 1200, 1440 or 2880"
+ end
+ local bps = 512
+ local root: Node = { name = "", dir = true, children = {}, byName = {}, cluster = 0 }
+ local function node(path: string, isDir: boolean): (Node?, string?)
+ local cur = root
+ local parts = string.split(path, "/")
+ for i, p in parts do
+ if p ~= "" and p ~= "." then
+ if p == ".." then
+ return nil, "'..' in a path"
+ end
+ local last = i == #parts or (i == #parts - 1 and parts[#parts] == "")
+ local child: Node? = cur.byName[string.lower(p)]
+ if not child then
+ local nc: Node = { name = p, dir = isDir or not last, children = {}, byName = {}, cluster = 0 }
+ cur.byName[string.lower(p)] = nc
+ table.insert(cur.children, nc)
+ child = nc
+ elseif not child.dir and (not last or isDir) then
+ return nil, p .. " is both a file and a directory"
+ end
+ cur = child :: Node
+ end
+ end
+ return cur, nil
+ end
+ for _, f in files do
+ local n, err = node(f.name, f.dir == true)
+ if not n then
+ return nil, err
+ end
+ if n ~= root then
+ n.mtime = f.mtime
+ if not n.dir then
+ n.data = f.data or buffer.create(0)
+ end
+ end
+ end
+ local csize = g.spc * bps
+ local dataSector = 1 + 2 * g.fat + g.root * 32 // bps
+ local clusters = (g.sectors - dataSector) // g.spc
+ local img = buffer.create(g.sectors * bps)
+ local fat = buffer.create(g.fat * bps)
+ local nextFree = 2
+ local function setFat(c: number, v: number)
+ local p = c + c // 2
+ local w = buffer.readu16(fat, p)
+ if c % 2 == 0 then
+ w = bit32.bor(bit32.band(w, 0xF000), v)
+ else
+ w = bit32.bor(bit32.band(w, 0x000F), bit32.lshift(v, 4))
+ end
+ buffer.writeu16(fat, p, w)
+ end
+ local function alloc(bytes: number): number?
+ local n = math.max(1, math.ceil(bytes / csize))
+ if nextFree + n - 1 > clusters + 1 then
+ return nil
+ end
+ local first = nextFree
+ for k = 0, n - 1 do
+ setFat(first + k, if k == n - 1 then 0xFFF else first + k + 1)
+ end
+ nextFree += n
+ return first
+ end
+ -- clusters: files get theirs first; a directory's size depends on its entries (long names), so measure first
+ local function place(n: Node): string?
+ for _, c in n.children do
+ if c.dir then
+ local size = buffer.len(dirEntries(c, 0, false, nil))
+ local cl = alloc(size)
+ if not cl then
+ return "disk full"
+ end
+ c.cluster = cl
+ local err = place(c)
+ if err then
+ return err
+ end
+ elseif c.data and buffer.len(c.data) > 0 then
+ local cl = alloc(buffer.len(c.data))
+ if not cl then
+ return "disk full"
+ end
+ c.cluster = cl
+ local at = (dataSector + (cl - 2) * g.spc) * bps
+ buffer.copy(img, at, c.data)
+ end
+ end
+ return nil
+ end
+ local perr = place(root)
+ if perr then
+ return nil, "limit: " .. perr
+ end
+ local function writeDirs(n: Node, parent: number): string?
+ for _, c in n.children do
+ if c.dir then
+ local d = dirEntries(c, parent, false, nil)
+ buffer.copy(img, (dataSector + (c.cluster - 2) * g.spc) * bps, d)
+ local err = writeDirs(c, c.cluster)
+ if err then
+ return err
+ end
+ end
+ end
+ return nil
+ end
+ writeDirs(root, 0)
+ local rootDir = dirEntries(root, 0, true, o.label)
+ if buffer.len(rootDir) > g.root * 32 then
+ return nil, "limit: too many entries in the root directory"
+ end
+ buffer.copy(img, (1 + 2 * g.fat) * bps, rootDir)
+ setFat(0, 0xF00 + g.media)
+ setFat(1, 0xFFF)
+ buffer.copy(img, bps, fat)
+ buffer.copy(img, (1 + g.fat) * bps, fat)
+ -- boot sector
+ buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU")
+ buffer.writeu16(img, 11, bps)
+ buffer.writeu8(img, 13, g.spc)
+ buffer.writeu16(img, 14, 1)
+ buffer.writeu8(img, 16, 2)
+ buffer.writeu16(img, 17, g.root)
+ buffer.writeu16(img, 19, g.sectors)
+ buffer.writeu8(img, 21, g.media)
+ buffer.writeu16(img, 22, g.fat)
+ buffer.writeu16(img, 24, g.spt)
+ buffer.writeu16(img, 26, g.heads)
+ buffer.writeu8(img, 36, 0)
+ buffer.writeu8(img, 38, 0x29)
+ buffer.writeu32(img, 39, o.serial or 0x12345678)
+ local label = string.upper(string.sub(o.label or "NO NAME", 1, 11))
+ buffer.writestring(img, 43, label .. string.rep(" ", 11 - #label) .. "FAT12 ")
+ buffer.writestring(img, 62, "\244\235\253") -- hlt; jmp $ (no boot code)
+ buffer.writeu8(img, 510, 0x55)
+ buffer.writeu8(img, 511, 0xAA)
+ return img, nil
+end
+
+return Fat
diff --git a/src/Formats/containers/Iso9660.luau b/src/Formats/containers/Iso9660.luau
new file mode 100644
index 0000000..c947ba2
--- /dev/null
+++ b/src/Formats/containers/Iso9660.luau
@@ -0,0 +1,525 @@
+--!strict
+-- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary,
+-- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross
+-- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is
+-- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names
+-- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the
+-- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE
+-- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock
+-- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog
+-- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet
+-- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns
+-- the stored bytes), UDF, writing.
+--
+-- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err
+-- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents)
+local Err = require("@formats/core/Err")
+local Types = require("@formats/Types")
+local Text = require("@formats/codecs/text/Text")
+
+local Iso9660 = {}
+
+export type Extent = { at: number, size: number } -- byte offset (from the image start) and length
+export type Entry = {
+ name: string, -- the path, "/" separated, no leading "/"
+ dir: boolean,
+ size: number,
+ extents: { Extent },
+ mtime: number?, -- unix seconds
+ type: string, -- tar letters: "0" file, "5" directory, "2" symlink, "3" / "4" devices, "6" fifo, "s" socket
+ mode: number?, -- Rock Ridge: the permission bits
+ uid: number?,
+ gid: number?,
+ nlink: number?,
+ link: string?, -- Rock Ridge symlink target
+ rdev: number?, -- Rock Ridge PN: high * 2^32 + low
+ hidden: boolean?,
+ interleaved: boolean?,
+ zisofs: boolean?,
+}
+export type ReadOptions = {
+ prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
+ maxEntries: number?, -- default 1e6
+}
+
+local SECTOR = 2048
+local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" }
+
+-- ------------------------------------------------------------------------------------------------ fields
+local function u16(b: buffer, o: number): number
+ return buffer.readu16(b, o)
+end
+local function u32(b: buffer, o: number): number
+ return buffer.readu32(b, o)
+end
+local function str(b: buffer, o: number, n: number): string
+ return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", ""))
+end
+
+-- a 7-byte directory record date -> unix seconds
+local function recDate(b: buffer, o: number): number?
+ local y = buffer.readu8(b, o)
+ local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2)
+ if m < 1 or m > 12 or d < 1 or d > 31 then
+ return nil
+ end
+ local off = buffer.readi8(b, o + 6)
+ return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 })
+end
+
+-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds
+local function longDate(b: buffer, o: number): number?
+ local s = buffer.readstring(b, o, 16)
+ local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$")
+ if not y or tonumber(y) == 0 then
+ return nil
+ end
+ local off = buffer.readi8(b, o + 16)
+ return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 })
+end
+
+-- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge
+type Susp = { [string]: any }
+
+-- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } }
+local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } }
+ local out = {}
+ while o + 4 <= e do
+ local sig = buffer.readstring(b, o, 2)
+ local len = buffer.readu8(b, o + 2)
+ if len < 4 or o + len > e then
+ break
+ end
+ if sig == "ST" then
+ break
+ elseif sig == "CE" and len >= 28 then
+ local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20)
+ local at = base + blk * bs + off
+ budget[1] -= 1
+ if budget[1] < 0 or at < base or at + n > limit or n > 65536 then
+ break
+ end
+ -- the rest of this area first, then the continuation (it holds what did not fit)
+ local rest = suspEntries(b, base, limit, o + len, e, bs, budget)
+ for _, x in rest do
+ table.insert(out, x)
+ end
+ local cont = suspEntries(b, base, limit, at, at + n, bs, budget)
+ for _, x in cont do
+ table.insert(out, x)
+ end
+ return out
+ end
+ table.insert(out, { sig, o, len })
+ o += len
+ end
+ return out
+end
+
+-- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs }
+local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp
+ local rr: Susp = {}
+ local name: { string }? = nil
+ local slParts: { string }? = nil
+ local slRoot = false
+ local slCont = false
+ for _, x in suspEntries(b, base, limit, o, e, bs, { 32 }) do
+ local sig, at, len = x[1], x[2], x[3]
+ if sig == "NM" and len >= 5 then
+ local flags = buffer.readu8(b, at + 4)
+ if bit32.band(flags, 6) == 0 then
+ name = name or {}
+ table.insert(name :: { string }, buffer.readstring(b, at + 5, len - 5))
+ end
+ elseif sig == "PX" and len >= 36 then
+ rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28)
+ elseif sig == "PN" and len >= 20 then
+ rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12)
+ elseif sig == "TF" and len >= 5 then
+ local flags = buffer.readu8(b, at + 4)
+ local w = if bit32.band(flags, 0x80) ~= 0 then 17 else 7
+ local q = at + 5
+ for bit = 0, 6 do
+ if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then
+ if q + w > at + len then
+ break
+ end
+ if bit == 1 then
+ rr.mtime = if w == 17 then longDate(b, q) else recDate(b, q)
+ end
+ q += w
+ end
+ end
+ elseif sig == "SL" and len >= 5 then
+ slParts = slParts or {}
+ local parts = slParts :: { string }
+ local q = at + 5
+ while q + 2 <= at + len do
+ local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1)
+ if q + 2 + cl > at + len then
+ break
+ end
+ local piece = if bit32.band(cf, 2) ~= 0 then "." elseif bit32.band(cf, 4) ~= 0 then ".." else buffer.readstring(b, q + 2, cl)
+ if bit32.band(cf, 8) ~= 0 then
+ slRoot = #parts == 0
+ piece = ""
+ end
+ if slCont and #parts > 0 then
+ parts[#parts] ..= piece
+ elseif bit32.band(cf, 8) == 0 or #parts > 0 then
+ table.insert(parts, piece)
+ end
+ slCont = bit32.band(cf, 1) ~= 0
+ q += 2 + cl
+ end
+ elseif sig == "CL" and len >= 12 then
+ rr.child = u32(b, at + 4)
+ elseif sig == "RE" then
+ rr.relocated = true
+ elseif sig == "ZF" then
+ rr.zisofs = true
+ end
+ end
+ if name then
+ rr.name = table.concat(name)
+ end
+ if slParts then
+ rr.link = (if slRoot then "/" else "") .. table.concat(slParts, "/")
+ end
+ return rr
+end
+
+-- ------------------------------------------------------------------------------------------------ directories
+type Record = {
+ name: string,
+ dir: boolean,
+ lba: number,
+ size: number,
+ ear: number,
+ flags: number,
+ interleave: boolean,
+ mtime: number?,
+ rr: Susp?,
+}
+
+-- the records of a directory extent (without "." and "..") | nil, Err
+local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?)
+ if at + size > limit then
+ return nil, Err.new(Err.TRUNCATED, "directory past the end", at)
+ end
+ local out: { Record } = {}
+ local p = at
+ local e = at + size
+ while p < e do
+ local len = buffer.readu8(b, p)
+ if len == 0 then
+ p = at + ((p - at) // SECTOR + 1) * SECTOR -- the rest of the sector is padding
+ continue
+ end
+ if len < 34 or p + len > e then
+ return nil, Err.new(Err.CORRUPT, "bad directory record", p)
+ end
+ local nl = buffer.readu8(b, p + 32)
+ if 33 + nl > len then
+ return nil, Err.new(Err.CORRUPT, "bad name length", p + 32)
+ end
+ local raw = buffer.readstring(b, p + 33, nl)
+ if raw ~= "\0" and raw ~= "\1" then
+ local flags = buffer.readu8(b, p + 25)
+ local name
+ if joliet then
+ name = Text.utf16(b, p + 33, nl, true)
+ else
+ name = raw
+ end
+ name = string.gsub(name, ";%d*$", "")
+ if not joliet and bit32.band(flags, 2) == 0 then
+ name = string.gsub(name, "%.$", "")
+ end
+ local r: Record = {
+ name = name,
+ dir = bit32.band(flags, 2) ~= 0,
+ lba = u32(b, p + 2),
+ size = u32(b, p + 10),
+ ear = buffer.readu8(b, p + 1),
+ flags = flags,
+ interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0,
+ mtime = recDate(b, p + 18),
+ rr = nil,
+ }
+ if rrSkip then
+ local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + rrSkip
+ r.rr = rockRidge(b, base, limit, su, p + len, bs)
+ end
+ table.insert(out, r)
+ end
+ p += len
+ end
+ return out, nil
+end
+
+-- the root record of a volume descriptor at vd -> lba, size
+local function root(b: buffer, vd: number): (number, number)
+ return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10)
+end
+
+-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length
+local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number, bs: number): number?
+ local p = base + lba * bs
+ if p + 34 > limit then
+ return nil
+ end
+ local len = buffer.readu8(b, p)
+ local nl = buffer.readu8(b, p + 32)
+ local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0)
+ if len < 34 or su + 7 > p + len or p + len > limit then
+ return nil
+ end
+ if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then
+ return buffer.readu8(b, su + 6)
+ end
+ return nil
+end
+
+-- ------------------------------------------------------------------------------------------------ El Torito
+local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }?
+ if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then
+ return nil
+ end
+ local cat = u32(b, vd + 0x47)
+ local p = base + cat * bs
+ local info: { [string]: any } = { catalog = cat }
+ if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then
+ return info
+ end
+ local sum = 0
+ for i = 0, 30, 2 do
+ sum += u16(b, p + i)
+ end
+ info.valid = sum % 65536 == 0
+ info.platform = buffer.readu8(b, p + 1)
+ info.id = str(b, p + 4, 24)
+ local d = p + 32
+ info.bootable = buffer.readu8(b, d) == 0x88
+ info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk
+ info.loadSegment = u16(b, d + 2)
+ info.systemType = buffer.readu8(b, d + 4)
+ info.sectors = u16(b, d + 6) -- 512-byte virtual sectors
+ info.lba = u32(b, d + 8)
+ return info
+end
+
+-- ------------------------------------------------------------------------------------------------ read
+-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
+function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
+ local base = offset or 0
+ local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base)))
+ local o: ReadOptions = opts or {}
+ local maxEntries = o.maxEntries or 1e6
+ local pvd: number? = nil
+ local svd: number? = nil
+ local jolietLevel: number? = nil
+ local bootInfo = nil
+ local p = base + 16 * SECTOR
+ for _ = 1, 64 do
+ if p + SECTOR > limit then
+ return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p)
+ end
+ if buffer.readstring(b, p + 1, 5) ~= "CD001" then
+ return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p)
+ end
+ local t = buffer.readu8(b, p)
+ if t == 255 then
+ break
+ elseif t == 1 and not pvd then
+ pvd = p
+ elseif t == 2 then
+ local esc = buffer.readstring(b, p + 88, 3)
+ if esc == "%/@" or esc == "%/C" or esc == "%/E" then
+ svd = p
+ jolietLevel = if esc == "%/@" then 1 elseif esc == "%/C" then 2 else 3
+ end
+ elseif t == 0 then
+ bootInfo = bootInfo or { vd = p }
+ end
+ p += SECTOR
+ end
+ if not pvd then
+ return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR)
+ end
+ local pv = pvd :: number
+ local bs = u16(b, pv + 128)
+ if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then
+ return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128)
+ end
+ local info: { [string]: any } = {
+ blockSize = bs,
+ blocks = u32(b, pv + 80),
+ systemId = str(b, pv + 8, 32),
+ volumeId = str(b, pv + 40, 32),
+ volumeSet = str(b, pv + 190, 128),
+ publisher = str(b, pv + 318, 128),
+ preparer = str(b, pv + 446, 128),
+ application = str(b, pv + 574, 128),
+ created = longDate(b, pv + 813),
+ modified = longDate(b, pv + 830),
+ joliet = jolietLevel,
+ }
+ if bootInfo then
+ info.boot = boot(b, base, limit, bootInfo.vd, bs)
+ end
+ local rlba, rsize = root(b, pv)
+ local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs)
+ info.rockRidge = rrSkip ~= nil
+ local tree = o.prefer or (if rrSkip then "rockridge" elseif svd then "joliet" else "iso9660")
+ if tree == "joliet" and not svd then
+ tree = "iso9660"
+ elseif tree == "rockridge" and not rrSkip then
+ tree = "iso9660"
+ end
+ info.tree = tree
+ local joliet = tree == "joliet"
+ local useRR = if tree == "rockridge" then rrSkip else nil
+ if joliet then
+ rlba, rsize = root(b, svd :: number)
+ end
+ if tree == "joliet" then
+ info.volumeId = (string.gsub(Text.utf16(b, (svd :: number) + 40, 32, true), "[ %z]+$", ""))
+ end
+ local out: { Entry } = {}
+ local visited: { [number]: boolean } = {}
+ local stack = { { lba = rlba, size = rsize, path = "" } }
+ local relocatedDirs: { [string]: boolean } = {}
+ while #stack > 0 do
+ local d = table.remove(stack) :: any
+ if visited[d.lba] then
+ continue
+ end
+ visited[d.lba] = true
+ local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR)
+ if not list then
+ return nil, err
+ end
+ local i = 1
+ local subdirs = {}
+ while i <= #list do
+ local r = list[i]
+ -- multi-extent: this record and the following ones of the same name
+ local extents: { Extent } = { { at = base + (r.lba + r.ear) * bs, size = r.size } }
+ local total = r.size
+ local last = r
+ while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do
+ i += 1
+ last = list[i]
+ table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size })
+ total += last.size
+ end
+ i += 1
+ if bit32.band(r.flags, 4) ~= 0 then
+ continue -- an associated file (resource fork)
+ end
+ local rr: any = r.rr
+ if rr and rr.relocated then
+ continue -- shown where its CL placeholder is
+ end
+ local name = if rr and rr.name then rr.name else r.name
+ local path = d.path .. name
+ local isDir = r.dir
+ local lba: number, size: number = r.lba, r.size
+ if rr and rr.child then
+ -- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's
+ isDir = true
+ lba = rr.child
+ local q = base + lba * bs
+ size = if q + 14 <= limit then u32(b, q + 10) else 0
+ end
+ local typ = if isDir then "5" else "0"
+ if rr and rr.mode then
+ typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ
+ end
+ local e: Entry = {
+ name = path,
+ dir = isDir,
+ size = if isDir or typ ~= "0" then 0 else total,
+ extents = if isDir or typ ~= "0" then {} else extents,
+ mtime = if rr and rr.mtime then rr.mtime else r.mtime,
+ type = typ,
+ mode = if rr and rr.mode then bit32.band(rr.mode, 0xFFF) else nil,
+ uid = rr and rr.uid,
+ gid = rr and rr.gid,
+ nlink = rr and rr.nlink,
+ link = if rr and typ == "2" then rr.link else nil,
+ rdev = rr and rr.rdev,
+ hidden = if bit32.band(r.flags, 1) ~= 0 then true else nil,
+ interleaved = if r.interleave then true else nil,
+ zisofs = if rr and rr.zisofs then true else nil,
+ }
+ table.insert(out, e)
+ if #out > maxEntries then
+ return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
+ end
+ if isDir then
+ table.insert(subdirs, { lba = lba, size = size, path = path .. "/" })
+ end
+ end
+ for k = #subdirs, 1, -1 do
+ table.insert(stack, subdirs[k])
+ end
+ if useRR then
+ for _, r in list do
+ if r.rr and r.rr.relocated then
+ relocatedDirs[d.path] = true
+ end
+ end
+ end
+ end
+ -- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it
+ if useRR then
+ for dirPath in relocatedDirs do
+ local name = string.sub(dirPath, 1, -2)
+ local holds = false
+ for _, e in out do
+ if string.sub(e.name, 1, #dirPath) == dirPath then
+ holds = true
+ break
+ end
+ end
+ if not holds then
+ for k, e in out do
+ if e.name == name then
+ table.remove(out, k)
+ break
+ end
+ end
+ end
+ end
+ end
+ -- archive order: depth-first walk order is kept; directories sorted as the image stores them
+ return out, info
+end
+
+-- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err
+function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?)
+ if e.interleaved then
+ return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name)
+ end
+ local lim = limit or buffer.len(b)
+ local out = buffer.create(e.size)
+ local q = 0
+ for _, x in e.extents do
+ if x.at < 0 or x.at + x.size > lim then
+ return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at)
+ end
+ buffer.copy(out, q, b, x.at, x.size)
+ q += x.size
+ end
+ return out, nil
+end
+
+-- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16
+function Iso9660.valid(b: buffer, offset: number?): boolean
+ local p = (offset or 0) + 16 * SECTOR
+ return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001"
+end
+
+return Iso9660
diff --git a/src/Formats/containers/MacFile.luau b/src/Formats/containers/MacFile.luau
new file mode 100644
index 0000000..be198aa
--- /dev/null
+++ b/src/Formats/containers/MacFile.luau
@@ -0,0 +1,158 @@
+--!strict
+-- containers/MacFile: classic Mac OS files (a data fork, a resource fork and Finder info) as Archive entries, shared by
+-- the Mac encodings (archive/binhex, archive/macbinary, archive/applesingle). The convention (unar's "visible forks"):
+-- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with
+-- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix
+-- seconds) and comment. Writers pair them back with collect().
+--
+-- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" })
+-- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string
+-- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes
+-- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped)
+-- New code. Never throws.
+local Err = require("@formats/core/Err")
+local Archive = require("@formats/containers/Archive")
+
+local MacFile = {}
+
+export type Info = {
+ name: string,
+ data: buffer,
+ rsrc: buffer,
+ type: string, -- 4 bytes ("\0\0\0\0" when unknown)
+ creator: string,
+ flags: number, -- Finder flags (16 bits)
+ created: number?, -- unix seconds
+ modified: number?,
+ comment: string?,
+}
+
+local MAC_EPOCH = 2082844800 -- seconds from 1904-01-01 to 1970-01-01
+
+function MacFile.fromMac(s: number): number?
+ return if s == 0 then nil else s - MAC_EPOCH
+end
+
+function MacFile.toMac(unix: number?): number
+ if type(unix) ~= "number" or unix ~= unix then
+ return 0
+ end
+ return math.clamp(math.floor(unix + MAC_EPOCH), 0, 0xFFFFFFFF)
+end
+
+-- Mac OS Roman bytes 0x80..0xFF
+local ROMAN = {
+ 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8,
+ 0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC,
+ 0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8,
+ 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8,
+ 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153,
+ 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02,
+ 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4,
+ 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7,
+}
+local FROM_UNICODE: { [number]: number } = {}
+for i, u in ROMAN do
+ FROM_UNICODE[u] = 127 + i
+end
+
+-- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through)
+function MacFile.name(s: string): string
+ if not string.find(s, "[\128-\255]") then
+ return s
+ end
+ local out = table.create(#s)
+ for i = 1, #s do
+ local c = string.byte(s, i)
+ out[i] = if c < 128 then string.char(c) else utf8.char(ROMAN[c - 127])
+ end
+ return table.concat(out)
+end
+
+-- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes)
+function MacFile.roman(s: string): string
+ if not string.find(s, "[\128-\255]") or not utf8.len(s) then
+ return s
+ end
+ local out = {}
+ for _, c in utf8.codes(s) do
+ table.insert(out, if c < 128 then string.char(c) else string.char(FROM_UNICODE[c] or 63))
+ end
+ return table.concat(out)
+end
+
+local function four(s: any): string
+ if type(s) ~= "string" then
+ return "\0\0\0\0"
+ end
+ return string.sub(s .. "\0\0\0\0", 1, 4)
+end
+
+-- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and
+-- there is a resource fork) and, when non-empty, the resource fork entry
+function MacFile.put(a: any, f: Info, noData: boolean?)
+ local common = {
+ macType = f.type,
+ macCreator = f.creator,
+ finderFlags = f.flags,
+ created = f.created,
+ mtime = f.modified,
+ comment = f.comment,
+ dir = false,
+ }
+ local e: any = table.clone(common)
+ e.name, e.size, e.data, e.fork = f.name, buffer.len(f.data), f.data, "data"
+ if not noData and (buffer.len(f.data) > 0 or buffer.len(f.rsrc) == 0) then
+ Archive.put(a, e)
+ end
+ if buffer.len(f.rsrc) > 0 then
+ local r: any = table.clone(common)
+ r.name, r.size, r.data, r.fork = f.name .. ".rsrc", buffer.len(f.rsrc), f.rsrc, "resource"
+ Archive.put(a, r)
+ end
+end
+
+-- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a
+-- buffer or a string (one data fork named name, default "data")
+function MacFile.collect(value: any, name: string?): ({ Info }?, Err.Err?)
+ local files, err = Archive.files(value, name)
+ if not files then
+ return nil, err
+ end
+ local out: { Info } = {}
+ local byName: { [string]: Info } = {}
+ local function get(n: string, e: any): Info
+ local f = byName[n]
+ if not f then
+ f = {
+ name = n,
+ data = buffer.create(0),
+ rsrc = buffer.create(0),
+ type = four(e.macType),
+ creator = four(e.macCreator),
+ flags = if type(e.finderFlags) == "number" then bit32.band(e.finderFlags, 0xFFFF) else 0,
+ created = if type(e.created) == "number" then e.created else nil,
+ modified = if type(e.mtime) == "number" then e.mtime else nil,
+ comment = if type(e.comment) == "string" then e.comment else nil,
+ }
+ byName[n] = f
+ table.insert(out, f)
+ end
+ return f :: Info
+ end
+ -- data forks first, so a resource fork finds its file whatever the order
+ for _, it in files do
+ if it.entry.fork ~= "resource" then
+ get(it.name, it.entry).data = it.data
+ end
+ end
+ for _, it in files do
+ if it.entry.fork == "resource" then
+ local base = string.match(it.name, "^(.*)%.rsrc$") or it.name
+ get(base, it.entry).rsrc = it.data
+ end
+ end
+ return out, nil
+end
+
+return MacFile
diff --git a/src/Formats/core/Crc16.luau b/src/Formats/core/Crc16.luau
new file mode 100644
index 0000000..4a2caac
--- /dev/null
+++ b/src/Formats/core/Crc16.luau
@@ -0,0 +1,52 @@
+--!strict
+--!native
+-- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code.
+-- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0,
+-- MacBinary II / III headers)
+-- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC)
+-- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer.
+local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift
+local readu8 = buffer.readu8
+
+local MSB = table.create(256, 0)
+local ARC = table.create(256, 0)
+for n = 0, 255 do
+ local c = lshift(n, 8)
+ for _ = 1, 8 do
+ c = if band(c, 0x8000) ~= 0 then bxor(band(lshift(c, 1), 0xFFFF), 0x1021) else band(lshift(c, 1), 0xFFFF)
+ end
+ MSB[n + 1] = c
+ local r = n
+ for _ = 1, 8 do
+ r = if band(r, 1) ~= 0 then bxor(rshift(r, 1), 0xA001) else rshift(r, 1)
+ end
+ ARC[n + 1] = r
+end
+
+local Crc16 = {}
+
+local function clamp(buf: buffer, off: number, len: number): (number, number)
+ local n = buffer.len(buf)
+ local o = math.clamp(math.floor(off), 0, n)
+ return o, math.clamp(math.floor(len), 0, n - o)
+end
+
+function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number
+ local o, l = clamp(buf, off, len)
+ local c = crc or 0
+ for i = o, o + l - 1 do
+ c = bxor(band(lshift(c, 8), 0xFFFF), MSB[bxor(rshift(c, 8), readu8(buf, i)) + 1])
+ end
+ return c
+end
+
+function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number
+ local o, l = clamp(buf, off, len)
+ local c = crc or 0
+ for i = o, o + l - 1 do
+ c = bxor(rshift(c, 8), ARC[bxor(band(c, 0xFF), readu8(buf, i)) + 1])
+ end
+ return c
+end
+
+return Crc16
diff --git a/src/Formats/font/bdf/init.luau b/src/Formats/font/bdf/init.luau
new file mode 100644
index 0000000..700f119
--- /dev/null
+++ b/src/Formats/font/bdf/init.luau
@@ -0,0 +1,295 @@
+--!strict
+-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the
+-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in
+-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used),
+-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to
+-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for
+-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and
+-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font
+-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification.
+-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Bitmap = require("@formats/codecs/font/Bitmap")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Bdf = {
+ name = "bdf",
+ category = "font",
+ extensions = { "bdf" },
+ mime = { "application/x-font-bdf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = true, bitmap = true },
+}
+
+export type DecodeOptions = { maxGlyphs: number? } -- default 1114112
+export type EncodeOptions = {
+ px: number?, -- pixel size for outline fonts (default 16)
+ chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
+ name: string?, -- the FONT (XLFD) name (default built from the font's family / style)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Bdf.sniff(r: Bytes.Reader): number
+ local head = r:peek(32)
+ return if string.match(head, "^STARTFONT%s+2%.%d") then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+local function unquote(v: string): any
+ local s = string.match(v, '^"(.*)"%s*$')
+ if s then
+ return (string.gsub(s, '""', '"'))
+ end
+ return tonumber(v) or v
+end
+
+local function hexRow(line: string, w: number, row: buffer, rowOff: number)
+ local n = math.min(#line // 2, math.ceil(w / 8))
+ for i = 0, n - 1 do
+ local v = tonumber(string.sub(line, i * 2 + 1, i * 2 + 2), 16) or 0
+ buffer.writeu8(row, rowOff + i, v)
+ end
+end
+
+function Bdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxGlyphs = o.maxGlyphs or 1114112
+ local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ local lines = string.split(text, "\n")
+ local props: { [string]: any } = {}
+ local fontName, size = "", 0
+ local fbb = { 0, 0, 0, 0 }
+ local fontDw = 0
+ local glyphs: { Types.BitmapGlyph } = {}
+ local encodings: { number } = {}
+ local i = 1
+ local n = #lines
+ local function line(): string
+ local l = string.gsub(lines[i] or "", "\r$", "")
+ i += 1
+ return l
+ end
+ local first = line()
+ if not string.match(first, "^STARTFONT%s") then
+ return nil, Err.new(Err.CORRUPT, "no STARTFONT")
+ end
+ local ended = false
+ while i <= n do
+ local l = line()
+ local key, rest = string.match(l, "^(%S+)%s*(.*)$")
+ if key == "FONT" then
+ fontName = rest :: string
+ elseif key == "SIZE" then
+ size = tonumber(string.match(rest :: string, "^(%S+)")) or 0
+ elseif key == "FONTBOUNDINGBOX" then
+ local a, b, c, d = string.match(rest :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)")
+ fbb = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 }
+ elseif key == "DWIDTH" then
+ fontDw = tonumber(string.match(rest :: string, "^(%-?%d+)")) or 0
+ elseif key == "STARTPROPERTIES" then
+ while i <= n do
+ local pl = line()
+ if string.match(pl, "^ENDPROPERTIES") then
+ break
+ end
+ local pk, pv = string.match(pl, "^(%S+)%s*(.*)$")
+ if pk then
+ props[pk :: string] = unquote(pv :: string)
+ end
+ end
+ elseif key == "STARTCHAR" then
+ if #glyphs >= maxGlyphs then
+ return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
+ end
+ local name = rest :: string
+ local enc = -1
+ local dw = fontDw
+ local bbx = { fbb[1], fbb[2], fbb[3], fbb[4] }
+ local px: buffer? = nil
+ while i <= n do
+ local cl = line()
+ local ck, cr = string.match(cl, "^(%S+)%s*(.*)$")
+ if ck == "ENCODING" then
+ local e1, e2 = string.match(cr :: string, "^(%-?%d+)%s*(%-?%d*)")
+ enc = tonumber(e1) or -1
+ if enc == -1 and e2 and e2 ~= "" then
+ enc = -(tonumber(e2) or 1) - 1 -- a non-standard code: kept negative (meta.encodings)
+ end
+ elseif ck == "DWIDTH" then
+ dw = tonumber(string.match(cr :: string, "^(%-?%d+)")) or dw
+ elseif ck == "BBX" then
+ local a, b, c, d = string.match(cr :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)")
+ bbx = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 }
+ elseif ck == "BITMAP" then
+ local w, h = bbx[1], bbx[2]
+ if w < 0 or h < 0 or w > 4096 or h > 4096 then
+ return nil, Err.new(Err.CORRUPT, "bad BBX in " .. name)
+ end
+ local stride = math.ceil(w / 8)
+ local rows = buffer.create(stride * h)
+ for y = 0, h - 1 do
+ local rl = string.gsub(lines[i] or "", "%s", "")
+ if string.match(rl, "^ENDCHAR") then
+ break
+ end
+ i += 1
+ hexRow(rl, w, rows, y * stride)
+ end
+ px = Bitmap.unpack(rows, 0, w, h, stride)
+ elseif ck == "ENDCHAR" then
+ break
+ end
+ end
+ local gl: Types.BitmapGlyph = {
+ name = name,
+ codepoint = nil,
+ width = bbx[1],
+ height = bbx[2],
+ left = bbx[3],
+ top = bbx[4] + bbx[2],
+ advance = dw,
+ pixels = px or buffer.create(math.max(0, bbx[1] * bbx[2])),
+ }
+ table.insert(glyphs, gl)
+ table.insert(encodings, enc)
+ elseif key == "ENDFONT" then
+ ended = true
+ break
+ end
+ end
+ if not ended then
+ return nil, Err.new(Err.TRUNCATED, "no ENDFONT")
+ end
+ local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil
+ local cset = if type(props.CHARSET_ENCODING) == "string" or type(props.CHARSET_ENCODING) == "number" then tostring(props.CHARSET_ENCODING) else nil
+ local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1")
+ local default: number? = nil
+ for k, gl in glyphs do
+ local enc = encodings[k]
+ if unicode and enc >= 0 then
+ gl.codepoint = enc
+ end
+ if type(props.DEFAULT_CHAR) == "number" and enc == props.DEFAULT_CHAR then
+ default = k - 1
+ end
+ end
+ local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (if fbb[2] > 0 then fbb[2] else size)
+ local strike: Types.BitmapStrike = {
+ size = pixelSize,
+ ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else fbb[2] + fbb[4],
+ descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else -fbb[4],
+ glyphs = glyphs,
+ default = default,
+ }
+ local slant = props.SLANT
+ local weight = props.WEIGHT_NAME
+ local style = (if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "")
+ if slant == "I" or slant == "O" then
+ style = (if style ~= "" then style .. " " else "") .. "Italic"
+ end
+ local info = {
+ family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else fontName,
+ style = if style ~= "" then style else "Regular",
+ fullName = fontName,
+ }
+ local font = Bitmap.font(strike, info, {
+ properties = props,
+ encodings = encodings,
+ unicode = unicode,
+ fontName = fontName,
+ boundingBox = fbb,
+ source = { format = "bdf", charset = if registry then registry .. "-" .. tostring(cset) else nil },
+ })
+ return font, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function quote(s: string): string
+ return '"' .. string.gsub(s, '"', '""') .. '"'
+end
+
+function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars })
+ if not strike then
+ return nil, err
+ end
+ local info = if type(font.info) == "table" then font.info else {}
+ local family = string.gsub(tostring(info.family or "formats-luau"), "[%-\n\r\"]", " ")
+ local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil
+ local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil
+ local px = strike.size
+ -- the font bounding box
+ local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
+ for _, g in strike.glyphs do
+ if g.width > 0 and g.height > 0 then
+ x0 = math.min(x0, g.left)
+ x1 = math.max(x1, g.left + g.width)
+ y0 = math.min(y0, g.top - g.height)
+ y1 = math.max(y1, g.top)
+ end
+ end
+ if x0 == math.huge then
+ x0, y0, x1, y1 = 0, 0, 0, 0
+ end
+ local name = o.name
+ or string.format("-formats-%s-%s-%s-normal--%d-%d-75-75-c-%d-ISO10646-1", family, if bold then "bold" else "medium", if italic then "i" else "r", px, px * 10, (x1 - x0) * 10)
+ local out = {
+ "STARTFONT 2.1",
+ "FONT " .. name,
+ string.format("SIZE %d 75 75", px),
+ string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0),
+ }
+ -- the default glyph: the strike's default, else glyph 0
+ local defaultIndex = (strike.default or 0) + 1
+ local props: { { any } } = {
+ { "FAMILY_NAME", quote(family) },
+ { "WEIGHT_NAME", quote(if bold then "Bold" else "Medium") },
+ { "SLANT", quote(if italic then "I" else "R") },
+ { "PIXEL_SIZE", px },
+ { "POINT_SIZE", px * 10 },
+ { "RESOLUTION_X", 75 },
+ { "RESOLUTION_Y", 75 },
+ { "CHARSET_REGISTRY", quote("ISO10646") },
+ { "CHARSET_ENCODING", quote("1") },
+ { "FONT_ASCENT", strike.ascent },
+ { "FONT_DESCENT", strike.descent },
+ }
+ local dg = strike.glyphs[defaultIndex]
+ if dg and dg.codepoint then
+ table.insert(props, { "DEFAULT_CHAR", dg.codepoint })
+ end
+ table.insert(out, "STARTPROPERTIES " .. #props)
+ for _, p in props do
+ table.insert(out, p[1] .. " " .. tostring(p[2]))
+ end
+ table.insert(out, "ENDPROPERTIES")
+ table.insert(out, "CHARS " .. #strike.glyphs)
+ for k, g in strike.glyphs do
+ local gname = g.name or (if g.codepoint then string.format("uni%04X", g.codepoint) else "glyph" .. (k - 1))
+ table.insert(out, "STARTCHAR " .. string.gsub(gname, "%s", "_"))
+ table.insert(out, "ENCODING " .. (if g.codepoint then tostring(g.codepoint) else "-1"))
+ table.insert(out, string.format("SWIDTH %d 0", math.floor(g.advance * 1000 / math.max(1, px) + 0.5)))
+ table.insert(out, string.format("DWIDTH %d 0", g.advance))
+ table.insert(out, string.format("BBX %d %d %d %d", g.width, g.height, g.left, g.top - g.height))
+ table.insert(out, "BITMAP")
+ local stride = math.ceil(g.width / 8)
+ local rows = Bitmap.pack(g.pixels, g.width, g.height, stride)
+ for y = 0, g.height - 1 do
+ local hex = table.create(stride)
+ for x = 0, stride - 1 do
+ hex[x + 1] = string.format("%02X", buffer.readu8(rows, y * stride + x))
+ end
+ table.insert(out, table.concat(hex))
+ end
+ table.insert(out, "ENDCHAR")
+ end
+ table.insert(out, "ENDFONT")
+ return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil
+end
+
+return Bdf
diff --git a/src/Formats/font/eot/init.luau b/src/Formats/font/eot/init.luau
new file mode 100644
index 0000000..463f786
--- /dev/null
+++ b/src/Formats/font/eot/init.luau
@@ -0,0 +1,233 @@
+--!strict
+-- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset,
+-- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and
+-- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot
+-- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string,
+-- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C
+-- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Text = require("@formats/codecs/text/Text")
+local TrueType = require("@formats/codecs/font/TrueType")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Eot = {
+ name = "eot",
+ category = "font",
+ extensions = { "eot" },
+ mime = { "application/vnd.ms-fontobject" },
+ deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" },
+ caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } },
+}
+
+export type DecodeOptions = {}
+export type EncodeOptions = {
+ xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false)
+ rootString: string?, -- the URLs allowed to use the font (default "")
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local MAGIC = 0x504C
+local COMPRESSED, XOR = 0x4, 0x10000000
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Eot.sniff(r: Bytes.Reader): number
+ local h = r:peek(36)
+ if #h < 36 then
+ return 0
+ end
+ local ver = string.sub(h, 9, 12)
+ local magic = string.byte(h, 35) + string.byte(h, 36) * 256
+ if magic == MAGIC and (ver == "\0\0\1\0" or ver == "\1\0\2\0" or ver == "\2\0\2\0") then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Eot.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local eotSize, dataSize, version, flags = r:u32le(), r:u32le(), r:u32le(), r:u32le()
+ local panose = r:string(10)
+ local charset, italic = r:u8(), r:u8()
+ local weight = r:u32le()
+ local fsType, magic = r:u16le(), r:u16le()
+ local ranges = { r:u32le(), r:u32le(), r:u32le(), r:u32le() }
+ local codepages = { r:u32le(), r:u32le() }
+ local checksum = r:u32le()
+ r:skip(16)
+ if r.err then
+ return nil, r.err
+ end
+ if magic ~= MAGIC then
+ return nil, Err.new(Err.CORRUPT, "bad magic number")
+ end
+ if version ~= 0x00010000 and version ~= 0x00020001 and version ~= 0x00020002 then
+ return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%08x", version))
+ end
+ local function name(): string
+ r:skip(2)
+ local n = r:u16le()
+ local s = r:bytes(n)
+ return Text.utf16(s, 0, buffer.len(s))
+ end
+ local eot: { [string]: any } = {
+ version = version,
+ flags = flags,
+ panose = panose,
+ charset = charset,
+ italic = italic ~= 0,
+ weight = weight,
+ fsType = fsType,
+ unicodeRange = ranges,
+ codePageRange = codepages,
+ checkSumAdjustment = checksum,
+ eotSize = eotSize,
+ }
+ eot.familyName, eot.styleName, eot.versionName, eot.fullName = name(), name(), name(), name()
+ if version >= 0x00020001 then
+ eot.rootString = name()
+ end
+ if version == 0x00020002 then
+ eot.rootStringChecksum = r:u32le()
+ eot.eudcCodePage = r:u32le()
+ r:skip(2)
+ r:skip(r:u16le()) -- signature
+ eot.eudcFlags = r:u32le()
+ r:skip(r:u32le()) -- EUDC font data
+ end
+ if r.err then
+ return nil, r.err
+ end
+ if bit32.band(flags, COMPRESSED) ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "MicroType Express compressed font data")
+ end
+ local data = r:bytes(dataSize)
+ if r.err then
+ return nil, r.err
+ end
+ if bit32.band(flags, XOR) ~= 0 then
+ for i = 0, dataSize - 1 do
+ buffer.writeu8(data, i, bit32.bxor(buffer.readu8(data, i), 0x50))
+ end
+ end
+ local font, ferr = TrueType.font(data)
+ if not font then
+ return nil, ferr
+ end
+ font.meta.eot = eot
+ font.meta.fontData = data
+ font.meta.source = { format = "eot", version = version, outlines = font.meta.outlines }
+ return font, nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function utf16(s: string): string
+ local out = {}
+ if utf8.len(s) then
+ for _, c in utf8.codes(s) do
+ if c >= 0x10000 then
+ c -= 0x10000
+ local hi, lo = 0xD800 + bit32.rshift(c, 10), 0xDC00 + bit32.band(c, 0x3FF)
+ table.insert(out, string.char(hi % 256, hi // 256, lo % 256, lo // 256))
+ else
+ table.insert(out, string.char(c % 256, c // 256))
+ end
+ end
+ end
+ return table.concat(out)
+end
+
+function Eot.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local data: buffer
+ if type(value) == "buffer" then
+ data = value
+ elseif type(value) == "string" then
+ data = buffer.fromstring(value)
+ elseif type(value) == "table" and type(value.meta) == "table" and type(value.meta.fontData) == "buffer" then
+ data = value.meta.fontData
+ else
+ return nil, Err.new(Err.ARG, "expected TrueType bytes (or a Font read from an EOT)")
+ end
+ local font, ferr = TrueType.font(data)
+ if not font then
+ return nil, ferr
+ end
+ local tables: { [string]: { number } } = TrueType.tables(data, 0, 0, buffer.len(data)) or {}
+ local function tab(tagName: string): Bytes.Reader?
+ local t: { number }? = tables[tagName]
+ return if t then Bytes.reader(data, t[1], t[2]) else nil
+ end
+ -- OS/2: PANOSE, weight, fsType, ranges, selection; head: checkSumAdjustment
+ local panose, weight, fsType, italic, charset = string.rep("\0", 10), 400, 0, 0, 1
+ local ranges, codepages = { 0, 0, 0, 0 }, { 0, 0 }
+ local os2 = tab("OS/2")
+ if os2 then
+ os2:seek(4)
+ weight = os2:u16be()
+ os2:seek(8)
+ fsType = os2:u16be()
+ os2:seek(32)
+ panose = os2:string(10)
+ ranges = { os2:u32be(), os2:u32be(), os2:u32be(), os2:u32be() }
+ os2:seek(62)
+ local sel = os2:u16be()
+ italic = if bit32.band(sel, 1) ~= 0 then 1 else 0
+ os2:seek(78)
+ codepages = { os2:u32be(), os2:u32be() }
+ if os2.err then
+ codepages = { 0, 0 }
+ end
+ end
+ local head = tab("head")
+ local checksum = 0
+ if head then
+ head:seek(8)
+ checksum = head:u32be()
+ end
+ local info = font.info or {}
+ local names = { info.family or "", info.style or "", info.version or "", info.fullName or "" }
+ local w = Bytes.writer(buffer.len(data) + 512)
+ w:u32le(0) -- EOTSize, patched
+ w:u32le(buffer.len(data))
+ w:u32le(0x00020001)
+ w:u32le(if o.xor then XOR else 0)
+ w:string(panose)
+ w:u8(charset)
+ w:u8(italic)
+ w:u32le(weight)
+ w:u16le(fsType)
+ w:u16le(MAGIC)
+ for _, v in ranges do
+ w:u32le(v)
+ end
+ for _, v in codepages do
+ w:u32le(v)
+ end
+ w:u32le(checksum)
+ w:string(string.rep("\0", 16))
+ for _, s in names do
+ local u = utf16(tostring(s))
+ w:u16le(0)
+ w:u16le(#u)
+ w:string(u)
+ end
+ local root = utf16(o.rootString or "")
+ w:u16le(0)
+ w:u16le(#root)
+ w:string(root)
+ local start = w:tell()
+ w:bytes(data)
+ local out = w:finish()
+ if o.xor then
+ for i = start, start + buffer.len(data) - 1 do
+ buffer.writeu8(out, i, bit32.bxor(buffer.readu8(out, i), 0x50))
+ end
+ end
+ buffer.writeu32(out, 0, buffer.len(out))
+ return out, nil
+end
+
+return Eot
diff --git a/src/Formats/font/fon/init.luau b/src/Formats/font/fon/init.luau
new file mode 100644
index 0000000..a952523
--- /dev/null
+++ b/src/Formats/font/fon/init.luau
@@ -0,0 +1,288 @@
+--!strict
+-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the
+-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE
+-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first
+-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI
+-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset).
+-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts.
+-- Not supported: vector FNT (Err.UNSUPPORTED), writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Text = require("@formats/codecs/text/Text")
+local Bitmap = require("@formats/codecs/font/Bitmap")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Fon = {
+ name = "fon",
+ category = "font",
+ extensions = { "fon", "fnt" },
+ mime = { "application/x-font-fnt" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } },
+}
+
+export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first)
+
+-- ------------------------------------------------------------------------------------------------ sniff
+local function isFnt(h: string): boolean
+ if #h < 4 then
+ return false
+ end
+ local ver = string.byte(h, 1) + string.byte(h, 2) * 256
+ return ver == 0x200 or ver == 0x300
+end
+
+function Fon.sniff(r: Bytes.Reader): number
+ local h = r:peek(64)
+ if string.sub(h, 1, 2) == "MZ" and #h >= 64 then
+ local lfanew = string.byte(h, 61) + string.byte(h, 62) * 256 + string.byte(h, 63) * 65536
+ local sig = r:peek(2, lfanew)
+ return if sig == "NE" then 0.6 elseif sig == "PE" then 0.2 else 0
+ end
+ if isFnt(h) and #h >= 6 then
+ local size = string.byte(h, 3) + string.byte(h, 4) * 256 + string.byte(h, 5) * 65536 + string.byte(h, 6) * 16777216
+ return if size == r:size() then 0.9 elseif size <= r:size() and size > 118 then 0.3 else 0
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- one FNT resource -> Font
+local function fnt(r: Bytes.Reader): (any, Err.Err?)
+ local version = r:u16le()
+ local total = r:u32le()
+ local copyright = string.match(r:string(60), "^[^%z]*") or ""
+ local ftype = r:u16le()
+ local points, vres, hres = r:u16le(), r:u16le(), r:u16le()
+ local ascent = r:u16le()
+ r:skip(4) -- internal / external leading
+ local italic = r:u8()
+ r:skip(2)
+ local weight = r:u16le()
+ local charset = r:u8()
+ local pixWidth, pixHeight = r:u16le(), r:u16le()
+ r:skip(5) -- pitch and family, average / max width
+ local first, last, default = r:u8(), r:u8(), r:u8()
+ r:skip(1 + 2 + 4)
+ local faceAt = r:u32le()
+ if r.err then
+ return nil, r.err
+ end
+ if version ~= 0x200 and version ~= 0x300 then
+ return nil, Err.new(Err.CORRUPT, "not a FNT resource")
+ end
+ if bit32.band(ftype, 1) ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "vector fonts")
+ end
+ if last < first or pixHeight == 0 or pixHeight > 1024 then
+ return nil, Err.new(Err.CORRUPT, "bad character range or height")
+ end
+ r:seek(if version == 0x300 then 148 else 118)
+ local glyphs: { Types.BitmapGlyph } = {}
+ for c = first, last do
+ local w = r:u16le()
+ local off = if version == 0x300 then r:u32le() else r:u16le()
+ if r.err then
+ return nil, r.err
+ end
+ if w > 4096 then
+ return nil, Err.new(Err.CORRUPT, "bad glyph width")
+ end
+ -- column-major: byte column k holds pixels 8k .. 8k + 7 of every row
+ local h = pixHeight
+ local px = buffer.create(w * h)
+ local cols = math.ceil(w / 8)
+ local base = r.base + off
+ local limit = r.base + r:size()
+ for k = 0, cols - 1 do
+ for y = 0, h - 1 do
+ local p = base + k * h + y
+ if p >= 0 and p < limit then
+ local byte = buffer.readu8(r.buf, p)
+ for b = 0, 7 do
+ local x = k * 8 + b
+ if x < w and bit32.band(byte, bit32.rshift(0x80, b)) ~= 0 then
+ buffer.writeu8(px, y * w + x, 255)
+ end
+ end
+ end
+ end
+ end
+ local cp: number? = nil
+ if charset == 0 then
+ cp = if c >= 0x80 and c < 0xA0 then Text.CP1252[c] else c
+ elseif c < 0x80 then
+ cp = c
+ end
+ table.insert(glyphs, { codepoint = cp, width = w, height = h, left = 0, top = ascent, advance = w, pixels = px })
+ end
+ local face = ""
+ if faceAt > 0 and faceAt < r:size() then
+ face = r:sub(faceAt):cstring(256)
+ end
+ local dflt = default + first
+ local strike: Types.BitmapStrike = {
+ size = pixHeight,
+ ascent = ascent,
+ descent = pixHeight - ascent,
+ glyphs = glyphs,
+ default = if dflt >= first and dflt <= last then dflt - first else nil,
+ }
+ local style = (if weight >= 600 then "Bold" else "") .. (if italic ~= 0 then " Italic" else "")
+ style = string.gsub(style, "^ ", "")
+ return Bitmap.font(strike, { family = face, style = if style ~= "" then style else "Regular", fullName = face }, {
+ copyright = copyright,
+ points = points,
+ resolution = { hres, vres },
+ charset = charset,
+ weight = weight,
+ pixWidth = pixWidth,
+ firstChar = first,
+ source = { format = "fon", version = if version == 0x300 then 3 else 2, size = total },
+ }), nil
+end
+
+-- the RT_FONT resources of an NE executable: { { offset, length } }
+local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?)
+ local rt = r:sub(ne + 0x24, 2):u16le()
+ local t = r:sub(ne + rt)
+ local shift = t:u16le()
+ if shift > 16 then
+ return nil, "bad resource alignment"
+ end
+ local out = {}
+ for _ = 1, 64 do
+ local typeId = t:u16le()
+ if typeId == 0 or t.err then
+ break
+ end
+ local count = t:u16le()
+ t:skip(4)
+ for _ = 1, count do
+ local off, len = t:u16le(), t:u16le()
+ t:skip(8)
+ if typeId == 0x8008 then
+ table.insert(out, { off * 2 ^ shift, len * 2 ^ shift })
+ end
+ end
+ end
+ if t.err then
+ return nil, "truncated resource table"
+ end
+ return out, nil
+end
+
+-- the RT_FONT (8) resources of a PE executable: { { offset, length } }
+local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?)
+ local h = r:sub(pe + 4, 20)
+ h:skip(2)
+ local nsec = h:u16le()
+ h:skip(12)
+ local optSize = h:u16le()
+ local opt = r:sub(pe + 24, optSize)
+ local magic = opt:u16le()
+ local ddAt = if magic == 0x20B then 112 else 96
+ opt:seek(ddAt + 2 * 8)
+ local rsrcRva = opt:u32le()
+ if opt.err or rsrcRva == 0 then
+ return {}, nil
+ end
+ -- the section holding the resources
+ local secs = r:sub(pe + 24 + optSize, nsec * 40)
+ local base, rva0 = -1, 0
+ for _ = 1, nsec do
+ secs:skip(8)
+ local vsize, va, rawSize, rawAt = secs:u32le(), secs:u32le(), secs:u32le(), secs:u32le()
+ secs:skip(16)
+ if rsrcRva >= va and rsrcRva < va + math.max(vsize, rawSize) then
+ base, rva0 = rawAt + (rsrcRva - va), va - rawAt
+ end
+ end
+ if base < 0 then
+ return nil, "no resource section"
+ end
+ local out = {}
+ local function dir(at: number, depth: number, isFont: boolean)
+ if depth > 3 then
+ return
+ end
+ local d = r:sub(base + at, 16)
+ d:skip(12)
+ local named, ids = d:u16le(), d:u16le()
+ local e = r:sub(base + at + 16, (named + ids) * 8)
+ for _ = 1, math.min(named + ids, 512) do
+ local id, target = e:u32le(), e:u32le()
+ if e.err then
+ return
+ end
+ if depth == 0 and id ~= 8 then
+ continue
+ end
+ if bit32.band(target, 0x80000000) ~= 0 then
+ dir(bit32.band(target, 0x7FFFFFFF), depth + 1, isFont or depth == 0)
+ elseif isFont then
+ local leaf = r:sub(base + target, 8)
+ local dataRva, size = leaf:u32le(), leaf:u32le()
+ table.insert(out, { dataRva - rva0, size })
+ end
+ end
+ end
+ dir(0, 0, false)
+ return out, nil
+end
+
+function Fon.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local list: { { number } }
+ if r:peek(2) == "MZ" then
+ local lfanew = r:sub(0x3C, 4):u32le()
+ local sig = r:peek(2, lfanew)
+ local l, err
+ if sig == "NE" then
+ l, err = neFonts(r, lfanew)
+ elseif sig == "PE" then
+ l, err = peFonts(r, lfanew)
+ else
+ return nil, Err.new(Err.CORRUPT, "an MZ file without an NE / PE header")
+ end
+ if not l then
+ return nil, Err.from(err)
+ end
+ list = l
+ else
+ if r:size() < 118 then
+ return nil, Err.new(Err.TRUNCATED, "shorter than a FNT header")
+ end
+ list = { { 0, r:size() } }
+ end
+ local fonts: { any } = {}
+ local firstErr: Err.Err? = nil
+ for _, res in list do
+ if res[1] + 118 <= r:size() then
+ local f, err = fnt(r:sub(res[1], res[2]))
+ if f then
+ table.insert(fonts, f)
+ else
+ firstErr = firstErr or err
+ end
+ end
+ end
+ if #fonts == 0 then
+ return nil, firstErr or Err.new(Err.CORRUPT, "no font resources")
+ end
+ local pick = fonts[1]
+ if type(o.size) == "number" then
+ for _, f in fonts do
+ if math.abs(f.unitsPerEm - o.size) < math.abs(pick.unitsPerEm - o.size) then
+ pick = f
+ end
+ end
+ end
+ pick.meta.strikes = fonts
+ return pick, nil
+end
+
+return Fon
diff --git a/src/Formats/font/hershey/init.luau b/src/Formats/font/hershey/init.luau
new file mode 100644
index 0000000..51808bd
--- /dev/null
+++ b/src/Formats/font/hershey/init.luau
@@ -0,0 +1,200 @@
+--!strict
+-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph
+-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R",
+-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths
+-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster
+-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of
+-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i
+-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph
+-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported:
+-- writing, the Hershey "occidental" index files (.hmp), filled rendering.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Raster = require("@formats/codecs/image/Raster")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Hershey = {
+ name = "hershey",
+ category = "font",
+ extensions = { "jhf" },
+ mime = { "application/x-hershey-font" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" },
+ caps = { decode = true, encode = false, strokes = true },
+}
+
+export type DecodeOptions = {
+ map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii")
+ strokeWidth: number?, -- stroke width in font units for rasterize (default 2)
+ maxGlyphs: number?, -- default 65536
+}
+
+-- ------------------------------------------------------------------------------------------------ constants
+local BASELINE = 9 -- the Hershey y of the Roman fonts' baseline (y grows downwards)
+
+-- ------------------------------------------------------------------------------------------------ sniff
+-- the first record: 5-digit id, 3-digit count, then coordinate characters in " " .. "~" (the pen-up pair " R")
+local function header(line: string): (number?, number?)
+ if #line < 10 then
+ return nil, nil
+ end
+ local id = tonumber((string.gsub(string.sub(line, 1, 5), "^%s+", "")))
+ local n = tonumber((string.gsub(string.sub(line, 6, 8), "^%s+", "")))
+ if not id or not n or n < 1 or string.find(string.sub(line, 1, 8), "[^%d ]") then
+ return nil, nil
+ end
+ return id, n
+end
+
+function Hershey.sniff(r: Bytes.Reader): number
+ local head = r:peek(256)
+ local line = string.match(head, "^([^\r\n]*)")
+ local id, n = header(line or "")
+ if not id or not n then
+ return 0
+ end
+ local body = string.sub(line :: string, 9)
+ if string.find(body, "[^ -~]") then
+ return 0
+ end
+ return if #body == math.min(2 * n, 64) or #body == 2 * n then 0.7 else 0.3
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Glyph = { id: number, left: number, right: number, cmds: { any } }
+
+local Face = {}
+Face.__index = Face
+
+function Face.glyphIndex(self: any, cp: number): number
+ return self._index[cp] or 0
+end
+
+function Face.advance(self: any, g: number): number
+ local gl = self._glyphs[g + 1]
+ return if gl then gl.right - gl.left else 0
+end
+
+function Face.kern(_self: any, _a: number, _b: number): number
+ return 0
+end
+
+function Face.outline(self: any, g: number): { any }?
+ local gl = self._glyphs[g + 1]
+ if not gl then
+ return nil
+ end
+ local out = table.create(#gl.cmds)
+ for i, c in gl.cmds do
+ out[i] = table.clone(c)
+ end
+ return out
+end
+
+-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels)
+function Face.rasterize(self: any, g: number, px: number): Types.Image?
+ local gl = self._glyphs[g + 1]
+ if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then
+ return nil
+ end
+ local s = px / self.unitsPerEm
+ local stroke = Raster.stroke(gl.cmds, { width = self.meta.strokeWidth, join = "round", cap = "round" })
+ local m = Raster.mask(stroke, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
+ local img
+ if m then
+ img = Types.Image.new(m.width, m.height, "alpha8")
+ buffer.copy(img.pixels, 0, m.coverage)
+ img.meta.left = m.x
+ img.meta.top = -m.y
+ else
+ img = Types.Image.new(0, 0, "alpha8")
+ img.meta.left, img.meta.top = 0, 0
+ end
+ img.meta.advance = (gl.right - gl.left) * s
+ img.meta.glyph = g
+ return img
+end
+
+function Hershey.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxGlyphs = o.maxGlyphs or 65536
+ local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
+ local lines = string.split((string.gsub(text, "\r", "")), "\n")
+ local glyphs: { Glyph } = {}
+ local i = 1
+ while i <= #lines do
+ local line = lines[i]
+ i += 1
+ if string.match(line, "^%s*$") then
+ continue
+ end
+ local id, n = header(line)
+ if not id or not n then
+ return nil, Err.new(Err.CORRUPT, "bad record header on line " .. (i - 1))
+ end
+ local data = string.sub(line, 9)
+ while #data < 2 * n and i <= #lines do
+ data ..= lines[i]
+ i += 1
+ end
+ if #data < 2 * n then
+ return nil, Err.new(Err.TRUNCATED, "glyph " .. id .. " has fewer vertices than its count")
+ end
+ if #glyphs >= maxGlyphs then
+ return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
+ end
+ local left = string.byte(data, 1) - 82
+ local right = string.byte(data, 2) - 82
+ local cmds: { any } = {}
+ local pen = false
+ for k = 1, n - 1 do
+ local a, b = string.byte(data, 2 * k + 1), string.byte(data, 2 * k + 2)
+ if a == 32 and b == 82 then
+ pen = false
+ else
+ local x, y = a - 82 - left, BASELINE - (b - 82)
+ local cmd: any = { op = if pen then "lineTo" else "moveTo" }
+ cmd[1], cmd[2] = x, y
+ table.insert(cmds, cmd)
+ pen = true
+ end
+ end
+ table.insert(glyphs, { id = id, left = left, right = right, cmds = cmds })
+ end
+ if #glyphs == 0 then
+ return nil, Err.new(Err.CORRUPT, "no glyphs")
+ end
+ local index: { [number]: number } = {}
+ local byId = o.map == "id"
+ for k, g in glyphs do
+ local cp = if byId then g.id else 31 + k
+ if index[cp] == nil then
+ index[cp] = k - 1
+ end
+ end
+ local font = setmetatable({
+ kind = "font",
+ info = { family = "Hershey", style = "Regular" },
+ unitsPerEm = 32,
+ ascent = 21,
+ descent = -7,
+ lineGap = 4,
+ numGlyphs = #glyphs,
+ meta = {
+ strokes = true,
+ strokeWidth = o.strokeWidth or 2,
+ ids = table.create(#glyphs, 0),
+ source = { format = "hershey", map = if byId then "id" else "ascii" },
+ },
+ _glyphs = glyphs,
+ _index = index,
+ }, Face)
+ for k, g in glyphs do
+ font.meta.ids[k] = g.id
+ end
+ return font, nil
+end
+
+return Hershey
diff --git a/src/Formats/font/pcf/init.luau b/src/Formats/font/pcf/init.luau
new file mode 100644
index 0000000..e46cc9a
--- /dev/null
+++ b/src/Formats/font/pcf/init.luau
@@ -0,0 +1,290 @@
+--!strict
+-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the
+-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties),
+-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad
+-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES.
+-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets
+-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver
+-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Bitmap = require("@formats/codecs/font/Bitmap")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Pcf = {
+ name = "pcf",
+ category = "font",
+ extensions = { "pcf" },
+ mime = { "application/x-font-pcf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = false, bitmap = true },
+}
+
+export type DecodeOptions = { maxGlyphs: number? } -- default 1114112
+
+-- ------------------------------------------------------------------------------------------------ constants
+local PROPERTIES, ACCELERATORS, METRICS, BITMAPS = 1, 2, 4, 8
+local BDF_ENCODINGS, SWIDTHS, GLYPH_NAMES, BDF_ACCELERATORS = 32, 64, 128, 256
+local COMPRESSED = 0x100
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Pcf.sniff(r: Bytes.Reader): number
+ return if r:peek(4) == "\1fcp" then 1 else 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+type Table = { format: number, size: number, offset: number }
+
+-- a reader positioned after a table's format word, with the integer readers for its byte order
+type TR = { r: Bytes.Reader, format: number, big: boolean }
+
+local function open(r: Bytes.Reader, t: Table?): TR?
+ if not t or t.offset + 4 > r:size() then
+ return nil
+ end
+ local s = r:sub(t.offset, t.size)
+ local format = s:u32le()
+ return { r = s, format = format, big = bit32.band(format, 4) ~= 0 }
+end
+
+local function u32(t: TR): number
+ return if t.big then t.r:u32be() else t.r:u32le()
+end
+local function i32(t: TR): number
+ return if t.big then t.r:i32be() else t.r:i32le()
+end
+local function i16(t: TR): number
+ return if t.big then t.r:i16be() else t.r:i16le()
+end
+local function u16(t: TR): number
+ return if t.big then t.r:u16be() else t.r:u16le()
+end
+
+local REV = buffer.create(256)
+for i = 0, 255 do
+ local v, rv = i, 0
+ for _ = 1, 8 do
+ rv = rv * 2 + v % 2
+ v //= 2
+ end
+ buffer.writeu8(REV, i, rv)
+end
+
+function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxGlyphs = o.maxGlyphs or 1114112
+ if r:string(4) ~= "\1fcp" then
+ return nil, Err.new(if r.err then Err.TRUNCATED else Err.CORRUPT, "not a PCF file")
+ end
+ local count = r:u32le()
+ if count > 64 then
+ return nil, Err.new(Err.CORRUPT, "too many tables")
+ end
+ local tables: { [number]: Table } = {}
+ for _ = 1, count do
+ local ty, format, size, offset = r:u32le(), r:u32le(), r:u32le(), r:u32le()
+ tables[ty] = { format = format, size = size, offset = offset }
+ end
+ if r.err then
+ return nil, r.err
+ end
+ -- properties
+ local props: { [string]: any } = {}
+ local pt = open(r, tables[PROPERTIES])
+ if pt then
+ local n = i32(pt)
+ if n < 0 or n > 4096 then
+ return nil, Err.new(Err.CORRUPT, "bad property count")
+ end
+ local raw = {}
+ for k = 1, n do
+ raw[k] = { i32(pt), pt.r:u8(), i32(pt) }
+ end
+ if n % 4 ~= 0 then
+ pt.r:skip(4 - n % 4)
+ end
+ local strSize = i32(pt)
+ local strAt = pt.r:tell()
+ local function str(off: number): string
+ if off < 0 or off >= strSize then
+ return ""
+ end
+ local s = pt.r:sub(strAt + off, strSize - off)
+ return s:cstring()
+ end
+ for _, p in raw do
+ props[str(p[1])] = if p[2] ~= 0 then str(p[3]) else p[3]
+ end
+ if pt.r.err then
+ return nil, Err.new(Err.TRUNCATED, "properties table")
+ end
+ end
+ -- accelerators: ascent / descent
+ local ascent: number?, descent: number? = nil, nil
+ local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS])
+ if at then
+ at.r:skip(8)
+ ascent, descent = i32(at), i32(at)
+ end
+ -- metrics
+ local mt = open(r, tables[METRICS])
+ if not mt then
+ return nil, Err.new(Err.CORRUPT, "no METRICS table")
+ end
+ local metrics = {}
+ local compressed = bit32.band(mt.format, COMPRESSED) ~= 0
+ local nm = if compressed then u16(mt) else u32(mt)
+ if nm > maxGlyphs then
+ return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
+ end
+ for k = 1, nm do
+ if compressed then
+ local b = mt.r
+ metrics[k] = { b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80 }
+ else
+ metrics[k] = { i16(mt), i16(mt), i16(mt), i16(mt), i16(mt) }
+ mt.r:skip(2)
+ end
+ end
+ if mt.r.err then
+ return nil, Err.new(Err.TRUNCATED, "metrics table")
+ end
+ -- bitmaps
+ local bt = open(r, tables[BITMAPS])
+ if not bt then
+ return nil, Err.new(Err.CORRUPT, "no BITMAPS table")
+ end
+ local nb = u32(bt)
+ if nb ~= nm then
+ return nil, Err.new(Err.CORRUPT, "bitmap count differs from metrics count")
+ end
+ local offsets = table.create(nb, 0)
+ for k = 1, nb do
+ offsets[k] = u32(bt)
+ end
+ local sizes = { u32(bt), u32(bt), u32(bt), u32(bt) }
+ local padIndex = bit32.band(bt.format, 3)
+ local pad = bit32.lshift(1, padIndex)
+ local unit = bit32.lshift(1, bit32.band(bit32.rshift(bt.format, 4), 3))
+ local msbBit = bit32.band(bt.format, 8) ~= 0
+ local dataAt = bt.r:tell()
+ local dataSize = sizes[padIndex + 1]
+ if bt.r.err or dataAt + dataSize > bt.r:size() then
+ return nil, Err.new(Err.TRUNCATED, "bitmaps table")
+ end
+ -- the bitmap data normalised to MSB-first bits and bytes
+ local bits = bt.r:sub(dataAt, dataSize):bytes(dataSize)
+ if not msbBit then
+ for k = 0, dataSize - 1 do
+ buffer.writeu8(bits, k, buffer.readu8(REV, buffer.readu8(bits, k)))
+ end
+ end
+ if bt.big ~= msbBit and unit > 1 then
+ for k = 0, dataSize - unit, unit do
+ for j = 0, unit // 2 - 1 do
+ local x, y = buffer.readu8(bits, k + j), buffer.readu8(bits, k + unit - 1 - j)
+ buffer.writeu8(bits, k + j, y)
+ buffer.writeu8(bits, k + unit - 1 - j, x)
+ end
+ end
+ end
+ local glyphs: { Types.BitmapGlyph } = {}
+ for k = 1, nm do
+ local m = metrics[k]
+ local w, h = m[2] - m[1], m[4] + m[5]
+ if w < 0 or h < 0 or w > 4096 or h > 4096 then
+ return nil, Err.new(Err.CORRUPT, "bad glyph metrics")
+ end
+ local stride = math.ceil(w / (pad * 8)) * pad
+ local px = Bitmap.unpack(bits, offsets[k], w, h, stride)
+ glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px }
+ end
+ -- encodings
+ local encodings: { [number]: number } = {}
+ local default: number? = nil
+ local et = open(r, tables[BDF_ENCODINGS])
+ if et then
+ local min2, max2, min1, max1, def = i16(et), i16(et), i16(et), i16(et), i16(et)
+ if min2 < 0 or max2 > 255 or min1 < 0 or max1 > 255 or max2 < min2 or max1 < min1 then
+ return nil, Err.new(Err.CORRUPT, "bad encoding ranges")
+ end
+ for b1 = min1, max1 do
+ for b2 = min2, max2 do
+ local g = u16(et)
+ if g ~= 0xFFFF and g < nm and encodings[g + 1] == nil then
+ encodings[g + 1] = b1 * 256 + b2
+ end
+ end
+ end
+ if et.r.err then
+ return nil, Err.new(Err.TRUNCATED, "encodings table")
+ end
+ local dcols = max2 - min2 + 1
+ local d1, d2 = def // 256, def % 256
+ if d1 >= min1 and d1 <= max1 and d2 >= min2 and d2 <= max2 then
+ local slot = (d1 - min1) * dcols + (d2 - min2)
+ local dr = r:sub(tables[BDF_ENCODINGS].offset + 14 + slot * 2, 2)
+ local g = if et.big then dr:u16be() else dr:u16le()
+ if g ~= 0xFFFF and g < nm then
+ default = g
+ end
+ end
+ end
+ -- glyph names
+ local nt = open(r, tables[GLYPH_NAMES])
+ if nt then
+ local n = u32(nt)
+ if n == nm then
+ local offs = table.create(n, 0)
+ for k = 1, n do
+ offs[k] = u32(nt)
+ end
+ local strSize = u32(nt)
+ local strAt = nt.r:tell()
+ for k = 1, n do
+ if offs[k] < strSize then
+ glyphs[k].name = nt.r:sub(strAt + offs[k], strSize - offs[k]):cstring()
+ end
+ end
+ end
+ end
+ local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil
+ local cset = if props.CHARSET_ENCODING ~= nil then tostring(props.CHARSET_ENCODING) else nil
+ local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1")
+ local encList = table.create(nm, -1)
+ for k = 1, nm do
+ local enc = encodings[k]
+ encList[k] = enc or -1
+ if unicode and enc then
+ glyphs[k].codepoint = enc
+ end
+ end
+ local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (ascent or 0) + (descent or 0)
+ local strike: Types.BitmapStrike = {
+ size = pixelSize,
+ ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else ascent or 0,
+ descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else descent or 0,
+ glyphs = glyphs,
+ default = default,
+ }
+ local weight = props.WEIGHT_NAME
+ local style = if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else ""
+ if props.SLANT == "I" or props.SLANT == "O" then
+ style = (if style ~= "" then style .. " " else "") .. "Italic"
+ end
+ return Bitmap.font(strike, {
+ family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else nil,
+ style = if style ~= "" then style else "Regular",
+ fullName = if type(props.FONT) == "string" then props.FONT else nil,
+ }, {
+ properties = props,
+ encodings = encList,
+ unicode = unicode,
+ source = { format = "pcf", pad = pad, unit = unit, msbBit = msbBit, msbByte = bt.big, charset = if registry then registry .. "-" .. tostring(cset) else nil },
+ }), nil
+end
+
+return Pcf
diff --git a/src/Formats/font/psf/init.luau b/src/Formats/font/psf/init.luau
new file mode 100644
index 0000000..52ba66f
--- /dev/null
+++ b/src/Formats/font/psf/init.luau
@@ -0,0 +1,328 @@
+--!strict
+-- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2
+-- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and
+-- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry
+-- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map
+-- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell
+-- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing:
+-- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through
+-- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps
+-- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd
+-- project's psf documentation (Andries Brouwer).
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Bitmap = require("@formats/codecs/font/Bitmap")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Psf = {
+ name = "psf",
+ category = "font",
+ extensions = { "psf", "psfu" },
+ mime = { "application/x-font-linux-psf" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
+ caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } },
+}
+
+export type DecodeOptions = { maxGlyphs: number? } -- default 65536
+export type EncodeOptions = {
+ version: number?, -- 1 or 2 (default 2)
+ px: number?, -- pixel size for outline fonts (default 16)
+ chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
+ unicode: boolean?, -- write the Unicode table (default true)
+}
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Psf.sniff(r: Bytes.Reader): number
+ local h = r:peek(4)
+ if h == "\114\181\74\134" then
+ return 1
+ end
+ if string.sub(h, 1, 2) == "\54\4" and #h >= 4 and string.byte(h, 3) <= 7 and string.byte(h, 4) > 0 then
+ return 0.9
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxGlyphs = o.maxGlyphs or 65536
+ local version, count, width, height, stride, glyphAt, hasTable
+ if r:peek(4) == "\114\181\74\134" then
+ r:skip(4)
+ local ver, hsize, flags = r:u32le(), r:u32le(), r:u32le()
+ count = r:u32le()
+ local charsize = r:u32le()
+ height, width = r:u32le(), r:u32le()
+ if r.err then
+ return nil, r.err
+ end
+ if ver ~= 0 then
+ return nil, Err.new(Err.UNSUPPORTED, "PSF 2 version " .. ver)
+ end
+ stride = math.ceil(width / 8)
+ if width < 1 or height < 1 or width > 4096 or height > 4096 or charsize ~= stride * height then
+ return nil, Err.new(Err.CORRUPT, "bad glyph size")
+ end
+ version, glyphAt, hasTable = 2, hsize, bit32.band(flags, 1) ~= 0
+ elseif r:peek(2) == "\54\4" then
+ r:skip(2)
+ local mode, charsize = r:u8(), r:u8()
+ if r.err then
+ return nil, r.err
+ end
+ version, width, height, stride = 1, 8, charsize, 1
+ count = if bit32.band(mode, 1) ~= 0 then 512 else 256
+ glyphAt, hasTable = 4, bit32.band(mode, 6) ~= 0
+ if height < 1 then
+ return nil, Err.new(Err.CORRUPT, "zero glyph height")
+ end
+ else
+ return nil, Err.new(Err.CORRUPT, "not a PSF font")
+ end
+ if count < 1 or count > maxGlyphs then
+ return nil, Err.new(Err.LIMIT, "glyph count " .. count .. " over maxGlyphs")
+ end
+ local size = stride * height
+ if glyphAt + count * size > r:size() then
+ return nil, Err.new(Err.TRUNCATED, "glyph data past the end")
+ end
+ local glyphs: { Types.BitmapGlyph } = {}
+ for i = 0, count - 1 do
+ glyphs[i + 1] = {
+ width = width,
+ height = height,
+ left = 0,
+ top = height,
+ advance = width,
+ pixels = Bitmap.unpack(r.buf, r.base + glyphAt + i * size, width, height, stride),
+ }
+ end
+ local map: { [number]: number } = {}
+ local sequences = {}
+ local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order
+ if hasTable then
+ local t = r:sub(glyphAt + count * size)
+ for i = 0, count - 1 do
+ local inSeq = false
+ local seq: { number } = {}
+ local entry: { any } = {}
+ unicodeTable[i + 1] = entry
+ local function endSeq()
+ if #seq > 0 then
+ table.insert(sequences, { glyph = i, codepoints = seq })
+ table.insert(entry, seq)
+ end
+ seq = {}
+ end
+ while true do
+ if t:eof() then
+ break
+ end
+ local cp
+ if version == 1 then
+ cp = t:u16le()
+ if cp == 0xFFFF then
+ break
+ elseif cp == 0xFFFE then
+ endSeq()
+ inSeq = true
+ continue
+ end
+ else
+ local b = t:u8()
+ if b == 0xFF then
+ break
+ elseif b == 0xFE then
+ endSeq()
+ inSeq = true
+ continue
+ end
+ -- UTF-8
+ local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1
+ if n < 0 then
+ return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table")
+ end
+ cp = if n == 0 then b elseif n == 1 then bit32.band(b, 0x1F) elseif n == 2 then bit32.band(b, 0x0F) else bit32.band(b, 0x07)
+ for _ = 1, n do
+ cp = cp * 64 + bit32.band(t:u8(), 0x3F)
+ end
+ end
+ if inSeq then
+ table.insert(seq, cp)
+ continue
+ end
+ table.insert(entry, cp)
+ if map[cp] == nil then
+ map[cp] = i
+ if glyphs[i + 1].codepoint == nil then
+ glyphs[i + 1].codepoint = cp
+ end
+ end
+ end
+ endSeq()
+ end
+ if t.err then
+ return nil, Err.new(Err.TRUNCATED, "Unicode table")
+ end
+ else
+ for i = 0, count - 1 do
+ glyphs[i + 1].codepoint = i
+ end
+ end
+ local strike: Types.BitmapStrike = { size = height, ascent = height, descent = 0, glyphs = glyphs, map = map, default = 0 }
+ local defaultGlyph = map[0xFFFD] or map[0x3F]
+ if defaultGlyph then
+ strike.default = defaultGlyph
+ end
+ return Bitmap.font(strike, {}, {
+ unicode = hasTable,
+ sequences = sequences,
+ unicodeTable = if hasTable then unicodeTable else nil,
+ width = width,
+ height = height,
+ source = { format = "psf", version = version, glyphs = count },
+ }), nil
+end
+
+-- ------------------------------------------------------------------------------------------------ encode
+local function utf8Bytes(cp: number): string
+ return utf8.char(cp)
+end
+
+function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
+ local o: EncodeOptions = opts or {}
+ local version = o.version or 2
+ if version ~= 1 and version ~= 2 then
+ return nil, Err.new(Err.ARG, "version must be 1 or 2")
+ end
+ local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars })
+ if not strike then
+ return nil, err
+ end
+ local glyphs = strike.glyphs
+ local n = #glyphs
+ if n == 0 then
+ return nil, Err.new(Err.ARG, "no glyphs")
+ end
+ -- the cell
+ local width = 0
+ for _, g in glyphs do
+ width = math.max(width, g.advance, g.left + g.width)
+ end
+ local height = math.max(1, strike.ascent + strike.descent)
+ if version == 1 then
+ if width > 8 then
+ return nil, Err.new(Err.ARG, "PSF 1 glyphs are 8 pixels wide (this font needs " .. width .. ")")
+ end
+ if n > 512 then
+ return nil, Err.new(Err.ARG, "PSF 1 holds 256 or 512 glyphs (this font has " .. n .. ")")
+ end
+ width = 8
+ end
+ width = math.max(width, 1)
+ local count = if version == 1 then (if n > 256 then 512 else 256) else n
+ local stride = math.ceil(width / 8)
+ local size = stride * height
+ local cells = buffer.create(count * size)
+ for i, g in glyphs do
+ local cell = buffer.create(width * height)
+ local x0, y0 = g.left, strike.ascent - g.top
+ for y = 0, g.height - 1 do
+ for x = 0, g.width - 1 do
+ local cx, cy = x0 + x, y0 + y
+ if cx >= 0 and cy >= 0 and cx < width and cy < height and buffer.readu8(g.pixels, y * g.width + x) >= 128 then
+ buffer.writeu8(cell, cy * width + cx, 255)
+ end
+ end
+ end
+ buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride))
+ end
+ -- the Unicode table: each glyph's code point and the extra mappings onto it
+ local cps: { { number } } = {}
+ for i = 1, count do
+ cps[i] = {}
+ end
+ local seen: { [number]: boolean } = {}
+ for i, g in glyphs do
+ if g.codepoint and not seen[g.codepoint] then
+ seen[g.codepoint] = true
+ table.insert(cps[i], g.codepoint)
+ end
+ end
+ if strike.map then
+ local extra: { { number } } = {}
+ for cp, gi in strike.map do
+ if not seen[cp] and gi >= 0 and gi < count then
+ table.insert(extra, { cp, gi })
+ end
+ end
+ table.sort(extra, function(a: { number }, b: { number }): boolean
+ return a[1] < b[1]
+ end)
+ for _, e in extra do
+ seen[e[1]] = true
+ table.insert(cps[e[2] + 1], e[1])
+ end
+ end
+ local meta = if type(font.meta) == "table" then font.meta else {}
+ local srcTable = if font.bitmap == strike and type(meta.unicodeTable) == "table" and #meta.unicodeTable == n then meta.unicodeTable else nil
+ local withTable = if o.unicode ~= nil then o.unicode else meta.unicode ~= false
+ local w = Bytes.writer(count * size + 64)
+ if version == 2 then
+ w:string("\114\181\74\134")
+ w:u32le(0)
+ w:u32le(32)
+ w:u32le(if withTable then 1 else 0)
+ w:u32le(count)
+ w:u32le(size)
+ w:u32le(height)
+ w:u32le(width)
+ else
+ w:string("\54\4")
+ w:u8((if count == 512 then 1 else 0) + (if withTable then 2 else 0))
+ w:u8(height)
+ end
+ w:bytes(cells)
+ if withTable then
+ local function put(cp: number)
+ if version == 2 then
+ w:string(utf8Bytes(cp))
+ elseif cp < 0xFFFE then
+ w:u16le(cp)
+ end
+ end
+ for i = 1, count do
+ -- a PSF read earlier writes its table back as it was (code points on several glyphs, sequences)
+ local list = if srcTable and srcTable[i] then srcTable[i] else cps[i]
+ for _, x in list do
+ if type(x) == "number" then
+ put(x)
+ end
+ end
+ for _, x in list do
+ if type(x) == "table" then
+ if version == 2 then
+ w:u8(0xFE)
+ else
+ w:u16le(0xFFFE)
+ end
+ for _, cp in x do
+ put(cp)
+ end
+ end
+ end
+ if version == 2 then
+ w:u8(0xFF)
+ else
+ w:u16le(0xFFFF)
+ end
+ end
+ end
+ return w:finish(), nil
+end
+
+return Psf
diff --git a/src/Formats/font/type1/Charstring.luau b/src/Formats/font/type1/Charstring.luau
new file mode 100644
index 0000000..e1b4f4a
--- /dev/null
+++ b/src/Formats/font/type1/Charstring.luau
@@ -0,0 +1,283 @@
+--!strict
+-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted
+-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side
+-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div,
+-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement;
+-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes,
+-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the
+-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops).
+local Charstring = {}
+
+export type Result = { cmds: { any }, advance: number, sbx: number }
+-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result
+export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? }
+
+local readu8 = buffer.readu8
+
+function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
+ local cmds: { any } = {}
+ local stack: { number } = {}
+ local sp = 0
+ local ps: { number } = {} -- the PostScript stack callothersubr / pop use
+ local x, y = 0, 0
+ local advance, sbx = 0, 0
+ local open = false
+ local flex = false
+ local flexPts: { number } = {}
+ local budget = 200000
+ local finished = false
+
+ local function push(v: number)
+ if sp < 48 then
+ sp += 1
+ stack[sp] = v
+ end
+ end
+ local function arg(i: number): number
+ return stack[i] or 0
+ end
+ local function close()
+ if open then
+ table.insert(cmds, { op = "close" })
+ open = false
+ end
+ end
+ local function moveTo(dx: number, dy: number)
+ x += dx
+ y += dy
+ if flex then
+ table.insert(flexPts, x)
+ table.insert(flexPts, y)
+ return
+ end
+ close()
+ local c: any = { op = "moveTo" }
+ c[1], c[2] = x, y
+ table.insert(cmds, c)
+ end
+ local function ensureOpen()
+ if not open then
+ -- a drawing operator without a moveto starts at the current point
+ local c: any = { op = "moveTo" }
+ c[1], c[2] = x, y
+ table.insert(cmds, c)
+ open = true
+ end
+ end
+ local function lineTo(dx: number, dy: number)
+ ensureOpen()
+ x += dx
+ y += dy
+ local c: any = { op = "lineTo" }
+ c[1], c[2] = x, y
+ table.insert(cmds, c)
+ end
+ local function curveTo(a: number, b: number, c: number, d: number, e: number, f: number)
+ ensureOpen()
+ local x1, y1 = x + a, y + b
+ local x2, y2 = x1 + c, y1 + d
+ x, y = x2 + e, y2 + f
+ local cmd: any = { op = "cubicTo" }
+ cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y
+ table.insert(cmds, cmd)
+ end
+
+ local function exec(b: buffer, depth: number): string?
+ if depth > 10 then
+ return "subroutines nested too deep"
+ end
+ local n = buffer.len(b)
+ local p = 0
+ while p < n do
+ budget -= 1
+ if budget <= 0 then
+ return "operation budget exceeded"
+ end
+ local v = readu8(b, p)
+ p += 1
+ if v >= 32 then
+ if v <= 246 then
+ push(v - 139)
+ elseif v <= 250 then
+ if p >= n then
+ return "truncated number"
+ end
+ push((v - 247) * 256 + readu8(b, p) + 108)
+ p += 1
+ elseif v <= 254 then
+ if p >= n then
+ return "truncated number"
+ end
+ push(-(v - 251) * 256 - readu8(b, p) - 108)
+ p += 1
+ else
+ if p + 4 > n then
+ return "truncated number"
+ end
+ local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
+ push(if u >= 0x80000000 then u - 0x100000000 else u)
+ p += 4
+ end
+ continue
+ end
+ local op = v
+ if op == 12 then
+ if p >= n then
+ return "truncated escape"
+ end
+ op = 1200 + readu8(b, p)
+ p += 1
+ end
+ if op == 13 then -- hsbw
+ sbx, advance = arg(1), arg(2)
+ x, y = sbx, 0
+ sp = 0
+ elseif op == 1207 then -- sbw
+ sbx, advance = arg(1), arg(3)
+ x, y = arg(1), arg(2)
+ sp = 0
+ elseif op == 21 then
+ moveTo(arg(1), arg(2))
+ sp = 0
+ elseif op == 22 then
+ moveTo(arg(1), 0)
+ sp = 0
+ elseif op == 4 then
+ moveTo(0, arg(1))
+ sp = 0
+ elseif op == 5 then
+ lineTo(arg(1), arg(2))
+ sp = 0
+ elseif op == 6 then
+ lineTo(arg(1), 0)
+ sp = 0
+ elseif op == 7 then
+ lineTo(0, arg(1))
+ sp = 0
+ elseif op == 8 then
+ curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6))
+ sp = 0
+ elseif op == 30 then -- vhcurveto
+ curveTo(0, arg(1), arg(2), arg(3), arg(4), 0)
+ sp = 0
+ elseif op == 31 then -- hvcurveto
+ curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4))
+ sp = 0
+ elseif op == 9 then
+ close()
+ sp = 0
+ elseif op == 10 then -- callsubr
+ local idx = arg(sp)
+ sp = math.max(0, sp - 1)
+ local sub = ctx.subrs[idx + 1]
+ if not sub then
+ return "call of a missing subroutine " .. idx
+ end
+ local err = exec(sub, depth + 1)
+ if err or finished then
+ return err
+ end
+ elseif op == 11 then -- return
+ return nil
+ elseif op == 14 then -- endchar
+ close()
+ finished = true
+ return nil
+ elseif op == 1212 then -- div
+ if sp >= 2 then
+ local d = stack[sp]
+ stack[sp - 1] = if d ~= 0 then stack[sp - 1] / d else 0
+ sp -= 1
+ end
+ elseif op == 1216 then -- callothersubr: args... n othersubr#
+ local num = arg(sp)
+ local count = arg(sp - 1)
+ sp = math.max(0, sp - 2)
+ count = math.clamp(count, 0, sp)
+ local args = {}
+ for i = 1, count do
+ args[i] = stack[sp - count + i]
+ end
+ sp -= count
+ if num == 1 then
+ flex = true
+ table.clear(flexPts)
+ elseif num == 2 then
+ -- a flex point: the rmoveto before it already recorded the point
+ elseif num == 0 and flex then
+ flex = false
+ -- flexPts: the reference point, then 6 control / end points
+ local f = flexPts
+ if #f >= 14 then
+ -- restore the current point to before the flex sequence's moves
+ local function curve(i: number)
+ ensureOpen()
+ local cmd: any = { op = "cubicTo" }
+ cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5]
+ table.insert(cmds, cmd)
+ end
+ curve(3)
+ curve(9)
+ x, y = f[13], f[14]
+ end
+ table.clear(ps)
+ table.insert(ps, args[3] or y)
+ table.insert(ps, args[2] or x)
+ elseif num == 3 then
+ table.clear(ps)
+ table.insert(ps, 3)
+ else
+ table.clear(ps)
+ for i = #args, 1, -1 do
+ table.insert(ps, args[i])
+ end
+ end
+ elseif op == 1217 then -- pop
+ push(table.remove(ps) or 0)
+ elseif op == 1233 then -- setcurrentpoint
+ x, y = arg(1), arg(2)
+ sp = 0
+ elseif op == 1206 then -- seac: asb adx ady bchar achar
+ local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5)
+ sp = 0
+ local seac = ctx.seac
+ if not seac then
+ return "seac without base glyphs"
+ end
+ local base = seac(bchar)
+ local accent = seac(achar)
+ if not base or not accent then
+ return "seac of a missing glyph"
+ end
+ close()
+ for _, c in base.cmds do
+ table.insert(cmds, c)
+ end
+ local ox, oy = adx - asb, ady
+ for _, c in accent.cmds do
+ local t: any = { op = c.op }
+ for i = 1, #c, 2 do
+ t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy
+ end
+ table.insert(cmds, t)
+ end
+ finished = true
+ return nil
+ elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then
+ sp = 0 -- hints
+ else
+ sp = 0 -- unknown operators clear the stack
+ end
+ end
+ return nil
+ end
+
+ local err = exec(cs, 0)
+ if err then
+ return nil, err
+ end
+ close()
+ return { cmds = cmds, advance = advance, sbx = sbx }, nil
+end
+
+return Charstring
diff --git a/src/Formats/font/type1/init.luau b/src/Formats/font/type1/init.luau
new file mode 100644
index 0000000..b92bfac
--- /dev/null
+++ b/src/Formats/font/type1/init.luau
@@ -0,0 +1,368 @@
+--!strict
+-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the
+-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox,
+-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV,
+-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring
+-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph
+-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through
+-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple
+-- Master and CID-keyed (Type 9 / 11) fonts, writing.
+
+-- ------------------------------------------------------------------------------------------------ requires
+local Err = require("@formats/core/Err")
+local Bytes = require("@formats/core/Bytes")
+local Types = require("@formats/Types")
+local Raster = require("@formats/codecs/image/Raster")
+local GlyphNames = require("@formats/codecs/font/GlyphNames")
+local Charstring = require("@formats/font/type1/Charstring")
+
+-- ------------------------------------------------------------------------------------------------ contract
+local Type1 = {
+ name = "type1",
+ category = "font",
+ extensions = { "pfb", "pfa", "t1" },
+ mime = { "application/x-font-type1" },
+ deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
+ caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
+}
+
+export type DecodeOptions = { maxGlyphs: number? } -- default 65536
+
+-- ------------------------------------------------------------------------------------------------ sniff
+function Type1.sniff(r: Bytes.Reader): number
+ local h = r:peek(64)
+ if string.sub(h, 1, 2) == "\128\1" then
+ h = string.sub(h, 7)
+ end
+ if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then
+ return 1
+ end
+ return 0
+end
+
+-- ------------------------------------------------------------------------------------------------ decode
+-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA
+local function sections(r: Bytes.Reader): (string?, buffer?, string?)
+ local b = r.buf
+ local n = r:size()
+ if r:peek(2) == "\128\1" then
+ local clear, bin = {}, Bytes.writer()
+ local p = 0
+ while p + 2 <= n do
+ local h = r:sub(p, 6)
+ local m, ty, len = h:u8(), h:u8(), h:u32le()
+ if m ~= 128 then
+ return nil, nil, "bad PFB segment marker"
+ end
+ if ty == 3 then
+ break
+ end
+ if h.err or p + 6 + len > n then
+ return nil, nil, "truncated PFB segment"
+ end
+ if ty == 1 then
+ if #clear == 0 or bin:tell() == 0 then
+ table.insert(clear, buffer.readstring(b, r.base + p + 6, len))
+ end
+ elseif ty == 2 then
+ bin:bytes(r:sub(p + 6, len):bytes(len))
+ else
+ return nil, nil, "bad PFB segment type " .. ty
+ end
+ p += 6 + len
+ end
+ return table.concat(clear), bin:finish(), nil
+ end
+ local text = buffer.readstring(b, r.base, n)
+ local e = string.find(text, "eexec", 1, true)
+ if not e then
+ return nil, nil, "no eexec section"
+ end
+ local clear = string.sub(text, 1, e + 4)
+ -- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex)
+ local rest = string.sub(text, e + 5)
+ local hexPart = string.match(rest, "^%s*([%x%s]+)")
+ if hexPart and #hexPart > 8 then
+ local digits = string.gsub(hexPart, "%s", "")
+ local out = buffer.create(#digits // 2)
+ for i = 0, #digits // 2 - 1 do
+ buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0)
+ end
+ return clear, out, nil
+ end
+ local s = string.match(rest, "^[\r\n]*(.*)$") or rest
+ return clear, buffer.fromstring(s), nil
+end
+
+local function decrypt(src: buffer, off: number, n: number, key: number, skip: number): buffer
+ local r = key
+ local out = buffer.create(math.max(0, n - skip))
+ for i = 0, n - 1 do
+ local c = buffer.readu8(src, off + i)
+ local p = bit32.bxor(c, bit32.rshift(r, 8))
+ r = ((c + r) * 52845 + 22719) % 65536
+ if i >= skip then
+ buffer.writeu8(out, i - skip, p)
+ end
+ end
+ return out
+end
+
+-- binary strings of the private dictionary: " RD " / " -| "
+local function binaryAt(priv: buffer, p: number, len: number): buffer?
+ if p < 0 or len < 0 or p + len > buffer.len(priv) then
+ return nil
+ end
+ local out = buffer.create(len)
+ buffer.copy(out, 0, priv, p, len)
+ return out
+end
+
+local function psString(clear: string, key: string): string?
+ return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)")
+end
+
+local Face = {}
+Face.__index = Face
+
+function Face.glyphIndex(self: any, cp: number): number
+ return self._cmap[cp] or 0
+end
+
+function Face.advance(self: any, g: number): number
+ local res = self:_run(g)
+ return if res then res.advance else 0
+end
+
+function Face.kern(_self: any, _a: number, _b: number): number
+ return 0
+end
+
+function Face._run(self: any, g: number): Charstring.Result?
+ local cached = self._cache[g]
+ if cached ~= nil then
+ return if cached == false then nil else cached
+ end
+ local cs = self._charstrings[g + 1]
+ if not cs then
+ return nil
+ end
+ local res = Charstring.run(cs, self._ctx)
+ self._cache[g] = res or false
+ return res
+end
+
+function Face.outline(self: any, g: number): { any }?
+ local res = self:_run(g)
+ if not res then
+ return nil
+ end
+ local out = table.create(#res.cmds)
+ for i, c in res.cmds do
+ out[i] = table.clone(c)
+ end
+ return out
+end
+
+function Face.rasterize(self: any, g: number, px: number): Types.Image?
+ if type(px) ~= "number" or not (px > 0) or px > 4096 then
+ return nil
+ end
+ local res = self:_run(g)
+ if not res then
+ return nil
+ end
+ local s = px / self.unitsPerEm
+ local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
+ local img
+ if m then
+ img = Types.Image.new(m.width, m.height, "alpha8")
+ buffer.copy(img.pixels, 0, m.coverage)
+ img.meta.left, img.meta.top = m.x, -m.y
+ else
+ img = Types.Image.new(0, 0, "alpha8")
+ img.meta.left, img.meta.top = 0, 0
+ end
+ img.meta.advance = res.advance * s
+ img.meta.glyph = g
+ return img
+end
+
+function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
+ local o: DecodeOptions = opts or {}
+ local maxGlyphs = o.maxGlyphs or 65536
+ local clear, enc, serr = sections(r)
+ if not clear or not enc then
+ return nil, Err.from(serr)
+ end
+ if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then
+ return nil, Err.new(Err.CORRUPT, "no eexec section")
+ end
+ if buffer.len(enc) < 4 then
+ return nil, Err.new(Err.TRUNCATED, "eexec section too short")
+ end
+ local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4)
+ local ptext = buffer.tostring(priv)
+ local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4
+ -- Subrs
+ local subrs: { buffer } = {}
+ local function charstring(p: number, len: number): buffer?
+ local raw = binaryAt(priv, p, len)
+ if not raw then
+ return nil
+ end
+ if lenIV < 0 then
+ return raw
+ end
+ return decrypt(raw, 0, len, 4330, lenIV)
+ end
+ local sAt = string.find(ptext, "/Subrs", 1, true)
+ local csAt = string.find(ptext, "/CharStrings", 1, true)
+ if not csAt then
+ return nil, Err.new(Err.CORRUPT, "no CharStrings")
+ end
+ if sAt and sAt < csAt then
+ local p = sAt
+ while true do
+ local s, e0, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p)
+ if not s or s > csAt then
+ break
+ end
+ local e = e0 :: number
+ local i, n = tonumber(idx) :: number, tonumber(len) :: number
+ if i > 65535 then
+ return nil, Err.new(Err.LIMIT, "too many subroutines")
+ end
+ local cs = charstring(e, n)
+ if not cs then
+ return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end")
+ end
+ subrs[i + 1] = cs
+ p = e + n
+ end
+ end
+ -- CharStrings
+ local names: { string } = {}
+ local charstrings: { buffer } = {}
+ local byName: { [string]: number } = {}
+ local p = csAt + 12
+ while true do
+ local s, e0, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p)
+ if not s then
+ break
+ end
+ local e = e0 :: number
+ -- stop at the end of the dictionary
+ if string.find(string.sub(ptext, p, s), "%send%s") then
+ break
+ end
+ local n = tonumber(len) :: number
+ local cs = charstring(e, n)
+ if not cs then
+ return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end")
+ end
+ if #names >= maxGlyphs then
+ return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
+ end
+ table.insert(names, name :: string)
+ table.insert(charstrings, cs)
+ if byName[name :: string] == nil then
+ byName[name :: string] = #names - 1
+ end
+ p = e + n
+ end
+ if #names == 0 then
+ return nil, Err.new(Err.CORRUPT, "no glyphs")
+ end
+ -- .notdef first: glyph 0
+ local nd = byName[".notdef"]
+ if nd and nd ~= 0 then
+ names[1], names[nd + 1] = names[nd + 1], names[1]
+ charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1]
+ byName[names[1]], byName[names[nd + 1]] = 0, nd
+ end
+ -- the encoding
+ local encoding: { [number]: string } = {}
+ if string.find(clear, "/Encoding%s+StandardEncoding") then
+ for code, gname in GlyphNames.STANDARD do
+ encoding[code] = gname
+ end
+ else
+ for code, gname in string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put") do
+ encoding[tonumber(code) :: number] = gname
+ end
+ end
+ local cmap: { [number]: number } = {}
+ for _, gname in encoding do
+ local g = byName[gname]
+ local cp = GlyphNames.unicode(gname)
+ if g and cp and cmap[cp] == nil then
+ cmap[cp] = g
+ end
+ end
+ for k, gname in names do
+ local cp = GlyphNames.unicode(gname)
+ if cp and cmap[cp] == nil then
+ cmap[cp] = k - 1
+ end
+ end
+ -- font matrix / bbox
+ local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]")
+ local scale = 0.001
+ if fm then
+ local a = tonumber(string.match(fm, "^%s*(%S+)"))
+ if a and a > 0 then
+ scale = a
+ end
+ end
+ local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]")
+ local bbox = { 0, 0, 0, 0 }
+ if bb then
+ local k = 1
+ for v in string.gmatch(bb, "%S+") do
+ bbox[k] = tonumber(v) or 0
+ k += 1
+ end
+ end
+ local upm = math.floor(1 / scale + 0.5)
+ local font = setmetatable({
+ kind = "font",
+ info = {
+ family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"),
+ style = psString(clear, "Weight") or "Regular",
+ fullName = psString(clear, "FullName"),
+ postscriptName = string.match(clear, "/FontName%s*/(%S+)"),
+ },
+ unitsPerEm = upm,
+ ascent = bbox[4],
+ descent = bbox[2],
+ lineGap = 0,
+ numGlyphs = #names,
+ meta = {
+ glyphNames = names,
+ encoding = encoding,
+ bbox = bbox,
+ italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"),
+ lenIV = lenIV,
+ source = { format = "type1", variant = if r:peek(2) == "\128\1" then "pfb" else "pfa" },
+ },
+ _cmap = cmap,
+ _charstrings = charstrings,
+ _cache = {},
+ }, Face)
+ font._ctx = {
+ subrs = subrs,
+ seac = function(code: number): Charstring.Result?
+ local gname = GlyphNames.STANDARD[code]
+ local g = if gname then byName[gname] else nil
+ if not g then
+ return nil
+ end
+ local res = Charstring.run(charstrings[g + 1], { subrs = subrs })
+ return res
+ end,
+ }
+ return font, nil
+end
+
+return Type1
diff --git a/src/Formats/init.luau b/src/Formats/init.luau
index 4fca743..fbf9bb5 100644
--- a/src/Formats/init.luau
+++ b/src/Formats/init.luau
@@ -241,35 +241,54 @@ end
-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a
-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer
--- one; an explicit opts.format also does.
+-- one; an explicit opts.format also does. Package archives name their payload entry in meta.payload (a .deb's
+-- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the
+-- outer archive (its control data). A single-stream archive holding a .pcf / .psf(u) / .bdf font loads as the font.
local function unwrap(value: any, formatName: string, o: Options): any
if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then
return value
end
- if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" or not value.meta.stream then
+ if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then
+ return value
+ end
+ local payload = value.meta.payload
+ if not value.meta.stream and type(payload) ~= "string" then
return value
end
local ok, list = pcall(value.list, value)
- if not ok or type(list) ~= "table" or #list ~= 1 then
+ if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then
return value
end
- local rok, inner = pcall(value.read, value, list[1].name)
+ local entryName = if type(payload) == "string" then payload else list[1].name
+ local rok, inner = pcall(value.read, value, entryName)
if not rok or type(inner) ~= "buffer" then
return value
end
+ local category = "archive"
local e = detect(inner, nil, "archive", nil)
+ local innerExt = Input.extension(entryName) or ""
+ if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then
+ -- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font
+ e = detect(inner, entryName, "font", nil)
+ category = "font"
+ end
if not e then
return value
end
local io = table.clone(o)
- io.category = "archive"
- io.name = list[1].name
+ io.category = category
+ io.name = entryName
io._depth = (o._depth or 0) + 1
local v = load(inner, io)
if type(v) ~= "table" or type(v.meta) ~= "table" then
return value
end
- v.meta.compression = formatName
+ if type(payload) == "string" then
+ v.meta.container = formatName
+ v.meta.outer = value
+ else
+ v.meta.compression = formatName
+ end
return v
end
diff --git a/tests/archive/_entries.luau b/tests/archive/_entries.luau
new file mode 100644
index 0000000..c8ccae3
--- /dev/null
+++ b/tests/archive/_entries.luau
@@ -0,0 +1,78 @@
+-- shared by the archive tests: check(t, archive, want, label) compares an Archive's entries with the reference listing
+-- want = { { name, size?, crc?, mode?, mtime?, dir?, link? } } (only the fields present are compared; every wanted
+-- entry must exist; crc is the CRC-32 of the data read back), and the files written by _arch2_ours.luau.
+local Crc32 = require("@formats/core/Crc32")
+
+local E = {}
+
+function E.check(t: any, a: any, want: { any }, label: string, exact: boolean?)
+ local list = a:list()
+ if exact ~= false then
+ t:eq(#list, #want, label .. ": entry count")
+ end
+ local by = {}
+ for _, e in list do
+ by[e.name] = e
+ end
+ for _, w in want do
+ local e = by[w.name]
+ t:check(e, label .. ": has " .. tostring(w.name))
+ if e then
+ for _, k in { "size", "mode", "mtime", "dir", "link" } do
+ if w[k] ~= nil then
+ t:eq(e[k], w[k], label .. ": " .. w.name .. " " .. k)
+ end
+ end
+ if w.crc then
+ local b, err = a:read(w.name)
+ t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err))
+ if b then
+ t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
+ end
+ end
+ end
+ end
+end
+
+-- the standard file set of tools/fixtures/_arch2_ours.luau / _arch2.py
+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
+ buffer.writeu8(b, i, if (i // 64) % 3 == 0 then (i // 7) % 256 else s % 256)
+ end
+ return b
+end
+E.content = content
+E.FILES = {
+ { name = "hello.txt", data = buffer.fromstring("hello, archive\n") },
+ { name = "data.bin", data = content(5000, 7) },
+ { name = "empty.txt", data = buffer.create(0) },
+}
+
+-- roundTrip(t, mod, opts, label): add the standard files to mod.new(), write with opts, decode, compare
+function E.roundTrip(t: any, mod: any, opts: any?, label: string): buffer?
+ local Bytes = require("@formats/core/Bytes")
+ local a = mod.new()
+ for _, f in E.FILES do
+ a:add(f.name, f.data, { mtime = 1700000000, mode = 0x1A4 })
+ end
+ local out, err = a:write(opts)
+ t:check(out, label .. ": write: " .. tostring(err))
+ if not out then
+ return nil
+ end
+ local back, berr = mod.decode(Bytes.reader(out), {})
+ t:check(back, label .. ": decode: " .. tostring(berr))
+ if back then
+ local want = {}
+ for _, f in E.FILES do
+ table.insert(want, { name = f.name, size = buffer.len(f.data), crc = Crc32.of(f.data) })
+ end
+ E.check(t, back, want, label, false)
+ end
+ return out
+end
+
+return E
diff --git a/tests/archive/_mac.luau b/tests/archive/_mac.luau
new file mode 100644
index 0000000..75d0967
--- /dev/null
+++ b/tests/archive/_mac.luau
@@ -0,0 +1,78 @@
+-- shared by tests/archive/{binhex,macbinary,applesingle}.luau: run(name, module) checks the format's cases of
+-- tools/fixtures/mac.py against The Unarchiver's listings (fork names, sizes, data CRCs, type / creator), our writer's
+-- output read by unar (fixture step), round trips with a resource fork and Finder info, and the fuzz pass.
+local T = require("@tests/T")
+local F = require("@formats")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/mac")
+
+return function(name: string, mod: any, encodeVariants: { any }): (any, { string })
+ local t = T.suite(name)
+ t:eq(mod.name, name, "name")
+ local samples = {}
+ local n = 0
+ for _, c in Fx.cases do
+ if c.format == name then
+ n += 1
+ local a, err = mod.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "x" })
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ local by = {}
+ for _, e in a:list() do
+ by[e.name] = e
+ end
+ for _, w in c.entries do
+ local e = by[w.name]
+ if e and w.macType then
+ t:eq(e.macType, w.macType, c.name .. ": type")
+ t:eq(e.macCreator, w.macCreator, c.name .. ": creator")
+ end
+ end
+ end
+ t:eq(F.detect(c.data), name, c.name .. ": detect")
+ table.insert(samples, c.data)
+ end
+ end
+ t:check(n > 0, "has cases")
+ for _, o in Fx.ours do
+ if o.format == name then
+ t:check(o.ok, "unar reads our output (" .. o.variant .. "): " .. o.detail)
+ end
+ end
+ -- round trips: Finder info, dates, a resource fork
+ for _, opts in encodeVariants do
+ local a = mod.new()
+ a:add("Caf\u{e9}", "data fork", { mtime = 1700000000 })
+ a:add("Caf\u{e9}.rsrc", string.rep("R", 300), {})
+ local d = a._byName["Caf\u{e9}"]
+ d.macType, d.macCreator, d.finderFlags = "TEXT", "ttxt", 0x0100
+ a._byName["Caf\u{e9}.rsrc"].fork = "resource"
+ local out, err = a:write(opts)
+ t:check(out, "write: " .. tostring(err))
+ local back = out and mod.decode(Bytes.reader(out))
+ t:check(back, "round trip decodes")
+ if back then
+ local list = back:list()
+ local by = {}
+ for _, e in list do
+ by[e.name] = e
+ end
+ local rs = by["Caf\u{e9}.rsrc"]
+ t:check(rs and rs.size == 300 and rs.fork == "resource", "round trip resource fork")
+ t:eq(Crc32.of((back:read("Caf\u{e9}.rsrc"))), Crc32.string(string.rep("R", 300)), "round trip resource data")
+ local df = by["Caf\u{e9}"]
+ local fi = df or rs
+ t:check(fi and fi.macType == "TEXT" and fi.macCreator == "ttxt" and fi.finderFlags == 0x0100, "round trip Finder info")
+ if not (opts and opts.double) then
+ t:eq(buffer.tostring((back:read("Caf\u{e9}"))), "data fork", "round trip data fork")
+ if name ~= "binhex" then
+ t:eq(df and df.mtime, 1700000000, "round trip mtime")
+ end
+ end
+ end
+ end
+ return t, samples
+end
diff --git a/tests/archive/adf.luau b/tests/archive/adf.luau
new file mode 100644
index 0000000..ff0775d
--- /dev/null
+++ b/tests/archive/adf.luau
@@ -0,0 +1,75 @@
+-- archive/adf tests: DD / HD images formatted OFS, FFS, FFS international, OFS / FFS with directory cache by amitools'
+-- xdftool, holding nested directories, an empty file, a file with extension blocks and an ISO-8859-1 name, list the
+-- files xdftool reads back (names, sizes, data CRCs, directories, a set date), volume name and file system; errors
+-- (root block checksum, bad hash chains); the fuzz pass. Fixtures: tools/fixtures/adf.py (images gzip-compressed).
+local T = require("@tests/T")
+local F = require("@formats")
+local Adf = require("@formats/archive/adf")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/adf")
+
+local t = T.suite("adf")
+t:eq(Adf.name, "adf", "name")
+
+local first: buffer? = nil
+for _, c in Fx.cases do
+ local gz = buffer.fromstring(c.gz)
+ local data = Deflate.gunzip(gz, 0, buffer.len(gz)) :: buffer
+ first = first or data
+ local a, err = Adf.decode(Bytes.reader(data))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ t:eq(a.meta.volume, c.volume, c.name .. ": volume")
+ t:eq(a.meta.fs, c.fs, c.name .. ": fs")
+ t:eq(a._byName.readme.protect, 3, c.name .. ": protect rw (the D and E bits set: active low)")
+ end
+ t:eq(F.detect(data), "adf", c.name .. ": detect")
+end
+
+-- errors
+local img = first :: buffer
+local function code(b: buffer): string?
+ local _, e = Adf.decode(Bytes.reader(b))
+ return e and e.code
+end
+local bad = buffer.create(buffer.len(img))
+buffer.copy(bad, 0, img)
+buffer.writeu8(bad, 880 * 512 + 433, 0x7A) -- the volume name: root checksum fails
+t:eq(code(bad), Err.CHECKSUM, "root checksum")
+t:eq(code(buffer.create(1000)), Err.CORRUPT, "not blocks")
+t:eq(code(buffer.create(4096)), Err.CORRUPT, "no boot block")
+local dos6 = buffer.create(4096)
+buffer.writestring(dos6, 0, "DOS\6")
+t:eq(code(dos6), Err.UNSUPPORTED, "long-name file system")
+
+-- fuzz: mutations concentrated on the root and directory blocks (a whole image is mostly free blocks)
+local rand = T.rng(7)
+local threw = 0
+for i = 1, 300 do
+ local m = buffer.create(buffer.len(img))
+ buffer.copy(m, 0, img)
+ for _ = 1, 1 + rand(4) do
+ local blk = if rand(2) == 0 then 880 else rand(1760)
+ buffer.writeu8(m, blk * 512 + rand(512), rand(256))
+ end
+ local ok = pcall(function()
+ local a = Adf.decode(Bytes.reader(m))
+ if a then
+ for _, e in a:list() do
+ a:read(e.name)
+ end
+ end
+ end)
+ if not ok then
+ threw += 1
+ end
+end
+t:eq(threw, 0, "mutated images never throw")
+t:fuzz("decode", function(b: buffer)
+ return Adf.decode(Bytes.reader(b))
+end, { buffer.tostring(img) }, { mutations = 20, garbage = 20 })
+t:done()
diff --git a/tests/archive/applesingle.luau b/tests/archive/applesingle.luau
new file mode 100644
index 0000000..0e6ca9d
--- /dev/null
+++ b/tests/archive/applesingle.luau
@@ -0,0 +1,23 @@
+-- archive/applesingle tests: the applesingle cases of tools/fixtures/mac.py against The Unarchiver's listings, our output read by unar,
+-- round trips with a resource fork and Finder info (tests/archive/_mac.luau), errors, the fuzz pass.
+local Mod = require("@formats/archive/applesingle")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local run = require("@tests/archive/_mac")
+
+local t, samples = run("applesingle", Mod, { {}, { double = true } })
+local function code(s: string): string?
+ local _, e = Mod.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+local good = buffer.tostring(Mod.encode("hello", { name = "h" }) :: buffer)
+t:eq(code(string.sub(good, 1, 30)), Err.TRUNCATED, "entry table cut")
+t:eq(code(string.sub(good, 1, #good - 2)), Err.TRUNCATED, "entry past the end")
+t:eq(code("\0\5\22\0\0\3\0\0" .. string.rep("\0", 20)), Err.CORRUPT, "bad version")
+-- the AppleDouble name comes from the file name without "._"
+local d = Mod.decode(Bytes.reader(Mod.encode("x", { double = true, name = "" }) :: buffer), { name = "dir/._Report" }) :: any
+t:check(d and d.meta.double, "appledouble flag")
+t:fuzz("decode", function(b: buffer)
+ return Mod.decode(Bytes.reader(b))
+end, samples)
+t:done()
diff --git a/tests/archive/ar.luau b/tests/archive/ar.luau
new file mode 100644
index 0000000..a6ae936
--- /dev/null
+++ b/tests/archive/ar.luau
@@ -0,0 +1,156 @@
+-- archive/ar tests: GNU ar (deterministic and with times, a library with its "/" symbol table), llvm-ar BSD (#1/ names,
+-- __.SYMDEF) and bsdtar arbsd archives list the input files (names, sizes, mtimes, data CRCs) and symbols; the GNU writer
+-- gives GNU ar rcSD's bytes for the same files; bsdtar and dpkg-deb archives re-encode to their own bytes; .deb packages
+-- from dpkg-deb (xz / gzip / zstd / none) and older bzip2 / lzma members give meta.control and load through the api as
+-- their data tar; errors; the fuzz pass. Fixtures: tools/fixtures/ar.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Ar = require("@formats/archive/ar")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/ar")
+
+local t = T.suite("ar")
+t:eq(Ar.name, "ar", "name")
+
+local function decode(s: string): (any, any)
+ return Ar.decode(Bytes.reader(buffer.fromstring(s)))
+end
+
+local function check(a: any, want: any, label: string)
+ local list = a:list()
+ t:eq(#list, #want, label .. ": entry count")
+ for i, w in want do
+ local e = list[i]
+ t:eq(e.name, w.name, label .. ": entry " .. i .. " name")
+ t:eq(e.size, w.size, label .. ": " .. w.name .. " size")
+ if w.mtime then
+ t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime")
+ end
+ if w.crc then
+ local b = a:read(w.name)
+ t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
+ end
+ if w.type then
+ t:eq(e.type, w.type, label .. ": " .. w.name .. " type")
+ end
+ end
+end
+
+local function sortedSymbols(list: { any }): string
+ local s = {}
+ for _, x in list do
+ table.insert(s, x.name .. "@" .. tostring(x.member))
+ end
+ table.sort(s)
+ return table.concat(s, ",")
+end
+
+-- 1. reading
+for _, c in Fx.archives do
+ local a, err = decode(c.data)
+ t:check(a, c.name .. ": " .. tostring(err))
+ check(a, c.entries, c.name)
+ t:eq(a.meta.source.variant, c.variant, c.name .. ": variant")
+ t:eq(F.detect(c.data), "ar", c.name .. ": F.detect")
+ if c.symbols then
+ t:check(a.meta.symbols, c.name .. ": symbols")
+ t:eq(sortedSymbols(a.meta.symbols), sortedSymbols(c.symbols), c.name .. ": symbol names and members")
+ end
+ if c.roundtrip then
+ local out = assert(a:write())
+ local o = buffer.tostring(out)
+ t:check(string.sub(c.data, 1, #o) == o and not string.find(string.sub(c.data, #o + 1), "[^%z]"), c.name .. ": re-encode gives the same bytes (bsdtar pads with zeros)")
+ end
+end
+
+-- 2. writing: GNU ar rcSD's bytes; BSD names read back; any Archive to ar
+do
+ local a = Ar.new()
+ for _, f in Fx.files do
+ a:add(f.name, f.data)
+ end
+ local out = assert(a:write())
+ t:check(buffer.tostring(out) == Fx.gnuD, "gnu: bytes identical to GNU ar rcSD")
+ local bsd = assert(a:write({ variant = "bsd" }))
+ local back = Ar.decode(Bytes.reader(bsd))
+ t:eq(back.meta.source.variant, "bsd", "bsd: variant")
+ t:eq(#back:list(), #Fx.files, "bsd: count")
+ for _, f in Fx.files do
+ t:eq(buffer.tostring(back:read(f.name)), f.data, "bsd: round trip " .. f.name)
+ end
+ local tar = F.format("tar").new()
+ tar:add("dir/", "", { dir = true })
+ tar:add("dir/file.txt", "in a dir", { mtime = 5 })
+ local conv = F.load(assert(F.save(tar, nil, { format = "ar" })))
+ t:eq(#conv:list(), 1, "tar -> ar: directories dropped")
+ t:eq(conv:list()[1].name, "dir/file.txt", "tar -> ar: path name in the long-name table")
+ t:eq(conv:list()[1].mtime, 5, "tar -> ar: mtime")
+end
+
+-- 3. Debian packages
+for _, d in Fx.debs do
+ local a, err = decode(d.data)
+ t:check(a, d.name .. ": " .. tostring(err))
+ t:eq(a.meta.source.variant, "deb", d.name .. ": variant")
+ t:eq(a.meta.debian, "2.0", d.name .. ": debian-binary")
+ t:eq(a.meta.payload, d.payload, d.name .. ": payload")
+ t:check(a.meta.control, d.name .. ": control fields")
+ for k, v in d.control do
+ t:eq(a.meta.control[k], v, d.name .. ": control " .. k)
+ end
+ local out = assert(a:write())
+ t:check(buffer.tostring(out) == d.data, d.name .. ": re-encode gives the same bytes")
+ local data, lerr = F.load(d.data, { name = "hello.deb" })
+ t:check(data, d.name .. ": F.load: " .. tostring(lerr))
+ t:eq(data.format, "tar", d.name .. ": loads as the data tar")
+ t:eq(data.meta.container, "ar", d.name .. ": meta.container")
+ t:eq(data.meta.outer.meta.control.Package, "hello", d.name .. ": meta.outer control")
+ check(data, d.entries, d.name .. " data")
+ local outer = F.load(d.data, { unwrap = false })
+ t:eq(outer.format, "ar", d.name .. ": unwrap = false keeps the ar")
+end
+
+-- 4. errors
+do
+ local _, e1 = decode("!\n")
+ t:check(e1 and e1.code == Err.UNSUPPORTED, "thin archive: " .. tostring(e1))
+ local good = Fx.archives[1].data
+ local b = buffer.fromstring(good)
+ buffer.writeu8(b, 8 + 58, 0x41)
+ local _, e2 = Ar.decode(Bytes.reader(b))
+ t:check(e2 and e2.code == Err.CORRUPT, "bad member header: " .. tostring(e2))
+ local _, e3 = decode(string.sub(good, 1, 100))
+ t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
+ local _, e4 = decode("!\n" .. string.format("%-16s%-12d%-6d%-6d%-8s%-10d`\n", "/99", 0, 0, 0, "644", 0))
+ t:check(e4 and e4.code == Err.CORRUPT, "long name without a table: " .. tostring(e4))
+ local _, e5 = Ar.encode({ kind = "image" })
+ t:check(e5 and e5.code == Err.ARG, "encode a non-archive")
+ local _, e6 = decode("not an archive")
+ t:check(e6 and e6.code == Err.CORRUPT, "bad magic")
+end
+
+local samples = {}
+for _, c in Fx.archives do
+ if #c.data < 8000 then
+ table.insert(samples, c.data)
+ end
+end
+for _, d in Fx.debs do
+ if #d.data < 8000 then
+ table.insert(samples, d.data)
+ end
+end
+t:fuzz("decode", function(b: buffer)
+ local a = Ar.decode(Bytes.reader(b))
+ if a then
+ for _, e in a:list() do
+ a:read(e.name)
+ end
+ a:write()
+ end
+ return a
+end, samples, { mutations = 30, keepHeader = 8 })
+
+t:done()
diff --git a/tests/archive/arj.luau b/tests/archive/arj.luau
new file mode 100644
index 0000000..b9528a0
--- /dev/null
+++ b/tests/archive/arj.luau
@@ -0,0 +1,58 @@
+-- archive/arj tests: archives by ARJ 3.10 with methods 0 .. 4 (stored, the LHA-style Huffman methods 1 .. 3, method
+-- 4) give the files `arj x` extracts (names, sizes, data CRCs); header and data CRC errors, truncation; the fuzz
+-- pass. Fixtures: tools/fixtures/arj.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Arj = require("@formats/archive/arj")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/arj")
+
+local t = T.suite("arj")
+t:eq(Arj.name, "arj", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local a, err = Arj.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name, false)
+ end
+ t:eq(F.detect(c.data), "arj", c.name .. ": detect")
+ table.insert(samples, string.sub(c.data, 1, 3000))
+end
+
+-- errors
+local data = Fx.cases[2].data -- -m1
+local function code(s: string): string?
+ local _, e = Arj.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+local hdr = string.sub(data, 1, 10) .. string.char((string.byte(data, 11) + 1) % 256) .. string.sub(data, 12)
+t:eq(code(hdr), Err.CHECKSUM, "main header CRC")
+t:eq(code(string.sub(data, 1, #data // 2)), Err.TRUNCATED, "cut")
+t:eq(code("\96\234\30\0"), Err.TRUNCATED, "short header")
+t:eq(code("PK\3\4xxxx"), Err.CORRUPT, "not arj")
+local mid = #data // 2 + 1000
+local bad = Arj.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, mid - 1) .. string.char(bit32.bxor(string.byte(data, mid), 0x10)) .. string.sub(data, mid + 1)))) :: any
+local failed = 0
+for _, e in bad:list() do
+ local b, err = bad:read(e.name)
+ if not b then
+ failed += 1
+ t:check(err.code == Err.CHECKSUM or err.code == Err.CORRUPT, "flipped data: " .. tostring(err))
+ end
+end
+t:eq(failed, 1, "one entry fails after a flipped data byte")
+
+t:fuzz("decode", function(b: buffer)
+ local r = Arj.decode(Bytes.reader(b))
+ if r then
+ for _, e in r:list() do
+ r:read(e.name)
+ end
+ end
+ return r
+end, samples, { mutations = 6 })
+t:done()
diff --git a/tests/archive/binhex.luau b/tests/archive/binhex.luau
new file mode 100644
index 0000000..d8a14aa
--- /dev/null
+++ b/tests/archive/binhex.luau
@@ -0,0 +1,26 @@
+-- archive/binhex tests: the binhex cases of tools/fixtures/mac.py against The Unarchiver's listings, our output read by unar,
+-- round trips with a resource fork and Finder info (tests/archive/_mac.luau), errors, the fuzz pass.
+local Mod = require("@formats/archive/binhex")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local run = require("@tests/archive/_mac")
+
+local t, samples = run("binhex", Mod, { {} })
+local function code(s: string): string?
+ local _, e = Mod.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+local good = buffer.tostring(Mod.encode("hello binhex", { name = "h" }) :: buffer)
+-- flip one data character (keeps the 6-bit alphabet): a CRC mismatch somewhere
+local i = #good - 10
+local c = string.sub(good, i, i)
+local bad = string.sub(good, 1, i - 1) .. (if c == "!" then "\"" else "!") .. string.sub(good, i + 1)
+t:eq(code(bad), Err.CHECKSUM, "flipped character")
+t:eq(code(string.sub(good, 1, #good - 3)), Err.TRUNCATED, "no closing colon")
+t:eq(code("nothing"), Err.CORRUPT, "no banner")
+t:eq(code("(This file must be converted with BinHex 4.0)\n:~~~:"), Err.CORRUPT, "bad character")
+t:eq((select(2, Mod.encode({})) :: any).code, Err.ARG, "encode a non-archive")
+t:fuzz("decode", function(b: buffer)
+ return Mod.decode(Bytes.reader(b))
+end, samples)
+t:done()
diff --git a/tests/archive/cab.luau b/tests/archive/cab.luau
new file mode 100644
index 0000000..a8fe737
--- /dev/null
+++ b/tests/archive/cab.luau
@@ -0,0 +1,166 @@
+-- archive/cab tests: cabinets by gcab (stored / MSZIP), lcab, a builder of MSZIP blocks that use the previous block as
+-- their dictionary (several folders, reserve areas, attributes, UTF-8 names) and libmspack's test cabinets give the
+-- files cabextract extracts (names, sizes, data CRCs, DOS times read as UTC); cabextract / gcab / 7z extract our
+-- writer's output (fixture step) and it round-trips; spanned files are UNSUPPORTED; checksum, truncation and
+-- signature errors, libmspack's broken cabinets; LZX (codecs/compress/Lzx) from a fixture compressor whose cabinets
+-- cabextract extracts (windows 2^15 .. 2^21, verbatim / aligned / uncompressed blocks, E8); Quantum
+-- (codecs/compress/Quantum) the same way (windows 2^10 .. 2^21, model rescaling); Deflate's preset
+-- dictionary; the fuzz pass. Fixtures: tools/fixtures/cab.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Cab = require("@formats/archive/cab")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/cab")
+
+local t = T.suite("cab")
+t:eq(Cab.name, "cab", "name")
+
+local function load(s: string, opts: any?): (any, Err.Err?)
+ return Cab.decode(Bytes.reader(buffer.fromstring(s)), opts)
+end
+
+local samples = {}
+local methods = {}
+for _, c in Fx.cases do
+ local a, err = load(c.data)
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ for _, e in a:list() do
+ methods[e.method] = true
+ end
+ end
+ t:eq(F.detect(c.data), "cab", c.name .. ": detect")
+ table.insert(samples, string.sub(c.data, 1, 4000))
+end
+t:check(methods.store and methods.mszip and methods.lzx and methods.quantum, "covers store, mszip, lzx and quantum")
+
+-- attributes, UTF-8 names, reserve areas (the builder's two-folder cabinet)
+local two = assert(load(Fx.cases[5].data))
+local naive = two._byName["na\u{ef}ve \u{2603}.txt"]
+t:check(naive and naive.utf8 and naive.attributes == 0x20, "utf-8 name and attributes")
+t:eq(two.meta.source.reserve.data, 3, "data reserve")
+t:eq(buffer.tostring(two.meta.reserve), "HEADER-RESERVE", "header reserve")
+t:eq(#two.meta.folders, 2, "two folders")
+t:check(assert(load(Fx.cases[4].data))._byName["b.bin"].readonly, "read-only attribute")
+
+-- our writer
+t:check(Fx.ours.ok, "reference tools extract our cabinets: " .. Fx.ours.log)
+E.roundTrip(t, Cab, nil, "round trip mszip")
+E.roundTrip(t, Cab, { compression = "none" }, "round trip store")
+local big = Cab.new()
+big:add("dir/big.bin", E.content(200000, 3), { mtime = 1700000000 })
+big:add("x.txt", "x")
+local bigData = assert(big:write())
+local back = assert(Cab.decode(Bytes.reader(bigData)))
+t:eq(buffer.tostring(assert(back:read("dir/big.bin"))), buffer.tostring(E.content(200000, 3)), "200 KB through 7 blocks")
+t:eq(back:list()[1].mtime, 1700000000, "mtime")
+t:eq(select(2, Cab.encode(big, { compression = "lzx" :: any })).code, Err.ARG, "bad compression")
+
+-- spanned cabinets: files continued from / to another cabinet are UNSUPPORTED, the others read
+for _, c in Fx.spanned do
+ local a, err = load(c.data)
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ local unsupported = 0
+ for _, e in a:list() do
+ local b, rerr = a:read(e.name)
+ if not b then
+ t:eq(rerr.code, Err.UNSUPPORTED, c.name .. ": " .. e.name)
+ unsupported += 1
+ end
+ end
+ t:check(unsupported > 0, c.name .. ": has spanned files")
+ end
+end
+
+-- libmspack's broken cabinets (cabextract fails on every one): an error (never a throw), not a full read
+for _, c in Fx.bad do
+ local a = load(c.data)
+ local ok = a ~= nil
+ if a then
+ for _, e in a:list() do
+ if not a:read(e.name) then
+ ok = false
+ end
+ end
+ end
+ -- a 263-byte file name: over the format's 256-byte limit, which libmspack enforces and we do not
+ t:check(not ok or c.name == "cve-2017-11423-fname-overread.cab", c.name .. ": fails")
+ table.insert(samples, c.data)
+end
+
+-- LZX directly
+local Lzx = require("@formats/codecs/compress/Lzx")
+t:check(not Lzx.decode(buffer.create(10), 0, 10, 100, 14), "LZX window 2^14 unsupported")
+t:check(not Lzx.decode(buffer.create(10), 0, 10, 100, 16), "LZX of zeros")
+t:check(not Lzx.decode(buffer.create(10), 4, 10, 100, 16), "LZX range past the end")
+
+-- Quantum directly
+local Quantum = require("@formats/codecs/compress/Quantum")
+t:check(not Quantum.decode(buffer.create(10), {}, 0, 9), "Quantum window 2^9 unsupported")
+t:check(not Quantum.decode(buffer.create(10), { { at = 0, len = 10, size = 5 } }, 6, 16), "Quantum sizes must add up")
+t:check(not Quantum.decode(buffer.create(10), { { at = 4, len = 10, size = 5 } }, 5, 16), "Quantum range past the end")
+
+-- Deflate's preset dictionary and MSZIP blocks
+local block1 = assert(Deflate.compress(string.rep("ab", 50)))
+local mszip = buffer.create(buffer.len(block1) + 2)
+buffer.writestring(mszip, 0, "CK")
+buffer.copy(mszip, 2, block1)
+t:eq(buffer.tostring(assert(Deflate.mszip(mszip, { { offset = 0, length = buffer.len(mszip), size = 100 } }))), string.rep("ab", 50), "Deflate.mszip")
+t:eq(select(2, Deflate.mszip(mszip, { { offset = 1, length = 4, size = 100 } })).code, Err.CORRUPT, "Deflate.mszip without CK")
+local dictText = string.rep("abcdefgh", 100)
+local z = assert(Deflate.compress(dictText .. dictText))
+local plain = assert(Deflate.inflate(z, nil, nil, 1600, buffer.fromstring("unused prefix")))
+t:eq(buffer.tostring(plain), dictText .. dictText, "inflate with an unused dictionary")
+
+-- errors
+local data = Fx.cases[2].data -- gcab -z
+local function code(s: string): string?
+ local a, e = load(s)
+ if not a then
+ return e and e.code
+ end
+ for _, en in a:list() do
+ local b, rerr = a:read(en.name)
+ if not b then
+ return rerr and rerr.code
+ end
+ end
+ return nil
+end
+t:eq(code(data), nil, "intact")
+t:eq(code("MSCF\0\0\0\0" .. string.rep("\0", 10)), Err.TRUNCATED, "short header")
+t:eq(code("PK\3\4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), Err.CORRUPT, "not a cabinet")
+t:eq(code(string.sub(data, 1, #data - 100)), Err.TRUNCATED, "cut")
+local mid = #data - 200
+local flipped = string.sub(data, 1, mid - 1) .. string.char(bit32.bxor(string.byte(data, mid), 0x08)) .. string.sub(data, mid + 1)
+t:eq(code(flipped), Err.CHECKSUM, "flipped data byte")
+local a2 = assert(load(flipped, { verify = false }))
+local failed = 0
+for _, e in a2:list() do
+ if not a2:read(e.name) then
+ failed += 1
+ end
+end
+t:note("flipped byte without verify: %d entries fail", failed)
+
+t:fuzz("decode", function(b: buffer)
+ local r = Cab.decode(Bytes.reader(b))
+ if r then
+ for _, e in r:list() do
+ r:read(e.name)
+ end
+ end
+ local r2 = Cab.decode(Bytes.reader(b), { verify = false })
+ if r2 then
+ for _, e in r2:list() do
+ r2:read(e.name)
+ end
+ end
+ return r
+end, samples, { mutations = 6 })
+t:done()
diff --git a/tests/archive/cpio.luau b/tests/archive/cpio.luau
new file mode 100644
index 0000000..d4e4b42
--- /dev/null
+++ b/tests/archive/cpio.luau
@@ -0,0 +1,164 @@
+-- archive/cpio tests (and containers/Cpio): GNU cpio archives of one tree in newc / crc / odc / bin (and the bin one
+-- byte-swapped to big endian) and bsdtar newc / odc archives list the entries os.lstat sees (names, types, modes, sizes,
+-- mtimes, link counts, symlink targets, data CRCs, hard links reading the shared data); re-encoding the GNU newc / crc /
+-- odc archives gives GNU's bytes; devices (rdev fields), crc sums, a .cpio.gz through the api, conversions to and from
+-- tar (hard links share an inode), errors, the fuzz pass. Fixtures: tools/fixtures/cpio.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local CpioF = require("@formats/archive/cpio")
+local Cpio = require("@formats/containers/Cpio")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/cpio")
+
+local t = T.suite("cpio")
+t:eq(CpioF.name, "cpio", "name")
+
+local function check(a: any, want: any, label: string)
+ local list = a:list()
+ t:eq(#list, #want, label .. ": entry count")
+ local by = {}
+ for _, e in list do
+ by[e.name] = e
+ end
+ for _, w in want do
+ local e = by[w.name]
+ t:check(e, label .. ": has " .. w.name)
+ t:eq(e.type, w.type, label .. ": " .. w.name .. " type")
+ t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode")
+ t:eq(e.size, w.size, label .. ": " .. w.name .. " size")
+ t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime")
+ if w.type ~= "5" then
+ t:eq(e.nlink, w.nlink, label .. ": " .. w.name .. " nlink")
+ end
+ t:eq(e.link, w.link, label .. ": " .. w.name .. " link")
+ t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir")
+ if w.crc then
+ local b, err = a:read(w.name)
+ t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err))
+ t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
+ end
+ end
+end
+
+-- 1. reading
+for _, c in Fx.archives do
+ local a, err = CpioF.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ do
+ check(a, c.entries, c.name)
+ t:eq(a.meta.source.variant, c.format, c.name .. ": variant")
+ t:eq(F.detect(c.data), "cpio", c.name .. ": F.detect")
+ -- hard links: the later links of the hello.txt group name the first
+ local hl = 0
+ for _, e in a:list() do
+ if e.hardlink then
+ hl += 1
+ end
+ end
+ t:eq(hl, 2, c.name .. ": two later hard links")
+ end
+end
+
+-- 2. writing: GNU's bytes back from the decoded archive (newc / crc / odc)
+for _, c in Fx.archives do
+ if c.gnu and c.format ~= "bin" then
+ local a = CpioF.decode(Bytes.reader(buffer.fromstring(c.data)))
+ local out, err = a:write({ format = c.format })
+ t:check(out, c.name .. ": write: " .. tostring(err))
+ t:check(out and buffer.tostring(out) == c.data, c.name .. ": bytes identical to GNU cpio")
+ end
+end
+
+-- 3. devices, sums, the container directly
+do
+ local list, info = Cpio.read(buffer.fromstring(Fx.devices))
+ t:check(list and info.format == "newc", "devices: read")
+ t:eq(#list, 4, "devices: entries")
+ t:eq(list[2].type, "3", "char device")
+ t:eq(list[2].rdevmajor * 256 + list[2].rdevminor, 259, "null: rdev 1:3")
+ t:eq(list[3].type, "4", "block device")
+ t:eq(list[3].rdevmajor, 8, "sda: rdev major")
+ t:eq(list[4].type, "s", "socket")
+ local _, e1 = Cpio.read(buffer.fromstring(Fx.badcrc))
+ t:check(e1 and e1.code == Err.CHECKSUM, "crc: bad sum: " .. tostring(e1))
+ t:check(Cpio.read(buffer.fromstring(Fx.badcrc), 0, nil, { verify = false }), "crc: verify = false")
+ -- devices survive a newc and an odc write
+ for _, fmt in { "newc", "odc" } do
+ local a = CpioF.decode(Bytes.reader(buffer.fromstring(Fx.devices)))
+ local back = CpioF.decode(Bytes.reader(assert(a:write({ format = fmt }))))
+ local d = back:list()[3]
+ t:check(d.type == "4" and d.rdevmajor == 8 and d.rdevminor == 0, fmt .. ": block device round trip")
+ end
+end
+
+-- 4. the api: .cpio.gz unwraps, Archive values, conversions
+do
+ local a, err = F.load(Fx.gz, { name = "tree.cpio.gz" })
+ t:check(a and a.format == "cpio" and a.meta.compression == "gzip", "cpio.gz unwraps: " .. tostring(err))
+ local c = CpioF.new()
+ c:add("bin/", "", { dir = true })
+ c:add("bin/run.sh", "#!/bin/sh\n", { mode = 493, mtime = 1767225600 })
+ local back = F.load(assert(F.save(c)))
+ t:eq(back.format, "cpio", "F.save(cpio) round trip")
+ t:eq(back:list()[2].mode, 493, "mode round trip")
+ t:eq(back:list()[2].mtime, 1767225600, "mtime round trip")
+ t:eq(buffer.tostring(back:read("bin/run.sh")), "#!/bin/sh\n", "data round trip")
+ -- cpio -> tar keeps symlinks; tar -> cpio turns tar hard links into a shared inode
+ local gnu = CpioF.decode(Bytes.reader(buffer.fromstring(Fx.archives[1].data)))
+ local tar = F.load(assert(F.save(gnu, nil, { format = "tar" })))
+ local sym
+ for _, e in tar:list() do
+ if e.name == "sym" then
+ sym = e
+ end
+ end
+ t:check(sym and sym.type == "2" and sym.link == "hello.txt", "cpio -> tar: symlink")
+ local tf = F.format("tar").new()
+ tf:add("a.txt", "shared")
+ tf:add("b.txt", "")
+ tf._byName["b.txt"].type, tf._byName["b.txt"].link = "1", "a.txt"
+ local cp = F.load(assert(F.save(tf, nil, { format = "cpio" })))
+ t:eq(buffer.tostring(cp:read("b.txt")), "shared", "tar hard link -> cpio: data")
+ t:eq(cp:list()[2].hardlink, "a.txt", "tar hard link -> cpio: hardlink")
+ t:eq(cp:list()[1].nlink, 2, "tar hard link -> cpio: nlink")
+end
+
+-- 5. errors
+do
+ local good = Fx.archives[1].data
+ local _, e1 = CpioF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 300))))
+ t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
+ local b = buffer.fromstring(good)
+ buffer.writeu8(b, 10, string.byte("z"))
+ local _, e2 = CpioF.decode(Bytes.reader(b))
+ t:check(e2 and e2.code == Err.CORRUPT, "bad hex field: " .. tostring(e2))
+ local _, e3 = CpioF.encode({ kind = "image" })
+ t:check(e3 and e3.code == Err.ARG, "encode a non-archive")
+ local _, e4 = Cpio.write({ { name = "x", data = buffer.create(1), mtime = 2 ^ 40 } }, { format = "odc" })
+ t:check(e4 and e4.code == Err.ARG, "odc: mtime too large")
+ local _, e5 = CpioF.decode(Bytes.reader(buffer.fromstring("070701")))
+ t:check(e5 and e5.code == Err.TRUNCATED, "header past the end")
+ t:eq(CpioF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 64)))), 0, "zeros are not cpio")
+end
+
+local samples = {}
+for _, c in Fx.archives do
+ if #c.data <= 20000 then
+ table.insert(samples, c.data)
+ end
+end
+table.insert(samples, Fx.devices)
+t:fuzz("decode", function(b: buffer)
+ local a = CpioF.decode(Bytes.reader(b))
+ if a then
+ for _, e in a:list() do
+ a:read(e.name)
+ end
+ a:write()
+ end
+ return a
+end, samples, { mutations = 30, keepHeader = 0 })
+
+t:done()
diff --git a/tests/archive/d64.luau b/tests/archive/d64.luau
new file mode 100644
index 0000000..b5b5ab4
--- /dev/null
+++ b/tests/archive/d64.luau
@@ -0,0 +1,75 @@
+-- archive/d64 tests: D64 / D71 / D81 images made by VICE's c1541 (PRG / SEQ / USR, multi-sector, a deleted file, an
+-- error-info block, 30 files over several directory sectors) list the files c1541 reads back (names, sizes, types,
+-- data CRCs), disk name and id; our D64 / D71 / D81 output is read by c1541 (fixture step) and round-trips; PETSCII
+-- names; errors; the fuzz pass. Fixtures: tools/fixtures/d64.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local D64 = require("@formats/archive/d64")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/d64")
+
+local t = T.suite("d64")
+t:eq(D64.name, "d64", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local a, err = D64.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ t:eq(a.meta.disk, c.disk, c.name .. ": disk name")
+ t:eq(a.meta.id, c.id, c.name .. ": disk id")
+ for _, w in c.entries do
+ local e = a._byName[w.name]
+ t:eq(e and e.type, w.type, c.name .. ": " .. w.name .. " type")
+ end
+ t:check(a._byName.gone == nil, c.name .. ": deleted file skipped")
+ end
+ t:eq(F.detect(c.data), "d64", c.name .. ": detect")
+ if c.name == "d64" then
+ table.insert(samples, c.data)
+ end
+end
+for _, o in Fx.ours do
+ t:check(o.ok, "c1541 reads our " .. o.variant .. ": " .. o.listing)
+end
+for _, v in { "d64", "d71", "d81" } do
+ local out = E.roundTrip(t, D64, { variant = v, disk = "round trip", id = "rt" }, "round trip " .. v)
+ if out then
+ local a = D64.decode(Bytes.reader(out)) :: any
+ t:eq(a.meta.variant, v, v .. ": variant")
+ t:eq(a.meta.disk, "round trip", v .. ": disk name")
+ end
+end
+-- PETSCII names: lower / upper case and other bytes survive a round trip
+local a = D64.new()
+a:add("Mixed Case 1", "x")
+a:add("\u{E0D3}hift", "y")
+local back = D64.decode(Bytes.reader(a:write() :: buffer)) :: any
+t:check(back._byName["Mixed Case 1"] and back._byName["\u{E0D3}hift"] == nil and back._byName["Shift"], "petscii names")
+
+-- errors
+local function code(b: buffer): string?
+ local _, e = D64.decode(Bytes.reader(b))
+ return e and e.code
+end
+t:eq(code(buffer.create(1000)), Err.CORRUPT, "bad size")
+local img = buffer.fromstring(Fx.cases[1].data)
+local dir = 357 * 256 -- track 18 sector 0
+buffer.writeu8(img, dir, 99)
+t:eq(code(img), Err.CORRUPT, "directory link off the disk")
+local many = D64.new()
+for i = 1, 145 do
+ many:add("f" .. i, "x")
+end
+t:eq((select(2, many:write()) :: any).code, Err.LIMIT, "directory full")
+local big = D64.new()
+big:add("big", buffer.create(200000))
+t:eq((select(2, big:write()) :: any).code, Err.LIMIT, "disk full")
+
+t:fuzz("decode", function(b: buffer)
+ return D64.decode(Bytes.reader(b))
+end, samples, { mutations = 60, garbage = 20 })
+t:done()
diff --git a/tests/archive/fat.luau b/tests/archive/fat.luau
new file mode 100644
index 0000000..277a15b
--- /dev/null
+++ b/tests/archive/fat.luau
@@ -0,0 +1,84 @@
+-- archive/fat tests (and containers/Fat): FAT12 (1.44 MB, 720 KB) / FAT16 / FAT32 images by mkfs.fat filled by mtools
+-- (long names over several entries, lower-case 8.3, non-ASCII names, nested directories, empty and many-cluster files)
+-- and a hard-disk image with an MBR partition list what mtools extracts (names, sizes, data CRCs, dates as UTC,
+-- directories), FAT width and label; our floppies pass fsck.fat -n and extract with mtools (fixture step) and
+-- round-trip; errors; the fuzz pass. Fixtures: tools/fixtures/fat.py (images gzip-compressed).
+local T = require("@tests/T")
+local F = require("@formats")
+local FatF = require("@formats/archive/fat")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/fat")
+
+local t = T.suite("fat")
+t:eq(FatF.name, "fat", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local gz = buffer.fromstring(c.gz)
+ local data = Deflate.gunzip(gz, 0, buffer.len(gz)) :: buffer
+ local a, err = FatF.decode(Bytes.reader(data))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ t:eq(a.meta.fat, c.bits, c.name .. ": bits")
+ t:eq(a.meta.label, c.label, c.name .. ": label")
+ end
+ t:eq(F.detect(data), "fat", c.name .. ": detect")
+ if c.name == "fat12 720K" then
+ table.insert(samples, data)
+ end
+end
+for _, o in Fx.ours do
+ t:check(o.ok, "mtools extracts our " .. o.size .. " KB floppy")
+ t:check(not string.find(o.fsck, "rror") and string.find(o.fsck, " files, ", 1, true) ~= nil and select(2, string.gsub(o.fsck, "\n", "")) == 2, "fsck.fat -n is clean: " .. o.fsck)
+end
+for _, size in { 1440, 720, 360, 2880 } do
+ E.roundTrip(t, FatF, { size = size }, "round trip " .. size)
+end
+-- long and short names, directories, dates
+local a = FatF.new()
+a:add("Some Long Name.html", "a", { mtime = 1700000000 })
+a:add("dir/UPPER.TXT", "b", { mtime = 1700000002 })
+a:add("dir/lower.txt", "c")
+a:add("dir/Same Prefix 1.txt", "d")
+a:add("dir/Same Prefix 2.txt", "e")
+a:add("empty dir/", "", { dir = true })
+local back = FatF.decode(Bytes.reader(a:write({ label = "Test" }) :: buffer)) :: any
+t:check(back, "names round trip decodes")
+for _, n in { "Some Long Name.html", "dir/UPPER.TXT", "dir/lower.txt", "dir/Same Prefix 1.txt", "dir/Same Prefix 2.txt", "empty dir/", "dir/" } do
+ t:check(back._byName[n], "names round trip: " .. n)
+end
+t:eq(back._byName["dir/UPPER.TXT"].mtime, 1700000002, "dos time")
+t:eq(back._byName["dir/Same Prefix 2.txt"].shortName, "SAMEPR~2.TXT", "numeric tail")
+t:eq(back.meta.label, "TEST", "label")
+
+-- errors
+local function code(b: buffer): string?
+ local _, e = FatF.decode(Bytes.reader(b))
+ return e and e.code
+end
+t:eq(code(buffer.create(100)), Err.TRUNCATED, "short")
+t:eq(code(buffer.create(4096)), Err.CORRUPT, "no boot sector")
+local big = FatF.new()
+big:add("big", buffer.create(2000000))
+t:eq((select(2, big:write()) :: any).code, Err.LIMIT, "disk full")
+local clash = FatF.new()
+clash:add("x", "file")
+clash:add("x/y", "under a file")
+t:eq((select(2, clash:write()) :: any).code, Err.ARG, "file and directory clash")
+t:eq((select(2, FatF.encode(FatF.new(), { size = 999 })) :: any).code, Err.ARG, "bad size")
+
+-- fuzz: the boot sector, FAT and directories are in the first 16 KB
+t:fuzz("decode", function(b: buffer)
+ local r = FatF.decode(Bytes.reader(b))
+ if r then
+ for _, e in r:list() do
+ r:read(e.name)
+ end
+ end
+ return r
+end, samples, { mutations = 200, garbage = 20, seed = 5 })
+t:done()
diff --git a/tests/archive/iso.luau b/tests/archive/iso.luau
new file mode 100644
index 0000000..c961d9d
--- /dev/null
+++ b/tests/archive/iso.luau
@@ -0,0 +1,134 @@
+-- archive/iso tests (and containers/Iso9660): xorriso images (plain names, Joliet, Rock Ridge, Joliet + Rock Ridge with
+-- deep directories / a 200-byte name / a long symlink target) and a genisoimage -J -R image (rr_moved relocation, CE
+-- areas) list what the source tree holds (Rock Ridge: names, modes, symlink targets, mtimes, data CRCs) or what pycdlib
+-- reads (plain and Joliet names, sizes, data CRCs); prefer = "joliet" on a -J -R image; an El Torito boot catalog as
+-- xorriso reports it; a crafted multi-extent file reads whole; an interleaved file is UNSUPPORTED; errors; the fuzz pass.
+-- Fixtures: tools/fixtures/iso.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Iso = require("@formats/archive/iso")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/iso")
+
+local t = T.suite("iso")
+t:eq(Iso.name, "iso", "name")
+
+local function dataOf(c: any): string
+ return if c.same then Fx.images[c.same].data else c.data
+end
+
+for _, c in Fx.images do
+ local a, err = Iso.decode(Bytes.reader(buffer.fromstring(dataOf(c))), { prefer = c.tree :: any })
+ t:check(a, c.name .. ": " .. tostring(err))
+ t:eq(a.meta.iso.tree, c.tree, c.name .. ": name set")
+ t:eq(F.detect(dataOf(c)), "iso", c.name .. ": F.detect")
+ local by = {}
+ for _, e in a:list() do
+ by[e.name] = e
+ end
+ t:eq(#a:list(), #c.entries, c.name .. ": entry count")
+ for _, w in c.entries do
+ local e = by[w.name]
+ t:check(e, c.name .. ": has " .. w.name)
+ t:eq(e.dir, w.dir, c.name .. ": " .. w.name .. " dir")
+ if w.mode then
+ t:eq(e.mode, w.mode, c.name .. ": " .. w.name .. " mode")
+ end
+ if w.link then
+ t:eq(e.type, "2", c.name .. ": " .. w.name .. " symlink")
+ t:eq(e.link, w.link, c.name .. ": " .. w.name .. " target")
+ end
+ if w.mtime and not w.dir then
+ t:eq(e.mtime, w.mtime, c.name .. ": " .. w.name .. " mtime")
+ end
+ if w.crc then
+ t:eq(e.size, w.size, c.name .. ": " .. w.name .. " size")
+ local b, rerr = a:read(w.name)
+ t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr))
+ t:eq(Crc32.of(b), w.crc, c.name .. ": " .. w.name .. " data")
+ end
+ end
+ t:note("%-24s %-9s %3d entries", c.name, c.tree, #c.entries)
+end
+
+-- the default name set: Rock Ridge over Joliet; Joliet over plain
+do
+ local jr = Iso.decode(Bytes.reader(buffer.fromstring(Fx.images[5].data)))
+ t:eq(jr.meta.iso.tree, "rockridge", "-J -R: Rock Ridge by default")
+ t:eq(jr.meta.iso.joliet, 3, "-J -R: Joliet level 3 seen")
+ t:check(jr.meta.iso.rockRidge, "-J -R: rockRidge")
+ local j = Iso.decode(Bytes.reader(buffer.fromstring(Fx.images[2].data)))
+ t:eq(j.meta.iso.tree, "joliet", "-J: Joliet by default")
+ local p = F.load(Fx.images[1].data)
+ t:eq(p.format, "iso", "F.load")
+ t:eq(p.meta.iso.tree, "iso9660", "plain")
+ t:check(p.meta.iso.blockSize == 2048 and p.meta.iso.blocks > 0, "volume facts")
+ -- any Archive converts: iso -> tar
+ local tar = F.load(assert(F.save(jr, nil, { format = "tar" })))
+ t:eq(buffer.tostring(tar:read("hello.txt")), "hello, iso\n", "iso -> tar")
+end
+
+-- El Torito
+do
+ local a = Iso.decode(Bytes.reader(buffer.fromstring(Fx.boot.data)))
+ local bt = a.meta.boot
+ t:check(bt, "boot catalog")
+ t:eq(bt.catalog, Fx.boot.catalog, "boot: catalog LBA")
+ t:eq(bt.lba, Fx.boot.lba, "boot: image LBA")
+ t:eq(bt.sectors, Fx.boot.sectors, "boot: load size")
+ t:eq(bt.bootable, Fx.boot.bootable, "boot: bootable")
+ t:eq(bt.media, 0, "boot: no emulation")
+ t:check(bt.valid, "boot: validation entry checksum")
+end
+
+-- multi-extent and interleaved records
+do
+ local a = Iso.decode(Bytes.reader(buffer.fromstring(Fx.multi.data)))
+ local n = 0
+ for _, e in a:list() do
+ if e.name == Fx.multi.name then
+ n += 1
+ t:eq(e.size, Fx.multi.size, "multi-extent: size")
+ end
+ end
+ t:eq(n, 1, "multi-extent: one entry")
+ t:eq(Crc32.of(a:read(Fx.multi.name)), Fx.multi.crc, "multi-extent: data")
+ local il = Iso.decode(Bytes.reader(buffer.fromstring(Fx.interleaved)))
+ local _, e = il:read("HELLO.TXT")
+ t:check(e and e.code == Err.UNSUPPORTED, "interleaved: " .. tostring(e))
+end
+
+-- errors
+do
+ local good = Fx.images[1].data
+ local _, e1 = Iso.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 20000))))
+ t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
+ local b = buffer.fromstring(good)
+ buffer.writeu8(b, 16 * 2048 + 1, 0x58)
+ local _, e2 = Iso.decode(Bytes.reader(b))
+ t:check(e2 and e2.code == Err.CORRUPT, "bad descriptor: " .. tostring(e2))
+ local cut = Iso.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 20 * 2048))))
+ t:check(cut == nil or cut, "a cut image: no throw")
+ t:eq(Iso.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 40000)))), 0, "zeros are not an iso")
+end
+
+-- fuzz: the volume descriptors and directories (the first 64 KB of a few images: their data lies further out)
+local samples = {}
+for i, c in Fx.images do
+ if c.data and (i == 1 or i == 3 or i == 5) then
+ table.insert(samples, string.sub(c.data, 1, 26 * 2048))
+ end
+end
+t:fuzz("decode", function(b: buffer)
+ local a = Iso.decode(Bytes.reader(b))
+ if a then
+ for _, e in a:list() do
+ a:read(e.name)
+ end
+ end
+ return a
+end, samples, { mutations = 40, keepHeader = 16 * 2048 })
+
+t:done()
diff --git a/tests/archive/lha.luau b/tests/archive/lha.luau
new file mode 100644
index 0000000..892c043
--- /dev/null
+++ b/tests/archive/lha.luau
@@ -0,0 +1,86 @@
+-- archive/lha tests (and codecs/compress/Lzh): lhasa's test archives (LHarc lh1, LArc lzs / lz5 / lz4, LHA lh0 / lh5 /
+-- lh6 / lh7 by many DOS / Amiga / OS-9 / Unix / Windows tools, header levels 0 / 1 / 2, subdirectories, symlinks, lh1 and
+-- lz5 length tests up to 2 MB) and LHa for UNIX archives (-o5 / -o6 / -o7 / -z at levels 0 / 1 / 2) give the files lhasa
+-- extracts (names, sizes, data CRCs) and its symlinks; our level-2 lh0 output extracts with lhasa (fixture step) and
+-- round-trips; CRC and truncation errors; the fuzz pass. Fixtures: tools/fixtures/lha.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Lha = require("@formats/archive/lha")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/lha")
+
+local t = T.suite("lha")
+t:eq(Lha.name, "lha", "name")
+
+local samples = {}
+local methods = {}
+for _, c in Fx.cases do
+ local a, err = Lha.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name, false)
+ for _, l in c.links do
+ local e = a._byName[l.name]
+ t:check(e and e.link == l.link, c.name .. ": symlink " .. l.name)
+ end
+ for _, e in a:list() do
+ methods[e.method] = (methods[e.method] or 0) + 1
+ end
+ end
+ if string.sub(c.data, 1, 2) ~= "MZ" then
+ t:eq(F.detect(c.data), "lha", c.name .. ": detect")
+ end
+ if #c.data < 6000 then
+ table.insert(samples, c.data)
+ end
+end
+local seen = {}
+for m in methods do
+ table.insert(seen, m)
+end
+table.sort(seen)
+t:note("methods: %s", table.concat(seen, " "))
+for _, m in { "lh0", "lh1", "lh5", "lh6", "lh7", "lzs", "lz5", "lz4", "lhd" } do
+ t:check(methods[m], "covers " .. m)
+end
+t:check(Fx.ours.ok, "lhasa extracts our archive: " .. Fx.ours.listing)
+E.roundTrip(t, Lha, nil, "round trip")
+local a = Lha.new()
+a:add("dir/sub/file.txt", "nested", { mode = 0x1A4, mtime = 1700000000 })
+a:add("dir/", "", { dir = true, mode = 0x1ED })
+local back = Lha.decode(Bytes.reader(a:write() :: buffer)) :: any
+t:check(back._byName["dir/sub/file.txt"] and back._byName["dir/sub/file.txt"].mode == 0x81A4 and back._byName["dir/"], "directories and modes round trip")
+
+-- errors: a flipped data byte in an lh5 entry fails its CRC (or decodes to a bad code), a cut archive is truncated
+local function first(pattern: string): any
+ for _, c in Fx.cases do
+ if string.find(c.name, pattern) then
+ return c
+ end
+ end
+ return nil
+end
+local c5 = first("lha114i %-h2 %-5")
+local bad = buffer.fromstring(c5.data)
+local ar = Lha.decode(Bytes.reader(bad)) :: any
+local ent = ar._byName["data.bin"]
+buffer.writeu8(bad, buffer.len(bad) // 2, bit32.bxor(buffer.readu8(bad, buffer.len(bad) // 2), 0x40)) -- inside dir/rand.bin
+local mut = Lha.decode(Bytes.reader(bad)) :: any
+local _, rerr = mut:read("dir/rand.bin")
+t:check(ent and rerr and (rerr.code == Err.CHECKSUM or rerr.code == Err.CORRUPT), "corrupt data: " .. tostring(rerr))
+local _, terr = Lha.decode(Bytes.reader(buffer.fromstring(string.sub(c5.data, 1, 200))))
+t:eq(terr and terr.code, Err.TRUNCATED, "cut archive")
+t:eq((select(2, Lha.decode(Bytes.reader(buffer.fromstring(string.rep("x", 100))))) :: any).code, Err.CORRUPT, "no header")
+
+t:fuzz("decode", function(b: buffer)
+ local r = Lha.decode(Bytes.reader(b))
+ if r then
+ for _, e in r:list() do
+ r:read(e.name)
+ end
+ end
+ return r
+end, samples, { mutations = 4, garbage = 50 })
+t:done()
diff --git a/tests/archive/lz4.luau b/tests/archive/lz4.luau
new file mode 100644
index 0000000..834e3bb
--- /dev/null
+++ b/tests/archive/lz4.luau
@@ -0,0 +1,119 @@
+-- archive/lz4 tests (and codecs/compress/Xxh32): frames from the lz4 tool (default, linked blocks, 64 KB blocks, block
+-- checksums, content size, no content checksum, HC, legacy), concatenated and skippable frames decode to their corpora;
+-- our frames (every option set) decode with `lz4 -d` (verdicts from the fixture step) and round-trip; XXH32 test
+-- vectors; checksum / size / truncation errors; the api (.tar.lz4 unwrap, naming); the fuzz pass.
+-- Fixtures: tools/fixtures/lz4frame.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Lz4F = require("@formats/archive/lz4")
+local Xxh32 = require("@formats/codecs/compress/Xxh32")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/lz4frame")
+local C = require("@tests/gen/lz4frame_corpora")
+
+local t = T.suite("lz4")
+t:eq(Lz4F.name, "lz4", "name")
+
+-- XXH32 vectors (xxHash's sanity checks)
+t:eq(Xxh32.hash(buffer.fromstring("")), 0x02CC5D05, "xxh32 empty")
+t:eq(Xxh32.hash(buffer.fromstring(""), 0, 0, 0x9E3779B1), 0x36B78AE7, "xxh32 empty, seed prime")
+t:eq(Xxh32.hash(buffer.fromstring("a")), 0x550D7456, "xxh32 a")
+t:eq(Xxh32.hash(buffer.fromstring("abc")), 0x32D153FF, "xxh32 abc")
+t:eq(Xxh32.hash(buffer.fromstring("Nobody inspects the spammish repetition")), 0xE2293B2F, "xxh32 sentence")
+
+local function want(c: any): string
+ if c.corpus == "short+text" then
+ return C.short .. C.text
+ end
+ return C[c.corpus]
+end
+
+for _, c in Fx.cases do
+ local out, err = Lz4F.decompress(c.data)
+ t:check(out, c.name .. ": " .. tostring(err))
+ local w = want(c)
+ t:eq(buffer.len(out), #w, c.name .. ": size")
+ t:eq(Crc32.of(out), Crc32.of(buffer.fromstring(w)), c.name .. ": data")
+ t:eq(F.detect(c.data), "lz4", c.name .. ": F.detect")
+end
+
+-- our frames, read by lz4 -d
+t:check(#Fx.ours >= 15, "verdicts present")
+for _, v in Fx.ours do
+ t:check(v.ok, "lz4 -d reads our " .. v.name)
+end
+for name, data in C do
+ for _, o in { {}, { blockSize = 65536, blockChecksum = true, contentSize = true }, { contentChecksum = false } } do
+ local z = assert(Lz4F.compress(data, o :: any))
+ t:eq(buffer.tostring(assert(Lz4F.decompress(z))), data, "round trip " .. name)
+ end
+end
+
+-- the api
+do
+ local a = assert(F.load(Fx.cases[1].data, { name = "notes.txt.lz4" }))
+ t:check(a.meta.stream and a.format == "lz4", "single stream")
+ t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
+ local tar = F.format("tar").new()
+ tar:add("a.txt", "alpha")
+ tar:add("b.txt", "beta")
+ local tl = assert(F.save(tar, nil, { format = "lz4" }))
+ local back = F.load(tl, { name = "x.tlz4" })
+ t:eq(back.format, "tar", "several entries: a .tar.lz4 that unwraps")
+ t:eq(back.meta.compression, "lz4", "meta.compression")
+ t:eq(F.load(tl, { name = "x.tlz4", unwrap = false }):list()[1].name, "x.tar", ".tlz4 -> .tar")
+ local s = assert(F.save("some text", nil, { format = "lz4" }))
+ t:eq(buffer.tostring(F.load(s):read("data")), "some text", "a string")
+end
+
+-- errors
+do
+ local good
+ for _, c in Fx.cases do
+ if c.name == "text/BX" then
+ good = c.data
+ end
+ end
+ local function flip(at: number): buffer
+ local b = buffer.fromstring(good)
+ buffer.writeu8(b, at, bit32.bxor(buffer.readu8(b, at), 1))
+ return b
+ end
+ local _, e1 = Lz4F.decompress(flip(6))
+ t:check(e1 and e1.code == Err.CHECKSUM, "header checksum: " .. tostring(e1))
+ local _, e2 = Lz4F.decompress(flip(20))
+ t:check(e2 and e2.code == Err.CHECKSUM, "block checksum: " .. tostring(e2))
+ local _, e3 = Lz4F.decompress(flip(#good - 2))
+ t:check(e3 and e3.code == Err.CHECKSUM, "content checksum: " .. tostring(e3))
+ t:check(Lz4F.decompress(flip(#good - 2), nil, nil, { verify = false }), "verify = false")
+ local _, e4 = Lz4F.decompress(string.sub(good, 1, 1000))
+ t:check(e4 and e4.code == Err.TRUNCATED, "truncated: " .. tostring(e4))
+ local _, e5 = Lz4F.decompress(Fx.cases[1].data, nil, nil, { maxBytes = 10 })
+ t:check(e5 == nil or e5.code == Err.LIMIT, "maxBytes")
+ local big
+ for _, c in Fx.cases do
+ if c.name == "zeros/default" then
+ big = c.data
+ end
+ end
+ local _, e6 = Lz4F.decompress(big, nil, nil, { maxBytes = 1000 })
+ t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
+ local _, e7 = Lz4F.compress("x", { blockSize = 1000 })
+ t:check(e7 and e7.code == Err.ARG, "bad blockSize")
+ local _, e8 = Lz4F.decompress("not lz4 at all")
+ t:check(e8 and e8.code == Err.CORRUPT, "bad magic")
+end
+
+local samples = {}
+for _, c in Fx.cases do
+ if #c.data < 6000 then
+ table.insert(samples, c.data)
+ end
+end
+t:fuzz("decode", function(b: buffer)
+ return Lz4F.decode(Bytes.reader(b), { maxBytes = 2 ^ 22 })
+end, samples, { mutations = 40, keepHeader = 4 })
+
+t:done()
diff --git a/tests/archive/macbinary.luau b/tests/archive/macbinary.luau
new file mode 100644
index 0000000..465f183
--- /dev/null
+++ b/tests/archive/macbinary.luau
@@ -0,0 +1,24 @@
+-- archive/macbinary tests: the macbinary cases of tools/fixtures/mac.py against The Unarchiver's listings, our output read by unar,
+-- round trips with a resource fork and Finder info (tests/archive/_mac.luau), errors, the fuzz pass.
+local Mod = require("@formats/archive/macbinary")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local run = require("@tests/archive/_mac")
+
+local t, samples = run("macbinary", Mod, { {} })
+local function code(s: string): string?
+ local _, e = Mod.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+local good = Mod.encode("hello macbinary", { name = "h" }) :: buffer
+local bad = buffer.create(buffer.len(good))
+buffer.copy(bad, 0, good)
+buffer.writeu8(bad, 70, 1)
+t:eq(code(buffer.tostring(bad)), Err.CHECKSUM, "header CRC")
+t:eq(code(string.sub(buffer.tostring(good), 1, 140)), Err.TRUNCATED, "short data fork")
+t:eq(code(string.rep("\1", 200)), Err.CORRUPT, "not MacBinary")
+t:eq(code("short"), Err.TRUNCATED, "short header")
+t:fuzz("decode", function(b: buffer)
+ return Mod.decode(Bytes.reader(b))
+end, samples, { keepHeader = 0 })
+t:done()
diff --git a/tests/archive/rpm.luau b/tests/archive/rpm.luau
new file mode 100644
index 0000000..80f305b
--- /dev/null
+++ b/tests/archive/rpm.luau
@@ -0,0 +1,101 @@
+-- archive/rpm tests: one package from rpmbuild with each payload compressor (gzip, bzip2, xz, lzma, zstd, none) gives
+-- the header fields `rpm -qp --qf` prints, its file list (names, sizes, modes, mtimes, symlink targets; %ghost files
+-- skipped), the file data rpm2cpio's stream holds (CRCs, hard links), and Rpm.cpio = rpm2cpio's bytes; errors; the
+-- fuzz pass. Fixtures: tools/fixtures/rpm.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Rpm = require("@formats/archive/rpm")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/rpm")
+
+local t = T.suite("rpm")
+t:eq(Rpm.name, "rpm", "name")
+
+local TYPES = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2" }
+
+for _, c in Fx.rpms do
+ local a, err = Rpm.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ t:eq(F.detect(c.data), "rpm", c.name .. ": F.detect")
+ for k, v in c.fields do
+ t:eq(a.meta.rpm[k], v, c.name .. ": " .. k)
+ end
+ t:eq(a.meta.rpm.type, "binary", c.name .. ": binary package")
+ local by = {}
+ for _, e in a:list() do
+ by[e.name] = e
+ end
+ local n = 0
+ for _, w in c.files do
+ local e = by[w.name]
+ if w.flags % 128 >= 64 then
+ t:check(e == nil, c.name .. ": ghost " .. w.name .. " not listed")
+ continue
+ end
+ n += 1
+ t:check(e, c.name .. ": has " .. w.name)
+ t:eq(e.type, TYPES[w.type], c.name .. ": " .. w.name .. " type")
+ t:eq(e.mode, w.mode, c.name .. ": " .. w.name .. " mode")
+ t:eq(e.mtime, w.mtime, c.name .. ": " .. w.name .. " mtime")
+ t:eq(e.link, w.link, c.name .. ": " .. w.name .. " link")
+ if w.crc then
+ t:eq(e.size, w.size, c.name .. ": " .. w.name .. " size")
+ local b, rerr = a:read(w.name)
+ t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr))
+ t:eq(Crc32.of(b), w.crc, c.name .. ": " .. w.name .. " data")
+ end
+ end
+ t:eq(#a:list(), n, c.name .. ": entry count")
+ -- hard links: both read the same bytes
+ t:eq(buffer.tostring(a:read("usr/bin/hello")), "#!/bin/sh\necho hello\n", c.name .. ": hard link (first)")
+ t:eq(buffer.tostring(a:read("usr/bin/hello2")), "#!/bin/sh\necho hello\n", c.name .. ": hard link (second)")
+ local raw = Rpm.cpio(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(raw and buffer.len(raw) == c.cpioSize and Crc32.of(raw) == c.cpioCrc, c.name .. ": Rpm.cpio = rpm2cpio")
+ t:note("%-16s %s %d files", c.name, tostring(a.meta.rpm.payloadCompressor), n)
+end
+
+-- the api: an rpm loads as itself (no payload unwrap), converts to tar
+do
+ local c = Fx.rpms[1]
+ local a = assert(F.load(c.data))
+ t:eq(a.format, "rpm", "F.load")
+ local tar = F.load(assert(F.save(a, nil, { format = "tar" })))
+ t:eq(buffer.tostring(tar:read("usr/bin/hello")), "#!/bin/sh\necho hello\n", "rpm -> tar")
+ local _, e = F.save(a)
+ t:check(e, "rpm is read-only")
+end
+
+-- errors
+do
+ local good = Fx.rpms[1].data
+ local _, e1 = Rpm.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 50))))
+ t:check(e1 and e1.code == Err.TRUNCATED, "short lead: " .. tostring(e1))
+ local b = buffer.fromstring(good)
+ buffer.writeu8(b, 96, 0)
+ local _, e2 = Rpm.decode(Bytes.reader(b))
+ t:check(e2 and e2.code == Err.CORRUPT, "bad signature magic: " .. tostring(e2))
+ local cut = Rpm.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, #good - 200))))
+ t:check(cut, "a cut payload still lists")
+ local _, e3 = cut:read("usr/share/doc/hello/README")
+ t:check(e3 ~= nil, "a cut payload fails on read: " .. tostring(e3))
+end
+
+local samples = {}
+for _, c in Fx.rpms do
+ if #c.data < 40000 then
+ table.insert(samples, c.data)
+ end
+end
+t:fuzz("decode", function(b: buffer)
+ local a = Rpm.decode(Bytes.reader(b))
+ if a then
+ for _, e in a:list() do
+ a:read(e.name)
+ end
+ end
+ return a
+end, samples, { mutations = 25, keepHeader = 4 })
+
+t:done()
diff --git a/tests/archive/uu.luau b/tests/archive/uu.luau
new file mode 100644
index 0000000..bdce844
--- /dev/null
+++ b/tests/archive/uu.luau
@@ -0,0 +1,70 @@
+-- archive/uu tests: blocks by GNU uuencode (classic / -m) and uuenview (-u / -x) decode to the right names, sizes,
+-- modes and data; several blocks in a mail; CRLF lines; our uu / xx / base64 output decodes with uudecode / uudeview
+-- (fixture step) and is byte-identical to GNU uuencode for one file; round trips; errors; the fuzz pass.
+-- Fixtures: tools/fixtures/uu.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Uu = require("@formats/archive/uu")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/uu")
+
+local t = T.suite("uu")
+t:eq(Uu.name, "uu", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local a, err = Uu.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ end
+ t:eq(F.detect(c.data), "uu", c.name .. ": detect")
+ table.insert(samples, c.data)
+end
+
+-- byte-identical to GNU uuencode (mode 644) for each single file
+for _, g in Fx.gnu do
+ local data = buffer.create(0)
+ for _, f in E.FILES do
+ if f.name == g.name then
+ data = f.data
+ end
+ end
+ local a = Uu.new()
+ a:add(g.name, data, { mode = 0x1A4 })
+ t:eq(buffer.tostring(a:write() :: buffer), g.uu, g.name .. ": same bytes as uuencode")
+ t:eq(buffer.tostring(a:write({ variant = "base64" }) :: buffer), g.base64, g.name .. ": same bytes as uuencode -m")
+end
+for _, o in Fx.ours do
+ t:check(o.ok, "our " .. o.variant .. " output decodes with the reference tool")
+end
+for _, v in { "uu", "xx", "base64" } do
+ local out = E.roundTrip(t, Uu, { variant = v }, "round trip " .. v)
+ if out then
+ local back = Uu.decode(Bytes.reader(out)) :: any
+ t:eq(back:list()[1].variant, v, v .. ": variant detected")
+ end
+end
+-- a single block is a stream: the api unwraps what is inside (here: a uuencoded uuencoded file)
+local inner = Uu.encode("abc", { name = "x.uu" }) :: buffer
+local outer = Uu.encode(inner, { name = "x.uu" }) :: buffer
+local v = F.load(outer) :: any
+t:check(v and v.format == "uu" and v.meta.compression == "uu" and buffer.tostring((v:read("x.uu"))) == "abc", "api unwraps a single block")
+
+-- errors
+local function code(s: string): string?
+ local _, e = Uu.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code("no blocks here\n"), Err.CORRUPT, "no begin line")
+t:eq(code("begin 644 x\n#86)C\n"), Err.TRUNCATED, "no end line")
+t:eq(code("begin 644 x\n#8~~~\n`\nend\n"), Err.CORRUPT, "bad characters")
+t:eq(select(2, Uu.encode({})) and (select(2, Uu.encode({})) :: any).code, Err.ARG, "encode a non-archive")
+t:eq((select(2, Uu.encode("x", { variant = "zz" :: any })) :: any).code, Err.ARG, "bad variant")
+
+t:fuzz("decode", function(b: buffer)
+ return Uu.decode(Bytes.reader(b))
+end, samples)
+t:done()
diff --git a/tests/archive/yenc.luau b/tests/archive/yenc.luau
new file mode 100644
index 0000000..197b78f
--- /dev/null
+++ b/tests/archive/yenc.luau
@@ -0,0 +1,53 @@
+-- archive/yenc tests: single-part files by uuenview -y (including every byte value and the critical characters), a
+-- multi-part posting in order and reversed, two files in one text; part / file CRC and size checks; an incomplete
+-- posting; our output decodes with uudeview (fixture step) and round-trips; errors; the fuzz pass.
+-- Fixtures: tools/fixtures/yenc.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Yenc = require("@formats/archive/yenc")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/yenc")
+
+local t = T.suite("yenc")
+t:eq(Yenc.name, "yenc", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local a, err = Yenc.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ t:eq(a.meta.incomplete, nil, c.name .. ": complete")
+ end
+ t:eq(F.detect(c.data), "yenc", c.name .. ": detect")
+ if #c.data < 20000 then
+ table.insert(samples, c.data)
+ end
+end
+t:check(Fx.ours.ok, "our output decodes with uudeview")
+E.roundTrip(t, Yenc, nil, "round trip")
+E.roundTrip(t, Yenc, { line = 7 }, "round trip, 7-character lines")
+
+-- only the first part of a posting: a short file flagged incomplete
+local p = Yenc.decode(Bytes.reader(buffer.fromstring(Fx.partial))) :: any
+t:check(p and p.meta.incomplete and p.meta.incomplete[1] == "big.bin" and p:list()[1].complete == false, "incomplete posting")
+
+-- errors
+local good = buffer.tostring(Yenc.encode("hello", { name = "h" }) :: buffer)
+local function code(s: string): string?
+ local _, e = Yenc.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code((string.gsub(good, "crc32=%x+", "crc32=00000000"))), Err.CHECKSUM, "bad crc32")
+t:eq(code((string.gsub(good, "=yend size=5", "=yend size=6"))), Err.CORRUPT, "size mismatch")
+t:eq(code((string.gsub(good, "=yend[^\n]*\n", ""))), Err.TRUNCATED, "no =yend")
+t:eq(code("nothing\n"), Err.CORRUPT, "no =ybegin")
+t:eq(code("=ybegin line=128 size=99999999999 name=x\n=yend size=99999999999\n"), Err.LIMIT, "huge size")
+t:eq((select(2, Yenc.encode("x", { line = 1 })) :: any).code, Err.ARG, "bad line length")
+
+t:fuzz("decode", function(b: buffer)
+ return Yenc.decode(Bytes.reader(b))
+end, samples)
+t:done()
diff --git a/tests/archive/z.luau b/tests/archive/z.luau
new file mode 100644
index 0000000..dd24a07
--- /dev/null
+++ b/tests/archive/z.luau
@@ -0,0 +1,70 @@
+-- archive/z tests: .Z files from ncompress load as single-stream archives (entry names from the file name, .taz -> .tar),
+-- a .tar.Z unwraps to the tar through the api, writing gives ncompress's bytes (a buffer, a one-entry Archive) and a
+-- tar inside for several entries, conversions, errors, the fuzz pass. Fixtures: tools/fixtures/z.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Z = require("@formats/archive/z")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/z")
+
+local t = T.suite("z")
+t:eq(Z.name, "z", "name")
+
+local text = Fx.cases[3]
+do
+ local a, err = Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "notes.txt.Z" })
+ t:check(a, "decode: " .. tostring(err))
+ t:check(a.meta.stream, "single stream")
+ t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
+ t:eq(a:list()[1].method, "lzw", "method")
+ t:eq(buffer.tostring(a:read("notes.txt")), text.input, "data")
+ t:eq(a.meta.source.maxBits, 16, "maxBits")
+ t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z))):list()[1].name, "data", "no name: data")
+ t:eq(F.detect(text.z), "z", "F.detect")
+ t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "x.taz" }):list()[1].name, "x.tar", ".taz -> .tar")
+ t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "x.tZ" }):list()[1].name, "x.tar", ".tZ -> .tar")
+end
+
+-- the api: a .tar.Z is the tar inside
+do
+ local a, err = F.load(Fx.tarZ, { name = "src.tar.Z" })
+ t:check(a, "tar.Z: " .. tostring(err))
+ t:eq(a.format, "tar", "tar.Z unwraps")
+ t:eq(a.meta.compression, "z", "meta.compression")
+ t:eq(#a:list(), #Fx.tarNames, "tar entries")
+ local outer = F.load(Fx.tarZ, { name = "src.tar.Z", unwrap = false })
+ t:eq(outer:list()[1].name, "src.tar", "unwrap = false")
+end
+
+-- writing
+do
+ local out = assert(F.save(text.input, nil, { format = "z" }))
+ t:check(buffer.tostring(out) == text.z, "a string: ncompress's bytes")
+ local one = Z.new(text.input, "t.txt")
+ t:check(buffer.tostring(assert(one:write())) == text.z, "a one-entry archive: ncompress's bytes")
+ local tar = F.format("tar").new()
+ tar:add("a.txt", "alpha")
+ tar:add("b.txt", "beta")
+ local tz = assert(F.save(tar, nil, { format = "z" }))
+ local back = F.load(tz)
+ t:eq(back.format, "tar", "several entries: a tar inside")
+ t:eq(buffer.tostring(back:read("b.txt")), "beta", "tar inside: data")
+ local b10 = assert(Z.encode(Fx.cases[6].input, { maxBits = Fx.cases[6].bits }))
+ t:check(buffer.tostring(b10) == Fx.cases[6].z, "maxBits option")
+end
+
+-- errors
+do
+ local _, e1 = Z.decode(Bytes.reader(buffer.fromstring("\31\157")))
+ t:check(e1 and e1.code == Err.TRUNCATED, "short")
+ local _, e2 = Z.encode({ kind = "image" })
+ t:check(e2 and e2.code == Err.ARG, "encode a non-archive")
+ t:eq(Z.sniff(Bytes.reader(buffer.fromstring("\31\139\8"))), 0, "gzip is not .Z")
+end
+
+t:fuzz("decode", function(b: buffer)
+ return Z.decode(Bytes.reader(b), { maxBytes = 2 ^ 22 })
+end, { text.z, Fx.tarZ }, { mutations = 40, keepHeader = 3 })
+
+t:done()
diff --git a/tests/archive/zoo.luau b/tests/archive/zoo.luau
new file mode 100644
index 0000000..716c44e
--- /dev/null
+++ b/tests/archive/zoo.luau
@@ -0,0 +1,58 @@
+-- archive/zoo tests: zoo archives assembled by tools/fixtures/zoo.py (type 1 / type 2 entries, long and directory
+-- names, a deleted entry, methods stored / LZW / lzh, an LZW stream with table resets) give the files The Unarchiver
+-- extracts (names, sizes, data CRCs); CRC errors; the fuzz pass. Fixtures: tools/fixtures/zoo.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Zoo = require("@formats/archive/zoo")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local E = require("@tests/archive/_entries")
+local Fx = require("@tests/gen/zoo")
+
+local t = T.suite("zoo")
+t:eq(Zoo.name, "zoo", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local a, err = Zoo.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(a, c.name .. ": " .. tostring(err))
+ if a then
+ E.check(t, a, c.entries, c.name)
+ t:eq(a._byName["gone.txt"], nil, c.name .. ": deleted entry skipped")
+ end
+ t:eq(F.detect(c.data), "zoo", c.name .. ": detect")
+ if #c.data < 60000 then
+ table.insert(samples, c.data)
+ end
+end
+
+local data = Fx.cases[2].data -- lzw
+local function code(s: string): string?
+ local _, e = Zoo.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code(string.sub(data, 1, 20)), Err.TRUNCATED, "short header")
+t:eq(code(string.rep("\0", 100)), Err.CORRUPT, "no tag")
+t:eq(code(string.sub(data, 1, 200)), Err.TRUNCATED, "cut")
+local mid = #data // 2
+local bad = Zoo.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, mid - 1) .. string.char(bit32.bxor(string.byte(data, mid), 4)) .. string.sub(data, mid + 1)))) :: any
+local failed = 0
+for _, e in bad:list() do
+ local b, err = bad:read(e.name)
+ if not b then
+ failed += 1
+ t:check(err.code == Err.CHECKSUM or err.code == Err.CORRUPT or err.code == Err.TRUNCATED, "flipped data: " .. tostring(err))
+ end
+end
+t:eq(failed, 1, "one entry fails after a flipped data byte")
+
+t:fuzz("decode", function(b: buffer)
+ local r = Zoo.decode(Bytes.reader(b))
+ if r then
+ for _, e in r:list() do
+ r:read(e.name)
+ end
+ end
+ return r
+end, samples, { mutations = 6 })
+t:done()
diff --git a/tests/codecs/bitmap.luau b/tests/codecs/bitmap.luau
new file mode 100644
index 0000000..b4d8b0a
--- /dev/null
+++ b/tests/codecs/bitmap.luau
@@ -0,0 +1,73 @@
+-- codecs/font/Bitmap tests: 1-bit row pack / unpack round trips (MSB- and LSB-first, padded strides), the Font over a
+-- strike (glyphIndex / advance / rasterize / default glyph), Bitmap.strike of a bitmap font and of the first outline
+-- font from tools/fixtures/fonts.py (thresholded rasterization), and argument errors.
+local T = require("@tests/T")
+local Bitmap = require("@formats/codecs/font/Bitmap")
+local Ttf = require("@formats/font/ttf")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/fonts")
+
+local t = T.suite("bitmap")
+
+local rand = T.rng(3)
+for k = 1, 30 do
+ local w, h = rand(40), rand(20)
+ local px = buffer.create(w * h)
+ for i = 0, w * h - 1 do
+ if rand(2) == 1 then
+ buffer.writeu8(px, i, 255)
+ end
+ end
+ local stride = math.ceil(w / 8) + (k % 3)
+ local lsb = k % 2 == 0
+ local packed = Bitmap.pack(px, w, h, stride, lsb)
+ t:eq(buffer.len(packed), stride * h, "pack size " .. k)
+ t:eq(buffer.tostring(Bitmap.unpack(packed, 0, w, h, stride, lsb)), buffer.tostring(px), "round trip " .. k)
+end
+-- 0x81 = left and right pixel on (MSB first)
+t:eq(buffer.tostring(Bitmap.unpack(T.bytes({ 0x81 }), 0, 8, 1, 1)), "\255\0\0\0\0\0\0\255", "msb order")
+t:eq(buffer.tostring(Bitmap.unpack(T.bytes({ 0x01 }), 0, 2, 1, 1, true)), "\255\0", "lsb order")
+t:eq(buffer.tostring(Bitmap.unpack(T.bytes({ 0xFF }), 0, 8, 2, 1)), string.rep("\255", 8) .. string.rep("\0", 8), "past the end reads 0")
+
+local A = { codepoint = 65, width = 2, height = 2, left = 1, top = 7, advance = 4, pixels = T.bytes({ 255, 0, 0, 255 }) }
+local strike = { size = 8, ascent = 7, descent = 1, glyphs = { { width = 0, height = 0, left = 0, top = 0, advance = 3, pixels = buffer.create(0) }, A }, default = 0 }
+local font = Bitmap.font(strike, { family = "Test" })
+t:eq(font.kind, "font", "kind")
+t:eq(font.unitsPerEm, 8, "unitsPerEm")
+t:eq(font.descent, -1, "descent")
+t:eq(font:glyphIndex(65), 1, "glyphIndex")
+t:eq(font:glyphIndex(66), 0, "default glyph")
+t:eq(font:advance(1), 4, "advance")
+t:eq(font:outline(1), nil, "no outline")
+local img = font:rasterize(1, 16)
+t:check(img and img.format == "alpha8" and img.width == 2 and buffer.tostring(img.pixels) == "\255\0\0\255", "rasterize")
+t:eq(img and img.meta.top, 7, "rasterize top")
+t:eq(img and img.meta.scale, 2, "rasterize scale")
+t:eq(font:rasterize(9, 8), nil, "rasterize out of range")
+t:eq(Bitmap.strike(font), strike, "strike of a bitmap font")
+
+local s1, e1 = Bitmap.strike({})
+t:check(s1 == nil and e1 and e1.code == Err.ARG, "strike of a non-font")
+if Fx.fonts[1] then
+ local ttf = Ttf.decode(Bytes.reader(buffer.fromstring(Fx.fonts[1].data)))
+ local s, err = Bitmap.strike(ttf, { px = 16, chars = "AB" })
+ t:check(s, "strike of " .. Fx.fonts[1].name .. ": " .. tostring(err))
+ if s then
+ t:eq(#s.glyphs, 3, "strike glyphs")
+ local g = s.glyphs[2]
+ t:eq(g.codepoint, 65, "strike codepoint")
+ t:check(g.width > 4 and g.height > 6 and g.top > 6 and g.advance > 4, "strike A metrics")
+ local on = 0
+ for i = 0, buffer.len(g.pixels) - 1 do
+ local v = buffer.readu8(g.pixels, i)
+ t:check(v == 0 or v == 255, "binary pixels")
+ if v == 255 then
+ on += 1
+ end
+ end
+ t:check(on > 10, "A has ink")
+ end
+ t:check(select(2, Bitmap.strike(ttf, { px = 0 })) ~= nil, "px 0 refused")
+end
+t:done()
diff --git a/tests/codecs/unixcompress.luau b/tests/codecs/unixcompress.luau
new file mode 100644
index 0000000..55749a3
--- /dev/null
+++ b/tests/codecs/unixcompress.luau
@@ -0,0 +1,75 @@
+-- codecs/compress/UnixCompress tests: ncompress 5.0 files (widths 10..16, block mode, CLEAR codes after the ratio
+-- check, empty / one-byte / random inputs) decode to their inputs; compress() gives ncompress's bytes for the same input
+-- and width; non-block-mode streams; errors; the fuzz pass. Fixtures: tools/fixtures/z.py.
+local T = require("@tests/T")
+local UnixCompress = require("@formats/codecs/compress/UnixCompress")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/z")
+
+local t = T.suite("unixcompress")
+
+for _, c in Fx.cases do
+ local out, err = UnixCompress.decompress(c.z)
+ t:check(out, c.name .. ": decompress: " .. tostring(err))
+ t:eq(buffer.len(out), #c.input, c.name .. ": size")
+ t:eq(Crc32.of(out), Crc32.of(buffer.fromstring(c.input)), c.name .. ": data")
+ local z, zerr = UnixCompress.compress(c.input, nil, nil, { maxBits = c.bits })
+ t:check(z, c.name .. ": compress: " .. tostring(zerr))
+ t:eq(buffer.len(z), #c.z, c.name .. ": compressed size = ncompress")
+ t:check(buffer.tostring(z) == c.z, c.name .. ": bytes identical to ncompress -b " .. c.bits)
+ t:note("%-12s %7d -> %7d bytes (-b %d)", c.name, #c.input, #c.z, c.bits)
+end
+
+-- 9-bit codes, LSB first, after a .Z header with the given flags byte
+local function pack(flags: number, codes: { number }): buffer
+ local acc, nb, bytes = 0, 0, { 0x1F, 0x9D, flags }
+ for _, c in codes do
+ acc += c * 2 ^ nb
+ nb += 9
+ while nb >= 8 do
+ table.insert(bytes, acc % 256)
+ acc = acc // 256
+ nb -= 8
+ end
+ end
+ if nb > 0 then
+ table.insert(bytes, acc)
+ end
+ return T.bytes(bytes)
+end
+
+-- a non-block-mode stream (no CLEAR code; 256 is the first table entry): "ABABABA"
+do
+ local out = UnixCompress.decompress(pack(0x10, { 65, 66, 256, 258 }))
+ t:eq(out and buffer.tostring(out), "ABABABA", "non-block mode")
+end
+
+-- errors
+do
+ local _, e1 = UnixCompress.decompress("\31\157")
+ t:check(e1 and e1.code == Err.TRUNCATED, "short header")
+ local _, e2 = UnixCompress.decompress("\31\158\144")
+ t:check(e2 and e2.code == Err.CORRUPT, "bad magic")
+ local _, e3 = UnixCompress.decompress("\31\157\145")
+ t:check(e3 and e3.code == Err.UNSUPPORTED, "17-bit codes")
+ local _, e4 = UnixCompress.decompress(pack(0x90, { 65, 400 }))
+ t:check(e4 and e4.code == Err.CORRUPT, "a code past the table: " .. tostring(e4))
+ local _, e5 = UnixCompress.decompress(Fx.cases[5].z, nil, nil, { maxBytes = 1000 })
+ t:check(e5 and e5.code == Err.LIMIT, "maxBytes")
+ local _, e6 = UnixCompress.compress("x", nil, nil, { maxBits = 17 })
+ t:check(e6 and e6.code == Err.ARG, "maxBits 17")
+end
+
+local samples = {}
+for _, c in Fx.cases do
+ if #c.z < 4000 and #c.z > 3 then
+ table.insert(samples, c.z)
+ end
+end
+table.insert(samples, string.sub(Fx.cases[#Fx.cases].z, 1, 3000))
+t:fuzz("decompress", function(b: buffer)
+ return UnixCompress.decompress(b, nil, nil, { maxBytes = 2 ^ 22 })
+end, samples, { mutations = 40, keepHeader = 3 })
+
+t:done()
diff --git a/tests/font/_bitmap.luau b/tests/font/_bitmap.luau
new file mode 100644
index 0000000..aa7d3e5
--- /dev/null
+++ b/tests/font/_bitmap.luau
@@ -0,0 +1,32 @@
+-- shared by the bitmap font tests: compare(t, font, ref, label) checks every glyph FreeType rendered (code point,
+-- bitmap size, left / top offsets, advance, pixels) against font:rasterize(font:glyphIndex(cp)) (by the font's own
+-- codes when FreeType had no Unicode charmap).
+local B = {}
+
+function B.compare(t: any, font: any, ref: any, label: string)
+ for _, g in ref.glyphs do
+ local gi = font:glyphIndex(g.cp)
+ if ref.unicode == false and font.meta.encodings then
+ -- FreeType used the font's own codes (not Unicode): find the glyph by its code
+ for k, enc in font.meta.encodings do
+ if enc == g.cp then
+ gi = k - 1
+ break
+ end
+ end
+ end
+ local img = font:rasterize(gi, 16)
+ local tag = string.format("%s U+%04X", label, g.cp)
+ t:check(img, tag .. ": rasterize")
+ if img then
+ t:eq(img.width, g.width, tag .. ": width")
+ t:eq(img.height, g.height, tag .. ": height")
+ t:eq(img.meta.left, g.left, tag .. ": left")
+ t:eq(img.meta.top, g.top, tag .. ": top")
+ t:eq(img.meta.advance, g.advance, tag .. ": advance")
+ t:check(buffer.tostring(img.pixels) == g.pixels, tag .. ": pixels")
+ end
+ end
+end
+
+return B
diff --git a/tests/font/bdf.luau b/tests/font/bdf.luau
new file mode 100644
index 0000000..a728224
--- /dev/null
+++ b/tests/font/bdf.luau
@@ -0,0 +1,61 @@
+-- font/bdf tests: Spleen BDF fonts against FreeType's renders (bitmaps, offsets, advances), properties and metrics; our
+-- BDF output (of BDF, PCF and outline fonts) read back by FreeType identically (fixture step) and round-tripping; an
+-- outline font written as BDF; errors; the fuzz pass. Fixtures: tools/fixtures/bitmapfonts.py, tools/fixtures/fonts.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Bdf = require("@formats/font/bdf")
+local Ttf = require("@formats/font/ttf")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local B = require("@tests/font/_bitmap")
+local Fx = require("@tests/gen/bitmapfonts")
+local Fonts = require("@tests/gen/fonts")
+
+local t = T.suite("bdf")
+t:eq(Bdf.name, "bdf", "name")
+
+local samples = {}
+for _, c in Fx.fonts do
+ t:check(c.ours.ok, c.name .. ": FreeType reads our BDF of it the same: " .. c.ours.detail)
+ if c.format == "bdf" then
+ local font, err = Bdf.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(font, c.name .. ": " .. tostring(err))
+ if font then
+ B.compare(t, font, c.ref, c.name)
+ t:eq(font.ascent, c.ref.ascent, c.name .. ": ascent")
+ t:eq(-font.descent, c.ref.descent, c.name .. ": descent")
+ t:eq(font.info.family, "Spleen", c.name .. ": family")
+ -- round trip through our writer
+ local out = Bdf.encode(font) :: buffer
+ local back = Bdf.decode(Bytes.reader(out)) :: any
+ t:check(back and #back.bitmap.glyphs == #font.bitmap.glyphs, c.name .. ": round trip glyph count")
+ if back then
+ B.compare(t, back, c.ref, c.name .. " (round trip)")
+ end
+ end
+ t:eq(F.detect(c.data), "bdf", c.name .. ": detect")
+ table.insert(samples, string.sub(c.data, 1, 6000) .. "\nENDFONT\n")
+ end
+end
+
+-- an outline font as BDF
+local ttf = Ttf.decode(Bytes.reader(buffer.fromstring(Fonts.fonts[1].data)))
+local out, err = Bdf.encode(ttf, { px = 14, chars = "Hello" })
+t:check(out, "ttf -> bdf: " .. tostring(err))
+local back = Bdf.decode(Bytes.reader(out :: buffer)) :: any
+t:check(back and back:glyphIndex(72) > 0 and back.unitsPerEm == 14 and back:rasterize(back:glyphIndex(72), 14).width > 3, "ttf -> bdf glyphs")
+
+-- errors
+local function code(s: string): string?
+ local _, e = Bdf.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code("hello"), Err.CORRUPT, "not BDF")
+t:eq(code("STARTFONT 2.1\nFONT x\n"), Err.TRUNCATED, "no ENDFONT")
+t:eq(code("STARTFONT 2.1\nSTARTCHAR a\nBBX 99999 2 0 0\nBITMAP\nENDCHAR\nENDFONT\n"), Err.CORRUPT, "bad BBX")
+t:eq((select(2, Bdf.encode({}))) and (select(2, Bdf.encode({})) :: any).code, Err.ARG, "encode a non-font")
+
+t:fuzz("decode", function(b: buffer)
+ return Bdf.decode(Bytes.reader(b))
+end, samples)
+t:done()
diff --git a/tests/font/eot.luau b/tests/font/eot.luau
new file mode 100644
index 0000000..b877055
--- /dev/null
+++ b/tests/font/eot.luau
@@ -0,0 +1,55 @@
+-- font/eot tests: EOT 1.0 / 2.1 / 2.1 XOR / 2.2 files around DejaVu Sans Mono (TrueType) and Source Sans 3 (CFF) give
+-- the header fields and the inner font (units per em, glyph count, cmap glyph ids and advances from fontTools); our
+-- EOT writer round-trips (same font bytes, header from the font's tables), XOR too; MTX is unsupported; errors; the fuzz
+-- pass. Fixtures: tools/fixtures/eot.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Eot = require("@formats/font/eot")
+local Bytes = require("@formats/core/Bytes")
+local Crc32 = require("@formats/core/Crc32")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/eot")
+
+local t = T.suite("eot")
+t:eq(Eot.name, "eot", "name")
+
+local samples = {}
+for _, c in Fx.cases do
+ local font, err = Eot.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(font, c.name .. ": " .. tostring(err))
+ if font then
+ local h = font.meta.eot
+ t:eq(h.version, c.version, c.name .. ": version")
+ t:eq(h.familyName, c.family, c.name .. ": family")
+ t:eq(h.styleName, c.style, c.name .. ": style")
+ t:eq(h.fullName, c.fullName, c.name .. ": full name")
+ t:eq(h.weight, c.weight, c.name .. ": weight")
+ t:eq(h.fsType, c.fsType, c.name .. ": fsType")
+ t:eq(font.unitsPerEm, c.upem, c.name .. ": units per em")
+ t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": glyph count")
+ t:eq(Crc32.of(font.meta.fontData), c.fontCrc, c.name .. ": font data")
+ for _, g in c.glyphs do
+ t:eq(font:glyphIndex(g.cp), g.gid, c.name .. ": cmap " .. g.cp)
+ t:eq(font:advance(g.gid), g.advance, c.name .. ": advance " .. g.cp)
+ end
+ -- our writer
+ for _, xor in { false, true } do
+ local out, werr = Eot.encode(font, { xor = xor })
+ t:check(out, c.name .. ": encode: " .. tostring(werr))
+ local back = out and Eot.decode(Bytes.reader(out)) :: any
+ t:check(back and Crc32.of(back.meta.fontData) == c.fontCrc and back.meta.eot.weight == c.weight and back.meta.eot.familyName == font.info.family, c.name .. ": round trip (xor " .. tostring(xor) .. ")")
+ end
+ end
+ t:eq(F.detect(c.data), "eot", c.name .. ": detect")
+ table.insert(samples, string.sub(c.data, 1, 3000))
+end
+local _, merr = Eot.decode(Bytes.reader(buffer.fromstring(Fx.mtx)))
+t:eq(merr and merr.code, Err.UNSUPPORTED, "MTX compressed")
+local _, serr = Eot.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.cases[1].data, 1, 50))))
+t:eq(serr and serr.code, Err.TRUNCATED, "cut header")
+t:eq((select(2, Eot.encode({}))) and (select(2, Eot.encode({})) :: any).code, Err.ARG, "encode a non-font")
+
+t:fuzz("decode", function(b: buffer)
+ return Eot.decode(Bytes.reader(b))
+end, samples, { mutations = 20 })
+t:done()
diff --git a/tests/font/fon.luau b/tests/font/fon.luau
new file mode 100644
index 0000000..9489ebe
--- /dev/null
+++ b/tests/font/fon.luau
@@ -0,0 +1,50 @@
+-- font/fon tests: Windows .fnt and NE .fon fonts (one and two strikes) made by FontForge from the Spleen BDFs against
+-- FreeType's renders (ASCII: FreeType maps FNT byte codes), strikes and size selection; errors; the fuzz pass.
+-- Fixtures: tools/fixtures/bitmapfonts.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Fon = require("@formats/font/fon")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local B = require("@tests/font/_bitmap")
+local Fx = require("@tests/gen/bitmapfonts")
+
+local t = T.suite("fon")
+t:eq(Fon.name, "fon", "name")
+
+local samples = {}
+local n = 0
+for _, c in Fx.fonts do
+ if c.format == "fon" then
+ n += 1
+ local font, err = Fon.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(font, c.name .. ": " .. tostring(err))
+ if font then
+ B.compare(t, font, c.ref, c.name)
+ t:eq(font.ascent, c.ref.ascent, c.name .. ": ascent")
+ if string.find(c.name, "two", 1, true) then
+ t:eq(#font.meta.strikes, 2, c.name .. ": two strikes")
+ local big = Fon.decode(Bytes.reader(buffer.fromstring(c.data)), { size = 24 }) :: any
+ t:eq(big.unitsPerEm, 24, c.name .. ": size selection")
+ end
+ end
+ t:eq(F.detect(c.data), "fon", c.name .. ": detect")
+ table.insert(samples, c.data)
+ end
+end
+t:check(n >= 3, "has cases")
+
+local function code(s: string): string?
+ local _, e = Fon.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code("\0\2\0\0"), Err.TRUNCATED, "short fnt")
+local vec = string.rep("\0", 200)
+vec = "\0\2" .. string.sub(vec, 3, 66) .. "\1\0" .. string.sub(vec, 69)
+t:eq(code(vec), Err.UNSUPPORTED, "vector font")
+t:eq(code("MZ" .. string.rep("\0", 100)), Err.CORRUPT, "MZ without NE")
+
+t:fuzz("decode", function(b: buffer)
+ return Fon.decode(Bytes.reader(b))
+end, samples, { mutations = 30 })
+t:done()
diff --git a/tests/font/hershey.luau b/tests/font/hershey.luau
new file mode 100644
index 0000000..dde69d9
--- /dev/null
+++ b/tests/font/hershey.luau
@@ -0,0 +1,62 @@
+-- font/hershey tests: JHF text with Roman-style glyphs and random stroke glyphs (records wrapped over 72-column lines)
+-- against an independent parser (ids, advances, every moveTo / lineTo), ASCII and id mappings, stroked rasterization;
+-- errors; the fuzz pass. Fixtures: tools/fixtures/hershey.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Hershey = require("@formats/font/hershey")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/hershey")
+
+local t = T.suite("hershey")
+t:eq(Hershey.name, "hershey", "name")
+
+local font, err = Hershey.decode(Bytes.reader(buffer.fromstring(Fx.text)))
+t:check(font, "decode: " .. tostring(err))
+if font then
+ t:eq(font.numGlyphs, #Fx.glyphs, "glyph count")
+ for k, g in Fx.glyphs do
+ local gi = k - 1
+ t:eq(font.meta.ids[k], g.id, "id " .. k)
+ t:eq(font:advance(gi), g.advance, "advance " .. g.id)
+ local cmds = font:outline(gi) :: any
+ t:eq(#cmds, #g.cmds, "commands " .. g.id)
+ local same = true
+ for i, c in g.cmds do
+ local m = cmds[i]
+ if not m or m.op ~= c.op or m[1] ~= c.x or m[2] ~= c.y then
+ same = false
+ end
+ end
+ t:check(same, "outline " .. g.id)
+ end
+ t:eq(font:glyphIndex(33), 1, "ascii mapping: the second glyph is \"!\"")
+ local img = font:rasterize(1, 64) :: any
+ t:check(img and img.format == "alpha8" and img.width > 20 and img.height > 30 and img.meta.top > 30, "rasterize A")
+ local ink = 0
+ for i = 0, buffer.len(img.pixels) - 1 do
+ ink += buffer.readu8(img.pixels, i)
+ end
+ t:check(ink > 255 * 50, "A has ink")
+ t:eq(font:rasterize(0, 32).width, 0, "space is empty")
+end
+local byId = Hershey.decode(Bytes.reader(buffer.fromstring(Fx.text)), { map = "id" }) :: any
+t:eq(byId:glyphIndex(508), 2, "id mapping")
+t:eq(F.detect(Fx.text), "hershey", "detect")
+
+local function code(s: string): string?
+ local _, e = Hershey.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code(" 501 9MWRFJ[ RRFZ["), Err.TRUNCATED, "short record")
+t:eq(code("hello world\n"), Err.CORRUPT, "not jhf")
+t:eq(code("\n\n"), Err.CORRUPT, "empty")
+
+t:fuzz("decode", function(b: buffer)
+ local f = Hershey.decode(Bytes.reader(b))
+ if f then
+ f:rasterize(1, 24)
+ end
+ return f
+end, { string.sub(Fx.text, 1, 1500) })
+t:done()
diff --git a/tests/font/pcf.luau b/tests/font/pcf.luau
new file mode 100644
index 0000000..5cb3143
--- /dev/null
+++ b/tests/font/pcf.luau
@@ -0,0 +1,62 @@
+-- font/pcf tests: PCF fonts compiled by bdftopcf with every glyph pad / scan unit / bit and byte order and -t, Tamzen
+-- PCFs and X11 misc-misc .pcf.gz fonts against FreeType's renders (bitmaps, offsets, advances) and metrics; charsets
+-- other than Unicode / Latin-1 stay unmapped; .pcf.gz through the api; errors; the fuzz pass.
+-- Fixtures: tools/fixtures/bitmapfonts.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Pcf = require("@formats/font/pcf")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local B = require("@tests/font/_bitmap")
+local Fx = require("@tests/gen/bitmapfonts")
+
+local t = T.suite("pcf")
+t:eq(Pcf.name, "pcf", "name")
+
+local samples = {}
+for _, c in Fx.fonts do
+ if c.format == "pcf" then
+ local data = buffer.fromstring(c.data)
+ if c.gz then
+ data = Deflate.gunzip(data, 0, buffer.len(data)) :: buffer
+ end
+ local font, err = Pcf.decode(Bytes.reader(data))
+ t:check(font, c.name .. ": " .. tostring(err))
+ if font then
+ B.compare(t, font, c.ref, c.name)
+ t:eq(font.ascent, c.ref.ascent, c.name .. ": ascent")
+ t:eq(-font.descent, c.ref.descent, c.name .. ": descent")
+ t:eq(#font.bitmap.glyphs, c.ref.numGlyphs - 1, c.name .. ": glyph count (FreeType counts one more)")
+ if string.find(c.name, "ISO8859-5", 1, true) then
+ t:check(font.meta.unicode == false and font:glyphIndex(65) == (font.bitmap.default or 0), c.name .. ": not mapped to Unicode")
+ end
+ end
+ t:eq(F.detect(data), "pcf", c.name .. ": detect")
+ if #samples < 3 then
+ table.insert(samples, data)
+ end
+ end
+end
+
+-- a .pcf.gz through the api: the gzip unwraps to the font (meta.compression = "gzip")
+for _, c in Fx.fonts do
+ if c.gz then
+ local v = F.load(c.data, { name = c.name }) :: any
+ t:check(v and v.kind == "font" and v.meta.compression == "gzip" and #v.bitmap.glyphs > 100, c.name .. ": F.load unwraps the gzip")
+ end
+end
+
+-- errors
+local function code(s: string): string?
+ local _, e = Pcf.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code("\1fc"), Err.TRUNCATED, "short")
+t:eq(code("xxxx\0\0\0\0"), Err.CORRUPT, "bad magic")
+t:eq(code("\1fcp\0\0\0\0"), Err.CORRUPT, "no tables")
+
+t:fuzz("decode", function(b: buffer)
+ return Pcf.decode(Bytes.reader(b))
+end, samples, { mutations = 40 })
+t:done()
diff --git a/tests/font/psf.luau b/tests/font/psf.luau
new file mode 100644
index 0000000..2483c66
--- /dev/null
+++ b/tests/font/psf.luau
@@ -0,0 +1,82 @@
+-- font/psf tests: kbd / Spleen / Tamzen / Terminus / Cozette console fonts (PSF 1 and 2, with and without Unicode
+-- tables) against an independent parser (sizes, glyph bitmaps) and kbd's psfgettable (every code point -> glyph
+-- pair); our PSF 2 / PSF 1 output read back by psfgettable and the parser (fixture step) and round-tripping; an
+-- outline font written as PSF; .psfu.gz through the api; errors; the fuzz pass. Fixtures: tools/fixtures/psf.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Psf = require("@formats/font/psf")
+local Ttf = require("@formats/font/ttf")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Deflate = require("@formats/codecs/compress/Deflate")
+local Fx = require("@tests/gen/psf")
+local Fonts = require("@tests/gen/fonts")
+
+local t = T.suite("psf")
+t:eq(Psf.name, "psf", "name")
+
+local samples = {}
+for _, c in Fx.fonts do
+ local data = buffer.fromstring(c.data)
+ if c.gz then
+ data = Deflate.gunzip(data, 0, buffer.len(data)) :: buffer
+ end
+ local font, err = Psf.decode(Bytes.reader(data))
+ t:check(font, c.name .. ": " .. tostring(err))
+ if font then
+ t:eq(font.meta.source.version, c.version, c.name .. ": version")
+ t:eq(#font.bitmap.glyphs, c.count, c.name .. ": glyph count")
+ t:eq(font.meta.width, c.width, c.name .. ": width")
+ t:eq(font.meta.height, c.height, c.name .. ": height")
+ for _, g in c.glyphs do
+ local img = font:rasterize(g.index, c.height)
+ t:check(img and buffer.tostring(img.pixels) == g.pixels, c.name .. ": glyph " .. g.index)
+ end
+ local mismatched = 0
+ for _, p in c.table do
+ local gi = font:glyphIndex(p.cp)
+ -- a code point on several glyphs maps to the first: the glyph images are equal or the pair is an alias
+ if gi ~= p.glyph and font.meta.unicodeTable[gi + 1] == nil then
+ mismatched += 1
+ end
+ end
+ t:eq(mismatched, 0, c.name .. ": Unicode table (" .. #c.table .. " pairs)")
+ t:check(c.ours2.ok, c.name .. ": our PSF 2 reads back: " .. c.ours2.detail)
+ if c.ours1 then
+ t:check(c.ours1.ok, c.name .. ": our PSF 1 reads back: " .. c.ours1.detail)
+ end
+ local back = Psf.decode(Bytes.reader(Psf.encode(font) :: buffer)) :: any
+ t:check(back and #back.bitmap.glyphs == c.count and back:glyphIndex(65) == font:glyphIndex(65), c.name .. ": round trip")
+ end
+ t:eq(F.detect(data), "psf", c.name .. ": detect")
+ if c.gz then
+ local v = F.load(c.data, { name = c.name }) :: any
+ t:check(v and v.kind == "font" and v.meta.compression == "gzip", c.name .. ": F.load unwraps the gzip")
+ end
+ if #samples < 3 then
+ table.insert(samples, data)
+ end
+end
+
+-- an outline font as PSF 2
+local ttf = Ttf.decode(Bytes.reader(buffer.fromstring(Fonts.fonts[1].data)))
+local out, err = Psf.encode(ttf, { px = 16, chars = "AB" })
+t:check(out, "ttf -> psf: " .. tostring(err))
+local back = Psf.decode(Bytes.reader(out :: buffer)) :: any
+t:check(back and back:glyphIndex(66) == 2 and back.meta.source.version == 2, "ttf -> psf glyphs")
+
+-- errors
+local function code(s: string): string?
+ local _, e = Psf.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code("\54\4\0\16"), Err.TRUNCATED, "psf1 without glyphs")
+t:eq(code("\114\181\74\134"), Err.TRUNCATED, "psf2 header cut")
+t:eq(code("\114\181\74\134\0\0\0\0\32\0\0\0\0\0\0\0\1\0\0\0\99\0\0\0\8\0\0\0\8\0\0\0"), Err.CORRUPT, "bad charsize")
+t:eq(code("hello"), Err.CORRUPT, "not psf")
+t:eq((select(2, Psf.encode(back, { version = 3 })) :: any).code, Err.ARG, "bad version")
+
+t:fuzz("decode", function(b: buffer)
+ return Psf.decode(Bytes.reader(b))
+end, samples, { mutations = 30 })
+t:done()
diff --git a/tests/font/type1.luau b/tests/font/type1.luau
new file mode 100644
index 0000000..b3419fd
--- /dev/null
+++ b/tests/font/type1.luau
@@ -0,0 +1,141 @@
+-- font/type1 tests (and codecs/font/GlyphNames): Latin Modern PFB fonts and a PFA (t1ascii) against fontTools
+-- (outline control boxes, areas, advances of sample glyphs including flex, hint replacement, seac accents and
+-- ligatures; code points from glyph names) and FreeType's unhinted renders (PSNR); errors; the fuzz pass.
+-- Fixtures: tools/fixtures/type1.py.
+local T = require("@tests/T")
+local F = require("@formats")
+local Type1 = require("@formats/font/type1")
+local GlyphNames = require("@formats/codecs/font/GlyphNames")
+local Raster = require("@formats/codecs/image/Raster")
+local Bytes = require("@formats/core/Bytes")
+local Err = require("@formats/core/Err")
+local Fx = require("@tests/gen/type1")
+
+local t = T.suite("type1")
+t:eq(Type1.name, "type1", "name")
+t:eq(GlyphNames.unicode("Aacute"), 0xC1, "agl")
+t:eq(GlyphNames.unicode("uni20AC"), 0x20AC, "uniXXXX")
+t:eq(GlyphNames.unicode("u1F600"), 0x1F600, "uXXXXX")
+t:eq(GlyphNames.unicode("a.sc"), 0x61, "suffix")
+t:eq(GlyphNames.unicode("f_f_i"), 0x66, "ligature name")
+t:eq(GlyphNames.unicode("nosuchname"), nil, "unknown")
+t:eq(GlyphNames.STANDARD[65], "A", "StandardEncoding")
+
+-- shoelace area of the flattened outline (font units)
+local function area(cmds: any): number
+ local polys = Raster.flatten(cmds, nil, 0.02)
+ local a = 0
+ for _, p in polys do
+ local n = #p
+ local x0, y0 = p[n - 1], p[n]
+ for i = 1, n - 1, 2 do
+ a += x0 * p[i + 1] - p[i] * y0
+ x0, y0 = p[i], p[i + 1]
+ end
+ end
+ return a / 2
+end
+
+local function psnr(img: any, r: any): (number, number)
+ -- union of both bitmaps, aligned on the pen position
+ local ax0, ay0 = img.meta.left, -img.meta.top
+ local bx0, by0 = r.left, -r.top
+ local x0, y0 = math.min(ax0, bx0), math.min(ay0, by0)
+ local x1, y1 = math.max(ax0 + img.width, bx0 + r.width), math.max(ay0 + img.height, by0 + r.height)
+ local se, n, ink = 0, 0, 0
+ for y = y0, y1 - 1 do
+ for x = x0, x1 - 1 do
+ local a, b = 0, 0
+ local ix, iy = x - ax0, y - ay0
+ if ix >= 0 and iy >= 0 and ix < img.width and iy < img.height then
+ a = buffer.readu8(img.pixels, iy * img.width + ix)
+ end
+ local jx, jy = x - bx0, y - by0
+ if jx >= 0 and jy >= 0 and jx < r.width and jy < r.height then
+ b = string.byte(r.pixels, jy * r.width + jx + 1)
+ end
+ se += (a - b) * (a - b)
+ ink += b
+ n += 1
+ end
+ end
+ if n == 0 or se == 0 then
+ return 99, ink
+ end
+ return 10 * math.log10(255 * 255 / (se / n)), ink
+end
+
+
+local worst = 99
+local samples = {}
+for _, c in Fx.fonts do
+ local font, err = Type1.decode(Bytes.reader(buffer.fromstring(c.data)))
+ t:check(font, c.name .. ": " .. tostring(err))
+ if font then
+ t:eq(font.unitsPerEm, c.upem, c.name .. ": units per em")
+ t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": glyph count")
+ t:eq(font.info.family, c.family, c.name .. ": family")
+ local byName = {}
+ for k, n in font.meta.glyphNames do
+ byName[n] = k - 1
+ end
+ local maxErr = 0
+ for _, g in c.glyphs do
+ local gi = byName[g.name]
+ t:check(gi, c.name .. ": has " .. g.name)
+ if gi then
+ if g.cp then
+ t:eq(font:glyphIndex(g.cp), gi, c.name .. ": cmap " .. g.name)
+ end
+ t:eq(font:advance(gi), g.advance, c.name .. ": advance " .. g.name)
+ local cmds = font:outline(gi) :: any
+ t:check(cmds, c.name .. ": outline " .. g.name)
+ if g.bounds then
+ local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
+ for _, cmd in cmds do
+ for i = 1, #cmd, 2 do
+ x0, x1 = math.min(x0, cmd[i]), math.max(x1, cmd[i])
+ y0, y1 = math.min(y0, cmd[i + 1]), math.max(y1, cmd[i + 1])
+ end
+ end
+ local ok = math.abs(x0 - g.bounds[1]) < 0.01 and math.abs(y0 - g.bounds[2]) < 0.01 and math.abs(x1 - g.bounds[3]) < 0.01 and math.abs(y1 - g.bounds[4]) < 0.01
+ t:check(ok, string.format("%s: %s control box %s %s %s %s vs %s %s %s %s", c.name, g.name, x0, y0, x1, y1, g.bounds[1], g.bounds[2], g.bounds[3], g.bounds[4]))
+ end
+ local a = math.abs(area(cmds))
+ local want = math.abs(g.area)
+ local e = if want > 0 then math.abs(a - want) / want else a
+ maxErr = math.max(maxErr, e)
+ t:check(e < 0.002, string.format("%s: %s area %.1f vs %.1f", c.name, g.name, a, want))
+ end
+ end
+ for _, r in c.renders do
+ local img = font:rasterize(font:glyphIndex(r.cp), r.px) :: any
+ local p = psnr(img, r)
+ worst = math.min(worst, p)
+ t:check(p > 25, string.format("%s: U+%04X at %d px: PSNR %.1f dB vs FreeType", c.name, r.cp, r.px, p))
+ end
+ t:note("%-22s %3d glyphs, area err %.5f", c.name, font.numGlyphs, maxErr)
+ end
+ t:eq(F.detect(c.data), "type1", c.name .. ": detect")
+ table.insert(samples, string.sub(c.data, 1, 4000))
+end
+t:note("worst PSNR vs FreeType %.1f dB", worst)
+
+local function code(s: string): string?
+ local _, e = Type1.decode(Bytes.reader(buffer.fromstring(s)))
+ return e and e.code
+end
+t:eq(code("%!PS-AdobeFont-1.0: X\n/FontName /X def\n"), Err.CORRUPT, "no eexec")
+t:eq(code("\128\1\255\255\0\0"), Err.TRUNCATED, "cut PFB segment")
+t:eq(code("%!PS-AdobeFont-1.0\ncurrentfile eexec\n00"), Err.TRUNCATED, "short eexec")
+
+t:fuzz("decode", function(b: buffer)
+ local f = Type1.decode(Bytes.reader(b))
+ if f then
+ for g = 0, math.min(f.numGlyphs - 1, 20) do
+ f:outline(g)
+ end
+ end
+ return f
+end, samples, { mutations = 20 })
+t:done()
diff --git a/tools/bench.luau b/tools/bench.luau
index 366db73..5be2931 100644
--- a/tools/bench.luau
+++ b/tools/bench.luau
@@ -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
diff --git a/tools/fixtures/_arch2.py b/tools/fixtures/_arch2.py
new file mode 100644
index 0000000..7137e04
--- /dev/null
+++ b/tools/fixtures/_arch2.py
@@ -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)
diff --git a/tools/fixtures/_arch2_ours.luau b/tools/fixtures/_arch2_ours.luau
new file mode 100644
index 0000000..ed23662
--- /dev/null
+++ b/tools/fixtures/_arch2_ours.luau
@@ -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 []`). 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))
diff --git a/tools/fixtures/_bitmapfonts_ours.luau b/tools/fixtures/_bitmapfonts_ours.luau
new file mode 100644
index 0000000..9650d10
--- /dev/null
+++ b/tools/fixtures/_bitmapfonts_ours.luau
@@ -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/.luau:
+-- `luau _bitmapfonts_ours.luau -a [version]`): decodes each source font with its format, encodes it
+-- with (default bdf) and prints " " 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
diff --git a/tools/fixtures/_bitmapfonts_ref.py b/tools/fixtures/_bitmapfonts_ref.py
new file mode 100644
index 0000000..818c6a6
--- /dev/null
+++ b/tools/fixtures/_bitmapfonts_ref.py
@@ -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))
diff --git a/tools/fixtures/_lz4frame_encode.luau b/tools/fixtures/_lz4frame_encode.luau
new file mode 100644
index 0000000..0c17f13
--- /dev/null
+++ b/tools/fixtures/_lz4frame_encode.luau
@@ -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 " " 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
diff --git a/tools/fixtures/_lzx.py b/tools/fixtures/_lzx.py
new file mode 100644
index 0000000..8c07c87
--- /dev/null
+++ b/tools/fixtures/_lzx.py
@@ -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("= 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("= 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
diff --git a/tools/fixtures/_quantum.py b/tools/fixtures/_quantum.py
new file mode 100644
index 0000000..3f9ee2c
--- /dev/null
+++ b/tools/fixtures/_quantum.py
@@ -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
diff --git a/tools/fixtures/adf.py b/tools/fixtures/adf.py
new file mode 100644
index 0000000..7fef3d1
--- /dev/null
+++ b/tools/fixtures/adf.py
@@ -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)
diff --git a/tools/fixtures/ar.py b/tools/fixtures/ar.py
new file mode 100644
index 0000000..f5af145
--- /dev/null
+++ b/tools/fixtures/ar.py
@@ -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 \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 ",
+ "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"!\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})
diff --git a/tools/fixtures/arj.py b/tools/fixtures/arj.py
new file mode 100644
index 0000000..747861b
--- /dev/null
+++ b/tools/fixtures/arj.py
@@ -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)
diff --git a/tools/fixtures/bitmapfonts.py b/tools/fixtures/bitmapfonts.py
new file mode 100644
index 0000000..0176c4b
--- /dev/null
+++ b/tools/fixtures/bitmapfonts.py
@@ -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)
diff --git a/tools/fixtures/cab.py b/tools/fixtures/cab.py
new file mode 100644
index 0000000..2a3ae87
--- /dev/null
+++ b/tools/fixtures/cab.py
@@ -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(" [(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(" 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)
diff --git a/tools/fixtures/cpio.py b/tools/fixtures/cpio.py
new file mode 100644
index 0000000..2376125
--- /dev/null
+++ b/tools/fixtures/cpio.py
@@ -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})
diff --git a/tools/fixtures/d64.py b/tools/fixtures/d64.py
new file mode 100644
index 0000000..eefab4d
--- /dev/null
+++ b/tools/fixtures/d64.py
@@ -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)
diff --git a/tools/fixtures/docs_arch2.py b/tools/fixtures/docs_arch2.py
new file mode 100644
index 0000000..28e9b37
--- /dev/null
+++ b/tools/fixtures/docs_arch2.py
@@ -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"})
diff --git a/tools/fixtures/docs_arch_cab.py b/tools/fixtures/docs_arch_cab.py
new file mode 100644
index 0000000..79ca4b0
--- /dev/null
+++ b/tools/fixtures/docs_arch_cab.py
@@ -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"})
diff --git a/tools/fixtures/docs_arch_unix.py b/tools/fixtures/docs_arch_unix.py
new file mode 100644
index 0000000..51ddd77
--- /dev/null
+++ b/tools/fixtures/docs_arch_unix.py
@@ -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 \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"})
diff --git a/tools/fixtures/eot.py b/tools/fixtures/eot.py
new file mode 100644
index 0000000..045ef3a
--- /dev/null
+++ b/tools/fixtures/eot.py
@@ -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("= 0x00020001:
+ u = utf16("https://example.com/")
+ hdr += struct.pack("I", a, 14, at_bytes)
+ a[25] |= 0x80
+ struct.pack_into("I", b2, 6, lba + at_bytes // 2048)
+ 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("= 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("> 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)
diff --git a/tools/fixtures/psf.py b/tools/fixtures/psf.py
new file mode 100644
index 0000000..44195ae
--- /dev/null
+++ b/tools/fixtures/psf.py
@@ -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)
diff --git a/tools/fixtures/rpm.py b/tools/fixtures/rpm.py
new file mode 100644
index 0000000..2ba559b
--- /dev/null
+++ b/tools/fixtures/rpm.py
@@ -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})
diff --git a/tools/fixtures/type1.py b/tools/fixtures/type1.py
new file mode 100644
index 0000000..e231fd9
--- /dev/null
+++ b/tools/fixtures/type1.py
@@ -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})
diff --git a/tools/fixtures/uu.py b/tools/fixtures/uu.py
new file mode 100644
index 0000000..b431c45
--- /dev/null
+++ b/tools/fixtures/uu.py
@@ -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)
diff --git a/tools/fixtures/yenc.py b/tools/fixtures/yenc.py
new file mode 100644
index 0000000..5e17546
--- /dev/null
+++ b/tools/fixtures/yenc.py
@@ -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)
diff --git a/tools/fixtures/z.py b/tools/fixtures/z.py
new file mode 100644
index 0000000..61eb11f
--- /dev/null
+++ b/tools/fixtures/z.py
@@ -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"]})
diff --git a/tools/fixtures/zoo.py b/tools/fixtures/zoo.py
new file mode 100644
index 0000000..f01c899
--- /dev/null
+++ b/tools/fixtures/zoo.py
@@ -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("> 8, 0x40])
+ var += struct.pack(" zoo bytes"""
+ hdr = b"ZOO 2.10 Archive.\x1a".ljust(20, b"\0") + struct.pack("