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