http_compress/compress/
impl.rs

1use crate::*;
2
3/// Provides the default value for the `Compress` enum, which is `Unknown`.
4impl Default for Compress {
5    fn default() -> Self {
6        Self::Unknown
7    }
8}
9
10/// Enables parsing a string into a `Compress` enum variant.
11///
12/// This implementation allows converting string representations of compression
13/// algorithms (like "gzip", "deflate", "br") into their corresponding `Compress`
14/// enum variants. If the string does not match any known compression types,
15/// it defaults to `Compress::Unknown`.
16impl FromStr for Compress {
17    type Err = ();
18
19    /// Parses a string into a `Compress` enum variant.
20    ///
21    /// This method converts string representations of compression algorithms
22    /// (case-insensitive) into their corresponding `Compress` enum variants.
23    /// Unknown strings are converted to `Compress::Unknown`.
24    ///
25    /// # Arguments
26    ///
27    /// - `data` - The string to parse, which should be a compression algorithm name.
28    ///
29    /// # Returns
30    ///
31    /// - `Result<Self, Self::Err>` - Returns `Ok` with the matching `Compress` variant,
32    ///   or `Ok(Compress::Unknown)` for unknown strings. Never returns `Err`.
33    fn from_str(data: &str) -> Result<Self, Self::Err> {
34        match data.to_lowercase().as_str() {
35            _data if _data == CONTENT_ENCODING_GZIP => Ok(Self::Gzip),
36            _data if _data == CONTENT_ENCODING_DEFLATE => Ok(Self::Deflate),
37            _data if _data == CONTENT_ENCODING_BROTLI => Ok(Self::Br),
38            _ => Ok(Self::Unknown),
39        }
40    }
41}
42
43/// Implements the `Display` trait for the `Compress` enum.
44///
45/// This allows the `Compress` enum variants to be formatted as strings,
46/// typically used for outputting the `Content-Encoding` header value.
47impl fmt::Display for Compress {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        let display_str = match *self {
50            Compress::Gzip => CONTENT_ENCODING_GZIP,
51            Compress::Deflate => CONTENT_ENCODING_DEFLATE,
52            Compress::Br => CONTENT_ENCODING_BROTLI,
53            Compress::Unknown => EMPTY_STR,
54        };
55        write!(f, "{}", display_str)
56    }
57}
58
59/// Provides methods for interacting with the `Compress` enum.
60impl Compress {
61    /// Checks if the current instance is of the `Unknown` type.
62    ///
63    /// This method compares the current instance with the `Unknown` variant of the enum.
64    /// It returns `true` if the instance is of type `Unknown`, otherwise `false`.
65    ///
66    /// # Returns
67    ///
68    /// - `true` if the instance is of type `Unknown`.
69    /// - `false` otherwise.
70    pub fn is_unknown(&self) -> bool {
71        *self == Self::Unknown
72    }
73
74    /// Extracts the compression type from an HTTP header.
75    ///
76    /// This function looks for the `Content-Encoding` header in the provided `Header` and attempts
77    /// to parse it into a `Compress` enum value.
78    ///
79    /// # Arguments
80    ///
81    /// - `header` - The HTTP header from which the compression type is to be extracted.
82    ///
83    /// # Returns
84    ///
85    /// - The `Compress` value corresponding to the `Content-Encoding` header, or `Compress::Unknown`
86    ///   if the header does not match any known compression types.
87    pub fn from(header: &HashMap<String, String, BuildHasherDefault<XxHash3_64>>) -> Self {
88        header
89            .get(CONTENT_ENCODING)
90            .map(|value| value.parse::<Compress>().unwrap_or_default())
91            .unwrap_or_default()
92    }
93
94    /// Decompresses the given data based on the selected compression algorithm.
95    ///
96    /// This method takes a byte slice of compressed data and decompresses it using one of the following
97    /// compression algorithms, depending on the variant of the enum it is called on:
98    /// - `Gzip` - Decompresses using Gzip compression.
99    /// - `Deflate` - Decompresses using Deflate compression.
100    /// - `Br` - Decompresses using Brotli compression.
101    /// - `Unknown` - Returns the input data as-is (no decompression performed).
102    ///
103    /// # Parameters
104    ///
105    /// - `data` - A reference to a byte slice (`&[u8]`) containing the compressed data to be decoded.
106    /// - `buffer_size` - The buffer size to use for the decompression process. A larger buffer size can
107    ///   improve performance for larger datasets.
108    ///
109    /// # Returns
110    ///
111    /// - `Cow<Vec<u8>>` - The decompressed data as a `Cow<Vec<u8>>`. If the compression algorithm
112    ///   is `Unknown`, the original data is returned unchanged, as a borrowed reference. Otherwise,
113    ///   the decompressed data is returned as an owned `Vec<u8>`.
114    pub fn decode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, Vec<u8>> {
115        match self {
116            Self::Gzip => gzip::decode::decode(data, buffer_size),
117            Self::Deflate => deflate::decode::decode(data, buffer_size),
118            Self::Br => brotli::decode::decode(data, buffer_size),
119            Self::Unknown => Cow::Owned(data.to_vec()),
120        }
121    }
122
123    /// Compresses the given data based on the selected compression algorithm.
124    ///
125    /// This method takes a byte slice of data and compresses it using one of the following
126    /// compression algorithms, depending on the variant of the enum it is called on:
127    /// - `Gzip` - Compresses using Gzip compression.
128    /// - `Deflate` - Compresses using Deflate compression.
129    /// - `Br` - Compresses using Brotli compression.
130    /// - `Unknown` - Returns the input data as-is (no compression performed).
131    ///
132    /// # Parameters
133    ///
134    /// - `data` - A reference to a byte slice (`&[u8]`) containing the data to be compressed.
135    /// - `buffer_size` - The buffer size to use for the compression process. A larger buffer size can
136    ///   improve performance for larger datasets.
137    ///
138    /// # Returns
139    ///
140    /// - `Cow<Vec<u8>>` - The compressed data as a `Cow<Vec<u8>>`. If the compression algorithm
141    ///   is `Unknown`, the original data is returned unchanged, as a borrowed reference. Otherwise,
142    ///   the compressed data is returned as an owned `Vec<u8>`.
143    pub fn encode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, Vec<u8>> {
144        match self {
145            Self::Gzip => gzip::encode::encode(data, buffer_size),
146            Self::Deflate => deflate::encode::encode(data, buffer_size),
147            Self::Br => brotli::encode::encode(data),
148            Self::Unknown => Cow::Owned(data.to_vec()),
149        }
150    }
151}