use super::{DialogueKey, Storage, StorageKeys};
use futures::future::BoxFuture;
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
sync::Arc,
};
use thiserror::Error;
use tokio::sync::Mutex;
#[derive(Debug, Error)]
pub enum InMemStorageError {
#[error("row not found")]
DialogueNotFound,
}
#[derive(Debug)]
pub struct InMemStorage<D> {
map: Mutex<HashMap<DialogueKey, D>>,
}
impl<S> InMemStorage<S> {
#[must_use]
pub fn new() -> Arc<Self> {
Arc::new(Self { map: Mutex::new(HashMap::new()) })
}
}
impl<D> Storage<D> for InMemStorage<D>
where
D: Clone,
D: Send + 'static,
{
type Error = InMemStorageError;
fn remove_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<(), Self::Error>>
where
D: Send + 'static,
{
Box::pin(async move {
self.map
.lock()
.await
.remove(&key)
.map_or(Err(InMemStorageError::DialogueNotFound), |_| Ok(()))
})
}
fn update_dialogue(
self: Arc<Self>,
key: DialogueKey,
dialogue: D,
) -> BoxFuture<'static, Result<(), Self::Error>>
where
D: Send + 'static,
{
Box::pin(async move {
self.map.lock().await.insert(key, dialogue);
Ok(())
})
}
fn get_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
Box::pin(async move { Ok(self.map.lock().await.get(&key).cloned()) })
}
fn get_or_insert_dialogue(
self: Arc<Self>,
key: DialogueKey,
default: fn() -> D,
_reset_incompatible: bool,
) -> BoxFuture<'static, Result<D, Self::Error>> {
Box::pin(
async move { Ok(self.map.lock().await.entry(key).or_insert_with(default).clone()) },
)
}
}
impl<D: Send + 'static> StorageKeys for InMemStorage<D> {
type Error = Infallible;
fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
Box::pin(async move { Ok(self.map.lock().await.keys().cloned().collect()) })
}
}