Merge pull request #166 from s-panferov/feature/client-cookies

Add more functions for client to work with cookies.
This commit is contained in:
Sean McArthur
2014-12-02 13:43:30 -08:00
2 changed files with 42 additions and 2 deletions

View File

@@ -66,11 +66,17 @@ impl Cookies {
/// to manipulate cookies and create a corresponding `SetCookie` header afterwards. /// to manipulate cookies and create a corresponding `SetCookie` header afterwards.
pub fn to_cookie_jar(&self, key: &[u8]) -> CookieJar<'static> { pub fn to_cookie_jar(&self, key: &[u8]) -> CookieJar<'static> {
let mut jar = CookieJar::new(key); let mut jar = CookieJar::new(key);
for cookie in self.0.iter() { for cookie in self.iter() {
jar.add_original((*cookie).clone()); jar.add_original(cookie.clone());
} }
jar jar
} }
/// Extracts all cookies from `CookieJar` and creates Cookie header.
/// Useful for clients.
pub fn from_cookie_jar(jar: &CookieJar) -> Cookies {
Cookies(jar.iter().collect())
}
} }
@@ -96,4 +102,15 @@ fn test_fmt() {
assert_eq!(headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n"); assert_eq!(headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n");
} }
#[test]
fn cookie_jar() {
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
let cookies = Cookies(vec![cookie]);
let jar = cookies.to_cookie_jar(&[]);
let new_cookies = Cookies::from_cookie_jar(&jar);
assert_eq!(cookies, new_cookies);
}
bench_header!(bench, Cookies, { vec![b"foo=bar; baz=quux".to_vec()] }) bench_header!(bench, Cookies, { vec![b"foo=bar; baz=quux".to_vec()] })

View File

@@ -63,6 +63,14 @@ impl SetCookie {
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie { pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta()) SetCookie(jar.delta())
} }
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
} }
@@ -88,3 +96,18 @@ fn test_fmt() {
assert_eq!(headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n"); assert_eq!(headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
} }
#[test]
fn cookie_jar() {
let jar = CookieJar::new("secret".as_bytes());
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
jar.encrypted().add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new("secret".as_bytes());
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
}