1//! Compression level
23use core::fmt::Display;
4use std::error::Error;
567/// 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);
1314impl 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]
19pub const fn new(level: u8) -> Option<Self> {
20if level <= 9 {
21Some(Self(level))
22 } else {
23None
24}
25 }
2627/// 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]
33pub const unsafe fn new_unchecked(level: u8) -> Self {
34Self(level)
35 }
3637/// No compression
38#[inline]
39pub const fn none() -> Self {
40Self(0)
41 }
4243/// Fastest compression
44#[inline]
45pub const fn fast() -> Self {
46Self(1)
47 }
4849/// Balanced level with moderate compression and speed. The raw value is 6.
50#[inline]
51pub const fn balanced() -> Self {
52Self(6)
53 }
5455/// Best compression ratio, comes at a worse performance
56#[inline]
57pub const fn best() -> Self {
58Self(9)
59 }
6061/// Get the compression level as an integer
62#[inline]
63pub const fn get(self) -> u8 {
64self.0
65}
66}
6768impl Default for CompressionLevel {
69/// Equivalent to [`Self::balanced`]
70fn default() -> Self {
71Self::balanced()
72 }
73}
7475/// The number for compression level was invalid
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct InvalidCompressionLevel(u32);
7879impl InvalidCompressionLevel {
80/// The value which was supplied
81pub fn value(self) -> u32 {
82self.0
83}
84}
8586impl Display for InvalidCompressionLevel {
87fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88write!(f, "Invalid compression level number: {}", self.0)
89 }
90}
9192impl Error for InvalidCompressionLevel {}
9394impl From<CompressionLevel> for u8 {
95#[inline]
96fn from(value: CompressionLevel) -> Self {
97 value.0
98}
99}
100101impl TryFrom<u8> for CompressionLevel {
102type Error = InvalidCompressionLevel;
103104#[inline]
105fn try_from(value: u8) -> Result<Self, Self::Error> {
106Self::new(value).ok_or(InvalidCompressionLevel(value.into()))
107 }
108}