ctb_io_webui/middleware/compression_with_range/
content_encoding.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from from tower-http: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Derived from tower-http (https://github.com/tower-rs/tower-http):
22
23// Copyright (c) 2019-2021 Tower Contributors
24
25// See additional licensing details at end of file.
26
27//! Types used by compression and decompression middleware.
28
29pub(crate) trait SupportedEncodings: Copy {
30    fn gzip(&self) -> bool;
31    fn deflate(&self) -> bool;
32    fn br(&self) -> bool;
33    fn zstd(&self) -> bool;
34}
35
36// This enum's variants are ordered from least to most preferred.
37#[derive(Copy, Clone, Debug, Ord, PartialOrd, PartialEq, Eq)]
38pub(crate) enum Encoding {
39    #[expect(dead_code, reason = "potentially unused API helper")]
40    Identity,
41    Deflate,
42    Gzip,
43    Brotli,
44    Zstd,
45}
46
47impl Encoding {
48    #[expect(dead_code, reason = "potentially unused API helper")]
49    fn to_str(self) -> &'static str {
50        match self {
51            Encoding::Gzip => "gzip",
52            Encoding::Deflate => "deflate",
53            Encoding::Brotli => "br",
54            Encoding::Zstd => "zstd",
55            Encoding::Identity => "identity",
56        }
57    }
58
59    pub(crate) fn to_file_extension(self) -> Option<&'static std::ffi::OsStr> {
60        match self {
61            Encoding::Gzip => Some(std::ffi::OsStr::new(".gz")),
62            Encoding::Deflate => Some(std::ffi::OsStr::new(".zz")),
63            Encoding::Brotli => Some(std::ffi::OsStr::new(".br")),
64            Encoding::Zstd => Some(std::ffi::OsStr::new(".zst")),
65            Encoding::Identity => None,
66        }
67    }
68
69    #[expect(dead_code, reason = "potentially unused API helper")]
70    pub(crate) fn into_header_value(self) -> http::HeaderValue {
71        http::HeaderValue::from_static(self.to_str())
72    }
73
74    fn parse(
75        s: &str,
76        _supported_encoding: impl SupportedEncodings,
77    ) -> Option<Encoding> {
78        if (s.eq_ignore_ascii_case("gzip") || s.eq_ignore_ascii_case("x-gzip"))
79            && _supported_encoding.gzip()
80        {
81            return Some(Encoding::Gzip);
82        }
83
84        if s.eq_ignore_ascii_case("deflate") && _supported_encoding.deflate() {
85            return Some(Encoding::Deflate);
86        }
87
88        if s.eq_ignore_ascii_case("br") && _supported_encoding.br() {
89            return Some(Encoding::Brotli);
90        }
91
92        if s.eq_ignore_ascii_case("zstd") && _supported_encoding.zstd() {
93            return Some(Encoding::Zstd);
94        }
95
96        if s.eq_ignore_ascii_case("identity") {
97            return Some(Encoding::Identity);
98        }
99
100        None
101    }
102
103    // based on https://github.com/http-rs/accept-encoding
104    //
105    // Returns `Some(encoding)` for the best acceptable encoding, or `None` if the client's
106    // preferences cannot be satisfied (406 Not Acceptable per RFC 9110 §12.5.3).
107    pub(crate) fn from_headers(
108        headers: &http::HeaderMap,
109        supported_encoding: impl SupportedEncodings,
110    ) -> Option<Self> {
111        preferred_encoding_with_wildcard(headers, supported_encoding)
112    }
113
114    pub(crate) fn preferred_encoding(
115        accepted_encodings: impl Iterator<Item = (Encoding, QValue)>,
116    ) -> Option<Self> {
117        accepted_encodings
118            .filter(|(_, qvalue)| qvalue.0 > 0)
119            .max_by_key(|&(encoding, qvalue)| (qvalue, encoding))
120            .map(|(encoding, _)| encoding)
121    }
122}
123
124// Allowed q-values are numbers between 0 and 1 with at most 3 digits in the fractional part. They
125// are presented here as an unsigned integer between 0 and 1000.
126#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
127pub(crate) struct QValue(u16);
128
129impl QValue {
130    #[inline]
131    pub(crate) fn one() -> Self {
132        Self(1000)
133    }
134
135    // Parse a q-value as specified in RFC 7231 section 5.3.1.
136    #[expect(
137        clippy::expect_used,
138        clippy::unwrap_in_result,
139        reason = "Division by constant 10 is non-zero and cannot fail"
140    )]
141    fn parse(s: &str) -> Option<Self> {
142        let mut c = s.chars();
143        // Parse "q=" (case-insensitively).
144        match c.next() {
145            Some('q' | 'Q') => (),
146            _ => return None,
147        }
148        match c.next() {
149            Some('=') => (),
150            _ => return None,
151        }
152
153        // Parse leading digit. Since valid q-values are between 0.000 and 1.000, only "0" and "1"
154        // are allowed.
155        let mut value = match c.next() {
156            Some('0') => 0u16,
157            Some('1') => 1000u16,
158            _ => return None,
159        };
160
161        // Parse optional decimal point.
162        match c.next() {
163            Some('.') => (),
164            None => return Some(Self(value)),
165            _ => return None,
166        }
167
168        // Parse optional fractional digits. The value of each digit is multiplied by `factor`.
169        // Since the q-value is represented as an integer between 0 and 1000, `factor` is `100` for
170        // the first digit, `10` for the next, and `1` for the digit after that.
171        let mut factor: u16 = 100;
172        loop {
173            match c.next() {
174                Some(n @ '0'..='9') => {
175                    // If `factor` is less than `1`, three digits have already been parsed. A
176                    // q-value having more than 3 fractional digits is invalid.
177                    if factor < 1 {
178                        return None;
179                    }
180                    let digit = match n {
181                        '0' => 0_u16,
182                        '1' => 1,
183                        '2' => 2,
184                        '3' => 3,
185                        '4' => 4,
186                        '5' => 5,
187                        '6' => 6,
188                        '7' => 7,
189                        '8' => 8,
190                        '9' => 9,
191                        _ => return None,
192                    };
193                    let product = factor.saturating_mul(digit);
194                    value = value.saturating_add(product);
195                }
196                None => {
197                    // No more characters to parse. Check that the value representing the q-value is
198                    // in the valid range.
199                    return if value <= 1000 {
200                        Some(Self(value))
201                    } else {
202                        None
203                    };
204                }
205                _ => return None,
206            }
207            factor = factor.checked_div(10).expect("10 is non-zero");
208        }
209    }
210}
211
212// based on https://github.com/http-rs/accept-encoding
213pub(crate) fn encodings<'a>(
214    headers: &'a http::HeaderMap,
215    supported_encoding: impl SupportedEncodings + 'a,
216) -> impl Iterator<Item = (Encoding, QValue)> + 'a {
217    headers
218        .get_all(http::header::ACCEPT_ENCODING)
219        .iter()
220        .filter_map(|hval| hval.to_str().ok())
221        .flat_map(|s| s.split(','))
222        .filter_map(move |v| {
223            let mut v = v.splitn(2, ';');
224            let coding = v.next()?.trim();
225            let encoding = match Encoding::parse(coding, supported_encoding) {
226                Some(encoding) => encoding,
227                None => return None, // ignore unknown encodings
228            };
229
230            let qval = if let Some(qval) = v.next() {
231                QValue::parse(qval.trim())?
232            } else {
233                QValue::one()
234            };
235
236            Some((encoding, qval))
237        })
238}
239
240/// Extracts the q-value for the `*` wildcard from Accept-Encoding headers.
241/// Returns `None` if no wildcard is present.
242fn wildcard_qvalue(headers: &http::HeaderMap) -> Option<QValue> {
243    headers
244        .get_all(http::header::ACCEPT_ENCODING)
245        .iter()
246        .filter_map(|hval| hval.to_str().ok())
247        .flat_map(|s| s.split(','))
248        .find_map(|v| {
249            let mut v = v.splitn(2, ';');
250            let coding = v.next()?.trim();
251            if coding != "*" {
252                return None;
253            }
254            let qval = if let Some(qval) = v.next() {
255                QValue::parse(qval.trim())?
256            } else {
257                QValue::one()
258            };
259            Some(qval)
260        })
261}
262
263/// Selects the preferred encoding considering the `*` wildcard per RFC 9110 §12.5.3.
264///
265/// The wildcard applies its q-value to any encoding not explicitly listed. If all acceptable
266/// encodings (including identity) are excluded, returns `None` to signal 406 Not Acceptable.
267fn preferred_encoding_with_wildcard(
268    headers: &http::HeaderMap,
269    supported_encoding: impl SupportedEncodings,
270) -> Option<Encoding> {
271    let explicit: Vec<(Encoding, QValue)> =
272        encodings(headers, supported_encoding).collect();
273    let wildcard_q = wildcard_qvalue(headers);
274
275    // If there is no wildcard, use only the explicitly listed encodings.
276    // Per RFC 9110 §12.5.3, if identity is excluded (q=0) and no other encoding is
277    // acceptable, the server SHOULD respond with 406.
278    let wildcard_q = if let Some(q) = wildcard_q {
279        q
280    } else {
281        let identity_rejected = explicit
282            .iter()
283            .any(|(enc, q)| *enc == Encoding::Identity && q.0 == 0);
284        return match Encoding::preferred_encoding(explicit.into_iter()) {
285            Some(enc) => Some(enc),
286            None => {
287                if identity_rejected {
288                    None
289                } else {
290                    Some(Encoding::Identity)
291                }
292            }
293        };
294    };
295
296    // Build the effective set of (encoding, qvalue) for all supported encodings.
297    // For each supported encoding, use its explicit q-value if listed, otherwise the wildcard
298    // q-value.
299    let all_supported = all_supported_encodings(supported_encoding);
300
301    let effective = all_supported.iter().filter_map(|e| *e).map(|enc| {
302        // Reason for fallback: encoding not explicitly listed in Accept-Encoding header uses wildcard q-value weight
303        let q = explicit
304            .iter()
305            .find(|(e, _)| *e == enc)
306            .map_or(wildcard_q, |(_, q)| *q);
307        (enc, q)
308    });
309
310    Encoding::preferred_encoding(effective)
311}
312
313/// Returns all encodings the server supports (including Identity) in a fixed-capacity array.
314fn all_supported_encodings(
315    supported_encoding: impl SupportedEncodings,
316) -> [Option<Encoding>; 5] {
317    let mut out: [Option<Encoding>; 5] = [None; 5];
318    let mut n = 0;
319
320    macro_rules! push {
321        ($enc:expr) => {
322            if let Some(slot) = out.get_mut(n) {
323                *slot = Some($enc);
324                n = n.saturating_add(1);
325            }
326        };
327    }
328
329    push!(Encoding::Identity);
330
331    if supported_encoding.gzip() {
332        push!(Encoding::Gzip);
333    }
334
335    if supported_encoding.deflate() {
336        push!(Encoding::Deflate);
337    }
338
339    if supported_encoding.br() {
340        push!(Encoding::Brotli);
341    }
342
343    if supported_encoding.zstd() {
344        push!(Encoding::Zstd);
345    }
346
347    let _ = n;
348    out
349}
350
351#[cfg(test)]
352#[allow(
353    clippy::panic,
354    clippy::expect_used,
355    clippy::unwrap_used,
356    clippy::unwrap_in_result,
357    clippy::panic_in_result_fn,
358    clippy::indexing_slicing,
359    clippy::arithmetic_side_effects,
360    reason = "Standard repository test boilerplate"
361)]
362mod tests {
363    use super::*;
364
365    #[derive(Copy, Clone, Default)]
366    struct SupportedEncodingsAll;
367
368    impl SupportedEncodings for SupportedEncodingsAll {
369        fn gzip(&self) -> bool {
370            true
371        }
372
373        fn deflate(&self) -> bool {
374            true
375        }
376
377        fn br(&self) -> bool {
378            true
379        }
380
381        fn zstd(&self) -> bool {
382            true
383        }
384    }
385
386    #[crate::ctb_test]
387    fn no_accept_encoding_header() {
388        let encoding = Encoding::from_headers(
389            &http::HeaderMap::new(),
390            SupportedEncodingsAll,
391        );
392        assert_eq!(Some(Encoding::Identity), encoding);
393    }
394
395    #[crate::ctb_test]
396    fn accept_encoding_header_single_encoding() {
397        let mut headers = http::HeaderMap::new();
398        headers.append(
399            http::header::ACCEPT_ENCODING,
400            http::HeaderValue::from_static("gzip"),
401        );
402        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
403        assert_eq!(Some(Encoding::Gzip), encoding);
404    }
405
406    #[crate::ctb_test]
407    fn accept_encoding_header_two_encodings() {
408        let mut headers = http::HeaderMap::new();
409        headers.append(
410            http::header::ACCEPT_ENCODING,
411            http::HeaderValue::from_static("gzip,br"),
412        );
413        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
414        assert_eq!(Some(Encoding::Brotli), encoding);
415    }
416
417    #[crate::ctb_test]
418    fn accept_encoding_header_gzip_x_gzip() {
419        let mut headers = http::HeaderMap::new();
420        headers.append(
421            http::header::ACCEPT_ENCODING,
422            http::HeaderValue::from_static("gzip,x-gzip"),
423        );
424        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
425        assert_eq!(Some(Encoding::Gzip), encoding);
426    }
427
428    #[crate::ctb_test]
429    fn accept_encoding_header_x_gzip_deflate() {
430        let mut headers = http::HeaderMap::new();
431        headers.append(
432            http::header::ACCEPT_ENCODING,
433            http::HeaderValue::from_static("deflate,x-gzip"),
434        );
435        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
436        assert_eq!(Some(Encoding::Gzip), encoding);
437    }
438
439    #[crate::ctb_test]
440    fn accept_encoding_header_three_encodings() {
441        let mut headers = http::HeaderMap::new();
442        headers.append(
443            http::header::ACCEPT_ENCODING,
444            http::HeaderValue::from_static("gzip,deflate,br"),
445        );
446        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
447        assert_eq!(Some(Encoding::Brotli), encoding);
448    }
449
450    #[crate::ctb_test]
451    fn accept_encoding_header_two_encodings_with_one_qvalue() {
452        let mut headers = http::HeaderMap::new();
453        headers.append(
454            http::header::ACCEPT_ENCODING,
455            http::HeaderValue::from_static("gzip;q=0.5,br"),
456        );
457        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
458        assert_eq!(Some(Encoding::Brotli), encoding);
459    }
460
461    #[crate::ctb_test]
462    fn accept_encoding_header_three_encodings_with_one_qvalue() {
463        let mut headers = http::HeaderMap::new();
464        headers.append(
465            http::header::ACCEPT_ENCODING,
466            http::HeaderValue::from_static("gzip;q=0.5,deflate,br"),
467        );
468        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
469        assert_eq!(Some(Encoding::Brotli), encoding);
470    }
471
472    #[crate::ctb_test]
473    fn two_accept_encoding_headers_with_one_qvalue() {
474        let mut headers = http::HeaderMap::new();
475        headers.append(
476            http::header::ACCEPT_ENCODING,
477            http::HeaderValue::from_static("gzip;q=0.5"),
478        );
479        headers.append(
480            http::header::ACCEPT_ENCODING,
481            http::HeaderValue::from_static("br"),
482        );
483        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
484        assert_eq!(Some(Encoding::Brotli), encoding);
485    }
486
487    #[crate::ctb_test]
488    fn two_accept_encoding_headers_three_encodings_with_one_qvalue() {
489        let mut headers = http::HeaderMap::new();
490        headers.append(
491            http::header::ACCEPT_ENCODING,
492            http::HeaderValue::from_static("gzip;q=0.5,deflate"),
493        );
494        headers.append(
495            http::header::ACCEPT_ENCODING,
496            http::HeaderValue::from_static("br"),
497        );
498        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
499        assert_eq!(Some(Encoding::Brotli), encoding);
500    }
501
502    #[crate::ctb_test]
503    fn three_accept_encoding_headers_with_one_qvalue() {
504        let mut headers = http::HeaderMap::new();
505        headers.append(
506            http::header::ACCEPT_ENCODING,
507            http::HeaderValue::from_static("gzip;q=0.5"),
508        );
509        headers.append(
510            http::header::ACCEPT_ENCODING,
511            http::HeaderValue::from_static("deflate"),
512        );
513        headers.append(
514            http::header::ACCEPT_ENCODING,
515            http::HeaderValue::from_static("br"),
516        );
517        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
518        assert_eq!(Some(Encoding::Brotli), encoding);
519    }
520
521    #[crate::ctb_test]
522    fn accept_encoding_header_two_encodings_with_two_qvalues() {
523        let mut headers = http::HeaderMap::new();
524        headers.append(
525            http::header::ACCEPT_ENCODING,
526            http::HeaderValue::from_static("gzip;q=0.5,br;q=0.8"),
527        );
528        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
529        assert_eq!(Some(Encoding::Brotli), encoding);
530
531        let mut headers = http::HeaderMap::new();
532        headers.append(
533            http::header::ACCEPT_ENCODING,
534            http::HeaderValue::from_static("gzip;q=0.8,br;q=0.5"),
535        );
536        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
537        assert_eq!(Some(Encoding::Gzip), encoding);
538
539        let mut headers = http::HeaderMap::new();
540        headers.append(
541            http::header::ACCEPT_ENCODING,
542            http::HeaderValue::from_static("gzip;q=0.995,br;q=0.999"),
543        );
544        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
545        assert_eq!(Some(Encoding::Brotli), encoding);
546    }
547
548    #[crate::ctb_test]
549    fn accept_encoding_header_three_encodings_with_three_qvalues() {
550        let mut headers = http::HeaderMap::new();
551        headers.append(
552            http::header::ACCEPT_ENCODING,
553            http::HeaderValue::from_static("gzip;q=0.5,deflate;q=0.6,br;q=0.8"),
554        );
555        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
556        assert_eq!(Some(Encoding::Brotli), encoding);
557
558        let mut headers = http::HeaderMap::new();
559        headers.append(
560            http::header::ACCEPT_ENCODING,
561            http::HeaderValue::from_static("gzip;q=0.8,deflate;q=0.6,br;q=0.5"),
562        );
563        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
564        assert_eq!(Some(Encoding::Gzip), encoding);
565
566        let mut headers = http::HeaderMap::new();
567        headers.append(
568            http::header::ACCEPT_ENCODING,
569            http::HeaderValue::from_static("gzip;q=0.6,deflate;q=0.8,br;q=0.5"),
570        );
571        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
572        assert_eq!(Some(Encoding::Deflate), encoding);
573
574        let mut headers = http::HeaderMap::new();
575        headers.append(
576            http::header::ACCEPT_ENCODING,
577            http::HeaderValue::from_static(
578                "gzip;q=0.995,deflate;q=0.997,br;q=0.999",
579            ),
580        );
581        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
582        assert_eq!(Some(Encoding::Brotli), encoding);
583    }
584
585    #[crate::ctb_test]
586    fn accept_encoding_header_invalid_encdoing() {
587        let mut headers = http::HeaderMap::new();
588        headers.append(
589            http::header::ACCEPT_ENCODING,
590            http::HeaderValue::from_static("invalid,gzip"),
591        );
592        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
593        assert_eq!(Some(Encoding::Gzip), encoding);
594    }
595
596    #[crate::ctb_test]
597    fn accept_encoding_header_with_qvalue_zero() {
598        let mut headers = http::HeaderMap::new();
599        headers.append(
600            http::header::ACCEPT_ENCODING,
601            http::HeaderValue::from_static("gzip;q=0"),
602        );
603        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
604        assert_eq!(Some(Encoding::Identity), encoding);
605
606        let mut headers = http::HeaderMap::new();
607        headers.append(
608            http::header::ACCEPT_ENCODING,
609            http::HeaderValue::from_static("gzip;q=0."),
610        );
611        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
612        assert_eq!(Some(Encoding::Identity), encoding);
613
614        let mut headers = http::HeaderMap::new();
615        headers.append(
616            http::header::ACCEPT_ENCODING,
617            http::HeaderValue::from_static("gzip;q=0,br;q=0.5"),
618        );
619        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
620        assert_eq!(Some(Encoding::Brotli), encoding);
621    }
622
623    #[crate::ctb_test]
624    fn accept_encoding_header_with_uppercase_letters() {
625        let mut headers = http::HeaderMap::new();
626        headers.append(
627            http::header::ACCEPT_ENCODING,
628            http::HeaderValue::from_static("gZiP"),
629        );
630        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
631        assert_eq!(Some(Encoding::Gzip), encoding);
632
633        let mut headers = http::HeaderMap::new();
634        headers.append(
635            http::header::ACCEPT_ENCODING,
636            http::HeaderValue::from_static("gzip;q=0.5,br;Q=0.8"),
637        );
638        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
639        assert_eq!(Some(Encoding::Brotli), encoding);
640    }
641
642    #[crate::ctb_test]
643    fn accept_encoding_header_with_allowed_spaces() {
644        let mut headers = http::HeaderMap::new();
645        headers.append(
646            http::header::ACCEPT_ENCODING,
647            http::HeaderValue::from_static(" gzip\t; q=0.5 ,\tbr ;\tq=0.8\t"),
648        );
649        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
650        assert_eq!(Some(Encoding::Brotli), encoding);
651    }
652
653    #[crate::ctb_test]
654    fn accept_encoding_header_with_invalid_spaces() {
655        let mut headers = http::HeaderMap::new();
656        headers.append(
657            http::header::ACCEPT_ENCODING,
658            http::HeaderValue::from_static("gzip;q =0.5"),
659        );
660        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
661        assert_eq!(Some(Encoding::Identity), encoding);
662
663        let mut headers = http::HeaderMap::new();
664        headers.append(
665            http::header::ACCEPT_ENCODING,
666            http::HeaderValue::from_static("gzip;q= 0.5"),
667        );
668        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
669        assert_eq!(Some(Encoding::Identity), encoding);
670    }
671
672    #[crate::ctb_test]
673    fn accept_encoding_header_with_invalid_quvalues() {
674        let mut headers = http::HeaderMap::new();
675        headers.append(
676            http::header::ACCEPT_ENCODING,
677            http::HeaderValue::from_static("gzip;q=-0.1"),
678        );
679        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
680        assert_eq!(Some(Encoding::Identity), encoding);
681
682        let mut headers = http::HeaderMap::new();
683        headers.append(
684            http::header::ACCEPT_ENCODING,
685            http::HeaderValue::from_static("gzip;q=00.5"),
686        );
687        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
688        assert_eq!(Some(Encoding::Identity), encoding);
689
690        let mut headers = http::HeaderMap::new();
691        headers.append(
692            http::header::ACCEPT_ENCODING,
693            http::HeaderValue::from_static("gzip;q=0.5000"),
694        );
695        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
696        assert_eq!(Some(Encoding::Identity), encoding);
697
698        let mut headers = http::HeaderMap::new();
699        headers.append(
700            http::header::ACCEPT_ENCODING,
701            http::HeaderValue::from_static("gzip;q=.5"),
702        );
703        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
704        assert_eq!(Some(Encoding::Identity), encoding);
705
706        let mut headers = http::HeaderMap::new();
707        headers.append(
708            http::header::ACCEPT_ENCODING,
709            http::HeaderValue::from_static("gzip;q=1.01"),
710        );
711        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
712        assert_eq!(Some(Encoding::Identity), encoding);
713
714        let mut headers = http::HeaderMap::new();
715        headers.append(
716            http::header::ACCEPT_ENCODING,
717            http::HeaderValue::from_static("gzip;q=1.001"),
718        );
719        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
720        assert_eq!(Some(Encoding::Identity), encoding);
721    }
722
723    #[crate::ctb_test]
724    fn wildcard_alone_picks_best_supported() {
725        let mut headers = http::HeaderMap::new();
726        headers.append(
727            http::header::ACCEPT_ENCODING,
728            http::HeaderValue::from_static("*"),
729        );
730        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
731        // * with q=1 means all encodings are acceptable; picks the highest-priority supported
732        assert_eq!(Some(Encoding::Zstd), encoding);
733    }
734
735    #[crate::ctb_test]
736    fn wildcard_q_zero_with_nothing_else_returns_not_satisfiable() {
737        let mut headers = http::HeaderMap::new();
738        headers.append(
739            http::header::ACCEPT_ENCODING,
740            http::HeaderValue::from_static("*;q=0"),
741        );
742        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
743        // *;q=0 rejects everything, including identity
744        assert_eq!(None, encoding);
745    }
746
747    #[crate::ctb_test]
748    fn wildcard_q_zero_with_gzip_picks_gzip() {
749        let mut headers = http::HeaderMap::new();
750        headers.append(
751            http::header::ACCEPT_ENCODING,
752            http::HeaderValue::from_static("*;q=0,gzip"),
753        );
754        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
755        assert_eq!(Some(Encoding::Gzip), encoding);
756    }
757
758    #[crate::ctb_test]
759    fn identity_q_zero_alone_returns_not_satisfiable() {
760        let mut headers = http::HeaderMap::new();
761        headers.append(
762            http::header::ACCEPT_ENCODING,
763            http::HeaderValue::from_static("identity;q=0"),
764        );
765        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
766        // identity;q=0 with no other encoding explicitly listed: the server cannot
767        // determine what the client accepts, so 406 per RFC 9110 §12.5.3
768        assert_eq!(None, encoding);
769    }
770
771    #[crate::ctb_test]
772    fn identity_q_zero_with_gzip_picks_gzip() {
773        let mut headers = http::HeaderMap::new();
774        headers.append(
775            http::header::ACCEPT_ENCODING,
776            http::HeaderValue::from_static("identity;q=0,gzip"),
777        );
778        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
779        assert_eq!(Some(Encoding::Gzip), encoding);
780    }
781
782    #[crate::ctb_test]
783    fn wildcard_q_zero_identity_q_zero_no_compression_returns_not_satisfiable()
784    {
785        // *;q=0,identity;q=0 with no explicit compression listed
786        let mut headers = http::HeaderMap::new();
787        headers.append(
788            http::header::ACCEPT_ENCODING,
789            http::HeaderValue::from_static("*;q=0,identity;q=0"),
790        );
791        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
792        // Both wildcard and identity are q=0, and no explicit encoding is listed with q>0
793        assert_eq!(None, encoding);
794    }
795
796    #[crate::ctb_test]
797    fn wildcard_with_low_qvalue() {
798        let mut headers = http::HeaderMap::new();
799        headers.append(
800            http::header::ACCEPT_ENCODING,
801            http::HeaderValue::from_static("*;q=0.5,gzip;q=1"),
802        );
803        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
804        // gzip is explicitly q=1, everything else gets q=0.5 from wildcard
805        assert_eq!(Some(Encoding::Gzip), encoding);
806    }
807
808    #[crate::ctb_test]
809    fn wildcard_q_zero_with_identity_picks_identity() {
810        let mut headers = http::HeaderMap::new();
811        headers.append(
812            http::header::ACCEPT_ENCODING,
813            http::HeaderValue::from_static("*;q=0,identity"),
814        );
815        let encoding = Encoding::from_headers(&headers, SupportedEncodingsAll);
816        // *;q=0 rejects all, but identity is explicitly listed with q=1
817        assert_eq!(Some(Encoding::Identity), encoding);
818    }
819
820    #[derive(Copy, Clone)]
821    struct SupportedGzipOnly;
822
823    impl SupportedEncodings for SupportedGzipOnly {
824        fn gzip(&self) -> bool {
825            true
826        }
827        fn deflate(&self) -> bool {
828            false
829        }
830        fn br(&self) -> bool {
831            false
832        }
833        fn zstd(&self) -> bool {
834            false
835        }
836    }
837
838    #[crate::ctb_test]
839    fn wildcard_with_partial_server_support_picks_best_available() {
840        let mut headers = http::HeaderMap::new();
841        headers.append(
842            http::header::ACCEPT_ENCODING,
843            http::HeaderValue::from_static("*"),
844        );
845        let encoding = Encoding::from_headers(&headers, SupportedGzipOnly);
846        // Server only supports gzip, so * should pick gzip (not zstd/br)
847        assert_eq!(Some(Encoding::Gzip), encoding);
848    }
849
850    #[crate::ctb_test]
851    fn wildcard_q_zero_with_unsupported_encoding_returns_not_satisfiable() {
852        let mut headers = http::HeaderMap::new();
853        headers.append(
854            http::header::ACCEPT_ENCODING,
855            http::HeaderValue::from_static("*;q=0,br"),
856        );
857        let encoding = Encoding::from_headers(&headers, SupportedGzipOnly);
858        // Client wants br, but server only supports gzip. br is not in the
859        // supported set so it's ignored by encodings(). Wildcard rejects
860        // everything else. Result: 406.
861        assert_eq!(None, encoding);
862    }
863}
864
865/*
866Code from tower-http is used under the following license:
867======
868
869Copyright (c) 2019-2021 Tower Contributors
870
871Permission is hereby granted, free of charge, to any
872person obtaining a copy of this software and associated
873documentation files (the "Software"), to deal in the
874Software without restriction, including without
875limitation the rights to use, copy, modify, merge,
876publish, distribute, sublicense, and/or sell copies of
877the Software, and to permit persons to whom the Software
878is furnished to do so, subject to the following
879conditions:
880
881The above copyright notice and this permission notice
882shall be included in all copies or substantial portions
883of the Software.
884
885THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
886ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
887TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
888PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
889SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
890CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
891OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
892IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
893DEALINGS IN THE SOFTWARE.
894
895
896*/