1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use async_trait::async_trait;
use dashmap::DashMap;

use crate::error::Result;
use crate::storage::KvStorageInterface;

#[derive(Debug, Default)]
pub struct MemStorage<V>
where V: Clone
{
    table: DashMap<String, V>,
}

impl<V> MemStorage<V>
where V: Clone
{
    pub fn new() -> Self {
        Self {
            table: DashMap::default(),
        }
    }
}

#[cfg_attr(feature = "wasm", async_trait(?Send))]
#[cfg_attr(not(feature = "wasm"), async_trait)]
impl<V> KvStorageInterface<V> for MemStorage<V>
where V: Clone + Send + Sync
{
    async fn get(&self, key: &str) -> Result<Option<V>> {
        Ok(self.table.get(&key.to_string()).map(|v| v.value().clone()))
    }

    async fn put(&self, key: &str, value: &V) -> Result<()> {
        self.table.insert(key.to_string(), value.clone());
        Ok(())
    }

    async fn get_all(&self) -> Result<Vec<(String, V)>> {
        Ok(self.table.clone().into_iter().collect())
    }

    async fn remove(&self, key: &str) -> Result<()> {
        match self.get(key).await? {
            Some(_) => self.table.remove(key),
            None => None,
        };
        Ok(())
    }

    async fn clear(&self) -> Result<()> {
        self.table.clear();
        Ok(())
    }

    async fn count(&self) -> Result<u32> {
        Ok(self.table.len() as u32)
    }
}

#[cfg(not(feature = "wasm"))]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::ecc::SecretKey;

    #[tokio::test]
    async fn memstorage_basic_interface_should_work() {
        let store = MemStorage::new();
        let addr = SecretKey::random().address().to_string();

        assert_eq!(store.get(&addr).await.unwrap(), None);

        store.put(&addr, &"value 1".to_string()).await.unwrap();
        assert_eq!(store.get(&addr).await.unwrap(), Some("value 1".into()));

        store.put(&addr, &"value 2".to_string()).await.unwrap();
        assert_eq!(store.get(&addr).await.unwrap(), Some("value 2".into()));
    }
}