mco_http/header/common/
pragma.rs

1use std::fmt;
2
3use crate::header::{Header, HeaderFormat, parsing};
4
5/// The `Pragma` header defined by HTTP/1.0.
6///
7/// > The "Pragma" header field allows backwards compatibility with
8/// > HTTP/1.0 caches, so that clients can specify a "no-cache" request
9/// > that they will understand (as Cache-Control was not defined until
10/// > HTTP/1.1).  When the Cache-Control header field is also present and
11/// > understood in a request, Pragma is ignored.
12
13/// > In HTTP/1.0, Pragma was defined as an extensible field for
14/// > implementation-specified directives for recipients.  This
15/// > specification deprecates such extensions to improve interoperability.
16///
17/// Spec: https://tools.ietf.org/html/rfc7234#section-5.4
18///
19/// # Examples
20/// ```
21/// use mco_http::header::{Headers, Pragma};
22///
23/// let mut headers = Headers::new();
24/// headers.set(Pragma::NoCache);
25/// ```
26/// ```
27/// use mco_http::header::{Headers, Pragma};
28///
29/// let mut headers = Headers::new();
30/// headers.set(Pragma::Ext("foobar".to_owned()));
31/// ```
32#[derive(Clone, PartialEq, Debug)]
33pub enum Pragma {
34    /// Corresponds to the `no-cache` value.
35    NoCache,
36    /// Every value other than `no-cache`.
37    Ext(String),
38}
39
40impl Header for Pragma {
41    fn header_name() -> &'static str {
42        "Pragma"
43    }
44
45    fn parse_header(raw: &[Vec<u8>]) -> crate::Result<Pragma> {
46        parsing::from_one_raw_str(raw).and_then(|s: String| {
47            let slice = &s.to_ascii_lowercase()[..];
48            match slice {
49                "no-cache" => Ok(Pragma::NoCache),
50                _ => Ok(Pragma::Ext(s)),
51            }
52        })
53    }
54}
55
56impl HeaderFormat for Pragma {
57    fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        fmt::Display::fmt(self, f)
59    }
60}
61
62impl fmt::Display for Pragma {
63    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64        f.write_str(match *self {
65            Pragma::NoCache => "no-cache",
66            Pragma::Ext(ref string) => &string[..],
67        })
68    }
69}
70
71#[test]
72fn test_parse_header() {
73    let a: Pragma = Header::parse_header([b"no-cache".to_vec()].as_ref()).unwrap();
74    let b = Pragma::NoCache;
75    assert_eq!(a, b);
76    let c: Pragma = Header::parse_header([b"FoObar".to_vec()].as_ref()).unwrap();
77    let d = Pragma::Ext("FoObar".to_owned());
78    assert_eq!(c, d);
79    let e: crate::Result<Pragma> = Header::parse_header([b"".to_vec()].as_ref());
80    assert_eq!(e.ok(), None);
81}