Skip to main content

dashtable/
lib.rs

1// This code is forked from https://docs.rs/dashmap/7.0.0-rc2/src/dashmap/lib.rs.html,
2// available under the MIT license.
3
4//! A fork of the [`dashmap`](https://docs.rs/dashmap) crate to expose a raw hash table API.
5
6#![forbid(
7    missing_docs,
8    unsafe_op_in_unsafe_fn,
9    clippy::missing_safety_doc,
10    clippy::multiple_unsafe_ops_per_block,
11    clippy::undocumented_unsafe_blocks
12)]
13#![cfg_attr(docsrs, feature(doc_cfg))]
14
15mod lock;
16
17use crossbeam_utils::CachePadded;
18#[cfg(feature = "get-size2")]
19use get_size2::{GetSize, GetSizeTracker};
20use hashbrown::{HashTable, hash_table};
21use lock::{RwLock, RwLockReadGuardDetached, RwLockWriteGuardDetached};
22use std::ops::Deref;
23use std::sync::LazyLock;
24
25fn default_shard_shift() -> u32 {
26    static DEFAULT_SHARD_SHIFT: LazyLock<u32> =
27        LazyLock::new(|| shard_shift(std::thread::available_parallelism().map_or(1, usize::from)));
28    *DEFAULT_SHARD_SHIFT
29}
30
31fn shard_shift(parallelism: usize) -> u32 {
32    if parallelism == 0 {
33        1
34    } else {
35        ((parallelism.saturating_mul(4) - 1).ilog2() + 1).min(usize::BITS - 1)
36    }
37}
38
39fn capacity_per_shard(capacity: usize, shard_shift: u32) -> usize {
40    let shard_amount = 1 << shard_shift;
41    capacity.div_ceil(shard_amount)
42}
43
44/// A concurrent raw hash table with items of type `T`.
45pub struct DashTable<T> {
46    shift: u32,
47    shards: Box<[CachePadded<RwLock<HashTable<T>>>]>,
48}
49
50impl<T> Default for DashTable<T> {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56#[cfg(feature = "get-size2")]
57impl<T: GetSize> GetSize for DashTable<T> {
58    fn get_heap_size_with_tracker<Tr: GetSizeTracker>(&self, tracker: Tr) -> (usize, Tr) {
59        let (size, tracker) = self
60            .shards
61            .iter()
62            .fold((0, tracker), |(size, tracker), table| {
63                let (table_size, tracker) =
64                    HashTable::get_size_with_tracker(table.read().deref(), tracker);
65                (size + table_size, tracker)
66            });
67
68        let allocation_size =
69            self.shards.len() * std::mem::size_of::<CachePadded<RwLock<HashTable<T>>>>();
70        (size + allocation_size, tracker)
71    }
72}
73
74impl<T> DashTable<T> {
75    /// Creates a new concurrent raw hash table.
76    pub fn new() -> Self {
77        let shard_shift = default_shard_shift();
78        assert!(shard_shift > 0);
79        assert!(shard_shift < usize::BITS);
80        let shard_amount = 1 << shard_shift;
81
82        let shift = usize::BITS - shard_shift;
83
84        let shards = (0..shard_amount)
85            .map(|_| CachePadded::new(RwLock::new(HashTable::new())))
86            .collect();
87
88        Self { shift, shards }
89    }
90
91    /// Creates a new concurrent raw hash table, pre-allocating capacity for
92    /// approximately the given number of items
93    pub fn with_capacity(capacity: usize) -> Self {
94        let shard_shift = default_shard_shift();
95        assert!(shard_shift > 0);
96        assert!(shard_shift < usize::BITS);
97        let shard_amount = 1 << shard_shift;
98
99        let shift = usize::BITS - shard_shift;
100
101        let cps = capacity_per_shard(capacity, shard_shift);
102
103        let shards = (0..shard_amount)
104            .map(|_| CachePadded::new(RwLock::new(HashTable::with_capacity(cps))))
105            .collect();
106
107        Self { shift, shards }
108    }
109
110    /// Retrieves an entry for the given hash value.
111    ///
112    /// See also:
113    /// - [`entry_mut()`](Self::entry_mut), which is more efficient if you hold
114    ///   a mutable reference to this [`DashTable`], as it avoids acquiring
115    ///   locks,
116    /// - [`find()`](Self::find), which is more efficient if you don't need to
117    ///   modify the entry, as it only acquires a read lock.
118    pub fn entry<'a>(
119        &'a self,
120        hash: u64,
121        eq: impl FnMut(&T) -> bool,
122        hasher: impl Fn(&T) -> u64,
123    ) -> Entry<'a, T> {
124        let shard = self.determine_shard(hash as usize);
125        let guard = self.shards[shard].write();
126        // SAFETY: The data doesn't outlive the detached guard, as the guard is
127        // stored in the entry returned by this function, and the entry properly
128        // ties the guard's lifetime to the corresponding value.
129        let (_guard, shard) = unsafe { guard.detach() };
130
131        match shard.entry(hash, eq, hasher) {
132            hash_table::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { _guard, entry }),
133            hash_table::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { _guard, entry }),
134        }
135    }
136
137    /// Retrieves an entry for the given hash value.
138    ///
139    /// Contrary to [`entry()`](Self::entry), no lock is held internally because
140    /// this function already takes an exclusive mutable reference to this
141    /// [`DashTable`].
142    pub fn entry_mut<'a>(
143        &'a mut self,
144        hash: u64,
145        eq: impl FnMut(&T) -> bool,
146        hasher: impl Fn(&T) -> u64,
147    ) -> EntryMut<'a, T> {
148        let shard = self.determine_shard(hash as usize);
149        let table = self.shards[shard].get_mut();
150        table.entry(hash, eq, hasher)
151    }
152
153    /// Returns a reference to a value if one matches the given hash.
154    ///
155    /// This is more efficient than using [`entry()`](Self::entry) as this only
156    /// uses a read lock.
157    ///
158    /// See also [`find_mut`](Self::find_mut), which is more efficient if you
159    /// hold a mutable reference to this [`DashTable`] as it avoids acquiring
160    /// locks.
161    pub fn find<'a>(&'a self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<Ref<'a, T>> {
162        let shard = self.determine_shard(hash as usize);
163        let guard = self.shards[shard].read();
164        // SAFETY: The data doesn't outlive the detached guard, as the guard is
165        // stored in the entry returned by this function, and the entry properly
166        // ties the guard's lifetime to the corresponding value.
167        let (_guard, shard) = unsafe { guard.detach() };
168
169        shard
170            .find(hash, eq)
171            .map(|reference| Ref { _guard, reference })
172    }
173
174    /// Returns a reference to a value if one matches the given hash.
175    ///
176    /// Contrary to [`find()`](Self::find), no lock is held internally because
177    /// this function already takes an exclusive mutable reference to this
178    /// [`DashTable`].
179    pub fn find_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> {
180        let shard = self.determine_shard(hash as usize);
181        let table = self.shards[shard].get_mut();
182        table.find(hash, eq)
183    }
184
185    /// Unconditionally inserts the given value for the given hash, without
186    /// checking whether an equivalent element already exists in the table.
187    ///
188    /// See also [`insert_unique_mut`](Self::insert_unique_mut), which is more
189    /// efficient if you hold a mutable reference to this [`DashTable`] as
190    /// it avoids acquiring locks.
191    pub fn insert_unique<'a>(
192        &'a self,
193        hash: u64,
194        value: T,
195        hasher: impl Fn(&T) -> u64,
196    ) -> OccupiedEntry<'a, T> {
197        let shard = self.determine_shard(hash as usize);
198        let guard = self.shards[shard].write();
199        // SAFETY: The data doesn't outlive the detached guard, as the guard is
200        // stored in the entry returned by this function, and the entry properly
201        // ties the guard's lifetime to the corresponding value.
202        let (_guard, shard) = unsafe { guard.detach() };
203
204        let entry = shard.insert_unique(hash, value, hasher);
205        OccupiedEntry { _guard, entry }
206    }
207
208    /// Unconditionally inserts the given value for the given hash, without
209    /// checking whether an equivalent element already exists in the table.
210    ///
211    /// Contrary to [`insert_unique()`](Self::insert_unique), no lock is held
212    /// internally because this function already takes an exclusive mutable
213    /// reference to this [`DashTable`].
214    pub fn insert_unique_mut<'a>(
215        &'a mut self,
216        hash: u64,
217        value: T,
218        hasher: impl Fn(&T) -> u64,
219    ) -> OccupiedEntryMut<'a, T> {
220        let shard = self.determine_shard(hash as usize);
221        let table = self.shards[shard].get_mut();
222        table.insert_unique(hash, value, hasher)
223    }
224
225    fn determine_shard(&self, hash: usize) -> usize {
226        // Leave the high 7 bits for the HashBrown SIMD tag.
227        (hash << 7) >> self.shift
228    }
229}
230
231/// Read-only reference to a value in a table.
232pub struct Ref<'a, T> {
233    _guard: RwLockReadGuardDetached<'a>,
234    reference: &'a T,
235}
236
237impl<'a, T> Deref for Ref<'a, T> {
238    type Target = T;
239
240    fn deref(&self) -> &Self::Target {
241        self.reference
242    }
243}
244
245/// A view into a single entry in a table, which may either be vacant or
246/// occupied.
247pub enum Entry<'a, T> {
248    /// The entry contains a value.
249    Occupied(OccupiedEntry<'a, T>),
250    /// The entry doesn't contain any value.
251    Vacant(VacantEntry<'a, T>),
252}
253
254impl<'a, T> Entry<'a, T> {
255    /// If this entry is vacant, inserts the given default value into it.
256    pub fn or_insert_with(self, default: impl FnOnce() -> T) -> OccupiedEntry<'a, T> {
257        match self {
258            Entry::Occupied(entry) => entry,
259            Entry::Vacant(entry) => entry.insert(default()),
260        }
261    }
262}
263
264/// A hash table entry that contains a value.
265pub struct OccupiedEntry<'a, T> {
266    _guard: RwLockWriteGuardDetached<'a>,
267    entry: hash_table::OccupiedEntry<'a, T>,
268}
269
270impl<'a, T> OccupiedEntry<'a, T> {
271    /// Obtains a reference to the corresponding value.
272    pub fn get(&self) -> &T {
273        self.entry.get()
274    }
275
276    /// Obtains a mutable reference to the corresponding value.
277    pub fn get_mut(&mut self) -> &mut T {
278        self.entry.get_mut()
279    }
280
281    /// Removes the value out of the entry, and returns it along with a
282    /// [`VacantEntry`] that can be used to insert another value with the same
283    /// hash.
284    pub fn remove(self) -> (T, VacantEntry<'a, T>) {
285        let (t, entry) = self.entry.remove();
286        (
287            t,
288            VacantEntry {
289                _guard: self._guard,
290                entry,
291            },
292        )
293    }
294}
295
296/// A hash table entry that doesn't contain any value.
297pub struct VacantEntry<'a, T> {
298    _guard: RwLockWriteGuardDetached<'a>,
299    entry: hash_table::VacantEntry<'a, T>,
300}
301
302impl<'a, T> VacantEntry<'a, T> {
303    /// Inserts the given value into this entry.
304    pub fn insert(self, value: T) -> OccupiedEntry<'a, T> {
305        OccupiedEntry {
306            _guard: self._guard,
307            entry: self.entry.insert(value),
308        }
309    }
310}
311
312/// A view into a single entry in a mutable table, which may either be vacant or
313/// occupied.
314pub type EntryMut<'a, T> = hash_table::Entry<'a, T>;
315
316/// An entry in a mutable hash table that contains a value.
317pub type OccupiedEntryMut<'a, T> = hash_table::OccupiedEntry<'a, T>;
318
319#[cfg(test)]
320mod test {
321    use super::*;
322    use std::hash::{BuildHasher, RandomState};
323    use std::thread;
324
325    #[test]
326    fn test_shard_shift() {
327        assert_eq!(shard_shift(0), 1);
328        assert_eq!(shard_shift(1), 2);
329        assert_eq!(shard_shift(2), 3);
330        assert_eq!(shard_shift(3), 4);
331        assert_eq!(shard_shift(4), 4);
332        assert_eq!(shard_shift(5), 5);
333        assert_eq!(shard_shift(6), 5);
334        assert_eq!(shard_shift(7), 5);
335        assert_eq!(shard_shift(8), 5);
336        assert_eq!(shard_shift(9), 6);
337        assert_eq!(shard_shift(10), 6);
338        assert_eq!(shard_shift(usize::MAX), usize::BITS - 1);
339    }
340
341    #[test]
342    fn test_capacity_per_shard() {
343        assert_eq!(capacity_per_shard(0, 2), 0);
344        assert_eq!(capacity_per_shard(1, 2), 1);
345        assert_eq!(capacity_per_shard(2, 2), 1);
346        assert_eq!(capacity_per_shard(3, 2), 1);
347        assert_eq!(capacity_per_shard(4, 2), 1);
348        assert_eq!(capacity_per_shard(5, 2), 2);
349        assert_eq!(capacity_per_shard(42, 2), 11);
350        assert_eq!(capacity_per_shard(usize::MAX, 2), 1 << (usize::BITS - 2));
351    }
352
353    const NUM_READERS: usize = 4;
354    const NUM_WRITERS: usize = 4;
355    #[cfg(not(miri))]
356    const NUM_ITEMS: usize = 100_000;
357    #[cfg(miri)]
358    const NUM_ITEMS: usize = 100;
359
360    #[test]
361    fn test_insert_unique() {
362        let mut table = DashTable::default();
363        let hasher = RandomState::default();
364
365        thread::scope(|s| {
366            let table = &table;
367            let hasher = &hasher;
368            for i in 0..NUM_WRITERS {
369                s.spawn(move || {
370                    for j in 0..NUM_ITEMS {
371                        let value = i * NUM_ITEMS + j;
372                        assert_eq!(
373                            *table
374                                .insert_unique(hasher.hash_one(value), value, |&x| {
375                                    hasher.hash_one(x)
376                                })
377                                .get(),
378                            value,
379                        );
380                    }
381                });
382            }
383        });
384
385        for value in 0..NUM_WRITERS * NUM_ITEMS {
386            assert_eq!(
387                table.find_mut(hasher.hash_one(value), |&x| x == value),
388                Some(&value)
389            );
390        }
391    }
392
393    #[test]
394    fn test_with_capacity_insert_unique() {
395        let mut table = DashTable::with_capacity(NUM_WRITERS * NUM_ITEMS);
396        let hasher = RandomState::default();
397
398        thread::scope(|s| {
399            let table = &table;
400            let hasher = &hasher;
401            for i in 0..NUM_WRITERS {
402                s.spawn(move || {
403                    for j in 0..NUM_ITEMS {
404                        let value = i * NUM_ITEMS + j;
405                        assert_eq!(
406                            *table
407                                .insert_unique(hasher.hash_one(value), value, |&x| {
408                                    hasher.hash_one(x)
409                                })
410                                .get(),
411                            value,
412                        );
413                    }
414                });
415            }
416        });
417
418        for value in 0..NUM_WRITERS * NUM_ITEMS {
419            assert_eq!(
420                table.find_mut(hasher.hash_one(value), |&x| x == value),
421                Some(&value)
422            );
423        }
424    }
425
426    #[test]
427    fn test_entry_or_insert_with() {
428        let mut table: DashTable<(usize, usize)> = DashTable::default();
429        let hasher = RandomState::default();
430
431        thread::scope(|s| {
432            let table = &table;
433            let hasher = &hasher;
434            for _ in 0..NUM_WRITERS {
435                s.spawn(move || {
436                    for value in 0..NUM_ITEMS {
437                        table
438                            .entry(
439                                hasher.hash_one(value),
440                                |x| x.0 == value,
441                                |x| hasher.hash_one(x.0),
442                            )
443                            .or_insert_with(|| (value, 0))
444                            .get_mut()
445                            .1 += 1;
446                    }
447                });
448            }
449        });
450
451        for value in 0..NUM_ITEMS {
452            assert_eq!(
453                table.find_mut(hasher.hash_one(value), |x| x.0 == value),
454                Some(&(value, NUM_WRITERS))
455            );
456        }
457    }
458
459    #[test]
460    fn test_entry_remove() {
461        let mut table = DashTable::default();
462        let hasher = RandomState::default();
463
464        for value in 0..NUM_ITEMS {
465            assert_eq!(
466                *table
467                    .insert_unique_mut(hasher.hash_one(value), value, |&x| { hasher.hash_one(x) })
468                    .get(),
469                value
470            );
471        }
472
473        thread::scope(|s| {
474            let table = &table;
475            let hasher = &hasher;
476            for _ in 0..NUM_WRITERS {
477                s.spawn(move || {
478                    for value in 0..NUM_ITEMS {
479                        if let Entry::Occupied(entry) = table.entry(
480                            hasher.hash_one(value),
481                            |&x| x == value,
482                            |&x| hasher.hash_one(x),
483                        ) {
484                            assert_eq!(entry.remove().0, value);
485                        }
486                    }
487                });
488            }
489        });
490
491        for value in 0..NUM_ITEMS {
492            assert_eq!(
493                table.find_mut(hasher.hash_one(value), |&x| x == value),
494                None
495            );
496        }
497    }
498
499    #[test]
500    fn test_entry_mut() {
501        let mut table: DashTable<(usize, usize)> = DashTable::default();
502        let hasher = RandomState::default();
503
504        for _ in 0..NUM_WRITERS {
505            for value in 0..NUM_ITEMS {
506                table
507                    .entry_mut(
508                        hasher.hash_one(value),
509                        |x| x.0 == value,
510                        |x| hasher.hash_one(x.0),
511                    )
512                    .or_insert_with(|| (value, 0))
513                    .get_mut()
514                    .1 += 1;
515            }
516        }
517
518        for value in 0..NUM_ITEMS {
519            assert_eq!(
520                table.find_mut(hasher.hash_one(value), |x| x.0 == value),
521                Some(&(value, NUM_WRITERS))
522            );
523        }
524    }
525
526    #[test]
527    fn test_find() {
528        let mut table = DashTable::default();
529        let hasher = RandomState::default();
530
531        for value in 0..NUM_ITEMS {
532            assert_eq!(
533                *table
534                    .insert_unique_mut(hasher.hash_one(value), value, |&x| { hasher.hash_one(x) })
535                    .get(),
536                value
537            );
538        }
539
540        thread::scope(|s| {
541            let table = &table;
542            let hasher = &hasher;
543            for _ in 0..NUM_READERS {
544                s.spawn(move || {
545                    for value in 0..NUM_ITEMS {
546                        assert_eq!(
547                            table
548                                .find(hasher.hash_one(value), |&x| x == value)
549                                .as_deref(),
550                            Some(&value)
551                        );
552                    }
553                });
554            }
555        });
556    }
557
558    #[test]
559    fn test_concurrent_insert_unique_find() {
560        let mut table: DashTable<usize> = DashTable::default();
561        let hasher = RandomState::default();
562
563        thread::scope(|s| {
564            let table = &table;
565            let hasher = &hasher;
566            for _ in 0..NUM_READERS {
567                s.spawn(move || {
568                    'outer: loop {
569                        for value in 0..NUM_WRITERS * NUM_ITEMS {
570                            match table.find(hasher.hash_one(value), |&x| x == value) {
571                                None => continue 'outer,
572                                Some(v) => assert_eq!(*v.deref(), value),
573                            }
574                        }
575                        break;
576                    }
577                });
578            }
579            for i in 0..NUM_WRITERS {
580                s.spawn(move || {
581                    for j in 0..NUM_ITEMS {
582                        let value = i * NUM_ITEMS + j;
583                        assert_eq!(
584                            *table
585                                .insert_unique(hasher.hash_one(value), value, |&x| {
586                                    hasher.hash_one(x)
587                                })
588                                .get(),
589                            value,
590                        );
591                    }
592                });
593            }
594        });
595
596        for value in 0..NUM_WRITERS * NUM_ITEMS {
597            assert_eq!(
598                table.find_mut(hasher.hash_one(value), |&x| x == value),
599                Some(&value)
600            );
601        }
602    }
603}