Skip to main content

nostr_double_ratchet_runtime/
storage.rs

1use crate::Result;
2use std::collections::HashMap;
3use std::sync::{Arc, Mutex};
4
5pub trait StorageAdapter: Send + Sync {
6    fn get(&self, key: &str) -> Result<Option<String>>;
7    fn put(&self, key: &str, value: String) -> Result<()>;
8    fn del(&self, key: &str) -> Result<()>;
9    fn list(&self, prefix: &str) -> Result<Vec<String>>;
10}
11
12#[derive(Clone)]
13pub struct InMemoryStorage {
14    store: Arc<Mutex<HashMap<String, String>>>,
15}
16
17impl InMemoryStorage {
18    pub fn new() -> Self {
19        Self {
20            store: Arc::new(Mutex::new(HashMap::new())),
21        }
22    }
23}
24
25impl Default for InMemoryStorage {
26    fn default() -> Self {
27        Self::new()
28    }
29}
30
31impl StorageAdapter for InMemoryStorage {
32    fn get(&self, key: &str) -> Result<Option<String>> {
33        Ok(self.store.lock().unwrap().get(key).cloned())
34    }
35
36    fn put(&self, key: &str, value: String) -> Result<()> {
37        self.store.lock().unwrap().insert(key.to_string(), value);
38        Ok(())
39    }
40
41    fn del(&self, key: &str) -> Result<()> {
42        self.store.lock().unwrap().remove(key);
43        Ok(())
44    }
45
46    fn list(&self, prefix: &str) -> Result<Vec<String>> {
47        Ok(self
48            .store
49            .lock()
50            .unwrap()
51            .keys()
52            .filter(|k| k.starts_with(prefix))
53            .cloned()
54            .collect())
55    }
56}