hyper_sync/header/common/
cache_control.rs

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