|
2 | 2 |
|
3 | 3 | use crate::content::EncodingProposal;
|
4 | 4 | use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, ACCEPT_ENCODING};
|
| 5 | +use crate::utils::sort_by_weight; |
5 | 6 |
|
6 | 7 | use std::fmt::{self, Debug, Write};
|
7 | 8 | use std::option;
|
@@ -70,6 +71,11 @@ impl AcceptEncoding {
|
70 | 71 | self.wildcard = wildcard
|
71 | 72 | }
|
72 | 73 |
|
| 74 | + /// Sort the entries in-place. |
| 75 | + pub fn sort(&mut self) { |
| 76 | + sort_by_weight(&mut self.entries); |
| 77 | + } |
| 78 | + |
73 | 79 | /// Insert a `HeaderName` + `HeaderValue` pair into a `Headers` instance.
|
74 | 80 | pub fn apply(&self, mut headers: impl AsMut<Headers>) {
|
75 | 81 | headers.as_mut().insert(ACCEPT_ENCODING, self.value());
|
@@ -291,21 +297,18 @@ mod test {
|
291 | 297 | fn reorder_iter_based_on_weight() -> crate::Result<()> {
|
292 | 298 | let mut accept = AcceptEncoding::new();
|
293 | 299 | accept.push(EncodingProposal::new(Encoding::Gzip, Some(0.4))?);
|
| 300 | + accept.push(EncodingProposal::new(Encoding::Identity, None)?); |
294 | 301 | accept.push(EncodingProposal::new(Encoding::Brotli, Some(0.8))?);
|
295 | 302 |
|
296 | 303 | let mut headers = Response::new(200);
|
297 | 304 | accept.apply(&mut headers);
|
298 | 305 |
|
299 |
| - let accept = AcceptEncoding::from_headers(headers)?.unwrap(); |
| 306 | + let mut accept = AcceptEncoding::from_headers(headers)?.unwrap(); |
| 307 | + accept.sort(); |
300 | 308 | let mut accept = accept.iter();
|
301 | 309 | assert_eq!(accept.next().unwrap(), Encoding::Brotli);
|
302 | 310 | assert_eq!(accept.next().unwrap(), Encoding::Gzip);
|
| 311 | + assert_eq!(accept.next().unwrap(), Encoding::Identity); |
303 | 312 | Ok(())
|
304 | 313 | }
|
305 | 314 | }
|
306 |
| - |
307 |
| -/// Order header proposals. In the case of two proposals of equal weight we pick |
308 |
| -/// the one that was declared last. |
309 |
| -fn sort_proposals<T: PartialOrd>(props: &mut Vec<T>) { |
310 |
| - props.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Less)) |
311 |
| -} |
|
0 commit comments