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
use std::hash::Hash;
use std::{borrow::Borrow, collections::HashMap};
use tokio::sync::RwLock;
#[derive(Debug, Default)]
pub struct AsyncHashMap<K, V>
where
K: Eq + Hash,
V: Clone,
{
data: RwLock<HashMap<K, V>>,
}
impl<K, V> AsyncHashMap<K, V>
where
K: Eq + Hash + Clone,
V: Clone,
{
pub fn new() -> Self {
Self {
data: Default::default(),
}
}
pub async fn reserve(&self, additional: usize) {
let mut guard = self.data.write().await;
guard.reserve(additional);
}
#[allow(clippy::clippy::len_without_is_empty)]
pub async fn len(&self) -> usize {
let guard = self.data.read().await;
guard.len()
}
pub async fn is_empty(&self) -> bool {
let guard = self.data.read().await;
guard.is_empty()
}
pub async fn clear(&self) {
let mut guard = self.data.write().await;
guard.clear();
}
pub async fn get<Q: ?Sized>(&self, k: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let guard = self.data.read().await;
guard.get(k).cloned()
}
pub async fn get_all(&self) -> Vec<(K, V)> {
let guard = self.data.read().await;
let mut data = Vec::with_capacity(guard.len());
for (key, value) in guard.iter() {
data.push((key.clone(), value.clone()));
}
data
}
pub async fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let guard = self.data.read().await;
guard.contains_key(k)
}
pub async fn insert(&self, k: K, v: V) -> Option<V> {
let mut guard = self.data.write().await;
guard.insert(k, v)
}
pub async fn remove<Q: ?Sized>(&self, k: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let mut guard = self.data.write().await;
guard.remove(k)
}
}