Skip to main content

structured_zstd/encoding/match_generator/
mod.rs

1//! Matching algorithm used find repeated parts in the original data
2//!
3//! The Zstd format relies on finden repeated sequences of data and compressing these sequences as instructions to the decoder.
4//! A sequence basically tells the decoder "Go back X bytes and copy Y bytes to the end of your decode buffer".
5//!
6//! The task here is to efficiently find matches in the already encoded data for the current suffix of the not yet encoded data.
7
8use alloc::vec::Vec;
9// SIMD/CRC intrinsics now live in `crate::encoding::fastpath::*` where they
10// sit under per-CPU `#[target_feature]` umbrellas; no architecture-specific
11// intrinsic imports remain in this file.
12use super::CompressionLevel;
13use super::Matcher;
14use super::Sequence;
15use super::cost_model::HC_FORMAT_MINMATCH;
16#[cfg(test)]
17use super::cost_model::HC_MAX_LIT;
18#[cfg(test)]
19use super::cost_model::{
20    HC_BITCOST_MULTIPLIER, HC_OPT_NUM, HC_PREDEF_THRESHOLD, HcOptState, HcOptimalCostProfile,
21};
22#[cfg(test)]
23use super::cost_model::{HC_BLOCKSIZE_MAX, HC_MAX_LL, HC_MAX_ML, HC_MAX_OFF, HcOptPriceType};
24use super::dfast::DfastMatchGenerator;
25#[cfg(test)]
26use super::hc::HC_MIN_MATCH_LEN;
27#[cfg(test)]
28use super::match_table::storage::HC3_HASH_LOG;
29// FAST_HASH_FILL_STEP test-only re-export was tied to the legacy
30// SuffixStore MatchGenerator's interleaved hash-fill stride. The
31// upstream zstd-shape Fast kernel walks ip0 with kSearchStrength step-skip
32// acceleration instead, so the constant has no consumer in the
33// remaining live test set today.
34#[cfg(test)]
35use super::match_table::helpers::INCOMPRESSIBLE_SKIP_STEP;
36use super::match_table::helpers::MIN_MATCH_LEN;
37#[cfg(test)]
38use super::match_table::helpers::common_prefix_len;
39#[cfg(test)]
40use super::opt::ldm::HcRawSeq;
41#[cfg(test)]
42use super::opt::types::{HcCandidateQuery, MatchCandidate};
43use super::row::RowMatchGenerator;
44use super::simple::fast_matcher::{FAST_LEVEL_1_HASH_LOG, FAST_LEVEL_1_MLS, FastKernelMatcher};
45
46pub(crate) const DFAST_MIN_MATCH_LEN: usize = 5;
47// Bytes the dfast short hash reads (upstream zstd `mls = 5`). Seeding / lookahead
48// guards use it so a position is only short-hashed once its full 5-byte key
49// is in range.
50pub(crate) const DFAST_SHORT_HASH_LOOKAHEAD: usize = 5;
51pub(crate) const ROW_MIN_MATCH_LEN: usize = 5;
52// Upstream zstd `clevels.h:31` at level 3 large-input bucket sets
53// `hashLog = 17` (the long-hash table) and `chainLog = 16` (the
54// short-hash table — upstream zstd names this `chainTable` even though for
55// dfast it's used as a plain single-slot hash). Each table holds one
56// `U32` per slot; the upstream zstd overwrites on collision and recovers
57// compression quality via the inline `_search_next_long` retry
58// (after a short-hash hit, probes `hashLong[hl1]` at `ip + 1` and
59// keeps the longer match).
60//
61// We mirror that storage layout: single `u32` per bucket (no
62// `[u32; N]` array), `long_hash` sized `1 << DFAST_HASH_BITS` and
63// `short_hash` one bit smaller via `DFAST_SHORT_HASH_BITS_DELTA`.
64// Two-table footprint at Level 3: `2^17 × 4 + 2^16 × 4 = 768 KiB`,
65// exact upstream parity. The `_search_next_long` retry lives in
66// `DfastMatchGenerator::hash_candidate` (called via
67// `best_match`). Earlier revisions kept a
68// 4-slot bucket per hash position; that paid 4× the upstream zstd memory
69// without measurable ratio gain once the retry was in place.
70//
71// `dfast_hash_bits_for_window` still clamps the runtime long-hash
72// value to `[MIN_WINDOW_LOG, DFAST_HASH_BITS]`, so this const is the
73// upper bound rather than a fixed default.
74pub(crate) const DFAST_HASH_BITS: usize = 17;
75/// Difference between `long_hash_bits` and `short_hash_bits` —
76/// upstream zstd `hashLog - chainLog` is 1 at every dfast level (`clevels.h`
77/// level 2: 16-15=1; level 3: 17-16=1). The short hash is one bit
78/// smaller than the long hash so the per-bucket footprint matches
79/// upstream zstd sizing exactly.
80pub(crate) const DFAST_SHORT_HASH_BITS_DELTA: usize = 1;
81/// Sentinel value for an empty slot in the dfast hash tables. Real
82/// positions are stored as `(abs_pos - position_base + 1) as u32`, so
83/// `0` is reserved as the "empty" marker and a true relative offset
84/// of `0` never appears in the table. Mirrors the LDM table's
85/// `LdmEntry.offset == 0` convention (see `encoding/ldm/table.rs`)
86/// so both rebasing structures share
87/// one sentinel scheme.
88pub(crate) const DFAST_EMPTY_SLOT: u32 = 0;
89
90/// Guard band reserved above the high-water mark before triggering a
91/// rebase on the Dfast hash tables. When the next insert would push a
92/// relative offset above `u32::MAX - DFAST_REBASE_GUARD_BAND`, the
93/// table calls `reduce(GUARD_BAND)` to shift every slot down and
94/// advance `position_base` so future inserts stay inside the `u32`
95/// window. Same scheme as `encoding/ldm/table.rs`.
96pub(crate) const DFAST_REBASE_GUARD_BAND: u32 = 1u32 << 30;
97// `kSearchStrength` (upstream `zstd_compress_internal.h:32`). The dfast step
98// ramp grows one position every `1 << kSearchStrength` = 256 bytes travelled
99// (upstream `kStepIncr`, zstd_double_fast.c:131). A smaller value accelerates
100// the scan faster and skips source positions upstream still inserts, which
101// drops the short matches upstream finds at a block start — so the
102// `#167`-disabled path must use the upstream 8 to stay byte-identical.
103pub(crate) const DFAST_SKIP_SEARCH_STRENGTH: usize = 8;
104pub(crate) const DFAST_SKIP_STEP_GROWTH_INTERVAL: usize = 1 << DFAST_SKIP_SEARCH_STRENGTH;
105/// How densely dfast indexes a block it wrote off without searching.
106///
107/// The block is not searched, so the only reason to index it at all is that a
108/// LATER block may duplicate it, and a duplicate is block-sized: the search
109/// that scans it meets an indexed position within one step, which is far inside
110/// what it scans anyway. Indexing at every sixteenth position instead cost a
111/// third of the encode on incompressible input — two tables, sixty-five
112/// thousand stores per mebibyte — for a proximity nothing needs. Fast reads the
113/// same reasoning from [`RAW_SKIP_INDEX_STEP`].
114pub(crate) const DFAST_INCOMPRESSIBLE_SKIP_STEP: usize =
115    crate::encoding::incompressible::RAW_SKIP_INDEX_STEP;
116pub(crate) const ROW_HASH_BITS: usize = 20;
117pub(crate) const ROW_LOG: usize = 5;
118pub(crate) const ROW_SEARCH_DEPTH: usize = 16;
119pub(crate) const ROW_TARGET_LEN: usize = 48;
120pub(crate) const ROW_TAG_BITS: usize = 8;
121pub(crate) const ROW_EMPTY_SLOT: u32 = u32::MAX;
122pub(crate) const ROW_HASH_KEY_LEN: usize = 4;
123// HC_PRIME3BYTES / HC_PRIME4BYTES moved to match_table::storage
124// alongside the hash helpers in Phase 1e Stage A. Only the test
125// module references the constants directly (production code goes
126// through `MatchTable::hash_value_with_mls`).
127#[cfg(test)]
128use super::match_table::storage::{HC_PRIME3BYTES, HC_PRIME4BYTES};
129
130// HC_HASH_LOG / HC_CHAIN_LOG / HC3_HASH_LOG / HC_EMPTY live on the
131// shared storage module so MatchTable methods can reference them
132// without pulling in this module. Re-imported here so existing
133// macros / configs / tests keep their unqualified names.
134#[cfg(test)]
135use super::match_table::storage::HC_EMPTY;
136// HC3_MAX_OFFSET moved to encoding::bt alongside the hash3 candidate
137// probe macro that consumes it; the macro references it via the
138// fully-qualified `$crate::encoding::bt::HC3_MAX_OFFSET` path so this
139// module no longer needs a local import.
140pub(crate) const HC_SEARCH_DEPTH: usize = 16;
141// HC_MIN_MATCH_LEN moved to encoding::hc; re-imported here so
142// existing references compile unchanged.
143pub(crate) const HC_OPT_MIN_MATCH_LEN: usize = HC_FORMAT_MINMATCH;
144pub(crate) const HC_TARGET_LEN: usize = 48;
145
146// MAX_HC_SEARCH_DEPTH moved to encoding::hc alongside chain_candidates.
147// Per-level tuning config (the config structs + `LEVEL_TABLE` + the
148// level→params resolution chain) lives in `levels::config`; the driver imports
149// that resolution API here.
150use super::levels::config::*;
151// The HashChain / BT match generator + its optimal-parse machinery lives in
152// `hc::generator`; the driver stores it in the `HashChain` storage variant.
153use super::hc::generator::HcMatchGenerator;
154
155// Dictionary prime + CDict-equivalent snapshot lifecycle. A child module so it
156// can reach the driver's private `primed` / `reset_shape` state directly; the
157// `Matcher` trait's dict entry points forward to its inherent `*_impl` helpers.
158mod dict_prime;
159
160// `Strategy` and `StrategyTag` live in `crate::encoding::strategy`.
161// The driver carries a `StrategyTag` field set at `reset()` and
162// dispatches each block into a monomorphised `compress_block::<S>`
163// per concrete strategy.
164
165/// Backend storage for [`MatchGeneratorDriver`]. Exactly one match-finder
166/// state lives in the driver at a time — the active variant. Backend
167/// transitions in [`Matcher::reset`] drain the current variant's allocations
168/// into the shared `vec_pool` and then replace `storage` with a freshly
169/// constructed variant for the new backend.
170///
171/// Replaces the prior pattern of four parallel fields (`match_generator`,
172/// `dfast_match_generator: Option<…>`, `row_match_generator: Option<…>`,
173/// `hc_match_generator: Option<…>`) + an `active_backend: BackendTag`
174/// discriminator: the parallel layout kept drained inner structures
175/// allocated across backend switches, and every per-frame/per-slice
176/// driver operation had to dispatch on `active_backend` to pick the
177/// right field. A single enum collapses the storage and makes the
178/// dispatcher pattern-match on the storage variant directly — same
179/// number of arms, but `storage.backend()` is now the canonical source
180/// of truth and dead variants are dropped when the active backend
181/// changes.
182#[derive(Clone)]
183enum MatcherStorage {
184    /// Upstream zstd `ZSTD_fast` family. Constructed by
185    /// [`MatchGeneratorDriver::new`] as the initial variant and
186    /// re-selected by [`Matcher::reset`] for any [`CompressionLevel`]
187    /// that `resolve_level_params` maps to [`StrategyTag::Fast`]
188    /// (`Uncompressed`, `Fastest`, `Level(1)`, and any non-positive
189    /// `Level(n)` not equal to `0`).
190    Simple(FastKernelMatcher),
191    /// Upstream zstd `ZSTD_dfast` family — two-table hash chain. Selected for
192    /// any level that resolves to [`StrategyTag::Dfast`] in
193    /// `resolve_level_params` (`Default`, `Level(0)`, `Level(2)`,
194    /// `Level(3)`).
195    Dfast(DfastMatchGenerator),
196    /// Upstream zstd `ZSTD_greedy` family with row hashing. Selected for any
197    /// level that resolves to [`StrategyTag::Greedy`] (currently
198    /// `Level(4)` only).
199    Row(RowMatchGenerator),
200    /// Upstream zstd `ZSTD_lazy2` and the BT-based optimal modes
201    /// (`btopt` / `btultra` / `btultra2`). Selected for any level that
202    /// resolves to [`StrategyTag::Lazy`], [`StrategyTag::BtOpt`],
203    /// [`StrategyTag::BtUltra`], or [`StrategyTag::BtUltra2`]
204    /// (`Better`, `Best`, `Level(5..=22)`, and any `Level(n)` with
205    /// `n > MAX_LEVEL` — `resolve_level_params` clamps positive
206    /// numeric levels at `MAX_LEVEL = 22` via
207    /// `Level(n).clamp(1, MAX_LEVEL)`, so `Level(23..=i32::MAX)` all
208    /// land on `BtUltra2` here). The [`HcMatchGenerator`]'s internal
209    /// [`HcBackend`] discriminator decides whether BT scratch is
210    /// allocated.
211    HashChain(HcMatchGenerator),
212}
213
214impl MatcherStorage {
215    /// Heap bytes the active backend variant holds (tables, history, scratch).
216    fn heap_size(&self) -> usize {
217        match self {
218            Self::Simple(m) => m.heap_size(),
219            Self::Dfast(m) => m.heap_size(),
220            Self::Row(m) => m.heap_size(),
221            Self::HashChain(m) => m.heap_size(),
222        }
223    }
224
225    /// Capacity of the buffer blocks are read into, for the backends that
226    /// ingest in place. A frame sized up front reserves this exactly; one that
227    /// grew into it lands on a doubling step instead, which is what makes the
228    /// difference observable to a test.
229    #[cfg(test)]
230    fn ingest_capacity(&self) -> usize {
231        match self {
232            Self::Simple(m) => m.history_capacity(),
233            Self::Dfast(m) => m.history.capacity(),
234            Self::Row(m) => m.history.capacity(),
235            Self::HashChain(m) => m.table.history.capacity(),
236        }
237    }
238
239    /// [`super::strategy::BackendTag`] family of the active variant.
240    fn backend(&self) -> super::strategy::BackendTag {
241        use super::strategy::BackendTag;
242        match self {
243            Self::Simple(_) => BackendTag::Simple,
244            Self::Dfast(_) => BackendTag::Dfast,
245            Self::Row(_) => BackendTag::Row,
246            Self::HashChain(_) => BackendTag::HashChain,
247        }
248    }
249}
250
251/// This is the default implementation of the `Matcher` trait. It allocates and reuses the buffers when possible.
252pub struct MatchGeneratorDriver {
253    vec_pool: Vec<Vec<u8>>,
254    /// Active match-finder state. Exactly one backend lives here at a
255    /// time; [`Matcher::reset`] drains the previous variant into
256    /// `vec_pool` before swapping in a freshly constructed variant for
257    /// the new backend. `storage.backend()` is the canonical source of
258    /// truth for the parse family; `strategy_tag` carries the
259    /// compile-time strategy chosen at the last `reset()`.
260    storage: MatcherStorage,
261    // Compile-time strategy tag resolved at `reset()` from the
262    // requested `CompressionLevel`'s `LevelParams`. The driver's
263    // hot-block dispatcher in `blocks/compressed.rs` matches on
264    // this tag to enter the corresponding `Strategy`
265    // monomorphisation (`compress_block::<S>`).
266    strategy_tag: super::strategy::StrategyTag,
267    // Decoupled search-method axis resolved at `reset()` from
268    // `LevelParams.search`. The per-block dispatcher routes on this
269    // (not on `strategy_tag`) so a level's parse and search backend can
270    // be chosen independently. The `BinaryTree` arm still consults
271    // `strategy_tag` to pick the opt `Strategy` ZST.
272    search: super::strategy::SearchMethod,
273    // Decoupled parse-mode axis resolved at `reset()` from
274    // `LevelParams::parse()`. Independent of `search`: greedy / lazy /
275    // lazy2 can run on any non-opt search backend. The backends still
276    // read their own `lazy_depth` (kept in sync at `reset()`); this is
277    // the authoritative parse selector for the dispatcher.
278    pub(crate) parse: super::strategy::ParseMode,
279    /// Test-only per-level recipe override applied in `reset()` before
280    /// backend selection. Lets the parse×search matrix be exercised
281    /// without editing `LEVEL_TABLE`; never compiled into production.
282    #[cfg(test)]
283    config_override: Option<(super::strategy::SearchMethod, super::strategy::ParseMode)>,
284    /// Fine-grained per-knob overrides from the public
285    /// [`super::parameters::CompressionParameters`] surface (#27).
286    /// `None` (or an all-`None` [`super::parameters::ParamOverrides`])
287    /// keeps the resolved level geometry byte-identical to plain
288    /// level-based compression. Applied in [`Matcher::reset`] after the
289    /// level params are resolved, before backend selection. Persists
290    /// across resets (it is frame configuration, not a one-shot) until
291    /// the caller changes it.
292    param_overrides: Option<super::parameters::ParamOverrides>,
293    slice_size: usize,
294    base_slice_size: usize,
295    // Frame header window size must stay at the configured live-window budget.
296    // Dictionary retention expands internal matcher capacity only.
297    reported_window_size: usize,
298    // Tracks currently retained bytes that originated from primed dictionary
299    // history and have not been evicted yet.
300    dictionary_retained_budget: usize,
301    // Source size hint for next frame (set via set_source_size_hint, cleared on reset).
302    source_size_hint: Option<u64>,
303    // Dictionary sizes for the next frame (set via set_dictionary_size_hint,
304    // consumed on reset): the serialized size keys the CDict cParams tier the
305    // frame runs (upstream `ZSTD_getCParamRowSize` on `dictSize`), the content
306    // size the dictionary tables and attach cutoffs.
307    dictionary_size_hint: Option<super::DictionarySizes>,
308    // Normalized `ceil_log2` bucket of the frame's source-size hint, captured at
309    // `reset` (where `source_size_hint` is consumed) via [`source_size_ceil_log`].
310    // `None` means the frame was unhinted. Drives `prime_with_dictionary`'s upstream zstd
311    // `ZSTD_shouldAttachDict` mode for the Simple/Fast backend: `None` (unknown)
312    // or `<= FAST_ATTACH_DICT_CUTOFF_LOG` → attach (separate dict table, 2-cursor
313    // `compress_block_fast_dict`); larger → copy (dictionary primed into the live
314    // table, 4-cursor `compress_block_fast`). The primed-snapshot key is the
315    // resolved shape ([`reset_shape`](Self::reset_shape)), not this bucket.
316    reset_size_log: Option<u8>,
317    // Whether the loaded dictionary fits the Fast attach path's tagged position
318    // field (`<= MAX_FAST_ATTACH_DICT_REGION`). Captured at `reset` from the
319    // dict-size hint (which equals the actual dict length on load) so the Fast
320    // attach decision, the attach-epoch reset bit, and the primed-snapshot
321    // `fast_attach` bit all gate on it consistently. `true` when there is no
322    // dictionary (the attach path is then unused). A dict too large to tag falls
323    // back to copy mode instead of overflowing the packed position.
324    reset_dict_attach_ok: bool,
325    // Hint-resolved matcher shape from the last `reset`: the [`LevelParams`], the
326    // active backend's applied Dfast/Row hash-table width (`0` for HC/Fast), the
327    // Fast attach-vs-copy mode, and the active LDM override (#27). Combined with
328    // the frame's level into the [`PrimedKey`] that keys the primed snapshot, so
329    // it is only restored into a reset that resolved the identical matcher AND
330    // LDM configuration. `None` before the first `reset`.
331    reset_shape: Option<(
332        LevelParams,
333        usize,
334        bool,
335        Option<super::parameters::LdmOverride>,
336    )>,
337    // One-shot borrowed block range `[start, end)` staged by the borrowed
338    // Fast frame path (`set_borrowed_block`) for the NEXT
339    // `start_matching` / `skip_matching_with_hint`. `Some` routes that
340    // call to the Simple backend's borrowed scan instead of the owned
341    // committed-block path; consumed (reset to `None`) by the routed
342    // call. Always `None` on the owned streaming path.
343    borrowed_pending: Option<(usize, usize)>,
344    /// CDict-equivalent: snapshot of the post-prime matcher state taken
345    /// once after the first dictionary prime — the backend `storage`
346    /// (hash tables + dictionary history + offset history + window) plus
347    /// the driver-level `dictionary_retained_budget`, the only two pieces
348    /// `prime_with_dictionary` writes. Subsequent frames restore this
349    /// (a table memcpy) instead of re-hashing every dictionary position,
350    /// mirroring upstream zstd `ZSTD_compressBegin_usingCDict` copying the
351    /// precomputed `cdict->matchState`. Invalidated when the dictionary
352    /// changes; keyed by the [`PrimedKey`] resolved matcher shape so a snapshot
353    /// is only restored into a reset that produces the same matcher — see
354    /// `restore_primed_dictionary`.
355    primed: Option<(MatcherStorage, usize, PrimedKey)>,
356}
357
358/// Identity of the matcher configuration a primed snapshot was captured under:
359/// the FULLY RESOLVED matcher shape, not the raw source-size hint.
360///
361/// `reset()` resolves the hint into a [`LevelParams`] (window_log cap, the
362/// HC/Fast table and search geometry, the parse depth/target-length that get
363/// baked into the restored `storage`) plus, for the Dfast/Row backends, a
364/// table-width derived from the hint's ceil-log bucket. The mapping from hint
365/// to resolved shape is many-to-one: the source-size adjustment is monotone in
366/// `ceil_log2(hint)`, and Level 22 additionally collapses several buckets onto
367/// one upstream zstd tier (its `<= 16/128/256 KiB` thresholds). Keying on the raw hint
368/// (or even its ceil-log bucket) therefore over-keys — two hints that resolve
369/// to the identical matcher would each force a full re-prime. Keying on the
370/// resolved (`params`, `table_bits`) pair restores across them.
371///
372/// `table_bits` is the hint-dependent hash-table width the ACTIVE backend
373/// applied (`set_hash_bits` value for Dfast/Row; `0` for HC/Fast, whose widths
374/// already live in `params`). The snapshot is only ever captured on the COPY
375/// path (a hinted, above-cutoff frame), so `table_bits` is always the resolved
376/// Dfast/Row value there, never the unhinted default.
377///
378/// `level` is kept alongside the resolved `params` because some stored matcher
379/// state is derived from the level DIRECTLY, not through `params`: e.g. Dfast's
380/// `use_fast_loop` is true for L3 but false for L4, yet L3 and L4 resolve to
381/// byte-identical `params`. Without `level` a snapshot captured at L3 could be
382/// restored into an L4 reset, installing the wrong `use_fast_loop`.
383///
384/// `fast_attach` records the Fast backend's attach-vs-copy mode
385/// ([`FAST_ATTACH_DICT_CUTOFF_LOG`]) because that cutoff (8 KiB) falls INSIDE a
386/// single resolved shape: an 8192- and an 8193-byte Level 1 hint both clamp to
387/// window_log 14 with identical `params`/`table_bits`, yet 8192 attaches (a
388/// separate dict table) while 8193 copies into the live table — two different
389/// `storage` shapes. The frame compressor only captures/restores snapshots on
390/// the copy path today, but keying on the mode keeps the snapshot identity
391/// self-sufficient rather than relying on that external gate.
392///
393/// Restoring a snapshot whose key differs would reinstate the old `storage`
394/// (and its `max_window_size` / table dimensions / parse params / dict-table
395/// shape) under a reset that resolved a different shape — the encoder could
396/// then search past the frame header's window and emit an undecodable match.
397/// All fields must match before a restore is allowed.
398#[derive(Clone, Copy, PartialEq, Eq)]
399struct PrimedKey {
400    level: super::CompressionLevel,
401    params: LevelParams,
402    table_bits: usize,
403    fast_attach: bool,
404    /// Fine-grained LDM override (#27) active at capture time. The
405    /// snapshot's cloned `storage` carries `BtMatcher::ldm_producer`,
406    /// which is configured from this override; restoring a snapshot
407    /// captured under a different LDM configuration (enable flip or
408    /// changed knobs) would reinstate a stale producer. `params` already
409    /// pins `window_log` / `strategy_tag` (the rest of the producer's
410    /// identity), so folding the override completes the LDM identity.
411    /// `None` = LDM off, matching `ParamOverrides::ldm`.
412    ldm: Option<super::parameters::LdmOverride>,
413}
414
415impl MatchGeneratorDriver {
416    /// See [`MatcherStorage::ingest_capacity`].
417    #[cfg(test)]
418    pub(crate) fn ingest_capacity(&self) -> usize {
419        self.storage.ingest_capacity()
420    }
421
422    /// `slice_size` sets the base block allocation size used for matcher input chunks.
423    /// `max_slices_in_window` determines the initial window capacity at construction
424    /// time. Effective window sizing is recalculated on every [`reset`](Self::reset)
425    /// from the resolved compression level and optional source-size hint.
426    pub(crate) fn new(slice_size: usize, max_slices_in_window: usize) -> Self {
427        // Validate inputs before deriving window_log_init. Three
428        // failure modes need explicit guards:
429        //
430        // 1. Zero args → `max_window_size = 0` → silent 1-byte
431        //    degenerate window (useless).
432        // 2. Multiplication overflow on `slice_size *
433        //    max_slices_in_window` → wraps silently in release.
434        // 3. `next_power_of_two` overflow when the product is
435        //    above `1 << (usize::BITS - 1)` → modern Rust PANICS
436        //    on overflow (older Rust returned 0).
437        //
438        // Catch all three at construction with a clear domain-
439        // specific message via `assert!` + `checked_mul` +
440        // `checked_next_power_of_two`, rather than letting either
441        // mode produce a silent degenerate matcher OR a generic
442        // panic deep in `FastKernelMatcher::with_params`.
443        assert!(
444            slice_size > 0,
445            "MatchGeneratorDriver::new requires slice_size > 0 (got 0)",
446        );
447        assert!(
448            max_slices_in_window > 0,
449            "MatchGeneratorDriver::new requires max_slices_in_window > 0 (got 0)",
450        );
451        let max_window_size = max_slices_in_window
452            .checked_mul(slice_size)
453            .expect("MatchGeneratorDriver::new: slice_size * max_slices_in_window overflows usize");
454        // Derive an effective window_log for the initial-state matcher.
455        // `MatchGeneratorDriver::new` runs BEFORE any reset, so it has
456        // no LevelParams to consult — we initialise to whatever
457        // window_log fits the caller's requested max_window_size
458        // (round up to the next power of two via `next_power_of_two`'s
459        // log). Reset() overwrites all three params from the resolved
460        // LevelParams.
461        //
462        // `checked_next_power_of_two` returns `None` if the next power
463        // of two would overflow `usize`. Modern Rust's
464        // `next_power_of_two` PANICS on overflow rather than returning
465        // 0 (the panic message is generic and unhelpful), so use the
466        // checked variant to surface the failure with a clear,
467        // domain-specific error.
468        let next_pow2 = max_window_size.checked_next_power_of_two().expect(
469            "MatchGeneratorDriver::new: max_window_size too large for \
470             next_power_of_two without overflow",
471        );
472        let window_log_init = next_pow2.trailing_zeros() as u8;
473        Self {
474            vec_pool: Vec::new(),
475            // Deferred table: `new` runs before any source size or resolved
476            // LevelParams exist, so allocating at the level-default hash_log
477            // here would be thrown away by the first frame's reset (which
478            // clamps the window to the input and reallocs at the resolved
479            // size). The deferral lets that first reset allocate exactly once.
480            storage: MatcherStorage::Simple(FastKernelMatcher::with_params_deferred(
481                window_log_init,
482                FAST_LEVEL_1_HASH_LOG,
483                FAST_LEVEL_1_MLS,
484                2, // upstream zstd default step_size (targetLength=0 → step=2)
485            )),
486            strategy_tag: super::strategy::StrategyTag::Fast,
487            search: super::strategy::SearchMethod::Fast,
488            parse: super::strategy::ParseMode::Greedy,
489            #[cfg(test)]
490            config_override: None,
491            param_overrides: None,
492            slice_size,
493            base_slice_size: slice_size,
494            // Report the ROUNDED-UP window size that the matcher
495            // actually carries (via `window_log_init = log2(next_pow2)`
496            // → matcher's `max_window_size = 1 << window_log_init =
497            // next_pow2`). For non-power-of-two `slice_size *
498            // max_slices_in_window` inputs, the unrounded value
499            // would under-report the active backend's window until
500            // the first `reset()` overwrites both sides from the
501            // resolved LevelParams.
502            reported_window_size: next_pow2,
503            reset_size_log: None,
504            reset_dict_attach_ok: true,
505            reset_shape: None,
506            dictionary_retained_budget: 0,
507            source_size_hint: None,
508            dictionary_size_hint: None,
509            borrowed_pending: None,
510            primed: None,
511        }
512    }
513
514    fn level_params(level: CompressionLevel, source_size: Option<u64>) -> LevelParams {
515        resolve_level_params(level, source_size)
516    }
517
518    /// Install the public-parameter per-knob overrides (#27) applied at
519    /// the next [`Matcher::reset`]. `None` (or an all-`None` set) restores
520    /// plain level-based geometry. Persists across resets until changed.
521    pub(crate) fn set_param_overrides(
522        &mut self,
523        overrides: Option<super::parameters::ParamOverrides>,
524    ) {
525        self.param_overrides = overrides;
526    }
527
528    /// Active backend family derived from the storage variant. Single
529    /// source of truth — no separate runtime tag to drift against.
530    pub(crate) fn active_backend(&self) -> super::strategy::BackendTag {
531        self.storage.backend()
532    }
533
534    /// Whether the borrowed (no-copy, in-place over-window) scan is
535    /// implemented for the current backend + search configuration. The
536    /// HashChain backend serves both the lazy CHAIN parser
537    /// (`SearchMethod::HashChain`) and the BT/optimal parsers
538    /// (`SearchMethod::BinaryTree`); only the lazy chain has a borrowed scan
539    /// so far, so BT/optimal stay on the owned path.
540    pub(crate) fn borrowed_supported(&self) -> bool {
541        use super::strategy::{BackendTag, SearchMethod};
542        match self.active_backend() {
543            BackendTag::Simple | BackendTag::Dfast | BackendTag::Row => true,
544            // The HashChain backend covers two searches: the lazy CHAIN parser
545            // (borrowed-capable) and the BINARY-TREE search (btlazy2 L13-15 +
546            // optimal BtOpt/BtUltra/BtUltra2 L16-22). btlazy2's BT-tree borrowed
547            // scan is byte-identical to owned (reads via live_history()), so it
548            // takes the in-place path. The OPTIMAL parsers stay owned: their
549            // cost-based DP is sensitive to candidate quality, and the borrowed
550            // continuous-index scan yields slightly different (ratio-worse)
551            // candidates than the owned evict+rehash scan — borrowed optimal
552            // both diverged from owned and fell outside the ffi ratio bound.
553            // Search-aware (not just strategy_tag) so optimal BT can never be
554            // staged on the borrowed path even via an internal caller.
555            BackendTag::HashChain => matches!(self.search, SearchMethod::HashChain),
556        }
557    }
558
559    /// Whether a DICTIONARY frame can take the borrowed (no input copy) path.
560    /// Only the Simple (Fast) backend with the dictionary ATTACHED (not the
561    /// copy/merge regime) has a borrowed dict scan — `start_matching_borrowed_dict`
562    /// reads live matches from the borrowed input in place and dict matches
563    /// from the committed dict prefix via the 2-segment counter. Every other
564    /// backend, and copy-mode (large-input) dict frames, stay on the owned
565    /// path. Checked AFTER priming, so `is_attached()` reflects the resolved
566    /// attach-vs-copy decision.
567    pub(crate) fn borrowed_dict_supported(&self) -> bool {
568        matches!(
569            &self.storage,
570            MatcherStorage::Simple(m) if m.dict_is_attached()
571        )
572    }
573
574    fn simple_mut(&mut self) -> &mut FastKernelMatcher {
575        match &mut self.storage {
576            MatcherStorage::Simple(m) => m,
577            _ => panic!("simple backend must be initialized by reset() before use"),
578        }
579    }
580
581    /// Reclaim the per-block input buffer that the Simple backend
582    /// just spent inside `start_matching` / `skip_matching_with_hint`.
583    ///
584    /// `FastKernelMatcher::take_recycled_space` returns the cleared
585    /// (capacity-retained) `Vec<u8>` from the last
586    /// `extend_history_with_pending`. We push it onto `vec_pool`
587    /// as-is (with `len = 0`); `get_next_space()` is responsible for
588    /// resizing the buffer back to `slice_size` on its next pop. The
589    /// pushed length is irrelevant — only the capacity matters, and
590    /// `extend_history_with_pending` preserves it. Without this
591    /// recycle path, the Simple backend would allocate a new
592    /// `Vec<u8>` per block — a measurable hot-path cost when blocks
593    /// are small (~128 KiB) and processed at hundreds of MiB/s.
594    fn recycle_simple_space(&mut self) {
595        if let Some(space) = self.simple_mut().take_recycled_space() {
596            // `space` is already cleared (len = 0) by
597            // `extend_history_with_pending`; capacity is retained.
598            // Leaving `len = 0` here avoids the cost of zero-filling
599            // the entire allocation — `get_next_space()` resizes the
600            // popped buffer up to `slice_size` on demand, so the
601            // length the pool holds is irrelevant. This matters most
602            // after a small-source-size hint has shrunk `slice_size`
603            // mid-frame: the recycled buffer can be much larger than
604            // the current `slice_size`, and zero-filling 128 KiB+ on
605            // every block would erase the perf win the recycle path
606            // is meant to deliver.
607            self.vec_pool.push(space);
608        }
609    }
610
611    /// Register a caller-owned input buffer as the Simple backend's
612    /// borrowed one-shot match window. Only valid on the Simple (Fast)
613    /// backend; the one-shot frame path gates on that before calling.
614    ///
615    /// # Safety
616    /// Same contract as [`FastKernelMatcher::set_borrowed_window`]: the
617    /// buffer must stay live and unmodified until the window is cleared,
618    /// and must be cleared before the buffer is dropped or the matcher is
619    /// reused for another frame.
620    pub(crate) unsafe fn set_borrowed_window(&mut self, buffer: &[u8]) {
621        // SAFETY: forwarded contract — caller upholds liveness/clear.
622        match self.active_backend() {
623            super::strategy::BackendTag::Simple => unsafe {
624                self.simple_mut().set_borrowed_window(buffer)
625            },
626            super::strategy::BackendTag::Dfast => unsafe {
627                self.dfast_matcher_mut().set_borrowed_window(buffer)
628            },
629            super::strategy::BackendTag::Row => unsafe {
630                self.row_matcher_mut().set_borrowed_window(buffer)
631            },
632            super::strategy::BackendTag::HashChain => unsafe {
633                self.hc_matcher_mut().set_borrowed_window(buffer)
634            },
635        }
636    }
637
638    /// Clear the borrowed one-shot window, returning the active backend
639    /// to the owned `history` path.
640    pub(crate) fn clear_borrowed_window(&mut self) {
641        match self.active_backend() {
642            super::strategy::BackendTag::Simple => self.simple_mut().clear_borrowed_window(),
643            super::strategy::BackendTag::Dfast => self.dfast_matcher_mut().clear_borrowed_window(),
644            super::strategy::BackendTag::Row => self.row_matcher_mut().clear_borrowed_window(),
645            super::strategy::BackendTag::HashChain => self.hc_matcher_mut().clear_borrowed_window(),
646            #[allow(unreachable_patterns)]
647            _ => {}
648        }
649        self.borrowed_pending = None;
650    }
651
652    /// Stage the borrowed block range `[block_start, block_end)` for the
653    /// NEXT `start_matching` / `skip_matching_with_hint`, which the
654    /// borrowed Fast frame path uses in place of `commit_space`. While
655    /// staged, those trait calls route to the Simple backend's borrowed
656    /// scan/skip (consuming the stage) instead of the owned committed
657    /// block. See [`Matcher::start_matching`] /
658    /// [`Matcher::skip_matching_with_hint`] on this type.
659    pub(crate) fn set_borrowed_block(&mut self, block_start: usize, block_end: usize) {
660        assert!(
661            self.borrowed_supported(),
662            "borrowed block staging is not supported for the active backend/search config",
663        );
664        assert!(
665            block_start <= block_end,
666            "borrowed block range must satisfy start <= end (start={block_start} end={block_end})",
667        );
668        self.borrowed_pending = Some((block_start, block_end));
669        // Make the range visible to `get_last_space()` immediately: the
670        // emit pipeline reads `get_last_space().len()` in
671        // `collect_block_parts` BEFORE `start_matching` consumes the
672        // stage, so the staged block (not the whole borrowed window) must
673        // be reported now to keep the literal-buffer reservation right.
674        match self.active_backend() {
675            super::strategy::BackendTag::Simple => self
676                .simple_mut()
677                .stage_borrowed_block(block_start, block_end),
678            super::strategy::BackendTag::Dfast => self
679                .dfast_matcher_mut()
680                .stage_borrowed_block(block_start, block_end),
681            super::strategy::BackendTag::Row => self
682                .row_matcher_mut()
683                .stage_borrowed_block(block_start, block_end),
684            super::strategy::BackendTag::HashChain => self
685                .hc_matcher_mut()
686                .table
687                .stage_borrowed_block(block_start, block_end),
688        }
689    }
690
691    #[cfg(test)]
692    fn dfast_matcher(&self) -> &DfastMatchGenerator {
693        match &self.storage {
694            MatcherStorage::Dfast(m) => m,
695            _ => panic!("dfast backend must be initialized by reset() before use"),
696        }
697    }
698
699    fn dfast_matcher_mut(&mut self) -> &mut DfastMatchGenerator {
700        match &mut self.storage {
701            MatcherStorage::Dfast(m) => m,
702            _ => panic!("dfast backend must be initialized by reset() before use"),
703        }
704    }
705
706    #[cfg(test)]
707    pub(crate) fn row_matcher(&self) -> &RowMatchGenerator {
708        match &self.storage {
709            MatcherStorage::Row(m) => m,
710            _ => panic!("row backend must be initialized by reset() before use"),
711        }
712    }
713
714    pub(crate) fn row_matcher_mut(&mut self) -> &mut RowMatchGenerator {
715        match &mut self.storage {
716            MatcherStorage::Row(m) => m,
717            _ => panic!("row backend must be initialized by reset() before use"),
718        }
719    }
720
721    #[cfg(test)]
722    fn hc_matcher(&self) -> &HcMatchGenerator {
723        match &self.storage {
724            MatcherStorage::HashChain(m) => m,
725            _ => panic!("hash chain backend must be initialized by reset() before use"),
726        }
727    }
728
729    fn hc_matcher_mut(&mut self) -> &mut HcMatchGenerator {
730        match &mut self.storage {
731            MatcherStorage::HashChain(m) => m,
732            _ => panic!("hash chain backend must be initialized by reset() before use"),
733        }
734    }
735
736    /// Shrink the active backend's `max_window_size` by the bytes
737    /// reclaimed from the dictionary-retention budget. Returns `true`
738    /// iff any reclamation happened — the caller uses that as the
739    /// gate for [`Self::trim_after_budget_retire`] (which is a no-op
740    /// otherwise: with `max_window_size` unchanged the backend's
741    /// `trim_to_window` cannot find anything to evict, so calling it
742    /// just runs an extra `match` ladder + a single early-out check
743    /// per slice commit).
744    #[must_use]
745    fn retire_dictionary_budget(&mut self, evicted_bytes: usize) -> bool {
746        let reclaimed = evicted_bytes.min(self.dictionary_retained_budget);
747        if reclaimed == 0 {
748            return false;
749        }
750        self.dictionary_retained_budget -= reclaimed;
751        match self.active_backend() {
752            super::strategy::BackendTag::Simple => {
753                let matcher = self.simple_mut();
754                // `reclaimed` can exceed the CURRENT `max_window_size`: the
755                // retained dict budget is tracked independently and the
756                // window may already have been shrunk by a prior eviction,
757                // so the floor at 0 is the correct clamp, not a masked bug.
758                matcher.max_window_size = matcher.max_window_size.saturating_sub(reclaimed);
759            }
760            super::strategy::BackendTag::Dfast => {
761                let matcher = self.dfast_matcher_mut();
762                // `reclaimed` can exceed the CURRENT `max_window_size`: the
763                // retained dict budget is tracked independently and the
764                // window may already have been shrunk by a prior eviction,
765                // so the floor at 0 is the correct clamp, not a masked bug.
766                matcher.max_window_size = matcher.max_window_size.saturating_sub(reclaimed);
767            }
768            super::strategy::BackendTag::Row => {
769                let matcher = self.row_matcher_mut();
770                // `reclaimed` can exceed the CURRENT `max_window_size`: the
771                // retained dict budget is tracked independently and the
772                // window may already have been shrunk by a prior eviction,
773                // so the floor at 0 is the correct clamp, not a masked bug.
774                matcher.max_window_size = matcher.max_window_size.saturating_sub(reclaimed);
775            }
776            super::strategy::BackendTag::HashChain => {
777                let matcher = self.hc_matcher_mut();
778                // See the Simple arm: `reclaimed` may exceed the current
779                // window, so saturating to 0 is the correct clamp.
780                matcher.table.max_window_size =
781                    matcher.table.max_window_size.saturating_sub(reclaimed);
782            }
783        }
784        true
785    }
786
787    fn trim_after_budget_retire(&mut self) {
788        loop {
789            let mut evicted_bytes = 0usize;
790            match self.active_backend() {
791                super::strategy::BackendTag::Simple => {
792                    // FastKernelMatcher owns its history as a single
793                    // flat `Vec<u8>` (upstream zstd's flat-buffer layout)
794                    // rather than the legacy per-block `WindowEntry`
795                    // stack. There are no per-block Vec allocations
796                    // to recycle into `vec_pool` — `trim_to_window`
797                    // drains the oldest bytes in-place and returns
798                    // the count for the dictionary-budget loop's
799                    // termination check.
800                    let MatcherStorage::Simple(m) = &mut self.storage else {
801                        unreachable!("active_backend() == Simple proven above");
802                    };
803                    evicted_bytes += m.trim_to_window();
804                }
805                super::strategy::BackendTag::Dfast => {
806                    // Dfast doesn't retain input Vecs — `history` is the
807                    // only byte store, so there is no per-block buffer
808                    // to push back through a callback. Eviction byte
809                    // count is derived from the `window_size` delta
810                    // before/after; the Dfast variant of
811                    // `trim_to_window` takes no closure, sidestepping
812                    // an unused-`impl FnMut` monomorphization that
813                    // would otherwise contractually never fire.
814                    let dfast = self.dfast_matcher_mut();
815                    let pre = dfast.window_size;
816                    dfast.trim_to_window();
817                    evicted_bytes += pre - dfast.window_size;
818                }
819                super::strategy::BackendTag::Row => {
820                    // Row keeps bytes only in the contiguous `history` mirror
821                    // (block buffers are returned to the pool per block in
822                    // `add_data`), so derive the eviction count from the
823                    // `window_size` delta, mirroring the Dfast / HashChain arms.
824                    let row = self.row_matcher_mut();
825                    let pre = row.window_size;
826                    row.trim_to_window();
827                    evicted_bytes += pre - row.window_size;
828                }
829                super::strategy::BackendTag::HashChain => {
830                    // HC keeps bytes only in the contiguous `history` mirror
831                    // (no per-block Vecs to recycle since the window<->history
832                    // dedup), so derive the eviction count from the
833                    // `window_size` delta, mirroring the Dfast arm above.
834                    let table = &mut self.hc_matcher_mut().table;
835                    let pre = table.window_size;
836                    table.trim_to_window();
837                    evicted_bytes += pre - table.window_size;
838                }
839            }
840            if evicted_bytes == 0 {
841                break;
842            }
843            // The loop's invariant is "the backend's previous
844            // `max_window_size` shrink had downstream bytes left to
845            // evict" — that's what `evicted_bytes != 0` proves at
846            // this point. `dictionary_retained_budget` is NOT
847            // guaranteed to be positive here: the outer
848            // `retire_dictionary_budget` call may have already
849            // drained it to zero by reclaiming the last retained
850            // bytes, while the backend still has bytes above the
851            // freshly-shrunk window cap waiting for this loop to
852            // evict. The return value of the retire call below is
853            // therefore intentionally discarded — the loop's
854            // termination is driven by `evicted_bytes == 0`, not by
855            // whether the budget has more bytes left to reclaim.
856            let _ = self.retire_dictionary_budget(evicted_bytes);
857        }
858    }
859
860    /// ATTACH (`true`) vs COPY (`false`) decision for the dms-bearing HashChain
861    /// backend (lazy hash-chain AND binary-tree/optimal levels), mirroring
862    /// upstream `ZSTD_shouldAttachDict` and its per-strategy `attachDictSizeCutoffs`:
863    /// a small / unknown source ATTACHES the dict as a separate dms (hash-chain
864    /// dms for lazy, DUBT dms for BT); a large known source COPIES it into the
865    /// live chain / tree. The cutoff is the lazy/lazy2 value for HC, the
866    /// btlazy2/btopt value for Bt{Opt}, and the smaller btultra/btultra2 value for
867    /// the deepest parses. Both `skip_matching_for_dictionary_priming` (which
868    /// stages the dict) and `prime_with_dictionary` (which builds-or-drops the
869    /// dms) read this so the two stay in lock-step.
870    fn hc_dict_attach_mode(&self) -> bool {
871        // Only the HashChain backend (lazy hash-chain + BT/optimal) routes here;
872        // a non-HashChain storage has no dms decision, so default to attach.
873        let MatcherStorage::HashChain(hc) = &self.storage else {
874            return true;
875        };
876        let cutoff = if hc.table.uses_bt {
877            match hc.strategy_tag {
878                super::strategy::StrategyTag::BtUltra | super::strategy::StrategyTag::BtUltra2 => {
879                    BT_ULTRA_ATTACH_DICT_CUTOFF_LOG
880                }
881                _ => BT_OPT_ATTACH_DICT_CUTOFF_LOG,
882            }
883        } else {
884            HC_ATTACH_DICT_CUTOFF_LOG
885        };
886        self.reset_size_log.is_none_or(|log| log <= cutoff)
887    }
888
889    fn skip_matching_for_dictionary_priming(&mut self, dict_len: usize) {
890        match self.active_backend() {
891            super::strategy::BackendTag::Simple => {
892                // Upstream zstd `ZSTD_shouldAttachDict` mode selection for the Fast
893                // strategy (cutoff 8 KB): small / unknown-size inputs ATTACH
894                // (index dict positions into a SEPARATE immutable table; the
895                // dual-probe 2-cursor `compress_block_fast_dict` then prefers
896                // recent-input matches and falls back to the dict — the path
897                // that wins small/unknown). Large known-size inputs COPY (prime
898                // dict into the live table; the 4-cursor `compress_block_fast`
899                // matches against it as window history — the path that already
900                // matches/beats the upstream zstd on large corpora). The dispatch in
901                // `start_matching` keys off `dict_table.is_some()`, which only
902                // the attach path populates. See [`FAST_ATTACH_DICT_CUTOFF_LOG`].
903                let attach = self.reset_dict_attach_ok
904                    && self
905                        .reset_size_log
906                        .is_none_or(|log| log <= FAST_ATTACH_DICT_CUTOFF_LOG);
907                if attach {
908                    self.simple_mut().skip_matching_for_dict_prime(dict_len);
909                } else {
910                    self.simple_mut().skip_matching_with_hint(Some(false));
911                }
912                self.recycle_simple_space();
913            }
914            super::strategy::BackendTag::Dfast => {
915                // Upstream zstd `ZSTD_dictMatchState` mode selection for dfast (cutoff
916                // 16 KiB): small / unknown-size inputs ATTACH (build the
917                // separate immutable dict long+short tables; the dual-probe
918                // `start_matching_fast_loop` searches live + dict, the path that
919                // avoids the per-frame dict re-prime that dominates small
920                // `compress-dict`). Larger known-size inputs COPY (re-prime the
921                // dict into the live tables via `skip_matching_dense`, where the
922                // dense scan matches it as window history). `skip_matching_for_dict_attach`
923                // self-gates on `use_fast_loop` (only fast-loop levels carry the
924                // dual-probe; general-path levels fall back to the dense copy).
925                // The tagged dictionary slots index at most
926                // `DFAST_ATTACH_DICT_MAX_LEN` bytes; a larger dictionary is
927                // copied into the live tables instead.
928                let attach = dict_len <= crate::encoding::dfast::DFAST_ATTACH_DICT_MAX_LEN
929                    && self
930                        .reset_size_log
931                        .is_none_or(|log| log <= DFAST_ATTACH_DICT_CUTOFF_LOG);
932                if attach {
933                    self.dfast_matcher_mut().skip_matching_for_dict_attach();
934                } else {
935                    self.dfast_matcher_mut().invalidate_dict_cache();
936                    self.dfast_matcher_mut().skip_matching_dense();
937                }
938            }
939            super::strategy::BackendTag::Row => {
940                // Upstream zstd `ZSTD_RowFindBestMatch` `dictMatchState`: small /
941                // unknown-size inputs ATTACH (build the separate immutable dict
942                // row index; the bounded dual-probe in `row_candidate_rl`
943                // searches live + dict, avoiding the per-frame dict re-index),
944                // larger known-size inputs COPY (dense re-prime into the live
945                // rows).
946                // The attach / copy decision was made with the CDict's cParams
947                // at `reset` (`RowDictPlan`); the backend indexes the dictionary
948                // block accordingly.
949                self.row_matcher_mut().prime_dictionary_current_block();
950            }
951            super::strategy::BackendTag::HashChain => {
952                // Lazy-HC AND BT/optimal both follow upstream zstd `ZSTD_shouldAttachDict`
953                // per-strategy: ATTACH (a separate dms — hash-chain dms for lazy,
954                // DUBT dms for BT) for small / unknown inputs, COPY (merge the dict
955                // into the live chain/tree) for large known inputs. ATTACH keeps
956                // the dict in history but out of the live structure via
957                // `skip_matching_dict_bt` (the cursor advance is shared by both
958                // arms); COPY routes through the normal `skip_matching` (its
959                // `uses_bt` branch fills the live tree, the lazy branch the live
960                // chain). The dms is built-or-dropped to match in
961                // `prime_with_dictionary`.
962                if self.hc_dict_attach_mode() {
963                    self.hc_matcher_mut().table.skip_matching_dict_bt();
964                } else {
965                    self.hc_matcher_mut().skip_matching(Some(false));
966                }
967            }
968        }
969    }
970}
971
972impl Matcher for MatchGeneratorDriver {
973    fn supports_dictionary_priming(&self) -> bool {
974        true
975    }
976
977    fn set_source_size_hint(&mut self, size: u64) {
978        self.source_size_hint = Some(size);
979    }
980
981    fn set_dictionary_size_hint(&mut self, sizes: super::DictionarySizes) {
982        self.dictionary_size_hint = Some(sizes);
983    }
984
985    /// Dict-relevance gate for the raw-fast-path. Reached only when a dictionary
986    /// is active (the caller short-circuits on `dict_active`), so this answers
987    /// "could the dict compress this otherwise-incompressible-looking block?".
988    /// The Simple (Fast) backend samples its dict table precisely
989    /// ([`FastKernelMatcher::block_samples_match_dict`]); the other backends
990    /// (Dfast / Row / HashChain / BT) have their own dict structures and no cheap
991    /// probe here, so they answer CONSERVATIVELY `true`: without a probe they
992    /// cannot tell whether the dict compresses an incompressible-LOOKING block,
993    /// and answering `false` would let the raw-fast-path emit such a block raw
994    /// and miss an embedded dict segment. `dictionary_segment_in_incompressible_input_is_matched`
995    /// pins this for Dfast/Row/BT — the 512-byte dict run inside high-entropy
996    /// filler is matched only because these backends stay on the scan. So they
997    /// keep the blanket scan the old `!dict_active` gate gave them; only the
998    /// Simple/Fast backend trades it for the precise probe.
999    fn block_samples_match_dict(&self, block: &[u8]) -> bool {
1000        match &self.storage {
1001            MatcherStorage::Simple(m) => m.block_samples_match_dict(block),
1002            _ => true,
1003        }
1004    }
1005
1006    /// Heap bytes this driver owns: the active backend's tables/history, the
1007    /// recycled input-buffer pool, and the primed-dictionary snapshot (a cloned
1008    /// backend kept for CDict-equivalent reuse). The inline struct itself is
1009    /// accounted by the owner's `size_of`.
1010    fn heap_size(&self) -> usize {
1011        let pool: usize = self.vec_pool.capacity() * core::mem::size_of::<Vec<u8>>()
1012            + self.vec_pool.iter().map(Vec::capacity).sum::<usize>();
1013        let snapshot = self
1014            .primed
1015            .as_ref()
1016            .map_or(0, |(storage, _, _)| storage.heap_size());
1017        pool + self.storage.heap_size() + snapshot
1018    }
1019
1020    fn clear_param_overrides(&mut self) {
1021        self.param_overrides = None;
1022    }
1023
1024    fn reset(&mut self, level: CompressionLevel) {
1025        let hint = self.source_size_hint.take();
1026        // An empty dictionary is "no dictionary": it primes nothing, so every
1027        // dictionary-frame decision below must see `None` for it.
1028        let dict_hint = self
1029            .dictionary_size_hint
1030            .take()
1031            .filter(|sizes| sizes.content > 0);
1032        // Snapshot the hint's normalized ceil-log bucket for the primed-snapshot
1033        // key and prime_with_dictionary's attach/copy mode decision (the hint is
1034        // consumed here, but priming happens just after reset). Storing the
1035        // bucket rather than the raw bytes means two hints that resolve to the
1036        // same matcher shape share one snapshot instead of each re-priming.
1037        self.reset_size_log = hint.map(source_size_ceil_log);
1038        // A dictionary too large for the tagged attach position field falls back
1039        // to copy mode. Captured here (from the load-set size hint = actual dict
1040        // length) so the prime decision and the snapshot-key / epoch bits agree.
1041        self.reset_dict_attach_ok =
1042            dict_hint.is_none_or(|sizes| sizes.content <= MAX_FAST_ATTACH_DICT_REGION);
1043        let hinted = hint.is_some();
1044        // A dictionary frame takes its cParams and match-finder from the
1045        // CDict's cParams (upstream `ZSTD_resetCCtx_usingCDict`), whose tier
1046        // is keyed by the serialized dictionary size; a lazy-band CDict also
1047        // carries `dict_plan` to the Row backend.
1048        let (params, dict_plan) = match dict_hint {
1049            Some(sizes) => {
1050                crate::encoding::levels::config::resolve_level_params_with_dict(level, hint, sizes)
1051            }
1052            None => (Self::level_params(level, hint), None),
1053        };
1054        #[cfg_attr(not(test), allow(unused_mut))]
1055        let mut params = params;
1056        // Test-only: apply a parse×search override so the matrix can be
1057        // exercised without editing `LEVEL_TABLE`. Mutating `params` here
1058        // (before `next_backend`) flows the override through storage
1059        // selection, `configure`, and the `self.search`/`self.parse`
1060        // writes uniformly. Consumed with `take()` so it is one-shot: the
1061        // synthetic pairing applies to exactly this `reset()`, and a later
1062        // reset on the same driver falls back to the level's real config.
1063        #[cfg(test)]
1064        if let Some((search, parse)) = self.config_override.take() {
1065            params.search = search;
1066            params.lazy_depth = parse.lazy_depth();
1067            // The matrix sweep can pair a level with a backend its native
1068            // row doesn't populate (e.g. greedy L5, which carries only `row`,
1069            // run on HashChain). Synthesize a default config for the
1070            // overridden backend so its `configure` arm has something to read.
1071            use super::strategy::SearchMethod;
1072            match search {
1073                SearchMethod::Fast => {
1074                    params.fast.get_or_insert(FAST_L1);
1075                }
1076                SearchMethod::DoubleFast => {
1077                    params.dfast.get_or_insert(DFAST_L3);
1078                }
1079                SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
1080                    let row = params.row.get_or_insert(ROW_CONFIG);
1081                    row.bt = matches!(search, SearchMethod::BinaryTreeLazy);
1082                }
1083                SearchMethod::HashChain | SearchMethod::BinaryTree => {
1084                    params.hc.get_or_insert(HC_CONFIG);
1085                }
1086            }
1087        }
1088        // Public-parameter overrides (#27): apply the per-knob set on top
1089        // of the level-resolved params. A strategy override re-routes the
1090        // backend, so this must precede `next_backend` selection. The
1091        // all-`None` case is skipped so default level geometry stays
1092        // byte-identical to plain level-based compression.
1093        if let Some(ov) = self.param_overrides
1094            && !ov.is_empty()
1095            && dict_hint.is_some()
1096        {
1097            // A dictionary frame runs the CDict's cParams whatever its
1098            // strategy (upstream `ZSTD_resetCCtx_byAttachingCDict` /
1099            // `byCopyingCDict`: "cdict overrides"); only the caller's
1100            // windowLog is kept. Reshaping the live search would probe the
1101            // dictionary's tables with another geometry / key width than they
1102            // were indexed with.
1103            //
1104            // The window still answers to the source, as it does for every
1105            // other frame: `ZSTD_adjustCParams_internal` caps it by the source
1106            // and dictionary extent, and a window neither can fill only makes
1107            // decoders reserve memory the frame never uses. Capped here rather
1108            // than through the full adjuster, which would reshape the search.
1109            if let Some(window_log) = ov.window_log {
1110                params.window_log = match hint {
1111                    // The source caps the window even here, and even with an
1112                    // explicit request: the reference command declares 2 KiB
1113                    // for `--ultra -22 --long=27 -D dict` on a 2 KiB file, and
1114                    // a window the content cannot fill only makes every decoder
1115                    // reserve memory the frame never uses. The floor that
1116                    // travels with the cap in `adjust_cparams` applies too, or
1117                    // a hint of a few dozen bytes asks for a window smaller
1118                    // than the format's smallest.
1119                    //
1120                    // The dictionary's own size is NOT part of that cap: the
1121                    // reference declares the same 2 KiB whether the dictionary
1122                    // is 4 KiB or 256 KiB, because a small window does not put
1123                    // the dictionary out of reach — sequences may reference it
1124                    // at offsets beyond the window while the output so far is
1125                    // within it (RFC 8878, Dictionary_Content). Counting it
1126                    // made our frames ask decoders for up to 256x what the
1127                    // reference asks.
1128                    Some(src) => (crate::encoding::cparams::adjusted_window_log(
1129                        u32::from(window_log),
1130                        src,
1131                        0,
1132                    ) as u8)
1133                        .max(MIN_WINDOW_LOG),
1134                    None => window_log,
1135                };
1136            }
1137        } else if let Some(ov) = self.param_overrides
1138            && !ov.is_empty()
1139        {
1140            apply_param_overrides(&mut params, &ov);
1141            // `Self::level_params(level, hint)` applied the source-size cap
1142            // for the LEVEL's native backend. If a strategy override moved
1143            // the frame onto a different backend, `apply_param_overrides`
1144            // synthesized that backend's DEFAULT config (FAST_L1 /
1145            // HC_OVERRIDE_DEFAULT) with full-size table logs AFTER that cap
1146            // ran. Re-apply the hint cap so a tiny hinted frame doesn't
1147            // allocate the new backend's full-size tables.
1148            //
1149            // The cap covers an explicit `window_log` too, as
1150            // `ZSTD_adjustCParams_internal` does upstream: the window is a
1151            // promise about the memory decoding will need, and a source that
1152            // cannot fill it makes that promise for nothing — every decoder
1153            // opening the frame would reserve the whole declared window to
1154            // read a few bytes. The override still raises the window as far as
1155            // the source can use.
1156            if let Some(hint_size) = hint {
1157                params = adjust_params_for_source_size(params, hint_size);
1158            }
1159        }
1160        // A dictionary frame's hash-chain / binary-tree widths are the CDict's
1161        // (`resolve_level_params_with_dict`): verbatim when the dictionary is
1162        // copied into the live tables (`ZSTD_resetCCtx_byCopyingCDict` builds
1163        // the context from the CDict's cParams), re-adjusted to the source
1164        // alone when it is attached (`byAttachingCDict`: the live tables hold
1165        // no dictionary entry, the dms carries its own dict-sized tables), so
1166        // a small source under a large attached dictionary keeps small live
1167        // tables. Nothing re-sizes `params.hc` here.
1168        // Upstream `ZSTD_resolveRowMatchFinderMode` (zstd_compress.c:238): the
1169        // greedy/lazy/lazy2 band searches rows only above a 2^14 window and a
1170        // hash chain otherwise. The Row backend runs that switch itself
1171        // (`RowMatchGenerator::use_chain`), so both finders share ONE parse
1172        // (upstream's single `lazy_generic`) and the level stays on `RowHash`.
1173        let next_backend = params.backend();
1174        let max_window_size = 1usize << params.window_log;
1175        self.dictionary_retained_budget = 0;
1176        // Drop any frame-local borrowed staging so it can't leak across a
1177        // reset and misroute the next start/skip into borrowed dispatch.
1178        self.borrowed_pending = None;
1179        if self.active_backend() != next_backend {
1180            // Drain the outgoing backend's allocations into the shared
1181            // pool. The `match &mut self.storage { ... }` block runs to
1182            // completion before the assignment below replaces the
1183            // variant, so the inner state we just drained is dropped
1184            // with the old variant.
1185            match &mut self.storage {
1186                MatcherStorage::Simple(_m) => {
1187                    // FastKernelMatcher owns a flat Vec<u8> history
1188                    // and a Vec<u32> hash table — both drop with the
1189                    // variant assignment below, no per-block buffers
1190                    // to recycle into the driver pools. The
1191                    // assignment-replace path collapses to a noop
1192                    // pre-pass for this backend.
1193                }
1194                MatcherStorage::Dfast(m) => {
1195                    // Drop the long / short hash table allocations
1196                    // before calling `m.reset`. Without this prepass,
1197                    // `DfastMatchGenerator::reset` would `fill` both
1198                    // tables with `DFAST_EMPTY_SLOT` sentinels — wasted
1199                    // work given the next assignment to `self.storage`
1200                    // is about to drop `m` entirely. `reset` itself
1201                    // short-circuits on `if !self.tables.is_empty()`, so
1202                    // handing it an empty `Vec` skips the fill loop.
1203                    // Mirrors the pre-drain pattern in the HashChain
1204                    // arm below (and serves the same peak-memory
1205                    // purpose: release the table-allocation footprint
1206                    // before constructing the replacement variant).
1207                    m.tables = Vec::new();
1208                    m.reset();
1209                }
1210                MatcherStorage::Row(m) => {
1211                    // One buffer holds the positions and, in its byte tail,
1212                    // the cursors and tags — releasing it releases all three.
1213                    m.release_tables();
1214                    m.reset();
1215                }
1216                MatcherStorage::HashChain(m) => {
1217                    // Release oversized tables when switching away from
1218                    // HashChain so Best's larger allocations don't persist.
1219                    // hash3_table must be released alongside the other
1220                    // two: BtUltra2's `1 << HC3_HASH_LOG` entries would
1221                    // otherwise stay pinned across the backend switch,
1222                    // even though no future caller of this backend will
1223                    // touch them.
1224                    m.table.tables = Vec::new();
1225                    m.table.chain_off = 0;
1226                    m.table.hash3_off = 0;
1227                    let vec_pool = &mut self.vec_pool;
1228                    m.reset(|mut data| {
1229                        data.resize(data.capacity(), 0);
1230                        vec_pool.push(data);
1231                    });
1232                }
1233            }
1234            // Swap in a fresh variant for the new backend. The previous
1235            // `storage` is dropped here.
1236            self.storage = match next_backend {
1237                super::strategy::BackendTag::Simple => {
1238                    // Per-level Fast cParams from resolve_level_params:
1239                    // Level(1) gets (hash_log=14, mls=7); Level(-7..=-1)
1240                    // get upstream zstd row-0 (hash_log=13, mls=7); Fastest /
1241                    // Uncompressed keep (hash_log=14, mls=6). See
1242                    // resolve_level_params for rationale.
1243                    let fast = params.fast.expect("Fast level row carries a FastConfig");
1244                    MatcherStorage::Simple(FastKernelMatcher::with_params(
1245                        params.window_log,
1246                        fast.hash_log,
1247                        fast.mls,
1248                        fast.step_size,
1249                    ))
1250                }
1251                super::strategy::BackendTag::Dfast => {
1252                    MatcherStorage::Dfast(DfastMatchGenerator::new(max_window_size))
1253                }
1254                super::strategy::BackendTag::Row => {
1255                    MatcherStorage::Row(RowMatchGenerator::new(max_window_size))
1256                }
1257                super::strategy::BackendTag::HashChain => {
1258                    MatcherStorage::HashChain(HcMatchGenerator::new(max_window_size))
1259                }
1260            };
1261        }
1262
1263        // Single source of truth: `LevelParams::strategy_tag` is the
1264        // authoritative mapping from `CompressionLevel` to strategy.
1265        // `storage.backend()` derives the parse family from the variant,
1266        // so there is no separate runtime tag that could drift against
1267        // `LEVEL_TABLE`.
1268        self.strategy_tag = params.strategy_tag;
1269        self.search = params.search;
1270        self.parse = params.parse();
1271        self.slice_size = self.base_slice_size.min(max_window_size);
1272        self.reported_window_size = max_window_size;
1273        let strategy_tag = self.strategy_tag;
1274        // Source-proportional table window for the backends whose hash-table
1275        // widths are recomputed here (Dfast / Row). Like the HC / Fast caps
1276        // in `adjust_params_for_source_size`, this sizes the internal tables
1277        // from the RAW source log (not the wire `window_log` floor) so a
1278        // small frame zeroes a small table; it never exceeds the real window.
1279        let table_window_size = match hint {
1280            Some(h) => {
1281                let raw_log = source_size_ceil_log(h);
1282                // Clamp the shift below the pointer width before `1usize <<`:
1283                // an oversized hint (>= 2^63 + 1, and on 32-bit usize any hint
1284                // >= 2^32) drives `raw_log` to 64 / >= 32, and the shift would
1285                // overflow (panic in debug, wrap to 0 in release) before the
1286                // `.min(max_window_size)` cap below could bound it. The min cap
1287                // still provides the real semantic window bound.
1288                let shift = raw_log.max(MIN_WINDOW_LOG).min(usize::BITS as u8 - 1);
1289                (1usize << shift).min(max_window_size)
1290            }
1291            None => max_window_size,
1292        };
1293        // The hint-dependent hash-table width the active backend applies, for
1294        // the primed-snapshot key. Dfast/Row compute it from `table_window_size`
1295        // below; HC/Fast leave it `0` because their widths live in `params`
1296        // (`hc.{hash,chain}_log` / `fast_hash_log`) — already part of the key.
1297        let mut resolved_table_bits: usize = 0;
1298        match &mut self.storage {
1299            MatcherStorage::Simple(m) => {
1300                // Per-level Fast cParams threaded from
1301                // resolve_level_params (see Simple-backend swap
1302                // arm above for the (level → params) mapping).
1303                let fast = params.fast.expect("Fast level row carries a FastConfig");
1304                // Same attach/copy split the dict-prime dispatch applies
1305                // below (`prime_with_dictionary`): only attach-mode dict
1306                // frames may keep the main table across the reset via an
1307                // epoch advance — copy-mode and no-dict frames must memset
1308                // it back to bias 0 for the raw-slice kernels.
1309                let dict_attach_epoch = dict_hint.is_some()
1310                    && self.reset_dict_attach_ok
1311                    && self
1312                        .reset_size_log
1313                        .is_none_or(|log| log <= FAST_ATTACH_DICT_CUTOFF_LOG);
1314                // Copy-mode dictionary frame whose primed snapshot matches
1315                // this exact resolved shape: `restore_primed_dictionary`
1316                // (called right after this reset; the caller gates the
1317                // restore on the same size bucket and the restore re-checks
1318                // the same key) will `clone_from` the snapshot over this
1319                // matcher, replacing the table contents and bias wholesale —
1320                // the reset's full-table memset would be thrown away. The
1321                // key components mirror `reset_shape` below: Simple leaves
1322                // `resolved_table_bits` 0, never carries an LDM override,
1323                // and `fast_attach` is false in copy mode by construction.
1324                let table_overwritten_by_restore = dict_hint.is_some()
1325                    && !dict_attach_epoch
1326                    && self.primed.as_ref().is_some_and(|(_, _, captured)| {
1327                        *captured
1328                            == PrimedKey {
1329                                level,
1330                                params,
1331                                table_bits: 0,
1332                                fast_attach: false,
1333                                ldm: None,
1334                            }
1335                    });
1336                // Cap `hash_log <= window_log + 1` (upstream zstd
1337                // `ZSTD_adjustCParams_internal`): once `window_log` is resized
1338                // down for a small source, a level-default `1 << hash_log`
1339                // table is mostly wasted address space whose per-frame memset
1340                // dominates the compress cost on tiny frames (a 4 KB frame at
1341                // window_log 12 still zero-fills the 64 KiB hash_log-14 table).
1342                // Gated to no-dict frames: the dict-attach path shares one
1343                // hash_log between the main and dict tables (so one hash keys
1344                // both), and shrinking only the main table would break that
1345                // invariant and the small-frame dict ratio.
1346                let hash_log = if dict_hint.is_some() {
1347                    fast.hash_log
1348                } else {
1349                    fast.hash_log.min(params.window_log as u32 + 1)
1350                };
1351                // The attached dictionary table takes the CDict's `hashLog`
1352                // (upstream `ZSTD_createCDict`: `ZSTD_getCParams(level,
1353                // UNKNOWN, dictSize)` adjusted for a `minSrcSize` source), not
1354                // the source-capped main width: a small source must not
1355                // shrink the table a large dictionary was sized for.
1356                m.set_dict_table_hash_log(dict_hint.map(|sizes| {
1357                    crate::encoding::cparams::get_cdict_cparams(
1358                        crate::encoding::levels::config::numeric_level(level),
1359                        sizes.serialized,
1360                    )
1361                    .hash_log
1362                }));
1363                m.reset(
1364                    params.window_log,
1365                    hash_log,
1366                    fast.mls,
1367                    fast.step_size,
1368                    dict_attach_epoch,
1369                    table_overwritten_by_restore,
1370                );
1371            }
1372            MatcherStorage::Dfast(dfast) => {
1373                dfast.max_window_size = max_window_size;
1374                let dcfg = params
1375                    .dfast
1376                    .expect("Dfast level row must carry a DfastConfig");
1377                // Upstream zstd `cParams.hashLog`/`chainLog`, capped by the
1378                // source-size window when hinted so tiny inputs don't
1379                // over-allocate.
1380                let long_bits = if hinted {
1381                    dfast_hash_bits_for_window(table_window_size).min(dcfg.long_hash_log as usize)
1382                } else {
1383                    dcfg.long_hash_log as usize
1384                };
1385                let short_bits = if hinted {
1386                    dfast_hash_bits_for_window(table_window_size).min(dcfg.short_hash_log as usize)
1387                } else {
1388                    dcfg.short_hash_log as usize
1389                };
1390                resolved_table_bits = long_bits;
1391                dfast.set_hash_bits(long_bits, short_bits);
1392                // The attached dictionary tables take the CDict's geometry
1393                // (upstream hashes the dictMatchState tables with
1394                // `dictCParams`), not the source-capped live widths.
1395                dfast.set_dict_table_bits(dict_hint.map(|sizes| {
1396                    let cd = crate::encoding::cparams::get_cdict_cparams(
1397                        crate::encoding::levels::config::numeric_level(level),
1398                        sizes.serialized,
1399                    );
1400                    (cd.hash_log as usize, cd.chain_log as usize)
1401                }));
1402                // A copy-mode frame (source past the attach cutoff, or a
1403                // dictionary too large to tag) merges the dictionary into the
1404                // live tables; a resident attach-mode table must not be
1405                // re-borrowed under it (same decision as the prime dispatch).
1406                // The width-change invalidation in `set_hash_bits` does not
1407                // cover an unhinted attach frame followed by a large hinted
1408                // one whose live widths coincide at the level's full widths.
1409                let dfast_attach_next = dict_hint.is_some_and(|sizes| {
1410                    sizes.content <= crate::encoding::dfast::DFAST_ATTACH_DICT_MAX_LEN
1411                }) && self
1412                    .reset_size_log
1413                    .is_none_or(|log| log <= DFAST_ATTACH_DICT_CUTOFF_LOG);
1414                if dict_hint.is_some() && !dfast_attach_next {
1415                    dfast.invalidate_dict_cache();
1416                }
1417                // Dfast holds no per-block input Vecs (history owns the
1418                // bytes and `add_data` returns each Vec eagerly), so
1419                // `reset` takes no `reuse_space` callback.
1420                dfast.reset();
1421            }
1422            MatcherStorage::Row(row) => {
1423                row.max_window_size = max_window_size;
1424                row.lazy_depth = params.lazy_depth;
1425                row.set_dict_plan(dict_plan);
1426                let mut row_cfg = params.row.expect("Row level row carries a RowConfig");
1427                // A dictionary frame's widths already come from the CDict's
1428                // cParams (adjusted to the source when attached); only a plain
1429                // hinted frame caps them by the window here.
1430                if hinted && dict_plan.is_none() {
1431                    // Clamp the configured hash width by the hinted window
1432                    // (upstream zstd `ZSTD_adjustCParams` caps hashLog by windowLog) —
1433                    // `min`, not replace, so an explicit `hash_log` param
1434                    // override (`row_cfg.hash_bits`) survives the hinted path
1435                    // instead of being overwritten by the window value.
1436                    //
1437                    // Clamp BEFORE `configure` so the backend sees ONE width
1438                    // per frame. Configuring with the unclamped level width
1439                    // and then re-clamping made `row_hash_log` oscillate on
1440                    // every hinted frame, and each width change clears the
1441                    // row tables — `ensure_tables` then re-filled all three
1442                    // every frame in a reused compressor.
1443                    row_cfg.hash_bits = row_cfg
1444                        .hash_bits
1445                        .min(row_hash_bits_for_window(table_window_size));
1446                }
1447                row.configure(row_cfg);
1448                // Key the primed snapshot on the width the backend ACTUALLY
1449                // applied (`set_hash_bits` clamps the request): recording the
1450                // request — or the 0 default on the unhinted path — keys
1451                // identical table geometries apart and forces needless
1452                // dictionary re-primes.
1453                resolved_table_bits = row.hash_bits();
1454                row.reset();
1455            }
1456            MatcherStorage::HashChain(hc) => {
1457                hc.table.max_window_size = max_window_size;
1458                hc.hc.lazy_depth = params.lazy_depth;
1459                let mut hc_cfg = params.hc.expect("HashChain level row carries an HcConfig");
1460                // Cap the hash / chain table logs by the hinted window so a small
1461                // input doesn't allocate the full level's tables (the upstream zstd
1462                // `ZSTD_adjustCParams_internal` clamp: `hashLog <= windowLog + 1`,
1463                // and `cycleLog <= windowLog` — `cycleLog == chainLog` for the HC
1464                // finder, `chainLog - 1` for the BT pair table, so `chainLog <=
1465                // windowLog` (+1 for BT)). Ratio-neutral: a hinted window of
1466                // `2^wlog` bytes holds at most `2^wlog` positions, so the slots
1467                // beyond that are never populated — capping only sheds unused
1468                // allocation. Was the source of L10-lazy peak-alloc ~2.15x the
1469                // upstream zstd on a 1 MiB input. Only applied when hinted; an
1470                // unknown-size stream keeps the full level tables.
1471                // Skip for dictionary frames: their `hc_cfg.{hash,chain}_log`
1472                // are the CDict's (verbatim when the dictionary is copied
1473                // into the live tables, source-adjusted when it is attached);
1474                // re-applying the source-window cap would collapse a copied
1475                // dictionary's tables to the small hinted source.
1476                if hinted && dict_hint.is_none() {
1477                    let wlog = hc_hash_bits_for_window(table_window_size);
1478                    let uses_bt = matches!(
1479                        strategy_tag,
1480                        super::strategy::StrategyTag::Btlazy2
1481                            | super::strategy::StrategyTag::BtOpt
1482                            | super::strategy::StrategyTag::BtUltra
1483                            | super::strategy::StrategyTag::BtUltra2
1484                    );
1485                    hc_cfg.hash_log = hc_cfg.hash_log.min(wlog + 1);
1486                    hc_cfg.chain_log = hc_cfg.chain_log.min(if uses_bt { wlog + 1 } else { wlog });
1487                }
1488                hc.configure(hc_cfg, strategy_tag, params.window_log);
1489                let vec_pool = &mut self.vec_pool;
1490                hc.reset(|mut data| {
1491                    data.resize(data.capacity(), 0);
1492                    vec_pool.push(data);
1493                });
1494                // When the source size is known, pre-size the history mirror to
1495                // the expected total (dictionary + payload) so per-block growth
1496                // does not overshoot via Vec capacity doubling (upstream zstd sizes its
1497                // window buffer exactly). Dominates peak once the match-finder
1498                // tables are dictionary-tier-small. Unhinted streams skip this
1499                // and keep doubling growth.
1500                if let Some(src) = hint {
1501                    // `src` is a u64 hint and may be the u64::MAX "unknown
1502                    // size" sentinel, which truncates under `as usize` on
1503                    // 32-bit targets and overflows when the dict hint is
1504                    // added. Saturate the source size, then saturate the
1505                    // dict-hint addition; `reserve_history` applies the
1506                    // tighter window ceiling to the result.
1507                    let src_hint = usize::try_from(src).unwrap_or(usize::MAX);
1508                    let expected =
1509                        src_hint.saturating_add(dict_hint.map_or(0, |sizes| sizes.content));
1510                    hc.table.reserve_history(expected);
1511                }
1512            }
1513        }
1514        // LDM wiring (#27): attach (or clear) the long-distance-match
1515        // producer on the optimal (BT) backend. LDM is the only
1516        // back-reference path that crosses the regular window, so it
1517        // only has a home on the `BtMatcher`; non-BT strategies drop the
1518        // producer. Built AFTER `hc.reset()` because `BtMatcher::reset`
1519        // clears an existing producer's table but does not null the
1520        // slot — installing here gives the new frame a fresh producer.
1521        #[cfg(feature = "ldm")]
1522        {
1523            // Resolve the derived LDM params first (immutable borrow of the
1524            // overrides), then reuse the existing producer's allocation below.
1525            let derived_ldm = self
1526                .param_overrides
1527                .as_ref()
1528                .and_then(|ov| ov.ldm)
1529                .map(|ldm_ov| {
1530                    let strategy_ord = ldm_strategy_ordinal(params.strategy_tag, params.lazy_depth);
1531                    // Seed the caller-pinned knobs, then run the upstream zstd
1532                    // derivation over the seed so the remaining (zero)
1533                    // fields are filled with cross-field consistency
1534                    // (e.g. `hash_rate_log = window_log - hash_log`).
1535                    // Clobbering after `adjust_for` would break that and
1536                    // hand the producer an inconsistent set.
1537                    let seed = super::ldm::params::LdmParams {
1538                        window_log: params.window_log as u32,
1539                        hash_log: ldm_ov.hash_log.unwrap_or(0),
1540                        hash_rate_log: ldm_ov.hash_rate_log.unwrap_or(0),
1541                        min_match_length: ldm_ov.min_match.unwrap_or(0),
1542                        bucket_size_log: ldm_ov.bucket_size_log.unwrap_or(0),
1543                    };
1544                    seed.derive(strategy_ord)
1545                });
1546            if let MatcherStorage::HashChain(hc) = &mut self.storage {
1547                // Reuse the existing producer's hash-table allocation when the
1548                // derived params are unchanged: only `clear()` (re-zero the
1549                // table + re-seed the rolling hash, no allocation) is needed for
1550                // the new frame. A params change (or the first frame) forces a
1551                // fresh `LdmProducer::new`. On the reused-encoder compress-dict
1552                // path this avoids re-allocating the LDM hash table (large at
1553                // btultra2) every frame — upstream zstd reuses its `ldmState_t`
1554                // the same way. `clear()` is mandatory here for correctness
1555                // regardless of what `BtMatcher::reset` did to the old table.
1556                let producer = derived_ldm.map(|p| match hc.take_ldm_producer() {
1557                    Some(mut existing) if existing.params() == p => {
1558                        existing.clear();
1559                        existing
1560                    }
1561                    _ => super::ldm::LdmProducer::new(p),
1562                });
1563                hc.set_ldm_producer(producer);
1564            }
1565        }
1566        // Record the resolved matcher shape for the primed-snapshot key. Captured
1567        // here (post-resolution, after the test-only param override) so the key
1568        // reflects exactly the geometry the restored `storage` must match. The
1569        // Fast attach-vs-copy mode is part of the shape ONLY for the Simple
1570        // backend (it decides the distinct dict-table shape that backend builds).
1571        // Dfast/Row/HashChain have their OWN attach/copy regimes, but this bit
1572        // models only the Fast table split; those backends are keyed by the
1573        // resolved matcher geometry instead, so folding the Fast bit into their
1574        // key would over-key identical resolved shapes. When it applies it
1575        // matches the decision `prime_with_dictionary` makes from the same
1576        // `reset_size_log`.
1577        let fast_attach = matches!(next_backend, super::strategy::BackendTag::Simple)
1578            && self.reset_dict_attach_ok
1579            && self
1580                .reset_size_log
1581                .is_none_or(|log| log <= FAST_ATTACH_DICT_CUTOFF_LOG);
1582        // The LDM override is part of the snapshot identity ONLY on the
1583        // optimal (BinaryTree) path: that is the only backend whose cloned
1584        // `storage` carries a `BtMatcher::ldm_producer`. On Fast / Dfast /
1585        // Row and lazy-HashChain resets the producer slot does not exist,
1586        // so folding the override there would over-key the snapshot and
1587        // force needless re-primes when LDM is toggled. Gated like
1588        // `fast_attach` (a key bit only participates where it changes the
1589        // cloned matcher shape).
1590        let active_ldm = if matches!(params.search, super::strategy::SearchMethod::BinaryTree) {
1591            self.param_overrides.and_then(|ov| ov.ldm)
1592        } else {
1593            None
1594        };
1595        self.reset_shape = Some((params, resolved_table_bits, fast_attach, active_ldm));
1596    }
1597
1598    // Dictionary entry points forward to the `dict_prime` child module, which
1599    // owns the prime / snapshot lifecycle (it reaches the driver's private
1600    // `primed` / `reset_shape` state directly as a descendant module).
1601
1602    #[inline]
1603    fn dictionary_is_resident(&self) -> bool {
1604        self.dictionary_is_resident_impl()
1605    }
1606
1607    #[inline]
1608    fn reapply_resident_dictionary(&mut self, offset_hist: [u32; 3]) {
1609        self.reapply_resident_dictionary_impl(offset_hist)
1610    }
1611
1612    #[inline]
1613    fn prime_with_dictionary(&mut self, dict_content: &[u8], offset_hist: [u32; 3]) {
1614        self.prime_with_dictionary_impl(dict_content, offset_hist)
1615    }
1616
1617    #[inline]
1618    fn restore_primed_dictionary(&mut self, level: super::CompressionLevel) -> bool {
1619        self.restore_primed_dictionary_impl(level)
1620    }
1621
1622    #[inline]
1623    fn capture_primed_dictionary(&mut self, level: super::CompressionLevel) {
1624        self.capture_primed_dictionary_impl(level)
1625    }
1626
1627    #[inline]
1628    fn invalidate_primed_dictionary(&mut self) {
1629        self.invalidate_primed_dictionary_impl()
1630    }
1631
1632    #[inline]
1633    fn seed_dictionary_entropy(
1634        &mut self,
1635        huff: Option<&crate::huff0::huff0_encoder::HuffmanTable>,
1636        ll: Option<&crate::fse::fse_encoder::FSETable>,
1637        ml: Option<&crate::fse::fse_encoder::FSETable>,
1638        of: Option<&crate::fse::fse_encoder::FSETable>,
1639    ) {
1640        self.seed_dictionary_entropy_impl(huff, ll, ml, of)
1641    }
1642
1643    fn window_size(&self) -> u64 {
1644        self.reported_window_size as u64
1645    }
1646
1647    fn get_next_space(&mut self) -> Vec<u8> {
1648        if let Some(mut space) = self.vec_pool.pop() {
1649            if space.len() > self.slice_size {
1650                space.truncate(self.slice_size);
1651            }
1652            if space.len() < self.slice_size {
1653                space.resize(self.slice_size, 0);
1654            }
1655            return space;
1656        }
1657        alloc::vec![0; self.slice_size]
1658    }
1659
1660    fn get_last_space(&mut self) -> &[u8] {
1661        match &self.storage {
1662            MatcherStorage::Simple(m) => m.last_committed_space(),
1663            MatcherStorage::Dfast(m) => m.get_last_space(),
1664            MatcherStorage::Row(m) => m.get_last_space(),
1665            MatcherStorage::HashChain(m) => m.table.get_last_space(),
1666        }
1667    }
1668
1669    /// Read the next block STRAIGHT into the backend's history buffer, so the
1670    /// owned block loop does not stage it in a scratch `Vec` and copy it in.
1671    ///
1672    /// Returns `None` when the active backend has no in-place ingest, in which
1673    /// case the caller keeps the staged-copy path. Dfast, Row and HashChain
1674    /// implement it; Simple stages the block in a `pending` slot that the
1675    /// kernel consumes, so its bytes do not reach `history` until match time
1676    /// and the two-phase shape does not apply to it as written.
1677    ///
1678    /// On `Some`, the bytes are in the buffer but not yet part of the window:
1679    /// the caller picks the block boundary from
1680    /// [`Self::uncommitted_input`] and then calls [`Self::commit_filled`].
1681    fn fill_in_place(
1682        &mut self,
1683        capacity: usize,
1684        fill: &mut dyn FnMut(&mut Vec<u8>) -> (usize, bool),
1685    ) -> Option<(usize, bool)> {
1686        match &mut self.storage {
1687            MatcherStorage::Dfast(m) => Some(m.fill_uncommitted(capacity, fill)),
1688            MatcherStorage::Row(m) => Some(m.fill_uncommitted(capacity, fill)),
1689            MatcherStorage::HashChain(m) => Some(m.table.fill_uncommitted(capacity, fill)),
1690            MatcherStorage::Simple(_) => None,
1691        }
1692    }
1693
1694    fn reserve_for_frame(&mut self, bytes: usize) {
1695        match &mut self.storage {
1696            MatcherStorage::Dfast(m) => m.reserve_for_frame(bytes),
1697            MatcherStorage::Row(m) => m.reserve_for_frame(bytes),
1698            MatcherStorage::HashChain(m) => m.table.reserve_for_frame(bytes),
1699            MatcherStorage::Simple(m) => m.reserve_for_frame(bytes),
1700        }
1701    }
1702
1703    /// Bytes read by [`Self::fill_in_place`] that no block has claimed yet.
1704    fn uncommitted_input(&self) -> &[u8] {
1705        match &self.storage {
1706            MatcherStorage::Dfast(m) => m.uncommitted(),
1707            MatcherStorage::Row(m) => m.uncommitted(),
1708            MatcherStorage::HashChain(m) => m.table.uncommitted(),
1709            MatcherStorage::Simple(_) => &[],
1710        }
1711    }
1712
1713    /// Claim `len` bytes of [`Self::uncommitted_input`] as the next block.
1714    ///
1715    /// Runs the same eviction accounting as [`Self::commit_space`]: a
1716    /// dictionary inflates `max_window_size` so the primed bytes stay
1717    /// reachable, and once eviction carries them out of the window that
1718    /// inflation has to be retired. Skipping it leaves the backend admitting
1719    /// matches older than the window the frame header reports, which encodes
1720    /// an offset no decoder can resolve.
1721    fn commit_filled(&mut self, len: usize) {
1722        // Same derivation as `commit_space`: the eviction loop decrements
1723        // `window_size` per evicted block before the commit adds `len`, so
1724        // `evicted = pre + len - post`.
1725        let pre = match &self.storage {
1726            MatcherStorage::Dfast(m) => m.window_size,
1727            MatcherStorage::Row(m) => m.window_size,
1728            MatcherStorage::HashChain(m) => m.table.window_size,
1729            MatcherStorage::Simple(_) => 0,
1730        };
1731        match &mut self.storage {
1732            MatcherStorage::Dfast(m) => m.commit_block(len),
1733            MatcherStorage::Row(m) => m.commit_block(len),
1734            MatcherStorage::HashChain(m) => m.table.commit_block(len),
1735            MatcherStorage::Simple(_) => return,
1736        }
1737        let post = match &self.storage {
1738            MatcherStorage::Dfast(m) => m.window_size,
1739            MatcherStorage::Row(m) => m.window_size,
1740            MatcherStorage::HashChain(m) => m.table.window_size,
1741            MatcherStorage::Simple(_) => 0,
1742        };
1743        // `saturating_sub` floors the no-eviction case at 0; `pre + len` are
1744        // byte counts bounded by the window, so the sum cannot overflow.
1745        let evicted_bytes = (pre + len).saturating_sub(post);
1746        if self.retire_dictionary_budget(evicted_bytes) {
1747            self.trim_after_budget_retire();
1748        }
1749    }
1750
1751    fn commit_space(&mut self, space: Vec<u8>) {
1752        let mut evicted_bytes = 0usize;
1753        // Split borrows manually so the `add_data` closures can write
1754        // into `vec_pool` while the backend itself holds an exclusive
1755        // borrow via `storage`. (Suffix-store recycling went away
1756        // with the legacy `MatchGenerator`; the FastKernelMatcher
1757        // arm below has no pool interaction.)
1758        let vec_pool = &mut self.vec_pool;
1759        match &mut self.storage {
1760            MatcherStorage::Simple(m) => {
1761                // FastKernelMatcher owns its history as a single
1762                // flat Vec<u8> and the hash table as a Vec<u32> —
1763                // neither recycles into the driver-side pools. The
1764                // eager pre-commit eviction inside
1765                // `FastKernelMatcher::accept_data` drops bytes when
1766                // accepting this block would push history past 2×
1767                // max_window_size; that delta is what feeds
1768                // `evicted_bytes` here via the `pre / post`
1769                // history-length comparison.
1770                let pre = m.history_len_for_eviction_accounting();
1771                m.accept_data(space);
1772                let post = m.history_len_for_eviction_accounting();
1773                // `accept_data` performs eager pre-commit window
1774                // eviction (so this `pre - post` delta correctly
1775                // feeds the dictionary-budget retire flow). See
1776                // `FastKernelMatcher::accept_data` for the
1777                // commit-time-visibility rationale (closes #216
1778                // CodeRabbit review #5 / Copilot review #1: without
1779                // eager eviction, the delta was always 0 and the
1780                // dict budget never retired, leaving max_window_size
1781                // inflated post-dict-prime → matcher could emit
1782                // offsets exceeding the frame header's window).
1783                evicted_bytes += pre.saturating_sub(post);
1784            }
1785            MatcherStorage::Dfast(m) => {
1786                // Dfast's `add_data` callback receives the INPUT
1787                // `Vec<u8>` for pool recycling (Dfast stores its
1788                // bytes in the contiguous `history` buffer, not in
1789                // per-block Vecs — there is no per-block buffer to
1790                // pop off and hand back). Counting `data.len()` as
1791                // evicted bytes would conflate "new bytes ingested"
1792                // with "old bytes evicted from window"; the two
1793                // happen to coincide when the previous window was
1794                // saturated and the new input fills it 1:1, but
1795                // diverge when the eviction pop-loop drops blocks
1796                // of a different size than the incoming input. The
1797                // `dictionary_retained_budget` retire decision
1798                // downstream then gets driven by inflated eviction
1799                // counts and shrinks `max_window_size` prematurely.
1800                //
1801                // Derive the real eviction delta from `window_size`
1802                // before/after the call. The pop loop inside
1803                // `add_data` decrements `window_size` by each
1804                // evicted block length and then the final
1805                // `extend_from_slice + push_back` adds `space_len`,
1806                // so `evicted = pre + space_len - post`.
1807                let pre = m.window_size;
1808                let space_len = space.len();
1809                m.add_data(space, |data| {
1810                    // Same per-block recycle as the HashChain arm: push
1811                    // the spent input buffer back as-is rather than
1812                    // zero-filling to capacity. `add_data` mirrors the
1813                    // bytes into `history` and calls this every block, so
1814                    // capacity-wide zeroing would be hot-path waste;
1815                    // `get_next_space` zeroes at most `slice_size` bytes
1816                    // when it later reuses the buffer.
1817                    vec_pool.push(data);
1818                });
1819                // Plain `+` (the `saturating_sub` floors at 0): `pre` + one
1820                // block are byte counts bounded by the window, no overflow.
1821                evicted_bytes += (pre + space_len).saturating_sub(m.window_size);
1822            }
1823            MatcherStorage::Row(m) => {
1824                // RowMatchGenerator::add_data recycles the *input* buffer
1825                // through this callback every commit (its bytes are mirrored
1826                // into `history`), not the evicted chunks. Derive the eviction
1827                // delta from `window_size` before/after — `evicted = pre +
1828                // space_len - post` — exactly like the Simple / HashChain arms.
1829                // Counting the callback argument as evicted would charge the
1830                // whole committed block as evicted and prematurely retire
1831                // dictionary budget on a window that evicts nothing.
1832                let pre = m.window_size;
1833                let space_len = space.len();
1834                m.add_data(space, |data| {
1835                    // Recycle the spent buffer as-is; `add_data` runs this for
1836                    // every committed block, so zero-filling to capacity here
1837                    // would be hot-path waste (`get_next_space` zeroes at most
1838                    // `slice_size` on reuse).
1839                    vec_pool.push(data);
1840                });
1841                // Plain `+` (the `saturating_sub` floors at 0): `pre` + one
1842                // block are byte counts bounded by the window, no overflow.
1843                evicted_bytes += (pre + space_len).saturating_sub(m.window_size);
1844            }
1845            MatcherStorage::HashChain(m) => {
1846                // MatchTable::add_data now recycles the *incoming* buffer
1847                // through `reuse_space` (its bytes are copied into the
1848                // contiguous `history` mirror), so the callback no longer
1849                // reports evicted chunks. Derive the eviction delta from
1850                // `window_size` before/after, exactly like the Simple arm:
1851                // `evicted = pre + space_len - post`.
1852                let pre = m.table.window_size;
1853                let space_len = space.len();
1854                m.table.add_data(space, |data| {
1855                    // Recycle the spent input buffer to the pool as-is.
1856                    // `add_data` runs this callback for every committed
1857                    // block (the bytes are mirrored into `history`), so
1858                    // growing the buffer to its full capacity here would
1859                    // zero the whole allocation on the hot path.
1860                    // `get_next_space` resizes a popped buffer to
1861                    // `slice_size` on demand, touching at most
1862                    // `slice_size` bytes — never the larger capacity the
1863                    // pool retains.
1864                    vec_pool.push(data);
1865                });
1866                // Plain `+` (the `saturating_sub` floors at 0): byte counts
1867                // bounded by the window, no overflow.
1868                evicted_bytes += (pre + space_len).saturating_sub(m.table.window_size);
1869            }
1870        }
1871        // Gate the second backend trim pass on actual budget
1872        // reclamation. Without it, every slice commit on the
1873        // no-dictionary / no-eviction path (the common case) would
1874        // run a backend `match` ladder + `trim_to_window` early-out
1875        // for no reason — `trim_after_budget_retire` only does
1876        // meaningful work when `retire_dictionary_budget` shrank
1877        // `max_window_size` enough to make the backend's
1878        // `window_size > max_window_size` invariant trigger
1879        // eviction.
1880        if self.retire_dictionary_budget(evicted_bytes) {
1881            self.trim_after_budget_retire();
1882        }
1883    }
1884
1885    fn start_matching(&mut self, mut handle_sequence: impl for<'a> FnMut(Sequence<'a>)) {
1886        use super::strategy::{self, StrategyTag};
1887        // Borrowed one-shot Fast path: if the frame driver staged a
1888        // block range via `set_borrowed_block`, scan it in place against
1889        // the borrowed window instead of the owned committed block. Only
1890        // the Simple backend is instrumented (the gate guarantees it),
1891        // and the stage is consumed so the next block re-stages.
1892        if let Some((block_start, block_end)) = self.borrowed_pending.take() {
1893            match self.active_backend() {
1894                super::strategy::BackendTag::Simple => {
1895                    let m = self.simple_mut();
1896                    if m.dict_is_attached() {
1897                        // Dict-attach borrowed scan: live matches read the
1898                        // borrowed input in place, dict matches read the
1899                        // committed dict prefix via the 2-segment counter.
1900                        m.start_matching_borrowed_dict(
1901                            block_start,
1902                            block_end,
1903                            &mut handle_sequence,
1904                        );
1905                    } else {
1906                        m.start_matching_borrowed(block_start, block_end, &mut handle_sequence);
1907                    }
1908                }
1909                super::strategy::BackendTag::Dfast => self
1910                    .dfast_matcher_mut()
1911                    .start_matching_borrowed(block_start, block_end, &mut handle_sequence),
1912                super::strategy::BackendTag::Row => {
1913                    // Same greedy/lazy parse split as the owned RowHash arm.
1914                    let greedy = self.parse == super::strategy::ParseMode::Greedy;
1915                    self.row_matcher_mut().start_matching_borrowed(
1916                        block_start,
1917                        block_end,
1918                        greedy,
1919                        &mut handle_sequence,
1920                    );
1921                }
1922                super::strategy::BackendTag::HashChain => match self.search {
1923                    super::strategy::SearchMethod::HashChain => self
1924                        .hc_matcher_mut()
1925                        .start_matching_lazy_borrowed(block_start, block_end, &mut handle_sequence),
1926                    // `borrowed_supported()` keeps the optimal parsers on the
1927                    // owned path and `set_borrowed_block` asserts it.
1928                    other => {
1929                        unreachable!("HashChain backend with unexpected borrowed search {other:?}")
1930                    }
1931                },
1932            }
1933            return;
1934        }
1935        // Decoupled parse×search dispatch (fires once per block). The
1936        // search axis (`self.search`) picks the candidate-finding backend;
1937        // the parse axis (greedy vs lazy depth) is carried by the
1938        // backend's runtime `lazy_depth`, set per level at `reset()`.
1939        // The two are independent, so any parse can run on any search
1940        // backend. The `BinaryTree` arm still selects the opt `Strategy`
1941        // ZST off `strategy_tag` so `compress_block::<S>` keeps its
1942        // const-folded optimal-parser monomorphisation.
1943        use super::strategy::SearchMethod;
1944        match self.search {
1945            SearchMethod::Fast => {
1946                self.simple_mut().start_matching(&mut handle_sequence);
1947                self.recycle_simple_space();
1948            }
1949            SearchMethod::DoubleFast => {
1950                self.dfast_matcher_mut()
1951                    .start_matching(&mut handle_sequence);
1952            }
1953            SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
1954                // One upstream `lazy_generic` body for greedy (depth 0: a
1955                // repcode hit is stored without a search, no lookahead), lazy
1956                // / lazy2 (`lazy_depth` 1 / 2) and btlazy2 (depth 2 over the
1957                // binary-tree finder); the finder (rows / chain / tree) was
1958                // resolved at `configure`.
1959                self.row_matcher_mut().start_matching(&mut handle_sequence);
1960            }
1961            SearchMethod::HashChain => {
1962                // Greedy/lazy/lazy2 all flow through the lazy parser; it
1963                // reads `hc.lazy_depth` (0 = greedy commit).
1964                self.hc_matcher_mut()
1965                    .start_matching_lazy(&mut handle_sequence);
1966            }
1967            SearchMethod::BinaryTree => match self.strategy_tag {
1968                StrategyTag::BtOpt => self.compress_block::<strategy::BtOpt>(&mut handle_sequence),
1969                StrategyTag::BtUltra => {
1970                    self.compress_block::<strategy::BtUltra>(&mut handle_sequence)
1971                }
1972                StrategyTag::BtUltra2 => {
1973                    self.compress_block::<strategy::BtUltra2>(&mut handle_sequence)
1974                }
1975                _ => unreachable!(
1976                    "SearchMethod::BinaryTree requires an optimal strategy tag (BtOpt/BtUltra/BtUltra2)"
1977                ),
1978            },
1979        }
1980    }
1981
1982    fn skip_matching(&mut self) {
1983        self.skip_matching_with_hint(None);
1984    }
1985
1986    fn skip_matching_with_hint(&mut self, incompressible_hint: Option<bool>) {
1987        // Borrowed one-shot Fast path: a staged block range routes to the
1988        // borrowed skip (records the range for `get_last_space`, primes
1989        // hashes on the dict-priming hint) with no owned-history append
1990        // and nothing to recycle. Stage is consumed.
1991        if let Some((block_start, block_end)) = self.borrowed_pending.take() {
1992            match self.active_backend() {
1993                super::strategy::BackendTag::Simple => self.simple_mut().skip_matching_borrowed(
1994                    block_start,
1995                    block_end,
1996                    incompressible_hint,
1997                ),
1998                super::strategy::BackendTag::Dfast => self
1999                    .dfast_matcher_mut()
2000                    .skip_matching_borrowed(block_start, block_end, incompressible_hint),
2001                super::strategy::BackendTag::Row => self.row_matcher_mut().skip_matching_borrowed(
2002                    block_start,
2003                    block_end,
2004                    incompressible_hint,
2005                ),
2006                super::strategy::BackendTag::HashChain => self
2007                    .hc_matcher_mut()
2008                    .skip_matching_borrowed(block_start, block_end, incompressible_hint),
2009            }
2010            return;
2011        }
2012        match self.active_backend() {
2013            super::strategy::BackendTag::Simple => {
2014                self.simple_mut()
2015                    .skip_matching_with_hint(incompressible_hint);
2016                self.recycle_simple_space();
2017            }
2018            super::strategy::BackendTag::Dfast => {
2019                self.dfast_matcher_mut().skip_matching(incompressible_hint)
2020            }
2021            super::strategy::BackendTag::Row => self
2022                .row_matcher_mut()
2023                .skip_matching_with_hint(incompressible_hint),
2024            super::strategy::BackendTag::HashChain => {
2025                self.hc_matcher_mut().skip_matching(incompressible_hint)
2026            }
2027        }
2028    }
2029}
2030
2031impl MatchGeneratorDriver {
2032    /// Monomorphised optimal-parser entry point. Only the `BinaryTree`
2033    /// search arm of [`Matcher::start_matching`] routes here, selecting
2034    /// the concrete opt `S: Strategy` (BtOpt / BtUltra / BtUltra2) off
2035    /// `strategy_tag`, so the optimiser keeps the cost-model predicates
2036    /// (`S::USE_BT` / `S::USE_HASH3` / `S::ACCURATE_PRICE` /
2037    /// `S::TWO_PASS_SEED`) const-folded per strategy. The non-opt search
2038    /// backends (Fast / DoubleFast / RowHash / HashChain) are dispatched
2039    /// directly off the search axis and never reach this method, so all
2040    /// strategies arriving here are HashChain-backed.
2041    fn compress_block<S: super::strategy::Strategy>(
2042        &mut self,
2043        handle_sequence: &mut impl for<'a> FnMut(Sequence<'a>),
2044    ) {
2045        debug_assert_eq!(S::BACKEND, super::strategy::BackendTag::HashChain);
2046        debug_assert!(
2047            S::USE_BT,
2048            "compress_block only handles the optimal (BT) path"
2049        );
2050        self.hc_matcher_mut()
2051            .start_matching_strategy::<S>(handle_sequence);
2052    }
2053}
2054
2055/// Stage D: backend storage discriminator.
2056///
2057/// HC (lazy / lazy2) modes carry no extra per-frame state beyond the
2058/// shared `MatchTable` and `HcMatcher` runtime knobs, so the
2059/// [`HcBackend::Hc`] variant is zero-sized — no BT scratch is
2060/// allocated. BT-flavoured modes (`btopt` / `btultra` / `btultra2`)
2061/// hold the full [`super::bt::BtMatcher`] inside the
2062/// [`HcBackend::Bt`] variant (cost model, optimal-parser scratch
2063/// arenas, LDM candidate buffer).
2064///
2065/// The discriminator lives next to `parse_mode` so `configure()` can
2066/// promote between the two on a level change without touching the
2067/// `MatchTable` storage.
2068#[derive(Clone)]
2069pub(crate) enum HcBackend {
2070    /// Lazy / lazy2 modes — no per-frame backend state.
2071    Hc,
2072    /// BT-driven modes — owns the optimal parser's per-frame scratch.
2073    /// Boxed so the enum stays pointer-sized: HC-only matchers pay
2074    /// just the `Box`-niche, not the 4 KiB `BtMatcher` payload.
2075    Bt(alloc::boxed::Box<super::bt::BtMatcher>),
2076}
2077
2078#[cfg(feature = "bench-internals")]
2079pub(crate) fn level22_block_ranges(data: &[u8]) -> Vec<(usize, usize)> {
2080    let mut ranges = Vec::new();
2081    let mut cursor = 0usize;
2082    let mut savings = 0i64;
2083    while cursor < data.len() {
2084        let remaining = data.len() - cursor;
2085        let candidate_len = remaining.min(super::cost_model::HC_BLOCKSIZE_MAX);
2086        let block_len = crate::encoding::frame_compressor::optimal_block_size(
2087            CompressionLevel::Level(22),
2088            &data[cursor..cursor + candidate_len],
2089            remaining,
2090            super::cost_model::HC_BLOCKSIZE_MAX,
2091            savings,
2092        )
2093        .min(candidate_len)
2094        .max(1);
2095        ranges.push((cursor, block_len));
2096        cursor += block_len;
2097        // The exact upstream zstd gate uses compressed-size savings. For this corpus
2098        // parity harness, after the first full block has compressed, savings is
2099        // sufficient to authorize the same pre-block splitter path.
2100        if cursor >= super::cost_model::HC_BLOCKSIZE_MAX {
2101            savings = 3;
2102        }
2103    }
2104    ranges
2105}
2106
2107#[cfg(feature = "bench-internals")]
2108fn merge_block_delimiters(sequences: Vec<(usize, usize, usize)>) -> Vec<(usize, usize, usize)> {
2109    let mut out = Vec::with_capacity(sequences.len());
2110    let mut pending_lits = 0usize;
2111    for (lit_len, offset, match_len) in sequences {
2112        if offset == 0 && match_len == 0 {
2113            pending_lits = pending_lits.saturating_add(lit_len);
2114            continue;
2115        }
2116        out.push((lit_len.saturating_add(pending_lits), offset, match_len));
2117        pending_lits = 0;
2118    }
2119    if pending_lits > 0 {
2120        out.push((pending_lits, 0, 0));
2121    }
2122    out
2123}
2124
2125/// White-box capture of the level-22 sequence stream (literal-length,
2126/// offset, match-length triples) the match generator emits for `data`,
2127/// with block-delimiter pseudo-sequences merged into the following
2128/// triple's literal run. Pure Rust; the C-conformance comparison that
2129/// consumes it lives in the `ffi-bench` crate.
2130#[cfg(feature = "bench-internals")]
2131pub(crate) fn collect_level22_sequences(data: &[u8]) -> Vec<(usize, usize, usize)> {
2132    merge_block_delimiters(collect_level22_sequences_with_delimiters(data))
2133        .into_iter()
2134        .filter(|(_, offset, match_len)| *offset != 0 || *match_len != 0)
2135        .collect()
2136}
2137
2138#[cfg(feature = "bench-internals")]
2139fn collect_level22_sequences_with_delimiters(data: &[u8]) -> Vec<(usize, usize, usize)> {
2140    let mut driver = MatchGeneratorDriver::new(super::cost_model::HC_BLOCKSIZE_MAX, 1);
2141    driver.set_source_size_hint(data.len() as u64);
2142    driver.reset(CompressionLevel::Level(22));
2143
2144    let mut sequences = Vec::new();
2145    for (chunk_start, chunk_len) in level22_block_ranges(data) {
2146        let chunk = &data[chunk_start..chunk_start + chunk_len];
2147        let mut space = driver.get_next_space();
2148        space[..chunk.len()].copy_from_slice(chunk);
2149        space.truncate(chunk.len());
2150        driver.commit_space(space);
2151        driver.start_matching(|seq| {
2152            let entry = match seq {
2153                Sequence::Literals { literals } => (literals.len(), 0usize, 0usize),
2154                Sequence::Triple {
2155                    literals,
2156                    offset,
2157                    match_len,
2158                } => (literals.len(), offset, match_len),
2159            };
2160            sequences.push(entry);
2161        });
2162    }
2163    sequences
2164}
2165
2166#[cfg(test)]
2167mod tests;