use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub type StorageChange = Arc<dyn Fn(&str, Option<&str>) + Send + Sync>;
pub struct StorageSubscription {
end: Option<Box<dyn FnOnce() + Send>>,
}
impl StorageSubscription {
pub fn new(end: impl FnOnce() + Send + 'static) -> StorageSubscription {
StorageSubscription {
end: Some(Box::new(end)),
}
}
}
impl Drop for StorageSubscription {
fn drop(&mut self) {
if let Some(end) = self.end.take() {
end();
}
}
}
pub trait SessionStorage: Send + Sync + 'static {
fn get(&self, key: &str) -> Option<String>;
fn set(&self, key: &str, value: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
fn delete(&self, key: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
fn update(
&self,
key: &str,
change: &mut dyn FnMut(Option<&str>) -> Option<String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
fn subscribe(&self, on_change: StorageChange) -> Option<StorageSubscription>;
}
#[derive(Default)]
pub struct InMemorySessionStorage {
stored: Mutex<HashMap<String, String>>,
}
impl InMemorySessionStorage {
pub fn new() -> InMemorySessionStorage {
InMemorySessionStorage::default()
}
fn stored(&self) -> std::sync::MutexGuard<'_, HashMap<String, String>> {
self.stored
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
}
impl SessionStorage for InMemorySessionStorage {
fn get(&self, key: &str) -> Option<String> {
self.stored().get(key).cloned()
}
fn set(&self, key: &str, value: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.stored().insert(key.to_owned(), value.to_owned());
Ok(())
}
fn delete(&self, key: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.stored().remove(key);
Ok(())
}
fn update(
&self,
key: &str,
change: &mut dyn FnMut(Option<&str>) -> Option<String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut stored = self.stored();
match change(stored.get(key).map(String::as_str)) {
Some(next) => stored.insert(key.to_owned(), next),
None => stored.remove(key),
};
Ok(())
}
fn subscribe(&self, _: StorageChange) -> Option<StorageSubscription> {
None
}
}