menmos_std/collections/
concurrent_set.rs

1use std::borrow::Borrow;
2use std::collections::HashSet;
3use std::hash::Hash;
4
5use parking_lot::RwLock;
6
7#[derive(Default)]
8pub struct ConcurrentSet<T>
9where
10    T: Eq + Hash,
11{
12    data: RwLock<HashSet<T>>,
13}
14
15impl<T> ConcurrentSet<T>
16where
17    T: Eq + Hash + Clone,
18{
19    pub fn new() -> Self {
20        Self {
21            data: Default::default(),
22        }
23    }
24
25    pub fn reserve(&self, additional: usize) {
26        let mut guard = self.data.write();
27        guard.reserve(additional);
28    }
29
30    pub fn len(&self) -> usize {
31        let guard = self.data.read();
32        guard.len()
33    }
34
35    pub fn is_empty(&self) -> bool {
36        let guard = self.data.read();
37        guard.is_empty()
38    }
39
40    pub fn clear(&self) {
41        let mut guard = self.data.write();
42        guard.clear();
43    }
44
45    pub fn insert(&self, value: T) -> bool {
46        let mut guard = self.data.write();
47        guard.insert(value)
48    }
49
50    pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
51    where
52        T: Borrow<Q>,
53        Q: Hash + Eq,
54    {
55        let guard = self.data.read();
56        guard.contains(value)
57    }
58
59    pub fn remove<Q: ?Sized>(&self, value: &Q) -> bool
60    where
61        T: Borrow<Q>,
62        Q: Hash + Eq,
63    {
64        let mut guard = self.data.write();
65        guard.remove(value)
66    }
67}