structured-zstd 0.0.41

Pure Rust zstd implementation — managed fork of ruzstd. Dictionary decompression, no FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Fine-grained compression parameters — the drop-in equivalent of C
//! zstd's advanced `ZSTD_CCtx_setParameter` surface (#27).
//!
//! [`CompressionLevel`](crate::encoding::CompressionLevel) selects a
//! whole tuning preset in one knob. This module exposes the individual
//! knobs underneath it — window/hash/chain/search logs, the match
//! strategy, and the long-distance-matching (LDM) block — so callers
//! can override a level's defaults for domain-specific tuning.
//!
//! # Builder
//!
//! [`CompressionParameters`] is built through
//! [`CompressionParameters::builder`], which takes an explicit base
//! [`CompressionLevel`](crate::encoding::CompressionLevel) (there is no
//! implicit default). Every knob left unset inherits that base level's
//! resolved value, so a builder that overrides nothing reproduces plain
//! level-based compression byte-for-byte.
//!
//! ```rust
//! use structured_zstd::encoding::{CompressionLevel, CompressionParameters, Strategy};
//!
//! let params = CompressionParameters::builder(CompressionLevel::Level(19))
//!     .window_log(22)
//!     .strategy(Strategy::Btultra2)
//!     .enable_long_distance_matching(true)
//!     .build()
//!     .expect("parameters within bounds");
//! ```
//!
//! # Bounds
//!
//! Every knob has an inclusive `[lower, upper]` range, queryable via
//! [`CParameter::bounds`] (the analogue of `ZSTD_cParam_getBounds`).
//! [`CompressionParametersBuilder::build`] validates each set knob and
//! returns [`ParameterError::OutOfBounds`] for the first violation.
//!
//! # Long-distance matching (LDM)
//!
//! LDM is **off at every [`CompressionLevel`](crate::encoding::CompressionLevel)
//! preset**, matching upstream `libzstd.so.1` where `ZSTD_compress(..., level)`
//! never enables LDM — even at level 22. It is activated either by
//! [`CompressionParametersBuilder::enable_long_distance_matching`] or by any of
//! the `ldm_*` setters, which each imply `enable_long_distance_matching(true)`.
//! When enabled, the LDM producer attaches to the optimal (`btopt` / `btultra`
//! / `btultra2`) match-finder; pair it with an optimal [`Strategy`] (or a level
//! ≥ 16) for it to take effect.

use crate::encoding::CompressionLevel;

/// Match-finder strategy — the drop-in equivalent of C zstd's
/// `ZSTD_strategy` enum (`ZSTD_fast` … `ZSTD_btultra2`). The numeric
/// ordinals match upstream (`fast = 1` … `btultra2 = 9`), so
/// [`Strategy::ordinal`] / [`Strategy::from_ordinal`] round-trip with
/// the C `ZSTD_c_strategy` parameter value.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Strategy {
    /// `ZSTD_fast` (1) — single-table fast finder.
    Fast,
    /// `ZSTD_dfast` (2) — two parallel hash tables.
    Dfast,
    /// `ZSTD_greedy` (3) — commit the first acceptable match, no lookahead.
    Greedy,
    /// `ZSTD_lazy` (4) — one-position lazy lookahead.
    Lazy,
    /// `ZSTD_lazy2` (5) — two-position lazy lookahead.
    Lazy2,
    /// `ZSTD_btlazy2` (6) — binary-tree-assisted lazy2.
    Btlazy2,
    /// `ZSTD_btopt` (7) — optimal parser, no ultra refinements.
    Btopt,
    /// `ZSTD_btultra` (8) — optimal parser with refined price tables.
    Btultra,
    /// `ZSTD_btultra2` (9) — optimal parser with two-pass dynamic stats.
    Btultra2,
}

impl Strategy {
    /// Upstream `ZSTD_strategy` ordinal (`fast = 1` … `btultra2 = 9`).
    pub const fn ordinal(self) -> u32 {
        match self {
            Self::Fast => 1,
            Self::Dfast => 2,
            Self::Greedy => 3,
            Self::Lazy => 4,
            Self::Lazy2 => 5,
            Self::Btlazy2 => 6,
            Self::Btopt => 7,
            Self::Btultra => 8,
            Self::Btultra2 => 9,
        }
    }

