|
7 | 7 | //! ## Examples
|
8 | 8 | //! ```rust
|
9 | 9 | //! # use failure::Error;
|
| 10 | +//! use accept_encoding::Encoding; |
10 | 11 | //! use http::header::{HeaderMap, HeaderValue, ACCEPT_ENCODING};
|
11 | 12 | //!
|
12 | 13 | //! # fn main () -> Result<(), failure::Error> {
|
13 | 14 | //! let mut headers = HeaderMap::new();
|
14 | 15 | //! headers.insert(ACCEPT_ENCODING, HeaderValue::from_str("gzip, deflate, br")?);
|
15 | 16 | //!
|
16 | 17 | //! let encoding = accept_encoding::parse(&headers)?;
|
17 |
| -//! assert!(encoding.is_gzip()); |
| 18 | +//! assert_eq!(encoding, Some(Encoding::Gzip)); |
18 | 19 | //! # Ok(())}
|
19 | 20 | //! ```
|
20 | 21 | //!
|
21 | 22 | //! ```rust
|
22 | 23 | //! # use failure::Error;
|
| 24 | +//! use accept_encoding::Encoding; |
23 | 25 | //! use http::header::{HeaderMap, HeaderValue, ACCEPT_ENCODING};
|
24 | 26 | //!
|
25 | 27 | //! # fn main () -> Result<(), failure::Error> {
|
26 | 28 | //! let mut headers = HeaderMap::new();
|
27 | 29 | //! headers.insert(ACCEPT_ENCODING, HeaderValue::from_str("gzip;q=0.5, deflate;q=0.9, br;q=1.0")?);
|
28 | 30 | //!
|
29 | 31 | //! let encoding = accept_encoding::parse(&headers)?;
|
30 |
| -//! assert!(encoding.is_brotli()); |
| 32 | +//! assert_eq!(encoding, Some(Encoding::Brotli)); |
31 | 33 | //! # Ok(())}
|
32 | 34 | //! ```
|
33 | 35 |
|
34 | 36 | mod error;
|
35 | 37 |
|
36 | 38 | pub use crate::error::{Error, ErrorKind, Result};
|
37 |
| -use derive_is_enum_variant::is_enum_variant; |
38 | 39 | use failure::ResultExt;
|
39 | 40 | use http::header::{HeaderMap, HeaderValue, ACCEPT_ENCODING};
|
40 | 41 |
|
41 | 42 | /// Encoding levels.
|
42 |
| -#[derive(Debug, Clone, Copy, Eq, PartialEq, is_enum_variant)] |
| 43 | +#[derive(Debug, Clone, Copy, Eq, PartialEq)] |
43 | 44 | pub enum Encoding {
|
44 |
| - /// Gzip is the most preferred encoding present. |
| 45 | + /// The Gzip encoding. |
45 | 46 | Gzip,
|
46 |
| - /// Deflate is the most preferred encoding present. |
| 47 | + /// The Deflate encoding. |
47 | 48 | Deflate,
|
48 |
| - /// Brotli is the most preferred encoding present. |
| 49 | + /// The Brotli encoding. |
49 | 50 | Brotli,
|
50 |
| - /// No encoding is preferred. |
| 51 | + /// The Zstd encoding. |
| 52 | + Zstd, |
| 53 | + /// No encoding. |
51 | 54 | Identity,
|
52 |
| - /// No preference is expressed on which encoding to use. Either the `Accept-Encoding` header is not present, or `*` is set as the most preferred encoding. |
53 |
| - None, |
54 | 55 | }
|
55 | 56 |
|
56 | 57 | impl Encoding {
|
57 | 58 | /// Parses a given string into its corresponding encoding.
|
58 |
| - fn parse(s: &str) -> Result<Encoding> { |
| 59 | + fn parse(s: &str) -> Result<Option<Encoding>> { |
59 | 60 | match s {
|
60 |
| - "gzip" => Ok(Encoding::Gzip), |
61 |
| - "deflate" => Ok(Encoding::Deflate), |
62 |
| - "br" => Ok(Encoding::Brotli), |
63 |
| - "identity" => Ok(Encoding::Identity), |
64 |
| - "*" => Ok(Encoding::None), |
| 61 | + "gzip" => Ok(Some(Encoding::Gzip)), |
| 62 | + "deflate" => Ok(Some(Encoding::Deflate)), |
| 63 | + "br" => Ok(Some(Encoding::Brotli)), |
| 64 | + "zstd" => Ok(Some(Encoding::Zstd)), |
| 65 | + "identity" => Ok(Some(Encoding::Identity)), |
| 66 | + "*" => Ok(None), |
65 | 67 | _ => Err(ErrorKind::UnknownEncoding)?,
|
66 | 68 | }
|
67 | 69 | }
|
68 | 70 |
|
69 | 71 | /// Converts the encoding into its' corresponding header value.
|
70 |
| - /// |
71 |
| - /// Note that [`Encoding::None`] will return a HeaderValue with the content `*`. |
72 |
| - /// This is likely not what you want if you are using this to generate the `Content-Encoding` header to be included in an encoded response. |
73 | 72 | pub fn to_header_value(self) -> HeaderValue {
|
74 | 73 | match self {
|
75 | 74 | Encoding::Gzip => HeaderValue::from_str("gzip").unwrap(),
|
76 | 75 | Encoding::Deflate => HeaderValue::from_str("deflate").unwrap(),
|
77 | 76 | Encoding::Brotli => HeaderValue::from_str("br").unwrap(),
|
| 77 | + Encoding::Zstd => HeaderValue::from_str("zstd").unwrap(), |
78 | 78 | Encoding::Identity => HeaderValue::from_str("identity").unwrap(),
|
79 |
| - Encoding::None => HeaderValue::from_str("*").unwrap(), |
80 | 79 | }
|
81 | 80 | }
|
82 | 81 | }
|
83 | 82 |
|
84 |
| -/// Parse a set of HTTP headers into an `Encoding`. |
85 |
| -pub fn parse(headers: &HeaderMap) -> Result<Encoding> { |
86 |
| - let mut preferred_encoding = Encoding::None; |
| 83 | +/// Parse a set of HTTP headers into a single option yielding an `Encoding` that the client prefers. |
| 84 | +/// |
| 85 | +/// If you're looking for an easy way to determine the best encoding for the client and support every [`Encoding`] listed, this is likely what you want. |
| 86 | +/// |
| 87 | +/// Note that a result of `None` indicates there preference is expressed on which encoding to use. |
| 88 | +/// Either the `Accept-Encoding` header is not present, or `*` is set as the most preferred encoding. |
| 89 | +pub fn parse(headers: &HeaderMap) -> Result<Option<Encoding>> { |
| 90 | + let mut preferred_encoding = None; |
87 | 91 | let mut max_qval = 0.0;
|
88 | 92 |
|
89 |
| - for header_value in headers.get_all(ACCEPT_ENCODING).iter() { |
90 |
| - let header_value = header_value.to_str().context(ErrorKind::InvalidEncoding)?; |
91 |
| - for v in header_value.split(',').map(str::trim) { |
92 |
| - let mut v = v.splitn(2, ";q="); |
93 |
| - let encoding = v.next().unwrap(); |
94 |
| - |
95 |
| - match Encoding::parse(encoding) { |
96 |
| - Ok(encoding) => { |
97 |
| - if let Some(qval) = v.next() { |
98 |
| - let qval = match qval.parse::<f32>() { |
99 |
| - Ok(f) => f, |
100 |
| - Err(_) => return Err(ErrorKind::InvalidEncoding)?, |
101 |
| - }; |
102 |
| - if (qval - 1.0f32).abs() < 0.01 { |
103 |
| - preferred_encoding = encoding; |
104 |
| - break; |
105 |
| - } else if qval > 1.0 { |
106 |
| - return Err(ErrorKind::InvalidEncoding)?; // q-values over 1 are unacceptable |
107 |
| - } else if qval > max_qval { |
108 |
| - preferred_encoding = encoding; |
109 |
| - max_qval = qval; |
110 |
| - } |
111 |
| - } else { |
112 |
| - preferred_encoding = encoding; |
113 |
| - break; |
114 |
| - } |
115 |
| - } |
116 |
| - Err(_) => continue, // ignore unknown encodings for now |
117 |
| - } |
| 93 | + for (encoding, qval) in encodings(headers)? { |
| 94 | + if (qval - 1.0f32).abs() < 0.01 { |
| 95 | + preferred_encoding = encoding; |
| 96 | + break; |
| 97 | + } else if qval > max_qval { |
| 98 | + preferred_encoding = encoding; |
| 99 | + max_qval = qval; |
118 | 100 | }
|
119 | 101 | }
|
120 | 102 |
|
121 | 103 | Ok(preferred_encoding)
|
122 | 104 | }
|
| 105 | + |
| 106 | +/// Parse a set of HTTP headers into a vector containing tuples of options containing encodings and their corresponding q-values. |
| 107 | +/// |
| 108 | +/// If you're looking for more fine-grained control over what encoding to choose for the client, or if you don't support every [`Encoding`] listed, this is likely what you want. |
| 109 | +/// |
| 110 | +/// Note that a result of `None` indicates there preference is expressed on which encoding to use. |
| 111 | +/// Either the `Accept-Encoding` header is not present, or `*` is set as the most preferred encoding. |
| 112 | +/// ## Examples |
| 113 | +/// ```rust |
| 114 | +/// # use failure::Error; |
| 115 | +/// use accept_encoding::Encoding; |
| 116 | +/// use http::header::{HeaderMap, HeaderValue, ACCEPT_ENCODING}; |
| 117 | +/// |
| 118 | +/// # fn main () -> Result<(), failure::Error> { |
| 119 | +/// let mut headers = HeaderMap::new(); |
| 120 | +/// headers.insert(ACCEPT_ENCODING, HeaderValue::from_str("zstd;q=1.0, deflate;q=0.8, br;q=0.9")?); |
| 121 | +/// |
| 122 | +/// let encodings = accept_encoding::encodings(&headers)?; |
| 123 | +/// for (encoding, qval) in encodings { |
| 124 | +/// println!("{:?} {}", encoding, qval); |
| 125 | +/// } |
| 126 | +/// # Ok(())} |
| 127 | +/// ``` |
| 128 | +pub fn encodings(headers: &HeaderMap) -> Result<Vec<(Option<Encoding>, f32)>> { |
| 129 | + headers |
| 130 | + .get_all(ACCEPT_ENCODING) |
| 131 | + .iter() |
| 132 | + .map(|hval| { |
| 133 | + hval.to_str() |
| 134 | + .context(ErrorKind::InvalidEncoding) |
| 135 | + .map_err(std::convert::Into::into) |
| 136 | + }) |
| 137 | + .collect::<Result<Vec<&str>>>()? |
| 138 | + .iter() |
| 139 | + .flat_map(|s| s.split(',').map(str::trim)) |
| 140 | + .filter_map(|v| { |
| 141 | + let mut v = v.splitn(2, ";q="); |
| 142 | + let encoding = match Encoding::parse(v.next().unwrap()) { |
| 143 | + Ok(encoding) => encoding, |
| 144 | + Err(_) => return None, // ignore unknown encodings |
| 145 | + }; |
| 146 | + let qval = if let Some(qval) = v.next() { |
| 147 | + let qval = match qval.parse::<f32>() { |
| 148 | + Ok(f) => f, |
| 149 | + Err(_) => return Some(Err(ErrorKind::InvalidEncoding)), |
| 150 | + }; |
| 151 | + if qval > 1.0 { |
| 152 | + return Some(Err(ErrorKind::InvalidEncoding)); // q-values over 1 are unacceptable |
| 153 | + } |
| 154 | + qval |
| 155 | + } else { |
| 156 | + 1.0f32 |
| 157 | + }; |
| 158 | + Some(Ok((encoding, qval))) |
| 159 | + }) |
| 160 | + .map(|v| v.map_err(std::convert::Into::into)) |
| 161 | + .collect::<Result<Vec<(Option<Encoding>, f32)>>>() |
| 162 | +} |
0 commit comments