cogo_http/header/common/
cookie.rs

1use crate::header::{Header, HeaderFormat};
2use std::fmt::{self, Display};
3use std::str::from_utf8;
4
5/// `Cookie` header, defined in [RFC6265](http://tools.ietf.org/html/rfc6265#section-5.4)
6///
7/// If the user agent does attach a Cookie header field to an HTTP
8/// request, the user agent must send the cookie-string
9/// as the value of the header field.
10///
11/// When the user agent generates an HTTP request, the user agent MUST NOT
12/// attach more than one Cookie header field.
13///
14/// # Example values
15/// * `SID=31d4d96e407aad42`
16/// * `SID=31d4d96e407aad42; lang=en-US`
17///
18/// # Example
19/// ```
20/// use cogo_http::header::{Headers, Cookie};
21///
22/// let mut headers = Headers::new();
23///
24/// headers.set(
25///    Cookie(vec![
26///        String::from("foo=bar")
27///    ])
28/// );
29/// ```
30#[derive(Clone, PartialEq, Debug)]
31pub struct Cookie(pub Vec<String>);
32
33__hyper__deref!(Cookie => Vec<String>);
34
35impl Header for Cookie {
36    fn header_name() -> &'static str {
37        "Cookie"
38    }
39
40    fn parse_header(raw: &[Vec<u8>]) -> crate::Result<Cookie> {
41        let mut cookies = Vec::with_capacity(raw.len());
42        for cookies_raw in raw.iter() {
43            let cookies_str = r#try!(from_utf8(&cookies_raw[..]));
44            for cookie_str in cookies_str.split(';') {
45                cookies.push(cookie_str.trim().to_owned())
46            }
47        }
48
49        if !cookies.is_empty() {
50            Ok(Cookie(cookies))
51        } else {
52            Err(crate::Error::Header)
53        }
54    }
55}
56
57impl HeaderFormat for Cookie {
58    fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        let cookies = &self.0;
60        for (i, cookie) in cookies.iter().enumerate() {
61            if i != 0 {
62                r#try!(f.write_str("; "));
63            }
64            r#try!(Display::fmt(&cookie, f));
65        }
66        Ok(())
67    }
68}
69
70bench_header!(bench, Cookie, { vec![b"foo=bar; baz=quux".to_vec()] });