cogo_http/header/common/
pragma.rs

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