storage_trait/
dashmap_storage.rs

1use std::hash::Hash;
2use std::marker::PhantomData;
3
4use dashmap::DashMap;
5use std::time::Duration;
6
7use crate::storage::{Err, Storage};
8
9pub struct DashMapStorage<K, V> {
10    dash: DashMap<K, V>,
11}
12
13impl<K: Hash + Eq, V: Clone> Storage<K, V> for DashMapStorage<K, V> {
14    fn get(&self, key: K) -> Result<Option<V>, Err> {
15        Ok(self.dash.get(&key).map(|v| (*v.value()).clone()))
16    }
17
18    fn set(&self, key: K, value: V) -> Result<(), Err> {
19        Ok(self.dash.insert(key, value).map_or((), |_| ()))
20    }
21
22    fn set_ex(&self, _key: K, _value: V, _expire: Duration) -> Result<(), Err> {
23        unimplemented!()
24    }
25
26    fn del(&self, key: K) -> Result<Option<K>, Err> {
27        Ok(self.dash.remove(&key).map(|p| p.0))
28    }
29
30    fn contains(&self, key: K) -> Result<bool, Err> {
31        Ok(self.dash.contains_key(&key))
32    }
33}
34
35pub struct DashMapStorageBuilder<K, V> {
36    capacity: Option<usize>,
37    _marker: PhantomData<(K, V)>,
38}
39
40#[allow(unused)]
41impl<K: Hash + Eq, V: Clone> DashMapStorageBuilder<K, V> {
42    pub fn new() -> Self {
43        DashMapStorageBuilder::default()
44    }
45
46    pub fn capacity(mut self, capacity: usize) -> Self {
47        self.capacity = Some(capacity);
48        self
49    }
50
51    pub fn build(self) -> DashMapStorage<K, V> {
52        DashMapStorage {
53            dash: self.capacity.map_or(DashMap::<K, V>::new(), |c| {
54                DashMap::<K, V>::with_capacity(c)
55            }),
56        }
57    }
58}
59
60impl<K, V> Default for DashMapStorageBuilder<K, V> {
61    fn default() -> Self {
62        Self {
63            capacity: None,
64            _marker: PhantomData,
65        }
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn test_contains() {
75        let storage = DashMapStorageBuilder::new().build();
76
77        let _ = storage
78            .set("name".to_string(), "Ferris".to_string())
79            .unwrap();
80        let _ = storage.contains("name".into()).unwrap();
81    }
82
83    #[test]
84    fn test_get() {
85        let storage = DashMapStorageBuilder::new().capacity(10).build();
86
87        let (key, value) = ("name", false.to_string());
88        let _ = storage.set(key, value.clone());
89        let resp = storage.get(key).unwrap();
90        assert_eq!(resp, Some(value.clone()));
91
92        let _ = storage.del(key).unwrap();
93        let resp = storage.get(key).unwrap();
94        assert_eq!(resp, None);
95    }
96}