Skip to main content

structured_zstd/encoding/
mod.rs

1//! Zstandard encoder — frame compression, streaming, dictionary support.
2//!
3//! Five entry points cover the common use cases:
4//!
5//! * [`compress`] — one-shot helper that builds a self-contained
6//!   Zstandard frame from a `Read` source to a `Write` sink. The
7//!   input is consumed incrementally from `Read`, so input buffering
8//!   stays bounded; however, the compressed output is buffered in
9//!   memory until the frame is complete so the Frame Content Size
10//!   field can be filled in the header — peak memory is
11//!   `O(compressed_size)` (worst-case `O(input_size)` for
12//!   incompressible payloads, plus a small frame overhead). The
13//!   savings vs [`compress_to_vec`] come from not materialising the
14//!   input alongside the output.
15//! * [`compress_to_vec`] — same one-shot path as [`compress`] but
16//!   the input is eagerly drained into an internal `Vec` first
17//!   (`read_to_end`) so the encoder can be handed a `&[u8]` and a
18//!   precise source-size hint. Peak memory is therefore ≈
19//!   `input_size + output_size`; prefer [`compress`] or
20//!   [`StreamingEncoder`] when the input is large or unbounded.
21//! * [`StreamingEncoder`] — implements [`crate::io::Write`], which
22//!   re-exports [`std::io::Write`] under the `std` feature and falls
23//!   back to a `no_std`-friendly trait otherwise. Accepts bytes
24//!   incrementally and flushes compressed output as blocks fill.
25//!   Requires `set_pledged_content_size` before the first write if
26//!   the Frame Content Size field is to be populated.
27//! * [`CompressionContext`] — the reusable state behind
28//!   [`StreamingEncoder`], with the output passed to each call: compresses
29//!   frame after frame with one set of settings, one attached dictionary and
30//!   one set of match-finder allocations, as upstream's `ZSTD_CCtx` does.
31//! * [`FrameCompressor`] — lower-level builder that owns the matcher and
32//!   the per-frame configuration; the streaming and one-shot helpers are
33//!   thin wrappers over it. Reach for it when you need to swap in a custom
34//!   [`Matcher`] implementation or share the matcher across frames.
35//!
36//! Compression intensity is selected via [`CompressionLevel`], which
37//! provides both named presets (`Fastest`, `Default`, `Better`, `Best`) and
38//! numeric levels (`from_level(n)`) that mirror C zstd's level numbering
39//! (negative for ultra-fast, `0` = default, `1..=22` for the standard
40//! range).
41//!
42//! All produced frames are valid RFC 8878 Zstandard streams and decode
43//! through both this crate's [`crate::decoding`] module and upstream C zstd.
44//!
45//! For memory budgeting, [`estimated_compression_workspace_bytes`] reports
46//! the approximate steady-state heap footprint of a one-shot compression at
47//! a given level (window + match-finder tables + block staging).
48
49pub(crate) mod block_header;
50pub(crate) mod blocks;
51pub(crate) mod cparams;
52pub(crate) mod dict_attach;
53pub(crate) mod fastpath;
54pub(crate) mod frame_header;
55pub(crate) mod incompressible;
56pub(crate) mod match_generator;
57pub(crate) mod util;
58
59// `#111` encoder architecture rewrite. `cost_model`, `opt`,
60// `strategy`, `dfast`, `row`, and `simple` host the relocated
61// cost-model types, the optimal-parser plain-data types, the
62// const-generic [`strategy::Strategy`] trait + per-level [`strategy::
63// StrategyTag`] dispatcher, and the Dfast / Row / Simple matchers
64// respectively. `match_table::helpers` hosts the shared match-finder
65// primitives. The rewrite plan is tracked in
66// <https://github.com/structured-world/structured-zstd/issues/111>;
67// per-phase boundaries are `perf/post-pr-110-baseline` (start),
68// `perf/post-pr-121-baseline` (post-Phase-2).
69pub(crate) mod bt;
70pub(crate) mod cost_model;
71pub(crate) mod dfast;
72pub(crate) mod hc;
73pub(crate) mod lazy_parse;
74// LDM hashes each `min_match_length` window with XXH64 (upstream zstd
75// `zstd_ldm.c:315`), so the `ldm` feature implies `hash` and the
76// `twox-hash` dependency it pulls in. `BtMatcher::ldm_producer` and the
77// `cfg(feature = "ldm")` blocks inside `BtMatcher::prepare_ldm_candidates` /
78// `BtMatcher::reset` carry the same gate; the call site in
79// `hc::optimal::HcMatchGenerator::start_matching_optimal` invokes
80// `prepare_ldm_candidates` unconditionally because the gating is internal to
81// the method body (without the feature it shrinks to an
82// `ldm_sequences.clear()` stub).
83#[cfg(feature = "ldm")]
84pub(crate) mod ldm;
85pub(crate) mod match_table;
86pub(crate) mod opt;
87pub(crate) mod row;
88pub(crate) mod simple;
89pub(crate) mod strategy;
90#[cfg(test)]
91pub(crate) mod test_input;
92pub(crate) mod workspace;
93
94pub(crate) mod frame_compressor;
95#[cfg(feature = "lsm")]
96pub mod frame_emit_info;
97mod levels;
98pub(crate) mod parameters;
99#[cfg(feature = "bench-internals")]
100pub mod sequence_capture;
101mod streaming_encoder;
102pub use frame_compressor::{EncoderDictionary, FrameCompressor};
103#[cfg(feature = "lsm")]
104pub use frame_emit_info::{BlockType, FrameBlock, FrameEmitInfo};
105pub use levels::config::{
106    estimated_bt_strategy_extra_bytes, estimated_compression_workspace_bytes,
107    estimated_compression_workspace_bytes_for_parameters,
108    estimated_compression_workspace_bytes_for_run,
109    estimated_compression_workspace_bytes_for_source,
110};
111pub use match_generator::MatchGeneratorDriver;
112pub use parameters::{
113    Bounds, CParameter, CompressionParameters, CompressionParametersBuilder, LevelParameters,
114    LiteralCompressionMode, ParameterError, Strategy,
115};
116pub use streaming_encoder::{CompressionContext, StreamingEncoder};
117pub use workspace::HistoryBuf;
118
119/// Name of the kernel tier the match finders run for this process (`scalar`,
120/// `sse2`, `sse4.2`, `avx2`, `neon`, `simd128`), chosen by run-time CPU
121/// detection under any [`set_cpu_ceiling`](crate::set_cpu_ceiling).
122///
123/// # Examples
124/// ```
125/// let name = structured_zstd::encoding::active_match_kernel_name();
126/// assert!(!name.is_empty());
127/// ```
128pub fn active_match_kernel_name() -> &'static str {
129    fastpath::select_kernel().name()
130}
131
132use crate::io::{Read, Write};
133use alloc::vec::Vec;
134
135/// Convenience function to compress some source into a target without reusing any resources of the compressor
136/// ```rust
137/// use structured_zstd::encoding::{compress, CompressionLevel};
138/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
139/// let mut target = Vec::new();
140/// compress(data, &mut target, CompressionLevel::Fastest);
141/// ```
142pub fn compress<R: Read, W: Write>(source: R, target: W, level: CompressionLevel) {
143    let mut frame_enc = FrameCompressor::new(level);
144    frame_enc.set_source(source);
145    frame_enc.set_drain(target);
146    frame_enc.compress();
147}
148
149/// Convenience function to compress some source into a Vec without reusing any resources of the compressor.
150///
151/// This helper eagerly buffers the full input (`Read`) before compression so it
152/// can provide a source-size hint to the one-shot encoder path. Peak memory can
153/// therefore be roughly `input_size + output_size`. For very large payloads or
154/// tighter memory budgets, prefer streaming APIs such as [`StreamingEncoder`].
155///
156/// **This is NOT a streaming API.** The source is fully buffered
157/// into a `Vec<u8>` before any compression work begins, so peak input
158/// memory is bounded by `source.len()` (not "constant regardless of
159/// payload size" as a stream-shaped encoder would offer). If the
160/// source is large enough that holding it in memory is not acceptable,
161/// use [`StreamingEncoder`] which consumes chunks incrementally
162/// without the up-front Vec build.
163///
164/// This helper drives `read_to_end` to materialize the full source
165/// into a `Vec<u8>` before forwarding the slice to
166/// [`compress_slice_to_vec`]. For a `Read` whose size is unknown ahead
167/// of time, `read_to_end` grows that input `Vec` via power-of-two
168/// doubling: peak input allocation can be up to 2× the final source
169/// length transiently. The live working set on this entry point is
170/// roughly `input.capacity()` plus the block-accumulation buffer and
171/// per-block scratch carried by [`compress_slice_to_vec`], plus the
172/// exactly-sized output `Vec`. [`StreamingEncoder`] avoids the input
173/// materialization step entirely and is the right entry point when
174/// the source is large or unbounded.
175///
176/// ```rust
177/// use structured_zstd::encoding::{compress_to_vec, CompressionLevel};
178/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
179/// let compressed = compress_to_vec(data, CompressionLevel::Fastest);
180/// ```
181pub fn compress_to_vec<R: Read>(source: R, level: CompressionLevel) -> Vec<u8> {
182    let mut source = source;
183    let mut input = Vec::new();
184    source.read_to_end(&mut input).unwrap();
185    compress_slice_to_vec(input.as_slice(), level)
186}
187
188/// Compress a contiguous byte slice into a fresh `Vec<u8>` without the
189/// input-buffering step that [`compress_to_vec`] performs to adapt a
190/// `Read` source.
191///
192/// One-shot wrapper over
193/// [`FrameCompressor::compress_independent_frame`]: the input is read by
194/// reference (the eligible Fast path scans it in place, no per-block
195/// history copy), and the returned `Vec` is allocated exactly once at the
196/// final frame size after compression. Peak transient memory is the
197/// block-accumulation buffer (grown via amortized doubling, ≈ 2× current
198/// compressed size at the last realloc) plus the exactly-sized output. The
199/// worst-case compressed-size bound is never pinned upfront, so a highly
200/// compressible 100 MiB input does not charge ~100 MiB of worst-case
201/// expansion against peak.
202///
203/// To compress many slices, construct one [`FrameCompressor`] and call
204/// [`compress_independent_frame_into`](FrameCompressor::compress_independent_frame_into)
205/// in a loop instead, which reuses the matcher tables, scratch, and output
206/// buffer across frames (this function allocates and primes from scratch
207/// each call).
208///
209/// # Panics
210///
211/// Panics on encoder error (matches the failure surface of
212/// [`compress_to_vec`], which this function backs). Out-of-memory during
213/// the output / per-block scratch allocations is handled by the global
214/// allocator's abort policy. The slice/Vec entry points mirror the upstream zstd
215/// `ZSTD_compress` shape (no error return on the bulk path).
216///
217/// ```rust
218/// use structured_zstd::encoding::{compress_slice_to_vec, CompressionLevel};
219/// let data: &[u8] = &[0,0,0,0,0,0,0,0,0,0,0,0];
220/// let compressed = compress_slice_to_vec(data, CompressionLevel::Fastest);
221/// ```
222pub fn compress_slice_to_vec(source: &[u8], level: CompressionLevel) -> Vec<u8> {
223    // Bare `FrameCompressor` resolves all three type params to their
224    // defaults (`&'static [u8]` reader, `Vec<u8>` drain, MatchGeneratorDriver);
225    // neither the reader nor the drain is used by the in-place
226    // `compress_independent_frame` path.
227    let mut enc: FrameCompressor = FrameCompressor::new(level);
228    enc.compress_independent_frame(source)
229}
230
231/// Worst-case compressed-frame size for an input of `src_size` bytes.
232///
233/// A destination buffer of this size is always large enough to hold the
234/// output of [`compress_slice_to_vec`] (or any single-frame compression) for
235/// an input of `src_size` bytes, so a caller sizing a fixed buffer once (the
236/// shape the C `ZSTD_compress` entry point needs) never has to grow it.
237///
238/// Mirrors the upstream `ZSTD_COMPRESSBOUND` formula exactly:
239/// `src_size + (src_size >> 8) + margin`, where `margin` is
240/// `(128 KiB - src_size) >> 11` for inputs below 128 KiB and `0` otherwise.
241/// The margin guarantees `bound(a) + bound(b) <= bound(a + b)` for blocks of
242/// at least 128 KiB, which keeps multi-frame concatenation sizing sound.
243///
244/// Saturates at [`usize::MAX`] if the formula would overflow on a
245/// pathologically large `src_size` — no allocation that large can exist, so
246/// the saturated value is the correct "cannot fit" sentinel rather than a
247/// masked wrap.
248///
249/// ```rust
250/// use structured_zstd::encoding::{compress_bound, compress_slice_to_vec, CompressionLevel};
251/// let data = [7u8; 4096];
252/// assert!(compress_slice_to_vec(&data, CompressionLevel::Default).len() <= compress_bound(data.len()));
253/// ```
254pub const fn compress_bound(src_size: usize) -> usize {
255    const LOWER: usize = 128 * 1024;
256    let margin = if src_size < LOWER {
257        (LOWER - src_size) >> 11
258    } else {
259        0
260    };
261    // Saturating is the correct UPPER-BOUND semantic here, not a masked bug:
262    // this is a public API over an arbitrary `usize`, and the largest meaningful
263    // bound is `usize::MAX`. A real slice is at most `isize::MAX` bytes, so the
264    // `* 1.004 + margin` cannot overflow for genuine inputs; the saturation only
265    // caps a pathological caller-supplied size at the representable ceiling.
266    src_size
267        .saturating_add(src_size >> 8)
268        .saturating_add(margin)
269}
270
271/// Compress a byte slice into a fresh `Vec<u8>` using fine-grained
272/// [`CompressionParameters`] (#27) instead of a bare
273/// [`CompressionLevel`].
274///
275/// One-shot wrapper over [`FrameCompressor::set_parameters`] +
276/// [`FrameCompressor::compress_independent_frame`]. The produced frame is
277/// a valid RFC 8878 stream regardless of the knobs chosen.
278///
279/// ```rust
280/// use structured_zstd::encoding::{
281///     compress_with_parameters, CompressionLevel, CompressionParameters, Strategy,
282/// };
283/// let data: &[u8] = b"the quick brown fox jumps over the lazy dog";
284/// let params = CompressionParameters::builder(CompressionLevel::Level(5))
285///     .strategy(Strategy::Greedy)
286///     .build()
287///     .unwrap();
288/// let compressed = compress_with_parameters(data, &params);
289/// assert!(!compressed.is_empty());
290/// ```
291pub fn compress_with_parameters(source: &[u8], params: &CompressionParameters) -> Vec<u8> {
292    let mut enc: FrameCompressor = FrameCompressor::new(params.level());
293    enc.set_parameters(params);
294    enc.compress_independent_frame(source)
295}
296
297/// The compression mode used impacts the speed of compression,
298/// and resulting compression ratios. Faster compression will result
299/// in worse compression ratios, and vice versa.
300#[derive(Copy, Clone, Debug, PartialEq, Eq)]
301pub enum CompressionLevel {
302    /// This level does not compress the data at all, and simply wraps
303    /// it in a Zstandard frame.
304    Uncompressed,
305    /// This level is roughly equivalent to Zstd compression level 1
306    Fastest,
307    /// This level uses the crate's dedicated `dfast`-style matcher to
308    /// target a better speed/ratio tradeoff than [`CompressionLevel::Fastest`].
309    ///
310    /// It represents this crate's "default" compression setting and may
311    /// evolve in future versions as the implementation moves closer to
312    /// reference zstd level 3 behavior.
313    Default,
314    /// This level is roughly equivalent to Zstd level 7.
315    ///
316    /// Uses the hash-chain matcher with a lazy2 matching strategy: the encoder
317    /// evaluates up to two positions ahead before committing to a match,
318    /// trading speed for a better compression ratio than [`CompressionLevel::Default`].
319    Better,
320    /// This level is equivalent to Zstd level 13.
321    ///
322    /// Uses the lazy2 parse over the binary-tree match finder (`btlazy2`),
323    /// the first level of the deep band that strictly dominates every level
324    /// below it on ratio; compared to [`CompressionLevel::Better`] it
325    /// trades speed for the best ratio of the named presets.
326    Best,
327    /// Numeric compression level.
328    ///
329    /// Levels 1–22 correspond to the C zstd level numbering.  Higher values
330    /// produce smaller output at the cost of more CPU time.  Negative values
331    /// select ultra-fast modes that trade ratio for speed.  Level 0 is
332    /// treated as [`DEFAULT_LEVEL`](Self::DEFAULT_LEVEL), matching C zstd
333    /// semantics.
334    ///
335    /// Named variants map to specific numeric levels:
336    /// [`Fastest`](Self::Fastest) = 1, [`Default`](Self::Default) = 3,
337    /// [`Better`](Self::Better) = 7, [`Best`](Self::Best) = 13.
338    /// [`Best`](Self::Best) remains the highest-ratio named preset, but
339    /// [`Level`](Self::Level) values above 13 can target stronger (slower)
340    /// tuning than the named hierarchy.
341    ///
342    /// Levels above 13 use progressively larger windows and deeper search.
343    /// Levels 16–17 use a `btopt`-style price parser, 18 uses `btultra`,
344    /// and 19–22 use a `btultra2`-style two-pass selection profile.
345    ///
346    /// Semver note: this variant was added after the initial enum shape and
347    /// is a breaking API change for downstream crates that exhaustively
348    /// `match` on [`CompressionLevel`] without a wildcard arm.
349    Level(i32),
350}
351
352impl CompressionLevel {
353    /// The minimum supported numeric compression level (ultra-fast mode).
354    pub const MIN_LEVEL: i32 = -131072;
355    /// The maximum supported numeric compression level.
356    pub const MAX_LEVEL: i32 = 22;
357    /// The default numeric compression level (equivalent to [`Default`](Self::Default)).
358    pub const DEFAULT_LEVEL: i32 = 3;
359
360    /// Create a compression level from a numeric value.
361    ///
362    /// Returns named variants for canonical levels (`0`/`3`, `1`, `7`, `13`)
363    /// and [`Level`](Self::Level) for all other values.
364    ///
365    /// With the default matcher backend (`MatchGeneratorDriver`), values
366    /// outside [`MIN_LEVEL`](Self::MIN_LEVEL)..=[`MAX_LEVEL`](Self::MAX_LEVEL)
367    /// are silently clamped during built-in level parameter resolution.
368    pub const fn from_level(level: i32) -> Self {
369        match level {
370            0 | Self::DEFAULT_LEVEL => Self::Default,
371            1 => Self::Fastest,
372            7 => Self::Better,
373            13 => Self::Best,
374            _ => Self::Level(level),
375        }
376    }
377}
378
379/// The sizes of a dictionary handed to [`Matcher::set_dictionary_size_hint`].
380///
381/// Upstream picks the CDict's cParams tier from the size of the serialized
382/// dictionary buffer (`ZSTD_createCDict(dictBuffer, dictSize, level)`, header
383/// and entropy tables included), while the dictionary tables and the attach
384/// cutoffs are sized from the content that is actually indexed.
385///
386/// # Examples
387/// ```
388/// use structured_zstd::encoding::DictionarySizes;
389/// let sizes = DictionarySizes::raw_content(4096);
390/// assert_eq!(sizes.serialized, sizes.content);
391/// ```
392#[derive(Clone, Copy, Debug, PartialEq, Eq)]
393pub struct DictionarySizes {
394    /// Bytes of dictionary content the matcher indexes.
395    pub content: usize,
396    /// Bytes of the serialized dictionary (the CDict cParams tier key); equal
397    /// to `content` for a raw-content dictionary.
398    pub serialized: usize,
399}
400
401impl DictionarySizes {
402    /// Sizes of a raw-content dictionary: nothing but the content is
403    /// serialized.
404    pub const fn raw_content(len: usize) -> Self {
405        Self {
406            content: len,
407            serialized: len,
408        }
409    }
410}
411
412/// Bytes below which a frame is still about its dictionary rather than about
413/// its own content (upstream `ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF`).
414const DICTIONARY_DESCRIBES_FRAME_BELOW: u64 = 128 * 1024;
415/// Multiple of the dictionary's content below which the same holds however
416/// large both are (upstream `ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER`).
417const DICTIONARY_DESCRIBES_FRAME_MULTIPLE: u64 = 6;
418
419/// Whether a dictionary of `dict_content` bytes still describes a frame over
420/// `src_size` bytes (`None` = not yet known), so that the shape it was prepared
421/// with is the frame's too.
422///
423/// A source under 128 KiB, or under six times the dictionary, is about the
424/// dictionary: the tables it was prepared with are the right ones and can be
425/// searched in place. Past that the frame is about its own content, and a shape
426/// chosen for a dictionary undersizes it. A frame of unknown size keeps the
427/// dictionary's shape, having nothing better to go on. Upstream weighs the same
428/// three things at `ZSTD_compressBegin_internal` (zstd_compress.c:5254).
429///
430/// A size of `u64::MAX` is the encoder's "unknown" sentinel, not a source of
431/// that many bytes, and counts as unknown here too.
432///
433/// This is the codec's rule, exported so that every surface in front of it
434/// (the C ABI included) asks rather than re-deciding.
435///
436/// # Examples
437/// ```
438/// use structured_zstd::encoding::dictionary_describes_frame;
439///
440/// // A few kilobytes against a 4 KiB dictionary: about the dictionary.
441/// assert!(dictionary_describes_frame(4096, Some(8192)));
442/// // A megabyte against the same: about itself.
443/// assert!(!dictionary_describes_frame(4096, Some(1 << 20)));
444/// // Unknown, so there is nothing better than the dictionary's own shape.
445/// assert!(dictionary_describes_frame(4096, None));
446/// assert!(dictionary_describes_frame(4096, Some(u64::MAX)));
447/// ```
448pub fn dictionary_describes_frame(dict_content: usize, src_size: Option<u64>) -> bool {
449    if dict_content == 0 {
450        return false;
451    }
452    let Some(src) = src_size.filter(|size| *size != crate::encoding::cparams::CONTENTSIZE_UNKNOWN)
453    else {
454        return true;
455    };
456    // Asked as a division rather than `src < dict * 6`: this is public, so the
457    // dictionary is whatever the caller names, and six times a large one does
458    // not fit the type. For integers the two are the same question, and a
459    // division of a `u64` by a constant cannot overflow.
460    src < DICTIONARY_DESCRIBES_FRAME_BELOW
461        || src / DICTIONARY_DESCRIBES_FRAME_MULTIPLE < dict_content as u64
462}
463
464/// Trait used by the encoder that users can use to extend the matching facilities with their own algorithm
465/// making their own tradeoffs between runtime, memory usage and compression ratio
466///
467/// The matcher owns the input: the encoder reads the data to be compressed
468/// straight into the matcher's [`HistoryBuf`] through
469/// [`fill_in_place`](Self::fill_in_place), where it waits, uncommitted, until
470/// the encoder has chosen where the next block ends. The encoder then claims
471/// the block with [`commit_filled`](Self::commit_filled) and either calls
472/// `start_matching` or, if the block is deemed not worth compressing,
473/// `skip_matching`. Bytes left uncommitted head the next block.
474///
475/// This is repeated until no more data is left to be compressed.
476pub trait Matcher {
477    /// The block most recently claimed by [`commit_filled`](Self::commit_filled).
478    fn get_last_space(&mut self) -> &[u8];
479    /// Read input straight into the matcher's history buffer.
480    ///
481    /// `fill` is handed the buffer, with room for `capacity` more bytes, to
482    /// append to, and returns `(appended, eof)`, which this returns. The bytes
483    /// are then readable through [`uncommitted_input`](Self::uncommitted_input)
484    /// but are NOT yet part of the match window: the encoder chooses the block
485    /// boundary (the pre-split pass needs the bytes to decide) and then calls
486    /// [`commit_filled`](Self::commit_filled). Whatever is left over stays in
487    /// the buffer and becomes the head of the next block, so a carried split
488    /// remainder costs no copy.
489    fn fill_in_place(
490        &mut self,
491        capacity: usize,
492        fill: &mut dyn FnMut(&mut HistoryBuf) -> (usize, bool),
493    ) -> (usize, bool);
494    /// Bytes read by [`fill_in_place`](Self::fill_in_place) that no block has
495    /// claimed yet.
496    fn uncommitted_input(&self) -> &[u8];
497    /// Claim `len` bytes from the head of
498    /// [`uncommitted_input`](Self::uncommitted_input) as the next block.
499    fn commit_filled(&mut self, len: usize);
500    /// Just process the data in the last committed space for future matching.
501    fn skip_matching(&mut self);
502    /// Hint-aware skip path used internally to thread a precomputed block
503    /// incompressibility verdict to matcher backends.
504    ///
505    /// Default implementation preserves backwards compatibility for external
506    /// custom matchers by delegating to [`skip_matching`](Self::skip_matching).
507    fn skip_matching_with_hint(&mut self, _incompressible_hint: Option<bool>) {
508        self.skip_matching();
509    }
510    /// Process the data in the last committed space for future matching AND
511    /// report its sequences, in order, covering the whole block (see
512    /// [`Sequence`]).
513    fn start_matching(&mut self, handle_sequence: impl FnMut(Sequence));
514    /// Reset this matcher so it can be used for the next new frame
515    fn reset(&mut self, level: CompressionLevel);
516    /// Reset for the next frame at `level`, as [`reset`](Self::reset), with
517    /// the compression context's workspace to take tables from rather than
518    /// allocating them. The context calls this in place of `reset`, once per
519    /// frame.
520    ///
521    /// The workspace type cannot be named outside this crate, so a matcher
522    /// defined elsewhere can neither override nor call this: it keeps the
523    /// default, which resets and keeps its own allocations. That is what makes
524    /// the workspace's regions sound to hand out: only the context lays it out,
525    /// and only for the matcher it is resetting.
526    #[doc(hidden)]
527    fn reset_in_workspace(
528        &mut self,
529        level: CompressionLevel,
530        _workspace: &mut workspace::Workspace,
531    ) {
532        self.reset(level);
533    }
534    /// Move whatever this matcher holds in a compression context's workspace
535    /// into allocations of its own, before it leaves that context. Only a
536    /// matcher that takes [`reset_in_workspace`](Self::reset_in_workspace)
537    /// holds anything there.
538    #[doc(hidden)]
539    fn leave_workspace(&mut self) {}
540    /// Provide a hint about the total uncompressed size for the next frame.
541    ///
542    /// Implementations may use this to select smaller hash tables and windows
543    /// for small inputs, matching the C zstd source-size-class behavior.
544    /// Called before [`reset`](Self::reset) when the caller knows the input
545    /// size (e.g. from pledged content size or file metadata).
546    ///
547    /// The default implementation is a no-op for custom matchers and
548    /// test stubs. The built-in runtime matcher (`MatchGeneratorDriver`)
549    /// overrides this hook and applies the hint during level resolution.
550    fn set_source_size_hint(&mut self, _size: u64) {}
551    /// Hint the sizes of the dictionary that will be primed into the next
552    /// frame. The built-in runtime matcher resolves the frame's cParams from
553    /// the dictionary's CDict tier (upstream `ZSTD_createCDict`, keyed by the
554    /// serialized size) and sizes its dictionary tables from the content.
555    /// Default no-op for custom matchers and test stubs; consumed at the next
556    /// [`reset`](Self::reset).
557    fn set_dictionary_size_hint(&mut self, _sizes: DictionarySizes) {}
558    /// Drop any per-frame fine-grained parameter overrides installed via
559    /// the public parameter API, reverting to plain level-based geometry
560    /// at the next [`reset`](Self::reset). Called by
561    /// [`FrameCompressor::set_compression_level`](crate::encoding::FrameCompressor::set_compression_level)
562    /// so switching back to a bare level after a customized frame does not
563    /// keep the old overrides sticky. Default no-op for custom matchers.
564    fn clear_param_overrides(&mut self) {}
565    /// Prime matcher state with dictionary history before compressing the next frame.
566    /// Default implementation is a no-op for custom matchers that do not support this.
567    fn prime_with_dictionary(&mut self, _dict_content: &[u8], _offset_hist: [u32; 3]) {}
568    /// Whether the most recent [`reset`](Self::reset) re-borrowed a resident
569    /// attach-mode dictionary (kept the dict bytes + cached index in place).
570    /// When `true` the caller MUST skip [`Self::prime_with_dictionary`] and only
571    /// reapply the offset history via [`Self::reapply_resident_dictionary`].
572    fn dictionary_is_resident(&self) -> bool {
573        false
574    }
575    /// Reapply the dictionary's offset history to a re-borrowed frame — the cheap
576    /// tail of priming, without the dict commit / re-index. Default no-op.
577    fn reapply_resident_dictionary(&mut self, _offset_hist: [u32; 3]) {}
578    /// CDict-equivalent fast path for repeated frames sharing one dictionary.
579    /// Restore the matcher state captured by [`Self::capture_primed_dictionary`]
580    /// at the SAME level (a table copy) instead of re-running
581    /// [`Self::prime_with_dictionary`] (which re-hashes every dictionary
582    /// position). Returns `true` when a matching snapshot was restored;
583    /// `false` (the default) means the caller must prime then capture.
584    fn restore_primed_dictionary(&mut self, _level: CompressionLevel) -> bool {
585        false
586    }
587    /// Snapshot the post-prime matcher state for the given level so later
588    /// frames can [`Self::restore_primed_dictionary`] it. Default no-op.
589    fn capture_primed_dictionary(&mut self, _level: CompressionLevel) {}
590    /// Drop any captured prime snapshot (dictionary or level changed).
591    /// Default no-op.
592    fn invalidate_primed_dictionary(&mut self) {}
593    /// Seed matcher cost model with dictionary entropy tables before the next frame.
594    /// Default implementation is a no-op for custom matchers.
595    fn seed_dictionary_entropy(
596        &mut self,
597        _huff: Option<&crate::huff0::huff0_encoder::HuffmanTable>,
598        _ll: Option<&crate::fse::fse_encoder::FSETable>,
599        _ml: Option<&crate::fse::fse_encoder::FSETable>,
600        _of: Option<&crate::fse::fse_encoder::FSETable>,
601    ) {
602    }
603    /// Returns whether this matcher can consume dictionary priming state and produce
604    /// dictionary-dependent sequences. Defaults to `false` for custom matchers.
605    fn supports_dictionary_priming(&self) -> bool {
606        false
607    }
608    /// Whether a sample of `block` hashes to a match in an attached dictionary.
609    /// The raw-fast-path uses this to avoid skipping the scan on a block that
610    /// looks incompressible but compresses against the dictionary (an external
611    /// match the block's own content cannot reveal). Defaults to `false` for
612    /// custom matchers (and the no-dict case), leaving the content-only verdict.
613    fn block_samples_match_dict(&self, _block: &[u8]) -> bool {
614        false
615    }
616    /// Heap bytes this matcher's allocations hold (tables, history, scratch),
617    /// excluding the inline struct itself. Lets a context report its true
618    /// footprint via `ZSTD_sizeof_CCtx`. Defaults to `0` for custom matchers.
619    fn heap_size(&self) -> usize {
620        0
621    }
622    /// The size of the window the decoder will need to execute all sequences produced by this matcher.
623    ///
624    /// Must return a positive (non-zero) value; returning 0 causes
625    /// [`StreamingEncoder`] to reject the first write with an invalid-input error
626    /// (`InvalidInput` with `std`, `Other` with `no_std`).
627    ///
628    /// Must remain stable for the lifetime of a frame.
629    /// It may change only after `reset()` is called for the next frame
630    /// (for example because the compression level changed).
631    fn window_size(&self) -> u64;
632}
633
634/// Sequences that a [`Matcher`] can produce, in block order.
635///
636/// A sequence names lengths, not bytes: the literals are the block's own bytes,
637/// and the encoder reads them from the block by position. The sequences of a
638/// block therefore cover it from its first byte, in order, each one's literals
639/// followed by its match, with any trailing literals last.
640#[derive(Clone, Copy, PartialEq, Eq, Debug)]
641pub enum Sequence {
642    /// `literal_len` literal bytes, then `match_len` bytes copied from `offset`
643    /// bytes back in the decoded data.
644    Triple {
645        literal_len: usize,
646        offset: usize,
647        match_len: usize,
648    },
649    /// The block's trailing literals, after its last match. Reported last.
650    Literals { len: usize },
651}
652
653#[cfg(test)]
654mod compress_bound_tests;
655#[cfg(test)]
656pub(crate) mod test_support;
657#[cfg(test)]
658mod tests;