    /// Construct from an upstream `ZSTD_strategy` ordinal. Returns
    /// `None` outside `1..=9`.
    pub const fn from_ordinal(ordinal: u32) -> Option<Self> {
        Some(match ordinal {
            1 => Self::Fast,
            2 => Self::Dfast,
            3 => Self::Greedy,
            4 => Self::Lazy,
            5 => Self::Lazy2,
            6 => Self::Btlazy2,
            7 => Self::Btopt,
            8 => Self::Btultra,
            9 => Self::Btultra2,
            _ => return None,
        })
    }

    /// Internal runtime strategy tag.
    pub(crate) const fn tag(self) -> crate::encoding::strategy::StrategyTag {
        use crate::encoding::strategy::StrategyTag;
        match self {
            Self::Fast => StrategyTag::Fast,
            Self::Dfast => StrategyTag::Dfast,
            Self::Greedy => StrategyTag::Greedy,
            // Lazy / Lazy2 ride the runtime `Lazy` tag (the lazy lookahead
            // depth carries the variance, see `lazy_depth`). `Btlazy2`
            // keeps its own tag: `Lazy` resolves to the Row finder, while
            // btlazy2 is a binary-tree search and must stay on the
            // HashChain/BT storage.
            Self::Lazy | Self::Lazy2 => StrategyTag::Lazy,
            Self::Btlazy2 => StrategyTag::Btlazy2,
            Self::Btopt => StrategyTag::BtOpt,
            Self::Btultra => StrategyTag::BtUltra,
            Self::Btultra2 => StrategyTag::BtUltra2,
        }
    }

    /// Lazy lookahead depth for the greedy/lazy band (0/1/2). `Optimal`
    /// strategies report 2 (the depth their hash-chain seed walk runs at).
    pub(crate) const fn lazy_depth(self) -> u8 {
        match self {
            Self::Fast | Self::Dfast | Self::Greedy => 0,
            Self::Lazy => 1,
            _ => 2,
        }
    }
}

/// One tunable compression parameter — the analogue of a C zstd
/// `ZSTD_cParameter`. Used to query bounds via [`CParameter::bounds`].
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CParameter {
    /// Maximum back-reference distance, `log2`. C `ZSTD_c_windowLog`.
    WindowLog,
    /// Match-finder hash table size, `log2`. C `ZSTD_c_hashLog`.
    HashLog,
    /// Match-finder chain table size, `log2`. C `ZSTD_c_chainLog`.
    ChainLog,
    /// Number of search attempts, `log2`. C `ZSTD_c_searchLog`.
    SearchLog,
    /// Minimum match length in bytes. C `ZSTD_c_minMatch`.
    MinMatch,
    /// "Good enough" match length that ends the search. C `ZSTD_c_targetLength`.
    TargetLength,
    /// Match-finder [`Strategy`] (1..=9). C `ZSTD_c_strategy`.
    Strategy,
    /// LDM enable flag (0/1). C `ZSTD_c_enableLongDistanceMatching`.
    EnableLongDistanceMatching,
    /// LDM hash table size, `log2`. C `ZSTD_c_ldmHashLog`.
    LdmHashLog,
    /// LDM minimum match length in bytes. C `ZSTD_c_ldmMinMatch`.
    LdmMinMatch,
    /// LDM bucket size, `log2`. C `ZSTD_c_ldmBucketSizeLog`.
    LdmBucketSizeLog,
    /// LDM hash-insertion rate, `log2`. C `ZSTD_c_ldmHashRateLog`.
    LdmHashRateLog,
}

/// Inclusive `[lower_bound, upper_bound]` range for a [`CParameter`],
/// the drop-in equivalent of C zstd's `ZSTD_bounds`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Bounds {
    /// Smallest accepted value (inclusive).
    pub lower_bound: i64,
    /// Largest accepted value (inclusive).
    pub upper_bound: i64,
}

impl Bounds {
    /// Whether `value` falls within `[lower_bound, upper_bound]`.
    pub const fn contains(&self, value: i64) -> bool {
        value >= self.lower_bound && value <= self.upper_bound
    }
}

