chaincraft_rust/
storage.rs1use crate::error::Result;
4use async_trait::async_trait;
5use std::collections::HashMap;
6
7#[async_trait]
9pub trait Storage: Send + Sync {
10 async fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;
11 async fn put(&self, key: &str, value: Vec<u8>) -> Result<()>;
12 async fn delete(&self, key: &str) -> Result<()>;
13 async fn exists(&self, key: &str) -> Result<bool>;
14 async fn clear(&self) -> Result<()>;
15 async fn initialize(&self) -> Result<()>;
16}
17
18#[derive(Debug, Default)]
20pub struct MemoryStorage {
21 data: tokio::sync::RwLock<HashMap<String, Vec<u8>>>,
22}
23
24impl MemoryStorage {
25 pub fn new() -> Self {
26 Self::default()
27 }
28}
29
30#[async_trait]
31impl Storage for MemoryStorage {
32 async fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
33 let data = self.data.read().await;
34 Ok(data.get(key).cloned())
35 }
36
37 async fn put(&self, key: &str, value: Vec<u8>) -> Result<()> {
38 let mut data = self.data.write().await;
39 data.insert(key.to_string(), value);
40 Ok(())
41 }
42
43 async fn delete(&self, key: &str) -> Result<()> {
44 let mut data = self.data.write().await;
45 data.remove(key);
46 Ok(())
47 }
48
49 async fn exists(&self, key: &str) -> Result<bool> {
50 let data = self.data.read().await;
51 Ok(data.contains_key(key))
52 }
53
54 async fn clear(&self) -> Result<()> {
55 let mut data = self.data.write().await;
56 data.clear();
57 Ok(())
58 }
59
60 async fn initialize(&self) -> Result<()> {
61 Ok(())
63 }
64}