Skip to main content

serenade_session/
flash.rs

1//! Flash bag (Symfony `FlashBag` analogue) stored inside a [`Session`](crate::Session).
2
3use std::collections::HashMap;
4
5use crate::Session;
6
7/// Session attribute key for serialized flash messages.
8pub const FLASH_SESSION_KEY: &str = "_serenade.flashes";
9
10/// One-shot messages keyed by type (`success`, `error`, …).
11///
12/// Backed by [`Session`] attribute [`FLASH_SESSION_KEY`].
13pub struct FlashBag<'a> {
14    session: &'a mut Session,
15}
16
17impl Session {
18    /// Borrows the flash bag stored in this session.
19    pub const fn flash(&mut self) -> FlashBag<'_> {
20        FlashBag { session: self }
21    }
22}
23
24impl FlashBag<'_> {
25    /// Appends `message` under `kind`.
26    pub fn add(&mut self, kind: impl AsRef<str>, message: impl Into<String>) {
27        let kind = kind.as_ref();
28        if kind.is_empty() {
29            return;
30        }
31        let mut map = load(self.session);
32        map.entry(kind.to_owned()).or_default().push(message.into());
33        save(self.session, &map);
34    }
35
36    /// Returns messages for `kind` without removing them.
37    #[must_use]
38    pub fn peek(&self, kind: &str) -> Vec<String> {
39        load(self.session).get(kind).cloned().unwrap_or_default()
40    }
41
42    /// Returns all flashes without removing them.
43    #[must_use]
44    pub fn peek_all(&self) -> HashMap<String, Vec<String>> {
45        load(self.session)
46    }
47
48    /// Returns messages for `kind` and removes that type from the bag.
49    pub fn get(&mut self, kind: &str) -> Vec<String> {
50        let mut map = load(self.session);
51        let messages = map.remove(kind).unwrap_or_default();
52        save(self.session, &map);
53        messages
54    }
55
56    /// Returns every flash and clears the bag.
57    pub fn all(&mut self) -> HashMap<String, Vec<String>> {
58        let map = load(self.session);
59        self.session.remove(FLASH_SESSION_KEY);
60        map
61    }
62
63    /// Drops all flash messages.
64    pub fn clear(&mut self) {
65        self.session.remove(FLASH_SESSION_KEY);
66    }
67
68    /// Whether any flashes are stored.
69    #[must_use]
70    pub fn is_empty(&self) -> bool {
71        load(self.session).is_empty()
72    }
73}
74
75fn load(session: &Session) -> HashMap<String, Vec<String>> {
76    session
77        .get(FLASH_SESSION_KEY)
78        .map_or_else(HashMap::new, decode)
79}
80
81fn save(session: &mut Session, map: &HashMap<String, Vec<String>>) {
82    if map.is_empty() {
83        session.remove(FLASH_SESSION_KEY);
84        return;
85    }
86    session.set(FLASH_SESSION_KEY, encode(map));
87}
88
89/// Line format: `kind|message` with `\`, `|`, and newlines escaped.
90fn encode(map: &HashMap<String, Vec<String>>) -> String {
91    let mut out = String::new();
92    let mut entries: Vec<(&String, &Vec<String>)> = map.iter().collect();
93    entries.sort_by_key(|(kind, _)| *kind);
94    for (kind, messages) in entries {
95        for message in messages {
96            out.push_str(&escape(kind));
97            out.push('|');
98            out.push_str(&escape(message));
99            out.push('\n');
100        }
101    }
102    out
103}
104
105fn decode(raw: &str) -> HashMap<String, Vec<String>> {
106    let mut map: HashMap<String, Vec<String>> = HashMap::new();
107    for line in raw.lines() {
108        if line.is_empty() {
109            continue;
110        }
111        let Some((kind_raw, message_raw)) = split_once_unescaped(line) else {
112            continue;
113        };
114        let kind = unescape(kind_raw);
115        let message = unescape(message_raw);
116        if kind.is_empty() {
117            continue;
118        }
119        map.entry(kind).or_default().push(message);
120    }
121    map
122}
123
124fn escape(value: &str) -> String {
125    let mut out = String::with_capacity(value.len());
126    for ch in value.chars() {
127        match ch {
128            '\\' => out.push_str("\\\\"),
129            '|' => out.push_str("\\|"),
130            '\n' => out.push_str("\\n"),
131            '\r' => out.push_str("\\r"),
132            c => out.push(c),
133        }
134    }
135    out
136}
137
138fn unescape(value: &str) -> String {
139    let mut out = String::with_capacity(value.len());
140    let mut chars = value.chars();
141    while let Some(ch) = chars.next() {
142        if ch == '\\' {
143            match chars.next() {
144                Some('\\') | None => out.push('\\'),
145                Some('|') => out.push('|'),
146                Some('n') => out.push('\n'),
147                Some('r') => out.push('\r'),
148                Some(other) => {
149                    out.push('\\');
150                    out.push(other);
151                }
152            }
153        } else {
154            out.push(ch);
155        }
156    }
157    out
158}
159
160fn split_once_unescaped(line: &str) -> Option<(&str, &str)> {
161    let bytes = line.as_bytes();
162    let mut i = 0;
163    while i < bytes.len() {
164        if bytes[i] == b'\\' {
165            i = i.saturating_add(2);
166            continue;
167        }
168        if bytes[i] == b'|' {
169            return Some((&line[..i], &line[i + 1..]));
170        }
171        i += 1;
172    }
173    None
174}
175
176#[cfg(test)]
177mod tests {
178    use super::{FLASH_SESSION_KEY, decode, encode, escape, unescape};
179    use crate::Session;
180
181    #[test]
182    fn add_peek_get_consume_and_clear() {
183        let mut session = Session::new("s");
184        {
185            let mut flash = session.flash();
186            flash.add("success", "Saved");
187            flash.add("success", "Also");
188            flash.add("error", "Nope");
189            assert_eq!(flash.peek("success"), vec!["Saved", "Also"]);
190            assert!(!flash.is_empty());
191            assert_eq!(flash.get("success"), vec!["Saved", "Also"]);
192            assert_eq!(flash.peek("success"), Vec::<String>::new());
193            assert_eq!(flash.peek("error"), vec!["Nope"]);
194        }
195        assert!(session.get(FLASH_SESSION_KEY).is_some());
196        {
197            let mut flash = session.flash();
198            let all = flash.all();
199            assert_eq!(all.get("error"), Some(&vec![String::from("Nope")]));
200            assert!(flash.is_empty());
201        }
202        assert!(session.get(FLASH_SESSION_KEY).is_none());
203
204        let mut session = Session::new("s2");
205        session.flash().add("info", "hi");
206        session.flash().clear();
207        assert!(session.flash().is_empty());
208    }
209
210    #[test]
211    fn empty_kind_ignored_and_roundtrip_escapes() {
212        let mut session = Session::new("s");
213        session.flash().add("", "x");
214        assert!(session.flash().is_empty());
215
216        session.flash().add("a|b", "line\nwith|pipe\\");
217        let peeked = session.flash().peek("a|b");
218        assert_eq!(peeked, vec!["line\nwith|pipe\\"]);
219
220        let encoded = encode(&session.flash().peek_all());
221        let decoded = decode(&encoded);
222        assert_eq!(
223            decoded.get("a|b"),
224            Some(&vec![String::from("line\nwith|pipe\\")])
225        );
226
227        assert_eq!(unescape(&escape("a|b\\c\nd\r")), "a|b\\c\nd\r");
228        assert!(decode("nonsplit").is_empty());
229        assert!(decode("\n").is_empty());
230        assert!(decode("|orphan").is_empty());
231        assert_eq!(unescape("trail\\"), "trail\\");
232        assert_eq!(unescape("\\z"), "\\z");
233    }
234
235    #[test]
236    fn survives_session_attribute_reload() {
237        let mut session = Session::new("s");
238        session.flash().add("notice", "Hello");
239        let attrs = session.attributes().clone();
240        let mut reloaded = Session::existing("s", attrs);
241        assert_eq!(reloaded.flash().get("notice"), vec!["Hello"]);
242        assert!(reloaded.flash().is_empty());
243    }
244}