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
use std::collections::HashMap;
use std::collections::BTreeMap;
use std::hash::Hash;
use std::sync::RwLock;
use std::sync::RwLockReadGuard;
use std::sync::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 fn insert(&self, key: K, value: V) -> Option<V> {
let mut lock = self.write();
lock.insert(key, value)
}
pub fn read(&self) -> RwLockReadGuard<HashMap<K, V>> {
self.0.read().unwrap()
}
pub fn write(&self) -> RwLockWriteGuard<HashMap<K, V>> {
self.0.write().unwrap()
}
pub fn contains_key(&self, key: &K) -> bool {
self.read().contains_key(key)
}
}
#[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 {
SimpleConcurrentBTreeMap(RwLock::new(BTreeMap::new()))
}
pub fn read(&self) -> RwLockReadGuard<BTreeMap<K, V>> {
self.0.read().unwrap()
}
pub fn write(&self) -> RwLockWriteGuard<BTreeMap<K, V>> {
self.0.write().unwrap()
}
pub fn insert(&self, key: K, value: V) -> Option<V> {
let mut lock = self.write();
lock.insert(key, value)
}
pub fn contains_key(&self, key: &K) -> bool {
self.read().contains_key(key)
}
}