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