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 match data.to_lowercase().as_str() {
29 _data if _data == CONTENT_ENCODING_GZIP => Ok(Self::Gzip),
30 _data if _data == CONTENT_ENCODING_DEFLATE => Ok(Self::Deflate),
31 _data if _data == CONTENT_ENCODING_BROTLI => Ok(Self::Br),
32 _ => Ok(Self::Unknown),
33 }
34 }
35}
36
37/// Implements the `Display` trait for the `Compress` enum.
38///
39/// This allows the `Compress` enum variants to be formatted as strings,
40/// typically used for outputting the `Content-Encoding` header value.
41impl fmt::Display for Compress {
42 /// Formats the `Compress` value as its `Content-Encoding` header token.
43 ///
44 /// `Compress::Unknown` formats as the empty string, since it has no
45 /// `Content-Encoding` representation.
46 ///
47 /// # Arguments
48 ///
49 /// - `&mut fmt::Formatter<'_>` - The formatter to write the value into.
50 ///
51 /// # Returns
52 ///
53 /// - `fmt::Result` - The result of the formatting operation.
54 #[inline(always)]
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 write!(f, "{}", self.as_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 /// - `bool`: `true` if the instance is of type `Unknown`, `false` otherwise.
70 #[inline(always)]
71 pub fn is_unknown(&self) -> bool {
72 *self == Self::Unknown
73 }
74
75 /// Renders the coding as its `Content-Encoding` field token.
76 ///
77 /// # Returns
78 ///
79 /// - `&'static str` - The token, empty for [`Compress::Unknown`].
80 #[inline(always)]
81 pub fn as_str(&self) -> &'static str {
82 match *self {
83 Self::Gzip => CONTENT_ENCODING_GZIP,
84 Self::Deflate => CONTENT_ENCODING_DEFLATE,
85 Self::Br => CONTENT_ENCODING_BROTLI,
86 Self::Unknown => EMPTY_STR,
87 }
88 }
89
90 /// Picks the coding this crate supports best out of an `Accept-Encoding` field value.
91 ///
92 /// The field is a comma separated list of codings, and every coding may carry a
93 /// `q` parameter that scales how much the client wants it, so `gzip;q=0.5, br`
94 /// asks for Brotli before Gzip. A coding the client refuses with `q=0` is never
95 /// picked, a coding this crate does not implement is ignored, and the `*` coding
96 /// stands for every supported coding the field does not name. Two codings the
97 /// client wants equally are resolved in favour of the smaller output, so the
98 /// answer is `br`, then `gzip`, then `deflate`, whatever order the field lists
99 /// them in.
100 ///
101 /// The field is parsed without allocating, so a server may negotiate the coding
102 /// of every response without a heap cost of its own.
103 ///
104 /// # Arguments
105 ///
106 /// - `H` - The field value, which requires the `AsRef<str>` bound.
107 ///
108 /// # Returns
109 ///
110 /// - `Option<Self>` - The coding to answer with, or `None` when the client
111 /// accepts none of the codings this crate implements.
112 #[inline]
113 pub fn from_accept_encoding<H>(header: H) -> Option<Self>
114 where
115 H: AsRef<str>,
116 {
117 let mut brotli: Option<f32> = None;
118 let mut gzip: Option<f32> = None;
119 let mut deflate: Option<f32> = None;
120 let mut wildcard: Option<f32> = None;
121 for item in header.as_ref().split(ACCEPT_ENCODING_SEPARATOR) {
122 let Some((coding, quality)) = Self::split_accept_item(item) else {
123 continue;
124 };
125 if coding == ACCEPT_ENCODING_WILDCARD {
126 wildcard = Some(quality);
127 } else if coding.eq_ignore_ascii_case(CONTENT_ENCODING_BROTLI) {
128 brotli = Some(quality);
129 } else if coding.eq_ignore_ascii_case(CONTENT_ENCODING_GZIP) {
130 gzip = Some(quality);
131 } else if coding.eq_ignore_ascii_case(CONTENT_ENCODING_DEFLATE) {
132 deflate = Some(quality);
133 }
134 }
135 let candidates: [(Self, Option<f32>); 3] = [
136 (Self::Br, brotli),
137 (Self::Gzip, gzip),
138 (Self::Deflate, deflate),
139 ];
140 let mut best: Option<Self> = None;
141 let mut best_quality: f32 = 0.0;
142 for (coding, quality) in candidates {
143 let quality: f32 = quality.or(wildcard).unwrap_or(0.0);
144 if quality <= best_quality {
145 continue;
146 }
147 best = Some(coding);
148 best_quality = quality;
149 }
150 best
151 }
152
153 /// Splits one entry of an `Accept-Encoding` field value into its coding and quality.
154 ///
155 /// A quality that is absent counts as `1`, and a quality that is present but
156 /// does not parse as a number inside the unit interval refuses the entry,
157 /// because a client that cannot say how much it wants a coding cannot be
158 /// answered with it.
159 ///
160 /// # Arguments
161 ///
162 /// - `&str` - The entry, with or without its parameters.
163 ///
164 /// # Returns
165 ///
166 /// - `Option<(&str, f32)>` - The coding and its quality, or `None` when the
167 /// entry names no coding or carries a quality the interval does not hold.
168 #[inline]
169 fn split_accept_item(item: &str) -> Option<(&str, f32)> {
170 let (coding, parameters): (&str, &str) = match item.split_once(PARAMETER_SEPARATOR) {
171 Some((coding, parameters)) => (coding, parameters),
172 None => (item, EMPTY_STR),
173 };
174 let coding: &str = coding.trim();
175 if coding.is_empty() {
176 return None;
177 }
178 for parameter in parameters.split(PARAMETER_SEPARATOR) {
179 let Some((name, value)) = parameter.split_once(PARAMETER_ASSIGN) else {
180 continue;
181 };
182 if !name.trim().eq_ignore_ascii_case(ACCEPT_ENCODING_QUALITY) {
183 continue;
184 }
185 let quality: f32 = value.trim().parse().ok()?;
186 if !(0.0..=1.0).contains(&quality) {
187 return None;
188 }
189 return Some((coding, quality));
190 }
191 Some((coding, DEFAULT_QUALITY))
192 }
193
194 /// Extracts the compression type from an HTTP header.
195 ///
196 /// This function looks for the `Content-Encoding` header in the provided `Header` and attempts
197 /// to parse it into a `Compress` enum value.
198 ///
199 /// # Arguments
200 ///
201 /// - `&HashMap<String, String, BuildHasherDefault<XxHash3_64>>` - The HTTP header from which
202 /// the compression type is to be extracted.
203 ///
204 /// # Returns
205 ///
206 /// - `Self` - The `Compress` value corresponding to the `Content-Encoding` header, or
207 /// `Compress::Unknown` if the header does not match any known compression types.
208 #[inline(always)]
209 pub fn from(header: &HashMap<String, String, BuildHasherDefault<XxHash3_64>>) -> Self {
210 header
211 .get(CONTENT_ENCODING)
212 .map(|value: &String| value.parse::<Compress>().unwrap_or_default())
213 .unwrap_or_default()
214 }
215
216 /// Decompresses the given data based on the selected compression algorithm.
217 ///
218 /// This method takes a byte slice of compressed data and decompresses it using one of the following
219 /// compression algorithms, depending on the variant of the enum it is called on:
220 /// - `Gzip` - Decompresses using Gzip compression.
221 /// - `Deflate` - Decompresses using Deflate compression.
222 /// - `Br` - Decompresses using Brotli compression.
223 /// - `Unknown` - Returns the input data as-is (no decompression performed).
224 ///
225 /// # Arguments
226 ///
227 /// - `&'a [u8]` - A reference to a byte slice containing the compressed data to be decoded.
228 /// - `usize` - The buffer size to use for the decompression process. A larger buffer size can
229 /// improve performance for larger datasets.
230 ///
231 /// # Returns
232 ///
233 /// - `Cow<'a, [u8]>` - The decompressed data. If the compression algorithm
234 /// is `Unknown`, the original data is returned unchanged, as an owned buffer. Otherwise,
235 /// the decompressed data is returned as an owned `Vec<u8>`.
236 pub fn decode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, [u8]> {
237 match self {
238 Self::Gzip => gzip::decode(data, buffer_size),
239 Self::Deflate => deflate::decode(data, buffer_size),
240 Self::Br => brotli::decode(data, buffer_size),
241 Self::Unknown => Cow::Owned(data.to_vec()),
242 }
243 }
244
245 /// Compresses the given data based on the selected compression algorithm.
246 ///
247 /// This method takes a byte slice of data and compresses it using one of the following
248 /// compression algorithms, depending on the variant of the enum it is called on:
249 /// - `Gzip` - Compresses using Gzip compression.
250 /// - `Deflate` - Compresses using Deflate compression.
251 /// - `Br` - Compresses using Brotli compression.
252 /// - `Unknown` - Returns the input data as-is (no compression performed).
253 ///
254 /// # Arguments
255 ///
256 /// - `&'a [u8]` - A reference to a byte slice containing the data to be compressed.
257 /// - `usize` - The buffer size to use for the compression process. A larger buffer size can
258 /// improve performance for larger datasets.
259 ///
260 /// # Returns
261 ///
262 /// - `Cow<'a, [u8]>` - The compressed data. If the compression algorithm
263 /// is `Unknown`, the original data is returned unchanged, as an owned buffer. Otherwise,
264 /// the compressed data is returned as an owned `Vec<u8>`.
265 pub fn encode<'a>(&self, data: &'a [u8], buffer_size: usize) -> Cow<'a, [u8]> {
266 match self {
267 Self::Gzip => gzip::encode(data, buffer_size),
268 Self::Deflate => deflate::encode(data, buffer_size),
269 Self::Br => brotli::encode(data, buffer_size),
270 Self::Unknown => Cow::Owned(data.to_vec()),
271 }
272 }
273}