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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use std::sync::Arc;
use actix_storage::{dev::Store, Result};
use dashmap::DashMap;
type ScopeMap = DashMap<Arc<[u8]>, Arc<[u8]>>;
type InternalMap = DashMap<Arc<[u8]>, ScopeMap>;
#[derive(Debug, Default)]
pub struct DashMapStore {
map: InternalMap,
}
impl DashMapStore {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
map: DashMap::with_capacity(capacity),
}
}
pub fn from_dashmap(map: InternalMap) -> Self {
Self { map }
}
}
#[async_trait::async_trait]
impl Store for DashMapStore {
async fn set(&self, scope: Arc<[u8]>, key: Arc<[u8]>, value: Arc<[u8]>) -> Result<()> {
self.map.entry(scope).or_default().insert(key, value);
Ok(())
}
async fn get(&self, scope: Arc<[u8]>, key: Arc<[u8]>) -> Result<Option<Arc<[u8]>>> {
let value = if let Some(scope_map) = self.map.get(&scope) {
scope_map.get(&key).map(|v| v.clone())
} else {
None
};
Ok(value)
}
async fn delete(&self, scope: Arc<[u8]>, key: Arc<[u8]>) -> Result<()> {
self.map
.get_mut(&scope)
.and_then(|scope_map| scope_map.remove(&key));
Ok(())
}
async fn contains_key(&self, scope: Arc<[u8]>, key: Arc<[u8]>) -> Result<bool> {
Ok(self
.map
.get(&scope)
.map(|scope_map| scope_map.contains_key(&key))
.unwrap_or(false))
}
}
#[cfg(test)]
mod test {
use super::*;
use actix_storage::tests::*;
#[test]
fn test_dashmap_basic_store() {
test_store(Box::pin(async { DashMapStore::default() }));
}
#[test]
fn test_dashmap_basic_formats() {
impl Clone for DashMapStore {
fn clone(&self) -> Self {
Self {
map: self.map.clone(),
}
}
}
test_all_formats(Box::pin(async { DashMapStore::default() }));
}
}