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