menmos_std/collections/
concurrent_map.rs1use std::hash::Hash;
2use std::{borrow::Borrow, collections::HashMap};
3
4use parking_lot::RwLock;
5
6#[derive(Debug, Default)]
7pub struct ConcurrentHashMap<K, V>
8where
9 K: Eq + Hash,
10 V: Clone,
11{
12 data: RwLock<HashMap<K, V>>,
13}
14
15impl<K, V> ConcurrentHashMap<K, V>
16where
17 K: Eq + Hash + Clone,
18 V: Clone,
19{
20 pub fn new() -> Self {
21 Self {
22 data: Default::default(),
23 }
24 }
25
26 pub fn reserve(&self, additional: usize) {
27 let mut guard = self.data.write();
28 guard.reserve(additional);
29 }
30
31 pub fn len(&self) -> usize {
32 let guard = self.data.read();
33 guard.len()
34 }
35
36 pub fn is_empty(&self) -> bool {
37 let guard = self.data.read();
38 guard.is_empty()
39 }
40
41 pub fn clear(&self) {
42 let mut guard = self.data.write();
43 guard.clear();
44 }
45
46 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<V>
47 where
48 K: Borrow<Q>,
49 Q: Hash + Eq,
50 {
51 let guard = self.data.read();
52 guard.get(k).cloned()
53 }
54
55 pub fn get_all(&self) -> Vec<(K, V)> {
56 let guard = self.data.read();
57 let mut data = Vec::with_capacity(guard.len());
58
59 for (key, value) in guard.iter() {
60 data.push((key.clone(), value.clone()));
61 }
62
63 data
64 }
65
66 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
67 where
68 K: Borrow<Q>,
69 Q: Hash + Eq,
70 {
71 let guard = self.data.read();
72 guard.contains_key(k)
73 }
74
75 pub fn insert(&self, k: K, v: V) -> Option<V> {
76 let mut guard = self.data.write();
77 guard.insert(k, v)
78 }
79
80 pub fn remove<Q: ?Sized>(&self, k: &Q) -> Option<V>
81 where
82 K: Borrow<Q>,
83 Q: Hash + Eq,
84 {
85 let mut guard = self.data.write();
86 guard.remove(k)
87 }
88}