pltrs_codec/deflate/
level.rs1use std::error::Error;
4use std::fmt;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct CompressionLevel(u8);
24
25impl CompressionLevel {
26 pub const NONE: Self = Self(0);
28 pub const FASTEST: Self = Self(1);
30 pub const DEFAULT: Self = Self(6);
32 pub const BEST: Self = Self(9);
34
35 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 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#[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}