serenade_session/
session.rs1use std::collections::HashMap;
4
5#[derive(Clone, Debug, Default, Eq, PartialEq)]
7pub struct Session {
8 id: String,
9 attributes: HashMap<String, String>,
10 is_new: bool,
11 invalidated: bool,
12 dirty: bool,
13}
14
15impl Session {
16 #[must_use]
18 pub fn new(id: impl Into<String>) -> Self {
19 Self {
20 id: id.into(),
21 attributes: HashMap::new(),
22 is_new: true,
23 invalidated: false,
24 dirty: false,
25 }
26 }
27
28 #[must_use]
30 pub fn existing(id: impl Into<String>, attributes: HashMap<String, String>) -> Self {
31 Self {
32 id: id.into(),
33 attributes,
34 is_new: false,
35 invalidated: false,
36 dirty: false,
37 }
38 }
39
40 #[must_use]
42 pub fn id(&self) -> &str {
43 &self.id
44 }
45
46 #[must_use]
48 pub const fn is_new(&self) -> bool {
49 self.is_new
50 }
51
52 #[must_use]
54 pub const fn is_invalidated(&self) -> bool {
55 self.invalidated
56 }
57
58 #[must_use]
60 pub const fn is_dirty(&self) -> bool {
61 self.dirty || self.is_new
62 }
63
64 #[must_use]
66 pub fn get(&self, key: &str) -> Option<&str> {
67 self.attributes.get(key).map(String::as_str)
68 }
69
70 pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
72 self.attributes.insert(key.into(), value.into());
73 self.dirty = true;
74 }
75
76 pub fn remove(&mut self, key: &str) -> Option<String> {
78 let previous = self.attributes.remove(key);
79 if previous.is_some() {
80 self.dirty = true;
81 }
82 previous
83 }
84
85 pub fn clear(&mut self) {
87 if !self.attributes.is_empty() {
88 self.attributes.clear();
89 self.dirty = true;
90 }
91 }
92
93 pub fn invalidate(&mut self) {
95 self.attributes.clear();
96 self.invalidated = true;
97 self.dirty = true;
98 }
99
100 #[must_use]
102 pub const fn attributes(&self) -> &HashMap<String, String> {
103 &self.attributes
104 }
105
106 pub(crate) fn take_for_save(&self) -> HashMap<String, String> {
107 self.attributes.clone()
108 }
109}