atrium_common/store/
memory.rs1use super::Store;
2use std::collections::HashMap;
3use std::fmt::Debug;
4use std::hash::Hash;
5use std::sync::Arc;
6use thiserror::Error;
7use tokio::sync::Mutex;
8
9#[derive(Error, Debug)]
10#[error("memory store error")]
11pub struct Error;
12
13#[derive(Clone)]
14pub struct MemoryStore<K, V> {
15 store: Arc<Mutex<HashMap<K, V>>>,
16}
17
18impl<K, V> Default for MemoryStore<K, V> {
19 fn default() -> Self {
20 Self { store: Arc::new(Mutex::new(HashMap::new())) }
21 }
22}
23
24impl<K, V> Store<K, V> for MemoryStore<K, V>
25where
26 K: Debug + Eq + Hash + Send + Sync + 'static,
27 V: Debug + Clone + Send + Sync + 'static,
28{
29 type Error = Error;
30
31 async fn get(&self, key: &K) -> Result<Option<V>, Self::Error> {
32 Ok(self.store.lock().await.get(key).cloned())
33 }
34 async fn set(&self, key: K, value: V) -> Result<(), Self::Error> {
35 self.store.lock().await.insert(key, value);
36 Ok(())
37 }
38 async fn del(&self, key: &K) -> Result<(), Self::Error> {
39 self.store.lock().await.remove(key);
40 Ok(())
41 }
42 async fn clear(&self) -> Result<(), Self::Error> {
43 self.store.lock().await.clear();
44 Ok(())
45 }
46}