1use std::fmt;
2use std::str::FromStr;
3use header::{Header, RawLike};
4use header::parsing::{from_comma_delimited, fmt_comma_delimited};
5
6#[derive(PartialEq, Clone, Debug)]
53pub struct CacheControl(pub Vec<CacheDirective>);
54
55__hyper__deref!(CacheControl => Vec<CacheDirective>);
56
57impl 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#[derive(PartialEq, Clone, Debug)]
88pub enum CacheDirective {
89 NoCache,
91 NoStore,
93 NoTransform,
95 OnlyIfCached,
97
98 MaxAge(u32),
101 MaxStale(u32),
103 MinFresh(u32),
105
106 MustRevalidate,
109 Public,
111 Private,
113 ProxyRevalidate,
115 SMaxAge(u32),
117
118 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);