Skip to main content

topcoat_cookie/
map.rs

1use cookie::Cookie;
2
3use crate::Cookies;
4
5/// A [`Cookies`] adapter that applies a transform to every cookie written
6/// through it.
7///
8/// Create it with [`Cookies::map`]. The closure changes the cookie before it
9/// reaches the wrapped jar.
10///
11/// The closure runs for both `add` and `remove`, so removals receive the same
12/// path and domain attributes as writes. Reads pass through unchanged.
13#[derive(Debug, Clone, Copy)]
14pub struct Map<J, F> {
15    inner: J,
16    f: F,
17}
18
19impl<J, F> Map<J, F> {
20    pub(crate) fn new(inner: J, f: F) -> Self {
21        Self { inner, f }
22    }
23}
24
25impl<J, F> Cookies for Map<J, F>
26where
27    J: Cookies,
28    F: Fn(&mut Cookie<'static>),
29{
30    fn get(&self, name: &str) -> Option<Cookie<'static>> {
31        self.inner.get(name)
32    }
33
34    fn add<C: Into<Cookie<'static>>>(&self, cookie: C) {
35        let mut cookie = cookie.into();
36        (self.f)(&mut cookie);
37        self.inner.add(cookie);
38    }
39
40    fn remove<C: Into<Cookie<'static>>>(&self, cookie: C) {
41        let mut cookie = cookie.into();
42        (self.f)(&mut cookie);
43        self.inner.remove(cookie);
44    }
45}