File tree Expand file tree Collapse file tree 2 files changed +42
-2
lines changed Expand file tree Collapse file tree 2 files changed +42
-2
lines changed Original file line number Diff line number Diff line change @@ -66,11 +66,17 @@ impl Cookies {
66
66
/// to manipulate cookies and create a corresponding `SetCookie` header afterwards.
67
67
pub fn to_cookie_jar ( & self , key : & [ u8 ] ) -> CookieJar < ' static > {
68
68
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 ( ) ) ;
71
71
}
72
72
jar
73
73
}
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
+ }
74
80
}
75
81
76
82
@@ -96,4 +102,15 @@ fn test_fmt() {
96
102
assert_eq ! ( headers. to_string( ) [ ] , "Cookie: foo=bar; baz=quux\r \n " ) ;
97
103
}
98
104
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
+
99
116
bench_header ! ( bench, Cookies , { vec![ b"foo=bar; baz=quux" . to_vec( ) ] } )
Original file line number Diff line number Diff line change @@ -63,6 +63,14 @@ impl SetCookie {
63
63
pub fn from_cookie_jar ( jar : & CookieJar ) -> SetCookie {
64
64
SetCookie ( jar. delta ( ) )
65
65
}
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
+ }
66
74
}
67
75
68
76
@@ -88,3 +96,18 @@ fn test_fmt() {
88
96
89
97
assert_eq ! ( headers. to_string( ) [ ] , "Set-Cookie: foo=bar; HttpOnly; Path=/p\r \n Set-Cookie: baz=quux; Path=/\r \n " ) ;
90
98
}
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
+ }
You can’t perform that action at this time.
0 commit comments