Repository navigation
v0.1.0
Initial public release. The bullets below are the entire change history
accumulated during the pre-1.0 scaffold-to-stable arc; everything listed
ships in v0.1.0. Highlights of the pre-release hardening pass:
- Fix (gzip, RFC 1952 §2.3.1 compliance): the decoder now (a) rejects
reserved FLG bits 0x20 / 0x40 / 0x80 with a typed
CodecInvalidData("gzip reserved FLG bits set")instead of silently
ignoring them; (b) actually verifies the FHCRC field against the
CRC-16 of the preceding header bytes (low two bytes of CRC-32) and
surfaces a typedgzip header CRC16 mismatchon disagreement
(previously the two bytes were skipped without verification); and
(c) decodes FNAME / FCOMMENT through a UTF-8-then-Latin-1 fallback so
RFC-conformant ISO-8859-1 names from oldergzipproducers no longer
surface as"gzip header string is not UTF-8". - Fix (archive):
archive.entry_by_pathsearches in insertion order
(the order the docstring promises andentries() |> list.find(...)
produces) instead of the internal reversed list, so duplicate-path
archives return the first match, not the last. - Fix (gzip):
with_name/with_commentpanic on embedded NUL
to keep the round-trip lawname(with_name(h, x)) == Some(x).
Previously they silently stripped NULs, breaking the law; the checked
counterparts (with_name_checked/with_comment_checked) are still
the untrusted-input route. - Fix (lz4, JS target): refactored
decode_block_loop,
decode_blocks,decode_legacy_blocks, andcopy_match_byte_by_byte
into Step/Continue trampolines, mirroring the deflate / bzip2 fix.
Decoding more than ~1500 LZ77 sequences on JS no longer overflows the
call stack withRangeError: Maximum call stack size exceeded. - Fix (detect):
from_path_or_bytessurfaces the caller-supplied
pathin theDetectUnknownFormat.inputfield when both detection
paths fail, instead of the internal"byte-signature scan"sentinel. - Tests: added 180 differential-corpus tests across gzip / bzip2 /
xz / zstd / lz4 / lzw (compress) against the system CLI, plus six
metamon-driven recipe pack/unpack round-trip properties. - Docs: README rewritten around worked examples (every code block
is checked bytest/packkit/readme_examples_test.gleamso it cannot
silently rot);doc/reference/spec.mdremoved (it was local-only,
gitignored, and stale). - Workflows: the GitHub Release body now points at
CHANGELOG.mdrather than a non-existent repository spec.
The remaining bullets are the per-feature history of the 0.1.0 cycle.
- Feature (brotli): the encoder now also emits a real LZ77
compressed metablock as a third candidate (alongside the existing
uncompressed and literals-only paths). A greedy 4-byte hash-chain
match finder over the 32 KiB window produces insert-and-copy
commands; each command picks acell_idx ≥ 2IC symbol so the
distance is read from a dedicated distance Huffman code instead of
reusing the ring buffer. Three complex-form Huffman descriptors
(256 literal, 704 IC, 64 distance) describe the alphabet, all
built via the same naive frequency-merge Huffman the literals path
already used. Repetitive payloads compress dramatically further:
1 KiB of zeros drops to ~60 bytes (was ~140 bytes),"abc" x 100
to ~54 bytes (was ~85), and 1.35 KiB of repeated lorem-ipsum to
~100 bytes. All outputs round-trip through both packkit's own
decoder and the referencebrotliCLI. - Fix (brotli encoder, single-symbol Huffman codes):
assign_brotli_canonical_codesnow matches the decoder's
canonicalise_from_pairsspecial case for single-active-symbol
alphabets: the decoder treats them as zero-bit codes
(decode_prefix_walkexits immediately when an entry has
length == 0 && code == 0), so the encoder must too — otherwise
the descriptor's trailing bits leak into the next section. The
bug surfaced when the LZ77 distance alphabet held a single code
(e.g., every command shared the same distance), shifting all
subsequent bitstream sections. - Feature (brotli): the encoder now optionally emits a single
ISLAST=1 compressed metablock whose literal alphabet uses a
complex-form Huffman code (RFC 7932 §3.5), still without an LZ77
match step. The complex-form descriptor is built via a CL-Huffman
table length-limited to 5 bits, RLE-encoded with sym 16 / 17 chain-
breakingLitseparators, trimmed at the last non-zero alphabet
length, and — crucially — terminated as soon as the CL Huffman
space is exhausted (matching the decoder's early-exit Kraft check
inread_one_cl). The encoder picks the smaller of the
uncompressed and the compressed candidate per payload, so
incompressible payloads never regress. Repetitive byte alphabets
(e.g.abcx 100, mostly-zero tar headers) round-trip through both
packkit's own decoder and the referencebrotliCLI. - Fix (brotli decoder, JS target):
emit_literals_loopand
decode_prefix_walkpreviously called themselves through
use <- result.try(...)closures and through mutually-recursive
helpers, so the Gleam JS compiler could not emit awhileloop.
Each compressed-metablock literal added a stack frame and a payload
of more than ~10 000 prefix-code bit reads — easily reached by a
3 KiB tar archive — blew the JS engine's call-stack limit. Both
loops are now structured around an explicitLiteralStep/
inlined-casedispatcher so the recursive call stays in tail
position, restoring single-frame iteration on JS. - Feature (zstd): the sequences encoder now also emits
FSE_Compressed_Modefor LL/OF/ML tables whenever the per-chunk
symbol distribution is biased enough that a chunk-specific FSE
distribution beats the predefined one. Once a chunk has ≥ 32
sequences the encoder tallies the LL/ML/OF codes, normalises
each alphabet to a power-of-2 table size (accuracy_log chosen
per RFC 8478 §3.1.1.3.2.2.1.1 — capped at 9 / 8 / 9
respectively), builds the encoder state tables via the
decoder-sidefse.build_state_table(so encoder and decoder
see identical layouts), and emits a distribution header
followed by the FSE bitstream. When the resulting section
beats the Predefined_Mode candidate, the encoder switches to
the0xA8mode byte (all three alphabets at value 2 =
FSE_Compressed_Mode); otherwise it falls back to the
predefined-tables path with the original0x00mode byte.
Highly-biased inputs (e.g. anABCDXmotif x 100) now
compress to ~3 % of raw size; uniform inputs incur no overhead
because the comparison stage rejects the FSE-compressed
candidate whenever it would be larger. - Feature (zstd): the LZ77 sequences encoder now threads the
three-entry rep-offset ring (per RFC 8478 §3.1.1.5 — initial
(1, 4, 8)) through every chunk, so matches whose real
distance hits one of the recent offsets collapse onto
raw_offset = 1,2, or3instead ofdistance + 3. The
literal_length == 0branch is also honoured (raw_offset 1
selects rep[1], 2 selects rep[2], 3 selects rep[0] - 1), and
the encoder rotates the ring the same way the decoder's
resolve_offsetdoes so encoder and decoder stay in
lockstep. Payloads that hit the same distance over and over
now compress dramatically further — a 4-byte motif repeated
200 times shrinks below 5 % of its raw size. - Feature (zstd): the zstd encoder now optionally emits a
Compressed_Block whose Sequences_Section carries real LZ77
sequences in addition to the existing literals-only path. A
greedy 3-byte hash-chain match finder over each 16 KiB chunk
(32 KiB max distance) producesSequence(literal_length, match_length, offset)triples; the sequence symbols are
encoded under Predefined_Mode for all three FSE alphabets
(LL / OF / ML) so the sequence section is just
Number_of_Sequences ++ 0x00 ++ FSE_bitstream. Each chunk
independently picks the smallest of Raw / RLE / Huffman /
sequences, so incompressible blocks never regress. Highly
repetitive payloads now compress dramatically below the
literals-only floor — e.g. a 16-byte motif repeated 50 times
(800 bytes) drops to well under 200 bytes through the
sequences path. - Feature (zip): ZIP decoder now reads entries protected by the
PKWARE "traditional" / "ZipCrypto" encryption scheme via two new
public entry points —zip.decode_with_passwordand
zip.decode_with_password_and_limits. The decoder seeds the
three-key cipher state from the supplied password, decrypts each
entry's 12-byte encryption header, verifies the trailing byte
against the high byte of the entry's CRC-32 (APPNOTE §6.0), and
hands the resulting plaintext to the matching method (store,
deflate,bzip2,zstd,xz,lzma). Encrypted entries
reached by the plainzip.decodeAPI surface a typed
ArchiveNotImplementedso the missing password is never silently
ignored; wrong passwords come back asArchiveInvalidrather than
passing garbage to the codec. Strong-encryption (gp flag bit 6)
is rejected with a typed not-implemented error rather than
decoded as ZipCrypto. - Feature (zstd): the zstd Huffman literals encoder now also
emits the FSE-compressed tree-description form (header byte
0..127 + FSE body) when the direct-weight form can't carry the
alphabet. Tree descriptions for byte alphabets that stream
more than 127 weights — i.e. anything that uses byte values
above 127 — are now Huffman-encoded instead of falling back to
Raw / RLE. The FSE encoder builds normalised counts (floor-
scale at accuracy_log = 6, give the remainder to the largest
count), writes the distribution header forward, then inverts
the decoder'sfse.build_state_tableto drive a two-state
backward encoding loop with the standard zstd "highest set bit
of the last byte" marker. A chunk whose FSE body would exceed
the 127-byte header cap still falls back to Raw / RLE; in
practice that only triggers on highly skewed inputs with > 200
distinct bytes. - Feature (lzma1): literal-or-short-rep dispatch on the LZMA1
encoder. Whenever the byte atpos - rep0 - 1already matches
the current input byte, the encoder emits the LZMA short-rep
packet (is_match=1, is_rep=1, is_rep_g0=0, is_rep0_long=0—
four prob bits, no literal-byte coding, no length encoding)
instead of a full literal. Strict win over the literal path
whenever the rep0 ring is already aligned with the input. - Feature (zstd): zstd encoder now emits a Compressed_Block
with Huffman-coded literals when it shrinks a chunk relative to
the raw / RLE alternatives. Supports both the 1-stream form
(size_format = 0, ≤ 1023-byte chunks) and the 4-stream form
(size_format = 2, ≤ 16 KiB chunks with a 6-byte jump table over
the four sub-bitstreams). Each chunk independently picks the
smallest of Raw / RLE / Huffman so the encoder never regresses
on incompressible payloads. Compression ratios on English-like
text now hold steady at ~50 % across small and large inputs
(pangram x 100 → 58 %, lorem x 200 / 500 / 2000 → all ~51 %). - Fix (internal/huf decoder):
decode_symbols_loopwas
structured arounduse <- result.trywhich compiled to JS
callbacks and prevented tail-call optimisation, so any single
Huffman stream larger than a few KiB blew the JavaScript
engine stack at ~10000 frames. Inliningdecode_one_symbol
and spelling out the case branches manually keeps every
recursive call literally in tail position so Gleam emits a
realwhileloop on the JS target and 16 KiB+ streams now
decode without exhausting the stack. - Feature (internal/lzma): added
encode_with_lz77— a real
LZ77 match finder for the LZMA1 encoder. Uses the same 3-byte
Knuth-hash chain pattern as the deflate encoder, a 32 KiB
search window, max match length 273. Emits LZMA matches
(is_match=1, is_rep=0) with the standard length / distance
scheme (3-tier length prefix + pos-slot distance + extra bits- reverse-bit-tree alignment). All three LZMA1 wrappers
(xz / 7z / ZIP method 14) now route through this path, so an
80 KiB repeating-string payload that used to encode to ~89 KiB
(literal-only 1.125x expansion) compresses to ~388 bytes
throughxz.encode.
- reverse-bit-tree alignment). All three LZMA1 wrappers
- Feature (internal/lzma): rep-match emission added on top of
the LZ77 encoder. When the match distance equals one of the
last four distances (rep0..rep3), the encoder skips the full
pos-slot / direct-bits dance and uses LZMA's much cheaper rep
prefix (is_rep=1+ a 1–3 bit slot selector) plus the
dedicated rep-length prob tables. Each rep slot rotates into
rep0exactly the way the decoder expects so the ring stays
consistent across matches. On the standard repeating-motif
benchmark this drops xz output from ~448 to ~388 bytes (an
additional ~13 % saving on top of the LZ77 baseline). - Feature (xz): xz encoder now emits LZMA2 LZMA-compressed
chunks (control byte0xE0) instead of falling back to
uncompressed chunks for every payload. Each 32 KiB sub-chunk
is encoded by the literal-only LZMA1 encoder, so the resulting
.xzfile is a fully conforming LZMA-compressed stream that
any standard decoder (xz CLI, libarchive, ...) accepts. Multi-
chunk payloads round-trip end-to-end through the existing
decoder. - Fix (internal/lzma decoder):
loop_untilwas structured
arounduse <- result.trywhich compiles to JS callbacks and
prevented tail-call optimisation, so any single LZMA chunk
larger than a few KiB blew the JavaScript engine stack at
~10000 frames. Manually spelling out the case branches keeps
every recursive call literally in tail position so Gleam emits
a realwhileloop on the JS target and 32 KiB chunks now
decode without exhausting the stack. - Feature (lzma1): added a literal-only LZMA1 encoder in
packkit/internal/lzma.encode_literal_only. The encoder mirrors
the existing decoder's range coder + literal-state machine
(LZMA SDK semantics including the deferred-carry cache trick) and
produces a fully valid LZMA1 byte stream that any conforming
decoder accepts. No LZ77 match search yet so the compression
ratio is ~1.125x, but the encoder unblocks every wrapper format
that needs an LZMA1 stream (ZIP method 14, 7z, future xz LZMA2). - Feature (zip): added
zip.lzma()Method that emits ZIP
method 14 (PKWARE LZMA wrapper) on the encode side. The
encoder wraps the literal-only LZMA1 stream in the standard
4-byte SDK preamble + 5-byte property block (lc=3 / lp=0 / pb=2,
64 KiB dictionary) and sets general-purpose flag bit 1 so the
decoder relies on the central-directory uncompressed size
instead of an in-stream EOS marker. - Feature (7z):
seven_z.encodeis implemented. Builds a
single-folder, single-coder 7z archive with a raw LZMA1 coder
for the packed stream, includingPackInfo,UnPackInfo,
optionalSubStreamsInfo(for multi-file archives), and
FilesInfowith UTF-16 LE file names. Multi-file archives
round-trip through the existing decoder. Restricted toFile
entries for now — directories / symlinks / hardlinks would need
EmptyStreamandAttributeblock emission and are rejected
withArchiveEntryRejected. - Feature (zip): ZIP encoder now supports methods 12 (bzip2),
93 (zstd), and 95 (xz) in addition to the existing store and
deflate methods. Three newMethodconstructors —
zip.bzip2(),zip.zstd(),zip.xz()— dispatch to the
matching packkit codec on encode; the decoder side already
handled these methods, so archives now round-trip in both
directions throughzip.encode_with_method/zip.decode.
version_neededfollows APPNOTE.TXT (4.6 for bzip2, 6.3 for
zstd / xz). - Feature (zip): ZIP decoder now reads method 14 (PKWARE
LZMA wrapper). Parses the 4-byte SDK preamble + 5-byte
property block (lc/lp/pb byte + 4-byte LE dictionary size),
hands the range-coded payload topackkit/internal/lzma, and
honours the central-directory uncompressed size as the decode
limit. Read-only; encode is still future work because we do
not have an LZMA1 range-coder writer. - Feature (xz): block-check field is now verified for
check_type = 4(CRC-64-XZ) andcheck_type = 10(SHA-256).
Previously both branches only checked that the field length
matched the expected size — a corrupted payload with the
right number of trailing bytes would pass undetected. CRC-64
is implemented inchecksum.crc64_xzusing a#(low_u32, high_u32)pair so the implementation stays exact on the
JavaScript target. SHA-256 is a pure-Gleam FIPS 180-4
implementation inchecksum.sha256. - Fix (correctness): cpio decoder now also accepts the
crc
format (magic070702). newc (070701) and crc share the same
on-disk layout; only the optional 32-bit body checksum differs.
The previous "not a newc cpio magic" error would block
cpio -H crcarchives entirely. The decoder still treats the
checksum field as opaque (no verification yet), but
cpio -H crcround-trips end-to-end now. - Fix (correctness): tar decoder now parses PAX extended-
header records. Previously the decoder skipped thex/g
bodies entirely, so files emitted bytar --format=pax
(the default on POSIX) with names longer than the USTAR 100-
character limit silently truncated to the leading 100 bytes
visible in the regular header. The new
apply_pax_recordswalks the<length> <key>=<value>\n
records and liftspath/linkpathinto the
PendingOverridethread that already handles GNU
LongName/LongLink. Other PAX keys (mtime, atime,
size, charset, …) are still skipped because they don't
change which bytes the entry holds. - Fix (correctness): zstd Raw / RLE literals block now accepts
size_format = 3(3-byte header, 20-bit regenerated_size, used
byzstdfor raw-literal blocks larger than 4 KiB). The
decoder previously rejected this with a typed
CodecNotImplemented, which broke any file that happened to
emit a large raw-literals block (mixed binary + text payloads
atzstd -1..-19hit this in ~17 % of fuzz iterations). - Fix (correctness): zstd
resolve_offsetraw_offset=2,
LL=0 case (offset_value 2 with zero literals_length, i.e.
reference repCode 2) wrote a corrupted repeated-offset
history. The code chained three rep-field updates inside
oneSeqContextrecord literal and a follow-uprotate_rep
helper, and the rotate observed its own freshly-written
fields — net effect:rep[1]ended up equal to the new
rep[0]andrep[2]was the oldrep[0]instead of old
rep[1]. Visible symptom was matched-text corruption at
highzstdlevels (-13 and above), e.g.zstd -15 src/zstd.gleam
mismatched at byte 37977 with a "rep code triggered a wrong
copy" pattern. After the fix everyzstd -1..-19level
decodes byte-for-byte for every fixture in the regression
suite — the repository's own README / CHANGELOG / source
files round-trip across the full level range. - Fix (correctness): zstd multi-block frames now thread the
running per-frame output and the repeated-offset triple
(rep0, rep1, rep2) across block boundaries. Previously each
block decoded from an empty match window and a fresh rep
triple(1, 4, 8), so any sequence whose match offset
reached back into a previous block surfaced as
"zstd match offset exceeds emitted output" (highzstd
levels) or silently emitted wrong bytes from byte
block_sizeonward (low levels). RFC 8478 §3.1.1.5 spells
the requirement out: "Repeated offsets are maintained across
blocks (but not across frames)." Frames now decode
byte-for-byte against typicalzstd -3/ -9 / -15 fixtures= 128 KB (the per-block ceiling).
- Fix (correctness): zstd
resolve_offsetdispatched on the
FSE-decodedof_codeinstead of the resultingraw_offset
(=offset_value). RFC 8478 §3.1.1.5 keys the repeated-
offset logic onraw_offset(1, 2, or 3) —of_code == 1
yieldsraw_offsetin {2, 3} with its associated repeated-
offset semantics — so the previous code clamped those cases
to "use rep[0]" and produced wrong match copies in any block
that hit araw_offsetof 2 or 3. Visible symptom was
silent-wrong-output deep inside CSV / JSON / XML records
(mismatch at the same content-relative byte across many file
sizes). After the fix everyzstd -3/zstd -9fixture in
the regression suite — including 8 KB JSON-line records,
4 KB CSV rows, and 4 KB XML entries — round-trips byte-for-byte. - Fix (correctness): zstd 2-byte
Number_of_Sequences
encoding (sequences section header) had a stray+ 0x80in
parse_and_apply_sequences, so any compressed block emitting
more than 127 sequences read ~2× the actual count and then
ran out of bitstream bits mid-decode (surfacing as
"truncated zstd literal_length state-update bits"). The
reference formula (see
doc/reference/zstd/lib/decompress/zstd_decompress_block.c
ZSTD_decodeSeqHeaders) is
((byte0 - 0x80) << 8) + byte1— the 2-byte form FULLY
OVERLAPS the 1-byte form and does not add a fresh 128 offset.
Files generated byzstd -3of typical structured text
(JSON-line, CSV, XML records) trigger this path; they all
errored before and now decode again. - Fix (correctness): zstd Huffman literal decoder produced
the wrong bytes for any compressed-literals block whose tree
had more than one code length (i.e. essentially every real
zstd -3+output of text or binary data with a skewed
byte distribution). The canonical-code assignment in
internal/huf.gleamsorted by(bits ASCENDING, symbol ASCENDING)— the OPPOSITE of zstd's convention, which puts
the LONGEST codes at the LOWEST table indices so the bit
pattern00000…decodes to the rarest symbol (see
HUF_readDTableX1indoc/reference/zstd/lib/decompress/ huf_decompress.c). The decoder used to silently return
valid alphabet symbols in scrambled order with no error,
which is the worst possible decompression bug. After the
fix everyzstd -3text fixture in the regression suite
round-trips byte-for-byte (N=5..50 line pangrams, a
generated 80 KB skewed-distribution payload, and the
existing 300-byte alphabet-16 fixture). - Decoder now skips zstd
Skippable_Frame(RFC 8478 §3.1.2)
payloads — any frame whose magic falls in 0x184D2A50..0x184D2A5F
is parsed for its 4-byte LE Frame_Size, the User_Data bytes
are discarded, and the next frame (or end-of-stream) is
consumed. Streams that mix data frames and skippable frames
(e.g. zstd CLI's--block-checksumdebug helpers, archives that
inline user metadata) now round-trip throughpackkit.decompress. - Implemented zstd sequence-symbol
Repeat_Mode(mode 3) for all
three alphabets (LL / OF / ML). The block loop now carries a
per-frameSeqTablesStatealongside the existing Huffman tree
thread, so a block can ask to reuse the previous block's FSE
table without re-emitting the distribution. A Repeat_Mode in
the first block of a frame still surfaces as a typed
CodecInvalidDatawith the alphabet's label. - Encoder now picks
RLE_Block(block_type 1) when a chunk
repeats a single byte, falling back toRaw_Blockotherwise.
Uniform-byte inputs collapse to a 1-byte RLE payload and the
output stays a valid Zstandard frame any conforming decoder
accepts. - Added a padded backward bit reader (
read_backward_bits_padded
ininternal/fse.gleam) that mirrors the zstd reference HUF
decoder's tolerance for the last symbol's code spanning the
bitstream boundary. Huffman decode uses it for both the
lookup peek and the actual bit consume; strict-stream
behaviour is unchanged. - Fixed the zstd predefined Match_Length distribution that
internal/fse.gleamwas using. The reference
ML_defaultNorm(lib/common/zstd_internal.h) marks seven
symbols (codes 46..52) as less-probable placeholders; the
packkit table had only the last five. That two-cell shortfall
pushed every state→code mapping past code 36 by one, so any
sequence whose decoded ml_code lived in the affected range
surfaced as a typedtruncated zstd match-length extraeven
though the bitstream itself was well-formed. With the fix the
previously-pending pangram fixture round-trips byte-for-byte
and adecode_compressed_block_pangram_testreplaces the old
"expects an error" marker test. - Completed zstd
Treeless_Literals_Blockdecoding. The block
loop now threads anOption(huf.Tree)forward; compressed
literals blocks publish their parsed tree, and treeless
blocks (block_type 3) reuse the most recently parsed one.
A treeless block in the first position of a frame still
surfaces as a typedCodecInvalidDatawith a "treeless
literals without a prior Huffman tree" message rather than
segfaulting into an undefined-tree path. This closes the
lastCompressed_Literals_Block/Treeless_Literals_Block
gap noted in earlier release notes. - Added the IA-64 / Itanium (filter id 0x06) and RISC-V (filter
id 0x0B) BCJ pre-processor filters to the xz multi-filter
chain. IA-64 walks 16-byte bundles, indexes a branch table by
the 5-bit template selector, and rewrites the 21-bit
IP-relative immediate in any of the three 41-bit slots that
the template marks as branch-bearing. RISC-V handles
JAL x1/x5(opcode 0xEF) and theAUIPC + inst2pair forms
the encoder produces — including the bijective "fake"
conversion path forAUIPC rd == x0 / x2that keeps the
filter safe to apply on arbitrary data. Both decoders are
verified byte-for-byte againstxz --ia64/xz --riscv
reference output, completing the BCJ filter set xz supports. - Added the SPARC (filter id 0x09) and ARM64 / AArch64 (filter
id 0x0A) BCJ pre-processor filters to the xz multi-filter
chain. SPARC decodes the 22-bitCALLdisplacement with
proper sign extension; ARM64 handles bothBL(top 6 bits
0x25) andADRP(mask0x9F000000 == 0x90000000), including
ADRP's ±512 MiB range check. Both decoders are verified
byte-for-byte againstxz --sparc/xz --arm64reference
output. Remaining filter IDs (IA-64 0x06, RISC-V 0x0B) still
surface asCodecNotImplementedcarrying the filter id. - Added the PowerPC (filter id 0x05) and ARM-Thumb (filter id
0x08) BCJ pre-processor filters to the xz multi-filter chain.
Both decoders are verified againstxz --powerpc/
xz --armthumbreference output and round-trip the
encoded-target sequence byte-for-byte. - Completed zstd
Compressed_Literals_Blockdecoding (RFC 8478
§4.2.1). Building on the direct-weight tree foundation from
the previous commit, the decoder now handles:- FSE-compressed Huffman weights (
header_byte < 128)
with the two interleaved FSE states the spec defines. - 4-stream bitstream layout (
size_format >= 1): the
6-byte jump table parses the per-stream byte sizes, the
first three streams each emitceil(regenerated_size / 4)
symbols, and the fourth stream covers the remainder. - End-to-end wiring into
parse_compressed_literalsso
block-type-2 literals materialise into the regenerated
bytes that the existing sequence decoder consumes.
Verified end-to-end with a 300-byte fixture generated by
zstd -1(FSE weights + 4-stream form), the common shape of
real-world.zstfiles. Treeless literals
(Treeless_Literals_Block, block_type 3) still surface as
CodecNotImplementedbecause they require persisting the
Huffman tree across blocks.
- FSE-compressed Huffman weights (
- Extended the xz decoder to support multi-filter chains whose
final filter is LZMA2 and whose earlier filters are
recognisable pre-processors. The delta filter (id 0x03), the
x86 BCJ filter (id 0x04), and the ARM A32 BCJ filter (id 0x07)
are wired up; after LZMA2 decode the pre-filter chain is
applied in REVERSE order so the bytes surfaced to the caller
match the encoder's input. The x86 BCJ implementation
faithfully reproduces theprev_maskstate machine from
xz-utils (0BSD reference) so consecutiveE8/E9opcodes
within five bytes of each other decode byte-exact against the
referencexz --x86output. Remaining BCJ IDs (PowerPC,
IA-64, ARM-Thumb, SPARC, ARM64, RISC-V) still surface as
typedCodecNotImplementederrors carrying the filter id. - Extended the 7z decoder with per-file substream awareness. The
parser previously skippedSubStreamsInfoentirely, so any 7z
archive containing more than one file inside a single folder
decoded as a single concatenated body assigned to the first
filename. The new parser captures the per-substream sizes from
kSize(NID 0x09), derives the final size from the folder's
total, and threads the list throughbuild_entries_loopso
every file gets exactly its own byte slice. Single-file
archives without aSubStreamsInfoblock keep their previous
"all remaining bytes" fallback so the existing fixtures are
unaffected. - Extended the ZIP decoder to dispatch on three more
compression methods: 12 (bzip2), 93 (zstd), and 95 (xz). Each
method routes through the corresponding packkit codec's
decode_with_limits, so archives produced by7z a -tzipor
zip --compression-method bzip2 / xz / zstdround-trip
without a manual unwrap step. ZIP method 14 (PKWARE LZMA)
still requires its specific 4-byte stream wrapper and is left
asArchiveNotImplemented("ZIP method 14")for now. - Added decoder support for the LZ4 legacy frame format
(magic0x184C2102— emitted by olderlz4 -l/lz4cand
embedded toolchains). The legacy format has no frame
descriptor and no end marker, just a magic followed by
<size_LE32, body>blocks terminated at EOF;lz4.decode
now dispatches on the leading magic and routes legacy streams
through a dedicated block walker that reuses the existing LZ4
block decoder.detect.from_bytesrecognises the legacy
magic too. - Added
gzip.Subfieldandgzip.with_extra/gzip.extraso
gzip's FEXTRA region (RFC 1952 §2.3.1.1) can now be set at
encode time and recovered at decode time. The decoder
previously skipped FEXTRA on the floor, which made formats
built on top of FEXTRA (BGZF'sBCblock-size subfield, the
RArandom-access index, ...) impossible to round-trip
through packkit. Encode validates the per-subfield 16-bit
LEN, the per-region 16-bit XLEN, and the per-byte ID range,
surfacing typedHeaderExtraSubfieldTooLong,
HeaderExtraTotalTooLong, andHeaderExtraSubfieldIdOutOfRange
errors viawith_extra_checkedrather than silently truncating
insideencode. - Added
recipe.tar_lzwplus the.tar.Z/.taz
filename detection. The lzw codec was already available
on its own but the tar recipe was missing. - Added
recipe.cpio_bzip2,recipe.cpio_xz, and
recipe.cpio_zstd, plus matching filename detection for
.cpio.bz2,.cpio.xz, and.cpio.zst. The cpio container
was previously only paired with gzip in the recipe and
detection layers, even though all three other codec recipes
are common enough in Linux package ecosystems (RPM.cpio.gz
vs.cpio.xz). - Extended
detect.from_byteswith two more signatures. Zstd
skippable frames (magic range0x184D2A50..0x184D2A5F,
used by wrappers that embed metadata between real zstd frames)
now resolve to the zstd codec, and the snappy framed format's
stream-identifier chunk (FF 06 00 00 "sNaPpY") is recognised
as snappy. Both signatures are matched strictly so they cannot
false-positive on arbitrary byte streams. - Made the multi-member / multi-stream / multi-frame loops in
gzip,bzip2,xz, andzstdenforcemax_output_bytes
across the full byte stream rather than per member. Each
codec's inner decoder already capped the current member at the
limit, but a stream of N members could still grow the catenated
payload to N × max_output_bytes before any check fired. The
new running-total check folds each member's contribution into
the limit so adversarial concatenated archives are rejected as
soon as the threshold is exceeded. - Made the
zstdliterals-section header parser cover all four
size_format variants ofCompressed_Literals_Blockand
Treeless_Literals_Block(3-, 4-, and 5-byte headers). The
CodecNotImplementeddiagnostic now carries the parsed
regenerated_size,compressed_size, and stream count (1 or 4)
so users can see exactly which configuration their.zstfile
uses, and the parser is wired up so the eventual Huffman
literal decoder can plug into a stable foundation. - Added
lz4.encode_with_content_sizeand a small pure-Gleam
internal/xxh32module that computes the LZ4 frame header
checksum byte. The new encoder sets the FLG content-size flag
(0x08), writes the 8-byte little-endian uncompressed size, and
derives the HC byte as(XXH32(FLG..BD..CSIZE, 0) >> 8) & 0xFF
so strict LZ4 decoders (the referencelz4CLI in particular)
accept the frame and can pre-allocate the output buffer. The
pre-existinglz4.encodekeeps its no-content-size, fixed-HC
output unchanged so round trips with itself are bit-for-bit
identical to previous releases. - Extended the
ardecoder with the GNU long-name string-table
variant. In addition to the BSD#1/Nform the decoder already
supported, the new path recognises the//(ARFILENAMES/)
member as a string table and resolves/<offset>references in
later headers to the corresponding long names. GNU symbol-table
members (named/or/SYM64/) are skipped transparently so they
never appear as user-visible entries. The encoder still emits the
BSD form, but archives produced bybinutils ar(typical for
.aand.debfiles on Linux) now round-trip through the
decoder end-to-end. - Added multi-frame zstd decoding (RFC 8478 §3.1). A zstd byte
stream may be the concatenation of independent zstd frames (the
typicalcat a.zst b.zstpattern); the decoder now walks the
entire input rather than returning as soon as the first frame's
optional content-checksum has been consumed, and catenates each
frame's payload into the resultingBitArray. - Added multi-stream bzip2 decoding. A
.bz2file may be the
concatenation of independent bzip2 streams (the typical
bzcat-style pattern); the decoder now follows each
end-of-stream marker, aligns to the next byte boundary, and
consumes any further"BZh"magic that appears in the
remainder. - Added multi-stream xz decoding. A
.xzfile is a concatenation
of one or more independent streams perxz-file-format.txt§1,
optionally separated by 4-byte-aligned all-zero stream padding.
The decoder now walks the entire input rather than stopping
after the first stream footer; padding between streams is
consumed silently. - Added multi-member gzip decoding (RFC 1952 §2.2). A gzip byte
stream built by concatenating two or more single-member streams
(the typicalcat a.gz b.gzpattern) now decodes to the
concatenated payloads instead of stopping at the first
member's trailer. Supporting this required a new
deflate.decode_with_remainderAPI that returns both the
decoded bytes AND the byte-aligned remainder of the input, so
wrappers like gzip can know exactly where the embedded DEFLATE
stream ends. - Added Zip64 support to the ZIP encoder and decoder. The decoder
recognises the Zip64 EOCD locator (signature0x07064b50) when
the standard EOCD carries the0xFFFF/0xFFFFFFFFsentinels,
reads the 64-bit totals from the Zip64 EOCD record (signature
0x06064b50), and walks each entry's extra-field block for the
header_id = 0x0001Zip64 extended-information record to pick up
64-bituncompressed_size,compressed_size, and
local_header_offsetvalues. The encoder mirrors the decoder:
any entry whose size or local-header offset would overflow 32
bits transparently emits the sentinel in the legacy slot plus the
Zip64 extra field, and archives whose total entry count or
central-directory region overflow the legacy EOCD slots emit a
Zip64 EOCD record + locator before the standard EOCD. Switched
the encoder's per-entry walk from explicit tail recursion to
list.foldso 65 537-entry archives no longer blow the
JavaScript engine's call stack. - Replaced the Snappy raw encoder's literal-only path with a real
LZ77 block compressor. The match-finder mirrors LZ4 (greedy
4-byte hash table, 16-bit hash) but emits the Snappy block format:
literal (low 2 bits = 00) + copy-1 (01, length 4..11, 11-bit
offset) / copy-2 (10, length 1..64, 16-bit offset) / copy-4 (11,
length 1..64, 32-bit offset), with matches longer than 64 split
across consecutive copies sharing an offset. The framed encoder
now dispatches each chunk through the raw encoder and picks the
smaller of the compressed (0x00) and uncompressed (0x01)
chunk types. - Replaced the LZ4 frame encoder's uncompressed-only path with a
real LZ77 block compressor. Each block runs a greedy 4-byte hash-
chain match-finder (16-bit hash table, max distance 65 535,
minimum match 4) and emits the LZ77 sequences in the canonical
block layout (token byte with 4-bit literal-length / 4-bit match-
length nibbles, 0xFF-terminated extensions for either field >=15,
literals, little-endian 16-bit offset, match-length extension).
Blocks whose compressed form would grow are still emitted in the
uncompressed form so the frame never gets larger than the input. - Extended the Zstandard sequences-section parser to recognise the
non-Predefined_Modesymbol-description selectors.RLE_Mode
builds a one-state FSE table from the inline byte and
FSE_Compressed_Modedecodes the RFC 8478 §4.1.1.2 distribution
header (variable-width count read with 2-bit zero-RLE jumps) to
build the table via the existinginternal/fse.build_state_table
primitive.Repeat_Modestill surfaces a typed
CodecNotImplementedbecause reusing tables across blocks requires
cross-block state the current decoder does not carry. - Implemented the DEFLATE dynamic-Huffman encoder
(deflate.encode_dynamic). It reuses the existing LZ77 match-
finder, builds per-stream Huffman codes for the literal/length and
distance alphabets from the observed token frequencies, then RLE-
compresses the combined code-length sequence with the 19-symbol
code-length alphabet and writes an RFC 1951 BTYPE=10 block. On
inputs whose natural Huffman tree would exceed the 15-bit code-
length cap the encoder transparently falls back to the fixed-
Huffman path so callers always get back a valid stream. - Hardened 7z decoder limits:
seven_z.decode_with_limitsnow
enforcesmax_membersagainst the declared file count and
max_output_bytesagainst the declared unpack size before the
LZMA/LZMA2 range coder runs. Previously onlymax_input_bytes
andmax_entry_depthwere checked, so a hostile archive could
force a multi-GB allocation by advertising a huge unpack size. - Lifted the convenience helpers
add_file/add_directory/
add_symlink/add_hardlink(and_checkedvariants) into
packkit/archiveso every format (tar / cpio / ar / zip / 7z) can
share them. Previously onlypackkit/tarexposed these wrappers. - Fixed an LZW decoder width-promote off-by-one bug that injected a
phantom0byte into round trips of the 256-byte sequence
[0..255]. The encoder pads to the 9-bit byte-block boundary
right after writing code 254, but the decoder's promote check used
free_ent > max_code, which fires one iteration too late given
LZW's classical encoder/decoder insert-pair asymmetry; the new
>=check promotes between codes 254 and 255 to match the
encoder. Added regression tests at the promote boundary ±1 to
guard against re-introducing the bug. See
[packkit/lzw.promote_decoder_width]. - Extended
packkit/streamto cover every codec uniformly.
Previously only DEFLATE, zlib, and gzip had streaming decoders;
addednew_lz4_decoder,new_snappy_decoder,new_bzip2_decoder,
new_lzw_decoder,new_xz_decoder,new_zstd_decoder, and
new_brotli_decoderso the streaming surface is consistent across
all ten supported codecs. - Added metamon-driven property-based round-trip tests
(test/packkit/property_test.gleam) over every codec for arbitrary
BitArrayinputs in the 0..256-byte range, plus length-preservation
invariants for DEFLATE and LZW. Together with the existing
fixture-based round-trip tests this materially widens coverage at
the empty-input, single-byte, and width-promote / window
boundaries that have historically been failure-prone. - Added panic-free fuzz tests for
seven_z.decode/1
(test/packkit/seven_z_fuzz_test.gleam) covering empty, partial
signature, garbage, alternating, all-zeros, all-FF, and counter
inputs so a future regression that panics on a malformed 7z stream
fails noisily instead of silently propagating. - Scaffolded the repository as a cross-target Gleam package.
- Added an opaque-first public API skeleton for codecs, archives,
recipes, safe entries, limits, and detection. - Implemented the foundational compression and archive engines:
Adler-32 / CRC-32 / CRC-32C / bzip2 CRC-32 checksums, tar (USTAR),
cpio (newc), ar (BSD long-name), zip (stored and deflate),
DEFLATE decode (all RFC 1951 block types) plus a fixed-Huffman
LZ77 encoder, zlib, gzip, lz4 (frame), and snappy (raw + framed). - Added the bzip2 family: pure-Gleam decoder (inverse BWT, MTF,
grouped Huffman, RUNA/RUNB, RLE1) and encoder (naive forward BWT,
length-limited Huffman) with round-trip tests. - Added the Unix LZW
.Z(compress) encoder and decoder, including
the width-change / clear-table padding rules and the KwKwK
exception in the decoder. - Added the xz codec: stream header / block header / index / footer
framing plus LZMA2 uncompressed and compressed chunks. Built the
underlying LZMA range coder (12-state machine, literal / match /
repeat decoders, length and distance bit-trees) at
packkit/internal/lzma. - Added a 7z reader covering the common
7z asingle-file case
(single folder, single coder, raw LZMA03 01 01or LZMA221). - Added a Zstandard decoder covering frame envelope + raw + RLE
blocks + FSE-compressed sequences (Raw / RLE literals, predefined
FSE modes). The FSE primitives live inpackkit/internal/fse
along with the predefined LL/ML/Offset distributions and the LL /
ML base+extra-bits lookup tables. - Added a Brotli decoder covering the empty stream and any
ISUNCOMPRESSEDmetablock (RFC 7932 §9.2). - Extended the Brotli decoder to parse compressed metablocks
through the entire header pipeline: NBLTYPES, NPOSTFIX/NDIRECT,
literal context modes, NTREES, and all three prefix-code
descriptors in both simple form (§3.4) and complex form (§3.5,
the 18-symbol code-length code with 16/17 run-length symbols). - Added the Brotli command loop with the I+C alphabet (
kCmdLut
port), the 4-entry recent-distance ring buffer, and self-
overlapping LZ77 copies; end-to-end round-trip works for
aaa…/time of the day/Hello, World!style fixtures. - Embedded the RFC 7932 122,784-byte static dictionary and ported
the 121-entry transform table (IDENTITY / OMIT_FIRST_n /
OMIT_LAST_n / UPPERCASE_FIRST / UPPERCASE_ALL with the brotli
"overly simplified" UTF-8 case rules; SHIFT_FIRST / SHIFT_ALL
intentionally absent because the basic transform set never
selects them). - Added Brotli literal context-map decoding (§7.3): RLEMAX +
zero-run-encoded prefix code + optional inverse MTF, plus the
embedded 2 KiB_kBrotliContextLookupTableand the per-context
literal/distance tree selection on every emission. - Added Brotli block switching (§6) for the literal, insert-and-
copy, and distance categories: each tracks its own block-type
prefix code, the shared 26-symbol block-length alphabet, and a
2-entry recent-type ring buffer that feeds back into context-map
indexing. - Fixed the WBITS prefix decoder (RFC 7932 §9.1) for the
1 000 nnnbranch — previously returned17 + extrainstead
of8 + extrafornnn ∈ {2..7}and now rejects the
large-window indicator with a typed error. - Added GNU long-name (
L) and long-link (K) decoding to the
USTAR tar reader, plus permissive skipping of PAX extended-
attribute headers (x,g). - Wired the
packkit.compress/decompress/read/write/
pack/unpackfacade and turned byte-signature detection into a
real magic-number scan. - Honour the codec's
leveland presetdictionaryin the facade.
Unsupported combinations now surface the typed
CodecOptionUnsupported(option, codec_name)instead of silently
dropping the option. Alignedcodec.bzip2()with bzip2's
canonical level 9 sopackkit.compress(b, codec.bzip2())and
bzip2.encode(b)produce identical output. - Implemented zlib preset-dictionary support:
encode_with_dictionary
emits the FDICT envelope with the Adler-32 DICT_ID,
decode_with_dictionaryresolves it (with a typed
CodecDictionaryMismatchon a wrong-key dictionary), and the
decoder now enforcesLimits.max_window_bitsagainst the CMF
CINFO field. - Added safe gzip header constructors:
with_name_checked/
with_comment_checkedreject the NUL byte that would silently
truncate the FNAME / FCOMMENT field on round-trip. The unchecked
builders panic on embedded NULs (lawful round-trip — the value the
caller passes is the value stored). - Tightened
detect.from_bytes: gzip requires CM=8, zlib verifies
CMF.CM/CINFO and the FCHECK mod-31 invariant (no more
false-positives on0x78 _prefixes), bzip2 requires the 1..9
block-size digit. - Enforced
Limits.max_entry_depthconsistently across cpio, ar,
zip, and 7z (it previously fired only on tar). - Implemented
gzip.new_decoder/push/finishas a buffered
decoder so the streaming surface is no longer a typed
CodecNotImplemented. Mirrors the codec-neutral
packkit/streamAPI. - Implemented a real
brotli.encodethat emits valid uncompressed
metablocks (RFC 7932 §9.2) followed by a terminating empty
ISLAST marker.tar.brotlinow round-trips end-to-end through
the facade.
Install
gleam add packkitSee HexDocs for the API
reference and
CHANGELOG.md
for the implementation history.