Skip to content

Commit 70f4747

Browse files
authored
add method for getting accept type preference (#1793)
1 parent 2f11ef0 commit 70f4747

3 files changed

Lines changed: 138 additions & 9 deletions

File tree

‎actix-http/CHANGES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased - 2020-xx-xx
44
### Added
55
* HttpResponse builders for 1xx status codes. [#1768]
6+
* `Accept::mime_precedence` and `Accept::mime_preference`. [#1793]
67

78
### Fixed
89
* Started dropping `transfer-encoding: chunked` and `Content-Length` for 1XX and 204 responses. [#1767]
@@ -12,6 +13,7 @@
1213

1314
[#1767]: https://github.com/actix/actix-web/pull/1767
1415
[#1768]: https://github.com/actix/actix-web/pull/1768
16+
[#1793]: https://github.com/actix/actix-web/pull/1793
1517

1618

1719
## 2.1.0 - 2020-10-30

‎actix-http/src/header/common/accept.rs‎

Lines changed: 134 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::cmp::Ordering;
2+
13
use mime::Mime;
24

35
use crate::header::{qitem, QualityItem};
@@ -7,7 +9,7 @@ header! {
79
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
810
///
911
/// The `Accept` header field can be used by user agents to specify
10-
/// response media types that are acceptable. Accept header fields can
12+
/// response media types that are acceptable. Accept header fields can
1113
/// be used to indicate that the request is specifically limited to a
1214
/// small set of desired types, as in the case of a request for an
1315
/// in-line image
@@ -97,14 +99,14 @@ header! {
9799
test_header!(
98100
test1,
99101
vec![b"audio/*; q=0.2, audio/basic"],
100-
Some(HeaderField(vec![
102+
Some(Accept(vec![
101103
QualityItem::new("audio/*".parse().unwrap(), q(200)),
102104
qitem("audio/basic".parse().unwrap()),
103105
])));
104106
test_header!(
105107
test2,
106108
vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
107-
Some(HeaderField(vec![
109+
Some(Accept(vec![
108110
QualityItem::new(mime::TEXT_PLAIN, q(500)),
109111
qitem(mime::TEXT_HTML),
110112
QualityItem::new(
@@ -138,23 +140,148 @@ header! {
138140
}
139141

140142
impl Accept {
141-
/// A constructor to easily create `Accept: */*`.
143+
/// Construct `Accept: */*`.
142144
pub fn star() -> Accept {
143145
Accept(vec![qitem(mime::STAR_STAR)])
144146
}
145147

146-
/// A constructor to easily create `Accept: application/json`.
148+
/// Construct `Accept: application/json`.
147149
pub fn json() -> Accept {
148150
Accept(vec![qitem(mime::APPLICATION_JSON)])
149151
}
150152

151-
/// A constructor to easily create `Accept: text/*`.
153+
/// Construct `Accept: text/*`.
152154
pub fn text() -> Accept {
153155
Accept(vec![qitem(mime::TEXT_STAR)])
154156
}
155157

156-
/// A constructor to easily create `Accept: image/*`.
158+
/// Construct `Accept: image/*`.
157159
pub fn image() -> Accept {
158160
Accept(vec![qitem(mime::IMAGE_STAR)])
159161
}
162+
163+
/// Construct `Accept: text/html`.
164+
pub fn html() -> Accept {
165+
Accept(vec![qitem(mime::TEXT_HTML)])
166+
}
167+
168+
/// Returns a sorted list of mime types from highest to lowest preference, accounting for
169+
/// [q-factor weighting] and specificity.
170+
///
171+
/// [q-factor weighting]: https://tools.ietf.org/html/rfc7231#section-5.3.2
172+
pub fn mime_precedence(&self) -> Vec<Mime> {
173+
let mut types = self.0.clone();
174+
175+
// use stable sort so items with equal q-factor and specificity retain listed order
176+
types.sort_by(|a, b| {
177+
// sort by q-factor descending
178+
b.quality.cmp(&a.quality).then_with(|| {
179+
// use specificity rules on mime types with
180+
// same q-factor (eg. text/html > text/* > */*)
181+
182+
// subtypes are not comparable if main type is star, so return
183+
match (a.item.type_(), b.item.type_()) {
184+
(mime::STAR, mime::STAR) => return Ordering::Equal,
185+
186+
// a is sorted after b
187+
(mime::STAR, _) => return Ordering::Greater,
188+
189+
// a is sorted before b
190+
(_, mime::STAR) => return Ordering::Less,
191+
192+
_ => {}
193+
}
194+
195+
// in both these match expressions, the returned ordering appears
196+
// inverted because sort is high-to-low ("descending") precedence
197+
match (a.item.subtype(), b.item.subtype()) {
198+
(mime::STAR, mime::STAR) => Ordering::Equal,
199+
200+
// a is sorted after b
201+
(mime::STAR, _) => Ordering::Greater,
202+
203+
// a is sorted before b
204+
(_, mime::STAR) => Ordering::Less,
205+
206+
_ => Ordering::Equal,
207+
}
208+
})
209+
});
210+
211+
types.into_iter().map(|qitem| qitem.item).collect()
212+
}
213+
214+
/// Extracts the most preferable mime type, accounting for [q-factor weighting].
215+
///
216+
/// If no q-factors are provided, the first mime type is chosen. Note that items without
217+
/// q-factors are given the maximum preference value.
218+
///
219+
/// Returns `None` if contained list is empty.
220+
///
221+
/// [q-factor weighting]: https://tools.ietf.org/html/rfc7231#section-5.3.2
222+
pub fn mime_preference(&self) -> Option<Mime> {
223+
let types = self.mime_precedence();
224+
types.first().cloned()
225+
}
226+
}
227+
228+
#[cfg(test)]
229+
mod tests {
230+
use super::*;
231+
use crate::header::q;
232+
233+
#[test]
234+
fn test_mime_precedence() {
235+
let test = Accept(vec![]);
236+
assert!(test.mime_precedence().is_empty());
237+
238+
let test = Accept(vec![qitem(mime::APPLICATION_JSON)]);
239+
assert_eq!(test.mime_precedence(), vec!(mime::APPLICATION_JSON));
240+
241+
let test = Accept(vec![
242+
qitem(mime::TEXT_HTML),
243+
"application/xhtml+xml".parse().unwrap(),
244+
QualityItem::new("application/xml".parse().unwrap(), q(0.9)),
245+
QualityItem::new(mime::STAR_STAR, q(0.8)),
246+
]);
247+
assert_eq!(
248+
test.mime_precedence(),
249+
vec![
250+
mime::TEXT_HTML,
251+
"application/xhtml+xml".parse().unwrap(),
252+
"application/xml".parse().unwrap(),
253+
mime::STAR_STAR,
254+
]
255+
);
256+
257+
let test = Accept(vec![
258+
qitem(mime::STAR_STAR),
259+
qitem(mime::IMAGE_STAR),
260+
qitem(mime::IMAGE_PNG),
261+
]);
262+
assert_eq!(
263+
test.mime_precedence(),
264+
vec![mime::IMAGE_PNG, mime::IMAGE_STAR, mime::STAR_STAR]
265+
);
266+
}
267+
268+
#[test]
269+
fn test_mime_preference() {
270+
let test = Accept(vec![
271+
qitem(mime::TEXT_HTML),
272+
"application/xhtml+xml".parse().unwrap(),
273+
QualityItem::new("application/xml".parse().unwrap(), q(0.9)),
274+
QualityItem::new(mime::STAR_STAR, q(0.8)),
275+
]);
276+
assert_eq!(test.mime_preference(), Some(mime::TEXT_HTML));
277+
278+
let test = Accept(vec![
279+
QualityItem::new("video/*".parse().unwrap(), q(0.8)),
280+
qitem(mime::IMAGE_PNG),
281+
QualityItem::new(mime::STAR_STAR, q(0.5)),
282+
qitem(mime::IMAGE_SVG),
283+
QualityItem::new(mime::IMAGE_STAR, q(0.8)),
284+
]);
285+
assert_eq!(test.mime_preference(), Some(mime::IMAGE_PNG));
286+
}
160287
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use self::internal::IntoQuality;
1818
///
1919
/// [RFC7231 Section 5.3.1](https://tools.ietf.org/html/rfc7231#section-5.3.1)
2020
/// gives more information on quality values in HTTP header fields.
21-
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
21+
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
2222
pub struct Quality(u16);
2323

2424
impl Default for Quality {
@@ -121,7 +121,7 @@ fn from_f32(f: f32) -> Quality {
121121
/// Convenience function to wrap a value in a `QualityItem`
122122
/// Sets `q` to the default 1.0
123123
pub fn qitem<T>(item: T) -> QualityItem<T> {
124-
QualityItem::new(item, Default::default())
124+
QualityItem::new(item, Quality::default())
125125
}
126126

127127
/// Convenience function to create a `Quality` from a float or integer.

0 commit comments

Comments
 (0)