Skip to main content

structured_zstd/encoding/levels/
config.rs

1//! Per-level compression tuning: the matcher config structs, the level
2//! parameter table, and the level → params resolution chain.
3//!
4//! Moved verbatim from `match_generator.rs` (no behaviour change): the
5//! `HcConfig` / `RowConfig` / `DfastConfig` / `FastConfig` knobs, `LevelParams`
6//! and `LEVEL_TABLE`, the public-parameter overrides, the source-size tiering,
7//! and the workspace estimators. `match_generator` imports this resolution API
8//! instead of carrying it inline. Encoding-level paths are written absolute
9//! (`crate::encoding::…`) so the module can live under `levels/` unchanged.
10
11use crate::encoding::CompressionLevel;
12use crate::encoding::match_generator::{HC_SEARCH_DEPTH, HC_TARGET_LEN, ROW_MIN_MATCH_LEN};
13#[cfg(test)]
14use crate::encoding::match_generator::{ROW_HASH_BITS, ROW_LOG, ROW_SEARCH_DEPTH, ROW_TARGET_LEN};
15#[cfg(test)]
16use crate::encoding::match_table::storage::{HC_CHAIN_LOG, HC_HASH_LOG};
17/// Bundled tuning knobs for the hash-chain matcher. Using a typed config
18/// instead of positional `usize` args eliminates parameter-order hazards.
19#[derive(Copy, Clone, PartialEq, Eq)]
20pub(crate) struct HcConfig {
21    pub(crate) hash_log: usize,
22    pub(crate) chain_log: usize,
23    pub(crate) search_depth: usize,
24    pub(crate) target_len: usize,
25    /// Binary-tree finder hash width. Upstream uses `mls = BOUNDED(3, minMatch, 6)`
26    /// (`ZSTD_selectBtGetAllMatches`, zstd_opt.c:896) — i.e. mls=3 on the
27    /// btultra/btultra2 levels (L18-22, minMatch=3) — and surfaces 3-byte matches
28    /// through a fallback-only HC3 finder (zstd_opt.c:691-720: distance < 256 KiB,
29    /// taken only when no longer/repcode match exists). Our optimal parser does
30    /// NOT yet replicate that 3-byte handling — it emits short matches C prices
31    /// out, breaking level-22 sequence parity — so the BT hash width is clamped UP
32    /// to 4 (`cp.min_match.clamp(4, 6)`) to keep the finder from surfacing those
33    /// 3-byte matches and so match C's output. This is a deliberate workaround,
34    /// NOT C's finder width; drop the clamp once the optimal parser is C-faithful
35    /// at minMatch 3 (tracked in #337). Carried explicitly per level so a
36    /// `target_length` override can't silently change the finder's hashing width.
37    /// Only the BT body reads it; HC / lazy levels keep it at 4.
38    pub(crate) search_mls: usize,
39}
40
41#[derive(Copy, Clone, PartialEq, Eq)]
42pub(crate) struct RowConfig {
43    pub(crate) hash_bits: usize,
44    pub(crate) row_log: usize,
45    pub(crate) search_depth: usize,
46    pub(crate) target_len: usize,
47    /// Upstream zstd `cParams.minMatch` for the row matcher: the regular-search
48    /// acceptance floor (a row candidate must extend to >= `mls` bytes).
49    /// The C-like advanced API surfaces this as the row min-match knob.
50    /// `ROW_MIN_MATCH_LEN` (5) is the default; the row hash key width stays
51    /// 4 bytes (an internal detail), so this only tunes the acceptance
52    /// floor, not the candidate hash distribution.
53    pub(crate) mls: usize,
54    /// Upstream `cParams.chainLog`: the hash-chain table the greedy/lazy
55    /// parse searches instead of rows when the window is 2^14 or smaller
56    /// (upstream `ZSTD_resolveRowMatchFinderMode`), or the binary tree
57    /// (`2^(chainLog-1)` nodes) of a btlazy2 level.
58    pub(crate) chain_log: usize,
59    /// Upstream `ZSTD_btlazy2`: the lazy parse searches the lazily-sorted
60    /// binary tree (`ZSTD_BtFindBestMatch`) instead of rows / the chain.
61    pub(crate) bt: bool,
62}
63
64// Only used as the default HashChain config when the test-only parse×search
65// override pairs a level with a backend its native row doesn't populate.
66#[cfg(test)]
67pub(crate) const HC_CONFIG: HcConfig = HcConfig {
68    hash_log: HC_HASH_LOG,
69    chain_log: HC_CHAIN_LOG,
70    search_depth: HC_SEARCH_DEPTH,
71    target_len: HC_TARGET_LEN,
72    search_mls: 4,
73};
74
75/// Base HashChain config synthesized when a public-parameter strategy
76/// override ([`crate::encoding::parameters`]) routes a level to the HC / BT
77/// backend whose native level row didn't populate `hc` (e.g. forcing
78/// `Strategy::Lazy2` onto a level the table resolves to Fast). Mirrors
79/// the mid-band lazy defaults; the per-knob overrides then refine it.
80pub(crate) const HC_OVERRIDE_DEFAULT: HcConfig = HcConfig {
81    hash_log: crate::encoding::match_table::storage::HC_HASH_LOG,
82    chain_log: crate::encoding::match_table::storage::HC_CHAIN_LOG,
83    search_depth: HC_SEARCH_DEPTH,
84    target_len: HC_TARGET_LEN,
85    search_mls: 4,
86};
87
88// Default Row config: only used by tests and the test-only parse×search
89// override (production greedy L5 carries its own `ROW_L5`).
90#[cfg(test)]
91pub(crate) const ROW_CONFIG: RowConfig = RowConfig {
92    hash_bits: ROW_HASH_BITS,
93    row_log: ROW_LOG,
94    search_depth: ROW_SEARCH_DEPTH,
95    target_len: ROW_TARGET_LEN,
96    mls: ROW_MIN_MATCH_LEN,
97    chain_log: ROW_HASH_BITS,
98    bt: false,
99};
100
101// Level-5 greedy is the ONLY strategy routed to the Row backend
102// (`StrategyTag::backend`: greedy -> Row; lazy / btopt / btultra* ->
103// HashChain), so it is the only level whose `row:` field is read. The upstream zstd
104// `clevels.h` default row (srcSize > 256 KB) for level 5 is searchLog=3,
105// targetLength=2, from which the row matcher derives:
106//   rowLog       = clamp(searchLog, 4, 6) = 4
107//   search_depth = 1 << min(searchLog, rowLog) = 8   (= nbAttempts)
108//   target_len   = targetLength = 2                  (nice-match early-out)
109// The shared `ROW_CONFIG` (row_log=5, search_depth=16, target_len=48) ran a
110// level-12-grade search here: 16 slots per row, never early-exiting until a
111// 48-byte match. That exhaustive walk was the dominant cost in greedy L5's
112// encode-speed regression vs FFI. `hash_bits` matches upstream zstd's
113// `ZSTD_getCParams(5, .., 0).hashLog` = 19 (verified via
114// `cparams_check 5`), so the row table is the same width as upstream's
115// (2^19 slots); the previous `ROW_HASH_BITS` (20) doubled both row tables vs
116// upstream, the dominant peak-memory excess on the greedy band.
117pub(crate) const ROW_L5: RowConfig = RowConfig {
118    hash_bits: 19,
119    row_log: 4,
120    search_depth: 8,
121    target_len: 2,
122    mls: ROW_MIN_MATCH_LEN,
123    chain_log: 18,
124    bt: false,
125};
126
127/// Per-level Double-Fast hash sizing, mirroring the upstream zstd `clevels.h` columns
128/// (config-driven, not a hardcoded constant): `long_hash_log` =
129/// `cParams.hashLog` (the long 8-byte hash table), `short_hash_log` =
130/// `cParams.chainLog` (the short hash table dfast repurposes as its
131/// secondary index). Only the Dfast backend reads it, so non-dfast level
132/// rows carry `dfast: None`. `minMatch` stays the upstream zstd-fixed `5`
133/// (`DFAST_MIN_MATCH_LEN`, used in const contexts).
134#[derive(Copy, Clone, PartialEq, Eq)]
135pub(crate) struct DfastConfig {
136    pub(crate) long_hash_log: u8,
137    pub(crate) short_hash_log: u8,
138}
139
140// Upstream zstd clevels.h default row (srcSize > 256 KB): L3 {hashLog 17, chainLog 16}.
141pub(crate) const DFAST_L3: DfastConfig = DfastConfig {
142    long_hash_log: 17,
143    short_hash_log: 16,
144};
145
146/// Per-level Fast-strategy tuning, only consumed by the `FastKernelMatcher`
147/// (Simple backend): `hash_log` = upstream zstd `cParams.hashLog`, `mls` = upstream zstd
148/// `cParams.minMatch` (4..=8), `step_size` = upstream zstd `stepSize`. Carried as
149/// `LevelParams.fast` (`Some` only on Fast level rows; `None` elsewhere).
150#[derive(Copy, Clone, PartialEq, Eq)]
151pub(crate) struct FastConfig {
152    pub(crate) hash_log: u32,
153    pub(crate) mls: u32,
154    pub(crate) step_size: usize,
155}
156
157pub(crate) const FAST_L1: FastConfig = FastConfig {
158    hash_log: 14,
159    // Tier-0 (srcSize > 256 KiB) `cParams.minMatch`. Upstream zstd selects the
160    // Level-1 row from a 4-way srcSize-tiered table (`ZSTD_getCParams_internal`
161    // → `ZSTD_defaultCParameters[tableID][1]`), and minMatch shrinks for
162    // smaller inputs: 7 (>256 KiB) / 6 (16..256 KiB) / 5 (<=16 KiB). The base
163    // here is the tier-0 value; `fast_l1_mls_for_source_size` lowers it per the
164    // tier in `adjust_params_for_source_size`.
165    mls: 7,
166    step_size: 2,
167};
168
169/// Resolved tuning parameters for a compression level. The
170/// [`StrategyTag`] is the single source of truth for the backend
171/// family and the compile-time strategy consts; the runtime
172/// [`BackendTag`] used by the driver dispatcher is derived via
173/// [`StrategyTag::backend`] so the two cannot drift.
174#[derive(Copy, Clone, PartialEq, Eq)]
175pub(crate) struct LevelParams {
176    pub(crate) strategy_tag: crate::encoding::strategy::StrategyTag,
177    /// Decoupled search-method axis. Independent of `strategy_tag`'s
178    /// parse half: a level can pair any parse (greedy / lazy depth via
179    /// `lazy_depth`) with any search backend here. Defaults to the
180    /// historical pairing (`strategy_tag.search()`) but is overridable
181    /// per level so the parse×search matrix can be swept and tuned.
182    pub(crate) search: crate::encoding::strategy::SearchMethod,
183    pub(crate) window_log: u8,
184    pub(crate) lazy_depth: u8,
185    /// Per-strategy tuning. Exactly one is `Some` on each level row, matching
186    /// `strategy_tag`'s backend, so the table self-documents which knobs a
187    /// level actually consumes (the others are `None`, not dead placeholders):
188    /// `fast` for the Fast/Simple backend, `dfast` for Double-Fast, `hc` for
189    /// the HashChain (lazy / btopt / btultra*) backend, `row` for the Row
190    /// (greedy L5) backend.
191    pub(crate) fast: Option<FastConfig>,
192    pub(crate) dfast: Option<DfastConfig>,
193    pub(crate) hc: Option<HcConfig>,
194    pub(crate) row: Option<RowConfig>,
195}
196
197impl LevelParams {
198    /// Backend family (storage variant) for the driver dispatcher.
199    /// Derived from the decoupled `search` axis so a level can route to
200    /// a different search backend than its `strategy_tag` historically
201    /// implied.
202    pub(crate) fn backend(&self) -> crate::encoding::strategy::BackendTag {
203        self.search.backend()
204    }
205
206    /// Parse mode derived from the decoupled `search` axis: the binary-tree
207    /// search path carries `ParseMode::Optimal`; every other search backend
208    /// derives greedy/lazy/lazy2 from `lazy_depth`. Reading `search` (not the
209    /// strategy tag) keeps the parse×search decoupling complete even when a
210    /// level whose tag is `Bt*` is overridden to a non-BT search backend.
211    pub(crate) fn parse(&self) -> crate::encoding::strategy::ParseMode {
212        match self.search {
213            crate::encoding::strategy::SearchMethod::BinaryTree => {
214                crate::encoding::strategy::ParseMode::Optimal
215            }
216            _ => crate::encoding::strategy::ParseMode::from_lazy_depth(self.lazy_depth),
217        }
218    }
219
220    /// Cheap fingerprint pre-splitter level (the `ZSTD_splitBlock` level;
221    /// `0` = from-borders heuristic, `1..=4` = byChunks with sampling tier
222    /// `level - 1`, rates 43 / 11 / 5 / 1). See [`pre_split_for`].
223    pub(crate) fn pre_split(&self) -> Option<u8> {
224        Some(pre_split_for(self.strategy_tag, self.lazy_depth))
225    }
226}
227
228/// The pre-splitter level for an effective strategy (the tag plus, for the
229/// collapsed `Lazy` tag, its lazy depth).
230///
231/// Upstream's default is `splitLevels[strategy] = {0,0,1,2,2,3,3,4,4,4}`
232/// (zstd_compress.c:4552, used as is; only an explicit `blockSplitterLevel`
233/// is shifted down by 2). It is followed up to lazy depth 1 — the finer
234/// sampling is a real ratio win on mixed data (decodecorpus at greedy/lazy:
235/// the borders tier compressed 4.6-4.9 % WORSE than upstream, the upstream
236/// rate-11 tier <= upstream) — but the lazy2/btlazy2 rate-5 and optimal-band
237/// rate-1 tiers are DELIBERATELY kept two steps coarser: on periodic input
238/// they over-split every block into tiny pieces exactly like upstream does
239/// (100 MiB of repeated log lines at L8-L12: 140,625 bytes and 3.6x the
240/// time upstream-tier, 9,742 bytes coarse — 14x better than upstream) while
241/// on real data they buy under 0.1 % (decodecorpus L8-L12: 170 bytes of
242/// 483 KiB). The drop-in contract asks for ratio <= upstream, not for
243/// upstream's block boundaries.
244pub(crate) fn pre_split_for(tag: crate::encoding::strategy::StrategyTag, lazy_depth: u8) -> u8 {
245    use crate::encoding::strategy::StrategyTag;
246    match tag {
247        // Upstream tiers: borders / byChunks rate 43 / rate 11.
248        StrategyTag::Fast => 0,
249        StrategyTag::Dfast => 1,
250        StrategyTag::Greedy => 2,
251        // lazy (depth 1) = upstream rate 11; lazy2 coarsened to rate 43.
252        StrategyTag::Lazy => {
253            if lazy_depth >= 2 {
254                1
255            } else {
256                2
257            }
258        }
259        StrategyTag::Btlazy2 => 1,
260        // Coarsened to byChunks rate 11 (upstream: rate 1).
261        StrategyTag::BtOpt | StrategyTag::BtUltra | StrategyTag::BtUltra2 => 2,
262    }
263}
264
265/// Apply the public-parameter per-knob overrides (#27) onto the
266/// level-resolved [`LevelParams`], in place. Runs in [`Matcher::reset`]
267/// after the level params are computed and before backend selection, so
268/// a strategy override re-routes the backend uniformly. An all-`None`
269/// override is a no-op the caller skips via
270/// [`crate::encoding::parameters::ParamOverrides::is_empty`], keeping the default
271/// level geometry byte-identical.
272pub(crate) fn apply_param_overrides(
273    params: &mut LevelParams,
274    ov: &crate::encoding::parameters::ParamOverrides,
275) {
276    use crate::encoding::strategy::SearchMethod;
277
278    // 1. Strategy override re-derives tag / search / lazy depth.
279    if let Some(strategy) = ov.strategy {
280        let tag = strategy.tag();
281        params.strategy_tag = tag;
282        params.search = tag.search();
283        params.lazy_depth = strategy.lazy_depth();
284    }
285
286    // 2. Ensure the active backend's config row exists (synthesize a
287    //    default when a strategy override moved off the native row).
288    match params.search {
289        SearchMethod::Fast => {
290            params.fast.get_or_insert(FAST_L1);
291        }
292        SearchMethod::DoubleFast => {
293            params.dfast.get_or_insert(DFAST_L3);
294        }
295        SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
296            // `ROW_L5` already carries `mls = ROW_MIN_MATCH_LEN = 5`, the
297            // upstream `minMatch` of the whole greedy..btlazy2 band at the
298            // >256 KiB tier, so a synthesized btlazy2 override hashes at the
299            // same width as a native btlazy2 row.
300            let row = params.row.get_or_insert(ROW_L5);
301            row.bt = matches!(params.search, SearchMethod::BinaryTreeLazy);
302        }
303        SearchMethod::HashChain | SearchMethod::BinaryTree => {
304            params.hc.get_or_insert(HC_OVERRIDE_DEFAULT);
305        }
306    }
307
308    // 3. window_log (bounds-checked at <= 30 by the builder).
309    if let Some(window_log) = ov.window_log {
310        params.window_log = window_log;
311    }
312
313    // 4. Per-backend numeric knobs map into the active config, mirroring
314    //    the upstream zstd `cParams` -> matcher translation documented on each
315    //    config struct.
316    match params.search {
317        SearchMethod::Fast => {
318            if let Some(fast) = params.fast.as_mut() {
319                if let Some(hash_log) = ov.hash_log {
320                    fast.hash_log = hash_log;
321                }
322                if let Some(min_match) = ov.min_match {
323                    fast.mls = min_match;
324                }
325            }
326        }
327        SearchMethod::DoubleFast => {
328            if let Some(dfast) = params.dfast.as_mut() {
329                // hashLog -> long table, chainLog -> short table (the
330                // dfast secondary index). Both bounds-checked <= 30, so
331                // the `u8` casts are lossless.
332                if let Some(hash_log) = ov.hash_log {
333                    dfast.long_hash_log = hash_log as u8;
334                }
335                if let Some(chain_log) = ov.chain_log {
336                    dfast.short_hash_log = chain_log as u8;
337                }
338            }
339        }
340        SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
341            if let Some(row) = params.row.as_mut() {
342                // Row hash-table width override (mirrors dfast `long_hash_log`
343                // / hc `hash_log`); `chain_log` sizes the hash chain the same
344                // backend searches on a <= 2^14 window, or its binary tree.
345                if let Some(hash_log) = ov.hash_log {
346                    row.hash_bits = hash_log as usize;
347                }
348                if let Some(chain_log) = ov.chain_log {
349                    row.chain_log = chain_log as usize;
350                }
351                if let Some(search_log) = ov.search_log {
352                    // Upstream zstd: rowLog = clamp(searchLog, 4, 6); the
353                    // compare budget stays the FULL `1 << searchLog`
354                    // (`nbAttempts`) — the chain walk and the tree walk
355                    // consume it directly, and the row probe bounds its own
356                    // budget by the row size at the search site.
357                    row.row_log = (search_log as usize).clamp(4, 6);
358                    row.search_depth = 1usize << search_log;
359                }
360                if let Some(target_length) = ov.target_length {
361                    row.target_len = target_length as usize;
362                }
363                if let Some(min_match) = ov.min_match {
364                    row.mls = min_match as usize;
365                }
366            }
367        }
368        SearchMethod::HashChain | SearchMethod::BinaryTree => {
369            if let Some(hc) = params.hc.as_mut() {
370                if let Some(hash_log) = ov.hash_log {
371                    hc.hash_log = hash_log as usize;
372                }
373                if let Some(chain_log) = ov.chain_log {
374                    hc.chain_log = chain_log as usize;
375                }
376                if let Some(search_log) = ov.search_log {
377                    hc.search_depth = 1usize << search_log;
378                }
379                if let Some(target_length) = ov.target_length {
380                    hc.target_len = target_length as usize;
381                }
382                if let Some(min_match) = ov.min_match {
383                    // BT finder hash width, derived from cParams.minMatch exactly
384                    // as upstream zstd: `mls = BOUNDED(3, cParams.minMatch, 6)`
385                    // (zstd_opt.c:896 ZSTD_selectBtGetAllMatches). minMatch=3
386                    // tiers hash on 3 bytes (btultra/btultra2 path). Only the BT
387                    // body reads `search_mls`; HC/lazy hash on 4 bytes regardless.
388                    hc.search_mls = (min_match as usize).clamp(3, 6);
389                }
390            }
391        }
392    }
393}
394
395/// Map the resolved runtime strategy to the upstream zstd LDM strategy ordinal
396/// (1..=9) that [`crate::encoding::ldm::params::LdmParams::adjust_for`] expects.
397/// The collapsed `Lazy` tag splits on `lazy_depth` (lazy = 4, lazy2 = 5).
398#[cfg(feature = "ldm")]
399pub(crate) fn ldm_strategy_ordinal(
400    tag: crate::encoding::strategy::StrategyTag,
401    lazy_depth: u8,
402) -> u32 {
403    use crate::encoding::strategy::StrategyTag;
404    match tag {
405        StrategyTag::Fast => 1,
406        StrategyTag::Dfast => 2,
407        StrategyTag::Greedy => 3,
408        StrategyTag::Lazy => {
409            if lazy_depth >= 2 {
410                5
411            } else {
412                4
413            }
414        }
415        // Upstream zstd `ZSTD_btlazy2` ordinal.
416        StrategyTag::Btlazy2 => 6,
417        StrategyTag::BtOpt => 7,
418        StrategyTag::BtUltra => 8,
419        StrategyTag::BtUltra2 => 9,
420    }
421}
422
423/// `ceil(log2(size))` of a source-size hint, with a zero hint floored to
424/// [`MIN_WINDOW_LOG`]. This is the single quantization every hint-dependent
425/// matcher parameter is derived from: the window-log cap, the HC / Fast hash
426/// and chain widths, the Dfast / Row table widths, the L22 config buckets, and
427/// the Fast attach-vs-copy cutoff. Two hints sharing this value resolve to the
428/// identical matcher shape, which is why it (not the raw byte count) keys the
429/// primed-dictionary snapshot — see [`PrimedKey`]. Operates on the full `u64`
430/// so callers comparing a hint against a cutoff get the same bucketed decision
431/// here and at the driver, with no `as usize` truncation on 32-bit targets.
432pub(crate) fn source_size_ceil_log(size: u64) -> u8 {
433    if size == 0 {
434        MIN_WINDOW_LOG
435    } else {
436        (64 - (size - 1).leading_zeros()) as u8
437    }
438}
439
440/// Attach-vs-copy cutoff for the Fast strategy, as a ceil-log bucket: a hint at
441/// or below `2^this` (or unknown, `None`) ATTACHES the dictionary (a separate
442/// immutable table scanned in place via the borrowed dual-base kernel); a larger
443/// hint would COPY it into the live table.
444///
445/// `13` is upstream zstd's Fast cutoff (`attachDictSizeCutoffs[ZSTD_fast]` is
446/// 8 KB, zstd_compress.c:2296; `ZSTD_shouldAttachDict`, :2309). Above it the
447/// dictionary is COPIED, and the copy is what makes the dictionary pay on a
448/// larger source: the scan then runs over a table already holding the
449/// dictionary's positions, so ordinary NEAR matches improve everywhere. Attach
450/// mode starts with an empty table and reaches the dictionary only through the
451/// separate exact table, at the positions the step happens to land on.
452///
453/// This was `31` (attach every source up to 2 GiB) on a speed argument alone,
454/// and the missing byte column is where it went wrong. Per frame, `z000033`
455/// (1,022,035 B) and its leading 10 KiB, with a 16 KiB dictionary trained over
456/// its 10 KiB chunks, on the i9: two prebuilt binaries and libzstd alternated
457/// in one session, `perf stat -r 3`, three rounds, ranges non-overlapping.
458///
459/// | case | bytes attach | bytes copy | reference | cycles attach | cycles copy | insn attach | insn copy |
460/// |---|---|---|---|---|---|---|---|
461/// | 10 KiB, L1 | 6,976 | 7,122 | 7,122 | 236,355 (1.95x) | 169,116 (1.39x) | 633,127 (1.78x) | 478,066 (1.34x) |
462/// | 10 KiB, L-5 | 9,660 | 9,124 | 9,130 | 51,678 (1.22x) | 56,444 (1.33x) | 152,281 (1.14x) | 153,369 (1.15x) |
463/// | 1 MiB, L1 | 550,810 | 551,584 | 570,765 | 19.84M (1.76x) | 16.21M (1.44x) | 54.01M (1.91x) | 39.60M (1.40x) |
464/// | 1 MiB, L-5 | 689,127 | 647,735 | 669,826 | 8.80M (1.46x) | 10.67M (1.77x) | 21.62M (1.54x) | 22.81M (1.63x) |
465///
466/// Copy is the better arm on both axes at the positive levels: it takes 18-28%
467/// fewer cycles and 22-27% fewer instructions, and its bytes are the
468/// reference's exactly on the small frame and 3.4% under the reference on the
469/// large one. At the ultra-fast levels it buys ratio with time: 21% more cycles
470/// on the 1 MiB frame for 6.0% fewer bytes, 9% more on the small one for 5.5%
471/// fewer. That trade is what the cutoff is for. Attach put us 2.9% ABOVE the
472/// reference on the 1 MiB ultra-fast frame — the dictionary made our frame
473/// bigger than our own no-dict frame there, while it made the reference's
474/// smaller — because it found 21,897 sequences where the reference finds
475/// 27,546. Copy puts us 3.3% under it.
476///
477/// The remaining gap is now a same-mode one: the reference does this copy in
478/// 1.0x where we take 1.3-1.8x, which is a target with an apples-to-apples
479/// reference rather than a mode the reference never runs.
480///
481/// The borrowed attach kernel stores virtual positions as `u32`
482/// (`cur_abs as u32`), so it could not attach past bucket `31` regardless; that
483/// ceiling is now far above the cutoff and no longer the binding constraint.
484/// Shared by `reset` (records the mode in the primed-snapshot key) and
485/// `prime_with_dictionary` (acts on it).
486pub(crate) const FAST_ATTACH_DICT_CUTOFF_LOG: u8 = 13;
487
488/// Largest dictionary region (bytes) the Fast attach path can index. The tagged
489/// dict table packs each position into `32 - DICT_TAG_BITS` (= 24) bits, so a
490/// region past `2^24` (16 MiB) would overflow the packed position. Dictionaries
491/// this large fall back to COPY mode, whose live table stores full `u32`
492/// positions and handles them. The size hint set on dict load equals the actual
493/// dict content length, so the attach-vs-copy decision (and the matching
494/// snapshot-key / epoch bits) can gate on it consistently at reset time.
495pub(crate) const MAX_FAST_ATTACH_DICT_REGION: usize = 1 << 24;
496
497/// Dfast counterpart of [`FAST_ATTACH_DICT_CUTOFF_LOG`]: upstream zstd
498/// `ZSTD_dictMatchState` attach cutoff for the double-fast strategy is 16 KiB
499/// (`2^14`), so small / unknown-size inputs ATTACH (separate immutable dict
500/// long+short tables + dual-probe in `start_matching_fast_loop`) and larger
501/// known-size inputs COPY (re-prime the dict into the live tables, where the
502/// dense scan matches it as window history). The attach build also self-gates
503/// on `use_fast_loop` inside `skip_matching_for_dict_attach` — only the
504/// fast-loop levels (L3 / Default / L0) carry the dual-probe.
505pub(crate) const DFAST_ATTACH_DICT_CUTOFF_LOG: u8 = 14;
506
507/// 32 KiB (`2^15`, upstream zstd `attachDictSizeCutoffs[ZSTD_lazy2]`): small /
508/// unknown-size inputs ATTACH the dict as a separate hash-chain dms (the dual
509/// search in `find_best_match` walks the live input chain + the dms), larger
510/// known-size inputs dense-COPY (merge the dict into the live chain and search
511/// the one combined chain).
512pub(crate) const HC_ATTACH_DICT_CUTOFF_LOG: u8 = 15;
513
514/// BT/optimal attach cutoff for `btlazy2` + `btopt`: 32 KiB (`2^15`, upstream
515/// zstd `attachDictSizeCutoffs[ZSTD_btlazy2]` == `[ZSTD_btopt]`). Small /
516/// unknown-size inputs ATTACH the dict as a separate DUBT dms; larger known-size
517/// inputs COPY the dict into the LIVE binary tree (upstream zstd
518/// `ZSTD_resetCCtx_byCopyingCDict`).
519pub(crate) const BT_OPT_ATTACH_DICT_CUTOFF_LOG: u8 = 15;
520
521/// BT/optimal attach cutoff for `btultra` + `btultra2`: 8 KiB (`2^13`, upstream
522/// zstd `attachDictSizeCutoffs[ZSTD_btultra]` == `[ZSTD_btultra2]`). The deepest
523/// parses copy the dict into the live tree past a much smaller source than the
524/// `btopt` tier, matching upstream's per-strategy cutoff table.
525pub(crate) const BT_ULTRA_ATTACH_DICT_CUTOFF_LOG: u8 = 13;
526
527// Source-size cap for the dfast hash bits when a size hint is present: a tiny
528// input needs no larger hash than its window. The upstream zstd `cParams.hashLog` /
529// `chainLog` (from `DfastConfig`) caps it from above at the call site.
530pub(crate) fn dfast_hash_bits_for_window(max_window_size: usize) -> usize {
531    let window_log = (usize::BITS - 1 - max_window_size.leading_zeros()) as usize;
532    window_log.max(MIN_WINDOW_LOG as usize)
533}
534
535pub(crate) fn row_hash_bits_for_window(max_window_size: usize) -> usize {
536    // Upstream zstd `ZSTD_adjustCParams_internal` cap: `hashLog <= windowLog + 1`.
537    // The `+ 1` is load-bearing for L12, whose upstream zstd hashLog (23) exceeds
538    // its windowLog (22) — a plain `windowLog` cap would shrink the L12
539    // table on EVERY hinted reset and split primed snapshots between
540    // hinted and unhinted frames that resolve to the identical geometry.
541    // No constant upper clamp: the old `ROW_HASH_BITS` (20) ceiling
542    // predates the lazy band moving onto Row (L9-12 carry upstream zstd hashLog
543    // 21-23).
544    let window_log = (usize::BITS - 1 - max_window_size.leading_zeros()) as usize;
545    (window_log + 1).max(MIN_WINDOW_LOG as usize)
546}
547
548/// `floor(log2(window))` for the HashChain table-log cap (upstream zstd
549/// `ZSTD_adjustCParams_internal`). The caller clamps the level's `hash_log` /
550/// `chain_log` from above with this so a small hinted input doesn't allocate the
551/// full level's tables.
552pub(crate) fn hc_hash_bits_for_window(max_window_size: usize) -> usize {
553    let window_log = (usize::BITS - 1 - max_window_size.leading_zeros()) as usize;
554    window_log.max(MIN_WINDOW_LOG as usize)
555}
556
557/// Smallest window_log the encoder will use regardless of source size.
558pub(crate) const MIN_WINDOW_LOG: u8 = 10;
559
560/// Largest window_log the public parameter API accepts
561/// ([`CParameter::WindowLog`](crate::encoding::CParameter)'s upper bound), and
562/// so the largest a workspace estimate can be asked to describe. The estimate
563/// answers for whatever it is given, and shifting by more than the width of a
564/// `usize` is undefined, so a request beyond this is answered with this.
565pub(crate) const MAX_ESTIMATED_WINDOW_LOG: u8 = 30;
566
567/// Translate a verbatim upstream `ZSTD_defaultCParameters[tier][level]` row
568/// (`cparams::CParams`) into our resolved [`LevelParams`], reproducing
569/// upstream's cParams -> matcher-config derivation so the encoder follows C's
570/// source-size-tiered STRATEGY + table widths rather than a single hand-tuned
571/// `LEVEL_TABLE`. Derivation (verified against L6/L16/L22 vs clevels.h):
572/// `search_depth = 1 << searchLog`; row `row_log = clamp(searchLog, 4, 6)`; the
573/// per-strategy sub-config carries the verbatim `hashLog` / `chainLog` /
574/// `targetLength` / `minMatch`. Strategy numbers are upstream `ZSTD_strategy`
575/// (fast=1, dfast=2, greedy=3, lazy=4, lazy2=5, btlazy2=6, btopt=7, btultra=8,
576/// btultra2=9).
577fn level_params_from_cparams(cp: crate::encoding::cparams::CParams) -> LevelParams {
578    use crate::encoding::strategy::{SearchMethod, StrategyTag};
579    let window_log = cp.window_log as u8;
580    let search_depth = 1usize << cp.search_log;
581    let target_len = cp.target_length as usize;
582    let hc = HcConfig {
583        hash_log: cp.hash_log as usize,
584        chain_log: cp.chain_log as usize,
585        search_depth,
586        target_len,
587        // Clamp UP to 4: C's BT finder uses mls=3 on L18-22, but our optimal
588        // parser diverges on the resulting 3-byte matches (breaks level-22
589        // sequence parity), so we keep the finder at >=4 as a workaround until
590        // the parser is C-faithful at minMatch 3. See `HcConfig::search_mls` (#337).
591        search_mls: cp.min_match.clamp(4, 6) as usize,
592    };
593    let row = RowConfig {
594        hash_bits: cp.hash_log as usize,
595        row_log: cp.search_log.clamp(4, 6) as usize,
596        search_depth,
597        target_len,
598        mls: cp.min_match as usize,
599        chain_log: cp.chain_log as usize,
600        // Upstream `ZSTD_btlazy2` (strategy 6).
601        bt: cp.strategy == 6,
602    };
603    let bt = |tag| LevelParams {
604        strategy_tag: tag,
605        search: SearchMethod::BinaryTree,
606        window_log,
607        lazy_depth: 2,
608        fast: None,
609        dfast: None,
610        hc: Some(hc),
611        row: None,
612    };
613    let row_lvl = |tag, search, lazy_depth| LevelParams {
614        strategy_tag: tag,
615        search,
616        window_log,
617        lazy_depth,
618        fast: None,
619        dfast: None,
620        hc: None,
621        row: Some(row),
622    };
623    match cp.strategy {
624        1 => LevelParams {
625            strategy_tag: StrategyTag::Fast,
626            search: SearchMethod::Fast,
627            window_log,
628            lazy_depth: 0,
629            // Upstream fast `stepSize`: `targetLength + 1` (0 -> 1, so step 2).
630            fast: Some(FastConfig {
631                hash_log: cp.hash_log,
632                mls: cp.min_match,
633                step_size: target_len.max(1) + 1,
634            }),
635            dfast: None,
636            hc: None,
637            row: None,
638        },
639        2 => LevelParams {
640            strategy_tag: StrategyTag::Dfast,
641            search: SearchMethod::DoubleFast,
642            window_log,
643            lazy_depth: 1,
644            fast: None,
645            dfast: Some(DfastConfig {
646                long_hash_log: cp.hash_log as u8,
647                short_hash_log: cp.chain_log as u8,
648            }),
649            hc: None,
650            row: None,
651        },
652        3 => row_lvl(StrategyTag::Greedy, SearchMethod::RowHash, 0),
653        4 => row_lvl(StrategyTag::Lazy, SearchMethod::RowHash, 1),
654        5 => row_lvl(StrategyTag::Lazy, SearchMethod::RowHash, 2),
655        // btlazy2: the same lazy2 parse over the lazily-sorted binary tree.
656        6 => row_lvl(StrategyTag::Btlazy2, SearchMethod::BinaryTreeLazy, 2),
657        7 => bt(StrategyTag::BtOpt),
658        8 => bt(StrategyTag::BtUltra),
659        _ => bt(StrategyTag::BtUltra2),
660    }
661}
662
663/// Down-size a synthesized backend's window / hash / chain logs for a known
664/// source size by routing through the single C-faithful adjuster
665/// [`adjust_cparams`](crate::encoding::cparams::adjust_cparams)
666/// (`ZSTD_adjustCParams_internal`).
667///
668/// Used only on the param-override re-cap path: [`apply_param_overrides`]
669/// synthesizes a backend's full-size default config when a strategy override
670/// moves off the native level row, and this re-applies the source-size cap
671/// C-faithfully — the SAME adjuster the `get_cparams` main path uses, so the
672/// override path and the level path now down-size identically (no extra hinted
673/// 16 KiB window floor, no per-backend headroom that diverged from C). The
674/// Dfast backend self-sizes its tables in `reset`, so only its window is capped.
675pub(crate) fn adjust_params_for_source_size(mut params: LevelParams, src_size: u64) -> LevelParams {
676    use crate::encoding::cparams::{CParams, adjust_cparams};
677    use crate::encoding::strategy::{BackendTag, StrategyTag};
678
679    let backend = params.backend();
680    // Lift the active backend's source-cappable logs into a flat CParams. Dfast
681    // contributes none (window-only); its table widths self-size in `reset`.
682    let (hash_log, chain_log): (u32, u32) = match backend {
683        BackendTag::Simple => (params.fast.as_ref().map_or(0, |f| f.hash_log), 0),
684        BackendTag::HashChain => params
685            .hc
686            .as_ref()
687            .map_or((0, 0), |h| (h.hash_log as u32, h.chain_log as u32)),
688        BackendTag::Row => params
689            .row
690            .as_ref()
691            .map_or((0, 0), |r| (r.hash_bits as u32, r.chain_log as u32)),
692        BackendTag::Dfast => (0, 0),
693    };
694    // The chain cap (`ZSTD_cycleLog`) reads only `strategy >= btlazy2(6)`, so a
695    // coarse 6/3 split is exact for it; `adjust_cparams`'s other strategy use
696    // (`cdict_indices_are_tagged`) is gated on `create_cdict = false` here.
697    let strategy = if matches!(
698        params.strategy_tag,
699        StrategyTag::Btlazy2 | StrategyTag::BtOpt | StrategyTag::BtUltra | StrategyTag::BtUltra2
700    ) {
701        6
702    } else {
703        3
704    };
705    let adj = adjust_cparams(
706        CParams {
707            window_log: u32::from(params.window_log),
708            chain_log,
709            hash_log,
710            search_log: 1,
711            min_match: 4,
712            target_length: 0,
713            strategy,
714        },
715        src_size,
716        0,
717        false,
718    );
719    params.window_log = adj.window_log as u8;
720    match backend {
721        BackendTag::Simple => {
722            if let Some(f) = params.fast.as_mut() {
723                f.hash_log = adj.hash_log;
724            }
725        }
726        BackendTag::HashChain => {
727            if let Some(h) = params.hc.as_mut() {
728                h.hash_log = adj.hash_log as usize;
729                h.chain_log = adj.chain_log as usize;
730            }
731        }
732        BackendTag::Row => {
733            if let Some(r) = params.row.as_mut() {
734                r.hash_bits = adj.hash_log as usize;
735                r.chain_log = adj.chain_log as usize;
736            }
737        }
738        BackendTag::Dfast => {}
739    }
740    params
741}
742
743/// Estimated steady-state heap footprint of a one-shot compression context
744/// at `level` (window history + match-finder tables + block staging), in
745/// bytes. Computed from the same per-level tuning table the encoder
746/// resolves at frame start, so the estimate tracks the real allocations;
747/// it is an upper-bound style budget figure, not an exact accounting.
748pub fn estimated_compression_workspace_bytes(level: CompressionLevel) -> usize {
749    estimated_compression_workspace_bytes_for_source(level, None)
750}
751
752/// The same estimate for a source whose size is known.
753///
754/// The window and the match-finder tables are capped by the source, so a level
755/// that would reserve hundreds of MiB for an arbitrary stream reserves a
756/// fraction of that for a small one — and a caller budgeting memory for a
757/// compression it is about to run knows which. `None` is the arbitrary-stream
758/// figure that [`estimated_compression_workspace_bytes`] reports.
759pub fn estimated_compression_workspace_bytes_for_source(
760    level: CompressionLevel,
761    src_size_hint: Option<u64>,
762) -> usize {
763    estimated_compression_workspace_bytes_for_run(level, src_size_hint, None, false, None)
764}
765
766/// The same estimate for a run whose window, long-distance matching and
767/// dictionary are what the caller has actually asked for.
768///
769/// A `window_log` override enlarges the history the frame keeps, and
770/// long-distance matching adds a hash table of its own on top — neither of them
771/// visible in the level's own preset. A dictionary goes further than adding to
772/// the figure: it *decides* it. The frame runs the dictionary's own compression
773/// parameters, so a small source compressed against a large dictionary builds
774/// tables sized for the dictionary, which at the higher levels is the
775/// difference between tens of KiB and hundreds of MiB. `None`, `false` and
776/// `None` give the preset, which is what
777/// [`estimated_compression_workspace_bytes_for_source`] reports.
778///
779/// `dictionary` is what a caller weighing a run before it parses the blob can
780/// answer with [`DictionarySizes::raw_content`] on the blob's own length: the
781/// content of a trained dictionary is smaller than the blob it came in, and
782/// overstating it can only move the estimate toward the copy-mode geometry,
783/// which is the larger of the two.
784///
785/// [`DictionarySizes::raw_content`]: crate::encoding::DictionarySizes::raw_content
786pub fn estimated_compression_workspace_bytes_for_run(
787    level: CompressionLevel,
788    src_size_hint: Option<u64>,
789    window_log: Option<u8>,
790    long_distance_matching: bool,
791    dictionary: Option<crate::encoding::DictionarySizes>,
792) -> usize {
793    use crate::encoding::strategy::StrategyTag;
794    let mut params = match dictionary.filter(|sizes| sizes.content != 0) {
795        Some(sizes) => resolve_level_params_with_dict(level, src_size_hint, sizes).0,
796        None => resolve_level_params(level, src_size_hint),
797    };
798    // The override is what the frame will keep, but never below the floor the
799    // format sets or above what the source can fill — the same two bounds the
800    // encoder applies to it.
801    if let Some(requested) = window_log {
802        // Bounded to what the encoder itself accepts before anything shifts by
803        // it. This answers for whatever it is asked, and a shift past the width
804        // of the type is undefined rather than merely large: the largest window
805        // there is, is the honest answer to a request beyond it.
806        let requested = requested.min(MAX_ESTIMATED_WINDOW_LOG);
807        let capped = match src_size_hint {
808            Some(src) => {
809                crate::encoding::cparams::adjusted_window_log(u32::from(requested), src, 0) as u8
810            }
811            None => requested,
812        };
813        params.window_log = capped.clamp(MIN_WINDOW_LOG, MAX_ESTIMATED_WINDOW_LOG);
814    }
815    // The long-distance matcher's own table, sized from the window it searches
816    // (upstream `ZSTD_ldm_adjustParameters`). Only the `ldm` build has one.
817    #[cfg(feature = "ldm")]
818    let ldm = if long_distance_matching {
819        let strategy = ldm_strategy_ordinal(params.strategy_tag, params.lazy_depth);
820        let ldm_params = crate::encoding::ldm::params::LdmParams::adjust_for(
821            u32::from(params.window_log),
822            strategy,
823        );
824        crate::encoding::ldm::table::LdmHashTable::estimated_workspace_bytes(
825            ldm_params.hash_log,
826            ldm_params.bucket_size_log,
827        )
828    } else {
829        0
830    };
831    #[cfg(not(feature = "ldm"))]
832    let ldm = {
833        let _ = long_distance_matching;
834        0
835    };
836    // A 30-bit window is a gibibyte, which a 32-bit `usize` cannot count: the
837    // widest window is more memory than such a machine has, so the figure is
838    // pinned rather than wrapped.
839    let window = 1usize
840        .checked_shl(u32::from(params.window_log))
841        .unwrap_or(usize::MAX);
842    // Mirror `configure()`: the HC3 short-match side table exists only on
843    // the btultra/btultra2 tags (minMatch 3), capped by the window log; the
844    // BT pointer-pair layout fits inside the `4 << chain_log` chain term
845    // (pairs over `chain_log - 1` nodes).
846    let wants_hash3 = matches!(
847        params.strategy_tag,
848        StrategyTag::BtUltra | StrategyTag::BtUltra2
849    );
850    let uses_bt = matches!(
851        params.strategy_tag,
852        StrategyTag::BtOpt | StrategyTag::BtUltra | StrategyTag::BtUltra2
853    );
854    // The lazy backend's chain / tree finders (window <= 2^14, or a btlazy2
855    // level) use a plain hash table (`4 << hash_bits`) plus the chain / tree
856    // table (`4 << chain_log`) instead of the row tables.
857    let row_chain = params
858        .row
859        .filter(|r| r.bt || params.window_log <= 14)
860        .map_or(0, |r| (4usize << r.hash_bits) + (4usize << r.chain_log));
861    let tables = params.fast.map(|f| 4usize << f.hash_log).unwrap_or(0)
862        + row_chain
863        + params
864            .dfast
865            .map(|d| (4usize << d.long_hash_log) + (4usize << d.short_hash_log))
866            .unwrap_or(0)
867        + params
868            .hc
869            .map(|h| {
870                let hash3 = if wants_hash3 {
871                    4usize
872                        << crate::encoding::match_table::storage::HC3_HASH_LOG
873                            .min(params.window_log as usize)
874                } else {
875                    0
876                };
877                (4usize << h.hash_log) + (4usize << h.chain_log) + hash3
878            })
879            .unwrap_or(0)
880        + params
881            .row
882            .filter(|r| !(r.bt || params.window_log <= 14))
883            .map(|r| (4usize << r.hash_bits) + (2usize << r.hash_bits))
884            .unwrap_or(0);
885    // BT modes box a `BtMatcher`; its retained scratch layout is budgeted
886    // next to the struct so estimator and allocator evolve together.
887    let bt = if uses_bt {
888        crate::encoding::bt::BtMatcher::estimated_workspace_bytes()
889    } else {
890        0
891    };
892    // Block staging: literal + sequence buffers plus the compressed-block
893    // scratch, each bounded by the 128 KiB block size.
894    let staging = 3 * (128 * 1024);
895    // Saturating: the parts are each bounded, but their sum at the widest
896    // window is more than a 32-bit `usize` counts, and a total that wrapped
897    // would report a run as fitting a limit it cannot.
898    window
899        .saturating_add(tables)
900        .saturating_add(bt)
901        .saturating_add(staging)
902        .saturating_add(ldm)
903}
904
905/// Extra steady-state workspace the optimal strategies (ordinals 7..=9,
906/// btopt..btultra2) retain beyond the hash/chain tables: the boxed matcher
907/// plus its scratch arenas, and the HC3 short-match side table for
908/// btultra/btultra2 (capped by the window log). 0 for the other ordinals
909/// (btlazy2's tree lives in the lazy backend's chain table).
910pub fn estimated_bt_strategy_extra_bytes(strategy_ordinal: u32, window_log: u32) -> usize {
911    if !(7..=9).contains(&strategy_ordinal) {
912        return 0;
913    }
914    let hash3 = if matches!(strategy_ordinal, 8 | 9) {
915        4usize << crate::encoding::match_table::storage::HC3_HASH_LOG.min(window_log as usize)
916    } else {
917        0
918    };
919    crate::encoding::bt::BtMatcher::estimated_workspace_bytes() + hash3
920}
921
922/// Resolve a [`CompressionLevel`] (+ optional source-size hint) to the
923/// concrete [`LevelParams`] the matcher runs: strategy tag, search method
924/// (match-finder), window log, and per-backend config.
925///
926/// ## CRITICAL: input size changes the match-finder (and can change strategy)
927///
928/// The resolved geometry is a function of the SOURCE SIZE, not the level
929/// alone. This is the easy-to-miss part (so read this before assuming a level
930/// maps to one fixed match-finder). It mirrors three upstream zstd stages:
931///
932/// 1. [`LEVEL_TABLE`] holds the tier-0 (source > 256 KiB) base row per level
933///    (upstream `ZSTD_defaultCParameters[0]`). L6-L12 carry
934///    `SearchMethod::RowHash` (the Row match-finder), like upstream's
935///    greedy/lazy default.
936/// 2. [`apply_cparams_tier`] overrides the table-shaping widths for the
937///    smaller source tiers (upstream `ZSTD_getCParams_internal` tier table).
938///    NOTE: upstream ALSO switches STRATEGY in some tiers (L2 → dfast, L4 →
939///    greedy on small sources); those backend switches are NOT yet replicated,
940///    so those levels keep their base strategy on small inputs.
941/// 3. [`adjust_params_for_source_size`] caps `window_log` to
942///    ~`ceil_log2(source_size)` (upstream `ZSTD_adjustCParams_internal`).
943///
944/// THEN, inside the Row backend, the greedy/lazy band searches a hash chain
945/// instead of rows when the resolved `window_log <= 14`
946/// (`RowMatchGenerator::finder`) — exactly upstream's
947/// `ZSTD_resolveRowMatchFinderMode` (the Row match-finder is used for
948/// greedy/lazy/lazy2 ONLY when `windowLog > 14`) — and a btlazy2 level
949/// searches the lazily-sorted binary tree; the parse itself is the same
950/// `lazy_generic` body in all three cases. Net effect for the SAME level:
951///
952/// * small input (e.g. a 10 KiB fixture → `window_log` 14) → hash chain
953///   (`ZSTD_HcFindBestMatch`, scalar chain walk);
954/// * large input (e.g. 1 MiB → `window_log` 20) → rows (the SIMD-tag
955///   row match-finder).
956///
957/// A dictionary frame resolves through [`resolve_level_params_with_dict`]
958/// instead: the CDict's cParams (its own size tier) with the frame's
959/// source-derived `window_log`. When comparing against C on a fixture,
960/// resolve the match-finder from the fixture's size (and dictionary) first,
961/// or you may optimise/benchmark a path C does not even take for that input.
962pub(crate) fn resolve_level_params(
963    level: CompressionLevel,
964    source_size: Option<u64>,
965) -> LevelParams {
966    // Uncompressed = raw blocks, no match-finder. Not a cParams level, so it is
967    // the one row resolved by hand rather than through `get_cparams`.
968    if matches!(level, CompressionLevel::Uncompressed) {
969        return LevelParams {
970            strategy_tag: crate::encoding::strategy::StrategyTag::Fast,
971            search: crate::encoding::strategy::SearchMethod::Fast,
972            // Raw frames emit literal blocks and never reference history;
973            // advertising a wider window only inflates the decoder-side buffer
974            // reservation, so clamp to 17 (128 KiB) regardless of input size.
975            window_log: 17,
976            lazy_depth: 0,
977            // Beyond-upstream: hash_log=14 (vs upstream's row-0 13) for ~2× fewer
978            // collisions on structured corpora; mls=6 / step_size=2 mirror the
979            // upstream "base for negative" row (targetLength=1 -> step 2).
980            fast: Some(FastConfig {
981                hash_log: 14,
982                mls: 6,
983                step_size: 2,
984            }),
985            dfast: None,
986            hc: None,
987            row: None,
988        };
989    }
990    // Every other level resolves through the SINGLE C-faithful cParams source,
991    // `cparams::get_cparams` (the port of `ZSTD_getCParams`). One place selects
992    // strategy + table widths + the negative-level acceleration per
993    // (level, srcSize) + the source-size window/hash down-clamp, so the encoder
994    // never re-derives parameters from a parallel hand-tuned path. Named presets
995    // map to their numeric level; the cParams source clamps out-of-range levels
996    // (>22 to 22, negatives to MIN_CLEVEL) itself.
997    let numeric = numeric_level(level);
998    let src = source_size.unwrap_or(crate::encoding::cparams::CONTENTSIZE_UNKNOWN);
999    level_params_from_cparams(crate::encoding::cparams::get_cparams(numeric, src, 0))
1000}
1001
1002/// The upstream numeric level a preset maps to.
1003pub(crate) fn numeric_level(level: CompressionLevel) -> i32 {
1004    match level {
1005        CompressionLevel::Uncompressed => unreachable!("raw frames resolve no cParams"),
1006        // Fastest = upstream level 1 (fast strategy, smallest real-compression
1007        // tables).
1008        CompressionLevel::Fastest => 1,
1009        // Default = upstream level 3 (the libzstd default).
1010        CompressionLevel::Default => CompressionLevel::DEFAULT_LEVEL,
1011        // Better = level 7: the lazy2 band — clearly above the fast/dfast levels
1012        // on ratio while still well under the binary-tree cost cliff.
1013        CompressionLevel::Better => 7,
1014        // Best = level 13: the first point of the deep binary-tree band that
1015        // strictly dominates every level below it on ratio (lower levels can tie
1016        // on window-bound corpora), so the alias sits on a config that always
1017        // wins rather than on a hair-thin margin.
1018        CompressionLevel::Best => 13,
1019        CompressionLevel::Level(n) => n,
1020    }
1021}
1022
1023/// How a greedy / lazy frame compressed with a dictionary takes its
1024/// match-finder from the dictionary's own cParams (upstream
1025/// `ZSTD_resetCCtx_usingCDict`).
1026#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1027pub(crate) struct RowDictPlan {
1028    /// `ZSTD_shouldAttachDict`: the dictionary tables are searched in place
1029    /// (`dictMatchState`) instead of being copied into the frame's tables.
1030    pub(crate) attach: bool,
1031    /// The CDict's `useRowMatchFinder`, inherited by the frame.
1032    pub(crate) use_row: bool,
1033    /// The CDict's cParams: the geometry (`hash_log`, `chain_log`,
1034    /// `search_log` → row width) and key width its tables were built with.
1035    pub(crate) cdict: crate::encoding::cparams::CParams,
1036}
1037
1038/// [`resolve_level_params`] for a frame that compresses with a dictionary of
1039/// `dict_size` bytes. Upstream builds the CDict with
1040/// `ZSTD_getCParams(level, UNKNOWN, dictSize, createCDict)` and the frame
1041/// then runs the CDict's strategy / widths / search depth / match-finder:
1042/// re-adjusted to the source when the dictionary is attached
1043/// (`ZSTD_resetCCtx_byAttachingCDict`), verbatim when it is copied
1044/// (`ZSTD_resetCCtx_byCopyingCDict`); only the frame's own `windowLog` is
1045/// kept. The CDict's strategy is taken whatever backend family the plain
1046/// level resolved to; a lazy-band CDict (greedy..btlazy2) also carries the
1047/// lazy backend's [`RowDictPlan`].
1048pub(crate) fn resolve_level_params_with_dict(
1049    level: CompressionLevel,
1050    source_size: Option<u64>,
1051    sizes: crate::encoding::DictionarySizes,
1052) -> (LevelParams, Option<RowDictPlan>) {
1053    use crate::encoding::cparams::{
1054        CONTENTSIZE_UNKNOWN, attach_cparams, copy_cparams, get_cdict_cparams, should_attach_dict,
1055        uses_row_match_finder,
1056    };
1057    let base = resolve_level_params(level, source_size);
1058    if sizes.content == 0 {
1059        return (base, None);
1060    }
1061    // The CDict's cParams decide the frame's strategy REGARDLESS of the
1062    // backend family the plain level resolved to for this source size
1063    // (upstream takes them unconditionally): L13 on a 4 KiB source is
1064    // btopt, but a 300 KiB CDict is btlazy2 and the frame runs btlazy2; L4
1065    // on a 1 MiB source is dfast, but a 4 KiB CDict is greedy. Only the
1066    // frame's own `windowLog` is kept.
1067    let cdict = get_cdict_cparams(numeric_level(level), sizes.serialized);
1068    // `ZSTD_shouldAttachDict`, bounded by the backend's attach representability:
1069    // the Fast / Dfast attached tables pack the dict position next to a tag, so
1070    // they index at most 2^24 content bytes. A larger dictionary is primed in
1071    // COPY mode, and the frame must then run the CDict's verbatim table
1072    // geometry (`byCopyingCDict`) — copying it into source-capped attach-mode
1073    // tables would collide away its matches.
1074    let attach_fits = match cdict.strategy {
1075        1 => sizes.content <= MAX_FAST_ATTACH_DICT_REGION,
1076        2 => sizes.content <= crate::encoding::dfast::DFAST_ATTACH_DICT_MAX_LEN,
1077        _ => true,
1078    };
1079    let attach = should_attach_dict(&cdict, source_size) && attach_fits;
1080    let window_log = u32::from(base.window_log);
1081    let frame = if attach {
1082        attach_cparams(
1083            cdict,
1084            source_size.unwrap_or(CONTENTSIZE_UNKNOWN),
1085            window_log,
1086        )
1087    } else {
1088        copy_cparams(cdict, window_log)
1089    };
1090    let params = level_params_from_cparams(frame);
1091    if !(3..=6).contains(&cdict.strategy) {
1092        // Fast / dfast / optimal strategies: their backends prime the
1093        // dictionary themselves; no lazy-backend plan.
1094        return (params, None);
1095    }
1096    (
1097        params,
1098        Some(RowDictPlan {
1099            attach,
1100            use_row: uses_row_match_finder(&cdict),
1101            cdict,
1102        }),
1103    )
1104}
1105
1106/// The cheap fingerprint pre-splitter level for a compression level (the
1107/// C-like `blockSplitterLevel`), resolved through the same per-level
1108/// `LevelParams` table as every other tuning knob. `None` keeps the whole
1109/// 128 KiB block. The frame loop reads this instead of hardcoding the
1110/// level→split mapping at the call site.
1111pub(crate) fn level_pre_split(level: CompressionLevel) -> Option<usize> {
1112    // Resolve through `resolve_level_params` directly — NOT via the legacy
1113    // `numeric_level()` alias — so named presets read the SAME table row as
1114    // every other tuning knob (`Best` maps to its own row there, which is
1115    // not the row its numeric alias points at). `Uncompressed` (raw
1116    // blocks) never splits.
1117    if matches!(level, CompressionLevel::Uncompressed) {
1118        return None;
1119    }
1120    resolve_level_params(level, None)
1121        .pre_split()
1122        .map(usize::from)
1123}
1124
1125#[cfg(test)]
1126mod tests;