hyperx/header/common/
cache_control.rs

1use std::fmt;
2use std::str::FromStr;
3use header::{Header, RawLike};
4use header::parsing::{from_comma_delimited, fmt_comma_delimited};
5
6/// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2)
7///
8/// The `Cache-Control` header field is used to specify directives for
9/// caches along the request/response chain.  Such cache directives are
10/// unidirectional in that the presence of a directive in a request does
11/// not imply that the same directive is to be given in the response.
12///
13/// # ABNF
14///
15/// ```text
16/// Cache-Control   = 1#cache-directive
17/// cache-directive = token [ "=" ( token / quoted-string ) ]
18/// ```
19///
20/// # Example values
21///
22/// * `no-cache`
23/// * `private, community="UCI"`
24/// * `max-age=30`
25///
26/// # Examples
27/// ```
28/// # extern crate http;
29/// use hyperx::header::{CacheControl, CacheDirective, TypedHeaders};
30///
31/// let mut headers = http::HeaderMap::new();
32/// headers.encode(
33///     &CacheControl(vec![CacheDirective::MaxAge(86400u32)])
34/// );
35/// ```
36///
37/// ```
38/// # extern crate http;
39/// use hyperx::header::{CacheControl, CacheDirective, TypedHeaders};
40///
41/// let mut headers = http::HeaderMap::new();
42/// headers.encode(
43///     &CacheControl(vec![
44///         CacheDirective::NoCache,
45///         CacheDirective::Private,
46///         CacheDirective::MaxAge(360u32),
47///         CacheDirective::Extension("foo".to_owned(),
48///                                   Some("bar".to_owned())),
49///     ])
50/// );
51/// ```
52#[derive(PartialEq, Clone, Debug)]
53pub struct CacheControl(pub Vec<CacheDirective>);
54
55__hyper__deref!(CacheControl => Vec<CacheDirective>);
56
57//TODO: this could just be the header! macro
58impl Header for CacheControl {
59    fn header_name() -> &'static str {
60        static NAME: &'static str = "Cache-Control";
61        NAME
62    }
63
64    fn parse_header<'a, T>(raw: &'a T) -> ::Result<CacheControl>
65    where T: RawLike<'a>
66    {
67        let directives = from_comma_delimited(raw)?;
68        if !directives.is_empty() {
69            Ok(CacheControl(directives))
70        } else {
71            Err(::Error::Header)
72        }
73    }
74
75    fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
76        f.fmt_line(self)
77    }
78}
79
80impl fmt::Display for CacheControl {
81    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82        fmt_comma_delimited(f, &self[..])
83    }
84}
85
86/// `CacheControl` contains a list of these directives.
87#[derive(PartialEq, Clone, Debug)]
88pub enum CacheDirective {
89    /// "no-cache"
90    NoCache,
91    /// "no-store"
92    NoStore,
93    /// "no-transform"
94    NoTransform,
95    /// "only-if-cached"
96    OnlyIfCached,
97
98    // request directives
99    /// "max-age=delta"
100    MaxAge(u32),
101    /// "max-stale=delta"
102    MaxStale(u32),
103    /// "min-fresh=delta"
104    MinFresh(u32),
105
106    // response directives
107    /// "must-revalidate"
108    MustRevalidate,
109    /// "public"
110    Public,
111    /// "private"
112    Private,
113    /// "proxy-revalidate"
114    ProxyRevalidate,
115    /// "s-maxage=delta"
116    SMaxAge(u32),
117
118    /// Extension directives. Optionally include an argument.
119    Extension(String, Option<String>)
120}
121
122impl fmt::Display for CacheDirective {
123    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
124        use self::CacheDirective::*;
125        fmt::Display::fmt(match *self {
126            NoCache => "no-cache",
127            NoStore => "no-store",
128            NoTransform => "no-transform",
129            OnlyIfCached => "only-if-cached",
130
131            MaxAge(secs) => return write!(f, "max-age={}", secs),
132            MaxStale(secs) => return write!(f, "max-stale={}", secs),
133            MinFresh(secs) => return write!(f, "min-fresh={}", secs),
134
135            MustRevalidate => "must-revalidate",
136            Public => "public",
137            Private => "private",
138            ProxyRevalidate => "proxy-revalidate",
139            SMaxAge(secs) => return write!(f, "s-maxage={}", secs),
140
141            Extension(ref name, None) => &name[..],
142            Extension(ref name, Some(ref arg)) => return write!(f, "{}={}", name, arg),
143
144        }, f)
145    }
146}
147
148impl FromStr for CacheDirective {
149    type Err = Option<<u32 as FromStr>::Err>;
150    fn from_str(s: &str) -> Result<CacheDirective, Option<<u32 as FromStr>::Err>> {
151        use self::CacheDirective::*;
152        match s {
153            "no-cache" => Ok(NoCache),
154            "no-store" => Ok(NoStore),
155            "no-transform" => Ok(NoTransform),
156            "only-if-cached" => Ok(OnlyIfCached),
157            "must-revalidate" => Ok(MustRevalidate),
158            "public" => Ok(Public),
159            "private" => Ok(Private),
160            "proxy-revalidate" => Ok(ProxyRevalidate),
161            "" => Err(None),
162            _ => match s.find('=') {
163                Some(idx) if idx+1 < s.len() => match (&s[..idx], (&s[idx+1..]).trim_matches('"')) {
164                    ("max-age" , secs) => secs.parse().map(MaxAge).map_err(Some),
165                    ("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
166                    ("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
167                    ("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
168                    (left, right) => Ok(Extension(left.to_owned(), Some(right.to_owned())))
169                },
170                Some(_) => Err(None),
171                None => Ok(Extension(s.to_owned(), None))
172            }
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use header::{Header, Raw};
180    use super::*;
181
182    #[test]
183    fn test_parse_multiple_headers() {
184        let r: Raw = vec![b"no-cache".to_vec(), b"private".to_vec()].into();
185        let cache = Header::parse_header(&r);
186        assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::NoCache,
187                                                 CacheDirective::Private])))
188    }
189
190    #[test]
191    fn test_parse_argument() {
192        let r: Raw = vec![b"max-age=100, private".to_vec()].into();
193        let cache = Header::parse_header(&r);
194        assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(100),
195                                                 CacheDirective::Private])))
196    }
197
198    #[test]
199    fn test_parse_quote_form() {
200        let r: Raw = vec![b"max-age=\"200\"".to_vec()].into();
201        let cache = Header::parse_header(&r);
202        assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(200)])))
203    }
204
205    #[test]
206    fn test_parse_extension() {
207        let r: Raw = vec![b"foo, bar=baz".to_vec()].into();
208        let cache = Header::parse_header(&r);
209        assert_eq!(cache.ok(), Some(CacheControl(vec![
210            CacheDirective::Extension("foo".to_owned(), None),
211            CacheDirective::Extension("bar".to_owned(), Some("baz".to_owned()))])))
212    }
213
214    #[test]
215    fn test_parse_bad_syntax() {
216        let r: Raw = vec![b"foo=".to_vec()].into();
217        let cache: ::Result<CacheControl> = Header::parse_header(&r);
218        assert_eq!(cache.ok(), None)
219    }
220}
221
222bench_header!(normal,
223    CacheControl, { vec![b"no-cache, private".to_vec(), b"max-age=100".to_vec()] });
224
225standard_header!(CacheControl, CACHE_CONTROL);