hyper_sync/header/common/
cache_control.rs1use std::fmt;
2use std::str::FromStr;
3
4use header::{Header, Raw};
5use header::parsing::{from_comma_delimited, fmt_comma_delimited};
6
7#[derive(PartialEq, Clone, Debug)]
52pub struct CacheControl(pub Vec<CacheDirective>);
53
54__hyper__deref!(CacheControl => Vec<CacheDirective>);
55
56impl 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#[derive(PartialEq, Clone, Debug)]
85pub enum CacheDirective {
86 NoCache,
88 NoStore,
90 NoTransform,
92 OnlyIfCached,
94
95 MaxAge(u32),
98 MaxStale(u32),
100 MinFresh(u32),
102
103 MustRevalidate,
106 Public,
108 Private,
110 ProxyRevalidate,
112 SMaxAge(u32),
114
115 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()] });