hyper_sync/header/shared/
quality_item.rs

1#[allow(unused, deprecated)]
2use std::ascii::AsciiExt;
3use std::cmp;
4use std::default::Default;
5use std::fmt;
6use std::str;
7
8use self::internal::IntoQuality;
9
10/// Represents a quality used in quality values.
11///
12/// Can be created with the `q` function.
13///
14/// # Implementation notes
15///
16/// The quality value is defined as a number between 0 and 1 with three decimal places. This means
17/// there are 1001 possible values. Since floating point numbers are not exact and the smallest
18/// floating point data type (`f32`) consumes four bytes, hyper_sync uses an `u16` value to store the
19/// quality internally. For performance reasons you may set quality directly to a value between
20/// 0 and 1000 e.g. `Quality(532)` matches the quality `q=0.532`.
21///
22/// [RFC7231 Section 5.3.1](https://tools.ietf.org/html/rfc7231#section-5.3.1)
23/// gives more information on quality values in HTTP header fields.
24#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
25pub struct Quality(u16);
26
27impl Default for Quality {
28    fn default() -> Quality {
29        Quality(1000)
30    }
31}
32
33/// Represents an item with a quality value as defined in
34/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.3.1).
35#[derive(Clone, PartialEq, Debug)]
36pub struct QualityItem<T> {
37    /// The actual contents of the field.
38    pub item: T,
39    /// The quality (client or server preference) for the value.
40    pub quality: Quality,
41}
42
43impl<T> QualityItem<T> {
44    /// Creates a new `QualityItem` from an item and a quality.
45    /// The item can be of any type.
46    /// The quality should be a value in the range [0, 1].
47    pub fn new(item: T, quality: Quality) -> QualityItem<T> {
48        QualityItem {
49            item: item,
50            quality: quality
51        }
52    }
53}
54
55impl<T: PartialEq> cmp::PartialOrd for QualityItem<T> {
56    fn partial_cmp(&self, other: &QualityItem<T>) -> Option<cmp::Ordering> {
57        self.quality.partial_cmp(&other.quality)
58    }
59}
60
61impl<T: fmt::Display> fmt::Display for QualityItem<T> {
62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63        try!(fmt::Display::fmt(&self.item, f));
64        match self.quality.0 {
65            1000 => Ok(()),
66            0 => f.write_str("; q=0"),
67            x => write!(f, "; q=0.{}", format!("{:03}", x).trim_right_matches('0'))
68        }
69    }
70}
71
72impl<T: str::FromStr> str::FromStr for QualityItem<T> {
73    type Err = ::Error;
74    fn from_str(s: &str) -> ::Result<QualityItem<T>> {
75        if !s.is_ascii() {
76            return Err(::Error::Header);
77        }
78        // Set defaults used if parsing fails.
79        let mut raw_item = s;
80        let mut quality = 1f32;
81
82        let parts: Vec<&str> = s.rsplitn(2, ';').map(|x| x.trim()).collect();
83        if parts.len() == 2 {
84            if parts[0].len() < 2 {
85                return Err(::Error::Header);
86            }
87            let start = &parts[0][0..2];
88            if start == "q=" || start == "Q=" {
89                let q_part = &parts[0][2..parts[0].len()];
90                if q_part.len() > 5 {
91                    return Err(::Error::Header);
92                }
93                match q_part.parse::<f32>() {
94                    Ok(q_value) => {
95                        if 0f32 <= q_value && q_value <= 1f32 {
96                            quality = q_value;
97                            raw_item = parts[1];
98                            } else {
99                                return Err(::Error::Header);
100                            }
101                        },
102                    Err(_) => return Err(::Error::Header),
103                }
104            }
105        }
106        match raw_item.parse::<T>() {
107            // we already checked above that the quality is within range
108            Ok(item) => Ok(QualityItem::new(item, from_f32(quality))),
109            Err(_) => Err(::Error::Header),
110        }
111    }
112}
113
114#[inline]
115fn from_f32(f: f32) -> Quality {
116    // this function is only used internally. A check that `f` is within range
117    // should be done before calling this method. Just in case, this
118    // debug_assert should catch if we were forgetful
119    debug_assert!(f >= 0f32 && f <= 1f32, "q value must be between 0.0 and 1.0");
120    Quality((f * 1000f32) as u16)
121}
122
123/// Convenience function to wrap a value in a `QualityItem`
124/// Sets `q` to the default 1.0
125pub fn qitem<T>(item: T) -> QualityItem<T> {
126    QualityItem::new(item, Default::default())
127}
128
129/// Convenience function to create a `Quality` from a float or integer.
130/// 
131/// Implemented for `u16` and `f32`. Panics if value is out of range.
132pub fn q<T: IntoQuality>(val: T) -> Quality {
133    val.into_quality()
134}
135
136mod internal {
137    use super::Quality;
138
139    // TryFrom is probably better, but it's not stable. For now, we want to
140    // keep the functionality of the `q` function, while allowing it to be
141    // generic over `f32` and `u16`.
142    //
143    // `q` would panic before, so keep that behavior. `TryFrom` can be
144    // introduced later for a non-panicking conversion.
145
146    pub trait IntoQuality: Sealed + Sized {
147        fn into_quality(self) -> Quality;
148    }
149
150    impl IntoQuality for f32 {
151        fn into_quality(self) -> Quality {
152            assert!(self >= 0f32 && self <= 1f32, "float must be between 0.0 and 1.0");
153            super::from_f32(self)
154        }
155    }
156
157    impl IntoQuality for u16 {
158        fn into_quality(self) -> Quality {
159            assert!(self <= 1000, "u16 must be between 0 and 1000");
160            Quality(self)
161        }
162    }
163
164
165    pub trait Sealed {}
166    impl Sealed for u16 {}
167    impl Sealed for f32 {}
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use super::super::encoding::*;
174
175    #[test]
176    fn test_quality_item_fmt_q_1() {
177        let x = qitem(Chunked);
178        assert_eq!(format!("{}", x), "chunked");
179    }
180    #[test]
181    fn test_quality_item_fmt_q_0001() {
182        let x = QualityItem::new(Chunked, Quality(1));
183        assert_eq!(format!("{}", x), "chunked; q=0.001");
184    }
185    #[test]
186    fn test_quality_item_fmt_q_05() {
187        // Custom value
188        let x = QualityItem{
189            item: EncodingExt("identity".to_owned()),
190            quality: Quality(500),
191        };
192        assert_eq!(format!("{}", x), "identity; q=0.5");
193    }
194
195    #[test]
196    fn test_quality_item_fmt_q_0() {
197        // Custom value
198        let x = QualityItem{
199            item: EncodingExt("identity".to_owned()),
200            quality: Quality(0),
201        };
202        assert_eq!(x.to_string(), "identity; q=0");
203    }
204
205    #[test]
206    fn test_quality_item_from_str1() {
207        let x: ::Result<QualityItem<Encoding>> = "chunked".parse();
208        assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: Quality(1000), });
209    }
210    #[test]
211    fn test_quality_item_from_str2() {
212        let x: ::Result<QualityItem<Encoding>> = "chunked; q=1".parse();
213        assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: Quality(1000), });
214    }
215    #[test]
216    fn test_quality_item_from_str3() {
217        let x: ::Result<QualityItem<Encoding>> = "gzip; q=0.5".parse();
218        assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: Quality(500), });
219    }
220    #[test]
221    fn test_quality_item_from_str4() {
222        let x: ::Result<QualityItem<Encoding>> = "gzip; q=0.273".parse();
223        assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: Quality(273), });
224    }
225    #[test]
226    fn test_quality_item_from_str5() {
227        let x: ::Result<QualityItem<Encoding>> = "gzip; q=0.2739999".parse();
228        assert!(x.is_err());
229    }
230    #[test]
231    fn test_quality_item_from_str6() {
232        let x: ::Result<QualityItem<Encoding>> = "gzip; q=2".parse();
233        assert!(x.is_err());
234    }
235    #[test]
236    fn test_quality_item_ordering() {
237        let x: QualityItem<Encoding> = "gzip; q=0.5".parse().ok().unwrap();
238        let y: QualityItem<Encoding> = "gzip; q=0.273".parse().ok().unwrap();
239        let comparision_result: bool = x.gt(&y);
240        assert!(comparision_result)
241    }
242
243    #[test]
244    fn test_quality() {
245        assert_eq!(q(0.5), Quality(500));
246    }
247
248    #[test]
249    #[should_panic] // FIXME - 32-bit msvc unwinding broken
250    #[cfg_attr(all(target_arch="x86", target_env="msvc"), ignore)]
251    fn test_quality_invalid() {
252        q(-1.0);
253    }
254
255    #[test]
256    #[should_panic] // FIXME - 32-bit msvc unwinding broken
257    #[cfg_attr(all(target_arch="x86", target_env="msvc"), ignore)]
258    fn test_quality_invalid2() {
259        q(2.0);
260    }
261
262    #[test]
263    fn test_fuzzing_bugs() {
264        assert!("99999;".parse::<QualityItem<String>>().is_err());
265        assert!("\x0d;;;=\u{d6aa}==".parse::<QualityItem<String>>().is_err())
266    }
267}