use header::{Header, HeaderFormat, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<CookiePair>);
__hyper__deref!(SetCookie => Vec<CookiePair>);
impl Header for SetCookie {
fn header_name() -> &'static str {
"Set-Cookie"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if !set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
}
impl HeaderFormat for SetCookie {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i != 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]);
let mut c1 = CookiePair::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
jar.add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.find("foo"), new_jar.find("foo"));
assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>());
}