hyper_sync/header/shared/
quality_item.rs1#[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#[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#[derive(Clone, PartialEq, Debug)]
36pub struct QualityItem<T> {
37 pub item: T,
39 pub quality: Quality,
41}
42
43impl<T> QualityItem<T> {
44 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 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 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 debug_assert!(f >= 0f32 && f <= 1f32, "q value must be between 0.0 and 1.0");
120 Quality((f * 1000f32) as u16)
121}
122
123pub fn qitem<T>(item: T) -> QualityItem<T> {
126 QualityItem::new(item, Default::default())
127}
128
129pub fn q<T: IntoQuality>(val: T) -> Quality {
133 val.into_quality()
134}
135
136mod internal {
137 use super::Quality;
138
139 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 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 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] #[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] #[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}