Skip to content

Commit ad22d79

Browse files
committed
Merge pull request #166 from s-panferov/feature/client-cookies
Add more functions for client to work with cookies.
2 parents 0ccd1ac + 6a8864c commit ad22d79

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/header/common/cookie.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,17 @@ impl Cookies {
6666
/// to manipulate cookies and create a corresponding `SetCookie` header afterwards.
6767
pub fn to_cookie_jar(&self, key: &[u8]) -> CookieJar<'static> {
6868
let mut jar = CookieJar::new(key);
69-
for cookie in self.0.iter() {
70-
jar.add_original((*cookie).clone());
69+
for cookie in self.iter() {
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: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ 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+
for cookie in self.iter() {
71+
jar.add_original(cookie.clone())
72+
}
73+
}
6674
}
6775

6876

@@ -88,3 +96,18 @@ fn test_fmt() {
8896

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

0 commit comments

Comments
 (0)