Debian Codegraph @

third_party/rust/headers/src/common/cache_control.rs

raw
1 use std::fmt;
2 use std::iter::FromIterator;
3 use std::str::FromStr;
4 use std::time::Duration;
5
6 use util::{self, csv, Seconds};
7 use HeaderValue;
8
9 /// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2)
10 /// with extensions in [RFC8246](https://www.rfc-editor.org/rfc/rfc8246)
11 ///
12 /// The `Cache-Control` header field is used to specify directives for
13 /// caches along the request/response chain. Such cache directives are
14 /// unidirectional in that the presence of a directive in a request does
15 /// not imply that the same directive is to be given in the response.
16 ///
17 /// ## ABNF
18 ///
19 /// ```text
20 /// Cache-Control = 1#cache-directive
21 /// cache-directive = token [ "=" ( token / quoted-string ) ]
22 /// ```
23 ///
24 /// ## Example values
25 ///
26 /// * `no-cache`
27 /// * `private, community="UCI"`
28 /// * `max-age=30`
29 ///
30 /// # Example
31 ///
32 /// ```
33 /// # extern crate headers;
34 /// use headers::CacheControl;
35 ///
36 /// let cc = CacheControl::new();
37 /// ```
38 #[derive(PartialEq, Clone, Debug)]
39 pub struct CacheControl {
40 flags: Flags,
41 max_age: Option<Seconds>,
42 max_stale: Option<Seconds>,
43 min_fresh: Option<Seconds>,
44 s_max_age: Option<Seconds>,
45 }
46
47 #[derive(Debug, Clone, PartialEq)]
48 struct Flags {
49 bits: u64,
50 }
51
52 impl Flags {
53 const NO_CACHE: Self = Self { bits: 0b000000001 };
54 const NO_STORE: Self = Self { bits: 0b000000010 };
55 const NO_TRANSFORM: Self = Self { bits: 0b000000100 };
56 const ONLY_IF_CACHED: Self = Self { bits: 0b000001000 };
57 const MUST_REVALIDATE: Self = Self { bits: 0b000010000 };
58 const PUBLIC: Self = Self { bits: 0b000100000 };
59 const PRIVATE: Self = Self { bits: 0b001000000 };
60 const PROXY_REVALIDATE: Self = Self { bits: 0b010000000 };
61 const IMMUTABLE: Self = Self { bits: 0b100000000 };
62
63 fn empty() -> Self {
64 Self { bits: 0 }
65 }
66
67 fn contains(&self, flag: Self) -> bool {
68 (self.bits & flag.bits) != 0
69 }
70
71 fn insert(&mut self, flag: Self) {
72 self.bits |= flag.bits;
73 }
74 }
75
76 impl CacheControl {
77 /// Construct a new empty `CacheControl` header.
78 pub fn new() -> Self {
79 CacheControl {
80 flags: Flags::empty(),
81 max_age: None,
82 max_stale: None,
83 min_fresh: None,
84 s_max_age: None,
85 }
86 }
87
88 // getters
89
90 /// Check if the `no-cache` directive is set.
91 pub fn no_cache(&self) -> bool {
92 self.flags.contains(Flags::NO_CACHE)
93 }
94
95 /// Check if the `no-store` directive is set.
96 pub fn no_store(&self) -> bool {
97 self.flags.contains(Flags::NO_STORE)
98 }
99
100 /// Check if the `no-transform` directive is set.
101 pub fn no_transform(&self) -> bool {
102 self.flags.contains(Flags::NO_TRANSFORM)
103 }
104
105 /// Check if the `only-if-cached` directive is set.
106 pub fn only_if_cached(&self) -> bool {
107 self.flags.contains(Flags::ONLY_IF_CACHED)
108 }
109
110 /// Check if the `public` directive is set.
111 pub fn public(&self) -> bool {
112 self.flags.contains(Flags::PUBLIC)
113 }
114
115 /// Check if the `private` directive is set.
116 pub fn private(&self) -> bool {
117 self.flags.contains(Flags::PRIVATE)
118 }
119
120 /// Check if the `immutable` directive is set.
121 pub fn immutable(&self) -> bool {
122 self.flags.contains(Flags::IMMUTABLE)
123 }
124
125 /// Get the value of the `max-age` directive if set.
126 pub fn max_age(&self) -> Option<Duration> {
127 self.max_age.map(Into::into)
128 }
129
130 /// Get the value of the `max-stale` directive if set.
131 pub fn max_stale(&self) -> Option<Duration> {
132 self.max_stale.map(Into::into)
133 }
134
135 /// Get the value of the `min-fresh` directive if set.
136 pub fn min_fresh(&self) -> Option<Duration> {
137 self.min_fresh.map(Into::into)
138 }
139
140 /// Get the value of the `s-maxage` directive if set.
141 pub fn s_max_age(&self) -> Option<Duration> {
142 self.s_max_age.map(Into::into)
143 }
144
145 // setters
146
147 /// Set the `no-cache` directive.
148 pub fn with_no_cache(mut self) -> Self {
149 self.flags.insert(Flags::NO_CACHE);
150 self
151 }
152
153 /// Set the `no-store` directive.
154 pub fn with_no_store(mut self) -> Self {
155 self.flags.insert(Flags::NO_STORE);
156 self
157 }
158
159 /// Set the `no-transform` directive.
160 pub fn with_no_transform(mut self) -> Self {
161 self.flags.insert(Flags::NO_TRANSFORM);
162 self
163 }
164
165 /// Set the `only-if-cached` directive.
166 pub fn with_only_if_cached(mut self) -> Self {
167 self.flags.insert(Flags::ONLY_IF_CACHED);
168 self
169 }
170
171 /// Set the `private` directive.
172 pub fn with_private(mut self) -> Self {
173 self.flags.insert(Flags::PRIVATE);
174 self
175 }
176
177 /// Set the `public` directive.
178 pub fn with_public(mut self) -> Self {
179 self.flags.insert(Flags::PUBLIC);
180 self
181 }
182
183 /// Set the `immutable` directive.
184 pub fn with_immutable(mut self) -> Self {
185 self.flags.insert(Flags::IMMUTABLE);
186 self
187 }
188
189 /// Set the `max-age` directive.
190 pub fn with_max_age(mut self, duration: Duration) -> Self {
191 self.max_age = Some(duration.into());
192 self
193 }
194
195 /// Set the `max-stale` directive.
196 pub fn with_max_stale(mut self, duration: Duration) -> Self {
197 self.max_stale = Some(duration.into());
198 self
199 }
200
201 /// Set the `min-fresh` directive.
202 pub fn with_min_fresh(mut self, duration: Duration) -> Self {
203 self.min_fresh = Some(duration.into());
204 self
205 }
206
207 /// Set the `s-maxage` directive.
208 pub fn with_s_max_age(mut self, duration: Duration) -> Self {
209 self.s_max_age = Some(duration.into());
210 self
211 }
212 }
213
214 impl ::Header for CacheControl {
215 fn name() -> &'static ::HeaderName {
216 &::http::header::CACHE_CONTROL
217 }
218
219 fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, ::Error> {
220 csv::from_comma_delimited(values).map(|FromIter(cc)| cc)
221 }
222
223 fn encode<E: Extend<::HeaderValue>>(&self, values: &mut E) {
224 values.extend(::std::iter::once(util::fmt(Fmt(self))));
225 }
226 }
227
228 // Adapter to be used in Header::decode
229 struct FromIter(CacheControl);
230
231 impl FromIterator<KnownDirective> for FromIter {
232 fn from_iter<I>(iter: I) -> Self
233 where
234 I: IntoIterator<Item = KnownDirective>,
235 {
236 let mut cc = CacheControl::new();
237
238 // ignore all unknown directives
239 let iter = iter.into_iter().filter_map(|dir| match dir {
240 KnownDirective::Known(dir) => Some(dir),
241 KnownDirective::Unknown => None,
242 });
243
244 for directive in iter {
245 match directive {
246 Directive::NoCache => {
247 cc.flags.insert(Flags::NO_CACHE);
248 }
249 Directive::NoStore => {
250 cc.flags.insert(Flags::NO_STORE);
251 }
252 Directive::NoTransform => {
253 cc.flags.insert(Flags::NO_TRANSFORM);
254 }
255 Directive::OnlyIfCached => {
256 cc.flags.insert(Flags::ONLY_IF_CACHED);
257 }
258 Directive::MustRevalidate => {
259 cc.flags.insert(Flags::MUST_REVALIDATE);
260 }
261 Directive::Public => {
262 cc.flags.insert(Flags::PUBLIC);
263 }
264 Directive::Private => {
265 cc.flags.insert(Flags::PRIVATE);
266 }
267 Directive::Immutable => {
268 cc.flags.insert(Flags::IMMUTABLE);
269 }
270 Directive::ProxyRevalidate => {
271 cc.flags.insert(Flags::PROXY_REVALIDATE);
272 }
273 Directive::MaxAge(secs) => {
274 cc.max_age = Some(Duration::from_secs(secs.into()).into());
275 }
276 Directive::MaxStale(secs) => {
277 cc.max_stale = Some(Duration::from_secs(secs.into()).into());
278 }
279 Directive::MinFresh(secs) => {
280 cc.min_fresh = Some(Duration::from_secs(secs.into()).into());
281 }
282 Directive::SMaxAge(secs) => {
283 cc.s_max_age = Some(Duration::from_secs(secs.into()).into());
284 }
285 }
286 }
287
288 FromIter(cc)
289 }
290 }
291
292 struct Fmt<'a>(&'a CacheControl);
293
294 impl<'a> fmt::Display for Fmt<'a> {
295 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
296 let if_flag = |f: Flags, dir: Directive| {
297 if self.0.flags.contains(f) {
298 Some(dir)
299 } else {
300 None
301 }
302 };
303
304 let slice = &[
305 if_flag(Flags::NO_CACHE, Directive::NoCache),
306 if_flag(Flags::NO_STORE, Directive::NoStore),
307 if_flag(Flags::NO_TRANSFORM, Directive::NoTransform),
308 if_flag(Flags::ONLY_IF_CACHED, Directive::OnlyIfCached),
309 if_flag(Flags::MUST_REVALIDATE, Directive::MustRevalidate),
310 if_flag(Flags::PUBLIC, Directive::Public),
311 if_flag(Flags::PRIVATE, Directive::Private),
312 if_flag(Flags::IMMUTABLE, Directive::Immutable),
313 if_flag(Flags::PROXY_REVALIDATE, Directive::ProxyRevalidate),
314 self.0
315 .max_age
316 .as_ref()
317 .map(|s| Directive::MaxAge(s.as_u64())),
318 self.0
319 .max_stale
320 .as_ref()
321 .map(|s| Directive::MaxStale(s.as_u64())),
322 self.0
323 .min_fresh
324 .as_ref()
325 .map(|s| Directive::MinFresh(s.as_u64())),
326 self.0
327 .s_max_age
328 .as_ref()
329 .map(|s| Directive::SMaxAge(s.as_u64())),
330 ];
331
332 let iter = slice.iter().filter_map(|o| *o);
333
334 csv::fmt_comma_delimited(f, iter)
335 }
336 }
337
338 #[derive(Clone, Copy)]
339 enum KnownDirective {
340 Known(Directive),
341 Unknown,
342 }
343
344 #[derive(Clone, Copy)]
345 enum Directive {
346 NoCache,
347 NoStore,
348 NoTransform,
349 OnlyIfCached,
350
351 // request directives
352 MaxAge(u64),
353 MaxStale(u64),
354 MinFresh(u64),
355
356 // response directives
357 MustRevalidate,
358 Public,
359 Private,
360 Immutable,
361 ProxyRevalidate,
362 SMaxAge(u64),
363 }
364
365 impl fmt::Display for Directive {
366 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
367 fmt::Display::fmt(
368 match *self {
369 Directive::NoCache => "no-cache",
370 Directive::NoStore => "no-store",
371 Directive::NoTransform => "no-transform",
372 Directive::OnlyIfCached => "only-if-cached",
373
374 Directive::MaxAge(secs) => return write!(f, "max-age={}", secs),
375 Directive::MaxStale(secs) => return write!(f, "max-stale={}", secs),
376 Directive::MinFresh(secs) => return write!(f, "min-fresh={}", secs),
377
378 Directive::MustRevalidate => "must-revalidate",
379 Directive::Public => "public",
380 Directive::Private => "private",
381 Directive::Immutable => "immutable",
382 Directive::ProxyRevalidate => "proxy-revalidate",
383 Directive::SMaxAge(secs) => return write!(f, "s-maxage={}", secs),
384 },
385 f,
386 )
387 }
388 }
389
390 impl FromStr for KnownDirective {
391 type Err = ();
392 fn from_str(s: &str) -> Result<Self, Self::Err> {
393 Ok(KnownDirective::Known(match s {
394 "no-cache" => Directive::NoCache,
395 "no-store" => Directive::NoStore,
396 "no-transform" => Directive::NoTransform,
397 "only-if-cached" => Directive::OnlyIfCached,
398 "must-revalidate" => Directive::MustRevalidate,
399 "public" => Directive::Public,
400 "private" => Directive::Private,
401 "immutable" => Directive::Immutable,
402 "proxy-revalidate" => Directive::ProxyRevalidate,
403 "" => return Err(()),
404 _ => match s.find('=') {
405 Some(idx) if idx + 1 < s.len() => {
406 match (&s[..idx], (&s[idx + 1..]).trim_matches('"')) {
407 ("max-age", secs) => secs.parse().map(Directive::MaxAge).map_err(|_| ())?,
408 ("max-stale", secs) => {
409 secs.parse().map(Directive::MaxStale).map_err(|_| ())?
410 }
411 ("min-fresh", secs) => {
412 secs.parse().map(Directive::MinFresh).map_err(|_| ())?
413 }
414 ("s-maxage", secs) => {
415 secs.parse().map(Directive::SMaxAge).map_err(|_| ())?
416 }
417 _unknown => return Ok(KnownDirective::Unknown),
418 }
419 }
420 Some(_) | None => return Ok(KnownDirective::Unknown),
421 },
422 }))
423 }
424 }
425
426 #[cfg(test)]
427 mod tests {
428 use super::super::{test_decode, test_encode};
429 use super::*;
430
431 #[test]
432 fn test_parse_multiple_headers() {
433 assert_eq!(
434 test_decode::<CacheControl>(&["no-cache", "private"]).unwrap(),
435 CacheControl::new().with_no_cache().with_private(),
436 );
437 }
438
439 #[test]
440 fn test_parse_argument() {
441 assert_eq!(
442 test_decode::<CacheControl>(&["max-age=100, private"]).unwrap(),
443 CacheControl::new()
444 .with_max_age(Duration::from_secs(100))
445 .with_private(),
446 );
447 }
448
449 #[test]
450 fn test_parse_quote_form() {
451 assert_eq!(
452 test_decode::<CacheControl>(&["max-age=\"200\""]).unwrap(),
453 CacheControl::new().with_max_age(Duration::from_secs(200)),
454 );
455 }
456
457 #[test]
458 fn test_parse_extension() {
459 assert_eq!(
460 test_decode::<CacheControl>(&["foo, no-cache, bar=baz"]).unwrap(),
461 CacheControl::new().with_no_cache(),
462 "unknown extensions are ignored but shouldn't fail parsing",
463 );
464 }
465
466 #[test]
467 fn test_immutable() {
468 let cc = CacheControl::new().with_immutable();
469 let headers = test_encode(cc.clone());
470 assert_eq!(headers["cache-control"], "immutable");
471 assert_eq!(test_decode::<CacheControl>(&["immutable"]).unwrap(), cc);
472 assert!(cc.immutable());
473 }
474
475 #[test]
476 fn test_parse_bad_syntax() {
477 assert_eq!(test_decode::<CacheControl>(&["max-age=lolz"]), None);
478 }
479
480 #[test]
481 fn encode_one_flag_directive() {
482 let cc = CacheControl::new().with_no_cache();
483
484 let headers = test_encode(cc);
485 assert_eq!(headers["cache-control"], "no-cache");
486 }
487
488 #[test]
489 fn encode_one_param_directive() {
490 let cc = CacheControl::new().with_max_age(Duration::from_secs(300));
491
492 let headers = test_encode(cc);
493 assert_eq!(headers["cache-control"], "max-age=300");
494 }
495
496 #[test]
497 fn encode_two_directive() {
498 let headers = test_encode(CacheControl::new().with_no_cache().with_private());
499 assert_eq!(headers["cache-control"], "no-cache, private");
500
501 let headers = test_encode(
502 CacheControl::new()
503 .with_no_cache()
504 .with_max_age(Duration::from_secs(100)),
505 );
506 assert_eq!(headers["cache-control"], "no-cache, max-age=100");
507 }
508 }