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<u16> = None;
123 let mut gzip: Option<u16> = None;
124 let mut deflate: Option<u16> = None;
125 let mut wildcard: Option<u16> = 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 match coding.len() {
131 1 if coding == ACCEPT_ENCODING_WILDCARD => {
132 wildcard = Some(quality);
133 }
134 2 if coding.eq_ignore_ascii_case(CONTENT_ENCODING_BROTLI) => {
135 brotli = Some(quality);
136 }
137 4 if coding.eq_ignore_ascii_case(CONTENT_ENCODING_GZIP) => {
138 gzip = Some(quality);
139 }
140 6 if coding.eq_ignore_ascii_case(CONTENT_ENCODING_X_GZIP) => {
141 gzip = Some(quality);
142 }
143 7 if coding.eq_ignore_ascii_case(CONTENT_ENCODING_DEFLATE) => {
144 deflate = Some(quality);
145 }
146 _ => {}
147 }
148 }
149 let candidates: [(Self, Option<u16>); 3] = [
150 (Self::Br, brotli),
151 (Self::Gzip, gzip),
152 (Self::Deflate, deflate),
153 ];
154 let mut best: Option<Self> = None;
155 let mut best_quality: u16 = 0;
156 for (coding, quality) in candidates {
157 let quality: u16 = quality.or(wildcard).unwrap_or(0);
158 if quality <= best_quality {
159 continue;
160 }
161 best = Some(coding);
162 best_quality = quality;
163 }
164 best
165 }
166
167 /// Splits one entry of an `Accept-Encoding` field value into its coding and scaled quality (`0..=1000`).
168 ///
169 /// A quality that is absent counts as `1000` (`1.0`), and a quality that is present but
170 /// does not match RFC 9110 Section 12.4.2 grammar refuses the entry.
171 ///
172 /// # Arguments
173 ///
174 /// - `&str` - The entry, with or without its parameters.
175 ///
176 /// # Returns
177 ///
178 /// - `Option<(&str, u16)>` - The coding and its scaled quality (`0..=1000`), or `None` when invalid.
179 #[inline]
180 fn split_accept_item(item: &str) -> Option<(&str, u16)> {
181 let (coding, parameters): (&str, &str) = match item.split_once(PARAMETER_SEPARATOR) {
182 Some((coding, parameters)) => (coding, parameters),
183 None => (item, EMPTY_STR),
184 };
185 let coding: &str = coding.trim_ascii();
186 if coding.is_empty() {
187 return None;
188 }
189 if parameters.is_empty() {
190 return Some((coding, DEFAULT_QUALITY_MILLI));
191 }
192 for parameter in parameters.split(PARAMETER_SEPARATOR) {
193 let Some((name, value)) = parameter.split_once(PARAMETER_ASSIGN) else {
194 continue;
195 };
196 if !name
197 .trim_ascii()
198 .eq_ignore_ascii_case(ACCEPT_ENCODING_QUALITY)
199 {
200 continue;
201 }
202 let quality: u16 = Self::parse_qvalue(value.trim_ascii())?;
203 return Some((coding, quality));
204 }
205 Some((coding, DEFAULT_QUALITY_MILLI))
206 }
207
208 /// Validates and parses an RFC 9110 Section 12.4.2 quality value (`qvalue`) into `0..=1000`.
209 ///
210 /// # Arguments
211 ///
212 /// - `&str` - The trimmed quality parameter value.
213 ///
214 /// # Returns
215 ///
216 /// - `Option<u16>` - Scaled quality in `0..=1000`, or `None` when syntactically invalid.
217 #[inline(always)]
218 fn parse_qvalue(value: &str) -> Option<u16> {
219 let bytes: &[u8] = value.as_bytes();
220 match bytes {
221 [QVALUE_DIGIT_ZERO] => Some(0),
222 [QVALUE_DIGIT_ONE] => Some(1000),
223 [QVALUE_DIGIT_ZERO, QVALUE_DECIMAL_POINT] => Some(0),
224 [QVALUE_DIGIT_ZERO, QVALUE_DECIMAL_POINT, d1] if d1.is_ascii_digit() => {
225 Some(u16::from(d1 - QVALUE_DIGIT_ZERO) * 100)
226 }
227 [QVALUE_DIGIT_ZERO, QVALUE_DECIMAL_POINT, d1, d2]
228 if d1.is_ascii_digit() && d2.is_ascii_digit() =>
229 {
230 Some(
231 u16::from(d1 - QVALUE_DIGIT_ZERO) * 100
232 + u16::from(d2 - QVALUE_DIGIT_ZERO) * 10,
233 )
234 }
235 [QVALUE_DIGIT_ZERO, QVALUE_DECIMAL_POINT, d1, d2, d3]
236 if d1.is_ascii_digit() && d2.is_ascii_digit() && d3.is_ascii_digit() =>
237 {
238 Some(
239 u16::from(d1 - QVALUE_DIGIT_ZERO) * 100
240 + u16::from(d2 - QVALUE_DIGIT_ZERO) * 10
241 + u16::from(d3 - QVALUE_DIGIT_ZERO),
242 )
243 }
244 [QVALUE_DIGIT_ONE, QVALUE_DECIMAL_POINT, frac @ ..]
245 if frac.len() <= 3 && frac.iter().all(|byte: &u8| *byte == QVALUE_DIGIT_ZERO) =>
246 {
247 Some(1000)
248 }
249 _ => None,
250 }
251 }
252
253 /// Extracts the compression type from an HTTP header.
254 ///
255 /// This function looks for the `Content-Encoding` header in the provided `Header` and attempts
256 /// to parse it into a `Compress` enum value.
257 ///
258 /// # Arguments
259 ///
260 /// - `&HashMap<String, String, BuildHasherDefault<XxHash3_64>>` - The HTTP header from which
261 /// the compression type is to be extracted.
262 ///
263 /// # Returns
264 ///
265 /// - `Self` - The `Compress` value corresponding to the `Content-Encoding` header, or
266 /// `Compress::Unknown` if the header does not match any known compression types.
267 #[inline(always)]
268 pub fn from(header: &HashMap<String, String, BuildHasherDefault<XxHash3_64>>) -> Self {
269 header
270 .get(CONTENT_ENCODING)
271 .or_else(|| {
272 header
273 .iter()
274 .find(|(key, _): &(&String, &String)| {
275 key.eq_ignore_ascii_case(CONTENT_ENCODING)
276 })
277 .map(|(_, value): (&String, &String)| value)
278 })
279 .map(|value: &String| value.parse::<Compress>().unwrap_or_default())
280 .unwrap_or_default()
281 }
282
283 /// Decompresses the given data based on the selected compression algorithm.
284 ///
285 /// This method takes a byte slice of compressed data and decompresses it using one of the following
286 /// compression algorithms, depending on the variant of the enum it is called on:
287 /// - `Gzip` - Decompresses using Gzip compression.
288 /// - `Deflate` - Decompresses using Deflate compression.
289 /// - `Br` - Decompresses using Brotli compression.
290 /// - `Unknown` - Returns the input data as-is (no decompression performed).
291 ///
292 /// # Arguments
293 ///
294 /// - `&'a [u8]` - A reference to a byte slice containing the compressed data to be decoded.
295 /// - `usize` - The buffer size to use for the decompression process. A larger buffer size can
296 /// improve performance for larger datasets.
297 ///
298 /// # Returns
299 ///
300 /// - `Cow<'a, [u8]>` - The decompressed data. If the compression algorithm
301 /// is `Unknown`, the original data is returned borrowed without copying. Otherwise,
302 /// the decompressed data is returned as an owned `Vec<u8>`.
303 pub fn decode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, [u8]> {
304 match self {
305 Self::Gzip => gzip::decode(data, buffer_size),
306 Self::Deflate => deflate::decode(data, buffer_size),
307 Self::Br => brotli::decode(data, buffer_size),
308 Self::Unknown => Cow::Borrowed(data),
309 }
310 }
311
312 /// Compresses the given data based on the selected compression algorithm.
313 ///
314 /// This method takes a byte slice of data and compresses it using one of the following
315 /// compression algorithms, depending on the variant of the enum it is called on:
316 /// - `Gzip` - Compresses using Gzip compression.
317 /// - `Deflate` - Compresses using Deflate compression.
318 /// - `Br` - Compresses using Brotli compression.
319 /// - `Unknown` - Returns the input data as-is (no compression performed).
320 ///
321 /// # Arguments
322 ///
323 /// - `&'a [u8]` - A reference to a byte slice containing the data to be compressed.
324 /// - `usize` - The buffer size to use for the compression process. A larger buffer size can
325 /// improve performance for larger datasets.
326 ///
327 /// # Returns
328 ///
329 /// - `Cow<'a, [u8]>` - The compressed data. If the compression algorithm
330 /// is `Unknown`, the original data is returned borrowed without copying. Otherwise,
331 /// the compressed data is returned as an owned `Vec<u8>`.
332 pub fn encode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, [u8]> {
333 match self {
334 Self::Gzip => gzip::encode(data, buffer_size),
335 Self::Deflate => deflate::encode(data, buffer_size),
336 Self::Br => brotli::encode(data, buffer_size),
337 Self::Unknown => Cow::Borrowed(data),
338 }
339 }
340}