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;
29use super::sequences::{ExternalSequence, SequenceProducer};
30// FAST_HASH_FILL_STEP test-only re-export was tied to the legacy
31// SuffixStore MatchGenerator's interleaved hash-fill stride. The
32// upstream zstd-shape Fast kernel walks ip0 with kSearchStrength step-skip
33// acceleration instead, so the constant has no consumer in the
34// remaining live test set today.
35#[cfg(test)]
36use super::match_table::helpers::INCOMPRESSIBLE_SKIP_STEP;
37use super::match_table::helpers::MIN_MATCH_LEN;
38#[cfg(test)]
39use super::match_table::helpers::common_prefix_len;
40#[cfg(test)]
41use super::opt::ldm::HcRawSeq;
42#[cfg(test)]
43use super::opt::types::{HcCandidateQuery, MatchCandidate};
44use super::row::RowMatchGenerator;
45use super::simple::fast_matcher::{
46    FAST_LEVEL_1_HASH_LOG, FAST_LEVEL_1_MLS, FastKernelMatcher, TableCarry,
47};
48use super::workspace::HistoryBuf;
49
50pub(crate) const DFAST_MIN_MATCH_LEN: usize = 5;
51// Bytes the dfast short hash reads (upstream zstd `mls = 5`). Seeding / lookahead
52// guards use it so a position is only short-hashed once its full 5-byte key
53// is in range.
54pub(crate) const DFAST_SHORT_HASH_LOOKAHEAD: usize = 5;
55pub(crate) const ROW_MIN_MATCH_LEN: usize = 5;
56// Upstream zstd `clevels.h:31` at level 3 large-input bucket sets
57// `hashLog = 17` (the long-hash table) and `chainLog = 16` (the
58// short-hash table — upstream zstd names this `chainTable` even though for
59// dfast it's used as a plain single-slot hash). Each table holds one
60// `U32` per slot; the upstream zstd overwrites on collision and recovers
61// compression quality via the inline `_search_next_long` retry
62// (after a short-hash hit, probes `hashLong[hl1]` at `ip + 1` and
63// keeps the longer match).
64//
65// We mirror that storage layout: single `u32` per bucket (no
66// `[u32; N]` array), `long_hash` sized `1 << DFAST_HASH_BITS` and
67// `short_hash` one bit smaller via `DFAST_SHORT_HASH_BITS_DELTA`.
68// Two-table footprint at Level 3: `2^17 × 4 + 2^16 × 4 = 768 KiB`,
69// exact upstream parity. The `_search_next_long` retry lives in
70// `DfastMatchGenerator::hash_candidate` (called via
71// `best_match`). Earlier revisions kept a
72// 4-slot bucket per hash position; that paid 4× the upstream zstd memory
73// without measurable ratio gain once the retry was in place.
74//
75// `dfast_hash_bits_for_window` still clamps the runtime long-hash
76// value to `[MIN_WINDOW_LOG, DFAST_HASH_BITS]`, so this const is the
77// upper bound rather than a fixed default.
78pub(crate) const DFAST_HASH_BITS: usize = 17;
79/// Difference between `long_hash_bits` and `short_hash_bits` —
80/// upstream zstd `hashLog - chainLog` is 1 at every dfast level (`clevels.h`
81/// level 2: 16-15=1; level 3: 17-16=1). The short hash is one bit
82/// smaller than the long hash so the per-bucket footprint matches
83/// upstream zstd sizing exactly.
84pub(crate) const DFAST_SHORT_HASH_BITS_DELTA: usize = 1;
85/// Sentinel value for an empty slot in the dfast hash tables. Real
86/// positions are stored as `(abs_pos - position_base + 1) as u32`, so
87/// `0` is reserved as the "empty" marker and a true relative offset
88/// of `0` never appears in the table. Mirrors the LDM table's
89/// `LdmEntry.offset == 0` convention (see `encoding/ldm/table.rs`)
90/// so both rebasing structures share
91/// one sentinel scheme.
92pub(crate) const DFAST_EMPTY_SLOT: u32 = 0;
93
94/// Guard band reserved above the high-water mark before triggering a
95/// rebase on the Dfast hash tables. When the next insert would push a
96/// relative offset above `u32::MAX - DFAST_REBASE_GUARD_BAND`, the
97/// table calls `reduce(GUARD_BAND)` to shift every slot down and
98/// advance `position_base` so future inserts stay inside the `u32`
99/// window. Same scheme as `encoding/ldm/table.rs`.
100pub(crate) const DFAST_REBASE_GUARD_BAND: u32 = 1u32 << 30;
101// `kSearchStrength` (upstream `zstd_compress_internal.h:32`). The dfast step
102// ramp grows one position every `1 << kSearchStrength` = 256 bytes travelled
103// (upstream `kStepIncr`, zstd_double_fast.c:131). A smaller value accelerates
104// the scan faster and skips source positions upstream still inserts, which
105// drops the short matches upstream finds at a block start — so the
106// `#167`-disabled path must use the upstream 8 to stay byte-identical.
107pub(crate) const DFAST_SKIP_SEARCH_STRENGTH: usize = 8;
108pub(crate) const DFAST_SKIP_STEP_GROWTH_INTERVAL: usize = 1 << DFAST_SKIP_SEARCH_STRENGTH;
109/// How densely dfast indexes a block it wrote off without searching.
110///
111/// The block is not searched, so the only reason to index it at all is that a
112/// LATER block may duplicate it, and a duplicate is block-sized: the search
113/// that scans it meets an indexed position within one step, which is far inside
114/// what it scans anyway. Indexing at every sixteenth position instead cost a
115/// third of the encode on incompressible input — two tables, sixty-five
116/// thousand stores per mebibyte — for a proximity nothing needs. Fast reads the
117/// same reasoning from
118/// [`RAW_SKIP_INDEX_STEP`](crate::encoding::incompressible::RAW_SKIP_INDEX_STEP).
119pub(crate) const DFAST_INCOMPRESSIBLE_SKIP_STEP: usize =
120    crate::encoding::incompressible::RAW_SKIP_INDEX_STEP;
121pub(crate) const ROW_HASH_BITS: usize = 20;
122pub(crate) const ROW_LOG: usize = 5;
123pub(crate) const ROW_SEARCH_DEPTH: usize = 16;
124pub(crate) const ROW_TARGET_LEN: usize = 48;
125pub(crate) const ROW_TAG_BITS: usize = 8;
126pub(crate) const ROW_EMPTY_SLOT: u32 = u32::MAX;
127pub(crate) const ROW_HASH_KEY_LEN: usize = 4;
128// HC_PRIME3BYTES / HC_PRIME4BYTES moved to match_table::storage
129// alongside the hash helpers in Phase 1e Stage A. Only the test
130// module references the constants directly (production code goes
131// through `MatchTable::hash_value_with_mls`).
132#[cfg(test)]
133use super::match_table::storage::{HC_PRIME3BYTES, HC_PRIME4BYTES};
134
135// HC_HASH_LOG / HC_CHAIN_LOG / HC3_HASH_LOG / HC_EMPTY live on the
136// shared storage module so MatchTable methods can reference them
137// without pulling in this module. Re-imported here so existing
138// macros / configs / tests keep their unqualified names.
139#[cfg(test)]
140use super::match_table::storage::HC_EMPTY;
141// HC3_MAX_OFFSET moved to encoding::bt alongside the hash3 candidate
142// probe macro that consumes it; the macro references it via the
143// fully-qualified `$crate::encoding::bt::HC3_MAX_OFFSET` path so this
144// module no longer needs a local import.
145pub(crate) const HC_SEARCH_DEPTH: usize = 16;
146// HC_MIN_MATCH_LEN moved to encoding::hc; re-imported here so
147// existing references compile unchanged.
148pub(crate) const HC_OPT_MIN_MATCH_LEN: usize = HC_FORMAT_MINMATCH;
149pub(crate) const HC_TARGET_LEN: usize = 48;
150
151// MAX_HC_SEARCH_DEPTH moved to encoding::hc alongside chain_candidates.
152// Per-level tuning config (the config structs + `LEVEL_TABLE` + the
153// level→params resolution chain) lives in `levels::config`; the driver imports
154// that resolution API here.
155use super::levels::config::*;
156// The HashChain / BT match generator + its optimal-parse machinery lives in
157// `hc::generator`; the driver stores it in the `HashChain` storage variant.
158use super::hc::generator::HcMatchGenerator;
159
160// Dictionary prime + CDict-equivalent snapshot lifecycle. A child module so it
161// can reach the driver's private `primed` / `reset_shape` state directly; the
162// `Matcher` trait's dict entry points forward to its inherent `*_impl` helpers.
163mod dict_prime;
164// Long-distance matching: the search ahead of the blocks and the blocks
165// matched around its matches. A child module for the same private access.
166#[cfg(feature = "ldm")]
167mod long_distance;
168
169// `Strategy` and `StrategyTag` live in `crate::encoding::strategy`.
170// The driver carries a `StrategyTag` field set at `reset()` and
171// dispatches each block into a monomorphised `compress_block::<S>`
172// per concrete strategy.
173
174/// Backend storage for [`MatchGeneratorDriver`]. Exactly one match-finder
175/// state lives in the driver at a time — the active variant. Backend
176/// transitions in [`Matcher::reset`] release the current variant's tables and
177/// then replace `storage` with a freshly constructed variant for the new
178/// backend.
179///
180/// Replaces the prior pattern of four parallel fields (`match_generator`,
181/// `dfast_match_generator: Option<…>`, `row_match_generator: Option<…>`,
182/// `hc_match_generator: Option<…>`) + an `active_backend: BackendTag`
183/// discriminator: the parallel layout kept drained inner structures
184/// allocated across backend switches, and every per-frame/per-slice
185/// driver operation had to dispatch on `active_backend` to pick the
186/// right field. A single enum collapses the storage and makes the
187/// dispatcher pattern-match on the storage variant directly — same
188/// number of arms, but `storage.backend()` is now the canonical source
189/// of truth and dead variants are dropped when the active backend
190/// changes.
191///
192/// The variant is chosen by the resolved search method,
193/// [`LevelParams::backend`](crate::encoding::levels::config::LevelParams::backend),
194/// never by the level number alone: the search method comes from the
195/// (level, source size) cParams row plus any parameter override, and the
196/// size tier can change it. Level 11, for one, runs lazy2 on the Row backend
197/// for a large source and btopt on the HashChain backend for 16 KiB or less.
198/// Resolve the parameters for the input before assuming which backend runs.
199#[derive(Clone)]
200enum MatcherStorage {
201    /// Upstream zstd `ZSTD_fast` family, for `SearchMethod::Fast`.
202    /// Constructed by [`MatchGeneratorDriver::new`] as the initial variant
203    /// and re-selected by [`Matcher::reset`] when that search method resolves.
204    Simple(FastKernelMatcher),
205    /// Upstream zstd `ZSTD_dfast` family — two-table hash chain, for
206    /// `SearchMethod::DoubleFast`.
207    Dfast(DfastMatchGenerator),
208    /// Upstream zstd `lazy_generic` parse (`ZSTD_greedy` / `ZSTD_lazy` /
209    /// `ZSTD_lazy2` / `ZSTD_btlazy2`), for `SearchMethod::RowHash` and
210    /// `SearchMethod::BinaryTreeLazy`. The Row backend itself searches a hash
211    /// chain instead of rows when the resolved window is small.
212    Row(RowMatchGenerator),
213    /// The hash-chain matcher, for `SearchMethod::HashChain` and
214    /// `SearchMethod::BinaryTree`; the latter carries the BT-based optimal
215    /// modes (`btopt` / `btultra` / `btultra2`). The [`HcMatchGenerator`]'s
216    /// internal [`HcBackend`] discriminator decides whether BT scratch is
217    /// allocated.
218    HashChain(HcMatchGenerator),
219}
220
221impl MatcherStorage {
222    /// Heap bytes the active backend variant holds (tables, history, scratch).
223    fn heap_size(&self) -> usize {
224        match self {
225            Self::Simple(m) => m.heap_size(),
226            Self::Dfast(m) => m.heap_size(),
227            Self::Row(m) => m.heap_size(),
228            Self::HashChain(m) => m.heap_size(),
229        }
230    }
231
232    /// Capacity of the buffer blocks are read into, for the backends that
233    /// ingest in place. A frame sized up front reserves this exactly; one that
234    /// grew into it lands on a doubling step instead, which is what makes the
235    /// difference observable to a test.
236    #[cfg(test)]
237    fn ingest_capacity(&self) -> usize {
238        match self {
239            Self::Simple(m) => m.history_capacity(),
240            Self::Dfast(m) => m.history.capacity(),
241            Self::Row(m) => m.history.capacity(),
242            Self::HashChain(m) => m.table.history.capacity(),
243        }
244    }
245
246    /// See the backends' `set_dictionary_index_floor`.
247    fn set_dictionary_index_floor(&mut self, floor: usize) {
248        match self {
249            Self::Simple(m) => m.set_dictionary_index_floor(floor),
250            Self::Dfast(m) => m.set_dictionary_index_floor(floor),
251            Self::Row(m) => m.set_dictionary_index_floor(floor),
252            Self::HashChain(m) => m.table.set_dictionary_index_floor(floor),
253        }
254    }
255
256    /// The committed window of the owned history, oldest byte first.
257    #[cfg(feature = "ldm")]
258    fn committed_window(&self) -> &[u8] {
259        match self {
260            Self::Simple(m) => m.committed_window(),
261            Self::Dfast(m) => m.live_history(),
262            Self::Row(m) => m.live_history(),
263            Self::HashChain(m) => m.table.live_history(),
264        }
265    }
266
267    /// The committed window followed by the input read but not committed.
268    #[cfg(feature = "ldm")]
269    fn window_with_pending(&self) -> &[u8] {
270        match self {
271            Self::Simple(m) => m.window_with_pending(),
272            Self::Dfast(m) => m.window_with_pending(),
273            Self::Row(m) => m.window_with_pending(),
274            Self::HashChain(m) => m.table.window_with_pending(),
275        }
276    }
277
278    /// Length of the last committed block.
279    #[cfg(feature = "ldm")]
280    fn last_block_len(&self) -> usize {
281        match self {
282            Self::Simple(m) => m.last_committed_space().len(),
283            Self::Dfast(m) => m.get_last_space().len(),
284            Self::Row(m) => m.get_last_space().len(),
285            Self::HashChain(m) => m.table.get_last_space().len(),
286        }
287    }
288
289    /// See the backends' `uncommit_block`.
290    #[cfg(feature = "ldm")]
291    fn uncommit_block(&mut self, len: usize) {
292        match self {
293            Self::Simple(m) => m.uncommit_block(len),
294            Self::Dfast(m) => m.uncommit_block(len),
295            Self::Row(m) => m.uncommit_block(len),
296            Self::HashChain(m) => m.table.uncommit_block(len),
297        }
298    }
299
300    /// Commit `len` bytes of a block handed back by [`Self::uncommit_block`].
301    /// The whole block fit the window when it was first committed, so a piece
302    /// of it evicts nothing.
303    #[cfg(feature = "ldm")]
304    fn commit_piece(&mut self, len: usize) {
305        match self {
306            Self::Simple(m) => {
307                let evicted = m.commit_block(len);
308                debug_assert_eq!(evicted, 0, "a recommitted piece evicted window bytes");
309            }
310            Self::Dfast(m) => m.commit_block(len),
311            Self::Row(m) => m.commit_block(len),
312            Self::HashChain(m) => m.table.commit_block(len),
313        }
314    }
315
316    /// See the backends' `skip_long_match`.
317    #[cfg(feature = "ldm")]
318    fn skip_long_match(&mut self) {
319        match self {
320            Self::Simple(m) => m.skip_long_match(),
321            Self::Dfast(m) => m.skip_long_match(),
322            Self::Row(m) => m.skip_long_match(),
323            Self::HashChain(m) => m.table.skip_long_match(),
324        }
325    }
326
327    /// See the backends' `note_long_match`.
328    #[cfg(feature = "ldm")]
329    fn note_long_match(&mut self, offset: usize, literal_len: usize) {
330        match self {
331            Self::Simple(m) => m.note_long_match(offset, literal_len),
332            Self::Dfast(m) => m.note_long_match(offset, literal_len),
333            Self::Row(m) => m.note_long_match(offset, literal_len),
334            Self::HashChain(m) => m.table.note_long_match(offset, literal_len),
335        }
336    }
337
338    /// [`super::strategy::BackendTag`] family of the active variant.
339    fn backend(&self) -> super::strategy::BackendTag {
340        use super::strategy::BackendTag;
341        match self {
342            Self::Simple(_) => BackendTag::Simple,
343            Self::Dfast(_) => BackendTag::Dfast,
344            Self::Row(_) => BackendTag::Row,
345            Self::HashChain(_) => BackendTag::HashChain,
346        }
347    }
348}
349
350/// This is the default implementation of the `Matcher` trait. It allocates and reuses the buffers when possible.
351pub struct MatchGeneratorDriver {
352    /// Active match-finder state. Exactly one backend lives here at a
353    /// time; [`Matcher::reset`] swaps in a freshly constructed variant for
354    /// the new backend. `storage.backend()` is the canonical source of
355    /// truth for the parse family; `strategy_tag` carries the
356    /// compile-time strategy chosen at the last `reset()`.
357    storage: MatcherStorage,
358    // Compile-time strategy tag resolved at `reset()` from the
359    // requested `CompressionLevel`'s `LevelParams`. The driver's
360    // hot-block dispatcher in `blocks/compressed.rs` matches on
361    // this tag to enter the corresponding `Strategy`
362    // monomorphisation (`compress_block::<S>`).
363    strategy_tag: super::strategy::StrategyTag,
364    // Decoupled search-method axis resolved at `reset()` from
365    // `LevelParams.search`. The per-block dispatcher routes on this
366    // (not on `strategy_tag`) so a level's parse and search backend can
367    // be chosen independently. The `BinaryTree` arm still consults
368    // `strategy_tag` to pick the opt `Strategy` ZST.
369    search: super::strategy::SearchMethod,
370    // Decoupled parse-mode axis resolved at `reset()` from
371    // `LevelParams::parse()`. Independent of `search`: greedy / lazy /
372    // lazy2 can run on any non-opt search backend. The backends still
373    // read their own `lazy_depth` (kept in sync at `reset()`); this is
374    // the authoritative parse selector for the dispatcher.
375    pub(crate) parse: super::strategy::ParseMode,
376    /// Test-only per-level recipe override applied in `reset()` before
377    /// backend selection. Lets the parse×search matrix be exercised
378    /// without editing `LEVEL_TABLE`; never compiled into production.
379    #[cfg(test)]
380    config_override: Option<(super::strategy::SearchMethod, super::strategy::ParseMode)>,
381    /// Fine-grained per-knob overrides from the public
382    /// [`super::parameters::CompressionParameters`] surface (#27).
383    /// `None` (or an all-`None` [`super::parameters::ParamOverrides`])
384    /// keeps the resolved level geometry byte-identical to plain
385    /// level-based compression. Applied in [`Matcher::reset`] after the
386    /// level params are resolved, before backend selection. Persists
387    /// across resets (it is frame configuration, not a one-shot) until
388    /// the caller changes it.
389    param_overrides: Option<super::parameters::ParamOverrides>,
390    /// Chunk a dictionary is primed in: `base_slice_size` capped by the
391    /// frame's window.
392    slice_size: usize,
393    base_slice_size: usize,
394    // Frame header window size must stay at the configured live-window budget.
395    // Dictionary retention expands internal matcher capacity only.
396    reported_window_size: usize,
397    // Tracks currently retained bytes that originated from primed dictionary
398    // history and have not been evicted yet.
399    dictionary_retained_budget: usize,
400    // Source size hint for next frame (set via set_source_size_hint, cleared on reset).
401    source_size_hint: Option<u64>,
402    // Dictionary sizes for the next frame (set via set_dictionary_size_hint,
403    // consumed on reset): the serialized size keys the CDict cParams tier the
404    // frame runs (upstream `ZSTD_getCParamRowSize` on `dictSize`), the content
405    // size the dictionary tables and attach cutoffs.
406    dictionary_size_hint: Option<super::DictionarySizes>,
407    // Normalized `ceil_log2` bucket of the frame's source-size hint, captured at
408    // `reset` (where `source_size_hint` is consumed) via [`source_size_ceil_log`].
409    // `None` means the frame was unhinted. Drives `prime_with_dictionary`'s upstream zstd
410    // `ZSTD_shouldAttachDict` mode for the Simple/Fast backend: `None` (unknown)
411    // or `<= FAST_ATTACH_DICT_CUTOFF_LOG` → attach (separate dict table, 2-cursor
412    // `compress_block_fast_dict`); larger → copy (dictionary primed into the live
413    // table, 4-cursor `compress_block_fast`). The primed-snapshot key is the
414    // resolved shape ([`reset_shape`](Self::reset_shape)), not this bucket.
415    reset_size_log: Option<u8>,
416    // Whether the loaded dictionary fits the Fast attach path's tagged position
417    // field (`<= MAX_FAST_ATTACH_DICT_REGION`). Captured at `reset` from the
418    // dict-size hint (which equals the actual dict length on load) so the Fast
419    // attach decision, the attach-epoch reset bit, and the primed-snapshot
420    // `fast_attach` bit all gate on it consistently. `true` when there is no
421    // dictionary (the attach path is then unused). A dict too large to tag falls
422    // back to copy mode instead of overflowing the packed position.
423    reset_dict_attach_ok: bool,
424    // Hint-resolved matcher shape from the last `reset`: the [`LevelParams`], the
425    // active backend's applied Dfast/Row hash-table width (`0` for HC/Fast), the
426    // Fast attach-vs-copy mode and the Fast slot format. Combined with the
427    // frame's level into the [`PrimedKey`] that keys the primed snapshot, so it
428    // is only restored into a reset that resolved the identical matcher. `None`
429    // before the first `reset`.
430    reset_shape: Option<(LevelParams, usize, bool, bool)>,
431    /// How much of the frame's dictionary the match-finder tables index, as
432    /// a log of its suffix length: from the CDict's cParams, so every frame
433    /// of one dictionary indexes the same part of it, as every frame upstream
434    /// takes the CDict's tables (`ZSTD_loadDictionaryContent`). `None`
435    /// without a dictionary.
436    dict_reach_log: Option<u32>,
437    // One-shot borrowed block range `[start, end)` staged by the borrowed
438    // Fast frame path (`set_borrowed_block`) for the NEXT
439    // `start_matching` / `skip_matching_with_hint`. `Some` routes that
440    // call to the Simple backend's borrowed scan instead of the owned
441    // committed-block path; consumed (reset to `None`) by the routed
442    // call. Always `None` on the owned streaming path.
443    borrowed_pending: Option<(usize, usize)>,
444    /// CDict-equivalent: snapshot of the post-prime matcher state taken
445    /// once after the first dictionary prime — the backend `storage`
446    /// (hash tables + dictionary history + offset history + window) plus
447    /// the driver-level `dictionary_retained_budget`, the only two pieces
448    /// `prime_with_dictionary` writes. Subsequent frames restore this
449    /// (a table memcpy) instead of re-hashing every dictionary position,
450    /// mirroring upstream zstd `ZSTD_compressBegin_usingCDict` copying the
451    /// precomputed `cdict->matchState`. Invalidated when the dictionary
452    /// changes; keyed by the [`PrimedKey`] resolved matcher shape so a snapshot
453    /// is only restored into a reset that produces the same matcher — see
454    /// `restore_primed_dictionary`.
455    primed: Option<(MatcherStorage, usize, PrimedKey)>,
456    /// The snapshot a dictionary change set aside, kept for its buffers: the
457    /// next dictionary's snapshot is captured into them rather than cloned
458    /// anew. Dropped with the dictionary when none is attached any more.
459    primed_spare: Option<MatcherStorage>,
460    /// Where the tables live when the driver is reset on its own through
461    /// [`Matcher::reset`]; inside a compression context they live in the
462    /// context's workspace instead and this stays empty.
463    own_workspace: crate::encoding::workspace::Workspace,
464    /// Whether this frame's input, handed over as one slice, is scanned in
465    /// place rather than copied into the history. Decided at the reset,
466    /// because it decides how large the history is laid out.
467    frame_in_place: bool,
468    /// Long-distance matcher, `Some` while the frame runs with it on. It
469    /// belongs to the driver rather than to a backend, as upstream keeps
470    /// `ldmState` beside the match state: every strategy reads the same one.
471    #[cfg(feature = "ldm")]
472    ldm: Option<super::ldm::LdmProducer>,
473    /// The long-distance matches searched ahead of the blocks.
474    #[cfg(feature = "ldm")]
475    ldm_store: super::ldm::store::LdmSequenceStore,
476    /// What the last search found, before the store takes it.
477    #[cfg(feature = "ldm")]
478    ldm_found: Vec<super::opt::ldm::HcRawSeq>,
479    /// The long-distance sequences of the block being matched.
480    #[cfg(feature = "ldm")]
481    ldm_block: Vec<super::opt::ldm::HcRawSeq>,
482    /// Stream position of the committed end, in the coordinates the
483    /// long-distance matcher keeps its table in: the frame's first byte
484    /// (its dictionary's, when it has one) is `0`.
485    #[cfg(feature = "ldm")]
486    ldm_committed_end: usize,
487    /// Where the frame's dictionary ends in those coordinates, `0` without
488    /// one: what a match may still reach while the window has not passed it.
489    #[cfg(feature = "ldm")]
490    ldm_dict_end: usize,
491    /// Length of a block the long-distance matcher recommitted in pieces, so
492    /// [`Matcher::get_last_space`] reports the whole block, not its last piece.
493    #[cfg(feature = "ldm")]
494    ldm_split_block: Option<usize>,
495    /// A parser asked for each block in place of the backends, when one is
496    /// installed (C `ZSTD_registerSequenceProducer`).
497    producer: Option<ProducerSlot>,
498}
499
500/// A [`SequenceProducer`] and what to do when it gives no parse.
501struct ProducerSlot {
502    producer: alloc::boxed::Box<dyn SequenceProducer>,
503    /// Match the block with the backend instead when the producer fails;
504    /// otherwise the block goes out as literals and the failure is recorded.
505    fallback: bool,
506    /// A block the producer failed on went out without a fallback.
507    failed: bool,
508    /// The producer's parse of the block in hand, kept for its allocation.
509    parse: Vec<ExternalSequence>,
510}
511
512/// Identity of the matcher configuration a primed snapshot was captured under:
513/// the FULLY RESOLVED matcher shape, not the raw source-size hint.
514///
515/// `reset()` resolves the hint into a [`LevelParams`] (window_log cap, the
516/// HC/Fast table and search geometry, the parse depth/target-length that get
517/// baked into the restored `storage`) plus, for the Dfast/Row backends, a
518/// table-width derived from the hint's ceil-log bucket. The mapping from hint
519/// to resolved shape is many-to-one: the source-size adjustment is monotone in
520/// `ceil_log2(hint)`, and Level 22 additionally collapses several buckets onto
521/// one upstream zstd tier (its `<= 16/128/256 KiB` thresholds). Keying on the raw hint
522/// (or even its ceil-log bucket) therefore over-keys — two hints that resolve
523/// to the identical matcher would each force a full re-prime. Keying on the
524/// resolved (`params`, `table_bits`) pair restores across them.
525///
526/// `table_bits` is the hint-dependent hash-table width the ACTIVE backend
527/// applied (`set_hash_bits` value for Dfast/Row; `0` for HC/Fast, whose widths
528/// already live in `params`). The snapshot is only ever captured on the COPY
529/// path (a hinted, above-cutoff frame), so `table_bits` is always the resolved
530/// Dfast/Row value there, never the unhinted default.
531///
532/// `level` is kept alongside the resolved `params` because some stored matcher
533/// state is derived from the level DIRECTLY, not through `params`: e.g. Dfast's
534/// `use_fast_loop` is true for L3 but false for L4, yet L3 and L4 resolve to
535/// byte-identical `params`. Without `level` a snapshot captured at L3 could be
536/// restored into an L4 reset, installing the wrong `use_fast_loop`.
537///
538/// `fast_attach` records the Fast backend's attach-vs-copy mode
539/// ([`FAST_ATTACH_DICT_CUTOFF_LOG`]) because that cutoff (8 KiB) falls INSIDE a
540/// single resolved shape: an 8192- and an 8193-byte Level 1 hint both clamp to
541/// window_log 14 with identical `params`/`table_bits`, yet 8192 attaches (a
542/// separate dict table) while 8193 copies into the live table — two different
543/// `storage` shapes. The frame compressor only captures/restores snapshots on
544/// the copy path today, but keying on the mode keeps the snapshot identity
545/// self-sufficient rather than relying on that external gate.
546///
547/// Restoring a snapshot whose key differs would reinstate the old `storage`
548/// (and its `max_window_size` / table dimensions / parse params / dict-table
549/// shape) under a reset that resolved a different shape — the encoder could
550/// then search past the frame header's window and emit an undecodable match.
551/// All fields must match before a restore is allowed.
552#[derive(Clone, Copy, PartialEq, Eq)]
553struct PrimedKey {
554    level: super::CompressionLevel,
555    params: LevelParams,
556    table_bits: usize,
557    fast_attach: bool,
558    /// Whether the Fast table's slots are tagged. The format is chosen per
559    /// frame from how full the input will leave the table, so two frames of one
560    /// geometry can differ in it; a restore carries the snapshot's format in.
561    fast_tagged: bool,
562}
563
564/// Whether a configured HashChain matcher attaches the dictionary for a frame
565/// of `size_log` (see [`MatchGeneratorDriver::hc_dict_attach_mode`]).
566fn hc_attaches_dictionary(hc: &HcMatchGenerator, size_log: Option<u8>) -> bool {
567    let cutoff = if hc.table.uses_bt {
568        match hc.strategy_tag {
569            super::strategy::StrategyTag::BtUltra | super::strategy::StrategyTag::BtUltra2 => {
570                BT_ULTRA_ATTACH_DICT_CUTOFF_LOG
571            }
572            _ => BT_OPT_ATTACH_DICT_CUTOFF_LOG,
573        }
574    } else {
575        HC_ATTACH_DICT_CUTOFF_LOG
576    };
577    size_log.is_none_or(|log| log <= cutoff)
578}
579
580/// History bytes a frame lays out: the dictionary primed at its head and the
581/// input it is expected to bring. Input that can fill the window slides it, and
582/// the history then grows to the most it ever holds, which is laid out from the
583/// start, as upstream sizes its input buffer from the window: for the Fast
584/// backend twice the window grown by the dictionary (it drains back to one
585/// window when an append would pass two), for the others that window plus the
586/// quarter of it compaction leaves behind; either way plus one pending block of
587/// the frame's size.
588///
589/// A size known exactly (a slice, or a pledge the context enforces) is taken as
590/// it is, and its reads are held to what remains, so nothing past it is ever
591/// asked for. A size hint on a stream is a claim about data not yet read,
592/// trusted only up to the window the LEVEL would choose for it, and a read may
593/// find more than it said, so it keeps one block of slack; overriding the
594/// window is a claim of its own that only the data can confirm. An unknown size
595/// may fill any window, and is laid out for it up front, as upstream's buffered
596/// stream takes `windowSize + blockSize` of input buffer for an unknown pledge
597/// (`ZSTD_resetCCtx_internal`, `zstd_compress.c:2131-2139`). Room no input
598/// reaches is never written, so it is never resident: a one-byte stream through
599/// the CLI at levels 3, 19 and 22 peaks at the same RSS as a history grown by
600/// reading, and growing it instead measured no faster.
601/// The most history `backend` keeps for a `window`-byte window with
602/// `dict_len` bytes of dictionary and blocks of up to `block` bytes: the
603/// window, the slack it slides in, and the block being read.
604pub(crate) fn history_ceiling(
605    backend: super::strategy::BackendTag,
606    window: usize,
607    dict_len: usize,
608    block: usize,
609) -> usize {
610    use super::match_table::storage::MAX_PRIMED_WINDOW_SIZE;
611    // `MAX_PRIMED_WINDOW_SIZE` is `(u32::MAX - MAX_BLOCK_SIZE) / 2`, so the
612    // ceiling stays inside `usize` on a 32-bit target; a sum past `usize` is
613    // past it too.
614    let window = window
615        .checked_add(dict_len)
616        .map_or(MAX_PRIMED_WINDOW_SIZE, |w| w.min(MAX_PRIMED_WINDOW_SIZE));
617    let slack = match backend {
618        super::strategy::BackendTag::Simple => window,
619        _ => window >> 2,
620    };
621    window + slack + block
622}
623
624fn frame_history_bytes(
625    backend: super::strategy::BackendTag,
626    workspace: &crate::encoding::workspace::Workspace,
627    in_place: bool,
628    hint: Option<u64>,
629    dict_len: usize,
630    max_window_size: usize,
631    level: CompressionLevel,
632) -> usize {
633    use crate::encoding::workspace::IngestPlan;
634    let block = workspace.block_for_window(max_window_size);
635    let ceiling = history_ceiling(backend, max_window_size, dict_len, block);
636    // A size past `usize` is past the ceiling too.
637    let bytes = hint.map(|bytes| usize::try_from(bytes).unwrap_or(usize::MAX));
638    // The input and the room past it its last read may ask for.
639    let (input, read_slack) = match workspace.ingest() {
640        IngestPlan::Raw => return 0,
641        IngestPlan::Slice(_) if in_place => return dict_len.min(ceiling),
642        IngestPlan::Slice(len) | IngestPlan::PledgedStream(len) => (Some(len), 0),
643        IngestPlan::Stream => (
644            bytes.map(|bytes| {
645                let level_window_log =
646                    crate::encoding::levels::config::resolve_level_params(level, hint).window_log;
647                bytes.min(1usize << level_window_log)
648            }),
649            block,
650        ),
651    };
652    match input {
653        // A window stays below 2^31 and a block below 2^17, so
654        // `bytes + read_slack` fits; a dictionary large enough to overflow the
655        // rest is past the ceiling anyway.
656        Some(bytes) if bytes < max_window_size => dict_len
657            .checked_add(bytes + read_slack)
658            .map_or(ceiling, |sum| sum.min(ceiling)),
659        _ => ceiling,
660    }
661}
662
663impl MatchGeneratorDriver {
664    /// See [`MatcherStorage::ingest_capacity`].
665    #[cfg(test)]
666    pub(crate) fn ingest_capacity(&self) -> usize {
667        self.storage.ingest_capacity()
668    }
669
670    /// `(tables, history)` bytes the active window backend holds in
671    /// allocations of its own rather than in a context's workspace.
672    #[cfg(test)]
673    pub(crate) fn owned_table_and_history_bytes(&self) -> (usize, usize) {
674        match &self.storage {
675            MatcherStorage::Simple(_) => panic!("asked of a window backend only"),
676            MatcherStorage::Dfast(m) => (m.tables.owned_bytes(), m.history.owned_bytes()),
677            MatcherStorage::Row(m) => (m.tables.owned_bytes(), m.history.owned_bytes()),
678            MatcherStorage::HashChain(m) => {
679                (m.table.tables.owned_bytes(), m.table.history.owned_bytes())
680            }
681        }
682    }
683
684    /// Read `input` in and commit it as one block, the way the frame loop
685    /// does in two calls.
686    #[cfg(any(test, feature = "bench-internals"))]
687    pub(crate) fn commit_input(&mut self, input: &[u8]) {
688        self.fill_in_place(input.len(), &mut |history| {
689            history.extend_from_slice(input);
690            (input.len(), false)
691        });
692        self.commit_filled(input.len());
693    }
694
695    /// `slice_size` sets the chunk a dictionary is primed in.
696    /// `max_slices_in_window` determines the initial window capacity at construction
697    /// time. Effective window sizing is recalculated on every [`reset`](Self::reset)
698    /// from the resolved compression level and optional source-size hint.
699    pub(crate) fn new(slice_size: usize, max_slices_in_window: usize) -> Self {
700        // Validate inputs before deriving window_log_init. Three
701        // failure modes need explicit guards:
702        //
703        // 1. Zero args → `max_window_size = 0` → silent 1-byte
704        //    degenerate window (useless).
705        // 2. Multiplication overflow on `slice_size *
706        //    max_slices_in_window` → wraps silently in release.
707        // 3. `next_power_of_two` overflow when the product is
708        //    above `1 << (usize::BITS - 1)` → modern Rust PANICS
709        //    on overflow (older Rust returned 0).
710        //
711        // Catch all three at construction with a clear domain-
712        // specific message via `assert!` + `checked_mul` +
713        // `checked_next_power_of_two`, rather than letting either
714        // mode produce a silent degenerate matcher OR a generic
715        // panic deep in `FastKernelMatcher::with_params`.
716        assert!(
717            slice_size > 0,
718            "MatchGeneratorDriver::new requires slice_size > 0 (got 0)",
719        );
720        assert!(
721            max_slices_in_window > 0,
722            "MatchGeneratorDriver::new requires max_slices_in_window > 0 (got 0)",
723        );
724        let max_window_size = max_slices_in_window
725            .checked_mul(slice_size)
726            .expect("MatchGeneratorDriver::new: slice_size * max_slices_in_window overflows usize");
727        // Derive an effective window_log for the initial-state matcher.
728        // `MatchGeneratorDriver::new` runs BEFORE any reset, so it has
729        // no LevelParams to consult — we initialise to whatever
730        // window_log fits the caller's requested max_window_size
731        // (round up to the next power of two via `next_power_of_two`'s
732        // log). Reset() overwrites all three params from the resolved
733        // LevelParams.
734        //
735        // `checked_next_power_of_two` returns `None` if the next power
736        // of two would overflow `usize`. Modern Rust's
737        // `next_power_of_two` PANICS on overflow rather than returning
738        // 0 (the panic message is generic and unhelpful), so use the
739        // checked variant to surface the failure with a clear,
740        // domain-specific error.
741        let next_pow2 = max_window_size.checked_next_power_of_two().expect(
742            "MatchGeneratorDriver::new: max_window_size too large for \
743             next_power_of_two without overflow",
744        );
745        let window_log_init = next_pow2.trailing_zeros() as u8;
746        Self {
747            // Deferred table: `new` runs before any source size or resolved
748            // LevelParams exist, so allocating at the level-default hash_log
749            // here would be thrown away by the first frame's reset (which
750            // clamps the window to the input and reallocs at the resolved
751            // size). The deferral lets that first reset allocate exactly once.
752            storage: MatcherStorage::Simple(FastKernelMatcher::with_params_deferred(
753                window_log_init,
754                FAST_LEVEL_1_HASH_LOG,
755                FAST_LEVEL_1_MLS,
756                2, // upstream zstd default step_size (targetLength=0 → step=2)
757            )),
758            strategy_tag: super::strategy::StrategyTag::Fast,
759            search: super::strategy::SearchMethod::Fast,
760            parse: super::strategy::ParseMode::Greedy,
761            #[cfg(test)]
762            config_override: None,
763            param_overrides: None,
764            slice_size,
765            base_slice_size: slice_size,
766            // Report the ROUNDED-UP window size that the matcher
767            // actually carries (via `window_log_init = log2(next_pow2)`
768            // → matcher's `max_window_size = 1 << window_log_init =
769            // next_pow2`). For non-power-of-two `slice_size *
770            // max_slices_in_window` inputs, the unrounded value
771            // would under-report the active backend's window until
772            // the first `reset()` overwrites both sides from the
773            // resolved LevelParams.
774            reported_window_size: next_pow2,
775            reset_size_log: None,
776            reset_dict_attach_ok: true,
777            reset_shape: None,
778            dict_reach_log: None,
779            dictionary_retained_budget: 0,
780            source_size_hint: None,
781            dictionary_size_hint: None,
782            borrowed_pending: None,
783            primed: None,
784            primed_spare: None,
785            own_workspace: crate::encoding::workspace::Workspace::new(),
786            frame_in_place: false,
787            #[cfg(feature = "ldm")]
788            ldm: None,
789            #[cfg(feature = "ldm")]
790            ldm_store: Default::default(),
791            #[cfg(feature = "ldm")]
792            ldm_found: Vec::new(),
793            #[cfg(feature = "ldm")]
794            ldm_block: Vec::new(),
795            #[cfg(feature = "ldm")]
796            ldm_committed_end: 0,
797            #[cfg(feature = "ldm")]
798            ldm_dict_end: 0,
799            #[cfg(feature = "ldm")]
800            ldm_split_block: None,
801            producer: None,
802        }
803    }
804
805    /// Ask `producer` for each block's parse from the next block on, in place
806    /// of the backends; `None` removes it. With `fallback` a block it fails on
807    /// is matched by the backend instead; without, it goes out as literals
808    /// and [`Self::take_producer_failure`] reports it.
809    pub(crate) fn set_sequence_producer(
810        &mut self,
811        producer: Option<alloc::boxed::Box<dyn SequenceProducer>>,
812        fallback: bool,
813    ) {
814        // Callers install the producer before every frame: the parse buffer
815        // the last one grew stays for the next.
816        let parse = self
817            .producer
818            .take()
819            .map(|slot| slot.parse)
820            .unwrap_or_default();
821        self.producer = producer.map(|producer| ProducerSlot {
822            producer,
823            fallback,
824            failed: false,
825            parse,
826        });
827    }
828
829    /// Whether a block went out as literals because the producer failed on
830    /// it with no fallback, since this was last asked.
831    pub(crate) fn take_producer_failure(&mut self) -> bool {
832        self.producer
833            .as_mut()
834            .is_some_and(|slot| core::mem::take(&mut slot.failed))
835    }
836
837    /// Report the producer's parse of the last committed block, or of the
838    /// piece of one between long matches, indexing it as an unsearched one.
839    /// Returns `false`, having done nothing, when the producer failed and the
840    /// backend is to match it.
841    fn match_produced(&mut self, handle_sequence: &mut impl FnMut(Sequence)) -> bool {
842        let mut slot = self
843            .producer
844            .take()
845            .expect("called with a producer installed");
846        slot.parse.clear();
847        let window = self.window_size();
848        let block = self.get_last_space();
849        let block_len = block.len();
850        // The parse must cover the block exactly, with matches inside it (the
851        // producer sees no history, as upstream hands it none), and each match
852        // must copy the bytes it stands for: a parse of the right shape that
853        // misreads the block would otherwise write a frame decoding to other
854        // data.
855        let produced = slot
856            .producer
857            .produce(block, window, &mut slot.parse)
858            .is_ok()
859            && crate::encoding::sequences::validate_parse(
860                &slot.parse,
861                block_len,
862                window,
863                0,
864                true,
865                block_len,
866            )
867            .is_ok()
868            && crate::encoding::sequences::parse_reproduces(&slot.parse, block, &[]).is_ok();
869        if !produced && slot.fallback {
870            self.producer = Some(slot);
871            return false;
872        }
873        // The block's long matches, if any, were taken before it got here.
874        self.skip_backend(None);
875        if produced {
876            let mut literals = 0usize;
877            for sequence in &slot.parse {
878                literals += sequence.lit_len as usize;
879                if sequence.match_len == 0 {
880                    continue;
881                }
882                handle_sequence(Sequence::Triple {
883                    literal_len: literals,
884                    offset: sequence.offset as usize,
885                    match_len: sequence.match_len as usize,
886                });
887                literals = 0;
888            }
889            if literals > 0 {
890                handle_sequence(Sequence::Literals { len: literals });
891            }
892        } else {
893            slot.failed = true;
894            if block_len > 0 {
895                handle_sequence(Sequence::Literals { len: block_len });
896            }
897        }
898        self.producer = Some(slot);
899        true
900    }
901
902    fn level_params(level: CompressionLevel, source_size: Option<u64>) -> LevelParams {
903        resolve_level_params(level, source_size)
904    }
905
906    /// Install the public-parameter per-knob overrides (#27) applied at
907    /// the next [`Matcher::reset`]. `None` (or an all-`None` set) restores
908    /// plain level-based geometry. Persists across resets until changed.
909    pub(crate) fn set_param_overrides(
910        &mut self,
911        overrides: Option<super::parameters::ParamOverrides>,
912    ) {
913        self.param_overrides = overrides;
914    }
915
916    /// Active backend family derived from the storage variant. Single
917    /// source of truth — no separate runtime tag to drift against.
918    pub(crate) fn active_backend(&self) -> super::strategy::BackendTag {
919        self.storage.backend()
920    }
921
922    /// Whether the borrowed (no-copy, in-place over-window) scan is
923    /// implemented for the current backend + search configuration. The
924    /// HashChain backend serves both the lazy CHAIN parser
925    /// (`SearchMethod::HashChain`) and the BT/optimal parsers
926    /// (`SearchMethod::BinaryTree`); only the lazy chain has a borrowed scan
927    /// so far, so BT/optimal stay on the owned path.
928    pub(crate) fn borrowed_supported(&self) -> bool {
929        use super::strategy::{BackendTag, SearchMethod};
930        // A producer reads the committed block, which the in-place scan never
931        // commits.
932        if self.producer.is_some() {
933            return false;
934        }
935        match self.active_backend() {
936            BackendTag::Simple | BackendTag::Dfast | BackendTag::Row => true,
937            // The HashChain backend covers two searches: the lazy CHAIN parser
938            // (borrowed-capable) and the BINARY-TREE search (btlazy2 L13-15 +
939            // optimal BtOpt/BtUltra/BtUltra2 L16-22). btlazy2's BT-tree borrowed
940            // scan is byte-identical to owned (reads via live_history()), so it
941            // takes the in-place path. The OPTIMAL parsers stay owned: their
942            // cost-based DP is sensitive to candidate quality, and the borrowed
943            // continuous-index scan yields slightly different (ratio-worse)
944            // candidates than the owned evict+rehash scan — borrowed optimal
945            // both diverged from owned and fell outside the ffi ratio bound.
946            // Search-aware (not just strategy_tag) so optimal BT can never be
947            // staged on the borrowed path even via an internal caller.
948            BackendTag::HashChain => matches!(self.search, SearchMethod::HashChain),
949        }
950    }
951
952    /// Whether this frame, handed over as one slice with no dictionary, is
953    /// scanned in place. Settled by the reset, which laid the history out for
954    /// it, so the frame loop must take the path this names.
955    pub(crate) fn frame_scans_in_place(&self) -> bool {
956        self.frame_in_place
957    }
958
959    /// Whether a borrowed scan starting now sees nothing of an earlier frame,
960    /// so the frame is the one a fresh matcher writes. Asked once per frame,
961    /// after `reset`; [`Self::borrowed_supported`] stays the per-block
962    /// invariant. Only the Dfast kernel numbers a borrowed frame's input from
963    /// zero regardless of what its tables hold; the others advance their
964    /// floor past the previous frame, borrowed or not.
965    pub(crate) fn borrowed_frame_is_independent(&self) -> bool {
966        match &self.storage {
967            MatcherStorage::Dfast(d) => !d.tables_hold_earlier_frames,
968            _ => true,
969        }
970    }
971
972    /// Make [`Self::borrowed_frame_is_independent`] hold by emptying the
973    /// tables of earlier frames.
974    pub(crate) fn forget_earlier_frames(&mut self) {
975        if let MatcherStorage::Dfast(d) = &mut self.storage {
976            d.forget_earlier_frames();
977        }
978    }
979
980    /// Whether a DICTIONARY frame can take the borrowed (no input copy) path.
981    /// Only the Simple (Fast) backend with the dictionary ATTACHED (not the
982    /// copy/merge regime) has a borrowed dict scan — `start_matching_borrowed_dict`
983    /// reads live matches from the borrowed input in place and dict matches
984    /// from the committed dict prefix via the 2-segment counter. Every other
985    /// backend, and copy-mode (large-input) dict frames, stay on the owned
986    /// path. Checked AFTER priming, so `is_attached()` reflects the resolved
987    /// attach-vs-copy decision.
988    pub(crate) fn borrowed_dict_supported(&self) -> bool {
989        // As in `borrowed_supported`: a producer reads the committed block.
990        self.producer.is_none()
991            && matches!(
992                &self.storage,
993                MatcherStorage::Simple(m) if m.dict_is_attached()
994            )
995    }
996
997    fn simple_mut(&mut self) -> &mut FastKernelMatcher {
998        match &mut self.storage {
999            MatcherStorage::Simple(m) => m,
1000            _ => panic!("simple backend must be initialized by reset() before use"),
1001        }
1002    }
1003
1004    /// Register a caller-owned input buffer as the Simple backend's
1005    /// borrowed one-shot match window. Only valid on the Simple (Fast)
1006    /// backend; the one-shot frame path gates on that before calling.
1007    ///
1008    /// # Safety
1009    /// Same contract as [`FastKernelMatcher::set_borrowed_window`]: the
1010    /// buffer must stay live and unmodified until the window is cleared,
1011    /// and must be cleared before the buffer is dropped or the matcher is
1012    /// reused for another frame.
1013    pub(crate) unsafe fn set_borrowed_window(&mut self, buffer: &[u8]) {
1014        // SAFETY: forwarded contract — caller upholds liveness/clear.
1015        match self.active_backend() {
1016            super::strategy::BackendTag::Simple => unsafe {
1017                self.simple_mut().set_borrowed_window(buffer)
1018            },
1019            super::strategy::BackendTag::Dfast => unsafe {
1020                self.dfast_matcher_mut().set_borrowed_window(buffer)
1021            },
1022            super::strategy::BackendTag::Row => unsafe {
1023                self.row_matcher_mut().set_borrowed_window(buffer)
1024            },
1025            super::strategy::BackendTag::HashChain => unsafe {
1026                self.hc_matcher_mut().set_borrowed_window(buffer)
1027            },
1028        }
1029    }
1030
1031    /// Clear the borrowed one-shot window, returning the active backend
1032    /// to the owned `history` path.
1033    pub(crate) fn clear_borrowed_window(&mut self) {
1034        match self.active_backend() {
1035            super::strategy::BackendTag::Simple => self.simple_mut().clear_borrowed_window(),
1036            super::strategy::BackendTag::Dfast => self.dfast_matcher_mut().clear_borrowed_window(),
1037            super::strategy::BackendTag::Row => self.row_matcher_mut().clear_borrowed_window(),
1038            super::strategy::BackendTag::HashChain => self.hc_matcher_mut().clear_borrowed_window(),
1039            #[allow(unreachable_patterns)]
1040            _ => {}
1041        }
1042        self.borrowed_pending = None;
1043    }
1044
1045    /// Stage the borrowed block range `[block_start, block_end)` for the
1046    /// NEXT `start_matching` / `skip_matching_with_hint`, which the
1047    /// borrowed frame path uses in place of `commit_filled`. While
1048    /// staged, those trait calls route to the Simple backend's borrowed
1049    /// scan/skip (consuming the stage) instead of the owned committed
1050    /// block. See [`Matcher::start_matching`] /
1051    /// [`Matcher::skip_matching_with_hint`] on this type.
1052    pub(crate) fn set_borrowed_block(&mut self, block_start: usize, block_end: usize) {
1053        assert!(
1054            self.borrowed_supported(),
1055            "borrowed block staging is not supported for the active backend/search config",
1056        );
1057        assert!(
1058            block_start <= block_end,
1059            "borrowed block range must satisfy start <= end (start={block_start} end={block_end})",
1060        );
1061        self.borrowed_pending = Some((block_start, block_end));
1062        // Make the range visible to `get_last_space()` immediately: the
1063        // emit pipeline reads `get_last_space().len()` in
1064        // `collect_block_parts` BEFORE `start_matching` consumes the
1065        // stage, so the staged block (not the whole borrowed window) must
1066        // be reported now to keep the literal-buffer reservation right.
1067        match self.active_backend() {
1068            super::strategy::BackendTag::Simple => self
1069                .simple_mut()
1070                .stage_borrowed_block(block_start, block_end),
1071            super::strategy::BackendTag::Dfast => self
1072                .dfast_matcher_mut()
1073                .stage_borrowed_block(block_start, block_end),
1074            super::strategy::BackendTag::Row => self
1075                .row_matcher_mut()
1076                .stage_borrowed_block(block_start, block_end),
1077            super::strategy::BackendTag::HashChain => self
1078                .hc_matcher_mut()
1079                .table
1080                .stage_borrowed_block(block_start, block_end),
1081        }
1082    }
1083
1084    #[cfg(test)]
1085    fn dfast_matcher(&self) -> &DfastMatchGenerator {
1086        match &self.storage {
1087            MatcherStorage::Dfast(m) => m,
1088            _ => panic!("dfast backend must be initialized by reset() before use"),
1089        }
1090    }
1091
1092    /// The dfast backend's dict table builds started and how many allocated.
1093    /// Test-only.
1094    #[cfg(test)]
1095    pub(crate) fn dfast_dict_table_builds(&self) -> (usize, usize) {
1096        self.dfast_matcher().dict_table_builds
1097    }
1098
1099    /// The row backend's dict index builds started and how many allocated.
1100    /// Test-only.
1101    #[cfg(test)]
1102    pub(crate) fn row_dict_index_builds(&self) -> (usize, usize) {
1103        self.row_matcher().dict_index_builds
1104    }
1105
1106    fn dfast_matcher_mut(&mut self) -> &mut DfastMatchGenerator {
1107        match &mut self.storage {
1108            MatcherStorage::Dfast(m) => m,
1109            _ => panic!("dfast backend must be initialized by reset() before use"),
1110        }
1111    }
1112
1113    #[cfg(test)]
1114    pub(crate) fn row_matcher(&self) -> &RowMatchGenerator {
1115        match &self.storage {
1116            MatcherStorage::Row(m) => m,
1117            _ => panic!("row backend must be initialized by reset() before use"),
1118        }
1119    }
1120
1121    pub(crate) fn row_matcher_mut(&mut self) -> &mut RowMatchGenerator {
1122        match &mut self.storage {
1123            MatcherStorage::Row(m) => m,
1124            _ => panic!("row backend must be initialized by reset() before use"),
1125        }
1126    }
1127
1128    #[cfg(test)]
1129    fn hc_matcher(&self) -> &HcMatchGenerator {
1130        match &self.storage {
1131            MatcherStorage::HashChain(m) => m,
1132            _ => panic!("hash chain backend must be initialized by reset() before use"),
1133        }
1134    }
1135
1136    fn hc_matcher_mut(&mut self) -> &mut HcMatchGenerator {
1137        match &mut self.storage {
1138            MatcherStorage::HashChain(m) => m,
1139            _ => panic!("hash chain backend must be initialized by reset() before use"),
1140        }
1141    }
1142
1143    /// Shrink the active backend's `max_window_size` by the bytes
1144    /// reclaimed from the dictionary-retention budget. Returns `true`
1145    /// iff any reclamation happened — the caller uses that as the
1146    /// gate for [`Self::trim_after_budget_retire`] (which is a no-op
1147    /// otherwise: with `max_window_size` unchanged the backend's
1148    /// `trim_to_window` cannot find anything to evict, so calling it
1149    /// just runs an extra `match` ladder + a single early-out check
1150    /// per slice commit).
1151    #[must_use]
1152    fn retire_dictionary_budget(&mut self, evicted_bytes: usize) -> bool {
1153        let reclaimed = evicted_bytes.min(self.dictionary_retained_budget);
1154        if reclaimed == 0 {
1155            return false;
1156        }
1157        self.dictionary_retained_budget -= reclaimed;
1158        match self.active_backend() {
1159            super::strategy::BackendTag::Simple => {
1160                let matcher = self.simple_mut();
1161                // `reclaimed` can exceed the CURRENT `max_window_size`: the
1162                // retained dict budget is tracked independently and the
1163                // window may already have been shrunk by a prior eviction,
1164                // so the floor at 0 is the correct clamp, not a masked bug.
1165                matcher.max_window_size = matcher.max_window_size.saturating_sub(reclaimed);
1166            }
1167            super::strategy::BackendTag::Dfast => {
1168                let matcher = self.dfast_matcher_mut();
1169                // `reclaimed` can exceed the CURRENT `max_window_size`: the
1170                // retained dict budget is tracked independently and the
1171                // window may already have been shrunk by a prior eviction,
1172                // so the floor at 0 is the correct clamp, not a masked bug.
1173                matcher.max_window_size = matcher.max_window_size.saturating_sub(reclaimed);
1174            }
1175            super::strategy::BackendTag::Row => {
1176                let matcher = self.row_matcher_mut();
1177                // `reclaimed` can exceed the CURRENT `max_window_size`: the
1178                // retained dict budget is tracked independently and the
1179                // window may already have been shrunk by a prior eviction,
1180                // so the floor at 0 is the correct clamp, not a masked bug.
1181                matcher.max_window_size = matcher.max_window_size.saturating_sub(reclaimed);
1182            }
1183            super::strategy::BackendTag::HashChain => {
1184                let matcher = self.hc_matcher_mut();
1185                // See the Simple arm: `reclaimed` may exceed the current
1186                // window, so saturating to 0 is the correct clamp.
1187                matcher.table.max_window_size =
1188                    matcher.table.max_window_size.saturating_sub(reclaimed);
1189            }
1190        }
1191        true
1192    }
1193
1194    fn trim_after_budget_retire(&mut self) {
1195        loop {
1196            let mut evicted_bytes = 0usize;
1197            match self.active_backend() {
1198                // The Fast backend drains the oldest bytes in place and
1199                // reports the count; the window backends evict whole blocks,
1200                // so their count is the `window_size` delta.
1201                super::strategy::BackendTag::Simple => {
1202                    let MatcherStorage::Simple(m) = &mut self.storage else {
1203                        unreachable!("active_backend() == Simple proven above");
1204                    };
1205                    evicted_bytes += m.trim_to_window();
1206                }
1207                super::strategy::BackendTag::Dfast => {
1208                    let dfast = self.dfast_matcher_mut();
1209                    let pre = dfast.window_size;
1210                    dfast.trim_to_window();
1211                    evicted_bytes += pre - dfast.window_size;
1212                }
1213                super::strategy::BackendTag::Row => {
1214                    let row = self.row_matcher_mut();
1215                    let pre = row.window_size;
1216                    row.trim_to_window();
1217                    evicted_bytes += pre - row.window_size;
1218                }
1219                super::strategy::BackendTag::HashChain => {
1220                    let table = &mut self.hc_matcher_mut().table;
1221                    let pre = table.window_size;
1222                    table.trim_to_window();
1223                    evicted_bytes += pre - table.window_size;
1224                }
1225            }
1226            if evicted_bytes == 0 {
1227                break;
1228            }
1229            // The loop's invariant is "the backend's previous
1230            // `max_window_size` shrink had downstream bytes left to
1231            // evict" — that's what `evicted_bytes != 0` proves at
1232            // this point. `dictionary_retained_budget` is NOT
1233            // guaranteed to be positive here: the outer
1234            // `retire_dictionary_budget` call may have already
1235            // drained it to zero by reclaiming the last retained
1236            // bytes, while the backend still has bytes above the
1237            // freshly-shrunk window cap waiting for this loop to
1238            // evict. The return value of the retire call below is
1239            // therefore intentionally discarded — the loop's
1240            // termination is driven by `evicted_bytes == 0`, not by
1241            // whether the budget has more bytes left to reclaim.
1242            let _ = self.retire_dictionary_budget(evicted_bytes);
1243        }
1244    }
1245
1246    /// ATTACH (`true`) vs COPY (`false`) decision for the dms-bearing HashChain
1247    /// backend (lazy hash-chain AND binary-tree/optimal levels), mirroring
1248    /// upstream `ZSTD_shouldAttachDict` and its per-strategy `attachDictSizeCutoffs`:
1249    /// a small / unknown source ATTACHES the dict as a separate dms (hash-chain
1250    /// dms for lazy, DUBT dms for BT); a large known source COPIES it into the
1251    /// live chain / tree. The cutoff is the lazy/lazy2 value for HC, the
1252    /// btlazy2/btopt value for Bt{Opt}, and the smaller btultra/btultra2 value for
1253    /// the deepest parses. Both `skip_matching_for_dictionary_priming` (which
1254    /// stages the dict) and `prime_with_dictionary` (which builds-or-drops the
1255    /// dms) read this so the two stay in lock-step.
1256    fn hc_dict_attach_mode(&self) -> bool {
1257        // Only the HashChain backend (lazy hash-chain + BT/optimal) routes here;
1258        // a non-HashChain storage has no dms decision, so default to attach.
1259        let MatcherStorage::HashChain(hc) = &self.storage else {
1260            return true;
1261        };
1262        hc_attaches_dictionary(hc, self.reset_size_log)
1263    }
1264
1265    /// Whether the dfast backend attaches a dictionary of `dict_len` bytes to
1266    /// the frame the last reset prepared, rather than copying it into the
1267    /// live tables.
1268    fn dfast_attaches_dictionary(&self, dict_len: usize) -> bool {
1269        dict_len <= crate::encoding::dfast::DFAST_ATTACH_DICT_MAX_LEN
1270            && self
1271                .reset_size_log
1272                .is_none_or(|log| log <= DFAST_ATTACH_DICT_CUTOFF_LOG)
1273    }
1274
1275    fn skip_matching_for_dictionary_priming(&mut self, dict_len: usize) {
1276        match self.active_backend() {
1277            super::strategy::BackendTag::Simple => {
1278                // Upstream zstd `ZSTD_shouldAttachDict` mode selection for the Fast
1279                // strategy (cutoff 8 KB): small / unknown-size inputs ATTACH
1280                // (index dict positions into a SEPARATE immutable table; the
1281                // dual-probe 2-cursor `compress_block_fast_dict` then prefers
1282                // recent-input matches and falls back to the dict — the path
1283                // that wins small/unknown). Large known-size inputs COPY (prime
1284                // dict into the live table; the 4-cursor `compress_block_fast`
1285                // matches against it as window history — the path that already
1286                // matches/beats the upstream zstd on large corpora). The dispatch in
1287                // `start_matching` keys off `dict_table.is_some()`, which only
1288                // the attach path populates. See [`FAST_ATTACH_DICT_CUTOFF_LOG`].
1289                let attach = self.reset_dict_attach_ok
1290                    && self
1291                        .reset_size_log
1292                        .is_none_or(|log| log <= FAST_ATTACH_DICT_CUTOFF_LOG);
1293                if attach {
1294                    self.simple_mut().skip_matching_for_dict_prime(dict_len);
1295                } else {
1296                    self.simple_mut().skip_matching_for_dict_copy();
1297                }
1298            }
1299            super::strategy::BackendTag::Dfast => {
1300                // Upstream zstd `ZSTD_dictMatchState` mode selection for dfast (cutoff
1301                // 16 KiB): small / unknown-size inputs ATTACH (build the
1302                // separate immutable dict long+short tables; the dual-probe
1303                // `start_matching_fast_loop` searches live + dict, the path that
1304                // avoids the per-frame dict re-prime that dominates small
1305                // `compress-dict`). Larger known-size inputs COPY (re-prime the
1306                // dict into the live tables via `skip_matching_dense`, where the
1307                // dense scan matches it as window history). `skip_matching_for_dict_attach`
1308                // self-gates on `use_fast_loop` (only fast-loop levels carry the
1309                // dual-probe; general-path levels fall back to the dense copy).
1310                // The tagged dictionary slots index at most
1311                // `DFAST_ATTACH_DICT_MAX_LEN` bytes; a larger dictionary is
1312                // copied into the live tables instead.
1313                if self.dfast_attaches_dictionary(dict_len) {
1314                    self.dfast_matcher_mut().skip_matching_for_dict_attach();
1315                } else {
1316                    self.dfast_matcher_mut().park_dict_cache();
1317                    self.dfast_matcher_mut().skip_matching_dense();
1318                }
1319            }
1320            super::strategy::BackendTag::Row => {
1321                // Upstream zstd `ZSTD_RowFindBestMatch` `dictMatchState`: small /
1322                // unknown-size inputs ATTACH (build the separate immutable dict
1323                // row index; the bounded dual-probe in `row_candidate_rl`
1324                // searches live + dict, avoiding the per-frame dict re-index),
1325                // larger known-size inputs COPY (dense re-prime into the live
1326                // rows).
1327                // The attach / copy decision was made with the CDict's cParams
1328                // at `reset` (`RowDictPlan`); the backend indexes the dictionary
1329                // block accordingly.
1330                self.row_matcher_mut().prime_dictionary_current_block();
1331            }
1332            super::strategy::BackendTag::HashChain => {
1333                // Lazy-HC AND BT/optimal both follow upstream zstd `ZSTD_shouldAttachDict`
1334                // per-strategy: ATTACH (a separate dms — hash-chain dms for lazy,
1335                // DUBT dms for BT) for small / unknown inputs, COPY (merge the dict
1336                // into the live chain/tree) for large known inputs. ATTACH keeps
1337                // the dict in history but out of the live structure via
1338                // `skip_matching_dict_bt` (the cursor advance is shared by both
1339                // arms); COPY routes through the normal `skip_matching` (its
1340                // `uses_bt` branch fills the live tree, the lazy branch the live
1341                // chain). The dms is built-or-dropped to match in
1342                // `prime_with_dictionary`.
1343                if self.hc_dict_attach_mode() {
1344                    self.hc_matcher_mut().table.skip_matching_dict_bt();
1345                } else {
1346                    self.hc_matcher_mut().skip_matching(Some(false));
1347                }
1348            }
1349        }
1350    }
1351}
1352
1353impl Matcher for MatchGeneratorDriver {
1354    fn supports_dictionary_priming(&self) -> bool {
1355        true
1356    }
1357
1358    fn set_source_size_hint(&mut self, size: u64) {
1359        self.source_size_hint = Some(size);
1360    }
1361
1362    fn set_dictionary_size_hint(&mut self, sizes: super::DictionarySizes) {
1363        self.dictionary_size_hint = Some(sizes);
1364    }
1365
1366    /// Dict-relevance gate for the raw-fast-path. Reached only when a dictionary
1367    /// is active (the caller short-circuits on `dict_active`), so this answers
1368    /// "could the dict compress this otherwise-incompressible-looking block?".
1369    /// The Simple (Fast) backend samples its dict table precisely
1370    /// (`FastKernelMatcher::block_samples_match_dict`); the other backends
1371    /// (Dfast / Row / HashChain / BT) have their own dict structures and no cheap
1372    /// probe here, so they answer CONSERVATIVELY `true`: without a probe they
1373    /// cannot tell whether the dict compresses an incompressible-LOOKING block,
1374    /// and answering `false` would let the raw-fast-path emit such a block raw
1375    /// and miss an embedded dict segment. `dictionary_segment_in_incompressible_input_is_matched`
1376    /// pins this for Dfast/Row/BT — the 512-byte dict run inside high-entropy
1377    /// filler is matched only because these backends stay on the scan. So they
1378    /// keep the blanket scan the old `!dict_active` gate gave them; only the
1379    /// Simple/Fast backend trades it for the precise probe.
1380    fn block_samples_match_dict(&self, block: &[u8]) -> bool {
1381        match &self.storage {
1382            MatcherStorage::Simple(m) => m.block_samples_match_dict(block),
1383            _ => true,
1384        }
1385    }
1386
1387    /// Heap bytes this driver owns: the active backend's tables/history, the
1388    /// primed-dictionary snapshot (a cloned backend kept for CDict-equivalent
1389    /// reuse), and the workspace its tables live in when it is reset on its
1390    /// own. Tables laid out in a compression context's workspace are the
1391    /// context's to count. The inline struct itself is accounted by the
1392    /// owner's `size_of`.
1393    fn heap_size(&self) -> usize {
1394        let snapshot = self
1395            .primed
1396            .as_ref()
1397            .map(|(storage, _, _)| storage)
1398            .into_iter()
1399            .chain(&self.primed_spare)
1400            .map(MatcherStorage::heap_size)
1401            .sum::<usize>();
1402        #[cfg(feature = "ldm")]
1403        let ldm = self.ldm.as_ref().map_or(0, |p| p.heap_size())
1404            + self.ldm_store.heap_size()
1405            + (self.ldm_found.capacity() + self.ldm_block.capacity())
1406                * core::mem::size_of::<super::opt::ldm::HcRawSeq>();
1407        #[cfg(not(feature = "ldm"))]
1408        let ldm = 0;
1409        // The producer's parse buffer is kept from block to block.
1410        let produced = self.producer.as_ref().map_or(0, |slot| {
1411            slot.parse.capacity() * core::mem::size_of::<ExternalSequence>()
1412        });
1413        self.storage.heap_size() + snapshot + self.own_workspace.heap_bytes() + ldm + produced
1414    }
1415
1416    fn clear_param_overrides(&mut self) {
1417        self.param_overrides = None;
1418    }
1419
1420    fn reset(&mut self, level: CompressionLevel) {
1421        // On its own the driver lays its tables out in a workspace of its own,
1422        // which is moved out for the call and back: moving it leaves the
1423        // allocation, and so every region carved from it, where it is.
1424        // Driven directly, it takes blocks of any size up to the format's, so
1425        // that is the block its history leaves room for; it carves no block
1426        // buffers of its own.
1427        let mut own = core::mem::take(&mut self.own_workspace);
1428        own.begin_layout(
1429            crate::common::MAX_BLOCK_SIZE as usize,
1430            crate::encoding::workspace::no_trailing,
1431            crate::encoding::workspace::IngestPlan::Stream,
1432        );
1433        self.reset_in_workspace(level, &mut own);
1434        own.release_retired();
1435        self.own_workspace = own;
1436    }
1437
1438    fn reset_in_workspace(
1439        &mut self,
1440        level: CompressionLevel,
1441        workspace: &mut crate::encoding::workspace::Workspace,
1442    ) {
1443        let hint = self.source_size_hint.take();
1444        // An empty dictionary is "no dictionary": it primes nothing, so every
1445        // dictionary-frame decision below must see `None` for it.
1446        let dict_hint = self
1447            .dictionary_size_hint
1448            .take()
1449            .filter(|sizes| sizes.content > 0);
1450        // A frame without a dictionary has no snapshot to capture into the
1451        // set-aside buffers, nor will one follow until a dictionary comes.
1452        if dict_hint.is_none() {
1453            self.primed_spare = None;
1454        }
1455        // Snapshot the hint's normalized ceil-log bucket for the primed-snapshot
1456        // key and prime_with_dictionary's attach/copy mode decision (the hint is
1457        // consumed here, but priming happens just after reset). Storing the
1458        // bucket rather than the raw bytes means two hints that resolve to the
1459        // same matcher shape share one snapshot instead of each re-priming.
1460        self.reset_size_log = hint.map(source_size_ceil_log);
1461        // A dictionary too large for the tagged attach position field falls back
1462        // to copy mode. Captured here (from the load-set size hint = actual dict
1463        // length) so the prime decision and the snapshot-key / epoch bits agree.
1464        self.reset_dict_attach_ok =
1465            dict_hint.is_none_or(|sizes| sizes.content <= MAX_FAST_ATTACH_DICT_REGION);
1466        let hinted = hint.is_some();
1467        // A dictionary frame takes its cParams and match-finder from the
1468        // CDict's cParams (upstream `ZSTD_resetCCtx_usingCDict`), whose tier
1469        // is keyed by the serialized dictionary size; a lazy-band CDict also
1470        // carries `dict_plan` to the Row backend. The dictionary is prepared
1471        // under the caller's parameters, so they are part of those cParams.
1472        let overrides = self.param_overrides.unwrap_or_default();
1473        // Upstream indexes the last `1 << max(hashLog + 3, chainLog + 1)`
1474        // bytes of a dictionary into its CDict, at the CDict's cParams
1475        // (`ZSTD_loadDictionaryContent`).
1476        self.dict_reach_log = dict_hint.map(|sizes| {
1477            let cd = crate::encoding::cparams::get_cdict_cparams(
1478                crate::encoding::levels::config::numeric_level(level),
1479                sizes.serialized,
1480                &overrides,
1481            );
1482            (cd.hash_log + 3).max(cd.chain_log + 1).min(31)
1483        });
1484        // A dictionary frame runs the shape the dictionary was prepared with,
1485        // whatever the source size. Upstream stops doing that once the source
1486        // outgrows the dictionary and resolves the frame's own instead
1487        // (zstd_compress.c:5264). That alternative was implemented and measured
1488        // against this one and against the reference, in one session with the
1489        // arms interleaved, over five levels and two dictionary shapes, and it
1490        // loses on every row where the two differ. Time per frame over a 1 MiB
1491        // source, ours / the alternative / the reference:
1492        //
1493        //   3 KB dictionary        110 KB dictionary
1494        //   L1  1.13 / 1.13 / 0.73  1.14 / 1.15 / 0.79 ms
1495        //   L3  0.24 / 0.30 / 0.27  0.26 / 0.32 / 0.42 ms
1496        //   L5  0.52 / 2.69 / 0.38  0.43 / 2.77 / 1.16 ms
1497        //   L9  0.50 / 5.36 / 1.37  0.71 / 5.58 / 2.28 ms
1498        //   L12 0.87 / 5.56 / 1.87  1.60 / 5.58 / 3.08 ms
1499        //
1500        // Three to eight times the time for bytes that match to within a
1501        // percent, and under the larger dictionary this shape also beats the
1502        // reference on BOTH axes from L3 up (at L9, 0.71 ms and 243 bytes
1503        // against 2.28 ms and 1241), which the alternative would have given
1504        // away. A control arm at 64 KiB, under the size where the alternative
1505        // can run at all, stayed within 2.4% with identical output.
1506        //
1507        // The bench host is a VMware guest with no PMU passthrough, so cycles
1508        // and instructions are unavailable there (`perf stat -e cycles` reports
1509        // the event as unsupported); the figures above are `task-clock`, and at
1510        // this margin an instruction count would not be what decides it.
1511        //
1512        // See `dictionary_describes_frame`, which the C ABI still reads for a
1513        // question the codec cannot answer.
1514        let (params, dict_plan) = match dict_hint {
1515            Some(sizes) => crate::encoding::levels::config::resolve_level_params_with_dict(
1516                level, hint, sizes, &overrides,
1517            ),
1518            None => (Self::level_params(level, hint), None),
1519        };
1520        #[cfg_attr(not(test), allow(unused_mut))]
1521        let mut params = params;
1522        // Test-only: apply a parse×search override so the matrix can be
1523        // exercised without editing `LEVEL_TABLE`. Mutating `params` here
1524        // (before `next_backend`) flows the override through storage
1525        // selection, `configure`, and the `self.search`/`self.parse`
1526        // writes uniformly. Consumed with `take()` so it is one-shot: the
1527        // synthetic pairing applies to exactly this `reset()`, and a later
1528        // reset on the same driver falls back to the level's real config.
1529        #[cfg(test)]
1530        if let Some((search, parse)) = self.config_override.take() {
1531            params.search = search;
1532            params.lazy_depth = parse.lazy_depth();
1533            // The matrix sweep can pair a level with a backend its native
1534            // row doesn't populate (e.g. greedy L5, which carries only `row`,
1535            // run on HashChain). Synthesize a default config for the
1536            // overridden backend so its `configure` arm has something to read.
1537            use super::strategy::SearchMethod;
1538            match search {
1539                SearchMethod::Fast => {
1540                    params.fast.get_or_insert(FAST_L1);
1541                }
1542                SearchMethod::DoubleFast => {
1543                    params.dfast.get_or_insert(DFAST_L3);
1544                }
1545                SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
1546                    let row = params.row.get_or_insert(ROW_CONFIG);
1547                    row.bt = matches!(search, SearchMethod::BinaryTreeLazy);
1548                }
1549                SearchMethod::HashChain | SearchMethod::BinaryTree => {
1550                    params.hc.get_or_insert(HC_CONFIG);
1551                }
1552            }
1553        }
1554        // Public-parameter overrides (#27): apply the per-knob set on top
1555        // of the level-resolved params. A strategy override re-routes the
1556        // backend, so this must precede `next_backend` selection. The
1557        // all-`None` case is skipped so default level geometry stays
1558        // byte-identical to plain level-based compression. Shared with the
1559        // workspace estimate, which has to build what this builds.
1560        if let Some(ov) = self.param_overrides {
1561            crate::encoding::levels::config::apply_frame_overrides(
1562                &mut params,
1563                &ov,
1564                dict_hint.is_some(),
1565                hint,
1566            );
1567        }
1568        // The long-distance matcher's parameters for the frame, `None` without one.
1569        #[cfg(feature = "ldm")]
1570        let frame_ldm = self
1571            .param_overrides
1572            .and_then(|ov| ov.ldm)
1573            .map(|ldm_ov| crate::encoding::levels::config::frame_ldm_params(&params, &ldm_ov));
1574        // A dictionary frame's hash-chain / binary-tree widths are the CDict's
1575        // (`resolve_level_params_with_dict`): verbatim when the dictionary is
1576        // copied into the live tables (`ZSTD_resetCCtx_byCopyingCDict` builds
1577        // the context from the CDict's cParams), re-adjusted to the source
1578        // alone when it is attached (`byAttachingCDict`: the live tables hold
1579        // no dictionary entry, the dms carries its own dict-sized tables), so
1580        // a small source under a large attached dictionary keeps small live
1581        // tables. Nothing re-sizes `params.hc` here.
1582        // Upstream `ZSTD_resolveRowMatchFinderMode` (zstd_compress.c:238): the
1583        // greedy/lazy/lazy2 band searches rows only above a 2^14 window and a
1584        // hash chain otherwise. The Row backend runs that switch itself
1585        // (`RowMatchGenerator::use_chain`), so both finders share ONE parse
1586        // (upstream's single `lazy_generic`) and the level stays on `RowHash`.
1587        let next_backend = params.backend();
1588        let max_window_size = 1usize << params.window_log;
1589        self.dictionary_retained_budget = 0;
1590        // Drop any frame-local borrowed staging so it can't leak across a
1591        // reset and misroute the next start/skip into borrowed dispatch.
1592        self.borrowed_pending = None;
1593        if self.active_backend() != next_backend {
1594            // Drain the outgoing backend's allocations into the shared
1595            // pool. The `match &mut self.storage { ... }` block runs to
1596            // completion before the assignment below replaces the
1597            // variant, so the inner state we just drained is dropped
1598            // with the old variant.
1599            match &mut self.storage {
1600                MatcherStorage::Simple(_m) => {
1601                    // FastKernelMatcher owns a flat Vec<u8> history
1602                    // and a Vec<u32> hash table — both drop with the
1603                    // variant assignment below, no per-block buffers
1604                    // to recycle into the driver pools. The
1605                    // assignment-replace path collapses to a noop
1606                    // pre-pass for this backend.
1607                }
1608                MatcherStorage::Dfast(m) => {
1609                    // Drop the long / short hash table allocations
1610                    // before calling `m.reset`. Without this prepass,
1611                    // `DfastMatchGenerator::reset` would `fill` both
1612                    // tables with `DFAST_EMPTY_SLOT` sentinels — wasted
1613                    // work given the next assignment to `self.storage`
1614                    // is about to drop `m` entirely. `reset` itself
1615                    // short-circuits on `if !self.tables.is_empty()`, so
1616                    // handing it an empty `Vec` skips the fill loop.
1617                    // Mirrors the pre-drain pattern in the HashChain
1618                    // arm below (and serves the same peak-memory
1619                    // purpose: release the table-allocation footprint
1620                    // before constructing the replacement variant).
1621                    m.tables = crate::encoding::workspace::Table::empty();
1622                    m.reset();
1623                }
1624                MatcherStorage::Row(m) => {
1625                    // One buffer holds the positions and, in its byte tail,
1626                    // the cursors and tags — releasing it releases all three.
1627                    m.release_tables();
1628                    m.reset();
1629                }
1630                MatcherStorage::HashChain(m) => {
1631                    // Release oversized tables when switching away from
1632                    // HashChain so Best's larger allocations don't persist.
1633                    // hash3_table must be released alongside the other
1634                    // two: BtUltra2's `1 << HC3_HASH_LOG` entries would
1635                    // otherwise stay pinned across the backend switch,
1636                    // even though no future caller of this backend will
1637                    // touch them.
1638                    m.table.tables = crate::encoding::workspace::Table::empty();
1639                    m.table.chain_off = 0;
1640                    m.table.hash3_off = 0;
1641                    m.reset();
1642                }
1643            }
1644            // Swap in a fresh variant for the new backend. The previous
1645            // `storage` is dropped here.
1646            self.storage = match next_backend {
1647                super::strategy::BackendTag::Simple => {
1648                    // Per-level Fast cParams from resolve_level_params:
1649                    // Level(1) gets (hash_log=14, mls=7); Level(-7..=-1)
1650                    // get upstream zstd row-0 (hash_log=13, mls=7); Fastest /
1651                    // Uncompressed keep (hash_log=14, mls=6). See
1652                    // resolve_level_params for rationale.
1653                    let fast = params.fast.expect("Fast level row carries a FastConfig");
1654                    // Deferred: the reset below lays the table out in the
1655                    // workspace at the frame's resolved width.
1656                    MatcherStorage::Simple(FastKernelMatcher::with_params_deferred(
1657                        params.window_log,
1658                        fast.hash_log,
1659                        fast.mls,
1660                        fast.step_size,
1661                    ))
1662                }
1663                super::strategy::BackendTag::Dfast => {
1664                    MatcherStorage::Dfast(DfastMatchGenerator::new(max_window_size))
1665                }
1666                super::strategy::BackendTag::Row => {
1667                    MatcherStorage::Row(RowMatchGenerator::new(max_window_size))
1668                }
1669                super::strategy::BackendTag::HashChain => {
1670                    MatcherStorage::HashChain(HcMatchGenerator::new(max_window_size))
1671                }
1672            };
1673        }
1674
1675        // Single source of truth: `LevelParams::strategy_tag` is the
1676        // authoritative mapping from `CompressionLevel` to strategy.
1677        // `storage.backend()` derives the parse family from the variant,
1678        // so there is no separate runtime tag that could drift against
1679        // `LEVEL_TABLE`.
1680        self.strategy_tag = params.strategy_tag;
1681        self.search = params.search;
1682        self.parse = params.parse();
1683        self.slice_size = self.base_slice_size.min(max_window_size);
1684        self.reported_window_size = max_window_size;
1685        let strategy_tag = self.strategy_tag;
1686        // Source-proportional table window for the backends whose hash-table
1687        // widths are recomputed here (Dfast / Row). Like the HC / Fast caps
1688        // in `adjust_params_for_source_size`, this sizes the internal tables
1689        // from the RAW source log (not the wire `window_log` floor) so a
1690        // small frame zeroes a small table; it never exceeds the real window.
1691        let table_window_size = match hint {
1692            Some(h) => {
1693                let raw_log = source_size_ceil_log(h);
1694                // Clamp the shift below the pointer width before `1usize <<`:
1695                // an oversized hint (>= 2^63 + 1, and on 32-bit usize any hint
1696                // >= 2^32) drives `raw_log` to 64 / >= 32, and the shift would
1697                // overflow (panic in debug, wrap to 0 in release) before the
1698                // `.min(max_window_size)` cap below could bound it. The min cap
1699                // still provides the real semantic window bound.
1700                let shift = raw_log.max(MIN_WINDOW_LOG).min(usize::BITS as u8 - 1);
1701                (1usize << shift).min(max_window_size)
1702            }
1703            None => max_window_size,
1704        };
1705        // The Fast backend's dictionary mode, which `prime_with_dictionary`
1706        // takes from the same `reset_size_log`: attached, the dictionary goes
1707        // into a table of its own and the input is scanned in place.
1708        let fast_attach = matches!(next_backend, super::strategy::BackendTag::Simple)
1709            && self.reset_dict_attach_ok
1710            && self
1711                .reset_size_log
1712                .is_none_or(|log| log <= FAST_ATTACH_DICT_CUTOFF_LOG);
1713        // A slice on a backend that can scan it in place never enters the
1714        // history, with no dictionary or one the Fast backend attaches; the frame
1715        // loop reads this decision back (`frame_scans_in_place`) instead of
1716        // taking it again. The kernels keep positions in `u32`, counting a
1717        // dictionary ahead of the slice, so a longer one is copied.
1718        let dict_len = dict_hint.map_or(0, |sizes| sizes.content);
1719        // The long-distance matcher splits a block into pieces through the
1720        // owned history, so its frames keep the input there.
1721        #[cfg(feature = "ldm")]
1722        let long_distance = self.param_overrides.is_some_and(|ov| ov.ldm.is_some());
1723        #[cfg(not(feature = "ldm"))]
1724        let long_distance = false;
1725        self.frame_in_place = match workspace.ingest() {
1726            crate::encoding::workspace::IngestPlan::Slice(len) => {
1727                (dict_hint.is_none() || fast_attach)
1728                    && !long_distance
1729                    && self.borrowed_supported()
1730                    && len
1731                        .checked_add(dict_len)
1732                        .is_some_and(|len| len <= u32::MAX as usize)
1733            }
1734            _ => false,
1735        };
1736        let history_bytes = frame_history_bytes(
1737            next_backend,
1738            workspace,
1739            self.frame_in_place,
1740            hint,
1741            dict_hint.map_or(0, |sizes| sizes.content),
1742            max_window_size,
1743            level,
1744        );
1745        // The input the frame can write into its tables: the size when known,
1746        // otherwise the most its history is laid out to hold.
1747        let expected_input = hint.map_or(history_bytes, |bytes| {
1748            usize::try_from(bytes).unwrap_or(usize::MAX)
1749        });
1750        // The hint-dependent hash-table width the active backend applies, for
1751        // the primed-snapshot key. Dfast/Row compute it from `table_window_size`
1752        // below; HC/Fast leave it `0` because their widths live in `params`
1753        // (`hc.{hash,chain}_log` / `fast_hash_log`) — already part of the key.
1754        let mut resolved_table_bits: usize = 0;
1755        // The prime makes the same decision through the same helper, so the
1756        // layout chosen here is the one the dictionary is primed into.
1757        let dfast_attach_next =
1758            dict_hint.is_some_and(|sizes| self.dfast_attaches_dictionary(sizes.content));
1759        match &mut self.storage {
1760            MatcherStorage::Simple(m) => {
1761                // Per-level Fast cParams threaded from
1762                // resolve_level_params (see Simple-backend swap
1763                // arm above for the (level → params) mapping).
1764                let fast = params.fast.expect("Fast level row carries a FastConfig");
1765                // Same attach/copy split the dict-prime dispatch applies
1766                // below (`prime_with_dictionary`): only attach-mode dict
1767                // frames may keep the main table across the reset via an
1768                // epoch advance — copy-mode and no-dict frames must memset
1769                // it back to bias 0 for the raw-slice kernels.
1770                let dict_attach_epoch = dict_hint.is_some()
1771                    && self.reset_dict_attach_ok
1772                    && self
1773                        .reset_size_log
1774                        .is_none_or(|log| log <= FAST_ATTACH_DICT_CUTOFF_LOG);
1775                // Dictionary frame the caller will restore the primed snapshot
1776                // into (the same `restores_primed_snapshot` rule on the same
1777                // size bucket; a dictionary too large to attach is in copy
1778                // mode at every size, but only these frames are restored) and
1779                // whose snapshot matches this exact resolved shape:
1780                // `restore_primed_dictionary`, called right after this reset,
1781                // will `clone_from` the snapshot over this matcher, replacing
1782                // the table contents and bias wholesale, so the reset's
1783                // full-table memset would be thrown away. The
1784                // key components mirror `reset_shape` below: Simple leaves
1785                // `resolved_table_bits` 0, and `fast_attach` is false in copy
1786                // mode by construction.
1787                // The slot format is the one component this reset has yet to
1788                // choose, so it travels with the carry: the reset leaves the
1789                // table only if it chooses the snapshot's format, which is
1790                // the only case the restore then accepts.
1791                let restored_slot_format = self
1792                    .primed
1793                    .as_ref()
1794                    .filter(|(_, _, captured)| {
1795                        dict_hint.is_some()
1796                            && restores_primed_snapshot(
1797                                self.reset_size_log,
1798                                FAST_ATTACH_DICT_CUTOFF_LOG,
1799                            )
1800                            && *captured
1801                                == PrimedKey {
1802                                    level,
1803                                    params,
1804                                    table_bits: 0,
1805                                    fast_attach: false,
1806                                    fast_tagged: captured.fast_tagged,
1807                                }
1808                    })
1809                    .map(|(_, _, captured)| captured.fast_tagged);
1810                let carry = if let Some(tagged) = restored_slot_format {
1811                    TableCarry::OverwrittenByRestore { tagged }
1812                } else if dict_attach_epoch {
1813                    TableCarry::AdvanceEpoch
1814                } else {
1815                    TableCarry::Clear
1816                };
1817                // Cap `hash_log <= window_log + 1` (upstream zstd
1818                // `ZSTD_adjustCParams_internal`): once `window_log` is resized
1819                // down for a small source, a level-default `1 << hash_log`
1820                // table is mostly wasted address space whose per-frame memset
1821                // dominates the compress cost on tiny frames (a 4 KB frame at
1822                // window_log 12 still zero-fills the 64 KiB hash_log-14 table).
1823                // Gated to no-dict frames: the dict-attach path shares one
1824                // hash_log between the main and dict tables (so one hash keys
1825                // both), and shrinking only the main table would break that
1826                // invariant and the small-frame dict ratio.
1827                let hash_log = if dict_hint.is_some() {
1828                    fast.hash_log
1829                } else {
1830                    fast.hash_log.min(params.window_log as u32 + 1)
1831                };
1832                // The attached dictionary table takes the CDict's `hashLog`
1833                // (upstream `ZSTD_createCDict`: `ZSTD_getCParams(level,
1834                // UNKNOWN, dictSize)` adjusted for a `minSrcSize` source), not
1835                // the source-capped main width: a small source must not
1836                // shrink the table a large dictionary was sized for.
1837                m.set_dict_table_hash_log(dict_hint.map(|sizes| {
1838                    crate::encoding::cparams::get_cdict_cparams(
1839                        crate::encoding::levels::config::numeric_level(level),
1840                        sizes.serialized,
1841                        &overrides,
1842                    )
1843                    .hash_log
1844                }));
1845                let tables =
1846                    crate::encoding::simple::fast_kernel::hash_table::FastHashTable::workspace_bytes(
1847                        hash_log,
1848                    );
1849                // The history keeps only what the reset will, as on the dfast arm.
1850                m.retire_history();
1851                workspace.open_for_match_finder(
1852                    tables + m.history_workspace_bytes(history_bytes),
1853                    tables,
1854                    max_window_size,
1855                    expected_input,
1856                );
1857                // The history binds first, carrying its bytes out from under
1858                // where the table may now land.
1859                m.bind_history(workspace, history_bytes);
1860                m.reset(
1861                    params.window_log,
1862                    hash_log,
1863                    fast.mls,
1864                    fast.step_size,
1865                    expected_input,
1866                    dict_hint.map_or(0, |sizes| sizes.content),
1867                    carry,
1868                    workspace,
1869                );
1870            }
1871            MatcherStorage::Dfast(dfast) => {
1872                dfast.max_window_size = max_window_size;
1873                let dcfg = params
1874                    .dfast
1875                    .expect("Dfast level row must carry a DfastConfig");
1876                // Upstream zstd `cParams.hashLog`/`chainLog`, capped by the
1877                // source-size window when hinted so tiny inputs don't
1878                // over-allocate.
1879                let long_bits = if hinted {
1880                    dfast_hash_bits_for_window(table_window_size).min(dcfg.long_hash_log as usize)
1881                } else {
1882                    dcfg.long_hash_log as usize
1883                };
1884                let short_bits = if hinted {
1885                    dfast_hash_bits_for_window(table_window_size).min(dcfg.short_hash_log as usize)
1886                } else {
1887                    dcfg.short_hash_log as usize
1888                };
1889                resolved_table_bits = long_bits;
1890                dfast.set_hash_bits(long_bits, short_bits);
1891                // The attached dictionary tables take the CDict's geometry
1892                // (upstream hashes the dictMatchState tables with
1893                // `dictCParams`), not the source-capped live widths.
1894                dfast.set_dict_table_bits(dict_hint.map(|sizes| {
1895                    let cd = crate::encoding::cparams::get_cdict_cparams(
1896                        crate::encoding::levels::config::numeric_level(level),
1897                        sizes.serialized,
1898                        &overrides,
1899                    );
1900                    (cd.hash_log as usize, cd.chain_log as usize)
1901                }));
1902                // A copy-mode frame (source past the attach cutoff, or a
1903                // dictionary too large to tag) merges the dictionary into the
1904                // live tables; a resident attach-mode table must not be
1905                // re-borrowed under it (same decision as the prime dispatch).
1906                // The width-change detach in `set_hash_bits` does not cover an
1907                // unhinted attach frame followed by a large hinted one whose
1908                // live widths coincide at the level's full widths. Parked, the
1909                // tables serve the next frame that attaches this dictionary.
1910                if dict_hint.is_some() && !dfast_attach_next {
1911                    dfast.park_dict_cache();
1912                }
1913                // The widths are settled, so the tables can be laid out; the
1914                // reset below reads whether they continue the last frame's.
1915                // The history binds first, carrying its bytes out from under
1916                // where the tables may now land.
1917                let tables = dfast.tables_workspace_bytes();
1918                // The history keeps only what the reset will: laid out and
1919                // carried over at its full length, a long stream's window would
1920                // be moved into room the next frame never reads.
1921                dfast.retire_history();
1922                workspace.open_for_match_finder(
1923                    tables + dfast.history.workspace_bytes(history_bytes),
1924                    tables,
1925                    max_window_size,
1926                    expected_input,
1927                );
1928                dfast.history.bind(workspace, history_bytes);
1929                // Tagged slots unless the dictionary is attached (its loop reads
1930                // the live tables bare) or the window, dictionary included, is
1931                // past what a tagged slot's position range keeps across a rebase.
1932                // A slice scanned in place numbers its positions from its start
1933                // and never rebases, so its whole length has to fit as well.
1934                let dict_len = dict_hint.map_or(0, |sizes| sizes.content);
1935                let in_place_fits = !self.frame_in_place
1936                    || matches!(
1937                        workspace.ingest(),
1938                        crate::encoding::workspace::IngestPlan::Slice(len)
1939                            if len <= crate::encoding::dfast::DFAST_TAGGED_MAX_REL
1940                    );
1941                let tagged = !dfast_attach_next
1942                    && in_place_fits
1943                    && max_window_size.checked_add(dict_len).is_some_and(|window| {
1944                        (crate::encoding::dfast::DFAST_TAGGED_WINDOW_FLOOR
1945                            ..=crate::encoding::dfast::DFAST_TAGGED_WINDOW_LIMIT)
1946                            .contains(&window)
1947                    });
1948                dfast.bind_tables(workspace, tagged);
1949                dfast.reset();
1950            }
1951            MatcherStorage::Row(row) => {
1952                row.max_window_size = max_window_size;
1953                row.lazy_depth = params.lazy_depth;
1954                row.set_dict_plan(dict_plan);
1955                let mut row_cfg = params.row.expect("Row level row carries a RowConfig");
1956                // A dictionary frame's widths already come from the CDict's
1957                // cParams (adjusted to the source when attached); only a plain
1958                // hinted frame caps them by the window here.
1959                if hinted && dict_plan.is_none() {
1960                    // Clamp the configured hash width by the hinted window
1961                    // (upstream zstd `ZSTD_adjustCParams` caps hashLog by windowLog) —
1962                    // `min`, not replace, so an explicit `hash_log` param
1963                    // override (`row_cfg.hash_bits`) survives the hinted path
1964                    // instead of being overwritten by the window value.
1965                    //
1966                    // Clamp BEFORE `configure` so the backend sees ONE width
1967                    // per frame. Configuring with the unclamped level width
1968                    // and then re-clamping made `row_hash_log` oscillate on
1969                    // every hinted frame, and each width change clears the
1970                    // row tables — `ensure_tables` then re-filled all three
1971                    // every frame in a reused compressor.
1972                    row_cfg.hash_bits = row_cfg
1973                        .hash_bits
1974                        .min(row_hash_bits_for_window(table_window_size));
1975                }
1976                row.configure(row_cfg);
1977                // Key the primed snapshot on the width the backend ACTUALLY
1978                // applied (`set_hash_bits` clamps the request): recording the
1979                // request — or the 0 default on the unhinted path — keys
1980                // identical table geometries apart and forces needless
1981                // dictionary re-primes.
1982                resolved_table_bits = row.hash_bits();
1983                // The finder and its widths are settled by `configure`, so the
1984                // tables can be laid out; the reset reads whether they continue
1985                // the last frame's. The history keeps only what the reset can,
1986                // as on the dfast arm.
1987                row.retire_history();
1988                workspace.open_for_match_finder(
1989                    row.tables_workspace_bytes() + row.history.workspace_bytes(history_bytes),
1990                    row.zero_table_bytes(),
1991                    max_window_size,
1992                    expected_input,
1993                );
1994                row.history.bind(workspace, history_bytes);
1995                row.bind_tables(workspace);
1996                row.reset();
1997            }
1998            MatcherStorage::HashChain(hc) => {
1999                hc.table.max_window_size = max_window_size;
2000                hc.hc.lazy_depth = params.lazy_depth;
2001                let mut hc_cfg = params.hc.expect("HashChain level row carries an HcConfig");
2002                // Cap the hash / chain table logs by the hinted window so a small
2003                // input doesn't allocate the full level's tables (the upstream zstd
2004                // `ZSTD_adjustCParams_internal` clamp: `hashLog <= windowLog + 1`,
2005                // and `cycleLog <= windowLog` — `cycleLog == chainLog` for the HC
2006                // finder, `chainLog - 1` for the BT pair table, so `chainLog <=
2007                // windowLog` (+1 for BT)). Ratio-neutral: a hinted window of
2008                // `2^wlog` bytes holds at most `2^wlog` positions, so the slots
2009                // beyond that are never populated — capping only sheds unused
2010                // allocation. Was the source of L10-lazy peak-alloc ~2.15x the
2011                // upstream zstd on a 1 MiB input. Only applied when hinted; an
2012                // unknown-size stream keeps the full level tables.
2013                // Skip for dictionary frames: their `hc_cfg.{hash,chain}_log`
2014                // are the CDict's (verbatim when the dictionary is copied
2015                // into the live tables, source-adjusted when it is attached);
2016                // re-applying the source-window cap would collapse a copied
2017                // dictionary's tables to the small hinted source.
2018                if hinted && dict_hint.is_none() {
2019                    let wlog = hc_hash_bits_for_window(table_window_size);
2020                    let uses_bt = matches!(
2021                        strategy_tag,
2022                        super::strategy::StrategyTag::Btlazy2
2023                            | super::strategy::StrategyTag::BtOpt
2024                            | super::strategy::StrategyTag::BtUltra
2025                            | super::strategy::StrategyTag::BtUltra2
2026                    );
2027                    hc_cfg.hash_log = hc_cfg.hash_log.min(wlog + 1);
2028                    hc_cfg.chain_log = hc_cfg.chain_log.min(if uses_bt { wlog + 1 } else { wlog });
2029                }
2030                hc.configure(hc_cfg, strategy_tag, params.window_log);
2031                // A copy-mode frame merges the dictionary into the live tables,
2032                // so the previous attach frame's dms must not be re-borrowed
2033                // under it (the same decision the prime makes, taken here
2034                // because the reset below re-borrows on a primed dms alone).
2035                if dict_hint.is_some() && !hc_attaches_dictionary(hc, self.reset_size_log) {
2036                    hc.table.dms.invalidate();
2037                }
2038                // The widths are settled by `configure`, so the tables can be
2039                // laid out before the reset retires the previous frame's
2040                // entries in them.
2041                let tables = hc.table.tables_workspace_bytes();
2042                // The history keeps only what the reset will, as on the dfast arm.
2043                hc.table.retire_history();
2044                workspace.open_for_match_finder(
2045                    tables + hc.table.history.workspace_bytes(history_bytes),
2046                    tables,
2047                    max_window_size,
2048                    expected_input,
2049                );
2050                hc.table.history.bind(workspace, history_bytes);
2051                hc.table.bind_tables(workspace);
2052                hc.reset();
2053            }
2054        }
2055        // The long-distance matcher for the frame, whichever strategy runs it.
2056        // The same parameters keep the table allocation and only clear it, as
2057        // upstream reuses its `ldmState_t`.
2058        #[cfg(feature = "ldm")]
2059        {
2060            self.ldm = frame_ldm.map(|p| match self.ldm.take() {
2061                Some(mut existing) if existing.params() == p => {
2062                    existing.clear();
2063                    existing
2064                }
2065                _ => super::ldm::LdmProducer::new(p),
2066            });
2067            // A dictionary the reset kept in place is the frame's first bytes.
2068            self.ldm_committed_end = self.storage.committed_window().len();
2069            self.ldm_dict_end = self.ldm_committed_end;
2070            self.ldm_split_block = None;
2071        }
2072        // Record the resolved matcher shape for the primed-snapshot key. Captured
2073        // here (post-resolution, after the test-only param override) so the key
2074        // reflects exactly the geometry the restored `storage` must match. The
2075        // Fast attach-vs-copy mode is part of the shape ONLY for the Simple
2076        // backend (it decides the distinct dict-table shape that backend builds).
2077        // Dfast/Row/HashChain have their OWN attach/copy regimes, but this bit
2078        // models only the Fast table split; those backends are keyed by the
2079        // resolved matcher geometry instead, so folding the Fast bit into their
2080        // key would over-key identical resolved shapes. `fast_attach` is the
2081        // decision `prime_with_dictionary` makes from the same `reset_size_log`.
2082        // The Fast slot format this reset chose; only the Simple backend has one.
2083        let fast_tagged = matches!(&self.storage, MatcherStorage::Simple(m) if m.slots_tagged());
2084        self.reset_shape = Some((params, resolved_table_bits, fast_attach, fast_tagged));
2085        // Everything is laid out in `workspace` now. A driver reset on its own
2086        // before it joined a context still holds the workspace it used then,
2087        // which nothing points into any more; on its own the field is empty
2088        // here, since `reset` has it out for the call.
2089        self.own_workspace = crate::encoding::workspace::Workspace::new();
2090    }
2091
2092    // Dictionary entry points forward to the `dict_prime` child module, which
2093    // owns the prime / snapshot lifecycle (it reaches the driver's private
2094    // `primed` / `reset_shape` state directly as a descendant module).
2095
2096    #[inline]
2097    fn dictionary_is_resident(&self) -> bool {
2098        self.dictionary_is_resident_impl()
2099    }
2100
2101    #[inline]
2102    fn reapply_resident_dictionary(&mut self, offset_hist: [u32; 3]) {
2103        self.reapply_resident_dictionary_impl(offset_hist)
2104    }
2105
2106    #[inline]
2107    fn prime_with_dictionary(&mut self, dict_content: &[u8], offset_hist: [u32; 3]) {
2108        self.prime_with_dictionary_impl(dict_content, offset_hist)
2109    }
2110
2111    #[inline]
2112    fn restore_primed_dictionary(&mut self, level: super::CompressionLevel) -> bool {
2113        self.restore_primed_dictionary_impl(level)
2114    }
2115
2116    #[inline]
2117    fn capture_primed_dictionary(&mut self, level: super::CompressionLevel) {
2118        self.capture_primed_dictionary_impl(level)
2119    }
2120
2121    #[inline]
2122    fn invalidate_primed_dictionary(&mut self) {
2123        self.invalidate_primed_dictionary_impl()
2124    }
2125
2126    #[inline]
2127    fn seed_dictionary_entropy(
2128        &mut self,
2129        huff: Option<&crate::huff0::huff0_encoder::HuffmanTable>,
2130        ll: Option<&crate::fse::fse_encoder::FSETable>,
2131        ml: Option<&crate::fse::fse_encoder::FSETable>,
2132        of: Option<&crate::fse::fse_encoder::FSETable>,
2133    ) {
2134        self.seed_dictionary_entropy_impl(huff, ll, ml, of)
2135    }
2136
2137    fn leave_workspace(&mut self) {
2138        match &mut self.storage {
2139            MatcherStorage::Simple(m) => m.leave_workspace(),
2140            MatcherStorage::Dfast(m) => {
2141                m.tables.leave_workspace();
2142                m.history.leave_workspace();
2143            }
2144            MatcherStorage::Row(m) => {
2145                m.tables.leave_workspace();
2146                m.history.leave_workspace();
2147            }
2148            MatcherStorage::HashChain(m) => {
2149                m.table.tables.leave_workspace();
2150                m.table.history.leave_workspace();
2151            }
2152        }
2153    }
2154
2155    fn window_size(&self) -> u64 {
2156        self.reported_window_size as u64
2157    }
2158
2159    fn matches_beyond_window_tables(&self) -> bool {
2160        #[cfg(feature = "ldm")]
2161        return self.ldm.is_some();
2162        #[cfg(not(feature = "ldm"))]
2163        false
2164    }
2165
2166    fn settle_block_cut(&mut self, window: usize, cut: usize) -> usize {
2167        #[cfg(feature = "ldm")]
2168        return self.settle_long_distance_cut(window, cut);
2169        #[cfg(not(feature = "ldm"))]
2170        {
2171            let _ = window;
2172            cut
2173        }
2174    }
2175
2176    fn get_last_space(&mut self) -> &[u8] {
2177        // A block matched in pieces is still one block to the encoder.
2178        #[cfg(feature = "ldm")]
2179        if let Some(len) = self.ldm_split_block {
2180            let window = self.storage.committed_window();
2181            return &window[window.len() - len..];
2182        }
2183        match &self.storage {
2184            MatcherStorage::Simple(m) => m.last_committed_space(),
2185            MatcherStorage::Dfast(m) => m.get_last_space(),
2186            MatcherStorage::Row(m) => m.get_last_space(),
2187            MatcherStorage::HashChain(m) => m.table.get_last_space(),
2188        }
2189    }
2190
2191    /// Read the next block STRAIGHT into the backend's history buffer.
2192    ///
2193    /// The bytes are in the buffer but not yet part of the window: the caller
2194    /// picks the block boundary from [`Self::uncommitted_input`] and then
2195    /// calls [`Self::commit_filled`].
2196    fn fill_in_place(
2197        &mut self,
2198        capacity: usize,
2199        fill: &mut dyn FnMut(&mut HistoryBuf) -> (usize, bool),
2200    ) -> (usize, bool) {
2201        match &mut self.storage {
2202            MatcherStorage::Simple(m) => m.fill_uncommitted(capacity, fill),
2203            MatcherStorage::Dfast(m) => m.fill_uncommitted(capacity, fill),
2204            MatcherStorage::Row(m) => m.fill_uncommitted(capacity, fill),
2205            MatcherStorage::HashChain(m) => m.table.fill_uncommitted(capacity, fill),
2206        }
2207    }
2208
2209    /// Bytes read by [`Self::fill_in_place`] that no block has claimed yet.
2210    fn uncommitted_input(&self) -> &[u8] {
2211        match &self.storage {
2212            MatcherStorage::Simple(m) => m.uncommitted(),
2213            MatcherStorage::Dfast(m) => m.uncommitted(),
2214            MatcherStorage::Row(m) => m.uncommitted(),
2215            MatcherStorage::HashChain(m) => m.table.uncommitted(),
2216        }
2217    }
2218
2219    /// Claim `len` bytes of [`Self::uncommitted_input`] as the next block.
2220    ///
2221    /// A dictionary inflates `max_window_size` so the primed bytes stay
2222    /// reachable, and once eviction carries them out of the window that
2223    /// inflation has to be retired. Skipping it leaves the backend admitting
2224    /// matches older than the window the frame header reports, which encodes
2225    /// an offset no decoder can resolve.
2226    fn commit_filled(&mut self, len: usize) {
2227        #[cfg(feature = "ldm")]
2228        {
2229            self.ldm_committed_end += len;
2230            self.ldm_split_block = None;
2231        }
2232        // The window backends evict whole blocks inside `commit_block`,
2233        // subtracting each evicted block from `window_size` and then adding
2234        // `len`, so `pre + len - post` is exactly what was evicted and never
2235        // negative; the sum is two byte counts bounded by the window. The Fast
2236        // backend reports the bytes it drained itself.
2237        let evicted_bytes = match &mut self.storage {
2238            MatcherStorage::Simple(m) => m.commit_block(len),
2239            MatcherStorage::Dfast(m) => {
2240                let pre = m.window_size;
2241                m.commit_block(len);
2242                pre + len - m.window_size
2243            }
2244            MatcherStorage::Row(m) => {
2245                let pre = m.window_size;
2246                m.commit_block(len);
2247                pre + len - m.window_size
2248            }
2249            MatcherStorage::HashChain(m) => {
2250                let pre = m.table.window_size;
2251                m.table.commit_block(len);
2252                pre + len - m.table.window_size
2253            }
2254        };
2255        // The second trim pass only does work when retiring the budget shrank
2256        // `max_window_size` below the backend's window, so the common
2257        // no-dictionary commit skips it.
2258        if self.retire_dictionary_budget(evicted_bytes) {
2259            self.trim_after_budget_retire();
2260        }
2261    }
2262
2263    fn start_matching(&mut self, mut handle_sequence: impl FnMut(Sequence)) {
2264        // Borrowed one-shot Fast path: if the frame driver staged a
2265        // block range via `set_borrowed_block`, scan it in place against
2266        // the borrowed window instead of the owned committed block. Only
2267        // the Simple backend is instrumented (the gate guarantees it),
2268        // and the stage is consumed so the next block re-stages.
2269        if let Some((block_start, block_end)) = self.borrowed_pending.take() {
2270            // The borrowed scans share their kernels with the owned ones, so
2271            // they report through the same sink type.
2272            let mut forward = None;
2273            let mut sink = owned_sink(&mut handle_sequence, &mut forward);
2274            match self.active_backend() {
2275                super::strategy::BackendTag::Simple => {
2276                    let m = self.simple_mut();
2277                    if m.dict_is_attached() {
2278                        // Dict-attach borrowed scan: live matches read the
2279                        // borrowed input in place, dict matches read the
2280                        // committed dict prefix via the 2-segment counter.
2281                        m.start_matching_borrowed_dict(block_start, block_end, &mut sink);
2282                    } else {
2283                        m.start_matching_borrowed(block_start, block_end, &mut sink);
2284                    }
2285                }
2286                super::strategy::BackendTag::Dfast => self
2287                    .dfast_matcher_mut()
2288                    .start_matching_borrowed(block_start, block_end, &mut sink),
2289                super::strategy::BackendTag::Row => {
2290                    // Same greedy/lazy parse split as the owned RowHash arm.
2291                    let greedy = self.parse == super::strategy::ParseMode::Greedy;
2292                    self.row_matcher_mut().start_matching_borrowed(
2293                        block_start,
2294                        block_end,
2295                        greedy,
2296                        &mut sink,
2297                    );
2298                }
2299                super::strategy::BackendTag::HashChain => match self.search {
2300                    super::strategy::SearchMethod::HashChain => self
2301                        .hc_matcher_mut()
2302                        .start_matching_lazy_borrowed(block_start, block_end, &mut sink),
2303                    // `borrowed_supported()` keeps the optimal parsers on the
2304                    // owned path and `set_borrowed_block` asserts it.
2305                    other => {
2306                        unreachable!("HashChain backend with unexpected borrowed search {other:?}")
2307                    }
2308                },
2309            }
2310            return;
2311        }
2312        if self.producer.is_some() {
2313            // A producer stands in for every parser, the optimal one too, so
2314            // its block's long matches are taken outright at any strategy and
2315            // the producer parses the literals between them. Upstream refuses
2316            // the pair instead (zstd.h, block-level sequence producer
2317            // limitations); taking both loses neither.
2318            #[cfg(feature = "ldm")]
2319            if self.ldm.is_some() {
2320                // Where the producer fails with fallback, the backend matches
2321                // what is left without long-match candidates: this block's are
2322                // taken outright, and the optimal parser still holds the last
2323                // block's, whose block-relative positions would name the wrong
2324                // bytes here (its candidates are trusted, not re-checked).
2325                if matches!(self.search, super::strategy::SearchMethod::BinaryTree) {
2326                    let MatcherStorage::HashChain(hc) = &mut self.storage else {
2327                        unreachable!("the optimal parser runs on the hash-chain backend");
2328                    };
2329                    hc.backend.bt_mut().ldm_sequences.clear();
2330                }
2331                if self.start_matching_long_distance(&mut handle_sequence, true) {
2332                    return;
2333                }
2334                if self.match_produced(&mut handle_sequence) {
2335                    return;
2336                }
2337                // The producer failed with fallback on a block with no long
2338                // match, which is already taken: the backend matches it.
2339                let mut gap_literals = None;
2340                self.start_matching_owned(&mut owned_sink(&mut handle_sequence, &mut gap_literals));
2341                return;
2342            }
2343            if self.match_produced(&mut handle_sequence) {
2344                return;
2345            }
2346        }
2347        #[cfg(feature = "ldm")]
2348        if self.ldm.is_some() {
2349            // The optimal parser weighs long-distance matches as candidates;
2350            // below it they are taken outright (upstream
2351            // `ZSTD_ldm_blockCompress`, `zstd_ldm.c:685-749`).
2352            if matches!(self.search, super::strategy::SearchMethod::BinaryTree) {
2353                self.take_long_distance_block();
2354                let MatcherStorage::HashChain(hc) = &mut self.storage else {
2355                    unreachable!("the optimal parser runs on the hash-chain backend");
2356                };
2357                core::mem::swap(&mut self.ldm_block, &mut hc.backend.bt_mut().ldm_sequences);
2358            } else if self.start_matching_long_distance(&mut handle_sequence, false) {
2359                return;
2360            }
2361        }
2362        let mut gap_literals = None;
2363        self.start_matching_owned(&mut owned_sink(&mut handle_sequence, &mut gap_literals));
2364    }
2365
2366    fn skip_matching(&mut self) {
2367        self.skip_matching_with_hint(None);
2368    }
2369
2370    fn skip_matching_with_hint(&mut self, incompressible_hint: Option<bool>) {
2371        // Borrowed one-shot Fast path: a staged block range routes to the
2372        // borrowed skip (records the range for `get_last_space`, primes
2373        // hashes on the dict-priming hint) with no owned-history append
2374        // and nothing to recycle. Stage is consumed.
2375        if let Some((block_start, block_end)) = self.borrowed_pending.take() {
2376            match self.active_backend() {
2377                super::strategy::BackendTag::Simple => self.simple_mut().skip_matching_borrowed(
2378                    block_start,
2379                    block_end,
2380                    incompressible_hint,
2381                ),
2382                super::strategy::BackendTag::Dfast => self
2383                    .dfast_matcher_mut()
2384                    .skip_matching_borrowed(block_start, block_end, incompressible_hint),
2385                super::strategy::BackendTag::Row => self.row_matcher_mut().skip_matching_borrowed(
2386                    block_start,
2387                    block_end,
2388                    incompressible_hint,
2389                ),
2390                super::strategy::BackendTag::HashChain => self
2391                    .hc_matcher_mut()
2392                    .skip_matching_borrowed(block_start, block_end, incompressible_hint),
2393            }
2394            return;
2395        }
2396        // A block written out unsearched is still searched for long matches,
2397        // as upstream searches every block it compresses, and its matches are
2398        // taken past.
2399        #[cfg(feature = "ldm")]
2400        if self.ldm.is_some() {
2401            self.take_long_distance_block();
2402        }
2403        self.skip_backend(incompressible_hint);
2404    }
2405}
2406
2407impl MatchGeneratorDriver {
2408    /// Index the last committed block (or piece of one) in the backend
2409    /// without searching it, leaving the long-distance state alone.
2410    fn skip_backend(&mut self, incompressible_hint: Option<bool>) {
2411        match self.active_backend() {
2412            super::strategy::BackendTag::Simple => {
2413                self.simple_mut()
2414                    .skip_matching_with_hint(incompressible_hint);
2415            }
2416            super::strategy::BackendTag::Dfast => {
2417                self.dfast_matcher_mut().skip_matching(incompressible_hint)
2418            }
2419            super::strategy::BackendTag::Row => self
2420                .row_matcher_mut()
2421                .skip_matching_with_hint(incompressible_hint),
2422            super::strategy::BackendTag::HashChain => {
2423                self.hc_matcher_mut().skip_matching(incompressible_hint)
2424            }
2425        }
2426    }
2427}
2428
2429/// The sink every owned match runs against: `handle_sequence`, except that a
2430/// block's trailing literals go to `gap_literals` when it is `Some`, as the
2431/// gap before a long-distance match needs them. One sink type for the plain
2432/// block and for those gaps compiles each backend's scan once per caller sink
2433/// instead of twice.
2434fn owned_sink<'a, F: FnMut(Sequence)>(
2435    handle_sequence: &'a mut F,
2436    gap_literals: &'a mut Option<usize>,
2437) -> impl FnMut(Sequence) + 'a {
2438    // The guard is read only for the block's last report, never per triple.
2439    // Each arm rebuilds the report from its fields: forwarding the matched
2440    // value whole copies it as one 32-byte block out of the separate stores
2441    // that wrote it, and that copy stalls on every triple.
2442    move |sequence| match sequence {
2443        Sequence::Triple {
2444            literal_len,
2445            offset,
2446            match_len,
2447        } => handle_sequence(Sequence::Triple {
2448            literal_len,
2449            offset,
2450            match_len,
2451        }),
2452        Sequence::Literals { len } => match gap_literals {
2453            Some(gap) => *gap = len,
2454            None => handle_sequence(Sequence::Literals { len }),
2455        },
2456    }
2457}
2458
2459impl MatchGeneratorDriver {
2460    /// Match the last committed block of the owned history with the frame's
2461    /// backend.
2462    fn start_matching_owned(&mut self, handle_sequence: &mut impl FnMut(Sequence)) {
2463        use super::strategy::{self, StrategyTag};
2464        // Decoupled parse×search dispatch (fires once per block). The
2465        // search axis (`self.search`) picks the candidate-finding backend;
2466        // the parse axis (greedy vs lazy depth) is carried by the
2467        // backend's runtime `lazy_depth`, set per level at `reset()`.
2468        // The two are independent, so any parse can run on any search
2469        // backend. The `BinaryTree` arm still selects the opt `Strategy`
2470        // ZST off `strategy_tag` so `compress_block::<S>` keeps its
2471        // const-folded optimal-parser monomorphisation.
2472        use super::strategy::SearchMethod;
2473        match self.search {
2474            SearchMethod::Fast => {
2475                self.simple_mut().start_matching(handle_sequence);
2476            }
2477            SearchMethod::DoubleFast => {
2478                self.dfast_matcher_mut().start_matching(handle_sequence);
2479            }
2480            SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
2481                // One upstream `lazy_generic` body for greedy (depth 0: a
2482                // repcode hit is stored without a search, no lookahead), lazy
2483                // / lazy2 (`lazy_depth` 1 / 2) and btlazy2 (depth 2 over the
2484                // binary-tree finder); the finder (rows / chain / tree) was
2485                // resolved at `configure`.
2486                self.row_matcher_mut().start_matching(handle_sequence);
2487            }
2488            SearchMethod::HashChain => {
2489                // Greedy/lazy/lazy2 all flow through the lazy parser; it
2490                // reads `hc.lazy_depth` (0 = greedy commit).
2491                self.hc_matcher_mut().start_matching_lazy(handle_sequence);
2492            }
2493            SearchMethod::BinaryTree => match self.strategy_tag {
2494                StrategyTag::BtOpt => self.compress_block::<strategy::BtOpt>(handle_sequence),
2495                StrategyTag::BtUltra => self.compress_block::<strategy::BtUltra>(handle_sequence),
2496                StrategyTag::BtUltra2 => self.compress_block::<strategy::BtUltra2>(handle_sequence),
2497                _ => unreachable!(
2498                    "SearchMethod::BinaryTree requires an optimal strategy tag (BtOpt/BtUltra/BtUltra2)"
2499                ),
2500            },
2501        }
2502    }
2503}
2504
2505impl MatchGeneratorDriver {
2506    /// Monomorphised optimal-parser entry point. Only the `BinaryTree`
2507    /// search arm of [`Matcher::start_matching`] routes here, selecting
2508    /// the concrete opt `S: Strategy` (BtOpt / BtUltra / BtUltra2) off
2509    /// `strategy_tag`, so the optimiser keeps the cost-model predicates
2510    /// (`S::USE_BT` / `S::USE_HASH3` / `S::ACCURATE_PRICE` /
2511    /// `S::TWO_PASS_SEED`) const-folded per strategy. The non-opt search
2512    /// backends (Fast / DoubleFast / RowHash / HashChain) are dispatched
2513    /// directly off the search axis and never reach this method, so all
2514    /// strategies arriving here are HashChain-backed.
2515    fn compress_block<S: super::strategy::Strategy>(
2516        &mut self,
2517        handle_sequence: &mut impl FnMut(Sequence),
2518    ) {
2519        debug_assert_eq!(S::BACKEND, super::strategy::BackendTag::HashChain);
2520        debug_assert!(
2521            S::USE_BT,
2522            "compress_block only handles the optimal (BT) path"
2523        );
2524        self.hc_matcher_mut()
2525            .start_matching_strategy::<S>(handle_sequence);
2526    }
2527}
2528
2529/// Stage D: backend storage discriminator.
2530///
2531/// HC (lazy / lazy2) modes carry no extra per-frame state beyond the
2532/// shared `MatchTable` and `HcMatcher` runtime knobs, so the
2533/// [`HcBackend::Hc`] variant is zero-sized — no BT scratch is
2534/// allocated. BT-flavoured modes (`btopt` / `btultra` / `btultra2`)
2535/// hold the full [`super::bt::BtMatcher`] inside the
2536/// [`HcBackend::Bt`] variant (cost model, optimal-parser scratch
2537/// arenas, LDM candidate buffer).
2538///
2539/// The discriminator lives next to `parse_mode` so `configure()` can
2540/// promote between the two on a level change without touching the
2541/// `MatchTable` storage.
2542#[derive(Clone)]
2543pub(crate) enum HcBackend {
2544    /// Lazy / lazy2 modes — no per-frame backend state.
2545    Hc,
2546    /// BT-driven modes — owns the optimal parser's per-frame scratch.
2547    /// Boxed so the enum stays pointer-sized: HC-only matchers pay
2548    /// just the `Box`-niche, not the 4 KiB `BtMatcher` payload.
2549    Bt(alloc::boxed::Box<super::bt::BtMatcher>),
2550}
2551
2552#[cfg(feature = "bench-internals")]
2553pub(crate) fn level22_block_ranges(data: &[u8]) -> Vec<(usize, usize)> {
2554    let mut ranges = Vec::new();
2555    let mut cursor = 0usize;
2556    let mut savings = 0i64;
2557    while cursor < data.len() {
2558        let remaining = data.len() - cursor;
2559        let candidate_len = remaining.min(super::cost_model::HC_BLOCKSIZE_MAX);
2560        let block_len = crate::encoding::frame_compressor::optimal_block_size(
2561            CompressionLevel::Level(22),
2562            &data[cursor..cursor + candidate_len],
2563            remaining,
2564            super::cost_model::HC_BLOCKSIZE_MAX,
2565            savings,
2566        )
2567        .min(candidate_len)
2568        .max(1);
2569        ranges.push((cursor, block_len));
2570        cursor += block_len;
2571        // The exact upstream zstd gate uses compressed-size savings. For this corpus
2572        // parity harness, after the first full block has compressed, savings is
2573        // sufficient to authorize the same pre-block splitter path.
2574        if cursor >= super::cost_model::HC_BLOCKSIZE_MAX {
2575            savings = 3;
2576        }
2577    }
2578    ranges
2579}
2580
2581#[cfg(feature = "bench-internals")]
2582fn merge_block_delimiters(sequences: Vec<(usize, usize, usize)>) -> Vec<(usize, usize, usize)> {
2583    let mut out = Vec::with_capacity(sequences.len());
2584    let mut pending_lits = 0usize;
2585    for (lit_len, offset, match_len) in sequences {
2586        if offset == 0 && match_len == 0 {
2587            pending_lits = pending_lits.saturating_add(lit_len);
2588            continue;
2589        }
2590        out.push((lit_len.saturating_add(pending_lits), offset, match_len));
2591        pending_lits = 0;
2592    }
2593    if pending_lits > 0 {
2594        out.push((pending_lits, 0, 0));
2595    }
2596    out
2597}
2598
2599/// White-box capture of the level-22 sequence stream (literal-length,
2600/// offset, match-length triples) the match generator emits for `data`,
2601/// with block-delimiter pseudo-sequences merged into the following
2602/// triple's literal run. Pure Rust; the C-conformance comparison that
2603/// consumes it lives in the `ffi-bench` crate.
2604#[cfg(feature = "bench-internals")]
2605pub(crate) fn collect_level22_sequences(data: &[u8]) -> Vec<(usize, usize, usize)> {
2606    merge_block_delimiters(collect_level22_sequences_with_delimiters(data))
2607        .into_iter()
2608        .filter(|(_, offset, match_len)| *offset != 0 || *match_len != 0)
2609        .collect()
2610}
2611
2612#[cfg(feature = "bench-internals")]
2613fn collect_level22_sequences_with_delimiters(data: &[u8]) -> Vec<(usize, usize, usize)> {
2614    let mut driver = MatchGeneratorDriver::new(super::cost_model::HC_BLOCKSIZE_MAX, 1);
2615    driver.set_source_size_hint(data.len() as u64);
2616    driver.reset(CompressionLevel::Level(22));
2617
2618    let mut sequences = Vec::new();
2619    for (chunk_start, chunk_len) in level22_block_ranges(data) {
2620        driver.commit_input(&data[chunk_start..chunk_start + chunk_len]);
2621        driver.start_matching(|seq| {
2622            let entry = match seq {
2623                Sequence::Literals { len } => (len, 0usize, 0usize),
2624                Sequence::Triple {
2625                    literal_len,
2626                    offset,
2627                    match_len,
2628                } => (literal_len, offset, match_len),
2629            };
2630            sequences.push(entry);
2631        });
2632    }
2633    sequences
2634}
2635
2636#[cfg(test)]
2637mod tests;