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 /// Key width the binary tree hashes. A level's own `minMatch` is clamped to
26 /// `4..=6`: upstream templates its finder on `mls = BOUNDED(3, minMatch, 6)`
27 /// (`ZSTD_selectBtGetAllMatches`, zstd_opt.c), but its `ZSTD_hashPtr` has no
28 /// 3-byte case and hashes `mls = 3` on four bytes (the `default` arm,
29 /// zstd_compress_internal.h), taking 3-byte matches from the hash3 table.
30 /// A `minMatch` of 3 set explicitly keys the tree on three bytes instead:
31 /// here only btultra and btultra2 search the hash3 table, and on btopt a
32 /// 4-byte key would leave no source for the short matches the knob asks for
33 /// (z000033 at level 16 with `minMatch` 3: 443,830 bytes against 428,164).
34 /// Only the BT body reads it; HC / lazy levels keep it at 4.
35 pub(crate) search_mls: usize,
36}
37
38#[derive(Copy, Clone, PartialEq, Eq)]
39pub(crate) struct RowConfig {
40 pub(crate) hash_bits: usize,
41 pub(crate) row_log: usize,
42 pub(crate) search_depth: usize,
43 pub(crate) target_len: usize,
44 /// Upstream zstd `cParams.minMatch` for the row matcher: the regular-search
45 /// acceptance floor (a row candidate must extend to >= `mls` bytes).
46 /// The C-like advanced API surfaces this as the row min-match knob.
47 /// `ROW_MIN_MATCH_LEN` (5) is the default; the row hash key width stays
48 /// 4 bytes (an internal detail), so this only tunes the acceptance
49 /// floor, not the candidate hash distribution.
50 pub(crate) mls: usize,
51 /// Upstream `cParams.chainLog`: the hash-chain table the greedy/lazy
52 /// parse searches instead of rows when the window is 2^14 or smaller
53 /// (upstream `ZSTD_resolveRowMatchFinderMode`), or the binary tree
54 /// (`2^(chainLog-1)` nodes) of a btlazy2 level.
55 pub(crate) chain_log: usize,
56 /// Upstream `ZSTD_btlazy2`: the lazy parse searches the lazily-sorted
57 /// binary tree (`ZSTD_BtFindBestMatch`) instead of rows / the chain.
58 pub(crate) bt: bool,
59}
60
61// Only used as the default HashChain config when the test-only parse×search
62// override pairs a level with a backend its native row doesn't populate.
63#[cfg(test)]
64pub(crate) const HC_CONFIG: HcConfig = HcConfig {
65 hash_log: HC_HASH_LOG,
66 chain_log: HC_CHAIN_LOG,
67 search_depth: HC_SEARCH_DEPTH,
68 target_len: HC_TARGET_LEN,
69 search_mls: 4,
70};
71
72/// Base HashChain config synthesized when a public-parameter strategy
73/// override ([`crate::encoding::parameters`]) routes a level to the HC / BT
74/// backend whose native level row didn't populate `hc` (e.g. forcing
75/// `Strategy::Lazy2` onto a level the table resolves to Fast). Mirrors
76/// the mid-band lazy defaults; the per-knob overrides then refine it.
77pub(crate) const HC_OVERRIDE_DEFAULT: HcConfig = HcConfig {
78 hash_log: crate::encoding::match_table::storage::HC_HASH_LOG,
79 chain_log: crate::encoding::match_table::storage::HC_CHAIN_LOG,
80 search_depth: HC_SEARCH_DEPTH,
81 target_len: HC_TARGET_LEN,
82 search_mls: 4,
83};
84
85// Default Row config: only used by tests and the test-only parse×search
86// override (production greedy L5 carries its own `ROW_L5`).
87#[cfg(test)]
88pub(crate) const ROW_CONFIG: RowConfig = RowConfig {
89 hash_bits: ROW_HASH_BITS,
90 row_log: ROW_LOG,
91 search_depth: ROW_SEARCH_DEPTH,
92 target_len: ROW_TARGET_LEN,
93 mls: ROW_MIN_MATCH_LEN,
94 chain_log: ROW_HASH_BITS,
95 bt: false,
96};
97
98// Level-5 greedy is the ONLY strategy routed to the Row backend
99// (`StrategyTag::backend`: greedy -> Row; lazy / btopt / btultra* ->
100// HashChain), so it is the only level whose `row:` field is read. The upstream zstd
101// `clevels.h` default row (srcSize > 256 KB) for level 5 is searchLog=3,
102// targetLength=2, from which the row matcher derives:
103// rowLog = clamp(searchLog, 4, 6) = 4
104// search_depth = 1 << min(searchLog, rowLog) = 8 (= nbAttempts)
105// target_len = targetLength = 2 (nice-match early-out)
106// The shared `ROW_CONFIG` (row_log=5, search_depth=16, target_len=48) ran a
107// level-12-grade search here: 16 slots per row, never early-exiting until a
108// 48-byte match. That exhaustive walk was the dominant cost in greedy L5's
109// encode-speed regression vs FFI. `hash_bits` matches upstream zstd's
110// `ZSTD_getCParams(5, .., 0).hashLog` = 19 (verified via
111// `cparams_check 5`), so the row table is the same width as upstream's
112// (2^19 slots); the previous `ROW_HASH_BITS` (20) doubled both row tables vs
113// upstream, the dominant peak-memory excess on the greedy band.
114pub(crate) const ROW_L5: RowConfig = RowConfig {
115 hash_bits: 19,
116 row_log: 4,
117 search_depth: 8,
118 target_len: 2,
119 mls: ROW_MIN_MATCH_LEN,
120 chain_log: 18,
121 bt: false,
122};
123
124/// Per-level Double-Fast hash sizing, mirroring the upstream zstd `clevels.h` columns
125/// (config-driven, not a hardcoded constant): `long_hash_log` =
126/// `cParams.hashLog` (the long 8-byte hash table), `short_hash_log` =
127/// `cParams.chainLog` (the short hash table dfast repurposes as its
128/// secondary index). Only the Dfast backend reads it, so non-dfast level
129/// rows carry `dfast: None`. `minMatch` stays the upstream zstd-fixed `5`
130/// (`DFAST_MIN_MATCH_LEN`, used in const contexts).
131#[derive(Copy, Clone, PartialEq, Eq)]
132pub(crate) struct DfastConfig {
133 pub(crate) long_hash_log: u8,
134 pub(crate) short_hash_log: u8,
135}
136
137// Upstream zstd clevels.h default row (srcSize > 256 KB): L3 {hashLog 17, chainLog 16}.
138pub(crate) const DFAST_L3: DfastConfig = DfastConfig {
139 long_hash_log: 17,
140 short_hash_log: 16,
141};
142
143/// Per-level Fast-strategy tuning, only consumed by the `FastKernelMatcher`
144/// (Simple backend): `hash_log` = upstream zstd `cParams.hashLog`, `mls` = upstream zstd
145/// `cParams.minMatch` (4..=8), `step_size` = upstream zstd `stepSize`. Carried as
146/// `LevelParams.fast` (`Some` only on Fast level rows; `None` elsewhere).
147#[derive(Copy, Clone, PartialEq, Eq)]
148pub(crate) struct FastConfig {
149 pub(crate) hash_log: u32,
150 pub(crate) mls: u32,
151 pub(crate) step_size: usize,
152}
153
154pub(crate) const FAST_L1: FastConfig = FastConfig {
155 hash_log: 14,
156 // Tier-0 (srcSize > 256 KiB) `cParams.minMatch`. Upstream zstd selects the
157 // Level-1 row from a 4-way srcSize-tiered table (`ZSTD_getCParams_internal`
158 // → `ZSTD_defaultCParameters[tableID][1]`), and minMatch shrinks for
159 // smaller inputs: 7 (>256 KiB) / 6 (16..256 KiB) / 5 (<=16 KiB). The base
160 // here is the tier-0 value; `fast_l1_mls_for_source_size` lowers it per the
161 // tier in `adjust_params_for_source_size`.
162 mls: 7,
163 step_size: 2,
164};
165
166/// Resolved tuning parameters for a compression level and source size. The
167/// [`StrategyTag`] selects the compile-time strategy consts; the runtime
168/// [`BackendTag`] used by the driver dispatcher comes from the resolved
169/// search method ([`Self::backend`]), so an override or a size tier that
170/// changes the search changes the backend with it.
171///
172/// [`StrategyTag`]: crate::encoding::strategy::StrategyTag
173/// [`BackendTag`]: crate::encoding::strategy::BackendTag
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 /// `log2` of how much of a dictionary's end the match-finder tables index
228 /// when it is loaded: a longer dictionary is indexed only that far from its
229 /// end, since tables this size could not keep more of it anyway (upstream
230 /// `ZSTD_loadDictionaryContent`, `zstd_compress.c:4987`:
231 /// `MIN(MAX(hashLog + 3, chainLog + 1), 31)`). Every byte of it stays in
232 /// the window.
233 pub(crate) fn dictionary_reach_log(&self) -> u32 {
234 use crate::encoding::strategy::SearchMethod;
235 // The active backend's config: an override may leave the level row's
236 // own beside it.
237 let logs = match self.search {
238 SearchMethod::Fast => self.fast.map(|fast| (fast.hash_log as usize, 0)),
239 SearchMethod::DoubleFast => self
240 .dfast
241 .map(|dfast| (dfast.long_hash_log as usize, dfast.short_hash_log as usize)),
242 SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
243 self.row.map(|row| (row.hash_bits, row.chain_log))
244 }
245 SearchMethod::HashChain | SearchMethod::BinaryTree => {
246 self.hc.map(|hc| (hc.hash_log, hc.chain_log))
247 }
248 };
249 // The reset synthesises the active config when a row lacks it, so a
250 // missing one only means a table-less level: nothing to index.
251 let Some((hash_log, chain_log)) = logs else {
252 return 0;
253 };
254 (hash_log + 3).max(chain_log + 1).min(31) as u32
255 }
256
257 /// The level's upstream `cParams.minMatch`: the shortest match its search
258 /// accepts, and so the shortest piece of a long-distance match a block cut
259 /// leaves worth keeping (`maybeSplitSequence`, `zstd_ldm.c:644`).
260 #[cfg(feature = "ldm")]
261 pub(crate) fn min_match(&self) -> usize {
262 use crate::encoding::strategy::SearchMethod;
263 let configured = match self.search {
264 SearchMethod::Fast => self.fast.map(|fast| fast.mls as usize),
265 SearchMethod::DoubleFast => Some(crate::encoding::match_generator::DFAST_MIN_MATCH_LEN),
266 SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => self.row.map(|row| row.mls),
267 SearchMethod::HashChain => Some(crate::encoding::hc::HC_MIN_MATCH_LEN),
268 SearchMethod::BinaryTree => self.hc.map(|hc| hc.search_mls),
269 };
270 configured.unwrap_or(crate::encoding::cost_model::HC_FORMAT_MINMATCH)
271 }
272}
273
274/// The pre-splitter level for an effective strategy (the tag plus, for the
275/// collapsed `Lazy` tag, its lazy depth).
276///
277/// Upstream's default is `splitLevels[strategy] = {0,0,1,2,2,3,3,4,4,4}`
278/// (zstd_compress.c:4552, used as is; only an explicit `blockSplitterLevel`
279/// is shifted down by 2). It is followed up to lazy depth 1 — the finer
280/// sampling is a real ratio win on mixed data (decodecorpus at greedy/lazy:
281/// the borders tier compressed 4.6-4.9 % WORSE than upstream, the upstream
282/// rate-11 tier <= upstream) — but the lazy2/btlazy2 rate-5 and optimal-band
283/// rate-1 tiers are DELIBERATELY kept two steps coarser: on periodic input
284/// they over-split every block into tiny pieces exactly like upstream does
285/// (100 MiB of repeated log lines at L8-L12: 140,625 bytes and 3.6x the
286/// time upstream-tier, 9,742 bytes coarse — 14x better than upstream) while
287/// on real data they buy under 0.1 % (decodecorpus L8-L12: 170 bytes of
288/// 483 KiB). The drop-in contract asks for ratio <= upstream, not for
289/// upstream's block boundaries.
290pub(crate) fn pre_split_for(tag: crate::encoding::strategy::StrategyTag, lazy_depth: u8) -> u8 {
291 use crate::encoding::strategy::StrategyTag;
292 match tag {
293 // Upstream tiers: borders / byChunks rate 43 / rate 11.
294 StrategyTag::Fast => 0,
295 StrategyTag::Dfast => 1,
296 StrategyTag::Greedy => 2,
297 // lazy (depth 1) = upstream rate 11; lazy2 coarsened to rate 43.
298 StrategyTag::Lazy => {
299 if lazy_depth >= 2 {
300 1
301 } else {
302 2
303 }
304 }
305 StrategyTag::Btlazy2 => 1,
306 // Coarsened to byChunks rate 11 (upstream: rate 1).
307 StrategyTag::BtOpt | StrategyTag::BtUltra | StrategyTag::BtUltra2 => 2,
308 }
309}
310
311/// Apply the public-parameter per-knob overrides onto the
312/// level-resolved [`LevelParams`], in place. Runs in
313/// [`Matcher::reset`](crate::encoding::Matcher::reset)
314/// after the level params are computed and before backend selection, so
315/// a strategy override re-routes the backend uniformly. An all-`None`
316/// override is a no-op the caller skips via
317/// [`crate::encoding::parameters::ParamOverrides::is_empty`], keeping the default
318/// level geometry byte-identical.
319pub(crate) fn apply_param_overrides(
320 params: &mut LevelParams,
321 ov: &crate::encoding::parameters::ParamOverrides,
322) {
323 use crate::encoding::strategy::SearchMethod;
324
325 // 1. Strategy override re-derives tag / search / lazy depth.
326 if let Some(strategy) = ov.strategy {
327 let tag = strategy.tag();
328 params.strategy_tag = tag;
329 params.search = tag.search();
330 params.lazy_depth = strategy.lazy_depth();
331 }
332
333 // 2. Ensure the active backend's config row exists (synthesize a
334 // default when a strategy override moved off the native row).
335 match params.search {
336 SearchMethod::Fast => {
337 params.fast.get_or_insert(FAST_L1);
338 }
339 SearchMethod::DoubleFast => {
340 params.dfast.get_or_insert(DFAST_L3);
341 }
342 SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
343 // `ROW_L5` already carries `mls = ROW_MIN_MATCH_LEN = 5`, the
344 // upstream `minMatch` of the whole greedy..btlazy2 band at the
345 // >256 KiB tier, so a synthesized btlazy2 override hashes at the
346 // same width as a native btlazy2 row.
347 let row = params.row.get_or_insert(ROW_L5);
348 row.bt = matches!(params.search, SearchMethod::BinaryTreeLazy);
349 }
350 SearchMethod::HashChain | SearchMethod::BinaryTree => {
351 params.hc.get_or_insert(HC_OVERRIDE_DEFAULT);
352 }
353 }
354
355 // 3. window_log (bounds-checked at <= 30 by the builder).
356 if let Some(window_log) = ov.window_log {
357 params.window_log = window_log;
358 }
359
360 // 4. Per-backend numeric knobs map into the active config, mirroring
361 // the upstream zstd `cParams` -> matcher translation documented on each
362 // config struct.
363 match params.search {
364 SearchMethod::Fast => {
365 if let Some(fast) = params.fast.as_mut() {
366 if let Some(hash_log) = ov.hash_log {
367 fast.hash_log = hash_log;
368 }
369 if let Some(min_match) = ov.min_match {
370 fast.mls = fast_key_len(min_match);
371 }
372 // targetLength is the Fast strategy's step, as it is on the
373 // level's own row: upstream zstd_fast.c `stepSize =
374 // targetLength + !targetLength + 1`.
375 if let Some(target_length) = ov.target_length {
376 fast.step_size = (target_length as usize).max(1) + 1;
377 }
378 }
379 }
380 SearchMethod::DoubleFast => {
381 if let Some(dfast) = params.dfast.as_mut() {
382 // hashLog -> long table, chainLog -> short table (the
383 // dfast secondary index). Both bounds-checked <= 30, so
384 // the `u8` casts are lossless.
385 if let Some(hash_log) = ov.hash_log {
386 dfast.long_hash_log = hash_log as u8;
387 }
388 if let Some(chain_log) = ov.chain_log {
389 dfast.short_hash_log = chain_log as u8;
390 }
391 }
392 }
393 SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => {
394 if let Some(row) = params.row.as_mut() {
395 // Row hash-table width override (mirrors dfast `long_hash_log`
396 // / hc `hash_log`); `chain_log` sizes the hash chain the same
397 // backend searches on a <= 2^14 window, or its binary tree.
398 if let Some(hash_log) = ov.hash_log {
399 row.hash_bits = hash_log as usize;
400 }
401 if let Some(chain_log) = ov.chain_log {
402 row.chain_log = chain_log as usize;
403 }
404 if let Some(search_log) = ov.search_log {
405 // Upstream zstd: rowLog = clamp(searchLog, 4, 6); the
406 // compare budget stays the FULL `1 << searchLog`
407 // (`nbAttempts`) — the chain walk and the tree walk
408 // consume it directly, and the row probe bounds its own
409 // budget by the row size at the search site.
410 row.row_log = (search_log as usize).clamp(4, 6);
411 row.search_depth = 1usize << search_log;
412 }
413 if let Some(target_length) = ov.target_length {
414 row.target_len = target_length as usize;
415 }
416 if let Some(min_match) = ov.min_match {
417 row.mls = min_match as usize;
418 }
419 }
420 }
421 SearchMethod::HashChain | SearchMethod::BinaryTree => {
422 if let Some(hc) = params.hc.as_mut() {
423 if let Some(hash_log) = ov.hash_log {
424 hc.hash_log = hash_log as usize;
425 }
426 if let Some(chain_log) = ov.chain_log {
427 hc.chain_log = chain_log as usize;
428 }
429 if let Some(search_log) = ov.search_log {
430 hc.search_depth = 1usize << search_log;
431 }
432 if let Some(target_length) = ov.target_length {
433 hc.target_len = target_length as usize;
434 }
435 if let Some(min_match) = ov.min_match {
436 // A `minMatch` of 3 asked for explicitly keys the tree on
437 // three bytes (see `HcConfig::search_mls`).
438 hc.search_mls = (min_match as usize).clamp(3, 6);
439 }
440 }
441 }
442 }
443}
444
445/// The key width the fast strategy hashes for a `minMatch`: upstream's fast
446/// block compressor takes 3 as 4 (zstd_fast.c, `ZSTD_compressBlock_fast`:
447/// `default: /* includes case 3 */`). A 3 reaches the fast strategy from the
448/// knob, or from an optimal level's CDict row a strategy knob moved onto it.
449fn fast_key_len(min_match: u32) -> u32 {
450 min_match.max(4)
451}
452
453/// Map the resolved runtime strategy to the upstream zstd LDM strategy ordinal
454/// (1..=9) that [`crate::encoding::ldm::params::LdmParams::adjust_for`] expects.
455/// The collapsed `Lazy` tag splits on `lazy_depth` (lazy = 4, lazy2 = 5).
456#[cfg(feature = "ldm")]
457pub(crate) fn ldm_strategy_ordinal(
458 tag: crate::encoding::strategy::StrategyTag,
459 lazy_depth: u8,
460) -> u32 {
461 use crate::encoding::strategy::StrategyTag;
462 match tag {
463 StrategyTag::Fast => 1,
464 StrategyTag::Dfast => 2,
465 StrategyTag::Greedy => 3,
466 StrategyTag::Lazy => {
467 if lazy_depth >= 2 {
468 5
469 } else {
470 4
471 }
472 }
473 // Upstream zstd `ZSTD_btlazy2` ordinal.
474 StrategyTag::Btlazy2 => 6,
475 StrategyTag::BtOpt => 7,
476 StrategyTag::BtUltra => 8,
477 StrategyTag::BtUltra2 => 9,
478 }
479}
480
481/// `ceil(log2(size))` of a source-size hint, with a zero hint floored to
482/// [`MIN_WINDOW_LOG`]. This is the single quantization every hint-dependent
483/// matcher parameter is derived from: the window-log cap, the HC / Fast hash
484/// and chain widths, the Dfast / Row table widths, the L22 config buckets, and
485/// the Fast attach-vs-copy cutoff. Two hints sharing this value resolve to the
486/// identical matcher shape, which is why it (not the raw byte count) keys the
487/// primed-dictionary snapshot — see `match_generator::PrimedKey`. Operates on the full `u64`
488/// so callers comparing a hint against a cutoff get the same bucketed decision
489/// here and at the driver, with no `as usize` truncation on 32-bit targets.
490pub(crate) fn source_size_ceil_log(size: u64) -> u8 {
491 if size == 0 {
492 MIN_WINDOW_LOG
493 } else {
494 (64 - (size - 1).leading_zeros()) as u8
495 }
496}
497
498/// Attach-vs-copy cutoff for the Fast strategy, as a ceil-log bucket: a hint at
499/// or below `2^this` (or unknown, `None`) ATTACHES the dictionary (a separate
500/// immutable table scanned in place via the borrowed dual-base kernel); a larger
501/// hint would COPY it into the live table.
502///
503/// `13` is upstream zstd's Fast cutoff (`attachDictSizeCutoffs[ZSTD_fast]` is
504/// 8 KB, zstd_compress.c:2296; `ZSTD_shouldAttachDict`, :2309). Above it the
505/// dictionary is COPIED, and the copy is what makes the dictionary pay on a
506/// larger source: the scan then runs over a table already holding the
507/// dictionary's positions, so ordinary NEAR matches improve everywhere. Attach
508/// mode starts with an empty table and reaches the dictionary only through the
509/// separate exact table, at the positions the step happens to land on.
510///
511/// This was `31` (attach every source up to 2 GiB) on a speed argument alone,
512/// and the missing byte column is where it went wrong. Per frame, `z000033`
513/// (1,022,035 B) and its leading 10 KiB, with a 16 KiB dictionary trained over
514/// its 10 KiB chunks, on the i9: two prebuilt binaries and libzstd alternated
515/// in one session, `perf stat -r 3`, three rounds, ranges non-overlapping.
516///
517/// | case | bytes attach | bytes copy | reference | cycles attach | cycles copy | insn attach | insn copy |
518/// |---|---|---|---|---|---|---|---|
519/// | 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) |
520/// | 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) |
521/// | 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) |
522/// | 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) |
523///
524/// Copy is the better arm on both axes at the positive levels: it takes 18-28%
525/// fewer cycles and 22-27% fewer instructions, and its bytes are the
526/// reference's exactly on the small frame and 3.4% under the reference on the
527/// large one. At the ultra-fast levels it buys ratio with time: 21% more cycles
528/// on the 1 MiB frame for 6.0% fewer bytes, 9% more on the small one for 5.5%
529/// fewer. That trade is what the cutoff is for. Attach put us 2.9% ABOVE the
530/// reference on the 1 MiB ultra-fast frame — the dictionary made our frame
531/// bigger than our own no-dict frame there, while it made the reference's
532/// smaller — because it found 21,897 sequences where the reference finds
533/// 27,546. Copy puts us 3.3% under it.
534///
535/// The remaining gap is now a same-mode one: the reference does this copy in
536/// 1.0x where we take 1.3-1.8x, which is a target with an apples-to-apples
537/// reference rather than a mode the reference never runs.
538///
539/// The borrowed attach kernel stores virtual positions as `u32`
540/// (`cur_abs as u32`), so it could not attach past bucket `31` regardless; that
541/// ceiling is now far above the cutoff and no longer the binding constraint.
542/// Shared by `reset` (records the mode in the primed-snapshot key) and
543/// `prime_with_dictionary` (acts on it).
544pub(crate) const FAST_ATTACH_DICT_CUTOFF_LOG: u8 = 13;
545
546/// Whether a dictionary frame in size bucket `size_log` reuses the captured
547/// primed snapshot rather than re-priming: only a known size above the
548/// strategy's attach cutoff `cutoff_log`, the upstream zstd copy regime
549/// (`ZSTD_shouldAttachDict`). The frame compressor restores on this and the
550/// Fast reset keeps its table only on it, so the two cannot disagree.
551pub(crate) fn restores_primed_snapshot(size_log: Option<u8>, cutoff_log: u8) -> bool {
552 size_log.is_some_and(|log| log > cutoff_log)
553}
554
555/// Largest dictionary region (bytes) the Fast attach path can index. The tagged
556/// dict table packs each position into `32 - DICT_TAG_BITS` (= 24) bits, so a
557/// region past `2^24` (16 MiB) would overflow the packed position. Dictionaries
558/// this large fall back to COPY mode, whose live table stores full `u32`
559/// positions and handles them. The size hint set on dict load equals the actual
560/// dict content length, so the attach-vs-copy decision (and the matching
561/// snapshot-key / epoch bits) can gate on it consistently at reset time.
562pub(crate) const MAX_FAST_ATTACH_DICT_REGION: usize = 1 << 24;
563
564/// Dfast counterpart of [`FAST_ATTACH_DICT_CUTOFF_LOG`]: upstream zstd
565/// `ZSTD_dictMatchState` attach cutoff for the double-fast strategy is 16 KiB
566/// (`2^14`), so small / unknown-size inputs ATTACH (separate immutable dict
567/// long+short tables + dual-probe in `start_matching_fast_loop`) and larger
568/// known-size inputs COPY (re-prime the dict into the live tables, where the
569/// dense scan matches it as window history). The attach build also self-gates
570/// on `use_fast_loop` inside `skip_matching_for_dict_attach` — only the
571/// fast-loop levels (L3 / Default / L0) carry the dual-probe.
572pub(crate) const DFAST_ATTACH_DICT_CUTOFF_LOG: u8 = 14;
573
574/// 32 KiB (`2^15`, upstream zstd `attachDictSizeCutoffs[ZSTD_lazy2]`): small /
575/// unknown-size inputs ATTACH the dict as a separate hash-chain dms (the dual
576/// search in `find_best_match` walks the live input chain + the dms), larger
577/// known-size inputs dense-COPY (merge the dict into the live chain and search
578/// the one combined chain).
579pub(crate) const HC_ATTACH_DICT_CUTOFF_LOG: u8 = 15;
580
581/// BT/optimal attach cutoff for `btlazy2` + `btopt`: 32 KiB (`2^15`, upstream
582/// zstd `attachDictSizeCutoffs[ZSTD_btlazy2]` == `[ZSTD_btopt]`). Small /
583/// unknown-size inputs ATTACH the dict as a separate DUBT dms; larger known-size
584/// inputs COPY the dict into the LIVE binary tree (upstream zstd
585/// `ZSTD_resetCCtx_byCopyingCDict`).
586pub(crate) const BT_OPT_ATTACH_DICT_CUTOFF_LOG: u8 = 15;
587
588/// BT/optimal attach cutoff for `btultra` + `btultra2`: 8 KiB (`2^13`, upstream
589/// zstd `attachDictSizeCutoffs[ZSTD_btultra]` == `[ZSTD_btultra2]`). The deepest
590/// parses copy the dict into the live tree past a much smaller source than the
591/// `btopt` tier, matching upstream's per-strategy cutoff table.
592pub(crate) const BT_ULTRA_ATTACH_DICT_CUTOFF_LOG: u8 = 13;
593
594// Source-size cap for the dfast hash bits when a size hint is present: a tiny
595// input needs no larger hash than its window. The upstream zstd `cParams.hashLog` /
596// `chainLog` (from `DfastConfig`) caps it from above at the call site.
597pub(crate) fn dfast_hash_bits_for_window(max_window_size: usize) -> usize {
598 let window_log = (usize::BITS - 1 - max_window_size.leading_zeros()) as usize;
599 window_log.max(MIN_WINDOW_LOG as usize)
600}
601
602pub(crate) fn row_hash_bits_for_window(max_window_size: usize) -> usize {
603 // Upstream zstd `ZSTD_adjustCParams_internal` cap: `hashLog <= windowLog + 1`.
604 // The `+ 1` is load-bearing for L12, whose upstream zstd hashLog (23) exceeds
605 // its windowLog (22) — a plain `windowLog` cap would shrink the L12
606 // table on EVERY hinted reset and split primed snapshots between
607 // hinted and unhinted frames that resolve to the identical geometry.
608 // No constant upper clamp: the old `ROW_HASH_BITS` (20) ceiling
609 // predates the lazy band moving onto Row (L9-12 carry upstream zstd hashLog
610 // 21-23).
611 let window_log = (usize::BITS - 1 - max_window_size.leading_zeros()) as usize;
612 (window_log + 1).max(MIN_WINDOW_LOG as usize)
613}
614
615/// `floor(log2(window))` for the HashChain table-log cap (upstream zstd
616/// `ZSTD_adjustCParams_internal`). The caller clamps the level's `hash_log` /
617/// `chain_log` from above with this so a small hinted input doesn't allocate the
618/// full level's tables.
619pub(crate) fn hc_hash_bits_for_window(max_window_size: usize) -> usize {
620 let window_log = (usize::BITS - 1 - max_window_size.leading_zeros()) as usize;
621 window_log.max(MIN_WINDOW_LOG as usize)
622}
623
624/// Smallest window_log the encoder will use regardless of source size.
625pub(crate) const MIN_WINDOW_LOG: u8 = 10;
626
627/// Largest window_log the public parameter API accepts
628/// ([`CParameter::WindowLog`](crate::encoding::CParameter)'s upper bound), and
629/// so the largest a workspace estimate can be asked to describe. The estimate
630/// answers for whatever it is given, and shifting by more than the width of a
631/// `usize` is undefined, so a request beyond this is answered with this.
632pub(crate) const MAX_ESTIMATED_WINDOW_LOG: u8 = 30;
633
634/// Translate a verbatim upstream `ZSTD_defaultCParameters[tier][level]` row
635/// (`cparams::CParams`) into our resolved [`LevelParams`], reproducing
636/// upstream's cParams -> matcher-config derivation so the encoder follows C's
637/// source-size-tiered STRATEGY + table widths rather than a single hand-tuned
638/// `LEVEL_TABLE`. Derivation (verified against L6/L16/L22 vs clevels.h):
639/// `search_depth = 1 << searchLog`; row `row_log = clamp(searchLog, 4, 6)`; the
640/// per-strategy sub-config carries the verbatim `hashLog` / `chainLog` /
641/// `targetLength` / `minMatch`. Strategy numbers are upstream `ZSTD_strategy`
642/// (fast=1, dfast=2, greedy=3, lazy=4, lazy2=5, btlazy2=6, btopt=7, btultra=8,
643/// btultra2=9).
644fn level_params_from_cparams(cp: crate::encoding::cparams::CParams) -> LevelParams {
645 use crate::encoding::strategy::{SearchMethod, StrategyTag};
646 let window_log = cp.window_log as u8;
647 let search_depth = 1usize << cp.search_log;
648 let target_len = cp.target_length as usize;
649 let hc = HcConfig {
650 hash_log: cp.hash_log as usize,
651 chain_log: cp.chain_log as usize,
652 search_depth,
653 target_len,
654 // See `HcConfig::search_mls`: a `minMatch` of 3 hashes four bytes.
655 search_mls: cp.min_match.clamp(4, 6) as usize,
656 };
657 let row = RowConfig {
658 hash_bits: cp.hash_log as usize,
659 row_log: cp.search_log.clamp(4, 6) as usize,
660 search_depth,
661 target_len,
662 mls: cp.min_match as usize,
663 chain_log: cp.chain_log as usize,
664 // Upstream `ZSTD_btlazy2` (strategy 6).
665 bt: cp.strategy == 6,
666 };
667 let bt = |tag| LevelParams {
668 strategy_tag: tag,
669 search: SearchMethod::BinaryTree,
670 window_log,
671 lazy_depth: 2,
672 fast: None,
673 dfast: None,
674 hc: Some(hc),
675 row: None,
676 };
677 let row_lvl = |tag, search, lazy_depth| LevelParams {
678 strategy_tag: tag,
679 search,
680 window_log,
681 lazy_depth,
682 fast: None,
683 dfast: None,
684 hc: None,
685 row: Some(row),
686 };
687 match cp.strategy {
688 1 => LevelParams {
689 strategy_tag: StrategyTag::Fast,
690 search: SearchMethod::Fast,
691 window_log,
692 lazy_depth: 0,
693 // Upstream fast `stepSize`: `targetLength + 1` (0 -> 1, so step 2).
694 fast: Some(FastConfig {
695 hash_log: cp.hash_log,
696 mls: fast_key_len(cp.min_match),
697 step_size: target_len.max(1) + 1,
698 }),
699 dfast: None,
700 hc: None,
701 row: None,
702 },
703 2 => LevelParams {
704 strategy_tag: StrategyTag::Dfast,
705 search: SearchMethod::DoubleFast,
706 window_log,
707 lazy_depth: 1,
708 fast: None,
709 dfast: Some(DfastConfig {
710 long_hash_log: cp.hash_log as u8,
711 short_hash_log: cp.chain_log as u8,
712 }),
713 hc: None,
714 row: None,
715 },
716 3 => row_lvl(StrategyTag::Greedy, SearchMethod::RowHash, 0),
717 4 => row_lvl(StrategyTag::Lazy, SearchMethod::RowHash, 1),
718 5 => row_lvl(StrategyTag::Lazy, SearchMethod::RowHash, 2),
719 // btlazy2: the same lazy2 parse over the lazily-sorted binary tree.
720 6 => row_lvl(StrategyTag::Btlazy2, SearchMethod::BinaryTreeLazy, 2),
721 7 => bt(StrategyTag::BtOpt),
722 8 => bt(StrategyTag::BtUltra),
723 _ => bt(StrategyTag::BtUltra2),
724 }
725}
726
727/// Down-size a synthesized backend's window / hash / chain logs for a known
728/// source size by routing through the single C-faithful adjuster
729/// [`adjust_cparams`](crate::encoding::cparams::adjust_cparams)
730/// (`ZSTD_adjustCParams_internal`).
731///
732/// Used only on the param-override re-cap path: [`apply_param_overrides`]
733/// synthesizes a backend's full-size default config when a strategy override
734/// moves off the native level row, and this re-applies the source-size cap
735/// C-faithfully — the SAME adjuster the `get_cparams` main path uses, so the
736/// override path and the level path now down-size identically (no extra hinted
737/// 16 KiB window floor, no per-backend headroom that diverged from C). The
738/// Dfast backend self-sizes its tables in `reset`, so only its window is capped.
739pub(crate) fn adjust_params_for_source_size(mut params: LevelParams, src_size: u64) -> LevelParams {
740 use crate::encoding::cparams::{CParams, adjust_cparams};
741 use crate::encoding::strategy::{BackendTag, StrategyTag};
742
743 let backend = params.backend();
744 // Lift the active backend's source-cappable logs into a flat CParams. Dfast
745 // contributes none (window-only); its table widths self-size in `reset`.
746 let (hash_log, chain_log): (u32, u32) = match backend {
747 BackendTag::Simple => (params.fast.as_ref().map_or(0, |f| f.hash_log), 0),
748 BackendTag::HashChain => params
749 .hc
750 .as_ref()
751 .map_or((0, 0), |h| (h.hash_log as u32, h.chain_log as u32)),
752 BackendTag::Row => params
753 .row
754 .as_ref()
755 .map_or((0, 0), |r| (r.hash_bits as u32, r.chain_log as u32)),
756 BackendTag::Dfast => (0, 0),
757 };
758 // `adjust_cparams` reads the strategy for the chain cap (`ZSTD_cycleLog`,
759 // btlazy2 and up) and for the row-hash cap (greedy to lazy2, with the
760 // search log as the row log), so it gets the real class and search log;
761 // `Lazy` stands for lazy and lazy2, which both caps treat alike.
762 let strategy = match params.strategy_tag {
763 StrategyTag::Fast => 1,
764 StrategyTag::Dfast => 2,
765 StrategyTag::Greedy => 3,
766 StrategyTag::Lazy => 4,
767 StrategyTag::Btlazy2 => 6,
768 StrategyTag::BtOpt => 7,
769 StrategyTag::BtUltra => 8,
770 StrategyTag::BtUltra2 => 9,
771 };
772 // `search_depth` is `1 << searchLog` on both backends that search.
773 let search_log = match backend {
774 BackendTag::HashChain => params
775 .hc
776 .as_ref()
777 .map_or(1, |h| h.search_depth.trailing_zeros()),
778 BackendTag::Row => params
779 .row
780 .as_ref()
781 .map_or(1, |r| r.search_depth.trailing_zeros()),
782 BackendTag::Simple | BackendTag::Dfast => 1,
783 };
784 let adj = adjust_cparams(
785 CParams {
786 window_log: u32::from(params.window_log),
787 chain_log,
788 hash_log,
789 search_log,
790 min_match: 4,
791 target_length: 0,
792 strategy,
793 },
794 src_size,
795 0,
796 false,
797 );
798 params.window_log = adj.window_log as u8;
799 match backend {
800 BackendTag::Simple => {
801 if let Some(f) = params.fast.as_mut() {
802 f.hash_log = adj.hash_log;
803 }
804 }
805 BackendTag::HashChain => {
806 if let Some(h) = params.hc.as_mut() {
807 h.hash_log = adj.hash_log as usize;
808 h.chain_log = adj.chain_log as usize;
809 }
810 }
811 BackendTag::Row => {
812 if let Some(r) = params.row.as_mut() {
813 r.hash_bits = adj.hash_log as usize;
814 r.chain_log = adj.chain_log as usize;
815 }
816 }
817 BackendTag::Dfast => {}
818 }
819 params
820}
821
822/// Apply the caller's parameter overrides to the level params a frame
823/// resolved to: the step the matcher's reset takes after the level (and a
824/// dictionary's CDict tier) is resolved, kept in one place so the workspace
825/// estimate builds exactly what the encoder does. An all-`None` set leaves the
826/// params untouched, which keeps plain level-based geometry byte-identical.
827pub(crate) fn apply_frame_overrides(
828 params: &mut LevelParams,
829 ov: &crate::encoding::parameters::ParamOverrides,
830 dictionary_frame: bool,
831 hint: Option<u64>,
832) {
833 if ov.is_empty() {
834 return;
835 }
836 if dictionary_frame {
837 // A dictionary frame runs the CDict's cParams (upstream
838 // `ZSTD_resetCCtx_byAttachingCDict` / `byCopyingCDict`), and the
839 // search knobs are already part of them
840 // (`resolve_level_params_with_dict`); the frame's own knob is the
841 // window.
842 //
843 // The window still answers to the source, as it does for every
844 // other frame: `ZSTD_adjustCParams_internal` caps it by the source
845 // and dictionary extent, and a window neither can fill only makes
846 // decoders reserve memory the frame never uses. Capped here rather
847 // than through the full adjuster, which would reshape the search.
848 if let Some(window_log) = ov.window_log {
849 params.window_log = match hint {
850 // The source caps the window even here, and even with an
851 // explicit request: the reference command declares 2 KiB
852 // for `--ultra -22 --long=27 -D dict` on a 2 KiB file, and
853 // a window the content cannot fill only makes every decoder
854 // reserve memory the frame never uses. The floor that
855 // travels with the cap in `adjust_cparams` applies too, or
856 // a hint of a few dozen bytes asks for a window smaller
857 // than the format's smallest.
858 //
859 // The dictionary's own size is NOT part of that cap: the
860 // reference declares the same 2 KiB whether the dictionary
861 // is 4 KiB or 256 KiB, because a small window does not put
862 // the dictionary out of reach: sequences may reference it
863 // at offsets beyond the window while the output so far is
864 // within it (RFC 8878, Dictionary_Content). Counting it
865 // made our frames ask decoders for up to 256x what the
866 // reference asks.
867 Some(src) => {
868 (crate::encoding::cparams::adjusted_window_log(u32::from(window_log), src, 0)
869 as u8)
870 .max(MIN_WINDOW_LOG)
871 }
872 None => window_log,
873 };
874 }
875 } else {
876 apply_param_overrides(params, ov);
877 // The level's own resolution applied the source-size cap for the
878 // LEVEL's native backend. If a strategy override moved the frame
879 // onto a different backend, `apply_param_overrides` synthesized that
880 // backend's DEFAULT config (FAST_L1 / HC_OVERRIDE_DEFAULT) with
881 // full-size table logs AFTER that cap ran. Re-apply the hint cap so a
882 // tiny hinted frame doesn't allocate the new backend's full-size
883 // tables.
884 //
885 // The cap covers an explicit `window_log` too, as
886 // `ZSTD_adjustCParams_internal` does upstream: the window is a
887 // promise about the memory decoding will need, and a source that
888 // cannot fill it makes that promise for nothing: every decoder
889 // opening the frame would reserve the whole declared window to read
890 // a few bytes. The override still raises the window as far as the
891 // source can use.
892 if let Some(hint_size) = hint {
893 *params = adjust_params_for_source_size(*params, hint_size);
894 }
895 }
896}
897
898/// The long-distance matcher's parameters for a frame: the caller-pinned knobs
899/// seeded first, then the upstream derivation fills the rest so the set stays
900/// consistent (`hash_rate_log = window_log - hash_log`, and so on); clobbering
901/// after the derivation would hand the producer an inconsistent set. Shared by
902/// the matcher's reset and the workspace estimate.
903#[cfg(feature = "ldm")]
904pub(crate) fn frame_ldm_params(
905 params: &LevelParams,
906 ldm: &crate::encoding::parameters::LdmOverride,
907) -> crate::encoding::ldm::params::LdmParams {
908 let seed = crate::encoding::ldm::params::LdmParams {
909 window_log: params.window_log as u32,
910 hash_log: ldm.hash_log.unwrap_or(0),
911 hash_rate_log: ldm.hash_rate_log.unwrap_or(0),
912 min_match_length: ldm.min_match.unwrap_or(0),
913 bucket_size_log: ldm.bucket_size_log.unwrap_or(0),
914 };
915 seed.derive(ldm_strategy_ordinal(params.strategy_tag, params.lazy_depth))
916}
917
918/// Estimated steady-state heap footprint of a one-shot compression context
919/// at `level` (window history + match-finder tables + block staging), in
920/// bytes. Computed from the same per-level tuning table the encoder
921/// resolves at frame start, so the estimate tracks the real allocations;
922/// it is an upper-bound style budget figure, not an exact accounting.
923pub fn estimated_compression_workspace_bytes(level: CompressionLevel) -> usize {
924 estimated_compression_workspace_bytes_for_source(level, None)
925}
926
927/// The same estimate for a source whose size is known.
928///
929/// The window and the match-finder tables are capped by the source, so a level
930/// that would reserve hundreds of MiB for an arbitrary stream reserves a
931/// fraction of that for a small one — and a caller budgeting memory for a
932/// compression it is about to run knows which. `None` is the arbitrary-stream
933/// figure that [`estimated_compression_workspace_bytes`] reports.
934pub fn estimated_compression_workspace_bytes_for_source(
935 level: CompressionLevel,
936 src_size_hint: Option<u64>,
937) -> usize {
938 estimated_compression_workspace_bytes_for_run(level, src_size_hint, None, false, None)
939}
940
941/// The same estimate for a run whose window, long-distance matching and
942/// dictionary are what the caller has actually asked for.
943///
944/// A `window_log` override enlarges the history the frame keeps, and
945/// long-distance matching adds a hash table of its own on top — neither of them
946/// visible in the level's own preset. A dictionary goes further than adding to
947/// the figure: it *decides* it. The frame runs the dictionary's own compression
948/// parameters, so a small source compressed against a large dictionary builds
949/// tables sized for the dictionary, which at the higher levels is the
950/// difference between tens of KiB and hundreds of MiB. `None`, `false` and
951/// `None` give the preset, which is what
952/// [`estimated_compression_workspace_bytes_for_source`] reports.
953///
954/// `dictionary` is what a caller weighing a run before it parses the blob can
955/// answer with [`DictionarySizes::raw_content`] on the blob's own length: the
956/// content of a trained dictionary is smaller than the blob it came in, and
957/// overstating it can only move the estimate toward the copy-mode geometry,
958/// which is the larger of the two.
959///
960/// [`DictionarySizes::raw_content`]: crate::encoding::DictionarySizes::raw_content
961pub fn estimated_compression_workspace_bytes_for_run(
962 level: CompressionLevel,
963 src_size_hint: Option<u64>,
964 window_log: Option<u8>,
965 long_distance_matching: bool,
966 dictionary: Option<crate::encoding::DictionarySizes>,
967) -> usize {
968 let mut params = match dictionary.filter(|sizes| sizes.content != 0) {
969 Some(sizes) => {
970 resolve_level_params_with_dict(
971 level,
972 src_size_hint,
973 sizes,
974 &crate::encoding::parameters::ParamOverrides::default(),
975 )
976 .0
977 }
978 None => resolve_level_params(level, src_size_hint),
979 };
980 // The override is what the frame will keep, but never below the floor the
981 // format sets or above what the source can fill — the same two bounds the
982 // encoder applies to it.
983 if let Some(requested) = window_log {
984 // Bounded to what the encoder itself accepts before anything shifts by
985 // it. This answers for whatever it is asked, and a shift past the width
986 // of the type is undefined rather than merely large: the largest window
987 // there is, is the honest answer to a request beyond it.
988 let requested = requested.min(MAX_ESTIMATED_WINDOW_LOG);
989 let capped = match src_size_hint {
990 Some(src) => {
991 crate::encoding::cparams::adjusted_window_log(u32::from(requested), src, 0) as u8
992 }
993 None => requested,
994 };
995 params.window_log = capped.clamp(MIN_WINDOW_LOG, MAX_ESTIMATED_WINDOW_LOG);
996 }
997 // The long-distance matcher's own table, sized from the window it searches
998 // (upstream `ZSTD_ldm_adjustParameters`). Only the `ldm` build has one.
999 #[cfg(feature = "ldm")]
1000 let ldm = if long_distance_matching {
1001 let strategy = ldm_strategy_ordinal(params.strategy_tag, params.lazy_depth);
1002 crate::encoding::ldm::estimated_workspace_bytes(
1003 &crate::encoding::ldm::params::LdmParams::adjust_for(
1004 u32::from(params.window_log),
1005 strategy,
1006 ),
1007 )
1008 } else {
1009 0
1010 };
1011 #[cfg(not(feature = "ldm"))]
1012 let ldm = {
1013 let _ = long_distance_matching;
1014 0
1015 };
1016 workspace_bytes(¶ms, ldm)
1017}
1018
1019/// The level params a frame resolves to under `parameters`, for a source of
1020/// `src_size_hint` bytes and an optional dictionary: the level (or the
1021/// dictionary's tier), then the caller's overrides, as the matcher's reset
1022/// resolves them.
1023pub(crate) fn frame_level_params(
1024 parameters: &crate::encoding::CompressionParameters,
1025 src_size_hint: Option<u64>,
1026 dictionary: Option<crate::encoding::DictionarySizes>,
1027) -> LevelParams {
1028 let level = parameters.level();
1029 let overrides = parameters.overrides();
1030 let dictionary = dictionary.filter(|sizes| sizes.content != 0);
1031 let mut params = match dictionary {
1032 Some(sizes) => resolve_level_params_with_dict(level, src_size_hint, sizes, &overrides).0,
1033 None => resolve_level_params(level, src_size_hint),
1034 };
1035 apply_frame_overrides(&mut params, &overrides, dictionary.is_some(), src_size_hint);
1036 params
1037}
1038
1039/// The workspace estimate for a frame run under `parameters`: the level, every
1040/// knob that overrides it, the source size and the dictionary, resolved the way
1041/// the encoder resolves them at frame start.
1042///
1043/// [`estimated_compression_workspace_bytes_for_run`] answers for a level with a
1044/// window and long-distance matching on top; a caller that also sets `hashLog`,
1045/// `chainLog`, a strategy or the long-distance matcher's own table sizes needs
1046/// this one, since each of those resizes what the frame allocates. A dictionary
1047/// frame runs the geometry the dictionary is prepared with, the knobs included,
1048/// as the encoder does.
1049///
1050/// # Examples
1051///
1052/// ```
1053/// use structured_zstd::encoding::{
1054/// estimated_compression_workspace_bytes_for_parameters, CompressionLevel,
1055/// CompressionParameters,
1056/// };
1057///
1058/// let level = CompressionParameters::builder(CompressionLevel::Level(3)).build().unwrap();
1059/// let wide = CompressionParameters::builder(CompressionLevel::Level(3))
1060/// .window_log(27)
1061/// .hash_log(24)
1062/// .build()
1063/// .unwrap();
1064/// let source = Some(512 << 20);
1065/// assert!(
1066/// estimated_compression_workspace_bytes_for_parameters(&wide, source, None)
1067/// > estimated_compression_workspace_bytes_for_parameters(&level, source, None)
1068/// );
1069/// ```
1070pub fn estimated_compression_workspace_bytes_for_parameters(
1071 parameters: &crate::encoding::CompressionParameters,
1072 src_size_hint: Option<u64>,
1073 dictionary: Option<crate::encoding::DictionarySizes>,
1074) -> usize {
1075 let params = frame_level_params(parameters, src_size_hint, dictionary);
1076 #[cfg(feature = "ldm")]
1077 let ldm = parameters.overrides().ldm.map_or(0, |ldm| {
1078 crate::encoding::ldm::estimated_workspace_bytes(&frame_ldm_params(¶ms, &ldm))
1079 });
1080 #[cfg(not(feature = "ldm"))]
1081 let ldm = 0;
1082 workspace_bytes(¶ms, ldm)
1083}
1084
1085/// `entry` bytes for each of `1 << log` slots, pinned at `usize::MAX` where
1086/// the table is more than a `usize` counts: the estimate is a budget, and a
1087/// figure that wrapped would call an impossible table affordable.
1088fn table_bytes(entry: usize, log: usize) -> usize {
1089 u32::try_from(log)
1090 .ok()
1091 .and_then(|log| 1usize.checked_shl(log))
1092 .and_then(|slots| slots.checked_mul(entry))
1093 .unwrap_or(usize::MAX)
1094}
1095
1096/// Everything a compressor keeps for a frame resolved to `params`, plus `ldm`
1097/// bytes of long-distance table: the workspace (history, match-finder tables
1098/// and block buffers, laid out by the same functions the reset uses), and
1099/// what lives beside it (optimal-parser scratch, entropy tables, the block
1100/// splitter's state, the window's block deque).
1101fn workspace_bytes(params: &LevelParams, ldm: usize) -> usize {
1102 use crate::encoding::strategy::{SearchMethod, StrategyTag};
1103 use crate::encoding::workspace::{ALIGN, region_bytes};
1104 // A 30-bit window is a gibibyte, which a 32-bit `usize` cannot count: the
1105 // widest window is more memory than such a machine has, so the figure is
1106 // pinned rather than wrapped.
1107 let window = 1usize
1108 .checked_shl(u32::from(params.window_log))
1109 .unwrap_or(usize::MAX);
1110 let block = (crate::common::MAX_BLOCK_SIZE as usize).min(window);
1111 let backend = params.backend();
1112 let history = crate::encoding::match_generator::history_ceiling(backend, window, 0, block);
1113 // Mirror `configure()`: the HC3 short-match side table exists only on
1114 // the btultra/btultra2 tags (minMatch 3), capped by the window log; the
1115 // BT pointer-pair layout fits inside the `4 << chain_log` chain term
1116 // (pairs over `chain_log - 1` nodes).
1117 let wants_hash3 = matches!(
1118 params.strategy_tag,
1119 StrategyTag::BtUltra | StrategyTag::BtUltra2
1120 );
1121 let uses_bt = matches!(
1122 params.strategy_tag,
1123 StrategyTag::BtOpt | StrategyTag::BtUltra | StrategyTag::BtUltra2
1124 );
1125 // Only the backend `params.search` selects is built: `reset` swaps in one
1126 // matcher storage per frame. A strategy override leaves the level's own
1127 // row in place beside the one it synthesized, so summing every populated
1128 // config would charge a frame for tables it never allocates.
1129 // Every term goes through `table_bytes` and every sum saturates: an
1130 // override can ask for a table past what a 32-bit `usize` counts, and a
1131 // shift that dropped its high bits would report that table as free.
1132 let tables = match params.search {
1133 SearchMethod::Fast => params
1134 .fast
1135 .map_or(0, |f| table_bytes(4, f.hash_log as usize)),
1136 SearchMethod::DoubleFast => params.dfast.map_or(0, |d| {
1137 table_bytes(4, usize::from(d.long_hash_log))
1138 .saturating_add(table_bytes(4, usize::from(d.short_hash_log)))
1139 }),
1140 // The lazy backend's chain / tree finders (window <= 2^14, or a
1141 // btlazy2 level) use a plain hash table (`4 << hash_bits`) plus the
1142 // chain / tree table (`4 << chain_log`) instead of the row tables.
1143 SearchMethod::RowHash | SearchMethod::BinaryTreeLazy => params.row.map_or(0, |r| {
1144 if r.bt || params.window_log <= 14 {
1145 table_bytes(4, r.hash_bits).saturating_add(table_bytes(4, r.chain_log))
1146 } else {
1147 table_bytes(4, r.hash_bits).saturating_add(table_bytes(2, r.hash_bits))
1148 }
1149 }),
1150 SearchMethod::HashChain | SearchMethod::BinaryTree => params.hc.map_or(0, |h| {
1151 let hash3 = if wants_hash3 {
1152 table_bytes(
1153 4,
1154 crate::encoding::match_table::storage::HC3_HASH_LOG
1155 .min(params.window_log as usize),
1156 )
1157 } else {
1158 0
1159 };
1160 table_bytes(4, h.hash_log)
1161 .saturating_add(table_bytes(4, h.chain_log))
1162 .saturating_add(hash3)
1163 }),
1164 };
1165 // BT modes box a `BtMatcher`; its retained scratch layout is budgeted
1166 // next to the struct so estimator and allocator evolve together.
1167 let bt = if uses_bt {
1168 crate::encoding::bt::BtMatcher::estimated_workspace_bytes()
1169 } else {
1170 0
1171 };
1172 // One allocation: each table region and the history rounded to `ALIGN`,
1173 // the block buffers behind them, and the padding that aligns its start.
1174 let laid_out = tables
1175 .saturating_add(3 * ALIGN)
1176 .saturating_add(region_bytes::<u8>(history))
1177 .saturating_add(crate::encoding::blocks::CompressedBlockScratch::workspace_bytes(block))
1178 .saturating_add(ALIGN - 1);
1179 // The backends that slide their window by blocks keep one length per
1180 // block in it, in a deque that grows by doubling. Plain arithmetic here
1181 // and in `beside`: `history / block` is at most the window over the
1182 // smallest block plus a few, and every term of `beside` is a constant or
1183 // bounded by the 128 KiB block, so neither comes near `usize::MAX`.
1184 let block_deque = if matches!(backend, crate::encoding::strategy::BackendTag::Simple) {
1185 0
1186 } else {
1187 2 * (history / block + 2) * core::mem::size_of::<usize>()
1188 };
1189 let splits =
1190 crate::encoding::levels::fastest::post_split_enabled(params.strategy_tag, window as u64);
1191 let beside = crate::encoding::frame_compressor::FseTables::max_heap_size()
1192 + crate::encoding::blocks::CompressedBlockScratch::max_retained_heap_size(block, splits)
1193 + 2 * crate::huff0::huff0_encoder::HuffmanTable::max_heap_size()
1194 + crate::huff0::huff0_encoder::WeightScratch::max_heap_size();
1195 // Saturating: the parts are each bounded, but their sum at the widest
1196 // window is more than a 32-bit `usize` counts, and a total that wrapped
1197 // would report a run as fitting a limit it cannot.
1198 laid_out
1199 .saturating_add(bt)
1200 .saturating_add(block_deque)
1201 .saturating_add(beside)
1202 .saturating_add(ldm)
1203}
1204
1205/// Extra steady-state workspace the optimal strategies (ordinals 7..=9,
1206/// btopt..btultra2) retain beyond the hash/chain tables: the boxed matcher
1207/// plus its scratch arenas, and the HC3 short-match side table for
1208/// btultra/btultra2 (capped by the window log). 0 for the other ordinals
1209/// (btlazy2's tree lives in the lazy backend's chain table).
1210pub fn estimated_bt_strategy_extra_bytes(strategy_ordinal: u32, window_log: u32) -> usize {
1211 if !(7..=9).contains(&strategy_ordinal) {
1212 return 0;
1213 }
1214 let hash3 = if matches!(strategy_ordinal, 8 | 9) {
1215 4usize << crate::encoding::match_table::storage::HC3_HASH_LOG.min(window_log as usize)
1216 } else {
1217 0
1218 };
1219 crate::encoding::bt::BtMatcher::estimated_workspace_bytes() + hash3
1220}
1221
1222/// Resolve a [`CompressionLevel`] (+ optional source-size hint) to the
1223/// concrete [`LevelParams`] the matcher runs: strategy tag, search method
1224/// (match-finder), window log, and per-backend config.
1225///
1226/// ## CRITICAL: input size changes the match-finder (and can change strategy)
1227///
1228/// The resolved geometry is a function of the SOURCE SIZE, not the level
1229/// alone. This is the easy-to-miss part (so read this before assuming a level
1230/// maps to one fixed match-finder). Every level except `Uncompressed` goes
1231/// through [`get_cparams`](crate::encoding::cparams::get_cparams), the port of
1232/// upstream zstd `ZSTD_getCParams_internal`, which runs its two stages:
1233///
1234/// 1. the `clevels.h` row for the (level, source-size tier) pair. The tier
1235/// changes the STRATEGY as well as the table widths: level 11 is lazy2 on
1236/// a large source and btopt on one of 16 KiB or less;
1237/// 2. `ZSTD_adjustCParams_internal`, which caps `window_log` to
1238/// ~`ceil_log2(source_size)` and shrinks the hash and chain logs to match.
1239///
1240/// THEN, inside the Row backend, the greedy/lazy band searches a hash chain
1241/// instead of rows when the resolved `window_log <= 14`
1242/// (`RowMatchGenerator::finder`) — exactly upstream's
1243/// `ZSTD_resolveRowMatchFinderMode` (the Row match-finder is used for
1244/// greedy/lazy/lazy2 ONLY when `windowLog > 14`) — and a btlazy2 level
1245/// searches the lazily-sorted binary tree; the parse itself is the same
1246/// `lazy_generic` body in all three cases. Net effect for the SAME level:
1247///
1248/// * small input (e.g. a 10 KiB fixture → `window_log` 14) → hash chain
1249/// (`ZSTD_HcFindBestMatch`, scalar chain walk);
1250/// * large input (e.g. 1 MiB → `window_log` 20) → rows (the SIMD-tag
1251/// row match-finder).
1252///
1253/// A dictionary frame resolves through [`resolve_level_params_with_dict`]
1254/// instead: the CDict's cParams (its own size tier) with the frame's
1255/// source-derived `window_log`. When comparing against C on a fixture,
1256/// resolve the match-finder from the fixture's size (and dictionary) first,
1257/// or you may optimise/benchmark a path C does not even take for that input.
1258pub(crate) fn resolve_level_params(
1259 level: CompressionLevel,
1260 source_size: Option<u64>,
1261) -> LevelParams {
1262 // Uncompressed = raw blocks, no match-finder. Not a cParams level, so it is
1263 // the one row resolved by hand rather than through `get_cparams`.
1264 if matches!(level, CompressionLevel::Uncompressed) {
1265 return LevelParams {
1266 strategy_tag: crate::encoding::strategy::StrategyTag::Fast,
1267 search: crate::encoding::strategy::SearchMethod::Fast,
1268 // Raw frames emit literal blocks and never reference history;
1269 // advertising a wider window only inflates the decoder-side buffer
1270 // reservation, so clamp to 17 (128 KiB) regardless of input size.
1271 window_log: 17,
1272 lazy_depth: 0,
1273 // Beyond-upstream: hash_log=14 (vs upstream's row-0 13) for ~2× fewer
1274 // collisions on structured corpora; mls=6 / step_size=2 mirror the
1275 // upstream "base for negative" row (targetLength=1 -> step 2).
1276 fast: Some(FastConfig {
1277 hash_log: 14,
1278 mls: 6,
1279 step_size: 2,
1280 }),
1281 dfast: None,
1282 hc: None,
1283 row: None,
1284 };
1285 }
1286 // Every other level resolves through the SINGLE C-faithful cParams source,
1287 // `cparams::get_cparams` (the port of `ZSTD_getCParams`). One place selects
1288 // strategy + table widths + the negative-level acceleration per
1289 // (level, srcSize) + the source-size window/hash down-clamp, so the encoder
1290 // never re-derives parameters from a parallel hand-tuned path. Named presets
1291 // map to their numeric level; the cParams source clamps out-of-range levels
1292 // (>22 to 22, negatives to MIN_CLEVEL) itself.
1293 let numeric = numeric_level(level);
1294 let src = source_size.unwrap_or(crate::encoding::cparams::CONTENTSIZE_UNKNOWN);
1295 level_params_from_cparams(crate::encoding::cparams::get_cparams(numeric, src, 0))
1296}
1297
1298/// The upstream numeric level a preset maps to.
1299pub(crate) fn numeric_level(level: CompressionLevel) -> i32 {
1300 match level {
1301 CompressionLevel::Uncompressed => unreachable!("raw frames resolve no cParams"),
1302 // Fastest = upstream level 1 (fast strategy, smallest real-compression
1303 // tables).
1304 CompressionLevel::Fastest => 1,
1305 // Default = upstream level 3 (the libzstd default).
1306 CompressionLevel::Default => CompressionLevel::DEFAULT_LEVEL,
1307 // Better = level 7: the lazy2 band — clearly above the fast/dfast levels
1308 // on ratio while still well under the binary-tree cost cliff.
1309 CompressionLevel::Better => 7,
1310 // Best = level 13: the first point of the deep binary-tree band that
1311 // strictly dominates every level below it on ratio (lower levels can tie
1312 // on window-bound corpora), so the alias sits on a config that always
1313 // wins rather than on a hair-thin margin.
1314 CompressionLevel::Best => 13,
1315 CompressionLevel::Level(n) => n,
1316 }
1317}
1318
1319/// How a greedy / lazy frame compressed with a dictionary takes its
1320/// match-finder from the dictionary's own cParams (upstream
1321/// `ZSTD_resetCCtx_usingCDict`).
1322#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1323pub(crate) struct RowDictPlan {
1324 /// `ZSTD_shouldAttachDict`: the dictionary tables are searched in place
1325 /// (`dictMatchState`) instead of being copied into the frame's tables.
1326 pub(crate) attach: bool,
1327 /// The CDict's `useRowMatchFinder`, inherited by the frame.
1328 pub(crate) use_row: bool,
1329 /// The CDict's cParams: the geometry (`hash_log`, `chain_log`,
1330 /// `search_log` → row width) and key width its tables were built with.
1331 pub(crate) cdict: crate::encoding::cparams::CParams,
1332}
1333
1334/// [`resolve_level_params`] for a frame that compresses with a dictionary of
1335/// `dict_size` bytes. Upstream builds the CDict with
1336/// `ZSTD_getCParams(level, UNKNOWN, dictSize, createCDict)` and the frame
1337/// then runs the CDict's strategy / widths / search depth / match-finder:
1338/// re-adjusted to the source when the dictionary is attached
1339/// (`ZSTD_resetCCtx_byAttachingCDict`), verbatim when it is copied
1340/// (`ZSTD_resetCCtx_byCopyingCDict`); only the frame's own `windowLog` is
1341/// kept. The CDict's strategy is taken whatever backend family the plain
1342/// level resolved to; a lazy-band CDict (greedy..btlazy2) also carries the
1343/// lazy backend's [`RowDictPlan`]. The caller's `overrides` are part of the
1344/// CDict's cParams, as they are for a dictionary upstream loads into a context
1345/// that carries them.
1346pub(crate) fn resolve_level_params_with_dict(
1347 level: CompressionLevel,
1348 source_size: Option<u64>,
1349 sizes: crate::encoding::DictionarySizes,
1350 overrides: &crate::encoding::parameters::ParamOverrides,
1351) -> (LevelParams, Option<RowDictPlan>) {
1352 use crate::encoding::cparams::{
1353 CONTENTSIZE_UNKNOWN, attach_cparams, copy_cparams, get_cdict_cparams, should_attach_dict,
1354 uses_row_match_finder,
1355 };
1356 let base = resolve_level_params(level, source_size);
1357 // A raw frame searches nothing, so a dictionary has no tier to give it.
1358 if sizes.content == 0 || matches!(level, CompressionLevel::Uncompressed) {
1359 return (base, None);
1360 }
1361 // The CDict's cParams decide the frame's strategy REGARDLESS of the
1362 // backend family the plain level resolved to for this source size
1363 // (upstream takes them unconditionally): L13 on a 4 KiB source is
1364 // btopt, but a 300 KiB CDict is btlazy2 and the frame runs btlazy2; L4
1365 // on a 1 MiB source is dfast, but a 4 KiB CDict is greedy. Only the
1366 // frame's own `windowLog` is kept.
1367 let cdict = get_cdict_cparams(numeric_level(level), sizes.serialized, overrides);
1368 // `ZSTD_shouldAttachDict`, bounded by the backend's attach representability:
1369 // the Fast / Dfast attached tables pack the dict position next to a tag, so
1370 // they index at most 2^24 content bytes. A larger dictionary is primed in
1371 // COPY mode, and the frame must then run the CDict's verbatim table
1372 // geometry (`byCopyingCDict`) — copying it into source-capped attach-mode
1373 // tables would collide away its matches.
1374 let attach_fits = match cdict.strategy {
1375 1 => sizes.content <= MAX_FAST_ATTACH_DICT_REGION,
1376 2 => sizes.content <= crate::encoding::dfast::DFAST_ATTACH_DICT_MAX_LEN,
1377 _ => true,
1378 };
1379 let attach = should_attach_dict(&cdict, source_size) && attach_fits;
1380 let window_log = u32::from(base.window_log);
1381 let frame = if attach {
1382 attach_cparams(
1383 cdict,
1384 source_size.unwrap_or(CONTENTSIZE_UNKNOWN),
1385 window_log,
1386 )
1387 } else {
1388 copy_cparams(cdict, window_log)
1389 };
1390 let params = level_params_from_cparams(frame);
1391 if !(3..=6).contains(&cdict.strategy) {
1392 // Fast / dfast / optimal strategies: their backends prime the
1393 // dictionary themselves; no lazy-backend plan.
1394 return (params, None);
1395 }
1396 (
1397 params,
1398 Some(RowDictPlan {
1399 attach,
1400 use_row: uses_row_match_finder(&cdict),
1401 cdict,
1402 }),
1403 )
1404}
1405
1406/// The cheap fingerprint pre-splitter level for a compression level (the
1407/// C-like `blockSplitterLevel`), resolved through the same per-level
1408/// `LevelParams` table as every other tuning knob. `None` keeps the whole
1409/// 128 KiB block. The frame loop reads this instead of hardcoding the
1410/// level→split mapping at the call site.
1411pub(crate) fn level_pre_split(level: CompressionLevel) -> Option<usize> {
1412 // Resolve through `resolve_level_params` directly — NOT via the legacy
1413 // `numeric_level()` alias — so named presets read the SAME table row as
1414 // every other tuning knob (`Best` maps to its own row there, which is
1415 // not the row its numeric alias points at). `Uncompressed` (raw
1416 // blocks) never splits.
1417 if matches!(level, CompressionLevel::Uncompressed) {
1418 return None;
1419 }
1420 resolve_level_params(level, None)
1421 .pre_split()
1422 .map(usize::from)
1423}
1424
1425#[cfg(test)]
1426mod tests;