whirlwind/
shard_set.rs

1//! # ShardSet
2//!
3//! A concurrent set based on a [`ShardMap`] with values of `()`.
4//!
5//! # Example
6//!
7//! ```
8//! use std::sync::Arc;
9//! use whirlwind::ShardSet;
10//!
11//! let rt = tokio::runtime::Runtime::new().unwrap();
12//! let set = Arc::new(ShardSet::new());
13//!
14//! rt.block_on(async {
15//!     for i in 0..10 {
16//!         let k = i;
17//!         if i % 2 == 0 {
18//!             set.insert(k).await;
19//!         } else {
20//!             set.remove(&(k-1)).await;
21//!         }
22//!     }
23//! });
24//! ```
25//!
26use std::hash::{BuildHasher, Hash, RandomState};
27
28use crate::shard_map::ShardMap;
29
30/// A concurrent set based on a [`ShardMap`] with values of `()`.
31///
32/// # Example
33///
34/// ```
35/// use std::sync::Arc;
36/// use whirlwind::ShardSet;
37///
38/// let rt = tokio::runtime::Runtime::new().unwrap();
39/// let set = Arc::new(ShardSet::new());
40///
41/// rt.block_on(async {
42///     for i in 0..10 {
43///         let k = i;
44///         if i % 2 == 0 {
45///             set.insert(k).await;
46///         } else {
47///             set.remove(&(k-1)).await;
48///         }
49///     }
50/// });
51/// ```
52///
53pub struct ShardSet<T, S = RandomState> {
54    inner: ShardMap<T, (), S>,
55}
56
57impl<T: Eq + Hash + 'static> ShardSet<T, RandomState> {
58    pub fn new() -> Self {
59        Self {
60            inner: ShardMap::new(),
61        }
62    }
63
64    pub fn new_with_shards(shards: usize) -> Self {
65        Self {
66            inner: ShardMap::with_shards(shards),
67        }
68    }
69}
70
71impl<T, S> ShardSet<T, S>
72where
73    T: Eq + std::hash::Hash + 'static,
74    S: BuildHasher,
75{
76    pub fn new_with_hasher(hasher: S) -> Self {
77        Self {
78            inner: ShardMap::with_hasher(hasher),
79        }
80    }
81
82    pub fn new_with_shards_and_hasher(shards: usize, hasher: S) -> Self {
83        Self {
84            inner: ShardMap::with_shards_and_hasher(shards, hasher),
85        }
86    }
87
88    /// Inserts a value into the set.
89    pub async fn insert(&self, value: T) {
90        self.inner.insert(value, ()).await;
91    }
92
93    /// Returns `true` if the set contains the specified value.
94    pub async fn contains(&self, value: &T) -> bool {
95        self.inner.contains_key(value).await
96    }
97
98    /// Removes a value from the set.
99    pub async fn remove(&self, value: &T) -> bool {
100        self.inner.remove(value).await.is_some()
101    }
102
103    /// Returns the number of elements in the set.
104    pub async fn len(&self) -> usize {
105        self.inner.len().await
106    }
107
108    /// Returns `true` if the set is empty.
109    pub async fn is_empty(&self) -> bool {
110        self.inner.len().await == 0
111    }
112
113    /// Clears the set, removing all values.
114    pub async fn clear(&self) {
115        self.inner.clear().await;
116    }
117}