[go: up one dir, main page]

dashmap/
set.rs

1use crate::iter_set::{Iter, OwningIter};
2#[cfg(feature = "raw-api")]
3use crate::lock::RwLock;
4use crate::setref::one::Ref;
5use crate::DashMap;
6#[cfg(feature = "raw-api")]
7use crate::HashMap;
8use cfg_if::cfg_if;
9use core::fmt;
10use core::hash::{BuildHasher, Hash};
11use core::iter::FromIterator;
12#[cfg(feature = "raw-api")]
13use crossbeam_utils::CachePadded;
14use equivalent::Equivalent;
15use std::collections::hash_map::RandomState;
16
17/// DashSet is a thin wrapper around [`DashMap`] using `()` as the value type. It uses
18/// methods and types which are more convenient to work with on a set.
19///
20/// [`DashMap`]: struct.DashMap.html
21pub struct DashSet<K, S = RandomState> {
22    pub(crate) inner: DashMap<K, (), S>,
23}
24
25impl<K: Eq + Hash + fmt::Debug, S: BuildHasher + Clone> fmt::Debug for DashSet<K, S> {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        fmt::Debug::fmt(&self.inner, f)
28    }
29}
30
31impl<K: Eq + Hash + Clone, S: Clone> Clone for DashSet<K, S> {
32    fn clone(&self) -> Self {
33        Self {
34            inner: self.inner.clone(),
35        }
36    }
37
38    fn clone_from(&mut self, source: &Self) {
39        self.inner.clone_from(&source.inner)
40    }
41}
42
43impl<K, S> Default for DashSet<K, S>
44where
45    K: Eq + Hash,
46    S: Default + BuildHasher + Clone,
47{
48    fn default() -> Self {
49        Self::with_hasher(Default::default())
50    }
51}
52
53impl<'a, K: 'a + Eq + Hash> DashSet<K, RandomState> {
54    /// Creates a new DashSet with a capacity of 0.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// use dashmap::DashSet;
60    ///
61    /// let games = DashSet::new();
62    /// games.insert("Veloren");
63    /// ```
64    pub fn new() -> Self {
65        Self::with_hasher(RandomState::default())
66    }
67
68    /// Creates a new DashMap with a specified starting capacity.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use dashmap::DashSet;
74    ///
75    /// let numbers = DashSet::with_capacity(2);
76    /// numbers.insert(2);
77    /// numbers.insert(8);
78    /// ```
79    pub fn with_capacity(capacity: usize) -> Self {
80        Self::with_capacity_and_hasher(capacity, RandomState::default())
81    }
82}
83
84impl<'a, K: 'a + Eq + Hash, S: BuildHasher + Clone> DashSet<K, S> {
85    /// Creates a new DashMap with a capacity of 0 and the provided hasher.
86    ///
87    /// # Examples
88    ///
89    /// ```
90    /// use dashmap::DashSet;
91    /// use std::collections::hash_map::RandomState;
92    ///
93    /// let s = RandomState::new();
94    /// let games = DashSet::with_hasher(s);
95    /// games.insert("Veloren");
96    /// ```
97    pub fn with_hasher(hasher: S) -> Self {
98        Self::with_capacity_and_hasher(0, hasher)
99    }
100
101    /// Creates a new DashMap with a specified starting capacity and hasher.
102    ///
103    /// # Examples
104    ///
105    /// ```
106    /// use dashmap::DashSet;
107    /// use std::collections::hash_map::RandomState;
108    ///
109    /// let s = RandomState::new();
110    /// let numbers = DashSet::with_capacity_and_hasher(2, s);
111    /// numbers.insert(2);
112    /// numbers.insert(8);
113    /// ```
114    pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
115        Self {
116            inner: DashMap::with_capacity_and_hasher(capacity, hasher),
117        }
118    }
119
120    /// Hash a given item to produce a usize.
121    /// Uses the provided or default HashBuilder.
122    pub fn hash_usize<T: Hash>(&self, item: &T) -> usize {
123        self.inner.hash_usize(item)
124    }
125
126    cfg_if! {
127        if #[cfg(feature = "raw-api")] {
128            /// Allows you to peek at the inner shards that store your data.
129            /// You should probably not use this unless you know what you are doing.
130            ///
131            /// Requires the `raw-api` feature to be enabled.
132            ///
133            /// # Examples
134            ///
135            /// ```
136            /// use dashmap::DashSet;
137            ///
138            /// let set = DashSet::<()>::new();
139            /// println!("Amount of shards: {}", set.shards().len());
140            /// ```
141            pub fn shards(&self) -> &[CachePadded<RwLock<HashMap<K, ()>>>] {
142                self.inner.shards()
143            }
144        }
145    }
146
147    cfg_if! {
148        if #[cfg(feature = "raw-api")] {
149            /// Finds which shard a certain key is stored in.
150            /// You should probably not use this unless you know what you are doing.
151            /// Note that shard selection is dependent on the default or provided HashBuilder.
152            ///
153            /// Requires the `raw-api` feature to be enabled.
154            ///
155            /// # Examples
156            ///
157            /// ```
158            /// use dashmap::DashSet;
159            ///
160            /// let set = DashSet::new();
161            /// set.insert("coca-cola");
162            /// println!("coca-cola is stored in shard: {}", set.determine_map("coca-cola"));
163            /// ```
164            pub fn determine_map<Q>(&self, key: &Q) -> usize
165            where
166            Q: Hash + Equivalent<K> + ?Sized,
167            {
168                self.inner.determine_map(key)
169            }
170        }
171    }
172
173    cfg_if! {
174        if #[cfg(feature = "raw-api")] {
175            /// Finds which shard a certain hash is stored in.
176            ///
177            /// Requires the `raw-api` feature to be enabled.
178            ///
179            /// # Examples
180            ///
181            /// ```
182            /// use dashmap::DashSet;
183            ///
184            /// let set: DashSet<i32> = DashSet::new();
185            /// let key = "key";
186            /// let hash = set.hash_usize(&key);
187            /// println!("hash is stored in shard: {}", set.determine_shard(hash));
188            /// ```
189            pub fn determine_shard(&self, hash: usize) -> usize {
190                self.inner.determine_shard(hash)
191            }
192        }
193    }
194
195    /// Inserts a key into the set. Returns true if the key was not already in the set.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use dashmap::DashSet;
201    ///
202    /// let set = DashSet::new();
203    /// set.insert("I am the key!");
204    /// ```
205    pub fn insert(&self, key: K) -> bool {
206        self.inner.insert(key, ()).is_none()
207    }
208
209    /// Removes an entry from the map, returning the key if it existed in the map.
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// use dashmap::DashSet;
215    ///
216    /// let soccer_team = DashSet::new();
217    /// soccer_team.insert("Jack");
218    /// assert_eq!(soccer_team.remove("Jack").unwrap(), "Jack");
219    /// ```
220    pub fn remove<Q>(&self, key: &Q) -> Option<K>
221    where
222        Q: Hash + Equivalent<K> + ?Sized,
223    {
224        self.inner.remove(key).map(|(k, _)| k)
225    }
226
227    /// Removes an entry from the set, returning the key
228    /// if the entry existed and the provided conditional function returned true.
229    ///
230    /// ```
231    /// use dashmap::DashSet;
232    ///
233    /// let soccer_team = DashSet::new();
234    /// soccer_team.insert("Sam");
235    /// soccer_team.remove_if("Sam", |player| player.starts_with("Ja"));
236    /// assert!(soccer_team.contains("Sam"));
237    /// ```
238    /// ```
239    /// use dashmap::DashSet;
240    ///
241    /// let soccer_team = DashSet::new();
242    /// soccer_team.insert("Sam");
243    /// soccer_team.remove_if("Jacob", |player| player.starts_with("Ja"));
244    /// assert!(!soccer_team.contains("Jacob"));
245    /// ```
246    pub fn remove_if<Q>(&self, key: &Q, f: impl FnOnce(&K) -> bool) -> Option<K>
247    where
248        Q: Hash + Equivalent<K> + ?Sized,
249    {
250        // TODO: Don't create another closure around f
251        self.inner.remove_if(key, |k, _| f(k)).map(|(k, _)| k)
252    }
253
254    /// Creates an iterator over a DashMap yielding immutable references.
255    ///
256    /// # Examples
257    ///
258    /// ```
259    /// use dashmap::DashSet;
260    ///
261    /// let words = DashSet::new();
262    /// words.insert("hello");
263    /// assert_eq!(words.iter().count(), 1);
264    /// ```
265    pub fn iter(&'a self) -> Iter<'a, K> {
266        let iter = self.inner.iter();
267
268        Iter::new(iter)
269    }
270
271    /// Get a reference to an entry in the set
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// use dashmap::DashSet;
277    ///
278    /// let youtubers = DashSet::new();
279    /// youtubers.insert("Bosnian Bill");
280    /// assert_eq!(*youtubers.get("Bosnian Bill").unwrap(), "Bosnian Bill");
281    /// ```
282    pub fn get<Q>(&'a self, key: &Q) -> Option<Ref<'a, K>>
283    where
284        Q: Hash + Equivalent<K> + ?Sized,
285    {
286        self.inner.get(key).map(Ref::new)
287    }
288
289    /// Remove excess capacity to reduce memory usage.
290    pub fn shrink_to_fit(&self) {
291        self.inner.shrink_to_fit()
292    }
293
294    /// Retain elements that whose predicates return true
295    /// and discard elements whose predicates return false.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// use dashmap::DashSet;
301    ///
302    /// let people = DashSet::new();
303    /// people.insert("Albin");
304    /// people.insert("Jones");
305    /// people.insert("Charlie");
306    /// people.retain(|name| name.contains('i'));
307    /// assert_eq!(people.len(), 2);
308    /// ```
309    pub fn retain(&self, mut f: impl FnMut(&K) -> bool) {
310        self.inner.retain(|k, _| f(k))
311    }
312
313    /// Fetches the total number of keys stored in the set.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// use dashmap::DashSet;
319    ///
320    /// let people = DashSet::new();
321    /// people.insert("Albin");
322    /// people.insert("Jones");
323    /// people.insert("Charlie");
324    /// assert_eq!(people.len(), 3);
325    /// ```
326    pub fn len(&self) -> usize {
327        self.inner.len()
328    }
329
330    /// Checks if the set is empty or not.
331    ///
332    /// # Examples
333    ///
334    /// ```
335    /// use dashmap::DashSet;
336    ///
337    /// let map = DashSet::<()>::new();
338    /// assert!(map.is_empty());
339    /// ```
340    pub fn is_empty(&self) -> bool {
341        self.inner.is_empty()
342    }
343
344    /// Removes all keys in the set.
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// use dashmap::DashSet;
350    ///
351    /// let people = DashSet::new();
352    /// people.insert("Albin");
353    /// assert!(!people.is_empty());
354    /// people.clear();
355    /// assert!(people.is_empty());
356    /// ```
357    pub fn clear(&self) {
358        self.inner.clear()
359    }
360
361    /// Returns how many keys the set can store without reallocating.
362    pub fn capacity(&self) -> usize {
363        self.inner.capacity()
364    }
365
366    /// Checks if the set contains a specific key.
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// use dashmap::DashSet;
372    ///
373    /// let people = DashSet::new();
374    /// people.insert("Dakota Cherries");
375    /// assert!(people.contains("Dakota Cherries"));
376    /// ```
377    pub fn contains<Q>(&self, key: &Q) -> bool
378    where
379        Q: Hash + Equivalent<K> + ?Sized,
380    {
381        self.inner.contains_key(key)
382    }
383}
384
385impl<K: Eq + Hash, S: BuildHasher + Clone> IntoIterator for DashSet<K, S> {
386    type Item = K;
387
388    type IntoIter = OwningIter<K>;
389
390    fn into_iter(self) -> Self::IntoIter {
391        OwningIter::new(self.inner.into_iter())
392    }
393}
394
395impl<K: Eq + Hash, S: BuildHasher + Clone> Extend<K> for DashSet<K, S> {
396    fn extend<T: IntoIterator<Item = K>>(&mut self, iter: T) {
397        let iter = iter.into_iter().map(|k| (k, ()));
398
399        self.inner.extend(iter)
400    }
401}
402
403impl<K: Eq + Hash, S: BuildHasher + Clone + Default> FromIterator<K> for DashSet<K, S> {
404    fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
405        let mut set = DashSet::default();
406
407        set.extend(iter);
408
409        set
410    }
411}
412
413#[cfg(feature = "typesize")]
414impl<K, S> typesize::TypeSize for DashSet<K, S>
415where
416    K: typesize::TypeSize + Eq + Hash,
417    S: typesize::TypeSize + Clone + BuildHasher,
418{
419    fn extra_size(&self) -> usize {
420        self.inner.extra_size()
421    }
422
423    typesize::if_typesize_details! {
424        fn get_collection_item_count(&self) -> Option<usize> {
425            Some(self.len())
426        }
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use crate::DashSet;
433
434    #[test]
435    fn test_basic() {
436        let set = DashSet::new();
437
438        set.insert(0);
439
440        assert_eq!(set.get(&0).as_deref(), Some(&0));
441    }
442
443    #[test]
444    fn test_default() {
445        let set: DashSet<u32> = DashSet::default();
446
447        set.insert(0);
448
449        assert_eq!(set.get(&0).as_deref(), Some(&0));
450    }
451
452    #[test]
453    fn test_multiple_hashes() {
454        let set = DashSet::<u32>::default();
455
456        for i in 0..100 {
457            assert!(set.insert(i));
458        }
459
460        for i in 0..100 {
461            assert!(!set.insert(i));
462        }
463
464        for i in 0..100 {
465            assert_eq!(Some(i), set.remove(&i));
466        }
467
468        for i in 0..100 {
469            assert_eq!(None, set.remove(&i));
470        }
471    }
472}