Skip to content

Commit 26eae86

Browse files
committed
Add more functions for client to work with cookies. Fixes #155.
1 parent fec030a commit 26eae86

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/header/common/cookie.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,16 @@ impl Cookies {
6767
pub fn to_cookie_jar(&self, key: &[u8]) -> CookieJar<'static> {
6868
let mut jar = CookieJar::new(key);
6969
for cookie in self.0.iter() {
70-
jar.add_original((*cookie).clone());
70+
jar.add_original(cookie.clone());
7171
}
7272
jar
7373
}
74+
75+
/// Extracts all cookies from `CookieJar` and creates Cookie header.
76+
/// Useful for clients.
77+
pub fn from_cookie_jar(jar: CookieJar) -> Cookies {
78+
Cookies(jar.iter().collect())
79+
}
7480
}
7581

7682

@@ -96,4 +102,15 @@ fn test_fmt() {
96102
assert_eq!(headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n");
97103
}
98104

105+
#[test]
106+
fn cookie_jar() {
107+
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
108+
let cookies = Cookies(vec![cookie]);
109+
let jar = cookies.to_cookie_jar(&[]);
110+
let new_cookies = Cookies::from_cookie_jar(jar);
111+
112+
assert_eq!(cookies, new_cookies);
113+
}
114+
115+
99116
bench_header!(bench, Cookies, { vec![b"foo=bar; baz=quux".to_vec()] })

src/header/common/set_cookie.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,15 @@ impl SetCookie {
6363
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
6464
SetCookie(jar.delta())
6565
}
66+
67+
/// Use this on client to apply changes from SetCookie to CookieJar.
68+
/// Note that this will `panic!` if `CookieJar` is not root.
69+
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
70+
let &SetCookie(ref cookies) = self;
71+
for cookie in cookies.iter() {
72+
jar.add_original(cookie.clone())
73+
}
74+
}
6675
}
6776

6877

@@ -88,3 +97,18 @@ fn test_fmt() {
8897

8998
assert_eq!(headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
9099
}
100+
101+
#[test]
102+
fn cookie_jar() {
103+
let jar = CookieJar::new("secret".as_bytes());
104+
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
105+
jar.encrypted().add(cookie);
106+
107+
let cookies = SetCookie::from_cookie_jar(&jar);
108+
109+
let mut new_jar = CookieJar::new("secret".as_bytes());
110+
cookies.apply_to_cookie_jar(&mut new_jar);
111+
112+
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
113+
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
114+
}

0 commit comments

Comments
 (0)