async_mtzip/zip/
level.rs

1//! Compression level
2
3use core::fmt::Display;
4use std::error::Error;
5
6
7/// Compression level that should be used when compressing a file or data.
8///
9/// Current compression providers support only levels from 0 to 9, so these are the only ones being
10/// supported.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
12pub struct CompressionLevel(u8);
13
14impl CompressionLevel {
15    /// Construct a new value of a compression level setting.
16    ///
17    /// The integer value must be less than or equal to 9, otherwise `None` is returned
18    #[inline]
19    pub const fn new(level: u8) -> Option<Self> {
20        if level <= 9 {
21            Some(Self(level))
22        } else {
23            None
24        }
25    }
26
27    /// Construct a new value of a compression level setting without checking the value.
28    ///
29    /// # Safety
30    ///
31    /// The value must be a valid supported compression level
32    #[inline]
33    pub const unsafe fn new_unchecked(level: u8) -> Self {
34        Self(level)
35    }
36
37    /// No compression
38    #[inline]
39    pub const fn none() -> Self {
40        Self(0)
41    }
42
43    /// Fastest compression
44    #[inline]
45    pub const fn fast() -> Self {
46        Self(1)
47    }
48
49    /// Balanced level with moderate compression and speed. The raw value is 6.
50    #[inline]
51    pub const fn balanced() -> Self {
52        Self(6)
53    }
54
55    /// Best compression ratio, comes at a worse performance
56    #[inline]
57    pub const fn best() -> Self {
58        Self(9)
59    }
60
61    /// Get the compression level as an integer
62    #[inline]
63    pub const fn get(self) -> u8 {
64        self.0
65    }
66}
67
68impl Default for CompressionLevel {
69    /// Equivalent to [`Self::balanced`]
70    fn default() -> Self {
71        Self::balanced()
72    }
73}
74
75/// The number for compression level was invalid
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct InvalidCompressionLevel(u32);
78
79impl InvalidCompressionLevel {
80    /// The value which was supplied
81    pub fn value(self) -> u32 {
82        self.0
83    }
84}
85
86impl Display for InvalidCompressionLevel {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(f, "Invalid compression level number: {}", self.0)
89    }
90}
91
92impl Error for InvalidCompressionLevel {}
93
94impl From<CompressionLevel> for u8 {
95    #[inline]
96    fn from(value: CompressionLevel) -> Self {
97        value.0
98    }
99}
100
101impl TryFrom<u8> for CompressionLevel {
102    type Error = InvalidCompressionLevel;
103
104    #[inline]
105    fn try_from(value: u8) -> Result<Self, Self::Error> {
106        Self::new(value).ok_or(InvalidCompressionLevel(value.into()))
107    }
108}