Skip to content

Commit 5af4677

Browse files
authored
refactor quality and use TryFrom instead of custom trait (#1797)
1 parent 70f4747 commit 5af4677

4 files changed

Lines changed: 106 additions & 86 deletions

File tree

‎actix-http/CHANGES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
### Added
55
* HttpResponse builders for 1xx status codes. [#1768]
66
* `Accept::mime_precedence` and `Accept::mime_preference`. [#1793]
7+
* `TryFrom<u16>` and `TryFrom<f32>` for `http::header::Quality`. [#1797]
78

89
### Fixed
910
* Started dropping `transfer-encoding: chunked` and `Content-Length` for 1XX and 204 responses. [#1767]
@@ -14,6 +15,7 @@
1415
[#1767]: https://github.com/actix/actix-web/pull/1767
1516
[#1768]: https://github.com/actix/actix-web/pull/1768
1617
[#1793]: https://github.com/actix/actix-web/pull/1793
18+
[#1797]: https://github.com/actix/actix-web/pull/1797
1719

1820

1921
## 2.1.0 - 2020-10-30

‎actix-http/src/header/mod.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -370,9 +370,7 @@ impl fmt::Display for ExtendedValue {
370370
}
371371

372372
/// Percent encode a sequence of bytes with a character set defined in
373-
/// [https://tools.ietf.org/html/rfc5987#section-3.2][url]
374-
///
375-
/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
373+
/// <https://tools.ietf.org/html/rfc5987#section-3.2>
376374
pub fn http_percent_encode(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
377375
let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE);
378376
fmt::Display::fmt(&encoded, f)

‎actix-http/src/header/shared/charset.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@ use self::Charset::*;
77
///
88
/// The string representation is normalized to upper case.
99
///
10-
/// See [http://www.iana.org/assignments/character-sets/character-sets.xhtml][url].
11-
///
12-
/// [url]: http://www.iana.org/assignments/character-sets/character-sets.xhtml
10+
/// See <http://www.iana.org/assignments/character-sets/character-sets.xhtml>.
1311
#[derive(Clone, Debug, PartialEq)]
1412
#[allow(non_camel_case_types)]
1513
pub enum Charset {

‎actix-http/src/header/shared/quality_item.rs‎

Lines changed: 102 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
1-
use std::{cmp, fmt, str};
1+
use std::{
2+
cmp,
3+
convert::{TryFrom, TryInto},
4+
fmt, str,
5+
};
26

3-
use self::internal::IntoQuality;
7+
use derive_more::{Display, Error};
8+
9+
const MAX_QUALITY: u16 = 1000;
10+
const MAX_FLOAT_QUALITY: f32 = 1.0;
411

512
/// Represents a quality used in quality values.
613
///
7-
/// Can be created with the `q` function.
14+
/// Can be created with the [`q`] function.
815
///
916
/// # Implementation notes
1017
///
@@ -21,9 +28,51 @@ use self::internal::IntoQuality;
2128
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
2229
pub struct Quality(u16);
2330

31+
impl Quality {
32+
/// # Panics
33+
/// Panics in debug mode when value is not in the range 0.0 <= n <= 1.0.
34+
fn from_f32(value: f32) -> Self {
35+
// Check that `value` is within range should be done before calling this method.
36+
// Just in case, this debug_assert should catch if we were forgetful.
37+
debug_assert!(
38+
(0.0f32..=1.0f32).contains(&value),
39+
"q value must be between 0.0 and 1.0"
40+
);
41+
42+
Quality((value * MAX_QUALITY as f32) as u16)
43+
}
44+
}
45+
2446
impl Default for Quality {
2547
fn default() -> Quality {
26-
Quality(1000)
48+
Quality(MAX_QUALITY)
49+
}
50+
}
51+
52+
#[derive(Debug, Clone, Display, Error)]
53+
pub struct QualityOutOfBounds;
54+
55+
impl TryFrom<u16> for Quality {
56+
type Error = QualityOutOfBounds;
57+
58+
fn try_from(value: u16) -> Result<Self, Self::Error> {
59+
if (0..=MAX_QUALITY).contains(&value) {
60+
Ok(Quality(value))
61+
} else {
62+
Err(QualityOutOfBounds)
63+
}
64+
}
65+
}
66+
67+
impl TryFrom<f32> for Quality {
68+
type Error = QualityOutOfBounds;
69+
70+
fn try_from(value: f32) -> Result<Self, Self::Error> {
71+
if (0.0..=MAX_FLOAT_QUALITY).contains(&value) {
72+
Ok(Quality::from_f32(value))
73+
} else {
74+
Err(QualityOutOfBounds)
75+
}
2776
}
2877
}
2978

@@ -55,8 +104,9 @@ impl<T: PartialEq> cmp::PartialOrd for QualityItem<T> {
55104
impl<T: fmt::Display> fmt::Display for QualityItem<T> {
56105
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57106
fmt::Display::fmt(&self.item, f)?;
107+
58108
match self.quality.0 {
59-
1000 => Ok(()),
109+
MAX_QUALITY => Ok(()),
60110
0 => f.write_str("; q=0"),
61111
x => write!(f, "; q=0.{}", format!("{:03}", x).trim_end_matches('0')),
62112
}
@@ -66,56 +116,61 @@ impl<T: fmt::Display> fmt::Display for QualityItem<T> {
66116
impl<T: str::FromStr> str::FromStr for QualityItem<T> {
67117
type Err = crate::error::ParseError;
68118

69-
fn from_str(s: &str) -> Result<QualityItem<T>, crate::error::ParseError> {
70-
if !s.is_ascii() {
119+
fn from_str(qitem_str: &str) -> Result<QualityItem<T>, crate::error::ParseError> {
120+
if !qitem_str.is_ascii() {
71121
return Err(crate::error::ParseError::Header);
72122
}
123+
73124
// Set defaults used if parsing fails.
74-
let mut raw_item = s;
125+
let mut raw_item = qitem_str;
75126
let mut quality = 1f32;
76127

77-
let parts: Vec<&str> = s.rsplitn(2, ';').map(|x| x.trim()).collect();
128+
let parts: Vec<_> = qitem_str.rsplitn(2, ';').map(str::trim).collect();
129+
78130
if parts.len() == 2 {
131+
// example for item with q-factor:
132+
//
133+
// gzip; q=0.65
134+
// ^^^^^^ parts[0]
135+
// ^^ start
136+
// ^^^^ q_val
137+
// ^^^^ parts[1]
138+
79139
if parts[0].len() < 2 {
140+
// Can't possibly be an attribute since an attribute needs at least a name followed
141+
// by an equals sign. And bare identifiers are forbidden.
80142
return Err(crate::error::ParseError::Header);
81143
}
144+
82145
let start = &parts[0][0..2];
146+
83147
if start == "q=" || start == "Q=" {
84-
let q_part = &parts[0][2..parts[0].len()];
85-
if q_part.len() > 5 {
148+
let q_val = &parts[0][2..];
149+
if q_val.len() > 5 {
150+
// longer than 5 indicates an over-precise q-factor
86151
return Err(crate::error::ParseError::Header);
87152
}
88-
match q_part.parse::<f32>() {
89-
Ok(q_value) => {
90-
if 0f32 <= q_value && q_value <= 1f32 {
91-
quality = q_value;
92-
raw_item = parts[1];
93-
} else {
94-
return Err(crate::error::ParseError::Header);
95-
}
96-
}
97-
Err(_) => return Err(crate::error::ParseError::Header),
153+
154+
let q_value = q_val
155+
.parse::<f32>()
156+
.map_err(|_| crate::error::ParseError::Header)?;
157+
158+
if (0f32..=1f32).contains(&q_value) {
159+
quality = q_value;
160+
raw_item = parts[1];
161+
} else {
162+
return Err(crate::error::ParseError::Header);
98163
}
99164
}
100165
}
101-
match raw_item.parse::<T>() {
102-
// we already checked above that the quality is within range
103-
Ok(item) => Ok(QualityItem::new(item, from_f32(quality))),
104-
Err(_) => Err(crate::error::ParseError::Header),
105-
}
106-
}
107-
}
108166

109-
#[inline]
110-
fn from_f32(f: f32) -> Quality {
111-
// this function is only used internally. A check that `f` is within range
112-
// should be done before calling this method. Just in case, this
113-
// debug_assert should catch if we were forgetful
114-
debug_assert!(
115-
f >= 0f32 && f <= 1f32,
116-
"q value must be between 0.0 and 1.0"
117-
);
118-
Quality((f * 1000f32) as u16)
167+
let item = raw_item
168+
.parse::<T>()
169+
.map_err(|_| crate::error::ParseError::Header)?;
170+
171+
// we already checked above that the quality is within range
172+
Ok(QualityItem::new(item, Quality::from_f32(quality)))
173+
}
119174
}
120175

121176
/// Convenience function to wrap a value in a `QualityItem`
@@ -127,44 +182,13 @@ pub fn qitem<T>(item: T) -> QualityItem<T> {
127182
/// Convenience function to create a `Quality` from a float or integer.
128183
///
129184
/// Implemented for `u16` and `f32`. Panics if value is out of range.
130-
pub fn q<T: IntoQuality>(val: T) -> Quality {
131-
val.into_quality()
132-
}
133-
134-
mod internal {
135-
use super::Quality;
136-
137-
// TryFrom is probably better, but it's not stable. For now, we want to
138-
// keep the functionality of the `q` function, while allowing it to be
139-
// generic over `f32` and `u16`.
140-
//
141-
// `q` would panic before, so keep that behavior. `TryFrom` can be
142-
// introduced later for a non-panicking conversion.
143-
144-
pub trait IntoQuality: Sealed + Sized {
145-
fn into_quality(self) -> Quality;
146-
}
147-
148-
impl IntoQuality for f32 {
149-
fn into_quality(self) -> Quality {
150-
assert!(
151-
self >= 0f32 && self <= 1f32,
152-
"float must be between 0.0 and 1.0"
153-
);
154-
super::from_f32(self)
155-
}
156-
}
157-
158-
impl IntoQuality for u16 {
159-
fn into_quality(self) -> Quality {
160-
assert!(self <= 1000, "u16 must be between 0 and 1000");
161-
Quality(self)
162-
}
163-
}
164-
165-
pub trait Sealed {}
166-
impl Sealed for u16 {}
167-
impl Sealed for f32 {}
185+
pub fn q<T>(val: T) -> Quality
186+
where
187+
T: TryInto<Quality>,
188+
T::Error: fmt::Debug,
189+
{
190+
// TODO: on next breaking change, handle unwrap differently
191+
val.try_into().unwrap()
168192
}
169193

170194
#[cfg(test)]
@@ -270,15 +294,13 @@ mod tests {
270294
}
271295

272296
#[test]
273-
#[should_panic] // FIXME - 32-bit msvc unwinding broken
274-
#[cfg_attr(all(target_arch = "x86", target_env = "msvc"), ignore)]
297+
#[should_panic]
275298
fn test_quality_invalid() {
276299
q(-1.0);
277300
}
278301

279302
#[test]
280-
#[should_panic] // FIXME - 32-bit msvc unwinding broken
281-
#[cfg_attr(all(target_arch = "x86", target_env = "msvc"), ignore)]
303+
#[should_panic]
282304
fn test_quality_invalid2() {
283305
q(2.0);
284306
}

0 commit comments

Comments
 (0)