hyperx/header/common/
pragma.rs

1use std::fmt;
2
3use header::{Header, RawLike, 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/// > In HTTP/1.0, Pragma was defined as an extensible field for
13/// > implementation-specified directives for recipients.  This
14/// > specification deprecates such extensions to improve interoperability.
15///
16/// Spec: [https://tools.ietf.org/html/rfc7234#section-5.4][url]
17///
18/// [url]: https://tools.ietf.org/html/rfc7234#section-5.4
19///
20/// # Examples
21///
22/// ```
23/// # extern crate http;
24/// use hyperx::header::{Pragma, TypedHeaders};
25///
26/// let mut headers = http::HeaderMap::new();
27/// headers.encode(&Pragma::NoCache);
28/// ```
29///
30/// ```
31/// # extern crate http;
32/// use hyperx::header::{Pragma, TypedHeaders};
33///
34/// let mut headers = http::HeaderMap::new();
35/// headers.encode(&Pragma::Ext("foobar".to_owned()));
36/// ```
37#[derive(Clone, PartialEq, Debug)]
38pub enum Pragma {
39    /// Corresponds to the `no-cache` value.
40    NoCache,
41    /// Every value other than `no-cache`.
42    Ext(String),
43}
44
45impl Header for Pragma {
46    fn header_name() -> &'static str {
47        static NAME: &'static str = "Pragma";
48        NAME
49    }
50
51    fn parse_header<'a, T>(raw: &'a T) -> ::Result<Pragma>
52    where T: RawLike<'a>
53    {
54        parsing::from_one_raw_str(raw).and_then(|s: String| {
55            let slice = &s.to_ascii_lowercase()[..];
56            match slice {
57                "no-cache" => Ok(Pragma::NoCache),
58                _ => Ok(Pragma::Ext(s)),
59            }
60        })
61    }
62
63    fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
64        f.fmt_line(self)
65    }
66}
67
68impl fmt::Display for Pragma {
69    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70        f.write_str(match *self {
71            Pragma::NoCache => "no-cache",
72            Pragma::Ext(ref string) => &string[..],
73        })
74    }
75}
76
77#[test]
78fn test_parse_header() {
79    use header::{Header, Raw};
80
81    let r: Raw = "no-cache".into();
82    let a: Pragma = Header::parse_header(&r).unwrap();
83    let b = Pragma::NoCache;
84    assert_eq!(a, b);
85
86    let r: Raw = "FoObar".into();
87    let c: Pragma = Header::parse_header(&r).unwrap();
88    let d = Pragma::Ext("FoObar".to_owned());
89    assert_eq!(c, d);
90
91    let r: Raw = "".into();
92    let e: ::Result<Pragma> = Header::parse_header(&r);
93    assert_eq!(e.ok(), None);
94}
95
96standard_header!(Pragma, PRAGMA);