Skip to main content

pltrs_codec/deflate/
level.rs

1//! Compression levels and the match-finder parameters each one selects.
2
3use std::error::Error;
4use std::fmt;
5
6/// A zlib-compatible compression level from 0 (store only) to 9 (smallest).
7///
8/// Levels trade speed for size as zlib-ng's do: level 0 emits stored
9/// blocks, level 1 one fixed-code block of the first matches found, level
10/// 2 greedy parsing, levels 3 to 6 greedy parsing with a look-ahead match
11/// and levels 7 to 9 lazy matching, with progressively longer hash-chain
12/// searches.
13///
14/// ```
15/// use pltrs_codec::CompressionLevel;
16///
17/// let level = CompressionLevel::new(6)?;
18/// assert_eq!(level, CompressionLevel::DEFAULT);
19/// assert!(CompressionLevel::new(10).is_err());
20/// # Ok::<(), pltrs_codec::deflate::InvalidCompressionLevel>(())
21/// ```
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct CompressionLevel(u8);
24
25impl CompressionLevel {
26    /// Level 0: no compression, the data is stored verbatim.
27    pub const NONE: Self = Self(0);
28    /// Level 1: the fastest compressing level.
29    pub const FASTEST: Self = Self(1);
30    /// Level 6: zlib's default balance between speed and size.
31    pub const DEFAULT: Self = Self(6);
32    /// Level 9: the smallest output.
33    pub const BEST: Self = Self(9);
34
35    /// Returns the level `level`, which must be at most 9.
36    pub const fn new(level: u8) -> Result<Self, InvalidCompressionLevel> {
37        if level <= 9 {
38            Ok(Self(level))
39        } else {
40            Err(InvalidCompressionLevel(level))
41        }
42    }
43
44    /// Returns the numeric level, 0–9.
45    pub const fn get(self) -> u8 {
46        self.0
47    }
48}
49
50impl Default for CompressionLevel {
51    fn default() -> Self {
52        Self::DEFAULT
53    }
54}
55
56impl TryFrom<u8> for CompressionLevel {
57    type Error = InvalidCompressionLevel;
58
59    fn try_from(level: u8) -> Result<Self, Self::Error> {
60        Self::new(level)
61    }
62}
63
64impl From<CompressionLevel> for u8 {
65    fn from(level: CompressionLevel) -> Self {
66        level.0
67    }
68}
69
70/// Error returned for a compression level above 9.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub struct InvalidCompressionLevel(pub u8);
73
74impl fmt::Display for InvalidCompressionLevel {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(f, "invalid compression level {}; expected 0 to 9", self.0)
77    }
78}
79
80impl Error for InvalidCompressionLevel {}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn levels_validate_range() {
88        for level in 0..=9 {
89            assert_eq!(
90                CompressionLevel::new(level).map(CompressionLevel::get),
91                Ok(level)
92            );
93        }
94        assert_eq!(
95            CompressionLevel::try_from(10),
96            Err(InvalidCompressionLevel(10))
97        );
98        assert_eq!(
99            InvalidCompressionLevel(42).to_string(),
100            "invalid compression level 42; expected 0 to 9"
101        );
102        assert_eq!(CompressionLevel::default(), CompressionLevel::DEFAULT);
103        assert_eq!(u8::from(CompressionLevel::BEST), 9);
104    }
105}