API reference
Compression codecs in pure Zig: Snappy, LZ4, DEFLATE, gzip, zlib, Zstandard, and Brotli.
One module; each codec is a namespace under it. Codecs import only std
and fastmem, plus the shared src/internal/ by relative import (gzip and
zlib also import flate), so a codec directory can be copied out together
with src/internal/.
module
brotli
src
brotli (RFC 7932): one-shot encode.compress and decode.decompress, and
the streaming Reader and Writer. Caller-owned buffers, no heap
allocation. API: src/brotli/README.md. Format:
docs/specs/rfc7932-brotli.txt.
Types
module
decode
src
One-shot decompression: decompress and its error set,
DecompressError.
Constants
pub const DecompressError = …
src
value
error{
/// `target` cannot hold the decoded stream.
BufferTooSmall,
/// `§9.1` — WBITS is the invalid 0010001 pattern.
BadWindowBits,
/// The input ended before the stream did.
Truncated,
/// `§9.2` — the metadata meta-block's reserved bit is set.
ReservedBit,
/// `§9.2` — MNIBBLES > 4 with an all-zero last nibble.
ExuberantNibble,
/// `§9.2` — MSKIPBYTES > 1 with an all-zero last byte.
ExuberantMetaNibble,
/// Nonzero fill bits where the format requires zeros (`§9.2`, `§9.3`).
BadPadding,
/// `§3.4` — a simple code's symbol is at or past the alphabet size.
SimpleHuffmanAlphabet,
/// `§3.4` — a simple code repeats a symbol.
SimpleHuffmanSame,
/// `§3.5` — the code-length code is not a complete prefix code.
BadCodeLengthCode,
/// `§3.5` — a code-length sequence breaks the format's rules.
BadHuffmanCode,
/// `§6`, `§9.3` — a block count, or the meta-block length accounting.
BadBlockLength,
/// `§7.3` — a context map's zero-run overruns the map.
ContextMapRepeat,
/// `§4` — a special distance code resolves to zero or less.
BadDistance,
/// `§8` — a transform id above 120, or a word the transform empties.
BadTransform,
/// `§8` — a dictionary reference's word length is outside 4..24.
BadDictionary,
}Everything decompress reports: the layers' own refusals composed, plus
this surface's BufferTooSmall. The streaming Reader reports the same
names in its err field, minus BufferTooSmall (its output is the
caller's Buffer).
Functions
pub fn decompress(source: []const u8, target: []u8) DecompressError!usize
src
Decode one brotli stream (§9.1's header through the last meta-block's
last bit) from source into target, and return the decoded length.
more
The format records no decoded length, so target is a cap: the decoded
bytes are also the match history (§8), and a stream that would write
past the cap fails error.BufferTooSmall before that write. A caller
enforcing a decoded-size limit sizes target from that limit, so the error
means the limit was exceeded and a retry with the same buffer cannot
succeed. Bytes after the stream's last byte are ignored; decompressCounted
reports where the stream ended.
Zero bytes of input is Truncated (no stream began; the empty stream is
the single byte 06), and a stream of only empty meta-blocks decodes to
zero bytes.
On any error target can hold partial output, which must not be used.
The convenience form: its Buffer, about 2.6 MiB, rides this frame, so
give decoding threads 4 MiB or more of stack. decompressBuffered is the
same decode over a caller-placed Buffer. Nothing is allocated.
pub fn decompressBuffered(source: []const u8, target: []u8, buffer: *Buffer) DecompressError!usize
src
decompress over a caller-placed Buffer instead of the stack, so the
thread needs only the layers' KiB-scale scratch. The result is the same.
pub fn decompressCounted(
source: []const u8,
target: []u8,
buffer: *Buffer,
) DecompressError!Decompressed
src
decompressBuffered, also reporting the stream's length in source, so
a caller can find the bytes after the stream or refuse them. Same errors
and costs.
Types
module
command
src
The command stream (§5, §6, §7.1, §7.2, §9.3, §10): the
insert-and-copy alphabet, the three block switches, the context IDs, the
distance element, and the copy machinery.
Constants
value
error{
/// §9.3 — the literals to insert, the copy length, or a dictionary
/// word's length would exceed MLEN ("the stream should be rejected as
/// invalid"). The reference reports it as `FORMAT_BLOCK_LENGTH_1` or
/// `_2` depending on where the meta-block's accounting is checked; both
/// are this class.
BadBlockLength,
/// §8 — a static dictionary reference's copy length is outside 4..24.
BadDictionary,
}The command layer's refusals.
Functions
pub fn readCommand(
comptime Bits: type,
br: *Bits,
tree: *const huffman.CommandTree,
) Bits.ErrorSet!Command
src
§5, §9.3 — read one command: the insert-and-copy length symbol and both extra-bit fields. The copy extra bits are read even when §9.3's last-command rule will ignore the copy.
pub fn literalContext(mode: context.Mode, p1: u8, p2: u8) u6
src
§7.1 — the literal context ID. p1 is the last uncompressed byte and
p2 the one before it, "regardless of whether these bytes are produced
by uncompressed meta-blocks, backward references, static dictionary
references, or by literal insertions"; both are zero at the stream's
start. The result is in 0..63.
§10 — "move backwards distance bytes in the uncompressed data, and copy
CLEN bytes from this position to the uncompressed stream". A reference
can overlap the bytes it is writing: "if the last 2 bytes decoded have
values X and Y, a string reference with <length = 5, distance = 2> adds
X,Y,X,Y,X". The overlapping case replicates the distance-byte pattern,
so it is not fastmem.move: a move copies as through a temporary and
preserves the source, which is a different string.
more
match_distance >= 1 and pos + length <= window.len are the caller's
guarantees; the match is a window read, never a dictionary one (§8).
When match_distance > pos the source sits past pos: the window is a
ring and the pattern reaches into its previous pass — the streaming
reader's shape (Reader.ring). The one-shot's linear window never takes
that branch, because a distance is at most the bytes produced.
pub fn decodeMetaBlock(
comptime Bits: type,
br: *Bits,
header: *const frame.Header,
state: *State,
window: []u8,
start: usize,
mlen: u32,
window_size: u32,
) Errors(Bits)!usize
src
§9.3, §10 — decode one compressed meta-block's command stream into
window, whose [0..start) is the stream's decoded prefix (the match
history) and whose [start..start + mlen) is this meta-block's room.
Returns the position after the meta-block, start + mlen.
start + mlen <= window.len is the caller's guarantee: the one-shot
checks its target's cap before the call, so the MLEN accounting here is
§9.3's invalid-stream class, never a write past the caller's buffer.
pub fn step(
comptime Bits: type,
br: *Bits,
header: *const frame.Header,
state: *State,
cursor: *Cursor,
window: *Window,
) Errors(Bits)!void
src
§9.3, §10 — one bounded step of the command stream: decode commands until
the meta-block is complete (window.left == 0) or the window has no room
left (window.pos == window.bytes.len). The one-shot's window always has
room for the whole meta-block, so its whole decode is one call; the
streaming reader's ring is full at its end, and the reader flushes and
wraps it before stepping again.
Every write is capped by the room and by MLEN, so the phase machine can
stop between any two bytes; the state it resumes from is cursor, plus
the window's position, produced count, and remaining length.
Types
struct
Command
src
§5 — one command's lengths and its distance class.
Fields
insert_length: u32
The insert length: literals to read before the copy.
copy_length: u32
The copy length, 2..16779333.
implicit_distance: bool
§5 — "If the insert-and-copy length code is between 0 and 127, the distance code of the command is set to zero (the last distance reused)": no distance element follows.
distance_context: u2
§7.2 — the distance context ID from the copy length: "0, 1, 2, and 3 for copy lengths 2, 3, 4, and more than 4".
struct
Blocks
src
§6 — the three categories' block-switch state for one meta-block: the (previous, current) type pair per category and the current block's remaining symbol count. "The previous and current block types are initialized to 1 and 0, respectively, at the end of the meta-block header."
Fields
types: [3][2]u16
[category][0] is the previous block type, [category][1] the
current.
counts: [3]u32
The remaining symbol count of the current block, from the header's
first count or a switch's count (§6, §10).
Functions
The header's first counts: BLEN = 16777216 for a single-type category
(§10), so its count never reaches zero within a meta-block.
struct
State
src
The state that spans a meta-block's commands and, for the ring, the stream: §4's four-distance ring, "initialized ... at the beginning of the stream ... and it is not reset at meta-block boundaries", and the distance tables the current meta-block's NPOSTFIX/NDIRECT derive.
Fields
Constants
A stream state before its first meta-block: the §4 ring seed and empty distance tables.
Functions
pub fn beginMetaBlock(self: *State, header: *const frame.Header) void
src
§4 — derive this meta-block's distance tables from NPOSTFIX and
NDIRECT (§3.3's alphabet size, 16 + NDIRECT + (48 << NPOSTFIX)).
The four-distance ring is stream-scoped and is never reset.
struct
Window
src
The window a command stream decodes into. The decoded bytes are the match
history (§8), so a match reads back from what this already holds.
more
The one-shot's window is linear: bytes is the target prefix, pos the
linear position, and produced the same number. The streaming reader's is
a ring of 1 << window_wbits bytes: pos is the ring index of the next
output byte and produced keeps counting past the wrap, so it — not pos
— is what §8's window bound and the dictionary class compare against.
Fields
bytes: []u8
The history and the room. pos <= bytes.len always; the streaming
reader flushes and wraps when pos == bytes.len.
pos: usize
The index in bytes of the next output byte.
produced: u64
The stream's produced count.
left: u32
§9.3 — the meta-block's remaining MLEN. Zero when the meta-block is
complete.
bound: u32
§9.1 — the stream's window size, (1 << WBITS) - 16.
struct
Cursor
src
The command stream's state across step calls: the block switches (§6)
and the command in flight, with how much of its insert and copy are left.
decodeMetaBlock runs it to completion in one call; the streaming reader
runs it in bounded steps as its ring makes room.
Fields
blocks: Blocks
command: Command
insert_left: u32
Insert bytes of command still to write.
copy_left: u32
Copy bytes of command still to write.
distance: u32
The copy's resolved distance (§4, §8).
word: [dictionary.scratch_len]u8
§8 — the transformed word in flight and how much of it is out. The
word is built here, not on the stack, because a ring can run out of
room mid-word.
word_left: u32
word_written: u32
phase: Phase
Functions
A cursor at the first command of the meta-block those blocks describe:
no insert, copy, distance, or word in flight.
Types
module
context
src
The context models (§7.1, §7.3): the four modes and the two context
maps.
Constants
pub const max_block_types = 256
src
§9.2 — the 1..11-bit count code's ceiling: a meta-block can declare up to 256 block types, and the modes array and context maps are sized for it.
value
error{
/// §7.3 — "If a run length would result in more lengths in total than
/// the size of the context map, then the stream should be rejected as
/// invalid."
ContextMapRepeat,
}§7.3 — the context-map layer's refusal.
Functions
§9.2 — the context modes: two bits per literal block type, in block-type order.
pub fn readMap(
comptime Bits: type,
br: *Bits,
tree: *huffman.ContextMapTree,
values: []u8,
num_trees: u16,
) (Bits.ErrorSet || huffman.Error || Error)!void
src
§7.3 — read one context map into values. num_trees is the map's
NTREES (the header's count, 2 or more); tree receives the map's own
prefix code, and values.len is the map's size (64 × NBLTYPESL for
literals, 4 × NBLTYPESD for distances).
The values are the tree indexes of the map, in [0, num_trees - 1] — the alphabet size bounds them, so no index check is needed downstream.
Types
struct
Arena
src
The context-model state of one meta-block: the context mode of every
literal block type and the two context maps. The maps are indexed by
64 * block_type + cid for literals and 4 * block_type + cid for
distances (§7.3).
Fields
modes: [max_block_types]Mode
§9.2 — the context mode of each literal block type.
literal_map: [64 * max_block_types]u8
§7.3 — CMAPL: 64 entries per literal block type.
distance_map: [4 * max_block_types]u8
§7.3 — CMAPD: 4 entries per distance block type.
module
dictionary
src
The static dictionary (§8): the 122,784-byte word table and its 121
transforms.
Constants
§8, Appendix A — DICT: "an array of bytes", 122,784 of them, the words a static dictionary reference names.
pub const min_word_len = 4
src
§8 — "The copy length for a static dictionary reference must be between 4 and 24": the base word lengths the table covers.
pub const max_word_len = 24
src
pub const scratch_len = 38
src
§8 — "a buffer of 38 bytes is sufficient to store any transformed words (counting a terminating zero byte)": the largest base word plus the largest prefix + suffix plus one. The terminator byte is not written; the returned slice carries the length.
pub const max_transform_id = data.transforms.len - 1
src
§8 — the largest valid transform id: "If transform_id is greater than 120 ... the compressed stream should be rejected as invalid".
value
error{
/// §8 — "If transform_id is greater than 120 ... the compressed stream
/// should be rejected as invalid." The reference reports it as
/// `FORMAT_TRANSFORM`, the same name an emptied word's guard uses (the
/// caller applies that guard, which needs the distance).
BadTransform,
}This layer's refusal.
Functions
pub fn transformedWord(
scratch: *[scratch_len]u8,
word_id: u32,
length: u32,
) Error![]const u8
src
§8 — the transformed word for a static dictionary reference. word_id is
distance - (max allowed distance + 1) and length the copy length,
4..24 (the caller's §8 check). The base word is
DICT[DOFFSET[length] + index * length ..] with index = word_id % NWORDS[length], and the transform is word_id >> NDBITS[length].
The result is written into scratch and returned as a slice of it.
error.BadTransform when the transform id is above 120.
module
distance
src
The distance layer (§4): the four-distance ring and the special codes.
Constants
pub const max_window_size: u32 = (1 << 24) - 16
src
§9.1 — the largest window a stream can declare, (1 << 24) - 16: the
bound on any distance the ring can hold, because only window references
are pushed.
value
error{
/// §4 — "If a special distance symbol resolves to a zero or negative
/// value, the stream should be rejected as invalid."
BadDistance,
}§4's refusals.
Functions
§4 — a special code's distance. error.BadDistance when the result is
zero or negative ("the stream should be rejected as invalid").
Types
struct
Ring
src
§4 — the ring of the four last distances, [0] fourth-to-last through
[3] last. "The ring buffer of the four last distances is initialized by
the values 16, 15, 11, and 4".
Fields
last: [4]u32
The distances, oldest first: the last distance is last[3].
Constants
§4's initial ring: 16, 15, 11, and 4, oldest first.
Functions
§4 — push a window reference. Symbol 0 and dictionary references are never pushed (the caller excludes them).
The distance index places back: 3 is the last distance, 2 the
second-to-last, 1 the third-to-last, 0 the fourth-to-last.
struct
Tables
src
§4's per-meta-block distance tables, derived from NPOSTFIX and NDIRECT:
the extra-bit count and the offset of every code at or above
16 + NDIRECT, so the reconstruction is offset[code] + (dextra << NPOSTFIX). Comptime-sized for the format's largest alphabet
(16 + 120 + (48 << 3) = 520) and filled per meta-block, the
reference's CalculateDistanceLut shape (c/dec/decode.c).
Fields
npostfix: u3
§4 — NPOSTFIX, 0..3.
extra_bits: [huffman.max_distance_alphabet_size]u5
§4 — the extra bits of each code; 0 for the direct codes and unused below 16.
offset: [huffman.max_distance_alphabet_size]u32
§4 — the offset of each code: the reconstruction adds the extra bits shifted by NPOSTFIX. The direct codes' offsets are their distances (1..NDIRECT).
Constants
value
.{
.npostfix = 0,
.extra_bits = @splat(0),
.offset = @splat(0),
}Tables before the first meta-block derives them: NPOSTFIX 0 and empty code entries.
Functions
Fill the tables for §3.3's declared alphabet size,
16 + NDIRECT + (48 << NPOSTFIX): the NDIRECT direct codes first
(no extra bits), then the extra-bit codes a postfix group at a time.
§4 — the distance of an extra-bit or direct code: "distance = ((offset
- dextra) << NPOSTFIX) + lcode + NDIRECT + 1" with
offsetand the postfix folded in.
module
frame
src
The stream header and the meta-block ladder (§9.1, §9.2), with the
compressed meta-block header's completion.
Constants
value
error{
/// `§9.1` — WBITS is the invalid pattern 0010001.
BadWindowBits,
/// `§9.2` — the metadata meta-block's reserved bit is set.
ReservedBit,
/// `§9.2` — MNIBBLES > 4 with an all-zero last nibble.
ExuberantNibble,
/// `§9.2` — MSKIPBYTES > 1 with an all-zero last byte.
ExuberantMetaNibble,
}Everything the framing layer reports: the bit reader's own refusals, this
layer's names, and the tree and context layers' names. The names match
decompress's header and ladder rows.
Functions
pub fn readStreamHeader(comptime Bits: type, br: *Bits) Errors(Bits)!StreamHeader
src
§9.1 — read WBITS. The 1..7-bit code is 0 for 16, 0011..1111
(read low bit first) for 18..24, 0000001 for 17, and
0100001..1110001 for 10..15; 0010001 "is invalid and must not be
used".
pub fn nextMetaBlock(comptime Bits: type, br: *Bits, header: *Header) Errors(Bits)!?MetaBlock
src
§9.2, §10 — read the next meta-block header. Metadata meta-blocks are
skipped here: they are "not part of either the sliding window or the
uncompressed data", and "not used as context bytes for literals" (§2),
so nothing above this layer sees them. null means the stream ends at
the current position: ISLAST+ISLASTEMPTY, or a metadata meta-block with
ISLAST set, whose zero fill was verified.
A compressed meta-block's header is read into header (§9.2's tail,
§3, §6, §7.3) before this returns; header is untouched by the
other forms.
pub fn readCompressedHeader(comptime Bits: type, br: *Bits, header: *Header) Errors(Bits)!void
src
§9.2's compressed meta-block header, from NBLTYPESL on: the block-type
counts, each interleaved with its block-type tree, block-count tree, and
first block count (§6); NPOSTFIX and NDIRECT (§4); the context modes
(§7.1); NTREESL and the literal context map, NTREESD and the distance
context map (§7.3); and the three tree groups in order — literals,
insert-and-copy lengths, distances (§3).
§9.2 — the 1..11-bit variable-length code shared by NBLTYPESL, NBLTYPESI,
NBLTYPESD, NTREESL, and NTREESD: the values 1..256, "as it appears in the
compressed data, where the bits are parsed from right to left". Returns
the count itself: the wire encodes count - 1, 0 being the single bit 0.
pub fn readBlockCount(
comptime Bits: type,
br: *Bits,
tree: *const huffman.BlockCountTree,
) Bits.ErrorSet!u32
src
§6 — one block count: a symbol from the 26-symbol count alphabet plus
its fixed-width extra bits. The command layer reads the switches' counts
through this too.
Types
struct
StreamHeader
src
§9.1 — the stream header has exactly one field.
Fields
wbits: u5
WBITS, 10..24.
window_size: u32
§9.1 — "window size = (1 << WBITS) - 16": the maximum value of any
non-dictionary reference backward distance (§2), 1,008 bytes to
16,777,200.
enum
Kind
src
The kind of meta-block the ladder found: the two forms that carry
uncompressed data. The empty forms do not produce a value at all —
nextMetaBlock returns null for them.
Fields
uncompressed uncompressed
ISUNCOMPRESSED=1 (§9.2): MLEN bytes of literal data follow at the
next byte boundary. "An uncompressed meta-block cannot be the last
meta-block" (§2).
compressed compressed
The compressed form. Its header is read into the caller's Header
before nextMetaBlock returns, so the position after it is the
meta-block's compressed data (§9.3).
struct
MetaBlock
src
A meta-block header (§9.2), as much as the framing layer reads.
Fields
kind: Kind
mlen: u32
MLEN: the meta-block's uncompressed length, 1..16777216 (§2).
is_last: bool
ISLAST: the stream ends after this meta-block's data. The last
byte's zero fill (§9.3) is the caller's check once the data is
decoded — bits.BitReader.alignToByte — because for a non-empty
meta-block it lies past the data, not in this header.
struct
Header
src
The compressed meta-block header's arena (§9.2's tail, §3, §6,
§7): the parameters, the context models, and the tree region. About
2.6 MiB, so it lives in a caller-owned stack or static object — never a
copy.
Fields
npostfix: u3
§4 — NPOSTFIX, 0..3, and NDIRECT: the 4-bit field left-shifted by
NPOSTFIX (0..120).
ndirect: u8
block_types: [3]u16
§9.2 — NBLTYPESL/I/D: the block-type count of each category.
num_trees: [3]u16
§9.2 — NTREESL/NBLTYPESI/NTREESD: the tree count of each group.
first_block_count: [3]u32
§6 — the first block count of each category. A category with a
single block type has none on the wire: BLEN = 16777216 (§10).
context: context.Arena
§7 — the context modes and the two context maps.
trees: huffman.Trees
§3 — the literal, command, and distance trees.
module
prefix
src
The prefix codes (§3): both tree forms and the canonical decode tables.
Constants
pub const literal_alphabet_size = 256
src
§3.3 — the alphabet sizes. Distance alphabets are dynamic: 16 special
codes, NDIRECT direct codes, and 48 code slots per NPOSTFIX bit (max 520
at NPOSTFIX=3, NDIRECT=120). Block-type and context-map alphabets are
dynamic too; these are their storage ceilings, max_trees and the
256-value block-type ceiling plus the two extra symbols.
pub const command_alphabet_size = 704
src
pub const block_count_alphabet_size = 26
src
pub const max_distance_alphabet_size = 16 + 120 + (48 << 3)
src
pub const max_block_type_alphabet_size = 256 + 2
src
pub const max_context_map_alphabet_size = max_trees + 16
src
Trees per tree category: the format's ceiling (§9.2's NBLTYPESI, NTREESL, and NTREESD count to 256), so every stream fits. brotli 1.2.0 writes more than 64 literal trees at q4 to q9 on inputs of a megabyte, and more than 64 distance trees on larger ones.
value
error{
/// §3.4 — a simple code's symbol is at or past the alphabet size.
SimpleHuffmanAlphabet,
/// §3.4 — a simple code repeats a symbol.
SimpleHuffmanSame,
/// §3.5 — the code-length code is not a complete prefix code.
BadCodeLengthCode,
/// §3.5 — the code-length sequence breaks a rule: the Kraft sum is not
/// 32768, a repeat overruns the alphabet, or the set would need more
/// table than the format's proven ceiling.
BadHuffmanCode,
}§3.4, §3.5 — the prefix-code layer's refusals.
pub const LiteralTree = Tree(literal_alphabet_size)
src
§3.3's fixed alphabets and the capped dynamic ones.
pub const CommandTree = Tree(command_alphabet_size)
src
pub const DistanceTree = Tree(max_distance_alphabet_size)
src
pub const BlockTypeTree = Tree(max_block_type_alphabet_size)
src
pub const BlockCountTree = Tree(block_count_alphabet_size)
src
pub const ContextMapTree = Tree(max_context_map_alphabet_size)
src
Functions
pub fn readTree(
comptime T: type,
comptime Bits: type,
br: *Bits,
tree: *T,
alphabet_size: u16,
) (Bits.ErrorSet || Error)!void
src
§3 — read one prefix code description: the simple form (§3.4), the
complex form (§3.5), and the table build. alphabet_size is the
declared alphabet — 256 for literals, 704 for insert-and-copy lengths,
NBLTYPES + 2 for block types, NTREES + RLEMAX for context maps, and
16 + NDIRECT + (48 << NPOSTFIX) for distances — and must fit the tree
type's bound.
Types
type fn
Tree
src
pub fn Tree(comptime bound: usize) type
A canonical prefix-code decode table (§3.2) for alphabets of at most
bound symbols, built by build from a length-per-symbol slice. The
declared alphabet size is the slice's length, so the storage bound and
the §3.4 symbol-width rules are independent.
Fields
root: [1 << root_bits]Entry
The primary table, indexed by the next root_bits wire bits.
sub: [table_size - (1 << root_bits)]Entry
Subtables, in first-use order; sub_used entries are live.
sub_used: u16
Live entries in sub.
single: ?u16
§3.4, §3.5 — the single zero-length-code symbol: decoding it
consumes no bits and returns it. null for a normal tree.
Constants
pub const alphabet_size = bound
src
The largest declared alphabet this instantiation can hold.
Functions
Build the table from lens: the code length of each symbol in
symbol order, 0 meaning the symbol does not occur (§3.2).
lens.len is the declared alphabet size, at most bound.
more
error.BadHuffmanCode when lens is not a complete prefix code
— §3.5: "the sum of (32768 >> code length) over all the non-zero
code lengths ... must be equal to 32768" — or when the two-level
table would exceed the storage: no conformant code-length set
can, the storage is the reference's proven ceiling, but the check
is what makes the region a hard bound rather than a hope. The
wire path (readComplexTree's code_space accumulator) refuses a
bad set first, so a caller of this public entry gets the refusal
rather than a table built from an over- or under-subscribed set.
Decode one symbol (§3.2). The caller spells out the bit source:
a type with peek, take, and an ErrorSet, such as this
package's bits.BitReader or the streaming reader's bit source.
The peek can read padding; every consume is a strict take, so
a starved decode is error.Truncated.
pub inline fn decodeRoot(
self: *const Self,
comptime Bits: type,
br: *Bits,
) Bits.ErrorSet!?u16
src
The root-table half of decode (§3.2): the symbol, or null
when the peeked code runs past root_bits — the caller's
fallback is decodeSubtable (or the plain decode). Split out
for hot loops that keep their bit source in a local the cold
path must not escape (the command layer's literal run).
pub fn decodeSubtable(self: *const Self, comptime Bits: type, br: *Bits) Bits.ErrorSet!u16
src
The subtable half of decode, outlined: codes longer than
root_bits are the rare path, and keeping it out of the inlined
fast path keeps the hot loop's register pressure to the root
peek-and-take. Re-peeks the root bits decodeRoot left
unconsumed.
struct
Trees
src
One meta-block's tree region: max_trees trees in each tree
category, the three block-type and block-count trees of §6, and the
context-map tree of §7.3 (the literal map's, then the distance map's).
About 2.6 MiB: a caller-owned stack or Buffer object, never a copy.
Fields
literal: [max_trees]LiteralTree
NTREESL literal trees.
command: [max_trees]CommandTree
NBLTYPESI insert-and-copy trees, one per command block type.
distance: [max_trees]DistanceTree
NTREESD distance trees.
block_type: [3]BlockTypeTree
One block-type tree per block category (L, I, D).
block_count: [3]BlockCountTree
One block-count tree per block category (L, I, D).
context_map: ContextMapTree
The context-map tree, reused by the literal and distance maps.
struct
Buffer
src
The state one decode threads through the layers: the current meta-block's
header (§9.2's tail — the parameters, the context models, and the tree
region) and the command stream's state (§4's four-distance ring,
"initialized ... at the beginning of the stream ... not reset at
meta-block boundaries", plus the distance tables each meta-block's
NPOSTFIX and NDIRECT derive).
more
About 2.6 MiB, nearly all of it the tree region (256 trees in each
category, the format's ceiling). decompressBuffered and
decompressCounted keep it in one the caller places, in static or heap
memory; decompress puts one on the stack. Its contents need no
initialization and are unspecified after a call. The streaming Reader
keeps the same two fields, its header arena in its own Buffer.
Fields
struct
Decompressed
src
What decompressCounted decoded: the bytes it wrote to target, and the
bytes of source the stream took, through its last byte.
Fields
target_len: usize
source_len: usize
module
encode
src
One-shot compression: compress, maxCompressedLength, and the
encoder's Options (the reference's q3 class).
Constants
pub const max_num_delayed_symbols = 0x2FFF
src
The reference's MAX_NUM_DELAYED_SYMBOLS: below the block-split
qualities, the encoder buffers at most this many literals-and-commands
before flushing a meta-block.
pub const max_simple_distance_alphabet_size = 140
src
The reference's MAX_SIMPLE_DISTANCE_ALPHABET_SIZE: the distance
histogram's scan length (NPOSTFIX 0, NDIRECT 0, the 62-bit large-window
maximum) — the reference scans 140 entries and declares 64.
pub const distance_alphabet_size = 16 + 48
src
§4's distance alphabet at NPOSTFIX 0 and NDIRECT 0:
16 + NDIRECT + (48 << NPOSTFIX).
value
error{
/// `target` cannot hold the stream.
BufferTooSmall,
}The one-shot encoder's errors.
pub const max_commands = max_num_delayed_symbols + (1 << 14) / 4 + 1
src
The delayed-command buffer's cap: the reference flushes at
max_num_delayed_symbols symbols, and one 16-KiB input block can add at
most one command per four bytes (every match is at least four bytes long)
on top of that, plus the flush's insert-only command.
pub const bucket_entries = match.bucket_size
src
The reference's MaxHashTableSize-independent H3 bucket count: the
table is always 1 << 16 entries, whatever the input's size.
pub const input_block_size = 1 << 14
src
The input block size: the reference's lgblock is 14 below the
block-split qualities, so it feeds the matcher 16-KiB blocks.
The emission's failures: the one-shot's target running out of room (the sizing pass proves it will not, before the first byte) and the streaming sink's output failing.
Functions
pub fn maxCompressedLength(input_len: usize) usize
src
The largest stream compress can write for an input_len-byte input:
the q3 class's worst case, not §11.1's trivial-compressor bound.
more
Every meta-block is either stored uncompressed or kept compressed only
when it is no more than four bytes larger than its input (encode.c's
bytes + 4 < (*storage_ix >> 3) rollback rule), so a meta-block costs at
most five bytes of header beyond its input. Every meta-block but the last
holds at least one full 16 KiB input block, so an N-byte input has at
most 1 + (N >> 14) meta-blocks; add the one-byte stream header and the
one-byte empty final block. §11.1's N + 3 * (N >> 16) + 5 is the
trivial compressor's bound (64 KiB blocks, a 3-byte header each) and is
too small for this class: brotli -q 3 emits N + 11 on a 128 KiB
adversarial input.
One-shot encode: one stream, header through last byte. target is a cap;
the return value is the compressed length. Nothing is allocated, and no
byte past the returned length is written.
more
Byte-identical to the pinned reference CLI's file form at brotli -q 3
with the window sized to the input (the CLI's own automatic-window rule),
and to the reference library's one-shot at the same quality and window.
The one divergence is the empty input: the reference library returns the
two-byte 06 shortcut, while the CLI's file form (the pin) writes the
window header plus the empty last meta-block.
Stack: the 256-KiB bucket table, the delayed-command buffer, and the tree-build scratch are comptime locals — about 550 KiB. Give encoding threads 1 MiB or more.
pub fn windowBitsFor(input_len: usize) u6
src
The CLI's automatic window (c/tools/brotli.c): the smallest lgwin in
10..24 whose §9.1 window bound (1 << lgwin) - 16 holds the whole input.
This is the pin the one-shot is byte-identical to.
pub fn maxMetablockSize(lgwin: u6) usize
src
The reference's MaxMetablockSize: 1 << min(ComputeRbBits, 24) where
ComputeRbBits is 1 + max(lgwin, lgblock).
pub fn storeWindowBits(w: *BitWriter, lgwin: u6) EmitError!void
src
§9.1's stream header: the lgwin 1..7-bit code (EncodeWindowBits).
Types
module
match
src
The matcher: the q3 hasher, the greedy scan, and the command record.
Constants
pub const bucket_bits = 16
src
The number of bucket-table entries: the H3 bucket bits are 16.
pub const bucket_size = 1 << bucket_bits
src
The hash reads five bytes (HASH_LEN 5).
pub const insert_base = …
src
value
[24]u32{
0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26,
34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594,
}§5's insert-length bases (kBrotliInsBase).
pub const insert_extra = …
src
value
[24]u5{
0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24,
}§5's insert extra-bit counts.
value
[24]u32{
2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18,
22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118,
}§5's copy-length bases (kBrotliCopyBase).
pub const copy_extra = …
src
value
[24]u5{
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24,
}§5's copy extra-bit counts.
Functions
pub fn log2FloorNonZero(n: usize) u32
src
The reference's Log2FloorNonZero.
pub fn insertLengthCode(insertlen: usize) u16
src
The reference's GetInsertLengthCode.
pub fn copyLengthCode(copylen: usize) u16
src
The reference's GetCopyLengthCode.
pub fn lengthCode(insertlen: usize, copylen: usize, use_last_distance: bool) u16
src
The reference's GetLengthCode.
pub fn prefixEncodeCopyDistance(distance_code: usize) struct { code: u16, extra: u32 }
src
The reference's PrefixEncodeCopyDistance at NPOSTFIX 0 and NDIRECT 0:
§4's distance symbol (the low 10 bits of the result) and its extra bits
(the high 6 bits are the extra-bit count).
pub fn initInsertCommand(insertlen: usize, out: *Command) void
src
The reference's InitInsertCommand: an insert-only command, whose copy is
ignored by §9.3's last-command rule. The copy length code is 4 (the
shortest real copy) so the code is a valid table position.
Types
struct
Window
src
The input history the matcher searches, addressed by absolute stream
position. bytes is the ring (or, for the one-shot, the input itself)
and mask maps a position to its index; the one-shot passes an all-ones
mask, so positions index the input directly.
Fields
Functions
The byte at position. Callers guarantee position is below the
current block's end.
struct
SearchResult
src
The reference's HasherSearchResult: the best candidate findLongestMatch
found. len_code_delta is always zero at this class (no dictionary
matches), and is kept because the command's copy-code math reads it.
Fields
struct
Hasher
src
The q3 hasher's state: the bucket table, whose entries are absolute
positions (the reference's uint32_t).
Fields
buckets: []u32
bucket_size entries, owned by the caller; zero at the stream's
start, and the zero reads as "position 0", which the reference's
zeroed table does too.
Functions
The reference's Prepare: zero the whole table. (Its partial-prepare
shortcut for one-shot inputs only skips buckets no lookup can read,
so the effective state is the same.)
The reference's StitchToPreviousBlock: the three bytes before the
block could not be hashed before it, because they need both sides.
struct
Command
src
One command of the stream: the reference's Command, unpacked into the
fields the emission reads.
Fields
cmd_prefix: u16
§5's insert-and-copy length code, 0..703.
dist_prefix: u16
§4's distance symbol (low 10 bits) and extra-bit count (high 6).
insert_len: u32
Literals to insert before the copy.
copy_len_code: u32
The copy code length — the produced length plus the copy-code delta. The delta is zero at this class (no dictionary matches).
copy_len: u32
The copy's produced length.
dist_extra: u32
§4's distance extra bits.
struct
Commands
src
The delayed commands of one meta-block: the reference's commands_ array
with its num_commands_, num_literals_, and the pending literal run
(last_insert_len_).
Fields
buffer: []Command
len: usize
literals: usize
last_insert_len: usize
Literals after the last command, without a command of their own; the
flush turns them into one (InitInsertCommand).
Functions
An empty command buffer over buffer.
struct
Matcher
src
The matcher: the hasher, the window it searches, the window's bit width, and §4's four-distance ring.
Fields
hasher: Hasher
window: Window
lgwin: u6
The stream's lgwin, 10..24: the window bound is (1 << lgwin) - 16
(§9.1).
dist_cache: [4]i32
§4's ring, most recent first: "initialized by the values 16, 15, 11, and 4 (i.e., the last four distances used)". The reference encoder stores them newest-first, so index 0 is the last distance (4) and index 3 the fourth-to-last (16) — the same order the decoder's ring resolves symbol 0 through.
Functions
A matcher over hasher and window: the §4 ring seeded 4, 11, 15, 16.
pub fn findReferences(
self: *Matcher,
position: usize,
num_bytes: usize,
commands: *Commands,
) void
src
The reference's CreateBackwardReferences: scan
[position, position + num_bytes), appending commands.
more
The scan cascade stays in one function on purpose (the house's
documented deviation, like snappy's encodeBlock and zstd's
scanBlock): it is one labeled control flow — the greedy accept, the
one-step lazy re-check, and the sparse-search jump — and splitting it
would scatter the loop's state (insert_length, the score, the
heuristic cursor) across helpers. Every pure piece is extracted:
hashBytes, findLongestMatch, findMatchLength, store,
storeRange, computeDistanceCode, and initCommand.
union
Sink
src
pub const Sink = union(enum)
Where a bit writer's whole bytes go.
Fields
slice: []u8
The one-shot's target. The sizing pass has already proved every meta-block fits, so the writes are asserted, never checked.
stream: Stream
The streaming Writer: a bounded window flushed to output.
count: void
Counting only: the sizing pass, which must count exactly the bits the writing pass emits.
Functions
The bytes left in a slice sink, if this is one: the streaming and counting sinks have no cap.
Types
struct
BitWriter
src
§1.5.1's bit writer: integers pack least significant bit first into bytes
in increasing order, and the whole bytes go to sink. The writer counts
the same bits in every mode, so the sizing pass and the writing pass
agree byte for byte.
Fields
sink: Sink
bit_pos: usize
Bits appended so far, the pending partial byte included: the wire position.
written: usize
Whole bytes handed to the sink.
bits: u64
The pending bits, LSB first.
pending_len: u7
The pending bit count, below eight between writes.
Functions
A writer at the start of its stream, with no pending bits.
A counting writer: no bytes, the same bit arithmetic.
Append n bits of value, least significant first (§1.5.1).
§9.2's zero fill: pad to the next byte boundary.
The number of whole bytes on the wire.
Types
struct
Scratch
src
The per-meta-block scratch: the three histograms, the three depth/bit tables, the builder's node pool, and the code-length serialization.
Fields
literal_histo: [256]u32
command_histo: [704]u32
distance_histo: [max_simple_distance_alphabet_size]u32
literal_depth: [256]u8
literal_bits: [256]u16
command_depth: [704]u8
command_bits: [704]u16
distance_depth: [max_simple_distance_alphabet_size]u8
distance_bits: [max_simple_distance_alphabet_size]u16
tree: [2 * 704 + 1]huffman.Node
The builder's node pool (MAX_HUFFMAN_TREE_SIZE).
tree_symbols: [704]u8
§3.5's run-length serialization of a depth sequence.
tree_extra_bits: [704]u8
code_length_depth: [18]u8
code_length_bits: [18]u16
Constants
value
.{
.literal_histo = @splat(0),
.command_histo = @splat(0),
.distance_histo = @splat(0),
.literal_depth = @splat(0),
.literal_bits = @splat(0),
.command_depth = @splat(0),
.command_bits = @splat(0),
.distance_depth = @splat(0),
.distance_bits = @splat(0),
.tree = undefined,
.tree_symbols = undefined,
.tree_extra_bits = undefined,
.code_length_depth = undefined,
.code_length_bits = undefined,
}Scratch before a meta-block: zeroed histograms and depths, with the builder's pool left undefined until the tree pass fills it.
struct
State
src
One stream's encoder state: the reference's BrotliEncoderState reduced
to what the q3 class reads. The one-shot drives it over the input itself;
Writer.zig drives it over a ring.
Fields
matcher: match.Matcher
commands: match.Commands
saved_dist_cache: [4]i32
The distance ring at the last meta-block boundary: an uncompressed
meta-block's symbols never execute, so the ring rolls back
(the reference's saved_dist_cache_).
writer: BitWriter
The bit writer. It lives by value here so neither driver has to keep a self-pointer honest across a move.
scratch: *Scratch
input_pos: usize
The input's absolute size: one past the last byte written.
last_processed_pos: usize
One past the last position the matcher has seen.
last_flush_pos: usize
The start of the pending meta-block.
max_metablock_size: usize
The largest meta-block this window can emit.
Functions
pub fn init(
matcher: match.Matcher,
commands: match.Commands,
writer: BitWriter,
scratch: *Scratch,
max_metablock_size: usize,
) State
src
A stream state at position zero, with the §4 distance-ring seed.
pub fn remainingInputBlock(self: *const State) usize
src
The reference's RemainingInputBlockSize: how much input the matcher
can still take before the current block is full.
Feed len bytes of input, which the caller has already made visible
in the window, and run the reference's EncodeData when it would:
on a full input block, on force_flush, or at the stream's end.
module
Reader
src
Streaming decompression: Reader, its Buffer, and streamAll.
Constants
pub const default_window_wbits: usize = 24
src
The default window cap, 24 — the format's maximum (§9.1). The
reference CLI's pipe form emits WBITS 24 for every stream it writes,
and its file form 10..19 by input size, so 24 decodes both
unconfigured; Buffer(22) (6.6 MiB rather than 18.6) decodes the file
family only.
pub const DefaultBuffer = Buffer(default_window_wbits)
src
Buffer(default_window_wbits): a 16 MiB ring plus the tree region, about
18.6 MiB — keep it in static or heap storage.
value
error{
/// `§9.1` — WBITS is the invalid 0010001 pattern. The one-shot's name for
/// the same wire pattern; at a start position the reader reports
/// `BadStreamStart` instead (the walk's name for bytes that cannot begin
/// a stream).
BadWindowBits,
/// The input ended before the stream did.
Truncated,
/// `§9.2` — the metadata meta-block's reserved bit is set.
ReservedBit,
/// `§9.2` — MNIBBLES > 4 with an all-zero last nibble.
ExuberantNibble,
/// `§9.2` — MSKIPBYTES > 1 with an all-zero last byte.
ExuberantMetaNibble,
/// Nonzero fill bits where the format requires zeros (`§9.2`, `§9.3`).
BadPadding,
/// `§3.4` — a simple code's symbol is at or past the alphabet size.
SimpleHuffmanAlphabet,
/// `§3.4` — a simple code repeats a symbol.
SimpleHuffmanSame,
/// `§3.5` — the code-length code is not a complete prefix code.
BadCodeLengthCode,
/// `§3.5` — a code-length sequence breaks the format's rules.
BadHuffmanCode,
/// `§6`, `§9.3` — a block count, or the meta-block length accounting.
BadBlockLength,
/// `§7.3` — a context map's zero-run overruns the map.
ContextMapRepeat,
/// `§4` — a special distance code resolves to zero or less.
BadDistance,
/// `§8` — a transform id above 120, or a word the transform empties.
BadTransform,
/// `§8` — a dictionary reference's word length is outside 4..24.
BadDictionary,
/// `§9.1` — the stream's WBITS is above the instantiated `window_wbits`.
/// Reported once the header is parsed, before any meta-block byte.
WindowTooLarge,
/// The input at a start position cannot begin a stream (`§9.1`'s invalid
/// 0010001 pattern, the reference family's large-window marker). The
/// walk's name: `streamAll` reads a tail as the next stream, and this is
/// why it refuses one.
BadStreamStart,
/// A contiguous request (`peek`, `take`, ...) is larger than the ring can
/// hold at the consumer's position. A consumer can cause it, so it is an
/// error and not an assert.
StreamTooLong,
/// The input reader failed with `error.ReadFailed`.
ReadFailed,
/// The clean end of the stream. The interface reports it as
/// `error.EndOfStream`; it is never recorded in `err`.
EndOfStream,
}The reader's error set: the one-shot decoder's DecompressError without
BufferTooSmall (the ring is the caller's buffer, so no decode can
outgrow it), plus the names this layer adds. err holds one of these once
state == .failed; the Io.Reader interface itself reports only
error.ReadFailed or error.EndOfStream.
Functions
pub fn init(comptime window_wbits: usize, input: *Io.Reader, buffer: *Buffer(window_wbits)) Reader
src
Wrap input (one brotli stream) with buffer for the history ring and
the meta-block trees. window_wbits is the largest WBITS the reader
accepts, and buffer must be a Buffer(window_wbits), which the compiler
checks at the call. input needs a buffer of at least four bytes (the
widest field the bit reader assembles is 24 bits, and the peek table reads
eight at a time). init reads nothing from input and allocates nothing.
more
Read through &r.reader (stream, the read family, the peek
family). Once the stream's last byte is decoded, reads return
error.EndOfStream. A malformed stream or a failing input returns
error.ReadFailed, and so does every later read, with the detail in
err. The reader consumes input exactly through the stream's last byte
and leaves any later bytes unread.
pub fn streamAll(
comptime window_wbits: usize,
in: *Io.Reader,
out: *Io.Writer,
buffer: *Buffer(window_wbits),
) Io.Reader.StreamRemainingError!usize
src
Decode every stream in in into out through buffer, and return the
total number of bytes written. The output is the concatenation of the
streams. Each stream is decoded as init describes, starting where the
previous one ended. An input that holds nothing at all decodes to zero
bytes (the walk's clean end); bytes at a start position that cannot begin
a stream fail error.ReadFailed (the cause is BadStreamStart). in
needs a buffer of at least four bytes (see init); Io.Reader.fixed
always qualifies. Does not allocate.
Types
type fn
Buffer
src
pub fn Buffer(comptime window_wbits: usize) type
The caller-owned decode buffer: the history ring plus the meta-block
header arena. window_wbits is 10..24 (§9.1), and init reads the
window cap from this exact type, so the buffer and the cap cannot
disagree.
Fields
ring: [1 << window_wbits]u8
§9.1 — the (1 << window_wbits)-byte history ring. It is also
the region the reader serves decoded bytes from, so the consumer
must keep up within a window's worth of output; the reader stops
(and later wraps) when the ring fills.
header: frame.Header
§9.2 — the meta-block header arena: the context models, the two
maps, and the tree region (the comptime tree cap).
module
Writer
src
Streaming compression: Writer, its Buffer, and streamAll — the
encoder's q3 class over an Io.Writer.
Constants
pub const default_window_wbits: usize = 22
src
The reference encoder library's default window: 22, 4,194,288 bytes.
pub const DefaultBuffer = Buffer(default_window_wbits)
src
Buffer(22): about 8.7 MiB. Keep it in static or heap storage.
Functions
pub fn init(
comptime window_wbits: usize,
output: *Io.Writer,
buffer: *Buffer(window_wbits),
) Writer
src
Start a brotli stream into output, accumulating input in buffer and
searching a window_wbits window. Write through &w.writer, then call
finish.
Stack: Buffer(window_wbits) is MiB-scale and lives in the caller's
storage; the writer itself is KiB-scale.
Complete the stream: process the buffered input, write the last
meta-block, flush the output window, and flush output. The stream is
complete only after this call, and the writer is unusable afterwards.
Returns error.WriteFailed if output fails; a writer that already
failed or already finished returns error.WriteFailed too, so a
truncated stream is never reported as complete.
pub fn streamAll(
comptime window_wbits: usize,
in: *Io.Reader,
out: *Io.Writer,
buffer: *Buffer(window_wbits),
) error{ ReadFailed, WriteFailed }!usize
src
One-call pump: encode every byte of in into one stream on out, using
buffer. Returns the bytes read. error.ReadFailed is an input failure;
error.WriteFailed an output failure.
Types
type fn
Buffer
src
pub fn Buffer(comptime window_wbits: usize) type
The caller-provided buffer for Buffer(window_wbits): the history ring
with its 16-KiB mirror, the q3 bucket table, the delayed commands, the
tree-build scratch, the input staging block, and the compressed-output
window.
Fields
ring: [ringSize(window_wbits) + chunk_len]u8
The ring plus a mirror of the ring's first 16 KiB: a read of up to one input block can run past the ring's end, and the reference's ring keeps those bytes copied there.
hash: [encode.bucket_entries]u32
The q3 bucket table: the reference's H3 is always
1 << 16 entries.
commands: [encode.max_commands]match.Command
The delayed commands of the pending meta-block.
scratch: encode.Scratch
The tree-build scratch.
staging: [chunk_len]u8
The input staging block: the Io.Writer's own buffer region.
out: [out_len]u8
The compressed-output window.
module
flate
src
Raw DEFLATE (RFC 1951): one-shot encode.compress and decode.decompress,
and the streaming Reader and Writer. Caller-owned buffers, no heap
allocation. API: src/flate/README.md. Format:
docs/specs/rfc1951-deflate.txt.
Types
module
encode
src
One-shot compression: compress, maxCompressedLength, and the encoder's
Options and Level.
Constants
pub const history_len = decode.history_len
src
The format's maximum backward match reach: 32768 (§3.2.5, the canonical
constant in decode.zig with the distance tables). The finder's window is
this much history followed by the block, so the cap is structural.
pub const max_match_len = decode.max_match_len
src
§3.2.5 — the longest match a length symbol can declare, 258 (length
code 285). Aliased from decode.zig, the one spelling of the RFC's
length and distance tables.
pub const max_block_size: usize = 65535
src
The encoder's block size: 65535, the stored-block LEN cap (§3.2.4), so any
block can fall back to stored. compress splits input at it; the streaming
Writer emits blocks at it.
pub const FinderTable = [table_size]u32
src
The match-finder table. An entry is the absolute stream position (wrapping
u32) of the newest scanned position with that hash. A stale entry fails
matchCandidate's distance cap, so one table persists across a stream's
blocks with no per-block zeroing. Callers zero it once per stream
(fastmem.set) and prime each block's history at stream_prime_stride.
pub const fixed_literal_codes: [288]Code = …
src
value
blk: {
var codes: [288]Code = undefined;
for (0..144) |i| codes[i] = .{ .bits = wireBits(@intCast(0x30 + i), 8), .len = 8 };
for (144..256) |i| codes[i] = .{ .bits = wireBits(@intCast(0x190 + (i - 144)), 9), .len = 9 };
for (256..280) |i| codes[i] = .{ .bits = wireBits(@intCast(i - 256), 7), .len = 7 };
for (280..288) |i| codes[i] = .{ .bits = wireBits(@intCast(0xC0 + (i - 280)), 8), .len = 8 };
break :blk codes;
}§3.2.6 — the fixed literal/length codes, from the numerals the RFC spells
out: 0-143 are 8 bits, 00110000 through 10111111; 144-255 are 9 bits,
110010000 through 111111111; 256-279 are 7 bits, 0000000 through
0010111; 280-287 are 8 bits, 11000000 through 11000111. Values 286-287
"will never actually occur in the compressed data, but participate in the
code construction", so they are part of the table.
pub const fixed_distance_codes: [32]Code = …
src
value
blk: {
var codes: [32]Code = undefined;
for (&codes, 0..) |*code, i| code.* = .{ .bits = wireBits(@intCast(i), 5), .len = 5 };
break :blk codes;
}§3.2.6 — "Distance codes 0-31 are represented by (fixed-length) 5-bit
codes", so the numeral is the symbol. 30-31 never occur.
pub const finder_origin: u32 = 65535
src
The finder's absolute-position origin: klauspost starts cur at
maxStoreBlockSize, so a zero-initialized slot is out of reach of the
distance cap and can never be a candidate.
Functions
pub fn maxCompressedLength(input_len: usize) usize
src
Worst-case compressed size for input_len bytes:
input_len + 5 * ceil(input_len / max_block_size) + 2. Every block costs at
most 5 bytes of stored-block header beyond its input (§3.2.4), and every
stream ends with a 2-byte empty block. Size target to this before
compress.
The wire bits of a canonical code: §3.2.2 assigns the numeral and
§3.1.1 transmits its MSB first, so the low len bits of the result are
the code in transmission order. (decode.zig's wireBits is the decoder's
half of the same transform.)
pub fn lengthSymbol(length: usize) LengthSymbol
src
§3.2.5 — the length symbol for length (3-258): the merged-alphabet
symbol, its extra-bit count, and the extra-bit value. Code 284's entry
covers 227-258 by the table's own arithmetic, and code 285 overwrites 258
with zero extra bits, which is what the encoder emits: 258 is code 285,
the one code with no extra bits.
pub fn distanceSymbol(distance: usize) DistanceSymbol
src
§3.2.5 — the distance symbol for distance (1-32768) and its extra bits.
pub fn emitStoredBlock(w: *BitWriter, block: []const u8) error{BufferTooSmall}!void
src
§3.2.4 — emit block (at most max_block_size bytes) as a stored block:
BFINAL clear and BTYPE=00, then skip to the next byte boundary, then LEN and
NLEN (u16 little-endian, NLEN the one's complement of LEN) and LEN raw bytes.
error.BufferTooSmall if the target cannot hold it. This is the fallback
that makes maxCompressedLength provable: no block ever exceeds its stored
form.
pub fn writeFinalEmptyBlock(w: *BitWriter) error{BufferTooSmall}!void
src
§3.2.3 — the final empty fixed block every stream ends with: BFINAL=1,
BTYPE=01, end-of-block (03 00 at a byte boundary). One function, so the
one-shot and streaming encoders cannot drift. No data block carries BFINAL,
which is what makes a mid-stream flush safe.
pub fn compressBlockStream(
source: []const u8,
block_start: usize,
block_end: usize,
w: *BitWriter,
table: *FinderTable,
base: u32,
) error{BufferTooSmall}!void
src
Encode source[block_start..block_end] as one block (fixed Huffman, or
stored when that is smaller) through w, for the streaming Writer. A
match can reach back into source[0..block_start], up to 32768 bytes.
table is the Writer's: zeroed once per stream and reused across blocks.
base is the absolute stream position of source[0] (the Writer's window
base). Returns error.BufferTooSmall if w's target cannot hold the block.
pub fn compressBlockStreamLazy(
source: []const u8,
block_start: usize,
block_end: usize,
w: *BitWriter,
finder: *lazy.Finder,
tokens: *dynamic.TokenList,
emitter: *dynamic.BlockWriter,
base: u32,
params: lazy.Params,
prime_dict: bool,
sync: bool,
) error{BufferTooSmall}!void
src
The streaming lazy block encode for the Writer: as
compressBlockStream6, with the lazy finder and params.
pub fn compressBlockStream6(
source: []const u8,
block_start: usize,
block_end: usize,
w: *BitWriter,
finder: *Finder6,
tokens: *dynamic.TokenList,
emitter: *dynamic.BlockWriter,
base: u32,
prime_dict: bool,
sync: bool,
) error{BufferTooSmall}!void
src
The streaming level-6 block encode for the Writer: source is the
window (history followed by the block), block_start/block_end are
window positions, and base is the absolute stream position of
source[0]. prime_dict is true on a stream's first block when the
window's front is a preset dictionary: the tables are seeded by the same
scan klauspost's fillWindow runs over the dictionary's tail.
Returns error.BufferTooSmall if w's target cannot hold the block.
pub fn lazyParams(level: Level, strategy: Strategy) ?lazy.Params
src
The lazy finder's search effort for level, or null for the greedy
levels (1 and 6).
pub fn compress(
source: []const u8,
target: []u8,
options: Options,
) error{BufferTooSmall}!usize
src
Compress source as one raw deflate stream into target and return the
number of bytes written. A target of maxCompressedLength(source.len)
always suffices; a smaller one can return error.BufferTooSmall, leaving
target partly written.
more
options.dict is the stream's preset dictionary or null (§3.2.3); see
Options.
The stream ends with an empty final block (BFINAL, §3.2.3), and every data
block is fixed Huffman, dynamic Huffman, or stored. The same input and
options always produce the same bytes. Allocates nothing; level 1 keeps a
128 KiB match-finder table on the stack, level 6 its two tables (384 KiB),
a 256 KiB token list, and the tree scratch.
Types
module
lazy
src
The lazy levels' match finder: hash chains with lazy match evaluation,
the method RFC 1951 §4 describes. Every position with four bytes ahead
is hashed into a table of chain heads, and each position links to the
previous one with the same hash, so a search walks back through the
candidates, newest first, up to Params.chain of them. A match found at
one position is held while the next position is searched too, and the
longer of the two wins (§4's "lazy match evaluation"): when the next
one is longer, the first position becomes a literal.
more
Positions in the tables are absolute stream positions (wrapping u32),
offset by encode.finder_origin so that a cleared head is out of reach,
as the level-6 finder keeps them. A link is followed only while it goes
strictly back and stays within the 32 KiB window (§3.2.5), and every
candidate's bytes are compared before it is used, so neither a link the
window has slid past nor a wrapped one is ever emitted.
The filtered strategy (Params.min_len above 4) codes short matches as
literals. Data that a predictor has turned into small residuals, such as
PNG's filtered rows, has short repeats everywhere whose literals the
dynamic Huffman code makes cheaper than a length and distance.
Format: docs/specs/rfc1951-deflate.txt
Constants
The shortest match the finder considers: a 4-byte hash.
Functions
pub fn compressBlock(
comptime preset: bool,
comptime windowed: bool,
window: encode.Window(preset),
block_start: usize,
block_end: usize,
w: *encode.BitWriter,
tokens: *dynamic.TokenList,
finder: *Finder,
emitter: *dynamic.BlockWriter,
base: u32,
params: Params,
sync: bool,
) error{BufferTooSmall}!void
src
The lazy scan over one block, window.source's positions
[block_start, block_end), filling tokens, then emitted as one deflate
block through emitter; sync marks the stream's last block. (Smaller
blocks, for codes that follow the data more closely, measured larger on
PNG image data.)
base is the absolute stream position of the window's first byte, and
windowed says the window may have dropped bytes the tables still name
(the streaming Writer).
pub fn prime(
comptime preset: bool,
window: encode.Window(preset),
finder: *Finder,
start: usize,
end: usize,
base: u32,
) void
src
Links every position in [start, end) with four bytes ahead into the
chains: a preset dictionary's, before the first block.
Types
struct
Params
src
One level's search effort.
Fields
chain: u16
The most candidates one search compares.
lazy: u16
A held match at least this long is taken without searching the next position.
nice: u16
A match at least this long ends a search.
good: u16
With a held match at least this long, the next search compares a
quarter of chain.
min_len: u16
Matches shorter than this are coded as literals: min_match, or
more for the filtered strategy.
type fn
Window
src
pub fn Window(comptime preset: bool) type
The finder's window (§3.2.3): the preset dictionary's tail followed by
the stream's own bytes, one conceptual region — the byte after the
dictionary's last is source[0], so a match can start in the dictionary
and continue at the output's start. Positions are window positions: the
dictionary occupies [0, dict.len) and source[i] sits at dict.len + i.
preset is comptime because a stream without a dictionary is the common
case: Window(false) is source alone, and its accessors compile to the
same loads as a bare source (no branch on dict.len in the finder's hot
loops).
Fields
dict: []const u8
The dictionary's last history_len bytes (dictHistory); empty
when the stream has no preset dictionary.
source: []const u8
The stream's own bytes, the window's tail.
Functions
The window position of source[index].
The byte at window position pos.
pub inline fn sourceSlice(self: Self, start: usize, end: usize) []const u8
src
The window's bytes at [start, end). Both positions are inside
the stream's own region (start >= dict.len), so this is a plain
source slice; the finder's blocks and literal runs are always
there.
The 4 bytes at window position pos (§3.2.5's match confirm).
Only a dictionary position can straddle the two regions, and then
by at most 3 bytes.
pub fn matchLength(self: Self, a: usize, b: usize, limit: usize) usize
src
The number of bytes a.. and b.. match, up to limit — all
window positions. b is always in source (the scan runs there);
a can start in the dictionary and cross into the source, where
the dictionary's continuation is the source's start (the
dictionary is conceptually in front of the output). Compares 8
bytes at a time and uses @ctz on the first differing u64 to find
the exact mismatch byte. The caller guarantees a < b and that
b < limit <= dict.len + source.len (the 8-byte loop bounds b,
and a trails it).
struct
LengthSymbol
src
A length symbol ready to emit: the merged-alphabet symbol (257-285), its extra-bit count, and the extra-bit value.
Fields
struct
BitWriter
src
The bit writer (§3.1.1): bits fill a byte from bit 0 up, and a 9th bit
spills into bit 0 of the next byte. bits/bit_count carry the stream's
pending partial byte, which is what lets the streaming Writer emit one
block at a time: a block's bits continue at the previous block's bit
offset.
more
It has exactly two write operations, named for the packing rule each
implements: writeBits for a non-Huffman data element (LSB-of-value first:
block headers, extra bits, stored LEN/NLEN) and writeCode for a Huffman
code (MSB-of-code first; the code tables store the wire bits pre-reversed).
Mixing them up can survive a round trip through this package's decoder if both
sides share the mistake, but every other decoder misreads the stream, which
is why just flate-oracle decodes the encoder's output with python3's zlib.
Fields
target: []u8
pos: usize
Whole bytes written into target.
bits: u64
Pending bits, LSB first: bit 0 is the next bit on the wire.
bit_count: u6
Valid bits in bits (0-63, and below 8 outside writeBits).
Functions
A writer at the start of target, with no pending bits.
Write a data element that is not a Huffman code, LSB-of-value first
(§3.1.1): the block header, extra bits, stored LEN/NLEN. Extra bits
are an ordinary element, so they go out LSB first; §3.2.5's
"most-significant bit first" sentence describes the numeral.
Write a Huffman code, MSB-of-code first (§3.1.1). code carries the
wire bits (see wireBits), never the numeral.
Flush the final partial byte, padded with zero bits.
struct
Finder6
src
The level-6 finder's tables (klauspost's fastEncL6 pair): a 4-byte-hash
table and a 7-byte-hash table with two candidates per slot. 384 KiB,
zeroed once per stream.
Fields
Functions
Zero the tables. An entry of 0 names a position before the window
(finder_origin is above the distance cap), so a cleared slot never
yields a candidate — the sentinel the scan relies on.
enum
Level
src
pub const Level = enum(u8)
The compression levels this encoder implements, named by the zlib scale.
The tag is the level number, so @backingInt spells the CLI's value.
Fields
@"1" @"1" = 1
Fixed-Huffman blocks from the level-1 match finder, or a stored block when that is smaller.
@"6" @"6" = 6
klauspost/compress's level-6 class: the wider two-table greedy finder,
dynamic-Huffman blocks (§3.2.7), and the per-block stored, fixed, and
dynamic dispatch. Byte-identical to klauspost/compress's flate at
level 6 (the pinned module version).
@"7" @"7" = 7
Lazy matching over hash chains (lazy.zig, RFC 1951 §4) with a
short search: dynamic-Huffman blocks from a finder that holds each
match while it searches the next position.
@"9" @"9" = 9
Lazy matching over hash chains with a long search: the smallest output, the slowest level.
Functions
The level for a zlib-scale number, or null when this encoder does
not implement it. Use this at a boundary where the number comes from
outside the type system, such as a config value or a flag; a literal
needs no conversion.
struct
Options
src
Encoder configuration. .{} is the default: level 1.
Fields
level: Level = .@"1"
The compression level. Only the levels in Level are representable.
dict: ?[]const u8 = null
The stream's preset dictionary or null (§3.2.3): history in front
of the stream, which the finder's table is primed from and a match can
reach into. Raw deflate names no dictionary, so the caller vouches for
the bytes on both sides; zlib's FDICT/DICTID is the checked form
(RFC 1950 §2.2). A dictionary longer than 32 KiB contributes only its
last 32 KiB.
strategy: Strategy = .default
How the lazy levels (7 and 9) weigh short matches; levels 1 and 6 ignore it.
module
decode
src
One-shot decompression: decompress and its error set, DecompressError.
Constants
pub const DecompressError = …
src
value
error{
/// `decompress` only: `target` cannot hold the decoded output.
BufferTooSmall,
/// Input ended before the final block completed.
Truncated,
/// BTYPE = 11 is "reserved (error)" (`§3.2.3`).
InvalidBlockType,
/// NLEN != one's complement of LEN (`§3.2.4`).
WrongStoredBlockNlen,
/// A malformed dynamic header (`§3.2.7`): HLIT above 286, HDIST above 30,
/// a repeat code with nothing to repeat or running past the lengths, or an
/// empty precode tree.
InvalidDynamicBlockHeader,
/// Kraft sum > 1 (`§3.2.2`).
OversubscribedHuffmanTree,
/// Kraft sum < 1, beyond the single-1-bit-code case (`§3.2.7`).
IncompleteHuffmanTree,
/// A literal/length tree with no code for 256 (`§3.2.7`).
MissingEndOfBlockCode,
/// A code that decodes to no legal symbol: the unused code of a one-code
/// tree, or a reserved symbol (length symbols 286-287, distance codes
/// 30-31).
InvalidCode,
/// A distance before the start of the history (`§3.2.3`): past the
/// dictionary's first byte (when one is supplied), then past the output's.
InvalidMatch,
}Why a stream failed to decode. decompress returns these directly. The
streaming Reader reports error.ReadFailed through the Io.Reader
interface and records the specific error in Reader.err.
value
error{
OversubscribedHuffmanTree,
IncompleteHuffmanTree,
MissingEndOfBlockCode,
InvalidDynamicBlockHeader,
}The errors build can return (§3.2.2's Kraft rule, §3.2.7's header
rules): a subset of DecompressError, narrow enough that both the one-shot
decoder and the streaming Reader can fold it into their own error sets.
pub const max_match_len: usize = 258
src
§3.2.5 — the longest match a length symbol can declare (length code 285
is 258). The streaming Reader keeps this much room free in its window
before decoding a symbol, and the encoder splits longer matches at it.
pub const history_len: usize = 32768
src
§3.2.5 — the format's maximum backward match reach: distance code 29's
32768. The encoder's window is this much history followed by the block, so
the cap is structural there; here it is the window a preset dictionary is
cut to (a longer one contributes only its last 32 KiB).
pub const length_base = …
src
value
[29]u16{
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27,
31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258,
}§3.2.5 — length code 257-285 bases (index = code - 257). The encoder reads
this and the other three code tables (encode.zig aliases them), so both
sides share one spelling of the RFC's tables.
pub const length_extra = …
src
value
[29]u5{
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
}§3.2.5 — length extra-bit counts (index = code - 257). Code 285 carries
zero extra bits: 258 is its only value.
pub const distance_base = …
src
value
[30]u16{
1, 2, 3, 4, 5, 7, 9, 13, 17, 25,
33, 49, 65, 97, 129, 193, 257, 385, 513, 769,
1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
}§3.2.5 — distance code 0-29 bases.
pub const distance_extra = …
src
value
[30]u5{
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
}§3.2.5 — distance extra-bit counts.
pub const LitDecoder = HuffmanDecoder(288, 15, 11, .literal_length)
src
Decode table for the literal/length alphabet: 288 symbols, codes up to 15
bits, a 10-bit primary table. Symbols 286-287 are reserved (§3.2.6) and
callers reject them.
pub const DistDecoder = HuffmanDecoder(32, 15, 9, .distance)
src
Decode table for the distance alphabet: 32 symbols, codes up to 15 bits, a
9-bit primary table. Codes 30-31 are reserved (§3.2.6) and callers reject
them.
pub const PrecodeDecoder = HuffmanDecoder(19, 7, 7, .precode)
src
Decode table for a dynamic header's code-length (precode) alphabet: 19 symbols, codes up to 7 bits, a 7-bit primary table.
pub const fixed_literal: LitDecoder = …
src
value
blk: {
@setEvalBranchQuota(10_000);
var decoder: LitDecoder = .{};
decoder.build(&fixed_literal_lens) catch |err| @compileError(
"fixed literal table: " ++ @errorName(err),
);
break :blk decoder;
}§3.2.6 — the fixed tables, built once at compile time. Building the
literal table with all 288 lengths is what makes it complete
(152x2^-8 + 112x2^-9 + 24x2^-7 = 1).
pub const fixed_distance: DistDecoder = …
src
value
blk: {
@setEvalBranchQuota(10_000);
var decoder: DistDecoder = .{};
decoder.build(&fixed_distance_lens) catch |err| @compileError(
"fixed distance table: " ++ @errorName(err),
);
break :blk decoder;
}§3.2.6 — the fixed distance table, built at compile time.
Functions
pub fn dictHistory(dict: ?[]const u8) []const u8
src
The history a preset dictionary contributes: its last history_len bytes.
The window is 32 KiB, so a longer dictionary is cut to its tail for
matching (§3.2.3; zlib's deflateSetDictionary uses the tail the same
way) while its identifier still names the whole. null and an empty slice
are both no dictionary.
pub fn decompress(source: []const u8, target: []u8, dict: ?[]const u8) DecompressError!usize
src
Decompress one raw deflate stream from source into target and return
the decoded length. target is a cap, not a size hint: the stream does not
record its decoded length, so size target from what you know about the
data, or stream with Reader. If the output does not fit, returns
error.BufferTooSmall before writing past target. A caller enforcing a
decoded-size limit sizes target from that limit, so the error means the
limit was exceeded and a retry with the same buffer cannot succeed. The
format's expansion ceiling is 1032:1 (§3.2.5: 258 bytes per
length/distance pair, two bits for the pair in a custom tree), so
source.len is no guide to the decoded size.
more
dict is the stream's preset dictionary or null (§3.2.3): the history
in front of the output, which a distance can reach into. Raw deflate names
no dictionary, so the caller vouches for the bytes; zlib's FDICT/DICTID is
the checked form (RFC 1950 §2.2). A dictionary longer than 32 KiB
contributes only its last 32 KiB.
Decoding stops at the first block with BFINAL set; bytes after it in
source are ignored (§3.2.3). A malformed or truncated stream returns the
matching DecompressError, and after any error target can hold a partial
prefix of the output that must not be used. Allocates nothing and uses a few
KiB of stack for the dynamic block's Huffman tables.
pub fn decodeLength(comptime Bits: type, br: *Bits, symbol: u16) Bits.ErrorSet!usize
src
§3.2.5 — read a match length: base + extra, computed without clamping. Code
284 with extra bits 31 is 258, even though the table states 284's range as
227-257, because zlib, Go, and std all decode it that way. symbol is a
length symbol (257-285); Bits is a bit source, as in
HuffmanDecoder.decode.
pub fn decodeDistance(comptime Bits: type, br: *Bits, symbol: u16) Bits.ErrorSet!usize
src
§3.2.5 — read a match distance: base + extra for a distance symbol
(0-29), which is 1-32768.
pub fn readDynamicHeader(
comptime Bits: type,
br: *Bits,
literal: *LitDecoder,
distance: *DistDecoder,
) Bits.ErrorSet!void
src
§3.2.7 — read a dynamic block's header from br and build its literal/length
and distance tables: HLIT, HDIST, HCLEN, the precode lengths in their
scrambled order, then the HLIT + HDIST code lengths as one sequence that a
repeat code can carry across the literal/distance boundary. Returns
error.Truncated if the input ends; error.InvalidDynamicBlockHeader for
HLIT above 286, HDIST above 30, an empty precode set, or a repeat with
nothing to repeat or running past the lengths; and the TreeErrors for an
invalid code-length set.
Copy length bytes from match_distance back in target (§3.2.3).
match_distance <= out_pos and out_pos + length <= target.len are the
caller's guarantees. A match can overlap the bytes it is writing — the
referenced string repeats — so the overlapping case replicates the
match_distance-byte pattern.
pub fn copyMatchHistory(
target: []u8,
out_pos: usize,
match_distance: usize,
length: usize,
history: []const u8,
) void
src
Copy length bytes from match_distance back in target (§3.2.3),
where the history before target is history (the preset dictionary's
last history_len bytes; empty when the stream has none). A match deeper
than the output starts in history and continues at the output's start:
the dictionary is conceptually in front of the output, so the byte after
its last is target[0] (§3.2.3). match_distance <= out_pos + history.len and out_pos + length <= target.len are the caller's
guarantees.
Types
enum
TreeKind
src
Decoder-table kinds: the alphabet decides which structural rules apply.
Fields
literal_length literal_length
Literal/length alphabet (0-285). Must be able to code 256 — without an
end-of-block code no block can ever terminate (§3.2.7).
distance distance
Distance alphabet (0-29). Zero codes ("the data is all literals") and a
single 1-bit code are both legal (§3.2.7).
precode precode
The 19-symbol precode alphabet. An empty precode tree cannot decode the lengths that must follow, so it is a malformed header.
type fn
HuffmanDecoder
src
pub fn HuffmanDecoder(
comptime alphabet_size: usize,
comptime max_bits: u5,
comptime lookup_bits: u5,
comptime kind: TreeKind,
) type
Canonical Huffman decode table (§3.2.2) for an alphabet of alphabet_size
symbols with codes up to max_bits long: a lookup_bits-wide primary table
plus a chained chase for longer codes. kind selects which structural rules
build enforces.
more
A code's wire bits are read MSB-of-code first (§3.1.1), so bit 0 of a
table index is the first bit on the wire and the index's low len bits are
the code. The low 16 bits of lookup[i] pack (symbol << 4) | code_len;
code_len == 0 marks a primary slot whose codes are all longer than
lookup_bits (the chain head is in the same field), and 0xFFFF marks a
slot no code matches (error.InvalidCode). The literal/length and
distance tables' entries are 32 bits, with what a decoder needs beyond
the symbol packed beside it (fast), so one load decodes a whole
symbol.
Public because the streaming Reader builds the same tables and decodes
through the same code: the two layers differ in where the bits come from and
where the output goes, not in the tree machinery.
Fields
Constants
The primary table's index mask: lookup[peeked & mask] is the
entry for every code no longer than lookup_bits, and has a
zero code_len otherwise.
Functions
Build the table from lens: the code length of each symbol, in
symbol order, with 0 meaning the symbol does not occur (§3.2.7).
Returns error.OversubscribedHuffmanTree for a set that over-fills
the code space, error.IncompleteHuffmanTree for one that leaves
code space unused (a single 1-bit code is allowed),
error.MissingEndOfBlockCode for a literal/length set with no code
for 256, and error.InvalidDynamicBlockHeader for an empty precode
set. A distance set can be empty.
Decode one symbol: peek max_bits, resolve the code, and consume
its length. error.InvalidCode for a bit pattern no code matches.
Bits is the bit source, spelled out by the caller: a type with
peek, take, and an ErrorSet, such as this file's BitReader
over a slice, the streaming Reader's over its input (whose reads
can fail), or the reference bit source in the fuzz tests.
The symbol and code length whose code starts peeked, which
holds at least max_bits valid bits, or null for a bit pattern
no code matches. The streaming Reader's fast path decodes
through this from its own bit buffer when the primary entry is
not a whole code.
struct
fast
src
The 32-bit entries of the literal/length and distance tables. The low 16
bits are HuffmanDecoder's (symbol << 4) | code_len (with, in a
distance entry, the total bit count above the symbol); the rest saves a
decoder the per-symbol table lookups:
more
- literal/length: bit 31 (
literal) for symbols 0-255, whose value is bits 4-11; bit 30 (exceptional) for the end-of-block code, the reserved symbols 286-287, a slot of longer codes, and a slot no code matches; otherwise a length, with its code and extra bits' total in bits 16-20 and its base in bits 21-29; - distance: bit 31 (
exceptional) for codes 30-31 and the two kinds of slot; otherwise the code and extra bits' total in bits 9-13 and the base in bits 16-30.
A length or distance is base + (bits & mask(total)) >> code_len.
Constants
Functions
pub fn exceptional(comptime kind: TreeKind) if (kind == .precode) u16 else u32
src
The entry for a code of len bits for symbol.
module
Reader
src
A decompressing Io.Reader over a raw deflate stream. Make one with
Reader.init and read through &r.reader; it returns error.EndOfStream
once the final block's output has been consumed. The caller provides the
window (Reader.Buffer); nothing is allocated.
Constants
The caller-provided decode window, 2 * history_len = 64 KiB. The last
history_len bytes are the match history (§3.2.3) and the rest is fresh
output; a preset dictionary is copied into the window's front before the
first read, so it is history too. The reader keeps no other buffer of
decoded or compressed bytes.
value
error{
Truncated,
InvalidBlockType,
WrongStoredBlockNlen,
InvalidDynamicBlockHeader,
OversubscribedHuffmanTree,
IncompleteHuffmanTree,
MissingEndOfBlockCode,
InvalidCode,
InvalidMatch,
/// A contiguous request that the window cannot hold at the consumer's
/// position.
StreamTooLong,
/// Reading `input` failed.
ReadFailed,
EndOfStream,
}The cause recorded in Reader.err beside the interface's coarse
error.ReadFailed. It holds every decode.DecompressError except
BufferTooSmall (the reader owns its window, so output cannot outgrow it),
plus the three below. EndOfStream is the clean end of the stream and is
never recorded in err.
Functions
Start reading the raw deflate stream in input, with buffer as the
decode window. Read the decoded bytes through &r.reader (stream, the
read and peek families).
more
dict is the stream's preset dictionary or null (§3.2.3): its last
32 KiB are copied into the window in front of the output, so a distance can
reach into them until the output pushes them out of the 32-KiB window. Raw
deflate names no dictionary, so the caller vouches for the bytes; zlib's
FDICT/DICTID is the checked form (RFC 1950 §2.2). A dictionary longer than
32 KiB contributes only its last 32 KiB.
The stream ends with error.EndOfStream once the final block's output has
been consumed. A malformed stream or a failing input returns
error.ReadFailed, with the cause in err. Both outcomes are sticky: later
reads repeat the result.
input's own buffer must hold at least 3 bytes: a 16-bit peek (a stored
block's LEN or NLEN) can start up to 7 bits into a byte, so it spans 3
bytes. An Io.Reader.fixed over a shorter slice is fine, since it already
holds the whole stream.
pub fn streamAll(
in: *Io.Reader,
out: *Io.Writer,
dict: ?[]const u8,
) Io.Reader.StreamRemainingError!usize
src
Decode the raw deflate stream in in into out and return the number of
bytes written. in is consumed exactly through the stream's last byte (the
final partial byte included); bytes after the stream are left unread.
dict is the stream's preset dictionary or null (§3.2.3); see
Reader.init.
more
Returns error.ReadFailed for a malformed stream or a failing in, and
error.WriteFailed when out fails. The cause of a decode failure is not
reported; use Reader directly to read err. Allocates nothing: the
Reader and its 64-KiB window are locals on the caller's stack.
Types
module
Checksum
src
The checksum hook's type: a container's state plus its byte-fold function
(Checksum.zig). It is re-exported here so a container can name it
through this namespace (one type across build modules) and assign it to
checksum before the first read.
Functions
Fold bytes into the container's state.
module
Writer
src
A compressing Io.Writer that produces a raw deflate stream. Make one with
Writer.init, write through &w.writer, and end the stream with finish.
The caller provides the buffer (Writer.Buffer); nothing is allocated.
Functions
Start a deflate stream into output, accumulating input in buffer.
options are fixed for the stream's lifetime; changing w.options
afterwards is not supported. Write through &w.writer, then call
finish.
more
options.dict is the stream's preset dictionary or null (§3.2.3): its
last 32 KiB are copied into buffer's front as the window's oldest bytes,
so the finder can match into them and a distance can reach them. Raw
deflate names no dictionary, so the caller vouches for the bytes; zlib's
FDICT/DICTID is the checked form (RFC 1950 §2.2).
Memory: a Writer holds the level-6 match-finder tables (384 KiB) and the
emitter state, and Buffer holds the window and a block emission's
token list and compressed-output scratch (about 417 KiB in all), so place
both with that in mind; a block emission adds no large stack frame.
pub fn initInPlace(w: *Writer, output: *Io.Writer, buffer: *Buffer, options: encode.Options) void
src
Start a deflate stream in w, as init does, writing the fields in
place. w.* = .init(...) builds the writer elsewhere and copies all of
it in, finder tables included, about 392 KiB per stream: the larger part
of a short stream's cost. Use this to start a stream in memory that held
an earlier writer, or any undefined Writer.
Complete the stream: emit the buffered partial block, write the final
empty fixed block, and flush output. The stream is complete only after
this call, and the writer is unusable afterwards.
Returns error.WriteFailed if output fails. A writer that already failed
or already finished also returns error.WriteFailed, so a truncated stream
is never reported as complete.
pub fn streamAll(
in: *Io.Reader,
out: *Io.Writer,
options: encode.Options,
) Io.Reader.StreamRemainingError!usize
src
Compress everything in yields into one complete raw deflate stream in
out, and return the number of input bytes consumed. The stream is
finished and out is flushed before the call returns.
Returns error.ReadFailed if in fails, and error.WriteFailed if out
fails.
Allocates nothing: the Writer and its Buffer, block scratch included,
are locals on the caller's stack, about 800 KiB.
Types
module
Checksum
src
The checksum hook's type: a container's state plus its byte-fold function
(Checksum.zig). It is re-exported here so a container can name it
through this namespace (one type across build modules) and assign it to
checksum before the first write.
Functions
Fold bytes into the container's state.
struct
Buffer
src
The caller-provided memory, about 417 KiB: the window and one block emission's scratch.
Fields
window: [max_block_size + history_len]u8
The uncompressed accumulation block (max_block_size) plus the
retained match history (history_len), 98303 bytes. The history sits
at the front and the block after it, so the encoder's window (history
followed by block) is one contiguous slice.
tokens: dynamic.TokenList
Level 6's and the lazy levels' token list for the block being emitted. Undefined between emissions.
scratch: [scratch_len]u8
The compressed block before it goes to output. Undefined between
emissions.
module
gzip
src
gzip (RFC 1952) over flate: one-shot encode.compress and
decode.decompress, and the streaming Reader and Writer. Caller-owned
buffers, no heap allocation. API: src/gzip/README.md. Format:
docs/specs/rfc1952-gzip.txt.
Types
module
encode
src
gzip.encode: the one-shot member encoder.
more
compress writes one complete member into a caller-provided buffer: a
fixed 10-byte header, flate's one-shot deflate body, and the 8-byte
trailer (the CRC-32 of the input and its length mod 2^32, RFC 1952
§2.3.1). Size the buffer with maxCompressedLength. The same input and
options always produce the same bytes, and nothing is allocated.
writeHeader, writeTrailer, and xflFor are public because the streaming
Writer is built from them. The order of header, body, and trailer is the
shared container driver's (src/internal/container.zig).
Format: docs/specs/rfc1952-gzip.txt
Constants
pub const header_len = framing.header_len
src
RFC 1952 §2.3 — the fixed header's length.
pub const trailer_len = framing.trailer_len
src
RFC 1952 §2.3 — the trailer's length.
Functions
pub fn maxCompressedLength(input_len: usize) usize
src
The largest member compress can produce for input_len bytes: the
10-byte header, flate's worst-case deflate body, and the 8-byte trailer. A
target of this size always fits the member.
pub fn writeHeader(target: *[header_len]u8, level: Level) void
src
Write the 10-byte member header into target: ID1/ID2/CM fixed, FLG=0 (no
optional fields, reserved bits clear, §2.3.1.2), MTIME=0 ("no time stamp
is available", §2.3.1), XFL from level (see xflFor), and OS=255
(unknown; §2.3.1.2 suggests "255 for OS"). For a given level the header
is the same every time: nothing in it depends on the clock or the
environment. Multi-byte fields are little-endian (§2.1).
pub fn writeTrailer(target: *[trailer_len]u8, crc: u32, len: u32) void
src
Write the 8-byte trailer into target: crc, the CRC-32 of the
uncompressed data (ISO 3309), then len, its length mod 2^32 (ISIZE); both
u32 little-endian (§2.1, §2.3.1).
The XFL byte for level (§2.3.1: 2 means "maximum compression", 4
means "fastest algorithm"): 4 for level 1, 2 for level 9, and 0 for the
rest, the bands C zlib and Go use. The field is informational (§2.3.1.2) and reflects the
requested level, not what the encoder did with it.
pub fn compress(
source: []const u8,
target: []u8,
options: Options,
) error{BufferTooSmall}!usize
src
Compress source into target as one complete gzip member and return the
member's length. Returns error.BufferTooSmall when target cannot hold
it: size target with maxCompressedLength, though a smaller target can
still fit when the data compresses well. target's contents are
unspecified after an error.
Allocates nothing. Level 1 uses about 128 KiB of stack (flate's match-finder table), level 6 about 700 KiB.
Types
enum
Level
src
pub const Level = framing.Level
The compression levels this encoder takes (flate's, re-exported).
Fields
@"1" @"1" = 1
Fixed-Huffman blocks from the level-1 match finder, or a stored block when that is smaller.
@"6" @"6" = 6
klauspost/compress's level-6 class: the wider two-table greedy finder,
dynamic-Huffman blocks (§3.2.7), and the per-block stored, fixed, and
dynamic dispatch. Byte-identical to klauspost/compress's flate at
level 6 (the pinned module version).
@"7" @"7" = 7
Lazy matching over hash chains (lazy.zig, RFC 1951 §4) with a
short search: dynamic-Huffman blocks from a finder that holds each
match while it searches the next position.
@"9" @"9" = 9
Lazy matching over hash chains with a long search: the smallest output, the slowest level.
Functions
The level for a zlib-scale number, or null when this encoder does
not implement it. Use this at a boundary where the number comes from
outside the type system, such as a config value or a flag; a literal
needs no conversion.
module
decode
src
gzip.decode: the one-shot member decoder, plus the header parser and the
trailer check that it shares with the streaming Reader.
more
decompress decodes one member into a caller-provided buffer. It runs the
member through the streaming Reader over a fixed input, so it needs no
allocator. HeaderParser is a byte-fed state machine that skips the
optional header fields as they stream past instead of storing them, so a
header declaring a 65,535-byte extra field costs no memory. checkTrailer
is the one place the CRC-32 and size are compared.
Format: docs/specs/rfc1952-gzip.txt
Constants
pub const header_len = encode.header_len
src
The fixed header's length, 10 bytes (RFC 1952 §2.3.1). Defined in
encode.zig and re-exported so decoder-side code need not reach across
namespaces.
pub const trailer_len = encode.trailer_len
src
The trailer's length, 8 bytes: CRC32 and ISIZE (RFC 1952 §2.3.1).
pub const DecompressError = framing.DecompressError
src
The errors decompress can return: flate's DecompressError (a malformed
or truncated deflate body, or BufferTooSmall when the decoded member does
not fit target) plus these:
more
BadHeader: ID1, ID2, or CM is wrong, or a reserved FLG bit is set (§2.3.1.2).HeaderTooLong: FNAME or FCOMMENT is longer thanname_comment_cap.WrongHeaderChecksum: the FHCRC field does not match the header (§2.3.1).WrongChecksum: the CRC32 in the trailer does not match the decoded data.WrongSize: the ISIZE in the trailer does not match the decoded length mod 2^32.
pub const name_comment_cap = 512
src
The longest FNAME or FCOMMENT the parser accepts, in bytes including the
NUL terminator. RFC 1952 sets no limit; 512 is the limit Go's reader uses.
A field with no terminator within this many bytes is HeaderTooLong.
pub const HeaderError = …
src
value
error{
BadHeader,
HeaderTooLong,
WrongHeaderChecksum,
}The header parser's own failures; the drivers add Truncated when the
input ends mid-header.
RFC 1952 §2.3.1 — the FLG bits. Bits 5-7 are reserved and must be zero
(§2.3.1.2); FTEXT is advisory and ignorable on decode.
pub const flg_fextra = 0x04
src
pub const flg_fcomment = 0x10
src
pub const flg_reserved = 0xe0
src
Functions
pub fn checkTrailer(
trailer: *const [trailer_len]u8,
crc: u32,
len: u32,
) error{ WrongChecksum, WrongSize }!void
src
Check the 8-byte trailer against crc and len, the CRC-32 and the
length mod 2^32 of the decoded data. Both trailer fields are u32
little-endian (§2.1, §2.3.1). Returns error.WrongChecksum if the
CRC-32 differs, else error.WrongSize if ISIZE differs, so the caller
learns which half failed (Go reports both as one error).
pub fn decompress(source: []const u8, target: []u8) DecompressError!usize
src
Decode one gzip member from source into target and return the decoded
length. target is a cap, not a size hint: a member that decodes to more
than target.len bytes returns error.BufferTooSmall before the
overflowing write. A caller enforcing a decoded-size limit sizes target
from that limit, so the error means the limit was exceeded and a retry with
the same buffer cannot succeed. The format's expansion ceiling is 1032:1
(§3.2.5: 258 bytes per length/distance pair, two bits for the pair in a
custom tree), so source.len is no guide to the decoded size.
more
The header, the deflate body, and the trailer are all checked (see
DecompressError). After an error the contents of target are
unspecified. Bytes after the member's trailer are ignored and the end of
the member is not reported, so use Reader where the boundary matters,
for example to walk concatenated members. An empty source is
error.Truncated.
Allocates nothing. The stack holds the decoder's 64 KiB window and about 4 KiB of reader state.
Types
struct
HeaderParser
src
The member header parser (§2.3.1): a byte-fed state machine over the
field order of §2.3 (the 10 fixed bytes, FEXTRA, FNAME, FCOMMENT,
FHCRC). Bytes are folded into the header CRC-32 as they are consumed (FHCRC
is its low 16 bits, §2.3.1). Optional fields are skipped, never stored:
a large XLEN or an unterminated name costs bounded work and no memory.
Fields
stage: Stage
The field being consumed, in §2.3's order.
flags: u8
The FLG byte: the optional-field presence bits (§2.3.1).
taken: usize
Bytes of the current fixed-width field consumed (XLEN, FHCRC).
extra_len: u16
XLEN (§2.3.1.1): the extra field's length, little-endian (§2.1).
skipped: usize
The extra field's bytes already skipped.
scanned: usize
The NUL-scan bytes consumed in the current FNAME/FCOMMENT field, terminator included (the cap counts both).
crc: u32
The header CRC-32 so far: FHCRC's expected value is its low 16 bits
(§2.3.1).
fhcrc: u16
The FHCRC value read from the wire.
Constants
value
.{
.stage = .fixed,
.flags = 0,
.taken = 0,
.extra_len = 0,
.skipped = 0,
.scanned = 0,
.crc = 0,
.fhcrc = 0,
}A parser at the fixed header's first byte.
Functions
Whether the header is complete.
Feed bytes to the parser and return the number consumed. The parser
consumes as much as the current field needs; a caller with more input
feeds again (the streaming route), and a caller with the whole member
feeds once. Every non-done stage consumes at least one byte of a
non-empty slice, so a driver always makes progress. A HeaderError is
returned as soon as the bytes show the header is invalid.
Types
module
Reader
src
A decompressing Io.Reader over one gzip member. Read through
&r.reader; it returns error.EndOfStream once the trailer is verified,
and after a failure r.err holds the specific error. It allocates
nothing; the caller provides Reader.Buffer.
Constants
The caller-provided decode window: flate's Reader.Buffer, re-exported,
64 KiB ([2 * history_len]u8). gzip adds no buffer of its own.
The failures a reader records in err: flate's reader errors (a malformed
deflate body, Truncated, StreamTooLong) plus BadHeader,
HeaderTooLong, WrongHeaderChecksum, WrongChecksum, and WrongSize.
There is no BufferTooSmall: output goes through a fixed window, not a
sized target.
Functions
Create a reader for one gzip member read from input, decoding through
buffer. Read through &r.reader (stream, the read family, the peek
family).
more
At the end of the member the reader verifies the trailer and then returns
error.EndOfStream. A malformed header, body, or trailer, or a failure of
input, returns error.ReadFailed (and keeps returning it) with the
specific error in err. input is consumed exactly through the trailer's
last byte, so bytes after the member are left unread. input needs a
buffer of at least 3 bytes. Do not move the reader once you have started
using it.
A peek or take of more than 32 KiB (flate.encode.history_len) can fail
with error.ReadFailed and err == .StreamTooLong, because the window
cannot hold that much contiguously.
pub fn streamMember(in: *Io.Reader, out: *Io.Writer) Io.Reader.StreamRemainingError!usize
src
Decode one member from in into out and return the number of decoded
bytes. in is consumed exactly through the member's last trailer byte, so
anything after it (the next member, or garbage) stays unread.
more
Returns error.ReadFailed for a bad or truncated member or a failure of
in, and error.WriteFailed for a failure of out. The specific error is
not available here; drive a Reader to get it. Allocates nothing; the
64 KiB window and the reader's state are on the stack.
Decode every member in in into out and return the total number of
decoded bytes (RFC 1952 §2.2: a gzip file is a series of members). After
each member it looks at the next byte of in: end of input finishes the
walk, so an empty in yields zero bytes and no error; any other byte
starts another member, so trailing garbage returns error.ReadFailed
(BadHeader) instead of being skipped. A member cut short fails as it
does in streamMember.
Like streamMember it reports only the coarse error.ReadFailed or
error.WriteFailed; drive a Reader to get the specific error. Allocates
nothing; one member's window at a time is on the stack.
module
Writer
src
A compressing Io.Writer that produces one gzip member. Write through
&w.writer and end the member with finish. It allocates nothing; the
caller provides Writer.Buffer.
Functions
Create a writer that compresses to output as one gzip member, using
buffer as its working space. options (the level) is fixed for the
member. Write through &w.writer and end the member with finish.
init writes nothing to output. Do not move the writer once you have
started using it.
pub fn initInPlace(w: *Writer, output: *Io.Writer, buffer: *Buffer, options: encode.Options) void
src
Start a member in w, as init does, writing the fields in place.
w.* = .init(...) builds the writer elsewhere and copies all of it in,
about 392 KiB per member: the larger part of a short member's cost. Use this
to start a member in memory that held an earlier writer, or any undefined
Writer.
End the member: write the header if nothing has been written yet, write
the buffered data and the final deflate block, write the trailer (CRC-32
and ISIZE, §2.3.1), and flush output. Call it once; without it the
output is not a complete member. After finish, and after any failed
write, every call on the writer returns error.WriteFailed, so a
truncated member is never reported as a success.
pub fn streamAll(
in: *Io.Reader,
out: *Io.Writer,
options: encode.Options,
) Io.Reader.StreamRemainingError!usize
src
Compress everything from in into out as one member and return the
number of bytes read from in. in is read to its end, then the member is
finished. Returns error.ReadFailed for a failure of in and
error.WriteFailed for a failure of out.
Allocates nothing. The writer, its block scratch included, and its buffer take about 800 KiB of stack.
Types
struct
Buffer
src
pub const Buffer = flate.Writer.Buffer
The caller-provided buffer: flate's Writer.Buffer, re-exported, 426,636
bytes (the window and a block's scratch). gzip adds no buffer of its own.
Fields
window: [max_block_size + history_len]u8
The uncompressed accumulation block (max_block_size) plus the
retained match history (history_len), 98303 bytes. The history sits
at the front and the block after it, so the encoder's window (history
followed by block) is one contiguous slice.
tokens: dynamic.TokenList
Level 6's and the lazy levels' token list for the block being emitted. Undefined between emissions.
scratch: [scratch_len]u8
The compressed block before it goes to output. Undefined between
emissions.
module
lz4
src
LZ4 blocks: encode.compressBlock and decode.decompressBlock over
caller-owned buffers. The caller supplies the decoded length as the decode
target's length. No heap allocation. API: src/lz4/README.md. Format:
docs/specs/lz4-block-format.md.
Types
module
decode
src
LZ4 block decoder. Entry point: decompressBlock.
more
Sequences are decoded in order because a match can reference bytes just
written. Literal and non-overlapping match copies use fastmem. Overlapping
matches use the shared SIMD kernel in src/internal/match.zig.
The decoder enforces the sequence grammar and both buffers' bounds. It does not enforce the encoder-side five-literal and 12-byte end margins, so valid blocks from encoders with different tail policies remain readable.
Format: docs/specs/lz4-block-format.md, "Compressed block format".
Constants
pub const DecompressError = error{DecompressionFailed}
src
A block is empty, truncated, malformed, or inconsistent with the expected
decoded length target.len.
Functions
pub fn decompressBlock(source: []const u8, target: []u8) DecompressError!usize
src
Decompress one raw LZ4 block from source into target and return the
bytes written. target.len is the expected decoded length, carried out of
band by the block's container. Success always returns target.len.
more
Returns error.DecompressionFailed for an empty or truncated source, a
length overflow, input or output overrun, offset zero, an offset before the
output's start, a missing final literal sequence, or decoded output shorter
than target.len. source and target must not overlap. Never writes
past target; after an error its contents are unspecified. Does not
allocate.
module
encode
src
LZ4 block encoder: a greedy LZ77 match finder over the 64 KiB window.
Entry points: compressBlock and maxCompressedLength.
more
The match finder follows pierrec/lz4's internal/lz4block/block.go: one
64-bit load feeds hash checks at the cursor and the next two positions. The
table stores the low 16 bits of each position. An occupancy bitmap keeps
unused entries from reading uninitialized table storage and is the only
region cleared between blocks. Match extension compares eight bytes at a
time and uses @ctz on the XOR to find the first mismatch.
No heap allocation: the position table and occupancy bitmap use 136 KiB of
stack. The caller supplies target, sized with maxCompressedLength.
Format: docs/specs/lz4-block-format.md, "Compressed block format". Reference encoder: https://github.com/pierrec/lz4 (BSD-3-Clause).
Constants
pub const max_block_size: usize = 0x7E00_0000
src
Largest input compressBlock accepts. This is the reference LZ4 maximum,
chosen so maxCompressedLength also fits a 32-bit usize.
Functions
pub fn maxCompressedLength(input_len: usize) usize
src
Upper bound on compressBlock output: the input, one length byte per 255
input bytes, and 16 bytes of slack. This is LZ4's CompressBlockBound.
A target of this size makes compression infallible.
pub fn compressBlock(source: []const u8, target: []u8) error{BufferTooSmall}!usize
src
Compress source into target as one raw LZ4 block and return the bytes
written. The block carries no decoded length or framing.
more
source.len must be at most max_block_size (asserted). Returns
error.BufferTooSmall if target cannot hold the result. A target of
maxCompressedLength(source.len) bytes always can. source and target
must not overlap. Uses 136 KiB of stack and does not allocate. The output
is valid LZ4 but need not match another encoder's bytes.
module
snappy
src
Snappy blocks: encode.compressBlock and decode.decompressBlock over
caller-owned buffers, and a streaming Reader and Writer over a
length-prefixed framing of this package's own. No heap allocation. API:
src/snappy/README.md. Format:
docs/specs/snappy-format-description.txt.
Types
module
decode
src
Snappy block decoder with a SIMD overlapping-copy fast path. Entry points:
decompressBlock and decompressedBlockLength.
more
The tag stream is decoded sequentially (a copy can reference bytes just written). The speed is in how copies run:
offset >= length(no overlap): a plainfastmem.copy.offset <= 16(overlapping, RLE-like): theoffset-byte pattern is replicated into a 16-byte register with one byte shuffle (tblon AArch64,pshufbon x86_64) and stored in 16-byte chunks.offset > 16: the 16-byte source window does not overlap the store, so a vectorized chunk copy is correct.
The copies live in ../internal/match.zig, shared with the LZ4 decoder.
Targets without those instructions use the same masks with a byte-wise
permute and produce the same output.
Format: https://github.com/google/snappy/blob/main/format_description.txt
Constants
pub const DecompressError = error{ BufferTooSmall, DecompressionFailed }
src
Errors from decompressBlock and decompressedBlockLength.
BufferTooSmall: target is shorter than the block's declared length.
DecompressionFailed: the block is corrupt or truncated.
Functions
pub fn decompressedBlockLength(source: []const u8) DecompressError!usize
src
The decompressed length a raw snappy block declares in its header. Reads
only the header; the rest of the block is not checked. Returns
error.DecompressionFailed if the header is truncated or malformed. The
value comes from the block and can be up to 2^32 - 1, so limit it before
allocating a buffer for untrusted input.
pub fn decompressBlock(source: []const u8, target: []u8) DecompressError!usize
src
Decompress a raw snappy block from source into target and return the
number of bytes written, which on success is the block's declared length.
more
Returns error.BufferTooSmall if target is shorter than the declared
length (see decompressedBlockLength), before writing anything. Returns
error.DecompressionFailed if the block is corrupt: a bad header, an
element that runs past source, a copy offset of zero or before the start
of the output, output that overshoots or falls short of the declared
length, or trailing bytes. Never writes past the declared length; after an
error the contents of target are unspecified. Does not allocate.
module
encode
src
Snappy block encoder: LZ77 with a hash-table match finder. Entry points:
compressBlock and maxCompressedLength.
more
A port of the algorithm in klauspost/compress's encodeBlockSnappyGo64K
(itself derived from the Snappy-Go reference, and the same shape as
Google's C++ CompressFragment): hash 6 bytes at the cursor into a
power-of-two u16 position table, scan forward, and on a 4-byte match
extend it 8 bytes at a time, using @ctz on the XOR of two loads to find
the first mismatch. A skip heuristic strides past incompressible regions.
If the encoded form would exceed source - source>>5 - 5 bytes, the whole
block is emitted as one literal, so output never exceeds the
maxCompressedLength bound.
No heap allocation: the hash table is a [1 << 14]u16 stack array (32 KiB),
sized for the 64 KiB maximum block. The caller supplies target, sized with
maxCompressedLength.
Format: https://github.com/google/snappy/blob/main/format_description.txt Reference encoder: https://github.com/klauspost/compress (s2/encode_all.go)
Constants
pub const max_block_size: usize = 65536
src
Largest input compressBlock accepts, 64 KiB: the match finder stores
positions as u16. Split larger input into blocks of at most this size;
snappy.Writer does that for streams.
Functions
pub fn maxCompressedLength(input_len: usize) usize
src
Upper bound on the size of compressBlock's output for input_len bytes of
input: the length varint, the input itself, and one tag byte per 60 input
bytes. The encoder falls back to a single literal whenever matching does not
help, so its output never exceeds this. A target of this size makes
compressBlock infallible.
pub fn compressBlock(source: []const u8, target: []u8) error{BufferTooSmall}!usize
src
Compress source into target as a raw snappy block: the uncompressed
length as a varint, then the tag stream. Returns the number of bytes
written.
more
source.len must be at most max_block_size (asserted). Returns
error.BufferTooSmall if target cannot hold the result; a target of
maxCompressedLength(source.len) bytes always can. Uses about 32 KiB of
stack for the match finder's hash table and does not allocate. The output
is valid Snappy but need not match another encoder's bytes.
Inputs shorter than 32 bytes, and inputs that do not shrink by about 3%, come out as a single literal.
module
Reader
src
snappy.Reader: a decompressing Io.Reader over Google's framed snappy
stream (framing_format.txt). Read through &r.reader.
more
The stream starts with the 10-byte identifier and is then a sequence of
chunks: data chunks (compressed or raw) carry a masked CRC-32C of their
uncompressed bytes, the identifier may repeat and is ignored, skippable and
padding chunks are skipped, and a reserved unskippable chunk fails the
stream. There is no end marker: the input's end is the stream's end, and a
chunk cut short is Truncated.
A corrupt chunk or block returns error.ReadFailed with the reason in
err. Both outcomes are sticky.
The caller's Buffer holds the decoded serving region (three chunks of
contiguous decoded reads) and, behind it, staging for one chunk's payload.
A peek or similar request for more than two contiguous chunks can return
error.ReadFailed with err set to StreamTooLong. Nothing is allocated.
Constants
The caller-provided buffer: the decoded serving region plus the chunk-payload staging region.
value
error{
/// The input ended inside the identifier, a chunk header, or a chunk.
Truncated,
/// A chunk's declared shape is invalid: a data chunk shorter than its
/// checksum, a payload past the staging region, or a block that decodes
/// past one chunk.
InvalidStream,
/// The stream does not start with the identifier, or a repeated
/// identifier is malformed (`framing_format.txt` §4.1).
BadStreamIdentifier,
/// A reserved unskippable chunk type, 0x02-0x7f (`§4.5`).
BadChunkType,
/// A data chunk's masked CRC-32C does not match its uncompressed bytes
/// (`§3`).
BadChecksum,
StreamTooLong,
} || decode.DecompressError || error{ ReadFailed, EndOfStream }The detailed error recorded once state == .failed (the interface reports
error.ReadFailed): framing errors come from this layer, block errors come
from decode.DecompressError, and ReadFailed/EndOfStream pass through
from the input.
Functions
Wrap input (a framed snappy stream) with buffer for decoded output.
Consume through &r.reader (stream, read-family, peek-family); the
stream ends cleanly with error.EndOfStream at a chunk boundary and
returns error.ReadFailed (sticky, details in err) on any corrupt
framing, checksum, or block.
Decode the framed snappy stream in in into out and return the decoded
byte count. Reads in to its end. Errors are error.ReadFailed (a corrupt
stream, or in failing) and error.WriteFailed (out failing). The
Reader and its Buffer (about 257 KiB) live on this function's stack
frame; nothing is allocated.
module
Writer
src
snappy.Writer: a compressing Io.Writer over Google's framed snappy
stream (framing_format.txt). Write through &w.writer, then call
finish.
more
Uncompressed writes accumulate in the caller-provided Buffer (one full
chunk). As the buffer fills, drain compresses whole max_block_size
chunks and emits them; flush and finish emit the partial tail. A
chunk is emitted compressed only when the block is smaller than the raw
bytes; otherwise it is a raw chunk. Each emitted chunk compresses into a
scratch_len stack buffer, so nothing is allocated.
Framing (framing_format.txt §4):
stream := identifier chunk*
identifier := 0xff, u24-le 6, "sNaPpY"
chunk := type, u24-le length, data
compressed 0x00: u32-le masked CRC-32C (uncompressed), snappy block
uncompressed 0x01: u32-le masked CRC-32C, raw bytes
The stream has no end marker; the input's end is the stream's end.
Constants
pub const identifier = "\xff\x06\x00\x00sNaPpY"
src
The stream identifier chunk every framed stream starts with (§4.1).
pub const chunk_header_len = 4
src
The chunk header's width: one type byte and a three-byte little-endian
length (§1).
pub const chunk_crc_len = 4
src
The masked CRC-32C's width, ahead of every data chunk's payload (§3).
pub const max_chunk_len = encode.max_block_size
src
The most uncompressed bytes one data chunk may carry (§4.2, §4.3).
The caller-provided uncompressed accumulation buffer: one full chunk.
pub const scratch_len = encode.maxCompressedLength(max_chunk_len)
src
The largest compressed block: maxCompressedLength of a full chunk.
Functions
Wrap output (the compressed-stream sink) with buffer as the
uncompressed accumulation buffer. Write through &w.writer; complete the
stream with finish.
Complete the stream: emit the identifier when nothing has been written,
the final partial chunk, then flush output. Without it the buffered tail
never reaches output. Terminal: afterwards, and after any failed write
to output, writes and finish return error.WriteFailed rather than
reporting a truncated stream as complete.
Compress everything in yields into out as one framed snappy stream and
finish it (the last partial block is written and out is flushed).
Returns the number of uncompressed bytes read from in. Errors are
error.ReadFailed (in failing) and error.WriteFailed (out failing).
The Writer and its 64 KiB Buffer live on this function's stack frame,
and compressing a block uses about 97 KiB more; nothing is allocated.
module
zlib
src
zlib (RFC 1950) over flate: one-shot encode.compress and
decode.decompress, and the streaming Reader and Writer. Caller-owned
buffers, no heap allocation. API: src/zlib/README.md. Format:
docs/specs/rfc1950-zlib.txt.
Types
module
encode
src
One-shot compression: compress and maxCompressedLength, plus the
header and trailer helpers the streaming Writer is built from.
Constants
pub const header_len = framing.header_len
src
RFC 1950 §2.2 — the header's length: CMF and FLG.
pub const dict_id_len = framing.dict_id_len
src
RFC 1950 §2.2 — the DICTID's length, behind a set FDICT flag: the dictionary's Adler-32, most-significant byte first.
pub const trailer_len = framing.trailer_len
src
RFC 1950 §2.2 — the trailer's length: ADLER32.
The emitted CMF: CM = 8 ("deflate", §2.2) in the low four bits, CINFO = 7
(a 32-KiB window: CINFO is "the base-2 logarithm of the LZ77 window size,
minus eight", §2.2) in the high four. Fixed: the encoder exposes no
header knobs.
Functions
pub fn maxCompressedLength(input_len: usize) usize
src
The most bytes compress can write for input_len input bytes: the
2-byte header, flate's worst-case deflate body, and the 4-byte trailer.
Size compress's target to this to rule out error.BufferTooSmall.
pub fn writeHeader(target: *[header_len]u8, level: Level, fdict: bool) void
src
Write the 2-byte header into target: CMF is cmf and FLG is
flgFor(level, fdict). fdict sets FDICT (bit 5) — the encoder sets it
exactly when a DICTID follows the header. Nothing else depends on the
clock or the environment, so the output is reproducible (§2.2).
pub fn writeDictId(target: *[dict_id_len]u8, dict: []const u8) void
src
Write the 4-byte DICTID into target: the Adler-32 of the whole
dictionary, most-significant byte first (§2.1, §2.2). It names the
whole even when the dictionary is longer than the 32-KiB window, so a
decoder must be given every byte (only the tail is matchable).
The FLG byte compress writes for level (§2.2): FLEVEL in bits 6-7,
FDICT (bit 5) set exactly when fdict is, FCHECK in bits 0-4. FLEVEL
follows the bands C zlib and Go use: level 1 gives 0, level 6 gives 2,
and levels 7 and 9 give 3.
It is only a hint ("not needed for decompression"). FCHECK is the smallest
value that makes CMF*256 + FLG a multiple of 31, as the RFC requires
("CMF and FLG, when viewed as a 16-bit unsigned integer stored in MSB order
(CMF*256 + FLG), is a multiple of 31"), so the pair always passes
decode.checkHeader. C zlib's naive emission with FDICT and FLEVEL 0 gives
FCHECK = 31 (78 3f), which is 0 mod 31 and fits the field; this encoder's
is minimal, so the corner only arises when decoding.
pub fn writeTrailer(target: *[trailer_len]u8, adler: u32) void
src
Emit the 4-byte trailer: the Adler-32 of the uncompressed data (excluding
any dictionary data), u32 most-significant-byte first (§2.1, §2.2).
pub fn compress(
source: []const u8,
target: []u8,
options: Options,
) error{BufferTooSmall}!usize
src
Compress source as one complete zlib stream into target and return the
stream's length. Returns error.BufferTooSmall when target cannot hold
the stream: size it with maxCompressedLength, although a smaller target
can still fit when the data compresses under the bound. After an error,
target's contents are unspecified; nothing is written past its end.
more
options.dict is the stream's preset dictionary or null (§2.2): FDICT
is set and the dictionary's Adler-32 written as DICTID, and the compressor
matches into the dictionary's last 32 KiB. A dictionary longer than 32 KiB
contributes only its tail to the window while DICTID names the whole.
Uses about 128 KiB of stack (flate's match-finder table). Allocates nothing.
Types
struct
Options
src
pub const Options = framing.Options
Encoder configuration. .{} is the default: level 1. The level also
selects the header's FLEVEL bits (flgFor).
Fields
level: Level = .@"1"
The compression level.
dict: ?[]const u8 = null
The stream's preset dictionary or null (§2.2): on encode it sets
FDICT and writes the Adler-32 of the whole slice as DICTID; on decode
it is checked against the header's DICTID before any body byte.
strategy: Strategy = .default
How the lazy levels (7 and 9) weigh short matches; levels 1 and 6 ignore it.
enum
Level
src
pub const Level = framing.Level
The compression levels this encoder takes (flate's, re-exported).
Fields
@"1" @"1" = 1
Fixed-Huffman blocks from the level-1 match finder, or a stored block when that is smaller.
@"6" @"6" = 6
klauspost/compress's level-6 class: the wider two-table greedy finder,
dynamic-Huffman blocks (§3.2.7), and the per-block stored, fixed, and
dynamic dispatch. Byte-identical to klauspost/compress's flate at
level 6 (the pinned module version).
@"7" @"7" = 7
Lazy matching over hash chains (lazy.zig, RFC 1951 §4) with a
short search: dynamic-Huffman blocks from a finder that holds each
match while it searches the next position.
@"9" @"9" = 9
Lazy matching over hash chains with a long search: the smallest output, the slowest level.
Functions
The level for a zlib-scale number, or null when this encoder does
not implement it. Use this at a boundary where the number comes from
outside the type system, such as a config value or a flag; a literal
needs no conversion.
module
decode
src
One-shot decompression: decompress and DecompressError, plus the header
and trailer checks the streaming Reader is built from.
Constants
pub const header_len = encode.header_len
src
RFC 1950 §2.2 — the header is 2 bytes (CMF and FLG), the preset
dictionary's DICTID 4 when FDICT is set, and the trailer 4 (ADLER32).
Defined in encode.zig and re-exported here so decoder-side code need not
reach across namespaces.
pub const dict_id_len = encode.dict_id_len
src
RFC 1950 §2.2 — the preset dictionary's identifier field: DICTID, the dictionary's Adler-32 in MSB order, behind a set FDICT flag.
pub const trailer_len = encode.trailer_len
src
RFC 1950 §2.2 — the trailer's length: ADLER32.
pub const DecompressError = framing.DecompressError
src
Everything decompress can return: flate's decode errors (Truncated,
BufferTooSmall, InvalidBlockType, ...) plus this module's: BadHeader
(CM is not 8, CINFO is above 7, or FCHECK is wrong; §2.2, §2.3),
DictionaryRequired (FDICT is set and dict is null; §2.3),
DictionaryMismatch (dict's Adler-32 is not the header's DICTID; §2.2),
and WrongChecksum (ADLER32 does not match; §2.3). BufferTooSmall means
the stream does not fit in target.
pub const HeaderError = …
src
value
error{
BadHeader,
DictionaryRequired,
DictionaryMismatch,
}The failures checkHeader and checkDictionary report. Input that ends
inside the header or the DICTID is Truncated, reported by the code that
reads the bytes (readExact).
RFC 1950 §2.2 — the FLG bits: FCHECK in 0-4, FDICT is bit 5, FLEVEL in
6-7. FDICT is the one the decoder acts on (§2.3): set, it names a preset
dictionary whose DICTID follows the header, and the caller's dictionary is
checked against it. FLEVEL "may be ignored" (§2.3).
Functions
Read exactly target.len bytes from input and consume them, refilling
as needed. Input that ends first is error.Truncated; a failing input is
error.ReadFailed. This is the shared driver's container.readExact,
re-exported because the header and trailer reads are built from it.
pub fn checkHeader(cmf: u8, flg: u8) error{BadHeader}!void
src
Check the two header bytes (§2.2, §2.3). CM, CINFO, and FCHECK
problems are BadHeader; FDICT is not itself a failure — it is checked
against the caller's dictionary by checkDictionary. The checks run in
that order.
more
- CM (CMF's low four bits) must be 8: "another value could indicate the
presence of new features that would cause subsequent data to be
interpreted incorrectly" (
§2.3). - CINFO (CMF's high four bits) must be at most 7: "Values of CINFO above 7
are not allowed in this version of the specification" (
§2.2). - FCHECK is checked as
(CMF*256 + FLG) % 31 == 0, not by recomputing the value and comparing. C zlib and Go write FCHECK = 31 when FDICT is set and FLEVEL is 0 (78 3f). That pair is valid (31 is 0 mod 31 and fits the five-bit field), and a check that recomputes FCHECK would reject it (§2.2).
pub fn checkDictionary(
input: *Io.Reader,
dict: ?[]const u8,
) error{ DictionaryRequired, DictionaryMismatch, Truncated, ReadFailed }!void
src
Check the dictionary a set FDICT flag names (§2.2): read the 4-byte
DICTID (the dictionary's Adler-32, most-significant byte first) and compare
it with dict's. With no dictionary supplied the stream is
DictionaryRequired before the DICTID is even read (§2.3: "A compliant
decompressor must give an error indication if FDICT is set and DICTID is
not the identifier of a known preset dictionary"); with one, a mismatched
identifier is DictionaryMismatch. Both are before any body byte.
DICTID names the whole dictionary, so a dictionary longer than 32 KiB
must be supplied in full even though only its last 32 KiB is matchable
(deflateSetDictionary's tail cut; §2.2).
pub fn checkTrailer(trailer: *const [trailer_len]u8, adler: u32) error{WrongChecksum}!void
src
Compare the 4-byte trailer with adler, the Adler-32 of the decoded
bytes. The trailer is a big-endian u32 (§2.2). Returns
error.WrongChecksum on a mismatch. RFC 1950 makes this check mandatory
for a decoder: "A compliant decompressor must check CMF, FLG, and ADLER32,
and provide an error indication if any of these have incorrect values"
(§2.3).
pub fn decompress(source: []const u8, target: []u8, dict: ?[]const u8) DecompressError!usize
src
Decode one complete zlib stream from source into target and return the
decoded length. target is a cap, not a size hint: the format stores no
decoded length, so the caller sizes it from outside knowledge. A stream
that decodes to more than target.len bytes returns
error.BufferTooSmall, and nothing is written past target. A caller
enforcing a decoded-size limit sizes target from that limit, so the error
means the limit was exceeded and a retry with the same buffer cannot
succeed.
more
dict is the stream's preset dictionary or null (§2.2): the FDICT
flag's bytes. With FDICT set the dictionary must be supplied — its
Adler-32 is checked against the header's DICTID before any body byte
(error.DictionaryRequired when it is null, error.DictionaryMismatch
when it is wrong) — and it pre-seeds the decode window as history. With
FDICT clear the stream names no dictionary and dict is unused.
The other errors are DecompressError's: Truncated when source ends
early (an empty source included), BadHeader, WrongChecksum, and
flate's errors for a malformed body. After any error, target's contents
are unspecified. The Adler-32 is compared after the body is decoded, so
even WrongChecksum leaves unverified output in target.
Bytes after ADLER32 are ignored ("Any data which may appear after ADLER32
are not part of the zlib stream", §2.2), and the return value does not
say where the stream ended. Use the streaming Reader when the boundary
matters.
Uses about 68 KiB of stack (the 64 KiB decode window plus 4 KiB of reader state). Allocates nothing.
module
Reader
src
A decompressing Io.Reader over one zlib stream. Read through
&r.reader. The clean end is error.EndOfStream, reported only after the
trailer checks out; on any failure the interface returns error.ReadFailed
and the cause is in r.err. The caller provides Reader.Buffer. Nothing
is allocated.
Constants
The caller-provided decode window: flate's Reader.Buffer, re-exported.
64 KiB ([2 * history_len]u8); the last 32 KiB of it is match history.
The failure detail recorded in err when the interface returns
error.ReadFailed: BadHeader, DictionaryRequired, DictionaryMismatch,
and WrongChecksum from this module; Truncated and flate's other decode
errors; StreamTooLong for a contiguous request the window cannot hold;
and ReadFailed when the input reader itself failed.
Functions
Start decoding the zlib stream in input, with buffer as the decode
window. Read decoded bytes through &r.reader (stream, take, peek,
and the rest of the Io.Reader interface). After the last body byte the
reader verifies the trailer and then reports error.EndOfStream. A
malformed header, body, or trailer, or a failing input, makes the
interface return error.ReadFailed from then on; the cause is in r.err.
more
dict is the stream's preset dictionary or null (§2.2). With FDICT
set the dictionary must be supplied: its Adler-32 is checked against the
header's DICTID before any body byte (error.DictionaryRequired when it
is null, error.DictionaryMismatch when it is wrong), and it pre-seeds the
decode window as history. With FDICT clear the stream names no dictionary
and dict is unused, so one reader can walk a mixed sequence of streams.
A dictionary longer than 32 KiB contributes only its last 32 KiB to the
window, while DICTID names the whole — supply the full slice.
The reader consumes input exactly through ADLER32's last byte and leaves
the bytes after it unread (§2.2: they "are not part of the zlib
stream"). The trailer is checked only when the reader is asked for bytes
past the last decoded one, so read to error.EndOfStream; output served
before then is unverified.
input's buffer must hold at least 3 bytes, or the input must end sooner.
A contiguous read (peek, take) of up to 32 KiB is always served; a
larger one can fail with error.ReadFailed and
err == error.StreamTooLong. Do not move the Reader after its first
read.
pub fn streamAll(
in: *Io.Reader,
out: *Io.Writer,
dict: ?[]const u8,
) Io.Reader.StreamRemainingError!usize
src
Decode one zlib stream from in into out and return the number of
decoded bytes written. in is consumed exactly through the stream's last
trailer byte; anything after it is left unread. dict is the stream's
preset dictionary or null (§2.2); see init. Returns
error.ReadFailed for a malformed stream or a failing in (the cause is
not reported; use a Reader to see err) and error.WriteFailed if out
fails. Uses about 68 KiB of stack (the 64 KiB window plus 4 KiB of reader
state). Allocates nothing.
module
Writer
src
A compressing Io.Writer that produces one zlib stream. Write through
&w.writer, then call finish to complete the stream. The caller
provides Writer.Buffer. Nothing is allocated.
Functions
Start a zlib stream that is written to output, with buffer as the
compression buffer and options fixed for the stream's lifetime. Write
through &w.writer and complete the stream with finish. Nothing reaches
output until a write fills the buffer or flush or finish is called.
more
options.dict is the stream's preset dictionary or null (§2.2): the
header then carries FDICT and the dictionary's Adler-32 as DICTID, and the
compressor matches into the dictionary's last 32 KiB. A dictionary longer
than 32 KiB contributes only its tail to the window while DICTID names the
whole.
If options.level is not implemented, the returned writer has already
failed, so every write and finish returns error.WriteFailed.
Do not move the Writer after its first write.
pub fn initInPlace(w: *Writer, output: *Io.Writer, buffer: *Buffer, options: encode.Options) void
src
Start a stream in w, as init does, writing the fields in place.
w.* = .init(...) builds the writer elsewhere and copies all of it in,
about 392 KiB per stream: the larger part of a short stream's cost. Use this
to start a stream in memory that held an earlier writer, or any undefined
Writer.
Complete the stream: write the header if it is still pending, the
buffered data as a last block, the empty final block that ends the deflate
stream, and the Adler-32 trailer (§2.2), then flush output. A stream
that is never finished is incomplete and will not decode.
more
Returns error.WriteFailed if output fails. It also returns
error.WriteFailed if an earlier write failed or the writer was already
finished, so a truncated stream is never reported as complete. The writer
is unusable afterwards: later writes and a second finish return
error.WriteFailed.
pub fn streamAll(
in: *Io.Reader,
out: *Io.Writer,
options: encode.Options,
) Io.Reader.StreamRemainingError!usize
src
Compress everything in in into one zlib stream written to out, and
return the number of input bytes consumed. in is read to its end, then
the stream is finished. Returns error.ReadFailed if in fails and
error.WriteFailed if out fails. Uses about 800 KiB of stack (flate's writer
and its buffer, block scratch included) and allocates nothing.
Types
struct
Buffer
src
pub const Buffer = flate.Writer.Buffer
The caller-provided compression buffer: flate's Writer.Buffer,
re-exported. 426,636 bytes: the window, one 65535-byte block plus 32 KiB of
match history, and the scratch for emitting a block.
Fields
window: [max_block_size + history_len]u8
The uncompressed accumulation block (max_block_size) plus the
retained match history (history_len), 98303 bytes. The history sits
at the front and the block after it, so the encoder's window (history
followed by block) is one contiguous slice.
tokens: dynamic.TokenList
Level 6's and the lazy levels' token list for the block being emitted. Undefined between emissions.
scratch: [scratch_len]u8
The compressed block before it goes to output. Undefined between
emissions.
module
zstd
src
zstd (RFC 8878): one-shot encode.compress and decode.decompress, and
the streaming Reader and Writer, with XXH64 frame checksum
verification and dictionaries (zstd.Dictionary, §5). Caller-owned
buffers, no heap allocation. API: src/zstd/README.md. Format:
docs/specs/rfc8878-zstd.txt.
Types
module
encode
src
The one-shot encoder: compress, maxCompressedLength, and their
options.
Constants
value
error{
/// `target` cannot hold the frame. Its contents are then unspecified.
BufferTooSmall,
}Everything compress reports.
pub const frame_header_len_max = frame.magic_len + 1 + 1 + 4 + 8
src
ZSTD_FRAMEHEADERSIZE_MAX (zstd_compress.c:4695): the magic, the
descriptor, the Window_Descriptor, the 4-byte Dictionary_ID form, and the
8-byte Frame_Content_Size form. writeFrameHeader gates on it, as the C
does on ZSTD_FRAMEHEADERSIZE_MAX.
Functions
pub fn maxCompressedLength(source_len: usize) usize
src
The largest frame compress can write for a source_len-byte source:
the 18-byte header cap (the 14 no-dictionary bytes plus the 4-byte
Dictionary_ID field, §3.1.1.1.1.6), 3 bytes per block, the source
itself, and the 4-byte checksum. Always inside the C's
ZSTD_COMPRESSBOUND (zstd.h).
Compress source into target as one Zstandard frame and return the
frame's length.
more
The frame declares its exact Frame_Content_Size in the smallest form
(§3.1.1.1.4) and always carries the XXH64 Content_Checksum
(§3.1.1). The window is the smallest power of two covering the source,
from 1 KiB to 512 KiB (§3.1.1.1.2); a source of at most 512 KiB fits
its window and is single-segment, and a larger one declares a 512 KiB
window. No dictionary is ever named, and the output is deterministic: the
same source and options produce the same bytes.
target must be at least maxCompressedLength(source.len); a smaller
one can still work when the source compresses, and otherwise fails with
error.BufferTooSmall before writing past target. On success only the
first n bytes are the frame: an abandoned entropy attempt leaves
scratch bytes past n, so do not assume target[n..] was untouched.
target's contents are unspecified after a failure. Nothing is allocated.
pub fn compressBuffered(
source: []const u8,
target: []u8,
buffer: *Buffer,
options: Options,
) Error!usize
src
compress over a caller-owned Buffer instead of the stack: the
literals buffer, the sequence list, and the match finder's table live in
buffer (768 KiB), so this form needs only the entropy writers' KiB-scale
scratch of thread stack (about 64 KiB). The frame is
the same, byte for byte; buffer's contents are unspecified after the
call.
Types
enum
Level
src
pub const Level = enum(u8)
The compression levels this encoder implements, named by the CLI scale.
The tag is the level number, so @backingInt spells the CLI's value.
Fields
@"1" @"1" = 1
ZSTD_fast, byte-identical to zstd -1.
@"3" @"3" = 3
ZSTD_dfast, byte-identical to zstd -3 up to the 8 MiB job size.
Functions
The level for a CLI-scale number, or null when this encoder does not
implement it. Use this at a boundary where the number comes from
outside the type system; a literal needs no conversion.
struct
Options
src
compress's options.
Fields
level: Level = .@"1"
The compression level. Only the levels in Level are representable.
dict: ?*const Dictionary = null
The dictionary the frame is compressed against (§5): its tables seed
the frame's entropy state (with ZSTD_loadCEntropy's promotions) and
its content is the match region's virtual past. The frame names the
dictionary's ID in its header (§3.1.1.1.1.6). null is a
no-dictionary frame.
struct
Buffer
src
The one-shot's heavy per-block arrays: the literals buffer, the sequence
list, and the match finder's position tables (the long one, and dfast's
small one). Sized by the block layer's worst cases, so no allocation is
needed. compress puts one on the stack, about 1.5 MiB in all;
compressBuffered takes a pointer to one the caller owns, which keeps
that stack out of the caller's thread.
Fields
literals: [block_compress.max_block_size]u8 = undefined
sequences: [block_compress.max_sequences]sequences_compress.Sequence = undefined
long_table: [dfast_compress.long_table_entries_max]u32 = undefined
small_table: [dfast_compress.small_table_entries_max]u32 = undefined
module
decode
src
The one-shot decoder: decompress and its error set, plus the layer
namespaces it is built from (frame, block, literals, sequences,
fse, and window).
Constants
pub const max_block_size = block.max_block_size
src
§3.1.1.2.4 — "128 KB": Block_Maximum_Size's ceiling. A frame's own
bound is min(Window_Size, this).
pub const DecompressError = frame.Error
src
The errors decompress returns: frame.Error, name for name. It covers
the frame header's, the block layer's, and the literals and sequences
layers' errors.
Functions
pub fn decompress(
source: []const u8,
target: []u8,
dict: ?*const Dictionary,
) DecompressError!usize
src
Decode one Zstandard frame from source into target and return the
decoded length.
more
dict seeds the frame's starting state (§5): the literals tree, the
three sequences tables, and the repeat offsets come from the dictionary
when it has entropy, and its content is the preset history a match can
reach into while the frame's decoded total is at most Window_Size. null
is the no-dictionary decode. A frame that names a nonzero Dictionary_ID
needs the matching dictionary: without one it is DictionaryRequired, and
with one whose ID differs it is DictionaryMismatch. A frame that names
no ID (or names 0) decodes either way, a supplied dictionary still
seeding it. dict is borrowed for the call; its bytes must outlive it.
Leading skippable frames (§3.1.2) are skipped. The frame ends after its
last block, or after the 4-byte Content_Checksum when the header sets the
checksum flag. Bytes after the frame are ignored and the number of bytes
consumed is not reported, so this reads one frame only, where the C
reference's ZSTD_decompress and klauspost's DecodeAll decode every
concatenated frame. For concatenated frames, or to learn where a frame
ended, use zstd.Reader.
Input with no frame in it is Truncated: empty input, a partial magic, or
a header cut short. Input that holds only skippable frames decodes to zero
bytes. Other errors are DecompressError's, for example BadMagic,
DictionaryRequired, ContentSizeMismatch when the decoded length differs
from a declared Frame_Content_Size, and WrongChecksum when the trailer
does not match.
target limits the output: a frame that would write past it fails with
BufferTooSmall before the write. A caller enforcing a decoded-size limit
sizes target from that limit, so the error means the limit was exceeded
and a retry with the same buffer cannot succeed. On any error target can
hold partial output, which must not be used. A Compressed block keeps a
128 KiB literals scratch on the stack and the frame state is about 16 KiB.
Nothing is allocated.
Types
module
block
src
The block layer (§3.1.1.2): the Block_Header, the four Block_Types, and
the per-block decode.
Constants
pub const max_block_size: usize = 128 * 1024
src
§3.1.1.2.4 — "128 KB": Block_Maximum_Size's ceiling. A frame's own
bound is min(Window_Size, this), so this is also the largest block any
frame can carry and the block scratch this layer sizes for.
pub const block_header_len = 3
src
§3.1.1.2: "Block_Header uses 3 bytes, written using little-endian
convention."
value
error{
/// The input ends inside the 3-byte Block_Header or inside the
/// Block_Content its Block_Size declares (`§3.1.1.2`).
Truncated,
/// `§3.1.1.2.4` — Block_Size past Block_Maximum_Size = "the smallest
/// of: Window_Size, 128 KB" — or a compressed block that would decode
/// past it (the maximum "is applicable to both the decompressed size
/// and the compressed size of any block in the frame").
BlockOversize,
/// `§3.1.1.2.2` — block type 3, Reserved: "This is not a block. ...
/// a compliant decoder must reject it."
ReservedBlock,
/// A block's output does not fit in what is left of the caller's
/// `target`. Raised before the write that would overflow (`§3.1.1.2.4`,
/// `§8`).
BufferTooSmall,
} || literals.Error || sequences.ErrorEverything the block layer reports: the literals and sequences layers'
error sets plus this layer's own names. The frame layer's set adds the
frame header's (BadMagic, ReservedBitSet, DictionaryRequired, and so
on).
Functions
pub fn parseHeader(source: []const u8) error{Truncated}!Header
src
Parse a Block_Header (§3.1.1.2, Table 9): 3 bytes, little-endian,
Last_Block in bit 0, Block_Type in bits 1-2, Block_Size in bits 3-23.
Fewer than 3 bytes is the input's end: Truncated.
pub fn contentLength(header: Header) usize
src
The Block_Content length a header implies (§3.1.1.2.3): "When
Block_Type is RLE_Block, since Block_Content's size is always 1,
Block_Size represents the number of times this byte must be repeated";
for Raw_Block and Compressed_Block it "is the size of Block_Content
(hence excluding Block_Header)".
pub fn decode(
source: []const u8,
target: []u8,
decoded_len: usize,
window_size: u64,
frame_total: u64,
dict: []const u8,
literals_state: *literals.State,
sequences_state: *sequences.State,
checksum: ?*xxh64.State,
) Error!Section
src
Decode one block. source starts at the block's Block_Header and can hold
more input after the block.
more
target[0..decoded_len] is the output already in target, and the block's
output goes to target[decoded_len..]. window_size is the frame's
Window_Size (§3.1.1.1.2); it also sets Block_Maximum_Size, the smaller
of window_size and 128 KiB. A match can read the last
min(decoded_len, window_size) bytes of that output and whatever this
block has already written. An offset of exactly window_size reads the
oldest retained byte, and later in a block an offset can exceed
window_size, because the block's own output extends the readable span.
An offset that reaches before the retained history is OffsetTooFar.
frame_total is the frame's decoded total before this block. On the
one-shot's contiguous path it equals decoded_len; the streaming reader's
window slides, so its region holds only a suffix of the frame and the two
differ. dict is the dictionary content (§5), conceptually in front of
target[0]; a match can reach into it only while the frame's decoded
total at the match is at most window_size (§5's boundary, applied in
decodeCompressed).
literals_state and sequences_state belong to the frame. A Compressed
block updates them; Raw and RLE blocks leave them alone (§3.1.1.5:
"blocks that are not Compressed_Block are skipped; they do not contribute
to offset history").
Returns the bytes written, the bytes consumed (header included), and the
Last_Block flag. The errors are Error's. Each check runs before the write
it guards, so the decode never writes more than Block_Maximum_Size bytes
or past the end of target. A Compressed block that fails partway can
leave the output of its earlier sequences in target[decoded_len..]; the
caller discards it.
A Compressed block keeps a literals scratch of max_block_size (128 KiB)
on the stack. Nothing is allocated.
pub fn decodeContent(
header: Header,
content: []const u8,
target: []u8,
decoded_len: usize,
window_size: u64,
frame_total: u64,
dict: []const u8,
literals_state: *literals.State,
sequences_state: *sequences.State,
checksum: ?*xxh64.State,
) Error!usize
src
Decode one block's Block_Content when its header is already parsed, for a
caller that reads its own input (the streaming reader parses the header,
then stages the content). content must hold at least
contentLength(header) bytes, and anything after them is ignored. Returns
the length of the block's output, written to target[decoded_len..].
Everything else is as for decode, which is this plus the header parse
and the consumed count (frame_total included).
more
Staging is the caller's job because a Compressed block's two backward
bitstreams are read from the block's end, so all of its content must be in
memory before decoding starts.
checksum is the frame's XXH64 state when the frame carries the
Content_Checksum flag, null otherwise. Only a Raw block uses it: its
output is the staged bytes verbatim, so the copy folds each chunk into
the checksum while the bytes are still cache-hot, instead of the frame
layer re-reading the whole block afterwards. The fold is the same bytes,
once, in block order; the caller must then record the block with
frame.State.recordRawBlock, not recordBlock.
Types
struct
Header
src
A parsed Block_Header (§3.1.1.2, Table 9).
Fields
last_block: bool
§3.1.1.2.1 — "The lowest bit (Last_Block) signals whether this
block is the last one. The frame will end after this last block."
block_type: BlockType
block_size: usize
Block_Size: Block_Content's length for Raw_Block and
Compressed_Block, the repeat count for RLE_Block (§3.1.1.2.3).
struct
Section
src
One decoded block.
Fields
bytes_written: usize
The block's output: bytes_written bytes at target[decoded_len..]
of the region the caller handed decode.
bytes_consumed: usize
The block's bytes consumed from the caller's source: the 3-byte
Block_Header plus its Block_Content.
last_block: bool
§3.1.1.2.1 — the frame ends after this block.
module
Dictionary
src
A parsed dictionary (§5), the value both directions take.
Constants
§5 — "Magic_Number: 4 bytes, little-endian format. Value: 0xEC30A437."
The Magic_Number's 4 bytes (§5).
§5 — "Dictionary_ID: 4 bytes, little-endian format. ... any value,
except 0 (which means no Dictionary_ID)".
pub const repcodes_len = 12
src
§5 — "3 offset values, populating repeat offsets ... stored in order,
4 bytes little-endian each, for a total of 12 bytes."
pub const ParseError = …
src
value
error{
/// The source ends before the magic, inside the Dictionary_ID, or inside
/// the 12 repcode bytes. A table description cut short is its reader's
/// own error instead (`MalformedHuffmanWeights`, `MalformedFseTable`):
/// the description's length is decoded from its own bytes.
Truncated,
/// The first four bytes are not `0xEC30A437` LE: not the formatted form.
BadDictionaryMagic,
/// `§5` — the Dictionary_ID is 0, "which means no Dictionary_ID". The C
/// reads a zero ID and keeps going (DT4); ours fails closed at the parse.
InvalidDictionaryId,
/// `§5` — a repeat offset is 0 or above the content size. The RFC's word
/// is "the dictionary size"; the references enforce the content size,
/// the only reading consistent with the trainer's output (DT2).
InvalidDictionaryRepcode,
/// `§4.2.1` — the literals tree description is cut short or its weights
/// do not form a valid tree. Incomplete statistics are legal (§5's
/// tables are the block forms): zero weights are accepted.
MalformedHuffmanWeights,
/// `§4.1.1` — one of the three FSE descriptions is cut short, exceeds its
/// context's caps, or its budget does not land exactly. Zero-probability
/// symbols are legal: the table can cover less than its whole alphabet.
MalformedFseTable,
}Everything parse reports. The first four names are this layer's; the
last two are the shared readers' (huff0.readTree, fse.readDescription)
for a table description that is cut short or malformed — the same names
the block layer reports for the same bytes.
Functions
Parse a formatted dictionary (§5) from source.
more
The entropy tables are read with the same parsers a compressed block's
tables go through (huff0.readTree, then fse.readDescription for
offsets, match lengths, and literals lengths with the caps 31/8, 52/9,
35/9), and the tables are built once here — nothing re-parses per frame
or block. The returned value borrows source: the content slice and the
table descriptions are never copied, so keep the bytes alive as long as
the value is used.
Errors are ParseError's: a malformed piece fails with its own name,
raised before any table is handed out.
pub fn matchParams(self: *const Dictionary, level: u8) match_compress.DictParams
src
The dictionary's own parameters for a level (the C's CDict cParams),
which a frame's window, hash widths, and match width are drawn from
(ZSTD_resetCCtx_byAttachingCDict / ..._byCopyingCDict).
A raw-content dictionary (§5): "Zstandard is compatible with 'raw
content' dictionaries, free of any format restriction ... These
dictionaries function as if they were just the content part of a
formatted dictionary." Content only: no tables (so no Treeless literals
or Repeat sequences from the first block), the default {1,4,8} repeat
offsets, and no Dictionary_ID — it never satisfies a frame that declares
one (the C decoder's shape; klauspost's ID-assigning raw form is not
ported).
Infallible and format-free: any bytes parse, and §5's 8-byte floor is not
enforced (the references accept shorter content too). The value borrows
content.
module
frame
src
The frame layer (§3.1): the Magic_Number, the Frame_Header, the block
chain, the checksum trailer, and skippable frames.
Constants
value
error{
/// `§3.1`, `§3.1.2` — the 4-byte Magic_Number is neither the Zstandard
/// magic nor one of the 16 skippable magics.
BadMagic,
/// `§3.1.1.1.1.4` — descriptor bit 3: "Its value must be zero. A decoder
/// compliant with this specification version must ensure it is not set."
ReservedBitSet,
/// `§3.1.1.1.3`, `§5` — the frame's Dictionary_ID. A frame that names a
/// nonzero ID needs a dictionary: none supplied is `DictionaryRequired`,
/// a supplied one whose ID differs is `DictionaryMismatch` (a raw
/// dictionary's 0 included). A frame with no ID field, or one whose
/// value is 0 ("0 means no Dictionary_ID"), decodes with or without a
/// dictionary. Both checks run once the header is parsed, before any
/// body byte; the ID field itself is read, never skipped.
DictionaryRequired,
/// `§3.1.1.1.3`, `§5` — the frame names a Dictionary_ID and the supplied
/// dictionary's ID does not match it (the C's own label,
/// `zstd_decompress.c:716-719`). Raised before any body byte.
DictionaryMismatch,
/// `§3.1.1.1.4` — Frame_Content_Size against the frame's actual decoded
/// total: a running bound (`recordBlock`, `§8`'s smaller-than-actual
/// vector) and a frame-end check (`checkContentSize`).
ContentSizeMismatch,
/// `§3.1.1` — the Content_Checksum trailer does not match the XXH64 of the
/// decoded bytes. A trailer that is present is always verified, although
/// `§2` allows a decoder to ignore it.
WrongChecksum,
} || block.ErrorEverything the frame layer reports: the block layer's composed set plus
this layer's own names. zstd.decode.DecompressError is this set, name
for name (decode.zig asserts it at comptime). WindowTooLarge is not in
it: only a caller with its own window limit (checkWindow) can raise that.
§3.1.1 — "Magic_Number: 4 bytes, little-endian format. Value:
0xFD2FB528."
pub const skippable_magic_base: u32 = 0x184D_2A50
src
§3.1.2 — "Magic_Number: 4 bytes, little-endian format. Value:
0x184D2A5?, which means any value from 0x184D2A50 to 0x184D2A5F. All 16
values are valid to identify a skippable frame."
pub const skippable_magic_mask: u32 = 0xFFFF_FFF0
src
The skippable magic's low four bits carry the frame's tag; the rest must
match skippable_magic_base.
The Magic_Number's 4 bytes (§3.1.1, §3.1.2).
pub const frame_size_len = 4
src
The skippable Frame_Size's 4 bytes (§3.1.2): "the size, in bytes, of the
following User_Data (without including the magic number nor the size field
itself)".
pub const checksum_len = 4
src
§3.1.1 — "Content_Checksum: ... 4 bytes" ("The low 4 bytes of the
checksum are stored in little-endian format").
pub const descriptor_fcs_flag_mask: u8 = 0xc0
src
The Frame_Header_Descriptor's fields (§3.1.1.1.1, Table 3).
pub const descriptor_single_segment: u8 = 0x20
src
pub const descriptor_unused: u8 = 0x10
src
pub const descriptor_reserved: u8 = 0x08
src
pub const descriptor_checksum: u8 = 0x04
src
pub const descriptor_dictionary_flag_mask: u8 = 0x03
src
Functions
Classify the 4 bytes at the front of source (§3.1, §3.1.2): the
Zstandard frame magic, one of the 16 skippable magics, or BadMagic.
Fewer than 4 bytes is the input's end, Truncated. The one-shot and the
streaming reader both classify through this, so they agree on what a frame
is.
pub fn fcsFieldSize(descriptor: u8) usize
src
§3.1.1.1.1.1, Table 4 — FCS_Field_Size from the descriptor: 1 when
Frame_Content_Size_Flag is 0 and Single_Segment_Flag is set, 0 when the
flag is 0 and it is not, else 2 / 4 / 8.
pub fn didFieldSize(descriptor: u8) usize
src
§3.1.1.1.1.6, Table 5 — DID_Field_Size from the descriptor.
pub fn parseHeader(source: []const u8) Error!Header
src
Parse a whole Frame_Header from the front of source, the bytes after
the Magic_Number (§3.1.1.1). The streaming reader drives HeaderParser
directly instead. Fewer bytes than the header needs is the input's end:
Truncated. The parser's own error is ReservedBitSet; the
Dictionary_ID it reads is checked by checkDictionary.
pub fn checkDictionary(header: Header, dict: ?*const Dictionary) error{
DictionaryRequired,
DictionaryMismatch,
}!void
src
§3.1.1.1.3 + §5 — the Dictionary_ID matrix, run once the header is
parsed and before any body byte: a frame with no Dictionary_ID field, or
one whose value is 0 ("0 means no Dictionary_ID"), decodes with or
without a dictionary; a frame that names a nonzero ID needs one. None
supplied is DictionaryRequired; a supplied dictionary whose ID differs —
a raw dictionary's 0 included, since it names none — is
DictionaryMismatch, the C's own label for the same case
(zstd_decompress.c:716-719). The reserved ID ranges are not enforced:
a decoder cannot know the registry.
pub fn checkWindow(header: Header, max_window_size: u64) error{WindowTooLarge}!void
src
§3.1.1.1.2 — "a decoder is allowed to reject a compressed frame that
requests a memory size beyond the decoder's authorized range": the
streaming reader's cap, checked once the header is parsed and before any
block byte is read. The one-shot applies no cap — its history is target
itself — so WindowTooLarge is not in zstd.decode.DecompressError.
Types
struct
window
src
§3.1.1.1.2's Window_Size arithmetic: the four formulas a frame's window is
computed from. Every descriptor byte parses, so the formulas cannot fail;
the limit on what a caller accepts is checkWindow's.
Constants
§3.1.1.1.2 — "The minimum Window_Size is 1 KB."
§3.1.1.1.2 — "The maximum Window_Size is (1<<41) + 7*(1<<38) bytes,
which is 3.75 TB."
Functions
windowLog = 10 + Exponent — 10 to 41.
pub fn windowBase(exponent: u5) u64
src
windowBase = 1 << windowLog.
windowAdd = (windowBase / 8) * Mantissa.
Window_Size = windowBase + windowAdd, from the Window_Descriptor
byte (§3.1.1.1.2, Table 6: bits 7-3 Exponent, bits 2-0 Mantissa).
pub fn descriptor(window_log: u6) u8
src
The Window_Descriptor byte declaring a window of exactly
1 << window_log bytes (§3.1.1.1.2): the exponent in bits 7-3,
mantissa 0 in bits 2-0. size of the result is that window, which
a comptime check pins for every encodable window_log.
The format's Window_Log is 10 to 41; an encoder that declares
1 << window_log with a nonzero mantissa would declare more than it
retains, so the mantissa stays 0.
struct
Header
src
A parsed Frame_Header (§3.1.1.1, Table 2): the descriptor's fields and
the two sizes they imply.
Fields
descriptor: u8
The raw Frame_Header_Descriptor byte (§3.1.1.1.1, Table 3), kept
whole so every bit's provenance stays visible at the call site.
window_size: u64
§3.1.1.1.2 — Window_Size: the window arithmetic's value, or
Frame_Content_Size itself when Single_Segment_Flag is set.
content_size: ?u64
§3.1.1.1.4 — Frame_Content_Size; null when FCS_Field_Size is 0.
Single_Segment_Flag makes it necessarily present. It is only checked
against the decoded length (State.recordBlock,
State.checkContentSize), never used to size anything.
dictionary_id: ?u32
§3.1.1.1.3 — Dictionary_ID; null when DID_Field_Size is 0. A
nonzero value is the ID the frame's dictionary must carry
(checkDictionary); 0 means no Dictionary_ID.
checksum: bool
§3.1.1.1.1.5 — Content_Checksum_Flag: the 4-byte trailer.
bytes_consumed: usize
The Frame_Header's length, 2-14 bytes (§3.1.1.1): the descriptor
plus its optional fields. The block chain starts here.
struct
HeaderParser
src
The Frame_Header parser (§3.1.1.1, Table 2): a state machine fed bytes in
field order (the descriptor, the Window_Descriptor, the Dictionary_ID, the
Frame_Content_Size). It stages nothing, since the header is at most 14 bytes
and each field accumulates in its own scalar, so a reader whose input
buffer holds only the magic's 4 bytes can still parse the header across
reads. parseHeader drives it over a whole slice.
Fields
stage: Stage
descriptor: u8
The Frame_Header_Descriptor byte, once read.
taken: usize
The current field's bytes consumed so far.
value: u64
The current field's little-endian value (the Dictionary_ID's up to
four bytes, the FCS's up to eight). Both taken and this reset when
a field completes: the Dictionary_ID and the Frame_Content_Size are
separate fields that share them.
window_size: u64
Window_Size, 0 until its field is complete.
content_size: ?u64
null until its field is complete; null when FCS_Field_Size is 0.
dictionary_id: ?u32
null until its field is complete, and when DID_Field_Size is 0.
total: usize
The Frame_Header's bytes consumed (§3.1.1.1: 2-14).
Constants
value
.{
.stage = .descriptor,
.descriptor = 0,
.taken = 0,
.value = 0,
.window_size = 0,
.content_size = null,
.dictionary_id = null,
.total = 0,
}A parser at the descriptor byte.
Functions
Whether the header is complete.
The parsed header. Only legal once done.
Feed bytes to the parser and return the bytes consumed. The parser
consumes as much as the current field needs; a caller with more input
feeds again (the streaming route), and a caller holding the whole
header feeds once. Every stage of a non-empty slice either consumes a
byte or fails, so a driver always makes progress. The input ending
inside the header is the driver's Truncated: the parser is not
done yet. Fails with ReservedBitSet; the Dictionary_ID field is
read whole, and the dictionary it names is checked by
checkDictionary once the header is parsed.
Types
struct
State
src
One frame's decode state, kept across its blocks: the parsed header, the literals and sequences layers' cross-block states, the decoded length so far, and the checksum.
more
recordBlock is where decoded bytes reach the checksum — handed exactly
the bytes each block wrote, in order — except Raw blocks, whose bytes the
copy folds chunk by chunk while they are cache-hot (block.decodeContent;
those record with recordRawBlock). Either way each byte is folded once,
in order.
Fields
header: Header
The parsed Frame_Header (§3.1.1.1).
literals: literals.State
The Huffman tree a Treeless_Literals_Block reuses (§3.1.1.3), one
per frame; a dictionary seeds its table pointer.
sequences: sequences.State
The three decoding tables and the repeat offsets a Repeat_Mode reuses
(§3.1.1.3, §3.1.1.5), one per frame; a dictionary seeds its
table pointers and its repeat offsets.
dict_content: []const u8
§5 — the dictionary content, the preset history in front of the
frame's output. Empty without a dictionary. Borrowed: the caller's
dictionary must outlive the state (the same lifetime the seeded table
pointers carry).
checksum: xxh64.State
§3.1.1 — the decoded bytes' XXH64, folded per block. A frame without
the checksum flag folds nothing, since nothing will be verified.
decoded_len: u64
The frame's decoded length so far: the block layer's decoded_len on
the one-shot's contiguous path, and the running total that
Frame_Content_Size is checked against (§3.1.1.1.4) everywhere. A
u64, not a usize: a frame's output has no usize bound (about
131 KB of RLE blocks decodes to over 4 GiB), so the total must not wrap
on 32-bit targets, where a wrap would panic in safe builds and be
undefined behavior in ReleaseFast. Hostile input gets an error, never a
crash.
Functions
Start a new frame in state, initializing it in place. A State is
about 16 KiB, mostly decoding-table payload that stays undefined until a
block builds it. Returning one by value would copy the whole aggregate,
undefined payload included, a measurable cost on 32-64 KiB frames.
more
A dictionary seeds exactly the seats this resets: literals.table
(pointing at the dictionary's decode table when it has entropy), the
three sequences.tables (pointing at its parsed tables), and
sequences.repeat_offsets (its 12 bytes, or the {1,4,8} seed for a
raw one). Nothing is copied: the state's pointers reach into the
caller-owned dictionary, which must outlive the state.
pub fn decodeBlock(state: *State, source: []const u8, target: []u8) Error!block.Section
src
Decode one block from the front of source (its Block_Header) into
target and record its output. This is the one-shot's step:
target[0..decoded_len] is the frame's output so far, so the frame's
decoded length is also the block's position in target. Returns the
errors of block.decode, plus ContentSizeMismatch from the record.
The streaming reader's output window slides, so it does not use this.
It parses the Block_Header itself, stages the content, calls
block.decodeContent with the length it has retained, and then calls
recordBlock.
pub fn recordRawBlock(state: *State, bytes_written: usize) error{ContentSizeMismatch}!void
src
Record a Raw block, whose output the copy already folded into the
checksum chunk by chunk (block.decodeContent): only the accounting
remains — the decoded total and the Frame_Content_Size running bound.
pub fn recordBlock(state: *State, output: []const u8) error{ContentSizeMismatch}!void
src
Record one decoded block: fold its output into the checksum (when the
frame has one), add its length to the decoded total, and enforce
Frame_Content_Size as a running bound. Raw blocks are the exception:
their fold rides the copy (block.decodeContent), so they record
with recordRawBlock. A frame that has produced more
bytes than it declared fails at that block with ContentSizeMismatch,
so a header that understates the size cannot keep the frame decoding
until its end (§3.1.1.1.4, §8's smaller-than-actual vector).
output is exactly the bytes the block just wrote, taken with the
length that block call used: target[decoded_len..][0..bytes_written]
for the one-shot, serving[retained_len..][0..bytes_written] for the
streaming reader. Call it once per block, in order.
pub fn checkContentSize(state: *const State) error{ContentSizeMismatch}!void
src
The frame end's check (§3.1.1.1.4): Frame_Content_Size against the
frame's actual decoded total. recordBlock catches the running
overshoot; this catches a frame that stopped short of what it declared.
pub fn verifyTrailer(state: *State, trailer: []const u8) error{WrongChecksum}!void
src
The frame end's trailer step (§3.1.1, §3.1.1.1.1.5): compare the
4-byte Content_Checksum against the digest folded so far ("The low 4
bytes of the checksum are stored in little-endian format") and return
WrongChecksum on a mismatch.
more
The caller calls this only when the header's checksum flag is set (a
frame without the flag has no trailer and folded nothing), and passes
exactly checksum_len bytes. Input that ends before the trailer is the
caller's Truncated. A decode that fails earlier never gets here, so it
reports the decode's error, not the checksum's. state is a mutable
pointer only because xxh64.State.final takes one; verifying does not
change the digest.
struct
window
src
pub const window = frame.window
§3.1.1.1.2's Window_Size arithmetic.
Constants
§3.1.1.1.2 — "The minimum Window_Size is 1 KB."
§3.1.1.1.2 — "The maximum Window_Size is (1<<41) + 7*(1<<38) bytes,
which is 3.75 TB."
Functions
windowLog = 10 + Exponent — 10 to 41.
pub fn windowBase(exponent: u5) u64
src
windowBase = 1 << windowLog.
windowAdd = (windowBase / 8) * Mantissa.
Window_Size = windowBase + windowAdd, from the Window_Descriptor
byte (§3.1.1.1.2, Table 6: bits 7-3 Exponent, bits 2-0 Mantissa).
pub fn descriptor(window_log: u6) u8
src
The Window_Descriptor byte declaring a window of exactly
1 << window_log bytes (§3.1.1.1.2): the exponent in bits 7-3,
mantissa 0 in bits 2-0. size of the result is that window, which
a comptime check pins for every encodable window_log.
The format's Window_Log is 10 to 41; an encoder that declares
1 << window_log with a nonzero mantissa would declare more than it
retains, so the mantissa stays 0.
module
fse
src
The FSE tables (§4.1), shared by the sequences section and the Huffman
weights.
Constants
value
error{
/// A table description that breaks `§4.1.1`'s rules: the accuracy log
/// exceeds the context's cap, the probability budget does not land exactly
/// on `1 << Accuracy_Log`, the symbol count exceeds the context's, fewer
/// than two symbols have a nonzero probability, or the description needs
/// more bytes than the source holds.
MalformedFseTable,
/// A backwards stream whose last byte is zero, so it carries no final 1
/// bit (`§3.1.1.3.2.1.2`, `§4.2.2`).
MissingStartBit,
/// A read ran past the stream's start (`§4.1`).
InvalidBitStream,
/// Bits left over once the last symbol was decoded (`§3.1.1.3.2.1.2`:
/// "At the end, the bitstream shall be entirely consumed").
BitstreamNotConsumed,
}Everything the FSE layer reports.
pub const accuracy_log_max: u5 = 9
src
The largest accuracy log any zstd FSE context uses: the literals length
and match length code tables cap at 9, the offset code table at 8, and
the Huffman weights at 6 (§3.1.1.3.2.1 Table 15, §4.2.1.2).
pub const table_size_max = 1 << accuracy_log_max
src
The largest table any context builds: 1 << accuracy_log_max cells.
pub const symbol_count_max = 256
src
"That expected number of symbols never exceeds 256" (§4.1.1).
Functions
pub fn readDescription(
source: []const u8,
symbol_value_max: u16,
accuracy_log_cap: u5,
) Error!Description
src
Read a distribution table description (§4.1.1) from the front of
source.
more
symbol_value_max is the context's last symbol index (35, 52, and 31 for
the literals length, match length, and offset code tables, 255 for the
Huffman weights) and accuracy_log_cap its accuracy log cap. The
description can cover fewer symbols than the context allows but never
more. Returns MalformedFseTable for a description that breaks the rules
listed on that error.
pub fn buildTable(counts: []const i16, accuracy_log: u5) Table
src
Build the decoding table from normalized counts (§4.1.1's
construction). counts runs from symbol 0 to the last present one.
Types
struct
Description
src
A normalized-count table description (§4.1.1): the probability of each
symbol from 0 to the last present one, on a scale of
1 << accuracy_log. -1 is the "less than 1" probability, which "counts
as 1" point.
Fields
counts: [symbol_count_max]i16
Only the first symbol_count entries are meaningful.
symbol_count: u16
The number of symbols the description covers: the distribution runs
from symbol 0 to symbol_count - 1.
accuracy_log: u5
bytes_consumed: usize
The bytes the description consumed: "The bitstream consumes a round
number of bytes" (§4.1.1).
struct
State
src
A decoding state (§4.1): an index into a table.
Fields
index: u16
Functions
"To obtain the initial state value, consume Accuracy_Log bits from
the stream as a little-endian value" (§4.1).
"The next symbol in the stream is the Symbol indicated in the table
for that state" (§4.1).
"To obtain the next state value, the decoder should consume Num_Bits
bits from the stream as a little-endian value and add it to
Baseline" (§4.1).
module
literals
src
The literals section (§3.1.1.3.1) and its Huffman streams.
Constants
value
error{
/// The 1-5 byte literals header (`§3.1.1.3.1.1`): a source too short for
/// the Size_Format its first byte declares.
MalformedLiteralsHeader,
/// A declared size beyond what the block or the target can hold: a
/// Regenerated_Size or Compressed_Size past the block content, a
/// Regenerated_Size past the caller's target, a 4-stream Jump_Table
/// whose sizes exceed the streams region, or a 4-stream section below
/// errata 7297's 6 regenerated literals.
LiteralsTooLarge,
/// Treeless literals with no previous Huffman table in the frame
/// (`§3.1.1.3.1.1`).
TreelessLiteralsFirst,
} || huff0.ErrorEverything the literals layer reports.
pub const jump_table_len = 6
src
§3.1.1.3.1.6 — "The Jump_Table is 6 bytes long and consists of three
2-byte little-endian fields".
pub const min_literals_for_4streams = 6
src
Errata 7297 (§3.1.1.3.1.6): the 4-stream size ranges are 6-1023,
6-16383, and 6-262143, not 0-based. Below 6 the fourth stream's size,
Regenerated_Size - 3 * ((Regenerated_Size+3)/4), can underflow. The C
reference enforces it as MIN_LITERALS_FOR_4_STREAMS.
Functions
pub fn parseHeader(source: []const u8) error{MalformedLiteralsHeader}!Header
src
Parse a Literals_Section_Header (§3.1.1.3.1.1, Table 12). A source too
short for the form the first byte declares is MalformedLiteralsHeader.
Decode one literals section from the front of source (a compressed
block's content) into target (the caller's literals scratch, up to the
block maximum), updating state when the section is Compressed.
Every path is bounded: the decoded literals never exceed
Regenerated_Size, Regenerated_Size never exceeds target.len, and every
read stays inside the block content — a declaration that would break
either is LiteralsTooLarge, before any write.
Types
struct
Header
src
A parsed Literals_Section_Header (§3.1.1.3.1.1, Table 12).
Fields
block_type: BlockType
size_format: u2
The Size_Format field; its width and meaning follow the block type's
family (§3.1.1.3.1.1).
regenerated_size: u20
Regenerated_Size: the literals the section decodes to (5-20 bits).
compressed_size: u18
Compressed_Size: the section's content length for the compressed
family — "includes the size of the Huffman_Tree_Description when it
is present" (§3.1.1.3.1.1) — 10-18 bits. Zero for Raw and RLE,
which carry no such field.
header_len: usize
The header's own length in bytes: 1-5.
struct
State
src
The literals layer's cross-block state (§3.1.1.3): the decode table of
the frame's most recent Compressed_Literals_Block, which a
Treeless_Literals_Block reuses ("The Huffman tree comes from the previous
Compressed_Literals_Block"). One per frame, threaded through the block
loop; only a Compressed block updates it, and Raw, RLE, and Treeless
blocks leave it alone. A dictionary (§5) seeds table with its own tree
instead, so a Treeless block is legal from the frame's first block.
Fields
built: huff0.DecodeTable
The frame's own decode table, built by its first Compressed_Literals_Block; undefined until then, so initializing the frame that never builds one does not pay to zero it.
table: ?*const huff0.DecodeTable
The table a Treeless_Literals_Block reuses: the frame's own built
once a Compressed section decoded, else the dictionary's table when
one seeded the frame. null when neither exists; Treeless before
that is TreelessLiteralsFirst.
Constants
A frame state before its first literals section: no decode table and no reusable tree.
struct
Section
src
One decoded literals section.
Fields
bytes: []u8
The literals: Regenerated_Size bytes, a prefix of the caller's
target — exactly what Sequence Execution copies from (§3.1.1.4).
bytes_consumed: usize
How much of the block content the section consumed: the header, the
tree description when present, the Jump_Table, and the streams. The
sequences section starts here (§3.1.1.3.2).
module
sequences
src
The sequences section (§3.1.1.3.2) and Sequence Execution
(§3.1.1.4).
Constants
value
error{
/// The section's fixed-size fields — the Number_of_Sequences bytes, the
/// Symbol_Compression_Modes byte, an RLE_Mode symbol byte — run past the
/// block's remaining bytes (`§3.1.1.3.2.1`). The reference's
/// `srcSize_wrong`; never `Truncated`, which is the input's end.
MalformedSequencesHeader,
/// `§3.1.1.3.2.1` — "The last field, Reserved, must be all zeroes."
ReservedModeBits,
/// `§3.1.1.3.2.1` — Repeat_Mode "used without any previous sequence
/// table in the frame ... to repeat, this should be treated as
/// corruption."
RepeatModeFirst,
/// A sequence's literals_length reaches past the literals section's
/// Regenerated_Size — a declared size the section cannot supply.
LiteralsTooLarge,
/// A sequence or the trailing literals would write past the caller's
/// `target` (`§3.1.1.2.4`'s Block_Maximum_Size is the caller's cap).
BufferTooSmall,
/// `§3.1.1.5` — the repeat-offset arithmetic reached offset 0: an
/// offset_value of 3 with literals_length 0 means Repeated_Offset1 - 1
/// byte, which is 0 when Repeated_Offset1 is 1. The C reference and std
/// reject it too.
ZeroOffset,
/// `§3.1.1.4` — "all offsets leading to previously decoded data must be
/// smaller than Window_Size": the offset reaches past the history the
/// caller authorized.
OffsetTooFar,
} || fse.ErrorEverything the sequences layer reports.
pub const literals_length_code_max: u8 = 35
src
§3.1.1.3.2.1.1, Table 16 — literals length codes 0-35, "They define
lengths from 0 to 131071 bytes."
pub const match_length_code_max: u8 = 52
src
§3.1.1.3.2.1.1, Table 17 — match length codes 0-52, "They define lengths
from 3 to 131074 bytes."
pub const offset_code_max: u5 = 31
src
§3.1.1.3.2.1.1 — "A decoder is free to limit its maximum supported
value for N. Support for values of at least 22 is recommended. At the time
of this writing, the reference decoder supports a maximum N value of 31."
This decoder uses the reference's 31.
pub const offset_value_max: u32 = (@as(u32, 1) << offset_code_max) + 0x7fffffff
src
§3.1.1.3.2.1.1 — an offset code's Offset_Value = (1 << offsetCode) + readNBits(offsetCode), "supporting back-reference distance up to
(2^(N+1)) - 4".
pub const alphabet_count = @typeInfo(Alphabet).@"enum".field_names.len
src
The alphabets' number.
pub const literals_length_codes: [literals_length_code_max + 1]Code = …
src
value
blk: {
@setEvalBranchQuota(10_000);
var codes: [literals_length_code_max + 1]Code = undefined;
for (codes[0..16], 0..) |*code, length| code.* = .{ .baseline = length, .extra_bits = 0 };
const bands = [20]Code{
.{ .baseline = 16, .extra_bits = 1 },
.{ .baseline = 18, .extra_bits = 1 },
.{ .baseline = 20, .extra_bits = 1 },
.{ .baseline = 22, .extra_bits = 1 },
.{ .baseline = 24, .extra_bits = 2 },
.{ .baseline = 28, .extra_bits = 2 },
.{ .baseline = 32, .extra_bits = 3 },
.{ .baseline = 40, .extra_bits = 3 },
.{ .baseline = 48, .extra_bits = 4 },
.{ .baseline = 64, .extra_bits = 6 },
.{ .baseline = 128, .extra_bits = 7 },
.{ .baseline = 256, .extra_bits = 8 },
.{ .baseline = 512, .extra_bits = 9 },
.{ .baseline = 1024, .extra_bits = 10 },
.{ .baseline = 2048, .extra_bits = 11 },
.{ .baseline = 4096, .extra_bits = 12 },
.{ .baseline = 8192, .extra_bits = 13 },
.{ .baseline = 16384, .extra_bits = 14 },
.{ .baseline = 32768, .extra_bits = 15 },
.{ .baseline = 65536, .extra_bits = 16 },
};
for (bands, 16..) |band, index| codes[index] = band;
break :blk codes;
}§3.1.1.3.2.1.1, Table 16 — "Literals length codes are values ranging
from 0 to 35 ... Codes 0-15 are the literal length itself" with no extra
bits, then the baseline/extra-bits bands up to code 35's 65536 + 16 bits.
pub const match_length_codes: [match_length_code_max + 1]Code = …
src
value
blk: {
@setEvalBranchQuota(10_000);
var codes: [match_length_code_max + 1]Code = undefined;
for (codes[0..32], 0..) |*code, symbol| code.* = .{ .baseline = symbol + 3, .extra_bits = 0 };
const bands = [21]Code{
.{ .baseline = 35, .extra_bits = 1 },
.{ .baseline = 37, .extra_bits = 1 },
.{ .baseline = 39, .extra_bits = 1 },
.{ .baseline = 41, .extra_bits = 1 },
.{ .baseline = 43, .extra_bits = 2 },
.{ .baseline = 47, .extra_bits = 2 },
.{ .baseline = 51, .extra_bits = 3 },
.{ .baseline = 59, .extra_bits = 3 },
.{ .baseline = 67, .extra_bits = 4 },
.{ .baseline = 83, .extra_bits = 4 },
.{ .baseline = 99, .extra_bits = 5 },
.{ .baseline = 131, .extra_bits = 7 },
.{ .baseline = 259, .extra_bits = 8 },
.{ .baseline = 515, .extra_bits = 9 },
.{ .baseline = 1027, .extra_bits = 10 },
.{ .baseline = 2051, .extra_bits = 11 },
.{ .baseline = 4099, .extra_bits = 12 },
.{ .baseline = 8195, .extra_bits = 13 },
.{ .baseline = 16387, .extra_bits = 14 },
.{ .baseline = 32771, .extra_bits = 15 },
.{ .baseline = 65539, .extra_bits = 16 },
};
for (bands, 32..) |band, index| codes[index] = band;
break :blk codes;
}§3.1.1.3.2.1.1, Table 17 — "Match length codes are values ranging from 0
to 52 ... Codes 0-31 are Match_Length_Code + 3" with no extra bits, then
the bands up to code 52's 65539 + 16 bits.
pub const offset_codes: [offset_code_count]Code = …
src
value
blk: {
@setEvalBranchQuota(10_000);
var codes: [offset_code_count]Code = undefined;
for (&codes, 0..) |*code, symbol| {
code.* = .{ .baseline = @as(u32, 1) << @intCast(symbol), .extra_bits = @intCast(symbol) };
}
break :blk codes;
}§3.1.1.3.2.1.1 — "Offset_Value = (1 << offsetCode) + readNBits(offsetCode)",
so the offset code's Baseline is the 1 << code term and its extra bits
are the code itself. Codes 0-31 are the reference's range; the predefined
offset table (§3.1.1.3.2.2.3) tops out at 28.
pub const literals_length_distribution = …
src
value
[36]i16{
4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2,
2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1,
}§3.1.1.3.2.2.1 — literalsLength_defaultDistribution[36], "The decoding
table uses an accuracy log of 6 bits (64 states)", transcribed verbatim.
pub const match_length_distribution = …
src
value
[53]i16{
1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
}§3.1.1.3.2.2.2 — matchLengths_defaultDistribution[53], accuracy log 6.
pub const offset_distribution = …
src
value
[29]i16{
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-1, -1, -1, -1, -1,
}§3.1.1.3.2.2.3 — offsetCodes_defaultDistribution[29], accuracy log 5,
"supports a maximum N value of 28".
pub const repeat_offsets_start = [3]u32{ 1, 4, 8 }
src
§3.1.1.5 — "For the first block, the starting offset history is
populated with the following values: Repeated_Offset1 (1), Repeated_Offset2
(4), and Repeated_Offset3 (8)".
Functions
pub fn parseHeader(source: []const u8) Error!Header
src
Parse a Sequences_Section_Header (§3.1.1.3.2.1) from the front of a
compressed block's sequences section.
pub fn readDictionaryTable(
alphabet: Alphabet,
source: []const u8,
) error{MalformedFseTable}!DictionaryTable
src
Read one of a dictionary's FSE table descriptions (§5): "They are stored
in the following order: Huffman table for literals, FSE table for offsets,
FSE table for match lengths, and FSE table for literals lengths." The
description is the compressed-block form (fse.readDescription,
§4.1.1) read with the alphabet's own symbol and accuracy caps, fused
with the alphabet's codes — the exact table a Repeat_Mode reuses.
source is the dictionary from this table's first byte to its end (the
next table, the 12 repcode bytes, or the content). A description that
runs past it is MalformedFseTable (the reader's own name), never an
overread.
pub fn decode(
source: []const u8,
literals_bytes: []const u8,
target: []u8,
history_len: usize,
dict: []const u8,
dict_limit: u64,
state: *State,
) Error!Section
src
Decode one sequences section: source is the block's bytes after the
literals section (Sequences_Section_Size, §3.1.1.3.2), literals_bytes
the decoded literals Sequence Execution copies from, and target the
caller's contiguous output region — target[0..history_len] is the
history a match can read (the caller caps it at the frame's Window_Size,
§3.1.1.4), target[history_len..] where this block's output is written.
state carries the frame's tables and repeat offsets across blocks.
more
dict is §5's dictionary content, conceptually in front of target[0],
and dict_limit is the region-relative match position up to which it is
addressable — §5's Window_Size boundary, derived by the caller ("as long
as the amount of data decoded from this frame is less than or equal to
Window_Size, sequence commands may specify offsets ... to reference back
to the dictionary ... after the total output has surpassed Window_Size,
... the dictionary is no longer accessible"). A match reaching into it
past that boundary, or deeper than the content holds, is OffsetTooFar.
The empty slice (no dictionary) refuses every reach, exactly as the
history bound did before dictionaries existed.
Every declared size is a bound: the output never exceeds target, the
literals read never exceeds literals_bytes, and no offset reaches past
the authorized history — the bound failures are BufferTooSmall,
LiteralsTooLarge, and OffsetTooFar, raised before the offending write.
Types
struct
Code
src
One §3.1.1.3.2.1.1 code: "The [value] is equal to the decoded Baseline
plus the result of reading Number_of_Bits bits from the bitstream, as a
little-endian value."
Fields
baseline: u32
extra_bits: u5
The RFC's Number_of_Bits: the extra bits read after the code's own.
struct
SeqTable
src
A sequences decoding table: the FSE table's 1 << log cells, each fused
with the alphabet's code. This is the form the decode loop reads, and the
form a dictionary carries one of per alphabet (Dictionary): a
Repeat_Mode points State.tables at it, in the frame's own storage or in
the dictionary's.
Fields
struct
Header
src
A parsed Sequences_Section_Header (§3.1.1.3.2.1).
Fields
sequence_count: u32
Number_of_Sequences: 0, 1-127, ((byte0 - 128) << 8) + byte1, or
byte1 + (byte2 << 8) + 0x7F00 (at most 98047).
count_len: usize
The count field's own length: 1-3 bytes.
modes: ?Modes
The Symbol_Compression_Modes byte's three fields (Table 14), null
when the count is zero: "The sequence section stops here", so no mode
byte follows.
struct
DictionaryTable
src
One of a dictionary's three FSE table descriptions (§5): the table the
parse built, the description's normalized counts (the encode side's table
and its ZSTD_dictNCountRepeat promotion are built from the same parse),
and the bytes its description consumed.
Fields
struct
State
src
The sequences layer's cross-block state (§3.1.1.3): the three decoding
tables a Repeat_Mode reuses and the three repeat offsets (§3.1.1.5).
One per frame, threaded through the block loop; only a Compressed_Block
with a nonzero sequence count updates it ("blocks that are not
Compressed_Block are skipped; they do not contribute to offset history"),
and a zero-count section leaves it alone. A dictionary (§5) seeds the
state instead of frame.State.init's empty seats: tables point at the
dictionary's parsed tables, and repeat_offsets are its 12 bytes.
Fields
built: [alphabet_count]SeqTable
Storage for the tables a block builds (the FSE_Compressed and RLE modes), about 12 KB in all. Undefined until a mode writes a cell, so a new frame state does not pay to zero it.
tables: [alphabet_count]?*const SeqTable
The table each alphabet last decoded with, null until the frame's
first sequences section with a nonzero count. "The table used in the
previous Compressed_Block with Number_Of_Sequences > 0 will be used
again ... It also includes Predefined_Mode ... and RLE_Mode", so every
mode stores its resolved table here — Predefined by pointer to the
comptime table (no per-block copy), the built modes into built.
repeat_offsets: [3]u32
Repeated_Offset1/2/3 "sorted in recency order, with Repeated_Offset1
meaning 'most recent one'" (§3.1.1.5), seeded {1, 4, 8} "for the
first block ... unless a dictionary is used". A dictionary's 12
repcode bytes replace the seed; a raw dictionary has none, so it
keeps the default.
Constants
value
.{
.built = undefined,
.tables = @splat(null),
.repeat_offsets = repeat_offsets_start,
}A frame state before its first sequences section: no resolved tables and the §3.1.1.5 {1, 4, 8} repeat-offset seed.
struct
Section
src
One decoded sequences section.
Fields
bytes_written: usize
The block's output: bytes_written bytes at target[history_len..].
bytes_consumed: usize
The section bytes consumed. Always all of source on success — the
bitstream is the block's tail and "shall be entirely consumed"
(§3.1.1.3.2.1.2) — returned so the block layer checks its derived
Sequences_Section_Size against it (§3.1.1.3.2).
module
Reader
src
The streaming decoder: an Io.Reader that decompresses one Zstandard
frame, the caller-owned window buffer Reader.Buffer, and the
streamFrame and streamAll pumps.
Constants
pub const default_window_len: usize = 8 * 1024 * 1024
src
The default window cap, 8 MiB. §3.1.1.1.2 recommends that decoders
support Window_Size up to 8 MB, and zstd -19 writes windowLog 23 (8 MiB)
for large inputs.
pub const DefaultBuffer = Buffer(default_window_len)
src
Buffer(default_window_len): 8 MiB of window, 128 KiB serving, and
128 KiB staging. That is larger than a typical 8 MiB thread stack, so
allocate it, as streamFrameAlloc does.
value
error{
BadMagic,
ReservedBitSet,
DictionaryRequired,
DictionaryMismatch,
BlockOversize,
ReservedBlock,
MalformedLiteralsHeader,
LiteralsTooLarge,
TreelessLiteralsFirst,
MalformedHuffmanWeights,
MalformedFseTable,
MalformedSequencesHeader,
RepeatModeFirst,
ReservedModeBits,
MissingStartBit,
InvalidBitStream,
BitstreamNotConsumed,
ZeroOffset,
OffsetTooFar,
ContentSizeMismatch,
WrongChecksum,
Truncated,
/// The frame declares a Window_Size larger than the buffer's `window_len`
/// (`§3.1.1.1.2`: a decoder may reject a frame that "requests a memory
/// size beyond the decoder's authorized range"). Reported once the header
/// is parsed, before any block byte is read; the output is never
/// truncated instead.
WindowTooLarge,
/// A contiguous request (`peek`, `take`, ...) is larger than the serving
/// region can hold at the consumer's position. Requests of up to 128 KiB
/// never hit this. A consumer can trigger it, so it is an error and not
/// an assert.
StreamTooLong,
/// The input reader failed with `error.ReadFailed`.
ReadFailed,
/// The clean end of the frame. The interface reports it as
/// `error.EndOfStream`; it is never recorded in `err`.
EndOfStream,
}The reader's error set; err holds one of these once state == .failed.
It is the one-shot decoder's DecompressError (frame.Error) without
BufferTooSmall (the window is the caller's buffer, not a target cap, so
no decode can outgrow it), plus WindowTooLarge, StreamTooLong, and the
interface's ReadFailed and EndOfStream. The Io.Reader interface
itself reports only error.ReadFailed or error.EndOfStream.
pub const StreamAllocError = Io.Reader.StreamRemainingError || error{OutOfMemory}
src
The error set of streamFrameAlloc and streamAllAlloc: streamFrame's
(error.ReadFailed, error.WriteFailed) plus error.OutOfMemory from the
buffer allocation.
Functions
pub fn init(
comptime window_len: usize,
input: *Io.Reader,
buffer: *Buffer(window_len),
dict: ?*const Dictionary,
) Reader
src
Read one Zstandard frame from input, decoding through buffer.
Skippable frames before the frame are skipped. window_len is the largest
Window_Size the reader accepts, and buffer must be a
Buffer(window_len), which the compiler checks at the call. dict seeds
the frame's starting state (§5): its entropy tables, its repeat offsets,
and its content as the preset history. null is the no-dictionary reader;
a frame that names a nonzero Dictionary_ID then fails DictionaryRequired
(or DictionaryMismatch when a non-matching dictionary was supplied).
input needs a buffer of at least four bytes. init reads nothing from
input and allocates nothing.
more
Read through &r.reader (stream, the read family, the peek family).
Once the trailer is verified, reads return error.EndOfStream. A
malformed frame or a failing input returns error.ReadFailed, and so
does every later read, with the detail in err. The reader consumes
input exactly through the frame's last byte and leaves any later bytes
unread.
pub fn streamFrame(
comptime window_len: usize,
in: *Io.Reader,
out: *Io.Writer,
buffer: *Buffer(window_len),
dict: ?*const Dictionary,
) Io.Reader.StreamRemainingError!usize
src
Decode one frame from in into out through buffer, and return the
number of bytes written. Skippable frames before the frame are skipped
(§3.1.2). dict seeds the frame's starting state (§5), as
Reader.init's. in is consumed exactly through the frame's last byte
(the checksum trailer's, when the frame has one) and later bytes are left
unread. An empty in is an error, because it holds no frame. in needs a
buffer of at least four bytes. Failures are reported as error.ReadFailed
(a malformed frame or a failing in) or error.WriteFailed (a failing
out); a caller who needs the detail drives a Reader directly and reads
err. Does not allocate.
pub fn streamAll(
comptime window_len: usize,
in: *Io.Reader,
out: *Io.Writer,
buffer: *Buffer(window_len),
dict: ?*const Dictionary,
) Io.Reader.StreamRemainingError!usize
src
Decode every frame in in into out through buffer, and return the
total number of bytes written. The output is the concatenation of the
frames (§3.1). Each frame is decoded as in streamFrame, starting where
the previous one ended. Skippable frames are skipped, so an input that
holds only skippable frames, or nothing at all, decodes to zero bytes. Any
other bytes where a frame starts are BadMagic, reported as
error.ReadFailed; they are not skipped. dict seeds every frame's
starting state (§5), as Reader.init's. in needs a buffer of at least
four bytes. Other failures are reported as in streamFrame. Does not
allocate.
pub fn streamFrameAlloc(
allocator: mem.Allocator,
in: *Io.Reader,
out: *Io.Writer,
dict: ?*const Dictionary,
) StreamAllocError!usize
src
streamFrame with the default 8 MiB window. Allocates a DefaultBuffer
(8 MiB + 256 KiB) from allocator for the call and frees it before
returning; the decoder itself allocates nothing. Returns
error.OutOfMemory, before reading any input, if the allocation fails. A
caller who wants a smaller window, or no allocation, uses streamFrame
with its own Buffer(window_len).
pub fn streamAllAlloc(
allocator: mem.Allocator,
in: *Io.Reader,
out: *Io.Writer,
dict: ?*const Dictionary,
) StreamAllocError!usize
src
streamAll with the default 8 MiB window. Allocates a DefaultBuffer
(8 MiB + 256 KiB) from allocator for the call and frees it before
returning; the decoder itself allocates nothing. Returns
error.OutOfMemory, before reading any input, if the allocation fails.
Types
type fn
Buffer
src
pub fn Buffer(comptime window_len: usize) type
The caller-owned decode buffer for frames whose Window_Size is at most
window_len (§3.1.1.1.2). It holds window_len bytes of retained
history plus one maximum-size block (128 KiB, §3.1.1.2.4) as the
serving region, then room to stage one block's content (stagingLength):
window_len + 128 KiB + min(window_len, 128 KiB) bytes in all. init
takes a pointer to this exact type and reads the window cap from it, so
the buffer and the cap cannot disagree. window_len must be at least
1 KiB, the smallest window the format allows; Buffer(0) does not
compile.
module
Writer
src
The streaming encoder: an Io.Writer that compresses into one Zstandard
frame, the caller-owned Writer.Buffer, and the streamAll and
streamAllAlloc pumps.
Constants
pub const default_window_log: usize = 19
src
The default window log, 19: a 512 KiB window, the largest level 1
declares. It stays inside the decoder's default 8 MiB window
(Reader.default_window_len), so a default Reader decodes any frame
this writer produces.
pub const level3_default_window_log: usize = 21
src
The level-3 default window log, 21: the dfast class's own window (the
clevels.h default row's W), which the CLI's zstd -3 declares. A
level-3 Writer needs Buffer(21) to reach the class's window.
pub const DefaultBuffer = Buffer(default_window_log)
src
Buffer(default_window_log): about 2.2 MiB, larger than a typical thread
stack, so allocate it, as streamAllAlloc does.
pub const StreamAllocError = Io.Reader.StreamRemainingError || error{OutOfMemory}
src
The error set of streamAllAlloc: streamAll's (error.ReadFailed,
error.WriteFailed) plus error.OutOfMemory from the buffer allocation.
Functions
pub fn defaultWindowLog(level: encode.Level) usize
src
The default window log for a level: default_window_log for level 1 and
level3_default_window_log for level 3.
pub fn init(
comptime window_log: usize,
output: *Io.Writer,
buffer: *Buffer(window_log),
options: encode.Options,
) Writer
src
Start a Zstandard frame into output, accumulating input in buffer.
The frame declares a 1 << window_log window and no Frame_Content_Size
(§3.1.1.1.2). window_log must be 10 to 31. options are fixed for
the stream's lifetime; changing w.options afterwards is not supported.
Write through &w.writer, then call finish. init writes nothing,
allocates nothing, and zeroes the finder's tables.
Complete the frame: emit the buffered block as the frame's last block,
write the checksum trailer, and flush output. The frame is complete
only after this call, and the writer is unusable afterwards.
Returns error.WriteFailed if output fails. A writer that already
failed or already finished also returns error.WriteFailed, so a
truncated frame is never reported as complete. An empty writer still
writes a frame: the header, one raw zero-size last block, and the
checksum.
pub fn streamAll(
comptime window_log: usize,
in: *Io.Reader,
out: *Io.Writer,
buffer: *Buffer(window_log),
options: encode.Options,
) Io.Reader.StreamRemainingError!usize
src
Compress everything in yields into one complete Zstandard frame in
out, and return the number of input bytes consumed. The frame is
finished and out is flushed before the call returns; in is consumed
exactly through its end. Writes through buffer, a
Buffer(window_log) the caller owns (about 2.2 MiB at the default
window_log), so this needs no large stack local of its own.
Returns error.WriteFailed if out fails and error.ReadFailed if in
fails. Does not allocate.
pub fn streamAllAlloc(
allocator: mem.Allocator,
in: *Io.Reader,
out: *Io.Writer,
options: encode.Options,
) StreamAllocError!usize
src
streamAll with the default window log for the level: 19 for level 1,
21 for level 3 (the dfast class's window). Allocates one DefaultBuffer
(about 2.2 MiB) or Buffer(level3_default_window_log) (about 3.6 MiB)
from allocator for the call and frees it before returning; the writer
itself allocates nothing. Returns error.OutOfMemory, before reading any
input, if the allocation fails. A caller who wants a different window, or
no allocation, uses streamAll with its own Buffer(window_log).
Types
type fn
Buffer
src
pub fn Buffer(comptime window_log: usize) type
The caller-owned encode buffer for a frame that declares a
1 << window_log window (§3.1.1.1.2). It holds the retained history
and the accumulating block as one contiguous slice — the match finder
reads across the boundary (§3.1.1.4) — plus the block's literals, the
compressed-block scratch, the finder's position table, and the block's
sequence list. Every array whose size the window implies lives here, so
the writer's own frame is KiB-scale and no allocation happens on any
path. init takes a pointer to this exact type and reads the window from
it, so the buffer and the declared window cannot disagree. window_log
must be 10 to 31, the format's Window_Log range; Buffer(0) does not
compile.
Fields
window: [historyLength(window_log) + blockLength(window_log)]u8
The finder's source: historyLength(window_log) bytes of
retained history, then the accumulating block.
literals: [blockLength(window_log)]u8
The block's literals, in the order the finder extracts them.
target: [blockLength(window_log) + block.block_header_len]u8
The compressed block's output: the raw form's worst case
(blockLength(window_log) + block.block_header_len bytes), so
no block can outgrow it.
long_table: [longTableEntries(window_log)]u32
The finder's position tables, one u32 per hash, zeroed at
init; a zeroed slot means "no candidate". A frame that attaches
a dictionary uses the dictionary's own widths (up to 17 long and
16 small at level 3), so the capacity covers them at every
window; the scans slice the live width.
small_table: [smallTableEntries(window_log)]u32
dfast's small table; the level-1 finder leaves it unused.
sequences: [sequenceCapacity(window_log)]sequences_compress.Sequence
The block's sequence list.
module
Dictionary
src
A parsed dictionary (RFC 8878 §5): parse reads the formatted form,
initRaw takes format-free content. The value is handed to either
direction and borrows the caller's bytes.
Constants
§5 — "Magic_Number: 4 bytes, little-endian format. Value: 0xEC30A437."
The Magic_Number's 4 bytes (§5).
§5 — "Dictionary_ID: 4 bytes, little-endian format. ... any value,
except 0 (which means no Dictionary_ID)".
pub const repcodes_len = 12
src
§5 — "3 offset values, populating repeat offsets ... stored in order,
4 bytes little-endian each, for a total of 12 bytes."
pub const ParseError = …
src
value
error{
/// The source ends before the magic, inside the Dictionary_ID, or inside
/// the 12 repcode bytes. A table description cut short is its reader's
/// own error instead (`MalformedHuffmanWeights`, `MalformedFseTable`):
/// the description's length is decoded from its own bytes.
Truncated,
/// The first four bytes are not `0xEC30A437` LE: not the formatted form.
BadDictionaryMagic,
/// `§5` — the Dictionary_ID is 0, "which means no Dictionary_ID". The C
/// reads a zero ID and keeps going (DT4); ours fails closed at the parse.
InvalidDictionaryId,
/// `§5` — a repeat offset is 0 or above the content size. The RFC's word
/// is "the dictionary size"; the references enforce the content size,
/// the only reading consistent with the trainer's output (DT2).
InvalidDictionaryRepcode,
/// `§4.2.1` — the literals tree description is cut short or its weights
/// do not form a valid tree. Incomplete statistics are legal (§5's
/// tables are the block forms): zero weights are accepted.
MalformedHuffmanWeights,
/// `§4.1.1` — one of the three FSE descriptions is cut short, exceeds its
/// context's caps, or its budget does not land exactly. Zero-probability
/// symbols are legal: the table can cover less than its whole alphabet.
MalformedFseTable,
}Everything parse reports. The first four names are this layer's; the
last two are the shared readers' (huff0.readTree, fse.readDescription)
for a table description that is cut short or malformed — the same names
the block layer reports for the same bytes.
Functions
Parse a formatted dictionary (§5) from source.
more
The entropy tables are read with the same parsers a compressed block's
tables go through (huff0.readTree, then fse.readDescription for
offsets, match lengths, and literals lengths with the caps 31/8, 52/9,
35/9), and the tables are built once here — nothing re-parses per frame
or block. The returned value borrows source: the content slice and the
table descriptions are never copied, so keep the bytes alive as long as
the value is used.
Errors are ParseError's: a malformed piece fails with its own name,
raised before any table is handed out.
pub fn matchParams(self: *const Dictionary, level: u8) match_compress.DictParams
src
The dictionary's own parameters for a level (the C's CDict cParams),
which a frame's window, hash widths, and match width are drawn from
(ZSTD_resetCCtx_byAttachingCDict / ..._byCopyingCDict).
A raw-content dictionary (§5): "Zstandard is compatible with 'raw
content' dictionaries, free of any format restriction ... These
dictionaries function as if they were just the content part of a
formatted dictionary." Content only: no tables (so no Treeless literals
or Repeat sequences from the first block), the default {1,4,8} repeat
offsets, and no Dictionary_ID — it never satisfies a frame that declares
one (the C decoder's shape; klauspost's ID-assigning raw form is not
ported).
Infallible and format-free: any bytes parse, and §5's 8-byte floor is not
enforced (the references accept shorter content too). The value borrows
content.