compress#
DEFLATE, zlib, gzip, Brotli, LZ4, Zstandard, CRC-32, Adler-32 and xxHash, codec ids -- crate root lib/compress/lib.rs
compress -- lossless compression: DEFLATE, zlib, gzip, Brotli, LZ4 and Zstandard
deflate::compress(data, level) / decompress(data, max_out) raw DEFLATE (RFC 1951)
zlib::compress / decompress zlib streams (RFC 1950)
gzip::compress / decompress gzip members (RFC 1952; decompress reads
all members, as gunzip does)
brotli::compress(data, level) / decompress Brotli streams (RFC 7932; levels 0 to 11,
read by libbrotli and the browsers)
lz4::compress(data) -> Vec<u8> LZ4 block (greedy, 64 KiB window)
lz4::compress_hc(data, level) LZ4 block, longest matches (as lz4 -9)
lz4::decompress(block, max_out) -> Option<Vec> bounds-checked; None on any corruption
lz4::frame_compress / frame_decompress the LZ4 frame format (lz4 / zstd --format=lz4
interoperable), xxHash32 checksums
zstd::compress(data, level) / decompress Zstandard frames (RFC 8878; the zstd tool
reads ours and we read its)
zstd::Dictionary, compress_with_dict / decompress_with_dict dictionaries: trained on
samples or raw content, as zstd -D uses them
crc32(crc, data), adler32(adler, data) the checksums of gzip / PNG / ZIP and zlib
xxh32(data, seed), xxh64(data, seed); Xxh32, Xxh64 the same over data in pieces
stream::{Decode, Encode} every format in pieces, with bounded memory:
deflate::, zlib::, gzip::, zstd::Decoder /
Encoder, lz4::FrameDecoder / FrameEncoder,
brotli::Decoder / Encoder; decode(input, out) /
encode(input, out, flush) -> Step; the
pumps stream::decode_all / encode_all
Codec { None, Lz4, Zstd } with id(): the codec byte that formats on disk store per blob;
Codec::pack(data, level) / unpack(data, max_out)
Every decoder takes the largest output the caller accepts and treats its input as untrusted:
truncated or corrupt data, a wrong checksum or more output than allowed give None (or an
Error from the *_into variants), never a panic and never a read or write outside the buffers.
The stream decoders write at most the caller's buffer per call and keep no more than their
format's window (stream.rs).
compress crate root#
enum Codecthe compression of a stored blob (the byte on disk)None = 0Lz4 = 1Zstd = 2
impl Codec
fn id(self) -> u8fn from_id(b: u8) -> Option<Codec>fn name(self) -> &'static strfn from_name(s: &str) -> Option<Codec>fn pack(self, data: &[u8], level: i32) -> Vec<u8>compress with this codec (level: zstd only); None stores the data as it isfn unpack(self, data: &[u8], max_out: usize) -> Option<Vec<u8>>the data of pack(); None when it is damaged or longer than max_out
compress/brotli/mod.rs#
Source: lib/compress/brotli/mod.rs
brotli -- Brotli (RFC 7932) both ways, the Content-Encoding "br" of the web and the
compression of WOFF2 fonts and of JPEG XL's JPEG reconstruction data (until 0.2 in
img_jxl) [jxl-plus: no asm]
compress(data, level) -> stream levels 0..=11 (LEVEL_DEFAULT 5), the window
as small as the data allows (enc.rs)
decompress(data, max_out) -> Option<Vec<u8>> the stream that fills data completely;
None for a damaged stream, data after it
or more than max_out bytes
decompress_prefix(data, max_out) -> Ok((bytes, consumed)) the stream at the start of
data; Error::Corrupt for a damaged stream,
Error::Limit past max_out bytes
Decoder / Encoder in pieces (stream::Decode / Encode; sdec.rs,
senc.rs)
The decoder makes one pass over the whole input: bit reader, prefix codes (simple and
complex), block switches, context maps (RLE + move to front), insert-and-copy commands, the
distance ring buffer and the static dictionary with its 121 transforms (tab.rs, dict.bin;
tools/gen_brotli_dict.py). The output is bounded by max_out before it grows, every
distance is checked against the output so far. Large windows (an extension outside RFC
7932) are refused.
The bit reader holds up to 63 bits in a register, refilled eight bytes at a time (byte by
byte near the end). A prefix code is a table of its first 8 bits (fewer for short codes)
and second-level tables for the longer ones, so a symbol takes one or two lookups; reading
past the end fails exactly where reading bit by bit would.
/// the level of compress() for most uses, as for the responses of a web server
LEVEL_DEFAULT: i32 = 5
/// the strongest level, for files compressed once and sent often (as `brotli -q 11`)
LEVEL_MAX: i32 = 11
enum Errorwhy a Brotli stream could not be readCorrupt-- the stream is damaged, truncated or uses something RFC 7932 does not allowLimit-- the output would be larger than the caller allows
fn decompress(data: &[u8], max_out: usize) -> Option<Vec<u8>>the data of the Brotli stream that fillsdatacompletely, at mostmax_outbytesfn decompress_prefix(data: &[u8], max: usize) -> Result<(Vec<u8>, usize), Error>the Brotli stream at the start ofdata: (output, bytes of input used)
compress/brotli/enc.rs#
Source: lib/compress/brotli/enc.rs
brotli::enc -- Brotli compression (RFC 7932): compress(), and the parts brotli::Encoder
(senc.rs) shares with it
Levels 0 to 9 match greedily with lazy evaluation: hash chains over the window (deeper by
level), after the last distances and their neighbours (the short distance codes, a few
bits each); a candidate scores as in libbrotli (135 per byte, 30 per bit of distance); the
search skips ahead in data without matches. Levels 10 and 11 parse near-optimally: every
position's matches once, then the cheapest path through the meta-block under a cost model,
at level 11 a second time with the costs of the first path's commands (as libbrotli's
Zopfli parse). A position without a match looks for a word of the static dictionary, also
with a space before it, its first letter in upper case, one of 44 suffixes after it or up
to 9 of its last letters cut (the transforms of RFC 7932 appendix B). Each meta-block
(64 KiB to 1 MiB of input, by level) gets its own prefix codes: the literals 64 contexts
from the two bytes before them (the UTF-8 context mode for text, the signed one for the
rest, from level 9 whichever costs less), merged greedily into as few trees as pays, or
one tree when that takes fewer bits; the distances 4 contexts by copy length, merged the
same way. A meta-block that would come out larger than its input is stored.
const fn bound(n: usize) -> usizethe largest stream compress() makes from n bytesfn compress(data: &[u8], level: i32) -> Vec<u8>a Brotli stream ofdataatlevel(0..=11; brotli::LEVEL_DEFAULT is 5), with the smallest window that holds the data (at most 4 MiB, 16 MiB at levels 10 and 11)
compress/brotli/sdec.rs#
Source: lib/compress/brotli/sdec.rs
brotli::sdec -- brotli::Decoder, a Brotli stream in pieces
The decoder of mod.rs as a machine of small steps, each of which starts again when the
input runs out (stream::drive keeps the bytes of the step that ran out): the window bits,
a meta-block header, each of the three block-switch descriptions, the context modes, the
prefix code of a context map and then each of its entries, each prefix code of the
literals, commands and distances, and then per command: the insert-and-copy code with its
extra bits, each literal, the distance. The largest step is a prefix code of 704 symbols,
well under a kilobyte. Copies and uncompressed meta-blocks go out in pieces as the
caller takes them.
While the input surely holds the next part of a command (CMD_BITS, LIT_BITS, DIST_BITS:
the most a part can read) and the output has room for it, Core::fast runs whole commands
without the steps and their restarts; it stops in a state the steps go on from, so a call
ends where the steps alone would end it.
The output goes into a window of the stream's size ((1 << WBITS) - 16, at most 16 MiB):
it keeps that much of the output, as far as a distance may reach, and moves when it holds
more than twice that. Distances beyond it are static dictionary words, as in mod.rs.
struct Decodera Brotli decoder that takes its input in pieces (stream::Decode): one stream of RFC 7932, its window (at most 16 MiB, as the stream says) twice and 64 KiB of output
impl Decoder
fn new() -> Decoderfn reset(&mut self)start a new stream
compress/brotli/senc.rs#
Source: lib/compress/brotli/senc.rs
brotli::senc -- brotli::Encoder, a Brotli stream in pieces
The input collects in a buffer that keeps the window before the bytes not yet compressed;
a meta-block is compressed once its input and the 8 bytes after it are there (the match
finder looks that far ahead), with the same finder, codes and choices as compress(). So a
stream whose size is given (with_size) is the same bytes as compress() of the whole input;
without a size the window is the level's (4 MiB, 16 MiB at levels 10 and 11) or the one
with_window asks for. Flush::Sync ends a meta-block early and fills the last byte with an
empty metadata block. The buffer moves by a step (1 MiB, or the reach of the hash chains)
once it holds that much more than the window; the tables move with it.
struct Encodera Brotli encoder that takes its input in pieces (stream::Encode): one stream of RFC 7932; memory about twice the window and a meta-block (1 MiB at most), plus the tables of the level
impl Encoder
fn new(level: i32) -> Encoderan encoder atlevel(0..=11 as compress)fn with_size(mut self, bytes: u64) -> Encoderthe input is exactly this long (else Error::Size): the window and the tables fit it, and the stream is the same bytes as compress()fn with_window(mut self, log: u32) -> Encodera window of 2^log - 16 bytes (log 10..=24) instead of the level's: what a decoder must keep of the output
compress/checksum.rs#
Source: lib/compress/checksum.rs
checksum -- CRC-32 (zlib / PNG polynomial) and Adler-32 (until 0.2 img_core::checksum)
[src/img/checksum.s]
crc32(crc, data) -> u32 start with crc = 0 (like zlib's crc32())
adler32(adler, data) -> u32 start with adler = 1
CRC: table driven (slice-by-8 here, slice-by-4 in the assembly: the same values).
Adler-32: blocks of at most 5552 bytes summed exactly in 64 bit, both sums reduced mod
65521 after every block (as the assembly's SSE2 loop); a call with no data returns the
start value unchanged. The 16-byte groups add into 16 column sums, which the
compiler turns into vector code on every target (the crate depends on nothing, so the
build tools with std can use it too); the sums are exact, so the value is the same as the
assembly's psadbw / pmaddwd loop.
fn crc32(crc: u32, data: &[u8]) -> u32CRC-32 (zlib / PNG) of data, continuing crc (start with 0) [crc32]fn adler32(adler: u32, data: &[u8]) -> u32Adler-32 (zlib) of data, continuing adler (start with 1) [adler32]
compress/deflate/mod.rs#
Source: lib/compress/deflate/mod.rs
deflate -- raw DEFLATE data (RFC 1951), the compressed format inside zlib, gzip, ZIP and PNG
compress(data, level) -> Vec<u8> levels 0..=9 (LEVEL_DEFAULT 6; < 0 = 6, > 9 = 9)
decompress(data, max_out) -> Option<Vec<u8>> the whole input must be one DEFLATE stream;
None on corruption, data after the stream or
more than max_out bytes
compress_with(state, data, level) / compress_into(state, data, level, dst) /
compress_padded(state, data, level, head, tail) with a reusable state (None = a
temporary one), into the caller's buffer, or with
free bytes before and room after the data
decompress_into(state, data, dst) -> Ok((bytes, consumed)) into the caller's buffer;
consumed = the input bytes of the stream, so data
after it is the caller's to judge
bound(len) an output size with which compress_into never
fails
InflateState / DeflateState reusable decoder and encoder (~330 KB) states,
one thread at a time; a reused state gives the
same bytes and errors as a fresh one
Decoder / Encoder the same in pieces (stream::Decode / Encode):
sdec.rs, senc.rs (zlib and gzip wrap them)
The decoder checks every write against the output buffer and every back reference against
the bytes produced so far, so a corrupt or hostile stream ends with an Error, never with a
read or write outside the buffers. The encoder writes the same bytes on every platform
(zlib's levels: greedy 1..3, lazy 4..9, blocks as the cheapest of stored, fixed and
dynamic). dec.rs and enc.rs are the engines, zlib.rs and gzip.rs the two wrappers.
/// the level `compress` uses for a negative level, zlib's default
LEVEL_DEFAULT: i32 = 6
/// the strongest level; higher levels count as this one
LEVEL_MAX: i32 = 9
enum Errorwhy a DEFLATE, zlib or gzip stream could not be read or writtenTruncated-- the input ends before the stream doesHeader-- a zlib or gzip header that is not validBlock-- a block of an unknown type, or a stored block with a wrong lengthCode-- a Huffman code that is not valid, or a symbol no code allowsDistance-- a back reference to before the start of the outputOverflow-- the output does not fit into the bufferChecksum-- a checksum (Adler-32, CRC-32) or a stored size that does not match the data
fn bound(len: usize) -> usizean output capacity with whichcompress_into(and the zlib and gzip ones) never failfn compress(data: &[u8], level: i32) -> Vec<u8>raw DEFLATE data ofdataatlevelfn compress_with(state: Option<&mut DeflateState>, data: &[u8], level: i32) -> Vec<u8>compresswith a reusable state (None = a temporary one)fn compress_into(state: Option<&mut DeflateState>, data: &[u8], level: i32, dst: &mut [u8]) -> Result<usize, Error>compressintodst, the number of bytes written;Error::Overflowwhen the stream and 8 more bytes do not fit (the contents ofdstare undefined then)fn compress_padded(state: Option<&mut DeflateState>, data: &[u8], level: i32, head: usize, tail: usize) -> Vec<u8>compressafterheadzero bytes, with room fortailmore bytes behind the data (both at most 64 KiB): a container writes its header and trailer around the stream without copying it. The vector holds the head and the stream.fn decompress(data: &[u8], max_out: usize) -> Option<Vec<u8>>the data of one DEFLATE stream that fillsdatacompletely, at mostmax_outbytesfn decompress_into(state: Option<&mut InflateState>, data: &[u8], dst: &mut [u8]) -> Result<(usize, usize), Error>the stream at the start ofdataintodst: (bytes written, input bytes of the stream)struct Encodera raw DEFLATE encoder that takes its input in pieces (stream::Encode), about 900 KB of state: pieces of 256 KiB with the 32 KiB before each as their window; the same bytes as compress() for a stream of at most 256 KiB
impl Encoder
fn new(level: i32) -> Encoderan encoder atlevel(as compress: 0..=9, < 0 = 6)fn reset(&mut self)start a new stream at the same level (the memory stays)
compress/deflate/dec.rs#
Source: lib/compress/deflate/dec.rs
deflate::dec -- the DEFLATE (RFC 1951) and zlib (RFC 1950) decoder behind compress::deflate,
compress::zlib and compress::gzip (until 0.2 img_core::inflate) [src/img/inflate.s]
zlib_inflate_ex(st, src, dst) -> Ok((bytes, consumed)) / Err(Error) consumed = header,
deflate data and Adler-32
inflate_raw_st(st, src, dst) -> Ok((bytes, consumed)) / Err(Error) consumed = input
bytes of the deflate data (up to the end of the final
block)
InflateState::new() -> Box reusable decoder state (one thread at a time; an error
never affects later calls); st None = a temporary one
rev16(x) 16-bit bit reversal (shared with deflate)
LBASE / LEXT / DBASE / DEXT / CLORDER the code tables (shared with deflate)
The output buffer has a fixed capacity: every write is bounds-checked (Error::Overflow),
every back reference is checked against the bytes produced so far (Error::Distance), reading
past the end of the input gives Error::Truncated. zlib header errors: Error::Header; a wrong
Adler-32: Error::Checksum.
The bit buffer behaves exactly as the assembly's (the error codes of corrupt input depend
on it): refilled 8 bytes at a time while 8 input bytes remain (the count becomes
56 + count % 8), byte by byte near the end with zero bytes counted as padding (more than
PAD_MAX of them = Error::Truncated); Huffman tables as stb_image (10-bit fast table, canonical
slow path); a code table's sorted-index arrays keep entries of an earlier build (the
slow path checks the length, as the assembly).
Speed (perf-inflate): the symbol loop runs in codes_fast while 8 input bytes remain at
every refill and a whole match fits the output: no slow refill, no overflow checks, no
call on the literal path (the state stays in registers), u32 fast tables (lx / dx) with
the length / distance base and extra-bit count folded in (one load and two shifts per
code), wide match moves. It hands over to the careful loop before the symbol where a
condition fails; both follow the assembly's loop step by step.
struct InflateStatea reusable decoder state (IS_*); onlypadis reset per call, the fixed tables are built once per state, every other table is rebuilt before it is read
impl InflateState
fn new() -> Box<InflateState>a zeroed state [inflate_state_new]
compress/deflate/enc.rs#
Source: lib/compress/deflate/enc.rs
deflate::enc -- the DEFLATE (RFC 1951) / zlib (RFC 1950) encoder behind compress::deflate,
compress::zlib and compress::gzip (until 0.2 img_core::deflate) [src/img/deflate.s]
zlib_deflate(src, level) -> Vec zlib stream (level 0..9, < 0 = 6, > 9 = 9)
deflate_raw(src, level) -> Vec raw RFC 1951 data
deflate_raw_ex(st, src, level, head, tail) -> Vec head free bytes before the data
(gzip writes its header there), tail reserved
after it (not part of the Vec)
DeflateState::new() -> Box a reusable compressor state (~330 KB; one
thread at a time); the same bytes as fresh calls
zlib_deflate_st(st, src, level) / deflate_raw_st(st, src, level) -> Vec
zlib_deflate_to(st, src, level, dst) / deflate_raw_to(...) -> Ok(bytes) /
Err(Error::Overflow): into dst (no allocation with
a state); overflow when the stream + 8 bytes do
not fit (dst contents undefined then)
deflate_bound(len) -> len + len / 512 + 128 a cap with which *_to never overflow
The algorithm and every table of the assembly: 3-byte multiplicative hash, head / prev
chains over "global" positions (input offset + base; every input starts GEN_GAP after
the previous one, so a reused state matches a fresh one), zlib's levels (greedy 1..3, lazy
4..9, chain depth / nice / lazy limits), TOO_FAR, 16K-symbol blocks written as the
cheapest of stored / fixed / dynamic by exact bit count, two-queue Huffman lengths with
miniz's Kraft repair, RLE-coded code lengths. Inputs of 4 GiB - 64 KiB and more are
stored. The output limit: a block that would end past cap - 8 stops the compressor
(Error::Overflow). Speed (perf-inflate): the LZ77 loops keep their state in locals and
load the next position's hash head before the current chain walk (the walk is a chain of
dependent loads; the early load overlaps it) -- the same candidates in the same order.
struct DeflateStatea compressor state (DS_*); reusable, one thread at a time
impl DeflateState
fn new() -> Box<DeflateState>a zeroed state [deflate_state_new]
compress/deflate/sdec.rs#
Source: lib/compress/deflate/sdec.rs
deflate::sdec -- deflate::Decoder, raw DEFLATE data in pieces (zlib::Decoder and
gzip::Decoder wrap it)
The decoder of dec.rs in steps that start again when the input runs out: a block header
(at most 563 bytes: 17 bits, 19 code length codes, 316 lengths of up to 14 bits), one
symbol (a literal, the end of a block, or a length and a distance: at most 48 bits), or a
piece of a stored block. A step that runs out leaves the bit position at its start; the
bytes from there wait in the stage (stream::drive). While a step finds 8 input bytes and
room for a whole match, codes_fast of dec.rs runs the symbols as for a whole input.
The output goes into a window of 128 KiB: the last 32 KiB of output (the reach of a
distance) and room for new bytes. When the caller has taken everything, the window
keeps the last 32 KiB and moves them to its start. A distance is checked against the
bytes in the window, which hold every byte of the output while there are fewer than 32 KiB
and the last 32 KiB afterwards: the same checks as for a whole input.
struct Decodera decoder of raw DEFLATE data (RFC 1951) that takes its input in pieces (stream::Decode): about 150 KB of state, of which 128 KiB are the window
impl Decoder
fn new() -> Decoderfn reset(&mut self)start a new stream (the memory stays)
compress/gzip.rs#
Source: lib/compress/gzip.rs
gzip -- the gzip format (RFC 1952): members of a header, DEFLATE data, CRC-32 and size
(until 0.2 img_core::gzip) [src/img/gzip.s]
compress(data, level) -> Vec<u8> one member: 1F 8B 08, FLG 0, MTIME 0, XFL (2 for level
9, 4 for level 1, else 0), OS 255, deflate, CRC32, ISIZE
decompress(data, max_out) -> Option<Vec<u8>> every member of data, one after the other
as gunzip reads them; None on corruption, a wrong
CRC-32 or size, bytes that are no member, or more than
max_out bytes
compress_with(state, data, level) / compress_into(state, data, level, dst) -> Ok(bytes) /
Err(Error::Overflow) into dst (deflate::bound(len)
always suffices)
decompress_member_into(state, data, dst) -> Ok((bytes, consumed)) ONE member; consumed
= the member's length including the trailer
stored_size(data) -> Option<u32> ISIZE, the last 4 bytes of a single member (the size
mod 2^32, as the member claims it)
Decoder / Encoder in pieces (stream::Decode / Encode); Decoder reads every
member, Decoder::single() the first
Decoding: ID1 ID2, CM 8, FLG (reserved bits 5..7 must be 0), MTIME, XFL, OS, then FEXTRA,
FNAME, FCOMMENT, FHCRC (low 16 bits of the CRC-32 of the header bytes), the deflate data,
CRC32 and ISIZE. Errors: Error::Truncated, Error::Header, Error::Checksum and the inflate
errors.
fn decompress(data: &[u8], max_out: usize) -> Option<Vec<u8>>the data of all members that filldatacompletely, at mostmax_outbytesfn decompress_member_into(st: Option<&mut InflateState>, src: &[u8], dst: &mut [u8]) -> Result<(usize, usize), Error>the first member ofdataintodstwith a reusable state (None = a temporary one): (bytes written, input bytes of the member) [gzip_decode_st]fn compress(src: &[u8], level: i32) -> Vec<u8>one gzip member ofdataatlevel[gzip_encode]fn compress_with(st: Option<&mut DeflateState>, src: &[u8], level: i32) -> Vec<u8>compresswith a reusable state (None = a temporary one) [gzip_encode_st]fn compress_into(st: Option<&mut DeflateState>, src: &[u8], level: i32, dst: &mut [u8]) -> Result<usize, Error>the member ofcompressintodst, the number of bytes written [gzip_encode_to]fn stored_size(src: &[u8]) -> Option<u32>the ISIZE field (uncompressed size mod 2^32) of a single-member stream; None for fewer than 18 bytes [gzip_isize]struct Decodera gzip decoder that takes its input in pieces (stream::Decode): every member, one after the other as gunzip reads them (single(): only the first, and the input after it is not taken); the header with its optional fields, the DEFLATE data through deflate::Decoder, the CRC-32 and the size of each member
impl Decoder
fn new() -> Decodera decoder of all membersfn single() -> Decodera decoder of one member: Status::End after it, input behind it is not takenfn reset(&mut self)start anew (the memory stays)fn members(&self) -> u64the members ended so farstruct Encodera gzip encoder that takes its input in pieces (stream::Encode): one member with the header of compress(), DEFLATE data as deflate::Encoder writes it, the CRC-32 and size; the same bytes as compress() for a stream of at most 256 KiB
impl Encoder
fn new(level: i32) -> Encoderan encoder atlevel(as compress: 0..=9, < 0 = 6)fn reset(&mut self)start a new stream at the same level (the memory stays)
compress/lz4.rs#
Source: lib/compress/lz4.rs
lz4 -- the LZ4 block and frame formats
compress(data) -> block greedy matcher, 16K-entry hash table, skip
acceleration on incompressible data
compress_hc(data, level) -> block the longest match along a hash chain of
2^(level-1) candidates (levels 3..=12, as lz4 -9)
decompress(block, max_out) None on truncation, a bad offset, or more than
max_out bytes; never reads or writes out of bounds
decompress_into(block, &mut out, limit) appends (back references may reach into the
earlier contents of out: linked frame blocks)
frame_compress(data) / frame_decompress(frame, max_out)
FrameDecoder / FrameEncoder LZ4 frames in pieces (stream::Decode / Encode)
Block rules kept by the compressor: the last 5 bytes are literals, no match starts in the
last 12 bytes, offsets 1..=65535.
const fn bound(n: usize) -> usizethe largest block compress() can produce for n input bytesfn compress(src: &[u8]) -> Vec<u8>compress into one LZ4 block
/// the level of compress_hc() for most uses (as `lz4 -9`)
LEVEL_HC_DEFAULT: i32 = 9
fn compress_hc(src: &[u8], level: i32) -> Vec<u8>compress into one LZ4 block, smaller than compress() and slower: at each position the longest match along a hash chain of 2^(level-1) candidates (level 3..=12; LZ4's own high compression levels search as far, its levels 10 to 12 also parse optimally)fn decompress_into(src: &[u8], out: &mut Vec<u8>, limit: usize) -> booldecode one block, appending to out (out.len() stays <= limit) -> false on corrupt inputfn decompress(src: &[u8], max_out: usize) -> Option<Vec<u8>>decode one block of at most max_out bytesfn frame_compress(src: &[u8]) -> Vec<u8>an LZ4 frame: independent 4 MiB blocks, content size and content checksumfn frame_decompress(src: &[u8], max_out: usize) -> Option<Vec<u8>>decode one or more concatenated LZ4 frames (skippable frames are skipped) of at most max_out bytes in total; None on corruption, an unsupported feature (dictionary ids), a checksum mismatch, or too much outputstruct FrameDecoderan LZ4 frame decoder that takes its input in pieces (stream::Decode): frames one after the other, skippable frames skipped (single(): only the first frame). It holds one block (at most 4 MiB, as the frame's descriptor allows) and the last 64 KiB of output, which linked blocks may reach.
impl FrameDecoder
fn new() -> FrameDecodera decoder of all framesfn single() -> FrameDecodera decoder of one frame: Status::End after it, input behind it is not takenfn reset(&mut self)start anew (single() stays)fn frames(&self) -> u64the frames ended so far (skippable ones not counted)struct FrameEncoderan LZ4 frame encoder that takes its input in pieces (stream::Encode): independent blocks of 4 MiB and the content checksum, as frame_compress writes them; the content size only when it is given (with_size), and then the same bytes as frame_compress. Flush::Sync ends a block early. It holds one block of input and its output.
impl FrameEncoder
fn new() -> FrameEncoderfn with_size(mut self, bytes: u64) -> FrameEncoderstate the content size in the frame (the input must have exactly this length, else Error::Size)
compress/stream.rs#
Source: lib/compress/stream.rs
stream -- compression and decompression in pieces, with bounded memory
Decode::decode(input, out) -> Ok(Step) take input, write into the caller's buffer
Decode::finish() Ok when the input so far ended a whole stream
Encode::encode(input, out, flush) -> Ok(Step)
Step { read, written, status } Status::Input (all input taken, give more),
Output (out is full, call again), End
Flush::None / Sync / Finish encoders: buffer, make all input so far
decodable, or end the stream
decode_all(dec, read, write, limit) pump a whole stream from a reader to a writer
encode_all(enc, read, write)
The decoders and encoders are deflate::, zlib::, gzip::, zstd::, lz4:: (FrameDecoder,
FrameEncoder) and brotli::Decoder. Each keeps only what its format needs to go on: the
window a back reference may reach (32 KiB for DEFLATE, the frame's for zstd and Brotli, 64
KiB for LZ4), the bytes of one block where the format sizes its blocks (zstd, LZ4) and at
most a kilobyte of input otherwise. Every call writes at most out.len() bytes, so the
caller decides how much output a piece of input may produce.
The rules for a decoder:
- Status::Input: every byte of input was taken (read == input.len()); call again with
more. If there is no more, the stream is truncated (finish() says so).
- Status::Output: out is full; call again with the input from `read` on.
- Status::End: a whole stream ends at input[read]; every byte of it has been written.
DEFLATE, zlib and Brotli hold one stream, so input after it is not taken. gzip, zstd
and LZ4 files may hold several in a row: more input goes on with the next member or
frame, as their tools read them (Decoder::single() stops after the first).
- An error is final; the decoder must not be used again (reset() starts it anew).
Decoders take untrusted input: damaged data gives an Error, never a panic, a read outside
the input or memory beyond the format's window.
struct Stephow far one call gotread: usize-- bytes of input takenwritten: usize-- bytes written to the output bufferstatus: Status
enum Statuswhy a call returnedInput-- all input was taken: give more, or end (finish / Flush::Finish)Output-- the output buffer is full: call again with room, and the input fromreadonEnd-- the stream is complete: everything of it is written (decoders:readstops at its end)
enum Flushwhat an encoder does with the input it hasNone-- collect input as the format compresses best (output comes in blocks)Sync-- compress everything so far so that a decoder can give all of it back (the stream goes on: DEFLATE ends it with an empty stored block, zstd and LZ4 with a whole block)Finish-- compress the rest and end the stream (call again while it returns Status::Output)
enum Errorwhy a stream could not be read or writtenTruncated-- the input ended inside a streamCorrupt-- the data is damaged, or is no stream of the formatChecksum-- a checksum or a stored size does not match the dataUnsupported-- the stream needs something this crate does not read: an LZ4 dictionary, a zlib preset dictionary, a Brotli large windowLimit-- more memory or output than allowed: a zstd window above the decoder's limit, more output than a pump's limitSize-- the encoder got more or less input than the size it was givenDictionary-- a zstd frame names a dictionary that was not givenIo-- a pump's reader or writer failed
trait Decodea decoder that takes its input in piecesfn decode(&mut self, input: &[u8], out: &mut [u8]) -> Result<Step, Error>decode frominputintoout(see the module's rules for the Step)fn finish(&self) -> Result<(), Error>Ok when the input so far ended a whole stream (and everything is written), else Error::Truncated
trait Encodean encoder that takes its input in piecesfn encode(&mut self, input: &[u8], out: &mut [u8], flush: Flush) -> Result<Step, Error>takeinput(fewer bytes when out fills up), write compressed bytes intoout. Status::Input: all input taken and, for Sync and Finish, all output of it written; Output: call again (with the same flush); End: Finish is done.
fn decode_all<D: Decode + ?Sized>( dec: &mut D, mut read: impl FnMut(&mut [u8]) -> Option<usize>, mut write: impl FnMut(&[u8]) -> bool, limit: u64, ) -> Result<u64, Error>decode a whole stream:read(buf)gives input (Some(0) at its end, None on an error),write(bytes)takes output (false on an error); at mostlimitbytes are written. The input must be complete streams and nothing else -> the number of bytes written.fn encode_all<E: Encode + ?Sized>( enc: &mut E, mut read: impl FnMut(&mut [u8]) -> Option<usize>, mut write: impl FnMut(&[u8]) -> bool, ) -> Result<u64, Error>compress everythingread(buf)gives (Some(0) at the end, None on an error) intowrite(bytes)(false on an error) and end the stream -> the number of bytes written
compress/xxh.rs#
Source: lib/compress/xxh.rs
xxh -- xxHash32 (the checksum of LZ4 frames) and xxHash64 (zstd frames); not cryptographic.
Xxh32 / Xxh64 give the same values for data that comes in pieces (the streams use them).
fn xxh32(data: &[u8], seed: u32) -> u32xxHash32 of a byte stringfn xxh64(data: &[u8], seed: u64) -> u64xxHash64 of a byte string (zstd's content checksum is its low 32 bits)struct Xxh32xxHash32 over data that comes in pieces:updateas often as needed, thendigest(the same value asxxh32of all pieces in a row)
impl Xxh32
fn new(seed: u32) -> Xxh32fn update(&mut self, mut data: &[u8])fn digest(&self) -> u32the hash of everything so far (the state stays usable)struct Xxh64xxHash64 over data that comes in pieces (the same value asxxh64of all pieces in a row)
impl Xxh64
fn new(seed: u64) -> Xxh64fn update(&mut self, mut data: &[u8])fn digest(&self) -> u64the hash of everything so far (the state stays usable)
compress/zlib.rs#
Source: lib/compress/zlib.rs
zlib -- the zlib format (RFC 1950): a two-byte header, DEFLATE data and an Adler-32
compress(data, level) -> Vec<u8> levels as deflate::compress; the header names the
level as zlib does (78 01 / 5E / 9C / DA)
decompress(data, max_out) -> Option<Vec<u8>> the whole input must be one zlib stream;
None on corruption, a wrong Adler-32, data after
the stream or more than max_out bytes
compress_with(state, data, level) / compress_into(state, data, level, dst)
decompress_into(state, data, dst) -> Ok((bytes, consumed)) consumed = header, DEFLATE
data and Adler-32; data after it is not looked at
Decoder / Encoder in pieces (stream::Decode / Encode)
A preset dictionary (FDICT) is refused as Error::Header.
fn compress(data: &[u8], level: i32) -> Vec<u8>a zlib stream ofdataatlevelfn compress_with(state: Option<&mut DeflateState>, data: &[u8], level: i32) -> Vec<u8>compresswith a reusable state (None = a temporary one)fn compress_into(state: Option<&mut DeflateState>, data: &[u8], level: i32, dst: &mut [u8]) -> Result<usize, Error>compressintodst, the number of bytes written;Error::Overflowwhen it does not fit with 8 bytes to spare (deflate::boundalways suffices)fn decompress(data: &[u8], max_out: usize) -> Option<Vec<u8>>the data of the zlib stream that fillsdatacompletely, at mostmax_outbytesfn decompress_into(state: Option<&mut InflateState>, data: &[u8], dst: &mut [u8]) -> Result<(usize, usize), Error>the zlib stream at the start ofdataintodst: (bytes written, input bytes of the stream including its Adler-32)struct Decodera zlib decoder that takes its input in pieces (stream::Decode): the header, the DEFLATE data through deflate::Decoder, the Adler-32 of the output
impl Decoder
fn new() -> Decoderfn reset(&mut self)start a new stream (the memory stays)struct Encodera zlib encoder that takes its input in pieces (stream::Encode): the header, DEFLATE data as deflate::Encoder writes it, the Adler-32; the same bytes as compress() for a stream of at most 256 KiB
impl Encoder
fn new(level: i32) -> Encoderan encoder atlevel(as compress: 0..=9, < 0 = 6)fn reset(&mut self)start a new stream at the same level (the memory stays)
compress/zstd/mod.rs#
Source: lib/compress/zstd/mod.rs
zstd -- the Zstandard format (RFC 8878), interoperable with the zstd tool both ways
compress(data, level) -> frame levels 1..=19 (LEVEL_DEFAULT 3); content size and
checksum in the frame; window up to 8 MiB
decompress(frames, max_out) any conforming frames, concatenated and skippable
ones too; None on corruption, a checksum mismatch,
> max_out bytes or a frame that names a dictionary
Dictionary::train(samples, max) / parse / raw / to_bytes dictionaries as `zstd --train`
makes them (dict.rs, train.rs)
compress_with_dict / decompress_with_dict frames with a dictionary (zstd -D)
content_size(frame), dictionary_id(frame) what a frame header declares
bound(n) the largest frame compress() makes from n bytes
Decoder / Encoder in pieces (stream::Decode / Encode; sdec.rs, senc.rs):
windows up to 128 MiB (with_window_max), with_size
for the bytes of compress(), with_dictionary
LEVEL_DEFAULT: i32 = 3
LEVEL_MAX: i32 = 19
compress/zstd/dec.rs#
Source: lib/compress/zstd/dec.rs
dec -- the zstd frame decoder (RFC 8878): frames and skippable frames, raw / RLE /
compressed blocks, raw / RLE / Huffman / treeless literals with 1 or 4 streams, sequences
with predefined / RLE / FSE / repeat tables, repeat offsets, content size and checksum.
A frame that names a dictionary needs it (decompress_with_dict; dict.rs): its tables and
repeat offsets start the frame, its content stands before the output. Every length,
offset and table is checked: corrupt input gives None, never a panic or more than max_out
bytes.
fn decompress(src: &[u8], max_out: usize) -> Option<Vec<u8>>decode all frames of src -> None on corruption, unsupported features or > max_out bytesfn decompress_with_dict(src: &[u8], max_out: usize, dict: &Dictionary) -> Option<Vec<u8>>decompress with a dictionary: frames that name it or none (None also for a frame that names another one)fn dictionary_id(src: &[u8]) -> Option<u32>the dictionary ID a frame header names (None: none, or not a zstd frame)fn content_size(src: &[u8]) -> Option<u64>the content size a frame header declares (None: not stated or not a zstd frame)
compress/zstd/dict.rs#
Source: lib/compress/zstd/dict.rs
dict -- Zstandard dictionaries (RFC 8878 section 5)
Dictionary::parse(bytes) the format of `zstd --train` (magic EC30A437, the ID, the
literals' Huffman table, the FSE tables of the offset, match
length and literal length codes, three repeat offsets, the
content), or bytes without the magic as raw content (ID 0)
Dictionary::raw(content) content only: matches may reach into it, no tables
Dictionary::train(samples, max_size) train.rs
to_bytes / id / content
A frame that names a dictionary starts with its tables and repeat offsets, and its content
stands before the frame's output, where matches may reach. Every table is checked as a
frame's would be: a damaged dictionary is refused, never a panic.
struct Dictionarya Zstandard dictionary: content that matches may reach into, and for the trained format the entropy tables and repeat offsets a frame starts with
impl Dictionary
fn raw(content: &[u8]) -> Dictionarya dictionary of content only (ID 0): frames made with it name no dictionary, so the decoder must be given itfn parse(b: &[u8]) -> Option<Dictionary>a dictionary in the zstd format, or raw content when the bytes do not start with its magic (as libzstd reads them); None for a damaged zstd-format dictionaryfn train(samples: &[&[u8]], max_size: usize) -> Option<Dictionary>a dictionary of at most max_size bytes (at least 256; zstd's default is 112 640) trained on samples of the data it will compress, aszstd --trainmakes them (train.rs); None without enough samplesfn to_bytes(&self) -> Vec<u8>the dictionary as a file ofzstd --train(raw content: the content)fn id(&self) -> u32the ID frames name it by (0: raw content, named by none)fn content(&self) -> &[u8]the content matches may reach intofn has_tables(&self) -> boolwhether it has the trained format's entropy tables
compress/zstd/enc.rs#
Source: lib/compress/zstd/enc.rs
enc -- the zstd encoder: one frame with content size and checksum, blocks of 128 KiB.
Matches come from a hash-chain finder over a window of up to 8 MiB (levels 1..=19 set the
search depth and how many positions ahead a lazy match may be preferred); the three repeat
offsets are tried first. Literals are Huffman coded when that is smaller; each of the three
sequence codes takes the cheapest of RLE, the predefined distribution and its own table.
A block that does not get smaller is stored raw; a run of one byte value becomes an RLE
block. The decoder's repeat offsets do not move on raw blocks, so the encoder rolls them back.
The tables the decoder already has (the previous block's, or a dictionary's at the start)
are used again when that is cheapest: the literals without a new tree, a sequence code in
Repeat_Mode. With a dictionary its content stands before the input, so the first matches
can reach into it.
const fn bound(n: usize) -> usizethe largest frame compress() makes from n bytesfn compress(src: &[u8], level: i32) -> Vec<u8>one zstd framefn compress_with_dict(src: &[u8], level: i32, dict: &Dictionary) -> Vec<u8>one zstd frame with a dictionary: its content is where the first matches can come from, its tables and repeat offsets start the frame, the frame names its ID (none for raw content, Dictionary::raw)
compress/zstd/sdec.rs#
Source: lib/compress/zstd/sdec.rs
zstd::sdec -- zstd::Decoder, Zstandard frames in pieces
A frame is a header, blocks of at most 128 KiB whose sizes stand in their 3-byte headers,
and a checksum: each part is collected whole (at most one block's bytes wait) and decoded
with dec.rs. The output goes into a window that holds what the frame's matches may reach:
its Window_Size (the content size when it is smaller), refused above the decoder's limit
(128 MiB by default, as the zstd tool's). A match farther back than the window is an
error, as in the zstd tool's streaming decoder (dec.rs's one-shot decompress allows any
distance inside the frame). The next block is decoded once the caller has taken the
output of the last one; the window moves when it holds more than twice its size. With a
dictionary (with_dictionary), its content stands before the frame's output (not copied)
(not given to the caller) and widens the reach by its length.
struct Decodera Zstandard decoder that takes its input in pieces (stream::Decode): frames one after the other aszstd -dreads them, skippable frames skipped (single(): only the first frame). Its memory is about twice a frame's window and one block.
impl Decoder
fn new() -> Decodera decoder of all frames, windows up to 128 MiBfn single() -> Decodera decoder of one frame: Status::End after it, input behind it is not takenfn with_window_max(mut self, bytes: usize) -> Decoderrefuse frames whose window is larger thanbytes(Error::Limit)fn with_dictionary(mut self, dict: Dictionary) -> Decodera dictionary for the frames that name its ID (several may be given); a frame that names none takes the only one given (raw content: Dictionary::raw). A frame that names one not given is Error::Dictionary.fn reset(&mut self)start anew (the limit and single() stay)fn frames(&self) -> u64the frames ended so far (skippable ones not counted)
compress/zstd/senc.rs#
Source: lib/compress/zstd/senc.rs
zstd::senc -- zstd::Encoder, one Zstandard frame in pieces
The input collects in a buffer that keeps the frame's window (8 MiB, or the content when
a smaller size is given) before the bytes not yet compressed; a block of 128 KiB is
compressed once 8 more bytes are there (the match finder looks that far ahead), with the
same finder, tables and block choices as compress(). So a frame whose size is given
(with_size) is the same bytes as compress() of the whole input; without a size the
frame header states none, the window is 8 MiB and the tables have their full size.
Flush::Sync ends a block early. The buffer moves by 4 MiB once it holds more than the
window and 4 MiB; the tables move with it.
struct Encodera Zstandard encoder that takes its input in pieces (stream::Encode): one frame with a checksum, the content size when it is given; memory up to about 12 MiB plus the tables of the level
impl Encoder
fn new(level: i32) -> Encoderan encoder atlevel(1..=19 as compress)fn with_size(mut self, bytes: u64) -> Encoderstate the content size in the frame (the input must have exactly this length, else Error::Size); the frame is then the same bytes as compress()fn with_dictionary(mut self, dict: &Dictionary) -> Encodercompress with a dictionary (as compress_with_dict; with a size, the same bytes)