use std::collections::HashMap;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Session {
id: String,
attributes: HashMap<String, String>,
is_new: bool,
invalidated: bool,
dirty: bool,
}
impl Session {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
attributes: HashMap::new(),
is_new: true,
invalidated: false,
dirty: false,
}
}
#[must_use]
pub fn existing(id: impl Into<String>, attributes: HashMap<String, String>) -> Self {
Self {
id: id.into(),
attributes,
is_new: false,
invalidated: false,
dirty: false,
}
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
#[must_use]
pub const fn is_new(&self) -> bool {
self.is_new
}
#[must_use]
pub const fn is_invalidated(&self) -> bool {
self.invalidated
}
#[must_use]
pub const fn is_dirty(&self) -> bool {
self.dirty || self.is_new
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
self.attributes.get(key).map(String::as_str)
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.attributes.insert(key.into(), value.into());
self.dirty = true;
}
pub fn remove(&mut self, key: &str) -> Option<String> {
let previous = self.attributes.remove(key);
if previous.is_some() {
self.dirty = true;
}
previous
}
pub fn clear(&mut self) {
if !self.attributes.is_empty() {
self.attributes.clear();
self.dirty = true;
}
}
pub fn invalidate(&mut self) {
self.attributes.clear();
self.invalidated = true;
self.dirty = true;
}
#[must_use]
pub const fn attributes(&self) -> &HashMap<String, String> {
&self.attributes
}
pub(crate) fn take_for_save(&self) -> HashMap<String, String> {
self.attributes.clone()
}
}