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
use std::collections::HashMap;
use std::collections::BTreeMap;
use std::hash::Hash;
use async_rwlock::RwLock;
use async_rwlock::RwLockReadGuard;
use async_rwlock::RwLockWriteGuard;
pub struct SimpleConcurrentHashMap<K, V>(RwLock<HashMap<K, V>>);
impl<K, V> SimpleConcurrentHashMap<K, V>
where
K: Eq + Hash,
{
pub fn new() -> Self {
SimpleConcurrentHashMap(RwLock::new(HashMap::new()))
}
pub async fn insert(&self, key: K, value: V) -> Option<V> {
let mut lock = self.write().await;
lock.insert(key, value)
}
pub async fn read<'a>(&'_ self) -> RwLockReadGuard<'_, HashMap<K, V>> {
self.0.read().await
}
pub async fn write<'a>(&'_ self) -> RwLockWriteGuard<'_, HashMap<K, V>> {
self.0.write().await
}
pub async fn contains_key(&self, key: &K) -> bool {
self.read().await.contains_key(key)
}
}
impl<K, V> Default for SimpleConcurrentHashMap<K, V>
where
K: Eq + Hash,
{
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct SimpleConcurrentBTreeMap<K, V>(RwLock<BTreeMap<K, V>>);
impl<K, V> Default for SimpleConcurrentBTreeMap<K, V>
where
K: Ord,
{
fn default() -> Self {
SimpleConcurrentBTreeMap(RwLock::new(BTreeMap::new()))
}
}
impl<K, V> SimpleConcurrentBTreeMap<K, V>
where
K: Ord,
{
pub fn new() -> Self {
Self(RwLock::new(BTreeMap::new()))
}
pub fn new_with_map(map: BTreeMap<K, V>) -> Self {
Self(RwLock::new(map))
}
pub async fn read<'a>(&'_ self) -> RwLockReadGuard<'_, BTreeMap<K, V>> {
self.0.read().await
}
pub async fn write<'a>(&'_ self) -> RwLockWriteGuard<'_, BTreeMap<K, V>> {
self.0.write().await
}
pub fn try_write(&self) -> Option<RwLockWriteGuard<BTreeMap<K, V>>> {
self.0.try_write()
}
pub async fn insert(&self, key: K, value: V) -> Option<V> {
let mut lock = self.write().await;
lock.insert(key, value)
}
pub async fn contains_key(&self, key: &K) -> bool {
self.read().await.contains_key(key)
}
}