impl CParameter {
    /// Inclusive value bounds for this parameter, mirroring
    /// `ZSTD_cParam_getBounds`. Window/hash/chain logs cap at 30 (the
    /// encoder's match-finder ceiling) rather than the 31 C allows on
    /// 64-bit, because the back-reference history is indexed with `u32`
    /// positions over a `2 * window` eviction band.
    pub const fn bounds(self) -> Bounds {
        let (lower_bound, upper_bound) = match self {
            // ZSTD_WINDOWLOG_MIN .. encoder ceiling.
            Self::WindowLog => (10, 30),
            // ZSTD_HASHLOG_MIN .. ZSTD_HASHLOG_MAX.
            Self::HashLog => (6, 30),
            // ZSTD_CHAINLOG_MIN .. ZSTD_CHAINLOG_MAX (64-bit).
            Self::ChainLog => (6, 30),
            // ZSTD_SEARCHLOG_MIN .. ZSTD_SEARCHLOG_MAX (64-bit).
            Self::SearchLog => (1, 30),
            // ZSTD_MINMATCH_MIN .. ZSTD_MINMATCH_MAX.
            Self::MinMatch => (3, 7),
            // ZSTD_TARGETLENGTH_MIN .. ZSTD_TARGETLENGTH_MAX.
            Self::TargetLength => (0, 131_072),
            // ZSTD_fast .. ZSTD_btultra2.
            Self::Strategy => (1, 9),
            // Boolean flag.
            Self::EnableLongDistanceMatching => (0, 1),
            // ZSTD_LDM_HASHLOG_MIN .. ZSTD_LDM_HASHLOG_MAX.
            Self::LdmHashLog => (6, 30),
            // ZSTD_LDM_MINMATCH_MIN .. ZSTD_LDM_MINMATCH_MAX.
            Self::LdmMinMatch => (4, 4096),
            // ZSTD_LDM_BUCKETSIZELOG_MIN .. ZSTD_LDM_BUCKETSIZELOG_MAX.
            Self::LdmBucketSizeLog => (1, 8),
            // ZSTD_LDM_HASHRATELOG_MIN .. ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN.
            Self::LdmHashRateLog => (0, 24),
        };
        Bounds {
            lower_bound,
            upper_bound,
        }
    }
}

/// Error returned by [`CompressionParametersBuilder::build`] when a knob
/// is set outside its [`CParameter::bounds`].
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParameterError {
    /// A parameter was set to a value outside its inclusive bounds.
    OutOfBounds {
        /// Which parameter violated its range.
        parameter: CParameter,
        /// The rejected value.
        value: i64,
        /// The inclusive `[lower, upper]` range it had to fall within.
        bounds: Bounds,
    },
}

impl core::fmt::Display for ParameterError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::OutOfBounds {
                parameter,
                value,
                bounds,
            } => write!(
                f,
                "compression parameter {parameter:?} = {value} out of bounds \
                 [{}, {}]",
                bounds.lower_bound, bounds.upper_bound
            ),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParameterError {}

/// LDM tuning overrides — every knob is `Option`, falling back to the
/// strategy-derived upstream zstd default (`LdmParams::adjust_for`) when unset.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct LdmOverride {
    pub(crate) hash_log: Option<u32>,
    pub(crate) min_match: Option<u32>,
    pub(crate) bucket_size_log: Option<u32>,
    pub(crate) hash_rate_log: Option<u32>,
}

/// Internal per-knob override set consumed by the match-generator's
/// `reset` path. Every field left `None` inherits the base level's
/// resolved value, so the default path is byte-identical to level-based
/// compression.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ParamOverrides {
    pub(crate) window_log: Option<u8>,
    pub(crate) hash_log: Option<u32>,
    pub(crate) chain_log: Option<u32>,
    pub(crate) search_log: Option<u32>,
    pub(crate) min_match: Option<u32>,
    pub(crate) target_length: Option<u32>,
    pub(crate) strategy: Option<Strategy>,
    /// `Some` when `enable_long_distance_matching(true)` was set; carries
    /// the (possibly empty) LDM knob overrides.
    pub(crate) ldm: Option<LdmOverride>,
}

