net_traits/
quality.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5// TODO(eijebong): Remove this once typed headers figure out quality
6// This is copy pasted from the old hyper headers to avoid hardcoding everything
7// (I would probably also make some silly mistakes while migrating...)
8
9use std::{fmt, str};
10
11use http::header::HeaderValue;
12use mime::Mime;
13
14/// A quality value, as specified in [RFC7231].
15///
16/// Quality values are decimal numbers between 0 and 1 (inclusive) with up to 3 fractional digits of precision.
17///
18/// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3.1
19#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
20pub struct Quality(u16);
21
22impl Quality {
23    /// Creates a quality value from a value between 0 and 1000 inclusive.
24    ///
25    /// This is semantically divided by 1000 to produce a value between 0 and 1.
26    ///
27    /// # Panics
28    ///
29    /// Panics if the value is greater than 1000.
30    pub fn from_u16(quality: u16) -> Quality {
31        assert!(quality <= 1000);
32        Quality(quality)
33    }
34}
35
36/// A value paired with its "quality" as defined in [RFC7231].
37///
38/// Quality items are used in content negotiation headers such as `Accept` and `Accept-Encoding`.
39///
40/// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3
41#[derive(Clone, Debug, PartialEq)]
42pub struct QualityItem<T> {
43    pub item: T,
44    pub quality: Quality,
45}
46
47impl<T> QualityItem<T> {
48    /// Creates a new quality item.
49    pub fn new(item: T, quality: Quality) -> QualityItem<T> {
50        QualityItem { item, quality }
51    }
52}
53
54impl<T> fmt::Display for QualityItem<T>
55where
56    T: fmt::Display,
57{
58    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
59        fmt::Display::fmt(&self.item, fmt)?;
60        match self.quality.0 {
61            1000 => Ok(()),
62            0 => fmt.write_str(";q=0"),
63            mut x => {
64                fmt.write_str(";q=0.")?;
65                let mut digits = *b"000";
66                digits[2] = (x % 10) as u8 + b'0';
67                x /= 10;
68                digits[1] = (x % 10) as u8 + b'0';
69                x /= 10;
70                digits[0] = (x % 10) as u8 + b'0';
71
72                let s = str::from_utf8(&digits[..]).unwrap();
73                fmt.write_str(s.trim_end_matches('0'))
74            },
75        }
76    }
77}
78
79pub fn quality_to_value(q: Vec<QualityItem<Mime>>) -> HeaderValue {
80    HeaderValue::from_str(
81        &q.iter()
82            .map(|q| q.to_string())
83            .collect::<Vec<String>>()
84            .join(","),
85    )
86    .unwrap()
87}