Skip to main content

http_compress/compress/
impl.rs

1use super::*;
2
3/// Enables parsing a string into a `Compress` enum variant.
4///
5/// This implementation allows converting string representations of compression
6/// algorithms (like "gzip", "deflate", "br") into their corresponding `Compress`
7/// enum variants. If the string does not match any known compression types,
8/// it defaults to `Compress::Unknown`.
9impl FromStr for Compress {
10    type Err = ();
11
12    /// Parses a string into a `Compress` enum variant.
13    ///
14    /// This method converts string representations of compression algorithms
15    /// (case-insensitive) into their corresponding `Compress` enum variants.
16    /// Unknown strings are converted to `Compress::Unknown`.
17    ///
18    /// # Arguments
19    ///
20    /// - `&str` - The string to parse, which should be a compression algorithm name.
21    ///
22    /// # Returns
23    ///
24    /// - `Result<Self, Self::Err>` - Returns `Ok` with the matching `Compress` variant,
25    ///   or `Ok(Compress::Unknown)` for unknown strings. Never returns `Err`.
26    #[inline(always)]
27    fn from_str(data: &str) -> Result<Self, Self::Err> {
28        if data.eq_ignore_ascii_case(CONTENT_ENCODING_GZIP)
29            || data.eq_ignore_ascii_case(CONTENT_ENCODING_X_GZIP)
30        {
31            Ok(Self::Gzip)
32        } else if data.eq_ignore_ascii_case(CONTENT_ENCODING_DEFLATE) {
33            Ok(Self::Deflate)
34        } else if data.eq_ignore_ascii_case(CONTENT_ENCODING_BROTLI) {
35            Ok(Self::Br)
36        } else {
37            Ok(Self::Unknown)
38        }
39    }
40}
41
42/// Implements the `Display` trait for the `Compress` enum.
43///
44/// This allows the `Compress` enum variants to be formatted as strings,
45/// typically used for outputting the `Content-Encoding` header value.
46impl fmt::Display for Compress {
47    /// Formats the `Compress` value as its `Content-Encoding` header token.
48    ///
49    /// `Compress::Unknown` formats as the empty string, since it has no
50    /// `Content-Encoding` representation.
51    ///
52    /// # Arguments
53    ///
54    /// - `&mut fmt::Formatter<'_>` - The formatter to write the value into.
55    ///
56    /// # Returns
57    ///
58    /// - `fmt::Result` - The result of the formatting operation.
59    #[inline(always)]
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(f, "{}", self.as_str())
62    }
63}
64
65/// Provides methods for interacting with the `Compress` enum.
66impl Compress {
67    /// Checks if the current instance is of the `Unknown` type.
68    ///
69    /// This method compares the current instance with the `Unknown` variant of the enum.
70    /// It returns `true` if the instance is of type `Unknown`, otherwise `false`.
71    ///
72    /// # Returns
73    ///
74    /// - `bool`: `true` if the instance is of type `Unknown`, `false` otherwise.
75    #[inline(always)]
76    pub fn is_unknown(&self) -> bool {
77        *self == Self::Unknown
78    }
79
80    /// Renders the coding as its `Content-Encoding` field token.
81    ///
82    /// # Returns
83    ///
84    /// - `&'static str` - The token, empty for [`Compress::Unknown`].
85    #[inline(always)]
86    pub fn as_str(&self) -> &'static str {
87        match *self {
88            Self::Gzip => CONTENT_ENCODING_GZIP,
89            Self::Deflate => CONTENT_ENCODING_DEFLATE,
90            Self::Br => CONTENT_ENCODING_BROTLI,
91            Self::Unknown => EMPTY_STR,
92        }
93    }
94
95    /// Picks the coding this crate supports best out of an `Accept-Encoding` field value.
96    ///
97    /// The field is a comma separated list of codings, and every coding may carry a
98    /// `q` parameter that scales how much the client wants it, so `gzip;q=0.5, br`
99    /// asks for Brotli before Gzip. A coding the client refuses with `q=0` is never
100    /// picked, a coding this crate does not implement is ignored, and the `*` coding
101    /// stands for every supported coding the field does not name. Two codings the
102    /// client wants equally are resolved in favour of the smaller output, so the
103    /// answer is `br`, then `gzip`, then `deflate`, whatever order the field lists
104    /// them in.
105    ///
106    /// The field is parsed without allocating, so a server may negotiate the coding
107    /// of every response without a heap cost of its own.
108    ///
109    /// # Arguments
110    ///
111    /// - `H` - The field value, which requires the `AsRef<str>` bound.
112    ///
113    /// # Returns
114    ///
115    /// - `Option<Self>` - The coding to answer with, or `None` when the client
116    ///   accepts none of the codings this crate implements.
117    #[inline]
118    pub fn from_accept_encoding<H>(header: H) -> Option<Self>
119    where
120        H: AsRef<str>,
121    {
122        let mut brotli: Option<f32> = None;
123        let mut gzip: Option<f32> = None;
124        let mut deflate: Option<f32> = None;
125        let mut wildcard: Option<f32> = None;
126        for item in header.as_ref().split(ACCEPT_ENCODING_SEPARATOR) {
127            let Some((coding, quality)) = Self::split_accept_item(item) else {
128                continue;
129            };
130            if coding == ACCEPT_ENCODING_WILDCARD {
131                wildcard = Some(quality);
132            } else if coding.eq_ignore_ascii_case(CONTENT_ENCODING_BROTLI) {
133                brotli = Some(quality);
134            } else if coding.eq_ignore_ascii_case(CONTENT_ENCODING_GZIP)
135                || coding.eq_ignore_ascii_case(CONTENT_ENCODING_X_GZIP)
136            {
137                gzip = Some(quality);
138            } else if coding.eq_ignore_ascii_case(CONTENT_ENCODING_DEFLATE) {
139                deflate = Some(quality);
140            }
141        }
142        let candidates: [(Self, Option<f32>); 3] = [
143            (Self::Br, brotli),
144            (Self::Gzip, gzip),
145            (Self::Deflate, deflate),
146        ];
147        let mut best: Option<Self> = None;
148        let mut best_quality: f32 = 0.0;
149        for (coding, quality) in candidates {
150            let quality: f32 = quality.or(wildcard).unwrap_or(0.0);
151            if quality <= best_quality {
152                continue;
153            }
154            best = Some(coding);
155            best_quality = quality;
156        }
157        best
158    }
159
160    /// Splits one entry of an `Accept-Encoding` field value into its coding and quality.
161    ///
162    /// A quality that is absent counts as `1`, and a quality that is present but
163    /// does not parse as a number inside the unit interval refuses the entry,
164    /// because a client that cannot say how much it wants a coding cannot be
165    /// answered with it.
166    ///
167    /// # Arguments
168    ///
169    /// - `&str` - The entry, with or without its parameters.
170    ///
171    /// # Returns
172    ///
173    /// - `Option<(&str, f32)>` - The coding and its quality, or `None` when the
174    ///   entry names no coding or carries a quality the interval does not hold.
175    #[inline]
176    fn split_accept_item(item: &str) -> Option<(&str, f32)> {
177        let (coding, parameters): (&str, &str) = match item.split_once(PARAMETER_SEPARATOR) {
178            Some((coding, parameters)) => (coding, parameters),
179            None => (item, EMPTY_STR),
180        };
181        let coding: &str = coding.trim();
182        if coding.is_empty() {
183            return None;
184        }
185        for parameter in parameters.split(PARAMETER_SEPARATOR) {
186            let Some((name, value)) = parameter.split_once(PARAMETER_ASSIGN) else {
187                continue;
188            };
189            if !name.trim().eq_ignore_ascii_case(ACCEPT_ENCODING_QUALITY) {
190                continue;
191            }
192            let quality_text: &str = value.trim();
193            if !Self::is_valid_qvalue(quality_text) {
194                return None;
195            }
196            let quality: f32 = quality_text.parse().ok()?;
197            return Some((coding, quality));
198        }
199        Some((coding, DEFAULT_QUALITY))
200    }
201
202    /// Validates an RFC 9110 Section 12.4.2 quality value (`qvalue`).
203    ///
204    /// # Arguments
205    ///
206    /// - `&str` - The trimmed quality parameter value.
207    ///
208    /// # Returns
209    ///
210    /// - `bool` - `true` when the value matches `0[.0-9{0,3}]` or `1[.0{0,3}]`.
211    #[inline(always)]
212    fn is_valid_qvalue(value: &str) -> bool {
213        let bytes: &[u8] = value.as_bytes();
214        match bytes {
215            [b'0'] | [b'1'] => true,
216            [b'0', b'.', frac @ ..] if frac.len() <= 3 => {
217                frac.iter().all(|byte: &u8| byte.is_ascii_digit())
218            }
219            [b'1', b'.', frac @ ..] if frac.len() <= 3 => {
220                frac.iter().all(|byte: &u8| *byte == b'0')
221            }
222            _ => false,
223        }
224    }
225
226    /// Extracts the compression type from an HTTP header.
227    ///
228    /// This function looks for the `Content-Encoding` header in the provided `Header` and attempts
229    /// to parse it into a `Compress` enum value.
230    ///
231    /// # Arguments
232    ///
233    /// - `&HashMap<String, String, BuildHasherDefault<XxHash3_64>>` - The HTTP header from which
234    ///   the compression type is to be extracted.
235    ///
236    /// # Returns
237    ///
238    /// - `Self` - The `Compress` value corresponding to the `Content-Encoding` header, or
239    ///   `Compress::Unknown` if the header does not match any known compression types.
240    #[inline(always)]
241    pub fn from(header: &HashMap<String, String, BuildHasherDefault<XxHash3_64>>) -> Self {
242        header
243            .get(CONTENT_ENCODING)
244            .or_else(|| {
245                header
246                    .iter()
247                    .find(|(key, _): &(&String, &String)| {
248                        key.eq_ignore_ascii_case(CONTENT_ENCODING)
249                    })
250                    .map(|(_, value): (&String, &String)| value)
251            })
252            .map(|value: &String| value.parse::<Compress>().unwrap_or_default())
253            .unwrap_or_default()
254    }
255
256    /// Decompresses the given data based on the selected compression algorithm.
257    ///
258    /// This method takes a byte slice of compressed data and decompresses it using one of the following
259    /// compression algorithms, depending on the variant of the enum it is called on:
260    /// - `Gzip` - Decompresses using Gzip compression.
261    /// - `Deflate` - Decompresses using Deflate compression.
262    /// - `Br` - Decompresses using Brotli compression.
263    /// - `Unknown` - Returns the input data as-is (no decompression performed).
264    ///
265    /// # Arguments
266    ///
267    /// - `&'a [u8]` - A reference to a byte slice containing the compressed data to be decoded.
268    /// - `usize` - The buffer size to use for the decompression process. A larger buffer size can
269    ///   improve performance for larger datasets.
270    ///
271    /// # Returns
272    ///
273    /// - `Cow<'a, [u8]>` - The decompressed data. If the compression algorithm
274    ///   is `Unknown`, the original data is returned borrowed without copying. Otherwise,
275    ///   the decompressed data is returned as an owned `Vec<u8>`.
276    pub fn decode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, [u8]> {
277        match self {
278            Self::Gzip => gzip::decode(data, buffer_size),
279            Self::Deflate => deflate::decode(data, buffer_size),
280            Self::Br => brotli::decode(data, buffer_size),
281            Self::Unknown => Cow::Borrowed(data),
282        }
283    }
284
285    /// Compresses the given data based on the selected compression algorithm.
286    ///
287    /// This method takes a byte slice of data and compresses it using one of the following
288    /// compression algorithms, depending on the variant of the enum it is called on:
289    /// - `Gzip` - Compresses using Gzip compression.
290    /// - `Deflate` - Compresses using Deflate compression.
291    /// - `Br` - Compresses using Brotli compression.
292    /// - `Unknown` - Returns the input data as-is (no compression performed).
293    ///
294    /// # Arguments
295    ///
296    /// - `&'a [u8]` - A reference to a byte slice containing the data to be compressed.
297    /// - `usize` - The buffer size to use for the compression process. A larger buffer size can
298    ///   improve performance for larger datasets.
299    ///
300    /// # Returns
301    ///
302    /// - `Cow<'a, [u8]>` - The compressed data. If the compression algorithm
303    ///   is `Unknown`, the original data is returned borrowed without copying. Otherwise,
304    ///   the compressed data is returned as an owned `Vec<u8>`.
305    pub fn encode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, [u8]> {
306        match self {
307            Self::Gzip => gzip::encode(data, buffer_size),
308            Self::Deflate => deflate::encode(data, buffer_size),
309            Self::Br => brotli::encode(data, buffer_size),
310            Self::Unknown => Cow::Borrowed(data),
311        }
312    }
313}