impl ParamOverrides {
    /// Whether any knob overrides the base level. An all-`None`
    /// override is a no-op the `reset` path can skip entirely, keeping
    /// the default level-based geometry byte-identical.
    pub(crate) fn is_empty(&self) -> bool {
        self.window_log.is_none()
            && self.hash_log.is_none()
            && self.chain_log.is_none()
            && self.search_log.is_none()
            && self.min_match.is_none()
            && self.target_length.is_none()
            && self.strategy.is_none()
            && self.ldm.is_none()
    }
}

/// Fully-resolved fine-grained compression parameters. Build through
/// [`CompressionParameters::builder`]; pass to
/// [`FrameCompressor::set_parameters`](crate::encoding::FrameCompressor::set_parameters)
/// or [`compress_with_parameters`](crate::encoding::compress_with_parameters).
///
/// Wraps a base [`CompressionLevel`](crate::encoding::CompressionLevel)
/// plus the set of knobs that override it. A parameter set that
/// overrides nothing is equivalent to compressing at its base level.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CompressionParameters {
    level: CompressionLevel,
    overrides: ParamOverrides,
}

impl CompressionParameters {
    /// Start a builder from a base compression level. Knobs left unset
    /// inherit that level's resolved defaults.
    pub fn builder(level: CompressionLevel) -> CompressionParametersBuilder {
        CompressionParametersBuilder {
            level,
            window_log: None,
            hash_log: None,
            chain_log: None,
            search_log: None,
            min_match: None,
            target_length: None,
            strategy: None,
            enable_ldm: false,
            ldm: LdmOverride::default(),
        }
    }

    /// The base compression level these parameters override.
    pub fn level(&self) -> CompressionLevel {
        self.level
    }

    /// Whether long-distance matching is enabled.
    pub fn long_distance_matching_enabled(&self) -> bool {
        self.overrides.ldm.is_some()
    }

    pub(crate) fn overrides(&self) -> ParamOverrides {
        self.overrides
    }
}

/// Builder for [`CompressionParameters`]. Each setter records one knob;
/// [`Self::build`] validates them against [`CParameter::bounds`].
#[derive(Copy, Clone, Debug)]
pub struct CompressionParametersBuilder {
    level: CompressionLevel,
    window_log: Option<u32>,
    hash_log: Option<u32>,
    chain_log: Option<u32>,
    search_log: Option<u32>,
    min_match: Option<u32>,
    target_length: Option<u32>,
    strategy: Option<Strategy>,
    enable_ldm: bool,
    ldm: LdmOverride,
}

impl CompressionParametersBuilder {
    /// Override the maximum back-reference distance (`log2`). C
    /// `ZSTD_c_windowLog`.
    pub fn window_log(mut self, value: u32) -> Self {
        self.window_log = Some(value);
        self
    }

    /// Override the match-finder hash table size (`log2`). C `ZSTD_c_hashLog`.
    pub fn hash_log(mut self, value: u32) -> Self {
        self.hash_log = Some(value);
        self
    }

    /// Override the match-finder chain table size (`log2`). C `ZSTD_c_chainLog`.
    pub fn chain_log(mut self, value: u32) -> Self {
        self.chain_log = Some(value);
        self
    }

    /// Override the search-attempts count (`log2`). C `ZSTD_c_searchLog`.
    pub fn search_log(mut self, value: u32) -> Self {
        self.search_log = Some(value);
        self
    }

    /// Override the minimum match length in bytes. C `ZSTD_c_minMatch`.
    pub fn min_match(mut self, value: u32) -> Self {
        self.min_match = Some(value);
        self
    }

    /// Override the "good enough" target match length. C `ZSTD_c_targetLength`.
    pub fn target_length(mut self, value: u32) -> Self {
        self.target_length = Some(value);
        self
    }

    /// Override the match-finder [`Strategy`]. C `ZSTD_c_strategy`.
    pub fn strategy(mut self, value: Strategy) -> Self {
        self.strategy = Some(value);
        self
    }

    /// Enable or disable long-distance matching. C
    /// `ZSTD_c_enableLongDistanceMatching`. Off at every level preset.
    /// This is the explicit activation toggle; the `ldm_*` knob setters
    /// also enable LDM implicitly. The flag is plain last-write-wins, so
    /// a trailing `enable_long_distance_matching(false)` disables LDM even
    /// if an earlier `ldm_*` call set a knob (the knob is then ignored at
    /// [`build`](Self::build)).
    pub fn enable_long_distance_matching(mut self, enable: bool) -> Self {
        self.enable_ldm = enable;
        self
    }

    /// Override the LDM hash table size (`log2`). C `ZSTD_c_ldmHashLog`.
    /// Implies [`Self::enable_long_distance_matching(true)`](Self::enable_long_distance_matching).
    pub fn ldm_hash_log(mut self, value: u32) -> Self {
        self.enable_ldm = true;
        self.ldm.hash_log = Some(value);
        self
    }

    /// Override the LDM minimum match length. C `ZSTD_c_ldmMinMatch`.
    /// Implies [`Self::enable_long_distance_matching(true)`](Self::enable_long_distance_matching).
    pub fn ldm_min_match(mut self, value: u32) -> Self {
        self.enable_ldm = true;
        self.ldm.min_match = Some(value);
        self
    }

    /// Override the LDM bucket size (`log2`). C `ZSTD_c_ldmBucketSizeLog`.
    /// Implies [`Self::enable_long_distance_matching(true)`](Self::enable_long_distance_matching).
    pub fn ldm_bucket_size_log(mut self, value: u32) -> Self {
        self.enable_ldm = true;
        self.ldm.bucket_size_log = Some(value);
        self
    }

    /// Override the LDM hash-insertion rate (`log2`). C `ZSTD_c_ldmHashRateLog`.
    /// Implies [`Self::enable_long_distance_matching(true)`](Self::enable_long_distance_matching).
    pub fn ldm_hash_rate_log(mut self, value: u32) -> Self {
        self.enable_ldm = true;
        self.ldm.hash_rate_log = Some(value);
        self
    }

    /// Validate every set knob against [`CParameter::bounds`] and
    /// produce the resolved [`CompressionParameters`].
    ///
    /// # Errors
    ///
    /// Returns [`ParameterError::OutOfBounds`] for the first knob whose
    /// value falls outside its inclusive range.
    pub fn build(self) -> Result<CompressionParameters, ParameterError> {
        check(CParameter::WindowLog, self.window_log)?;
        check(CParameter::HashLog, self.hash_log)?;
        check(CParameter::ChainLog, self.chain_log)?;
        check(CParameter::SearchLog, self.search_log)?;
        check(CParameter::MinMatch, self.min_match)?;
        check(CParameter::TargetLength, self.target_length)?;
        if let Some(s) = self.strategy {
            check(CParameter::Strategy, Some(s.ordinal()))?;
        }
        let ldm = if self.enable_ldm {
            check(CParameter::LdmHashLog, self.ldm.hash_log)?;
            check(CParameter::LdmMinMatch, self.ldm.min_match)?;
            check(CParameter::LdmBucketSizeLog, self.ldm.bucket_size_log)?;
            check(CParameter::LdmHashRateLog, self.ldm.hash_rate_log)?;
            Some(self.ldm)
        } else {
            None
        };
        Ok(CompressionParameters {
            level: self.level,
            overrides: ParamOverrides {
                // `window_log` is bounds-checked at <= 30, so the cast is lossless.
                window_log: self.window_log.map(|v| v as u8),
                hash_log: self.hash_log,
                chain_log: self.chain_log,
                search_log: self.search_log,
                min_match: self.min_match,
                target_length: self.target_length,
                strategy: self.strategy,
                ldm,
            },
        })
    }
}

/// Validate one optional knob against its bounds.
fn check(parameter: CParameter, value: Option<u32>) -> Result<(), ParameterError> {
    if let Some(value) = value {
        let bounds = parameter.bounds();
        let value = i64::from(value);
        if !bounds.contains(value) {
            return Err(ParameterError::OutOfBounds {
                parameter,
                value,
                bounds,
            });
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn strategy_ordinals_round_trip() {
        for ordinal in 1..=9 {
            let s = Strategy::from_ordinal(ordinal).expect("valid ordinal");
            assert_eq!(s.ordinal(), ordinal);
        }
        assert_eq!(Strategy::from_ordinal(0), None);
        assert_eq!(Strategy::from_ordinal(10), None);
    }

    #[test]
    fn builder_default_overrides_nothing() {
        let p = CompressionParameters::builder(CompressionLevel::Level(7))
            .build()
            .unwrap();
        assert!(p.overrides().is_empty());
        assert_eq!(p.level(), CompressionLevel::Level(7));
        assert!(!p.long_distance_matching_enabled());
    }

    #[test]
    fn builder_records_each_knob() {
        let p = CompressionParameters::builder(CompressionLevel::Level(19))
            .window_log(22)
            .hash_log(23)
            .chain_log(24)
            .search_log(7)
            .min_match(4)
            .target_length(256)
            .strategy(Strategy::Btultra2)
            .build()
            .unwrap();
        let o = p.overrides();
        assert_eq!(o.window_log, Some(22));
        assert_eq!(o.hash_log, Some(23));
        assert_eq!(o.chain_log, Some(24));
        assert_eq!(o.search_log, Some(7));
        assert_eq!(o.min_match, Some(4));
        assert_eq!(o.target_length, Some(256));
        assert_eq!(o.strategy, Some(Strategy::Btultra2));
        assert!(!o.is_empty());
    }

    #[test]
    fn enable_ldm_sets_override_block() {
        let p = CompressionParameters::builder(CompressionLevel::Level(19))
            .enable_long_distance_matching(true)
            .build()
            .unwrap();
        assert!(p.long_distance_matching_enabled());
        assert_eq!(p.overrides().ldm, Some(LdmOverride::default()));
    }

    #[test]
    fn ldm_knob_implies_enable() {
        let p = CompressionParameters::builder(CompressionLevel::Level(19))
            .ldm_hash_log(24)
            .ldm_min_match(64)
            .ldm_bucket_size_log(4)
            .ldm_hash_rate_log(7)
            .build()
            .unwrap();
        assert!(p.long_distance_matching_enabled());
        let ldm = p.overrides().ldm.unwrap();
        assert_eq!(ldm.hash_log, Some(24));
        assert_eq!(ldm.min_match, Some(64));
        assert_eq!(ldm.bucket_size_log, Some(4));
        assert_eq!(ldm.hash_rate_log, Some(7));
    }

    #[test]
    fn out_of_bounds_window_log_rejected() {
        let err = CompressionParameters::builder(CompressionLevel::Default)
            .window_log(31)
            .build()
            .unwrap_err();
        match err {
            ParameterError::OutOfBounds {
                parameter, value, ..
            } => {
                assert_eq!(parameter, CParameter::WindowLog);
                assert_eq!(value, 31);
            }
        }
    }

    #[test]
    fn out_of_bounds_min_match_rejected() {
        let err = CompressionParameters::builder(CompressionLevel::Default)
            .min_match(2)
            .build()
            .unwrap_err();
        assert!(matches!(
            err,
            ParameterError::OutOfBounds {
                parameter: CParameter::MinMatch,
                ..
            }
        ));
    }

    #[test]
    fn ldm_bounds_only_checked_when_enabled() {
        // An out-of-range LDM knob is only rejected when LDM is on. A
        // builder that never enables LDM ignores the (unreachable)
        // values entirely.
        let err = CompressionParameters::builder(CompressionLevel::Default)
            .ldm_bucket_size_log(9)
            .build()
            .unwrap_err();
        assert!(matches!(
            err,
            ParameterError::OutOfBounds {
                parameter: CParameter::LdmBucketSizeLog,
                ..
            }
        ));
    }

    #[test]
    fn bounds_match_c_reference() {
        assert_eq!(
            CParameter::WindowLog.bounds(),
            Bounds {
                lower_bound: 10,
                upper_bound: 30
            }
        );
        assert_eq!(
            CParameter::Strategy.bounds(),
            Bounds {
                lower_bound: 1,
                upper_bound: 9
            }
        );
        assert_eq!(
            CParameter::TargetLength.bounds(),
            Bounds {
                lower_bound: 0,
                upper_bound: 131_072
            }
        );
        assert!(CParameter::MinMatch.bounds().contains(3));
        assert!(CParameter::MinMatch.bounds().contains(7));
        assert!(!CParameter::MinMatch.bounds().contains(8));
    }
}