Debian Codegraph @

debian/missing-sources/hashbrown-0.13.2/src/raw/mod.rs

raw
1 use crate::alloc::alloc::{handle_alloc_error, Layout};
2 use crate::scopeguard::{guard, ScopeGuard};
3 use crate::TryReserveError;
4 use core::iter::FusedIterator;
5 use core::marker::PhantomData;
6 use core::mem;
7 use core::mem::ManuallyDrop;
8 use core::mem::MaybeUninit;
9 use core::ptr::NonNull;
10 use core::{hint, ptr};
11
12 cfg_if! {
13 // Use the SSE2 implementation if possible: it allows us to scan 16 buckets
14 // at once instead of 8. We don't bother with AVX since it would require
15 // runtime dispatch and wouldn't gain us much anyways: the probability of
16 // finding a match drops off drastically after the first few buckets.
17 //
18 // I attempted an implementation on ARM using NEON instructions, but it
19 // turns out that most NEON instructions have multi-cycle latency, which in
20 // the end outweighs any gains over the generic implementation.
21 if #[cfg(all(
22 target_feature = "sse2",
23 any(target_arch = "x86", target_arch = "x86_64"),
24 not(miri)
25 ))] {
26 mod sse2;
27 use sse2 as imp;
28 } else {
29 #[path = "generic.rs"]
30 mod generic;
31 use generic as imp;
32 }
33 }
34
35 mod alloc;
36 pub(crate) use self::alloc::{do_alloc, Allocator, Global};
37
38 mod bitmask;
39
40 use self::bitmask::{BitMask, BitMaskIter};
41 use self::imp::Group;
42
43 // Branch prediction hint. This is currently only available on nightly but it
44 // consistently improves performance by 10-15%.
45 #[cfg(feature = "nightly")]
46 use core::intrinsics::{likely, unlikely};
47
48 // On stable we can use #[cold] to get a equivalent effect: this attributes
49 // suggests that the function is unlikely to be called
50 #[cfg(not(feature = "nightly"))]
51 #[inline]
52 #[cold]
53 fn cold() {}
54
55 #[cfg(not(feature = "nightly"))]
56 #[inline]
57 fn likely(b: bool) -> bool {
58 if !b {
59 cold();
60 }
61 b
62 }
63 #[cfg(not(feature = "nightly"))]
64 #[inline]
65 fn unlikely(b: bool) -> bool {
66 if b {
67 cold();
68 }
69 b
70 }
71
72 #[inline]
73 unsafe fn offset_from<T>(to: *const T, from: *const T) -> usize {
74 to.offset_from(from) as usize
75 }
76
77 /// Whether memory allocation errors should return an error or abort.
78 #[derive(Copy, Clone)]
79 enum Fallibility {
80 Fallible,
81 Infallible,
82 }
83
84 impl Fallibility {
85 /// Error to return on capacity overflow.
86 #[cfg_attr(feature = "inline-more", inline)]
87 fn capacity_overflow(self) -> TryReserveError {
88 match self {
89 Fallibility::Fallible => TryReserveError::CapacityOverflow,
90 Fallibility::Infallible => panic!("Hash table capacity overflow"),
91 }
92 }
93
94 /// Error to return on allocation error.
95 #[cfg_attr(feature = "inline-more", inline)]
96 fn alloc_err(self, layout: Layout) -> TryReserveError {
97 match self {
98 Fallibility::Fallible => TryReserveError::AllocError { layout },
99 Fallibility::Infallible => handle_alloc_error(layout),
100 }
101 }
102 }
103
104 /// Control byte value for an empty bucket.
105 const EMPTY: u8 = 0b1111_1111;
106
107 /// Control byte value for a deleted bucket.
108 const DELETED: u8 = 0b1000_0000;
109
110 /// Checks whether a control byte represents a full bucket (top bit is clear).
111 #[inline]
112 fn is_full(ctrl: u8) -> bool {
113 ctrl & 0x80 == 0
114 }
115
116 /// Checks whether a control byte represents a special value (top bit is set).
117 #[inline]
118 fn is_special(ctrl: u8) -> bool {
119 ctrl & 0x80 != 0
120 }
121
122 /// Checks whether a special control value is EMPTY (just check 1 bit).
123 #[inline]
124 fn special_is_empty(ctrl: u8) -> bool {
125 debug_assert!(is_special(ctrl));
126 ctrl & 0x01 != 0
127 }
128
129 /// Primary hash function, used to select the initial bucket to probe from.
130 #[inline]
131 #[allow(clippy::cast_possible_truncation)]
132 fn h1(hash: u64) -> usize {
133 // On 32-bit platforms we simply ignore the higher hash bits.
134 hash as usize
135 }
136
137 // Constant for h2 function that grabing the top 7 bits of the hash.
138 const MIN_HASH_LEN: usize = if mem::size_of::<usize>() < mem::size_of::<u64>() {
139 mem::size_of::<usize>()
140 } else {
141 mem::size_of::<u64>()
142 };
143
144 /// Secondary hash function, saved in the low 7 bits of the control byte.
145 #[inline]
146 #[allow(clippy::cast_possible_truncation)]
147 fn h2(hash: u64) -> u8 {
148 // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit
149 // value, some hash functions (such as FxHash) produce a usize result
150 // instead, which means that the top 32 bits are 0 on 32-bit platforms.
151 // So we use MIN_HASH_LEN constant to handle this.
152 let top7 = hash >> (MIN_HASH_LEN * 8 - 7);
153 (top7 & 0x7f) as u8 // truncation
154 }
155
156 /// Probe sequence based on triangular numbers, which is guaranteed (since our
157 /// table size is a power of two) to visit every group of elements exactly once.
158 ///
159 /// A triangular probe has us jump by 1 more group every time. So first we
160 /// jump by 1 group (meaning we just continue our linear scan), then 2 groups
161 /// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on.
162 ///
163 /// Proof that the probe will visit every group in the table:
164 /// <https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/>
165 struct ProbeSeq {
166 pos: usize,
167 stride: usize,
168 }
169
170 impl ProbeSeq {
171 #[inline]
172 fn move_next(&mut self, bucket_mask: usize) {
173 // We should have found an empty bucket by now and ended the probe.
174 debug_assert!(
175 self.stride <= bucket_mask,
176 "Went past end of probe sequence"
177 );
178
179 self.stride += Group::WIDTH;
180 self.pos += self.stride;
181 self.pos &= bucket_mask;
182 }
183 }
184
185 /// Returns the number of buckets needed to hold the given number of items,
186 /// taking the maximum load factor into account.
187 ///
188 /// Returns `None` if an overflow occurs.
189 // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258
190 #[cfg_attr(target_os = "emscripten", inline(never))]
191 #[cfg_attr(not(target_os = "emscripten"), inline)]
192 fn capacity_to_buckets(cap: usize) -> Option<usize> {
193 debug_assert_ne!(cap, 0);
194
195 // For small tables we require at least 1 empty bucket so that lookups are
196 // guaranteed to terminate if an element doesn't exist in the table.
197 if cap < 8 {
198 // We don't bother with a table size of 2 buckets since that can only
199 // hold a single element. Instead we skip directly to a 4 bucket table
200 // which can hold 3 elements.
201 return Some(if cap < 4 { 4 } else { 8 });
202 }
203
204 // Otherwise require 1/8 buckets to be empty (87.5% load)
205 //
206 // Be careful when modifying this, calculate_layout relies on the
207 // overflow check here.
208 let adjusted_cap = cap.checked_mul(8)? / 7;
209
210 // Any overflows will have been caught by the checked_mul. Also, any
211 // rounding errors from the division above will be cleaned up by
212 // next_power_of_two (which can't overflow because of the previous division).
213 Some(adjusted_cap.next_power_of_two())
214 }
215
216 /// Returns the maximum effective capacity for the given bucket mask, taking
217 /// the maximum load factor into account.
218 #[inline]
219 fn bucket_mask_to_capacity(bucket_mask: usize) -> usize {
220 if bucket_mask < 8 {
221 // For tables with 1/2/4/8 buckets, we always reserve one empty slot.
222 // Keep in mind that the bucket mask is one less than the bucket count.
223 bucket_mask
224 } else {
225 // For larger tables we reserve 12.5% of the slots as empty.
226 ((bucket_mask + 1) / 8) * 7
227 }
228 }
229
230 /// Helper which allows the max calculation for ctrl_align to be statically computed for each T
231 /// while keeping the rest of `calculate_layout_for` independent of `T`
232 #[derive(Copy, Clone)]
233 struct TableLayout {
234 size: usize,
235 ctrl_align: usize,
236 }
237
238 impl TableLayout {
239 #[inline]
240 const fn new<T>() -> Self {
241 let layout = Layout::new::<T>();
242 Self {
243 size: layout.size(),
244 ctrl_align: if layout.align() > Group::WIDTH {
245 layout.align()
246 } else {
247 Group::WIDTH
248 },
249 }
250 }
251
252 #[inline]
253 fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> {
254 debug_assert!(buckets.is_power_of_two());
255
256 let TableLayout { size, ctrl_align } = self;
257 // Manual layout calculation since Layout methods are not yet stable.
258 let ctrl_offset =
259 size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1);
260 let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?;
261
262 // We need an additional check to ensure that the allocation doesn't
263 // exceed `isize::MAX` (https://github.com/rust-lang/rust/pull/95295).
264 if len > isize::MAX as usize - (ctrl_align - 1) {
265 return None;
266 }
267
268 Some((
269 unsafe { Layout::from_size_align_unchecked(len, ctrl_align) },
270 ctrl_offset,
271 ))
272 }
273 }
274
275 /// A reference to a hash table bucket containing a `T`.
276 ///
277 /// This is usually just a pointer to the element itself. However if the element
278 /// is a ZST, then we instead track the index of the element in the table so
279 /// that `erase` works properly.
280 pub struct Bucket<T> {
281 // Actually it is pointer to next element than element itself
282 // this is needed to maintain pointer arithmetic invariants
283 // keeping direct pointer to element introduces difficulty.
284 // Using `NonNull` for variance and niche layout
285 ptr: NonNull<T>,
286 }
287
288 // This Send impl is needed for rayon support. This is safe since Bucket is
289 // never exposed in a public API.
290 unsafe impl<T> Send for Bucket<T> {}
291
292 impl<T> Clone for Bucket<T> {
293 #[inline]
294 fn clone(&self) -> Self {
295 Self { ptr: self.ptr }
296 }
297 }
298
299 impl<T> Bucket<T> {
300 const IS_ZERO_SIZED_TYPE: bool = mem::size_of::<T>() == 0;
301
302 #[inline]
303 unsafe fn from_base_index(base: NonNull<T>, index: usize) -> Self {
304 let ptr = if Self::IS_ZERO_SIZED_TYPE {
305 // won't overflow because index must be less than length
306 (index + 1) as *mut T
307 } else {
308 base.as_ptr().sub(index)
309 };
310 Self {
311 ptr: NonNull::new_unchecked(ptr),
312 }
313 }
314 #[inline]
315 unsafe fn to_base_index(&self, base: NonNull<T>) -> usize {
316 if Self::IS_ZERO_SIZED_TYPE {
317 self.ptr.as_ptr() as usize - 1
318 } else {
319 offset_from(base.as_ptr(), self.ptr.as_ptr())
320 }
321 }
322 #[inline]
323 pub fn as_ptr(&self) -> *mut T {
324 if Self::IS_ZERO_SIZED_TYPE {
325 // Just return an arbitrary ZST pointer which is properly aligned
326 mem::align_of::<T>() as *mut T
327 } else {
328 unsafe { self.ptr.as_ptr().sub(1) }
329 }
330 }
331 #[inline]
332 unsafe fn next_n(&self, offset: usize) -> Self {
333 let ptr = if Self::IS_ZERO_SIZED_TYPE {
334 (self.ptr.as_ptr() as usize + offset) as *mut T
335 } else {
336 self.ptr.as_ptr().sub(offset)
337 };
338 Self {
339 ptr: NonNull::new_unchecked(ptr),
340 }
341 }
342 #[cfg_attr(feature = "inline-more", inline)]
343 pub(crate) unsafe fn drop(&self) {
344 self.as_ptr().drop_in_place();
345 }
346 #[inline]
347 pub(crate) unsafe fn read(&self) -> T {
348 self.as_ptr().read()
349 }
350 #[inline]
351 pub(crate) unsafe fn write(&self, val: T) {
352 self.as_ptr().write(val);
353 }
354 #[inline]
355 pub unsafe fn as_ref<'a>(&self) -> &'a T {
356 &*self.as_ptr()
357 }
358 #[inline]
359 pub unsafe fn as_mut<'a>(&self) -> &'a mut T {
360 &mut *self.as_ptr()
361 }
362 #[cfg(feature = "raw")]
363 #[inline]
364 pub unsafe fn copy_from_nonoverlapping(&self, other: &Self) {
365 self.as_ptr().copy_from_nonoverlapping(other.as_ptr(), 1);
366 }
367 }
368
369 /// A raw hash table with an unsafe API.
370 pub struct RawTable<T, A: Allocator + Clone = Global> {
371 table: RawTableInner<A>,
372 // Tell dropck that we own instances of T.
373 marker: PhantomData<T>,
374 }
375
376 /// Non-generic part of `RawTable` which allows functions to be instantiated only once regardless
377 /// of how many different key-value types are used.
378 struct RawTableInner<A> {
379 // Mask to get an index from a hash value. The value is one less than the
380 // number of buckets in the table.
381 bucket_mask: usize,
382
383 // [Padding], T1, T2, ..., Tlast, C1, C2, ...
384 // ^ points here
385 ctrl: NonNull<u8>,
386
387 // Number of elements that can be inserted before we need to grow the table
388 growth_left: usize,
389
390 // Number of elements in the table, only really used by len()
391 items: usize,
392
393 alloc: A,
394 }
395
396 impl<T> RawTable<T, Global> {
397 /// Creates a new empty hash table without allocating any memory.
398 ///
399 /// In effect this returns a table with exactly 1 bucket. However we can
400 /// leave the data pointer dangling since that bucket is never written to
401 /// due to our load factor forcing us to always have at least 1 free bucket.
402 #[inline]
403 pub const fn new() -> Self {
404 Self {
405 table: RawTableInner::new_in(Global),
406 marker: PhantomData,
407 }
408 }
409
410 /// Attempts to allocate a new hash table with at least enough capacity
411 /// for inserting the given number of elements without reallocating.
412 #[cfg(feature = "raw")]
413 pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
414 Self::try_with_capacity_in(capacity, Global)
415 }
416
417 /// Allocates a new hash table with at least enough capacity for inserting
418 /// the given number of elements without reallocating.
419 pub fn with_capacity(capacity: usize) -> Self {
420 Self::with_capacity_in(capacity, Global)
421 }
422 }
423
424 impl<T, A: Allocator + Clone> RawTable<T, A> {
425 const TABLE_LAYOUT: TableLayout = TableLayout::new::<T>();
426 const DATA_NEEDS_DROP: bool = mem::needs_drop::<T>();
427
428 /// Creates a new empty hash table without allocating any memory, using the
429 /// given allocator.
430 ///
431 /// In effect this returns a table with exactly 1 bucket. However we can
432 /// leave the data pointer dangling since that bucket is never written to
433 /// due to our load factor forcing us to always have at least 1 free bucket.
434 #[inline]
435 pub const fn new_in(alloc: A) -> Self {
436 Self {
437 table: RawTableInner::new_in(alloc),
438 marker: PhantomData,
439 }
440 }
441
442 /// Allocates a new hash table with the given number of buckets.
443 ///
444 /// The control bytes are left uninitialized.
445 #[cfg_attr(feature = "inline-more", inline)]
446 unsafe fn new_uninitialized(
447 alloc: A,
448 buckets: usize,
449 fallibility: Fallibility,
450 ) -> Result<Self, TryReserveError> {
451 debug_assert!(buckets.is_power_of_two());
452
453 Ok(Self {
454 table: RawTableInner::new_uninitialized(
455 alloc,
456 Self::TABLE_LAYOUT,
457 buckets,
458 fallibility,
459 )?,
460 marker: PhantomData,
461 })
462 }
463
464 /// Attempts to allocate a new hash table with at least enough capacity
465 /// for inserting the given number of elements without reallocating.
466 fn fallible_with_capacity(
467 alloc: A,
468 capacity: usize,
469 fallibility: Fallibility,
470 ) -> Result<Self, TryReserveError> {
471 Ok(Self {
472 table: RawTableInner::fallible_with_capacity(
473 alloc,
474 Self::TABLE_LAYOUT,
475 capacity,
476 fallibility,
477 )?,
478 marker: PhantomData,
479 })
480 }
481
482 /// Attempts to allocate a new hash table using the given allocator, with at least enough
483 /// capacity for inserting the given number of elements without reallocating.
484 #[cfg(feature = "raw")]
485 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
486 Self::fallible_with_capacity(alloc, capacity, Fallibility::Fallible)
487 }
488
489 /// Allocates a new hash table using the given allocator, with at least enough capacity for
490 /// inserting the given number of elements without reallocating.
491 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
492 // Avoid `Result::unwrap_or_else` because it bloats LLVM IR.
493 match Self::fallible_with_capacity(alloc, capacity, Fallibility::Infallible) {
494 Ok(capacity) => capacity,
495 Err(_) => unsafe { hint::unreachable_unchecked() },
496 }
497 }
498
499 /// Returns a reference to the underlying allocator.
500 #[inline]
501 pub fn allocator(&self) -> &A {
502 &self.table.alloc
503 }
504
505 /// Deallocates the table without dropping any entries.
506 #[cfg_attr(feature = "inline-more", inline)]
507 unsafe fn free_buckets(&mut self) {
508 self.table.free_buckets(Self::TABLE_LAYOUT);
509 }
510
511 /// Returns pointer to one past last element of data table.
512 #[inline]
513 pub unsafe fn data_end(&self) -> NonNull<T> {
514 NonNull::new_unchecked(self.table.ctrl.as_ptr().cast())
515 }
516
517 /// Returns pointer to start of data table.
518 #[inline]
519 #[cfg(feature = "nightly")]
520 pub unsafe fn data_start(&self) -> *mut T {
521 self.data_end().as_ptr().wrapping_sub(self.buckets())
522 }
523
524 /// Return the information about memory allocated by the table.
525 ///
526 /// `RawTable` allocates single memory block to store both data and metadata.
527 /// This function returns allocation size and alignment and the beginning of the area.
528 /// These are the arguments which will be passed to `dealloc` when the table is dropped.
529 ///
530 /// This function might be useful for memory profiling.
531 #[inline]
532 #[cfg(feature = "raw")]
533 pub fn allocation_info(&self) -> (NonNull<u8>, Layout) {
534 self.table.allocation_info_or_zero(Self::TABLE_LAYOUT)
535 }
536
537 /// Returns the index of a bucket from a `Bucket`.
538 #[inline]
539 pub unsafe fn bucket_index(&self, bucket: &Bucket<T>) -> usize {
540 bucket.to_base_index(self.data_end())
541 }
542
543 /// Returns a pointer to an element in the table.
544 #[inline]
545 pub unsafe fn bucket(&self, index: usize) -> Bucket<T> {
546 debug_assert_ne!(self.table.bucket_mask, 0);
547 debug_assert!(index < self.buckets());
548 Bucket::from_base_index(self.data_end(), index)
549 }
550
551 /// Erases an element from the table without dropping it.
552 #[cfg_attr(feature = "inline-more", inline)]
553 unsafe fn erase_no_drop(&mut self, item: &Bucket<T>) {
554 let index = self.bucket_index(item);
555 self.table.erase(index);
556 }
557
558 /// Erases an element from the table, dropping it in place.
559 #[cfg_attr(feature = "inline-more", inline)]
560 #[allow(clippy::needless_pass_by_value)]
561 pub unsafe fn erase(&mut self, item: Bucket<T>) {
562 // Erase the element from the table first since drop might panic.
563 self.erase_no_drop(&item);
564 item.drop();
565 }
566
567 /// Finds and erases an element from the table, dropping it in place.
568 /// Returns true if an element was found.
569 #[cfg(feature = "raw")]
570 #[cfg_attr(feature = "inline-more", inline)]
571 pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool {
572 // Avoid `Option::map` because it bloats LLVM IR.
573 if let Some(bucket) = self.find(hash, eq) {
574 unsafe {
575 self.erase(bucket);
576 }
577 true
578 } else {
579 false
580 }
581 }
582
583 /// Removes an element from the table, returning it.
584 #[cfg_attr(feature = "inline-more", inline)]
585 #[allow(clippy::needless_pass_by_value)]
586 pub unsafe fn remove(&mut self, item: Bucket<T>) -> T {
587 self.erase_no_drop(&item);
588 item.read()
589 }
590
591 /// Finds and removes an element from the table, returning it.
592 #[cfg_attr(feature = "inline-more", inline)]
593 pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<T> {
594 // Avoid `Option::map` because it bloats LLVM IR.
595 match self.find(hash, eq) {
596 Some(bucket) => Some(unsafe { self.remove(bucket) }),
597 None => None,
598 }
599 }
600
601 /// Marks all table buckets as empty without dropping their contents.
602 #[cfg_attr(feature = "inline-more", inline)]
603 pub fn clear_no_drop(&mut self) {
604 self.table.clear_no_drop();
605 }
606
607 /// Removes all elements from the table without freeing the backing memory.
608 #[cfg_attr(feature = "inline-more", inline)]
609 pub fn clear(&mut self) {
610 // Ensure that the table is reset even if one of the drops panic
611 let mut self_ = guard(self, |self_| self_.clear_no_drop());
612 unsafe {
613 self_.drop_elements();
614 }
615 }
616
617 unsafe fn drop_elements(&mut self) {
618 if Self::DATA_NEEDS_DROP && !self.is_empty() {
619 for item in self.iter() {
620 item.drop();
621 }
622 }
623 }
624
625 /// Shrinks the table to fit `max(self.len(), min_size)` elements.
626 #[cfg_attr(feature = "inline-more", inline)]
627 pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) {
628 // Calculate the minimal number of elements that we need to reserve
629 // space for.
630 let min_size = usize::max(self.table.items, min_size);
631 if min_size == 0 {
632 *self = Self::new_in(self.table.alloc.clone());
633 return;
634 }
635
636 // Calculate the number of buckets that we need for this number of
637 // elements. If the calculation overflows then the requested bucket
638 // count must be larger than what we have right and nothing needs to be
639 // done.
640 let min_buckets = match capacity_to_buckets(min_size) {
641 Some(buckets) => buckets,
642 None => return,
643 };
644
645 // If we have more buckets than we need, shrink the table.
646 if min_buckets < self.buckets() {
647 // Fast path if the table is empty
648 if self.table.items == 0 {
649 *self = Self::with_capacity_in(min_size, self.table.alloc.clone());
650 } else {
651 // Avoid `Result::unwrap_or_else` because it bloats LLVM IR.
652 if self
653 .resize(min_size, hasher, Fallibility::Infallible)
654 .is_err()
655 {
656 unsafe { hint::unreachable_unchecked() }
657 }
658 }
659 }
660 }
661
662 /// Ensures that at least `additional` items can be inserted into the table
663 /// without reallocation.
664 #[cfg_attr(feature = "inline-more", inline)]
665 pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) {
666 if additional > self.table.growth_left {
667 // Avoid `Result::unwrap_or_else` because it bloats LLVM IR.
668 if self
669 .reserve_rehash(additional, hasher, Fallibility::Infallible)
670 .is_err()
671 {
672 unsafe { hint::unreachable_unchecked() }
673 }
674 }
675 }
676
677 /// Tries to ensure that at least `additional` items can be inserted into
678 /// the table without reallocation.
679 #[cfg_attr(feature = "inline-more", inline)]
680 pub fn try_reserve(
681 &mut self,
682 additional: usize,
683 hasher: impl Fn(&T) -> u64,
684 ) -> Result<(), TryReserveError> {
685 if additional > self.table.growth_left {
686 self.reserve_rehash(additional, hasher, Fallibility::Fallible)
687 } else {
688 Ok(())
689 }
690 }
691
692 /// Out-of-line slow path for `reserve` and `try_reserve`.
693 #[cold]
694 #[inline(never)]
695 fn reserve_rehash(
696 &mut self,
697 additional: usize,
698 hasher: impl Fn(&T) -> u64,
699 fallibility: Fallibility,
700 ) -> Result<(), TryReserveError> {
701 unsafe {
702 self.table.reserve_rehash_inner(
703 additional,
704 &|table, index| hasher(table.bucket::<T>(index).as_ref()),
705 fallibility,
706 Self::TABLE_LAYOUT,
707 if Self::DATA_NEEDS_DROP {
708 Some(mem::transmute(ptr::drop_in_place::<T> as unsafe fn(*mut T)))
709 } else {
710 None
711 },
712 )
713 }
714 }
715
716 /// Allocates a new table of a different size and moves the contents of the
717 /// current table into it.
718 fn resize(
719 &mut self,
720 capacity: usize,
721 hasher: impl Fn(&T) -> u64,
722 fallibility: Fallibility,
723 ) -> Result<(), TryReserveError> {
724 unsafe {
725 self.table.resize_inner(
726 capacity,
727 &|table, index| hasher(table.bucket::<T>(index).as_ref()),
728 fallibility,
729 Self::TABLE_LAYOUT,
730 )
731 }
732 }
733
734 /// Inserts a new element into the table, and returns its raw bucket.
735 ///
736 /// This does not check if the given element already exists in the table.
737 #[cfg_attr(feature = "inline-more", inline)]
738 pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket<T> {
739 unsafe {
740 let mut index = self.table.find_insert_slot(hash);
741
742 // We can avoid growing the table once we have reached our load
743 // factor if we are replacing a tombstone. This works since the
744 // number of EMPTY slots does not change in this case.
745 let old_ctrl = *self.table.ctrl(index);
746 if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) {
747 self.reserve(1, hasher);
748 index = self.table.find_insert_slot(hash);
749 }
750
751 self.table.record_item_insert_at(index, old_ctrl, hash);
752
753 let bucket = self.bucket(index);
754 bucket.write(value);
755 bucket
756 }
757 }
758
759 /// Attempts to insert a new element without growing the table and return its raw bucket.
760 ///
761 /// Returns an `Err` containing the given element if inserting it would require growing the
762 /// table.
763 ///
764 /// This does not check if the given element already exists in the table.
765 #[cfg(feature = "raw")]
766 #[cfg_attr(feature = "inline-more", inline)]
767 pub fn try_insert_no_grow(&mut self, hash: u64, value: T) -> Result<Bucket<T>, T> {
768 unsafe {
769 match self.table.prepare_insert_no_grow(hash) {
770 Ok(index) => {
771 let bucket = self.bucket(index);
772 bucket.write(value);
773 Ok(bucket)
774 }
775 Err(()) => Err(value),
776 }
777 }
778 }
779
780 /// Inserts a new element into the table, and returns a mutable reference to it.
781 ///
782 /// This does not check if the given element already exists in the table.
783 #[cfg_attr(feature = "inline-more", inline)]
784 pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T {
785 unsafe { self.insert(hash, value, hasher).as_mut() }
786 }
787
788 /// Inserts a new element into the table, without growing the table.
789 ///
790 /// There must be enough space in the table to insert the new element.
791 ///
792 /// This does not check if the given element already exists in the table.
793 #[cfg_attr(feature = "inline-more", inline)]
794 #[cfg(any(feature = "raw", feature = "rustc-internal-api"))]
795 pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket<T> {
796 let (index, old_ctrl) = self.table.prepare_insert_slot(hash);
797 let bucket = self.table.bucket(index);
798
799 // If we are replacing a DELETED entry then we don't need to update
800 // the load counter.
801 self.table.growth_left -= special_is_empty(old_ctrl) as usize;
802
803 bucket.write(value);
804 self.table.items += 1;
805 bucket
806 }
807
808 /// Temporary removes a bucket, applying the given function to the removed
809 /// element and optionally put back the returned value in the same bucket.
810 ///
811 /// Returns `true` if the bucket still contains an element
812 ///
813 /// This does not check if the given bucket is actually occupied.
814 #[cfg_attr(feature = "inline-more", inline)]
815 pub unsafe fn replace_bucket_with<F>(&mut self, bucket: Bucket<T>, f: F) -> bool
816 where
817 F: FnOnce(T) -> Option<T>,
818 {
819 let index = self.bucket_index(&bucket);
820 let old_ctrl = *self.table.ctrl(index);
821 debug_assert!(self.is_bucket_full(index));
822 let old_growth_left = self.table.growth_left;
823 let item = self.remove(bucket);
824 if let Some(new_item) = f(item) {
825 self.table.growth_left = old_growth_left;
826 self.table.set_ctrl(index, old_ctrl);
827 self.table.items += 1;
828 self.bucket(index).write(new_item);
829 true
830 } else {
831 false
832 }
833 }
834
835 /// Searches for an element in the table.
836 #[inline]
837 pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option<Bucket<T>> {
838 let result = self.table.find_inner(hash, &mut |index| unsafe {
839 eq(self.bucket(index).as_ref())
840 });
841
842 // Avoid `Option::map` because it bloats LLVM IR.
843 match result {
844 Some(index) => Some(unsafe { self.bucket(index) }),
845 None => None,
846 }
847 }
848
849 /// Gets a reference to an element in the table.
850 #[inline]
851 pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> {
852 // Avoid `Option::map` because it bloats LLVM IR.
853 match self.find(hash, eq) {
854 Some(bucket) => Some(unsafe { bucket.as_ref() }),
855 None => None,
856 }
857 }
858
859 /// Gets a mutable reference to an element in the table.
860 #[inline]
861 pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> {
862 // Avoid `Option::map` because it bloats LLVM IR.
863 match self.find(hash, eq) {
864 Some(bucket) => Some(unsafe { bucket.as_mut() }),
865 None => None,
866 }
867 }
868
869 /// Attempts to get mutable references to `N` entries in the table at once.
870 ///
871 /// Returns an array of length `N` with the results of each query.
872 ///
873 /// At most one mutable reference will be returned to any entry. `None` will be returned if any
874 /// of the hashes are duplicates. `None` will be returned if the hash is not found.
875 ///
876 /// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to
877 /// the `i`th key to be looked up.
878 pub fn get_many_mut<const N: usize>(
879 &mut self,
880 hashes: [u64; N],
881 eq: impl FnMut(usize, &T) -> bool,
882 ) -> Option<[&'_ mut T; N]> {
883 unsafe {
884 let ptrs = self.get_many_mut_pointers(hashes, eq)?;
885
886 for (i, &cur) in ptrs.iter().enumerate() {
887 if ptrs[..i].iter().any(|&prev| ptr::eq::<T>(prev, cur)) {
888 return None;
889 }
890 }
891 // All bucket are distinct from all previous buckets so we're clear to return the result
892 // of the lookup.
893
894 // TODO use `MaybeUninit::array_assume_init` here instead once that's stable.
895 Some(mem::transmute_copy(&ptrs))
896 }
897 }
898
899 pub unsafe fn get_many_unchecked_mut<const N: usize>(
900 &mut self,
901 hashes: [u64; N],
902 eq: impl FnMut(usize, &T) -> bool,
903 ) -> Option<[&'_ mut T; N]> {
904 let ptrs = self.get_many_mut_pointers(hashes, eq)?;
905 Some(mem::transmute_copy(&ptrs))
906 }
907
908 unsafe fn get_many_mut_pointers<const N: usize>(
909 &mut self,
910 hashes: [u64; N],
911 mut eq: impl FnMut(usize, &T) -> bool,
912 ) -> Option<[*mut T; N]> {
913 // TODO use `MaybeUninit::uninit_array` here instead once that's stable.
914 let mut outs: MaybeUninit<[*mut T; N]> = MaybeUninit::uninit();
915 let outs_ptr = outs.as_mut_ptr();
916
917 for (i, &hash) in hashes.iter().enumerate() {
918 let cur = self.find(hash, |k| eq(i, k))?;
919 *(*outs_ptr).get_unchecked_mut(i) = cur.as_mut();
920 }
921
922 // TODO use `MaybeUninit::array_assume_init` here instead once that's stable.
923 Some(outs.assume_init())
924 }
925
926 /// Returns the number of elements the map can hold without reallocating.
927 ///
928 /// This number is a lower bound; the table might be able to hold
929 /// more, but is guaranteed to be able to hold at least this many.
930 #[inline]
931 pub fn capacity(&self) -> usize {
932 self.table.items + self.table.growth_left
933 }
934
935 /// Returns the number of elements in the table.
936 #[inline]
937 pub fn len(&self) -> usize {
938 self.table.items
939 }
940
941 /// Returns `true` if the table contains no elements.
942 #[inline]
943 pub fn is_empty(&self) -> bool {
944 self.len() == 0
945 }
946
947 /// Returns the number of buckets in the table.
948 #[inline]
949 pub fn buckets(&self) -> usize {
950 self.table.bucket_mask + 1
951 }
952
953 /// Checks whether the bucket at `index` is full.
954 ///
955 /// # Safety
956 ///
957 /// The caller must ensure `index` is less than the number of buckets.
958 #[inline]
959 pub unsafe fn is_bucket_full(&self, index: usize) -> bool {
960 self.table.is_bucket_full(index)
961 }
962
963 /// Returns an iterator over every element in the table. It is up to
964 /// the caller to ensure that the `RawTable` outlives the `RawIter`.
965 /// Because we cannot make the `next` method unsafe on the `RawIter`
966 /// struct, we have to make the `iter` method unsafe.
967 #[inline]
968 pub unsafe fn iter(&self) -> RawIter<T> {
969 let data = Bucket::from_base_index(self.data_end(), 0);
970 RawIter {
971 iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()),
972 items: self.table.items,
973 }
974 }
975
976 /// Returns an iterator over occupied buckets that could match a given hash.
977 ///
978 /// `RawTable` only stores 7 bits of the hash value, so this iterator may
979 /// return items that have a hash value different than the one provided. You
980 /// should always validate the returned values before using them.
981 ///
982 /// It is up to the caller to ensure that the `RawTable` outlives the
983 /// `RawIterHash`. Because we cannot make the `next` method unsafe on the
984 /// `RawIterHash` struct, we have to make the `iter_hash` method unsafe.
985 #[cfg_attr(feature = "inline-more", inline)]
986 #[cfg(feature = "raw")]
987 pub unsafe fn iter_hash(&self, hash: u64) -> RawIterHash<'_, T, A> {
988 RawIterHash::new(self, hash)
989 }
990
991 /// Returns an iterator which removes all elements from the table without
992 /// freeing the memory.
993 #[cfg_attr(feature = "inline-more", inline)]
994 pub fn drain(&mut self) -> RawDrain<'_, T, A> {
995 unsafe {
996 let iter = self.iter();
997 self.drain_iter_from(iter)
998 }
999 }
1000
1001 /// Returns an iterator which removes all elements from the table without
1002 /// freeing the memory.
1003 ///
1004 /// Iteration starts at the provided iterator's current location.
1005 ///
1006 /// It is up to the caller to ensure that the iterator is valid for this
1007 /// `RawTable` and covers all items that remain in the table.
1008 #[cfg_attr(feature = "inline-more", inline)]
1009 pub unsafe fn drain_iter_from(&mut self, iter: RawIter<T>) -> RawDrain<'_, T, A> {
1010 debug_assert_eq!(iter.len(), self.len());
1011 RawDrain {
1012 iter,
1013 table: ManuallyDrop::new(mem::replace(self, Self::new_in(self.table.alloc.clone()))),
1014 orig_table: NonNull::from(self),
1015 marker: PhantomData,
1016 }
1017 }
1018
1019 /// Returns an iterator which consumes all elements from the table.
1020 ///
1021 /// Iteration starts at the provided iterator's current location.
1022 ///
1023 /// It is up to the caller to ensure that the iterator is valid for this
1024 /// `RawTable` and covers all items that remain in the table.
1025 pub unsafe fn into_iter_from(self, iter: RawIter<T>) -> RawIntoIter<T, A> {
1026 debug_assert_eq!(iter.len(), self.len());
1027
1028 let alloc = self.table.alloc.clone();
1029 let allocation = self.into_allocation();
1030 RawIntoIter {
1031 iter,
1032 allocation,
1033 marker: PhantomData,
1034 alloc,
1035 }
1036 }
1037
1038 /// Converts the table into a raw allocation. The contents of the table
1039 /// should be dropped using a `RawIter` before freeing the allocation.
1040 #[cfg_attr(feature = "inline-more", inline)]
1041 pub(crate) fn into_allocation(self) -> Option<(NonNull<u8>, Layout)> {
1042 let alloc = if self.table.is_empty_singleton() {
1043 None
1044 } else {
1045 // Avoid `Option::unwrap_or_else` because it bloats LLVM IR.
1046 let (layout, ctrl_offset) =
1047 match Self::TABLE_LAYOUT.calculate_layout_for(self.table.buckets()) {
1048 Some(lco) => lco,
1049 None => unsafe { hint::unreachable_unchecked() },
1050 };
1051 Some((
1052 unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) },
1053 layout,
1054 ))
1055 };
1056 mem::forget(self);
1057 alloc
1058 }
1059 }
1060
1061 unsafe impl<T, A: Allocator + Clone> Send for RawTable<T, A>
1062 where
1063 T: Send,
1064 A: Send,
1065 {
1066 }
1067 unsafe impl<T, A: Allocator + Clone> Sync for RawTable<T, A>
1068 where
1069 T: Sync,
1070 A: Sync,
1071 {
1072 }
1073
1074 impl<A> RawTableInner<A> {
1075 #[inline]
1076 const fn new_in(alloc: A) -> Self {
1077 Self {
1078 // Be careful to cast the entire slice to a raw pointer.
1079 ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) },
1080 bucket_mask: 0,
1081 items: 0,
1082 growth_left: 0,
1083 alloc,
1084 }
1085 }
1086 }
1087
1088 impl<A: Allocator + Clone> RawTableInner<A> {
1089 #[cfg_attr(feature = "inline-more", inline)]
1090 unsafe fn new_uninitialized(
1091 alloc: A,
1092 table_layout: TableLayout,
1093 buckets: usize,
1094 fallibility: Fallibility,
1095 ) -> Result<Self, TryReserveError> {
1096 debug_assert!(buckets.is_power_of_two());
1097
1098 // Avoid `Option::ok_or_else` because it bloats LLVM IR.
1099 let (layout, ctrl_offset) = match table_layout.calculate_layout_for(buckets) {
1100 Some(lco) => lco,
1101 None => return Err(fallibility.capacity_overflow()),
1102 };
1103
1104 let ptr: NonNull<u8> = match do_alloc(&alloc, layout) {
1105 Ok(block) => block.cast(),
1106 Err(_) => return Err(fallibility.alloc_err(layout)),
1107 };
1108
1109 let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset));
1110 Ok(Self {
1111 ctrl,
1112 bucket_mask: buckets - 1,
1113 items: 0,
1114 growth_left: bucket_mask_to_capacity(buckets - 1),
1115 alloc,
1116 })
1117 }
1118
1119 #[inline]
1120 fn fallible_with_capacity(
1121 alloc: A,
1122 table_layout: TableLayout,
1123 capacity: usize,
1124 fallibility: Fallibility,
1125 ) -> Result<Self, TryReserveError> {
1126 if capacity == 0 {
1127 Ok(Self::new_in(alloc))
1128 } else {
1129 unsafe {
1130 let buckets =
1131 capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?;
1132
1133 let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?;
1134 result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes());
1135
1136 Ok(result)
1137 }
1138 }
1139 }
1140
1141 /// Searches for an empty or deleted bucket which is suitable for inserting
1142 /// a new element and sets the hash for that slot.
1143 ///
1144 /// There must be at least 1 empty bucket in the table.
1145 #[inline]
1146 unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) {
1147 let index = self.find_insert_slot(hash);
1148 let old_ctrl = *self.ctrl(index);
1149 self.set_ctrl_h2(index, hash);
1150 (index, old_ctrl)
1151 }
1152
1153 /// Searches for an empty or deleted bucket which is suitable for inserting
1154 /// a new element.
1155 ///
1156 /// There must be at least 1 empty bucket in the table.
1157 #[inline]
1158 fn find_insert_slot(&self, hash: u64) -> usize {
1159 let mut probe_seq = self.probe_seq(hash);
1160 loop {
1161 unsafe {
1162 let group = Group::load(self.ctrl(probe_seq.pos));
1163 if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() {
1164 let result = (probe_seq.pos + bit) & self.bucket_mask;
1165
1166 // In tables smaller than the group width, trailing control
1167 // bytes outside the range of the table are filled with
1168 // EMPTY entries. These will unfortunately trigger a
1169 // match, but once masked may point to a full bucket that
1170 // is already occupied. We detect this situation here and
1171 // perform a second scan starting at the beginning of the
1172 // table. This second scan is guaranteed to find an empty
1173 // slot (due to the load factor) before hitting the trailing
1174 // control bytes (containing EMPTY).
1175 if unlikely(self.is_bucket_full(result)) {
1176 debug_assert!(self.bucket_mask < Group::WIDTH);
1177 debug_assert_ne!(probe_seq.pos, 0);
1178 return Group::load_aligned(self.ctrl(0))
1179 .match_empty_or_deleted()
1180 .lowest_set_bit_nonzero();
1181 }
1182
1183 return result;
1184 }
1185 }
1186 probe_seq.move_next(self.bucket_mask);
1187 }
1188 }
1189
1190 /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of
1191 /// code generated, but it is eliminated by LLVM optimizations.
1192 #[inline(always)]
1193 fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option<usize> {
1194 let h2_hash = h2(hash);
1195 let mut probe_seq = self.probe_seq(hash);
1196
1197 loop {
1198 let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) };
1199
1200 for bit in group.match_byte(h2_hash) {
1201 let index = (probe_seq.pos + bit) & self.bucket_mask;
1202
1203 if likely(eq(index)) {
1204 return Some(index);
1205 }
1206 }
1207
1208 if likely(group.match_empty().any_bit_set()) {
1209 return None;
1210 }
1211
1212 probe_seq.move_next(self.bucket_mask);
1213 }
1214 }
1215
1216 #[allow(clippy::mut_mut)]
1217 #[inline]
1218 unsafe fn prepare_rehash_in_place(&mut self) {
1219 // Bulk convert all full control bytes to DELETED, and all DELETED
1220 // control bytes to EMPTY. This effectively frees up all buckets
1221 // containing a DELETED entry.
1222 for i in (0..self.buckets()).step_by(Group::WIDTH) {
1223 let group = Group::load_aligned(self.ctrl(i));
1224 let group = group.convert_special_to_empty_and_full_to_deleted();
1225 group.store_aligned(self.ctrl(i));
1226 }
1227
1228 // Fix up the trailing control bytes. See the comments in set_ctrl
1229 // for the handling of tables smaller than the group width.
1230 if self.buckets() < Group::WIDTH {
1231 self.ctrl(0)
1232 .copy_to(self.ctrl(Group::WIDTH), self.buckets());
1233 } else {
1234 self.ctrl(0)
1235 .copy_to(self.ctrl(self.buckets()), Group::WIDTH);
1236 }
1237 }
1238
1239 #[inline]
1240 unsafe fn bucket<T>(&self, index: usize) -> Bucket<T> {
1241 debug_assert_ne!(self.bucket_mask, 0);
1242 debug_assert!(index < self.buckets());
1243 Bucket::from_base_index(self.data_end(), index)
1244 }
1245
1246 #[inline]
1247 unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 {
1248 debug_assert_ne!(self.bucket_mask, 0);
1249 debug_assert!(index < self.buckets());
1250 let base: *mut u8 = self.data_end().as_ptr();
1251 base.sub((index + 1) * size_of)
1252 }
1253
1254 #[inline]
1255 unsafe fn data_end<T>(&self) -> NonNull<T> {
1256 NonNull::new_unchecked(self.ctrl.as_ptr().cast())
1257 }
1258
1259 /// Returns an iterator-like object for a probe sequence on the table.
1260 ///
1261 /// This iterator never terminates, but is guaranteed to visit each bucket
1262 /// group exactly once. The loop using `probe_seq` must terminate upon
1263 /// reaching a group containing an empty bucket.
1264 #[inline]
1265 fn probe_seq(&self, hash: u64) -> ProbeSeq {
1266 ProbeSeq {
1267 pos: h1(hash) & self.bucket_mask,
1268 stride: 0,
1269 }
1270 }
1271
1272 /// Returns the index of a bucket for which a value must be inserted if there is enough rooom
1273 /// in the table, otherwise returns error
1274 #[cfg(feature = "raw")]
1275 #[inline]
1276 unsafe fn prepare_insert_no_grow(&mut self, hash: u64) -> Result<usize, ()> {
1277 let index = self.find_insert_slot(hash);
1278 let old_ctrl = *self.ctrl(index);
1279 if unlikely(self.growth_left == 0 && special_is_empty(old_ctrl)) {
1280 Err(())
1281 } else {
1282 self.record_item_insert_at(index, old_ctrl, hash);
1283 Ok(index)
1284 }
1285 }
1286
1287 #[inline]
1288 unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) {
1289 self.growth_left -= usize::from(special_is_empty(old_ctrl));
1290 self.set_ctrl_h2(index, hash);
1291 self.items += 1;
1292 }
1293
1294 #[inline]
1295 fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool {
1296 let probe_seq_pos = self.probe_seq(hash).pos;
1297 let probe_index =
1298 |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH;
1299 probe_index(i) == probe_index(new_i)
1300 }
1301
1302 /// Sets a control byte to the hash, and possibly also the replicated control byte at
1303 /// the end of the array.
1304 #[inline]
1305 unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) {
1306 self.set_ctrl(index, h2(hash));
1307 }
1308
1309 #[inline]
1310 unsafe fn replace_ctrl_h2(&self, index: usize, hash: u64) -> u8 {
1311 let prev_ctrl = *self.ctrl(index);
1312 self.set_ctrl_h2(index, hash);
1313 prev_ctrl
1314 }
1315
1316 /// Sets a control byte, and possibly also the replicated control byte at
1317 /// the end of the array.
1318 #[inline]
1319 unsafe fn set_ctrl(&self, index: usize, ctrl: u8) {
1320 // Replicate the first Group::WIDTH control bytes at the end of
1321 // the array without using a branch:
1322 // - If index >= Group::WIDTH then index == index2.
1323 // - Otherwise index2 == self.bucket_mask + 1 + index.
1324 //
1325 // The very last replicated control byte is never actually read because
1326 // we mask the initial index for unaligned loads, but we write it
1327 // anyways because it makes the set_ctrl implementation simpler.
1328 //
1329 // If there are fewer buckets than Group::WIDTH then this code will
1330 // replicate the buckets at the end of the trailing group. For example
1331 // with 2 buckets and a group size of 4, the control bytes will look
1332 // like this:
1333 //
1334 // Real | Replicated
1335 // ---------------------------------------------
1336 // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] |
1337 // ---------------------------------------------
1338 let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH;
1339
1340 *self.ctrl(index) = ctrl;
1341 *self.ctrl(index2) = ctrl;
1342 }
1343
1344 /// Returns a pointer to a control byte.
1345 #[inline]
1346 unsafe fn ctrl(&self, index: usize) -> *mut u8 {
1347 debug_assert!(index < self.num_ctrl_bytes());
1348 self.ctrl.as_ptr().add(index)
1349 }
1350
1351 #[inline]
1352 fn buckets(&self) -> usize {
1353 self.bucket_mask + 1
1354 }
1355
1356 /// Checks whether the bucket at `index` is full.
1357 ///
1358 /// # Safety
1359 ///
1360 /// The caller must ensure `index` is less than the number of buckets.
1361 #[inline]
1362 unsafe fn is_bucket_full(&self, index: usize) -> bool {
1363 debug_assert!(index < self.buckets());
1364 is_full(*self.ctrl(index))
1365 }
1366
1367 #[inline]
1368 fn num_ctrl_bytes(&self) -> usize {
1369 self.bucket_mask + 1 + Group::WIDTH
1370 }
1371
1372 #[inline]
1373 fn is_empty_singleton(&self) -> bool {
1374 self.bucket_mask == 0
1375 }
1376
1377 #[allow(clippy::mut_mut)]
1378 #[inline]
1379 unsafe fn prepare_resize(
1380 &self,
1381 table_layout: TableLayout,
1382 capacity: usize,
1383 fallibility: Fallibility,
1384 ) -> Result<crate::scopeguard::ScopeGuard<Self, impl FnMut(&mut Self)>, TryReserveError> {
1385 debug_assert!(self.items <= capacity);
1386
1387 // Allocate and initialize the new table.
1388 let mut new_table = RawTableInner::fallible_with_capacity(
1389 self.alloc.clone(),
1390 table_layout,
1391 capacity,
1392 fallibility,
1393 )?;
1394 new_table.growth_left -= self.items;
1395 new_table.items = self.items;
1396
1397 // The hash function may panic, in which case we simply free the new
1398 // table without dropping any elements that may have been copied into
1399 // it.
1400 //
1401 // This guard is also used to free the old table on success, see
1402 // the comment at the bottom of this function.
1403 Ok(guard(new_table, move |self_| {
1404 if !self_.is_empty_singleton() {
1405 self_.free_buckets(table_layout);
1406 }
1407 }))
1408 }
1409
1410 /// Reserves or rehashes to make room for `additional` more elements.
1411 ///
1412 /// This uses dynamic dispatch to reduce the amount of
1413 /// code generated, but it is eliminated by LLVM optimizations when inlined.
1414 #[allow(clippy::inline_always)]
1415 #[inline(always)]
1416 unsafe fn reserve_rehash_inner(
1417 &mut self,
1418 additional: usize,
1419 hasher: &dyn Fn(&mut Self, usize) -> u64,
1420 fallibility: Fallibility,
1421 layout: TableLayout,
1422 drop: Option<fn(*mut u8)>,
1423 ) -> Result<(), TryReserveError> {
1424 // Avoid `Option::ok_or_else` because it bloats LLVM IR.
1425 let new_items = match self.items.checked_add(additional) {
1426 Some(new_items) => new_items,
1427 None => return Err(fallibility.capacity_overflow()),
1428 };
1429 let full_capacity = bucket_mask_to_capacity(self.bucket_mask);
1430 if new_items <= full_capacity / 2 {
1431 // Rehash in-place without re-allocating if we have plenty of spare
1432 // capacity that is locked up due to DELETED entries.
1433 self.rehash_in_place(hasher, layout.size, drop);
1434 Ok(())
1435 } else {
1436 // Otherwise, conservatively resize to at least the next size up
1437 // to avoid churning deletes into frequent rehashes.
1438 self.resize_inner(
1439 usize::max(new_items, full_capacity + 1),
1440 hasher,
1441 fallibility,
1442 layout,
1443 )
1444 }
1445 }
1446
1447 /// Allocates a new table of a different size and moves the contents of the
1448 /// current table into it.
1449 ///
1450 /// This uses dynamic dispatch to reduce the amount of
1451 /// code generated, but it is eliminated by LLVM optimizations when inlined.
1452 #[allow(clippy::inline_always)]
1453 #[inline(always)]
1454 unsafe fn resize_inner(
1455 &mut self,
1456 capacity: usize,
1457 hasher: &dyn Fn(&mut Self, usize) -> u64,
1458 fallibility: Fallibility,
1459 layout: TableLayout,
1460 ) -> Result<(), TryReserveError> {
1461 let mut new_table = self.prepare_resize(layout, capacity, fallibility)?;
1462
1463 // Copy all elements to the new table.
1464 for i in 0..self.buckets() {
1465 if !self.is_bucket_full(i) {
1466 continue;
1467 }
1468
1469 // This may panic.
1470 let hash = hasher(self, i);
1471
1472 // We can use a simpler version of insert() here since:
1473 // - there are no DELETED entries.
1474 // - we know there is enough space in the table.
1475 // - all elements are unique.
1476 let (index, _) = new_table.prepare_insert_slot(hash);
1477
1478 ptr::copy_nonoverlapping(
1479 self.bucket_ptr(i, layout.size),
1480 new_table.bucket_ptr(index, layout.size),
1481 layout.size,
1482 );
1483 }
1484
1485 // We successfully copied all elements without panicking. Now replace
1486 // self with the new table. The old table will have its memory freed but
1487 // the items will not be dropped (since they have been moved into the
1488 // new table).
1489 mem::swap(self, &mut new_table);
1490
1491 Ok(())
1492 }
1493
1494 /// Rehashes the contents of the table in place (i.e. without changing the
1495 /// allocation).
1496 ///
1497 /// If `hasher` panics then some the table's contents may be lost.
1498 ///
1499 /// This uses dynamic dispatch to reduce the amount of
1500 /// code generated, but it is eliminated by LLVM optimizations when inlined.
1501 #[allow(clippy::inline_always)]
1502 #[cfg_attr(feature = "inline-more", inline(always))]
1503 #[cfg_attr(not(feature = "inline-more"), inline)]
1504 unsafe fn rehash_in_place(
1505 &mut self,
1506 hasher: &dyn Fn(&mut Self, usize) -> u64,
1507 size_of: usize,
1508 drop: Option<fn(*mut u8)>,
1509 ) {
1510 // If the hash function panics then properly clean up any elements
1511 // that we haven't rehashed yet. We unfortunately can't preserve the
1512 // element since we lost their hash and have no way of recovering it
1513 // without risking another panic.
1514 self.prepare_rehash_in_place();
1515
1516 let mut guard = guard(self, move |self_| {
1517 if let Some(drop) = drop {
1518 for i in 0..self_.buckets() {
1519 if *self_.ctrl(i) == DELETED {
1520 self_.set_ctrl(i, EMPTY);
1521 drop(self_.bucket_ptr(i, size_of));
1522 self_.items -= 1;
1523 }
1524 }
1525 }
1526 self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items;
1527 });
1528
1529 // At this point, DELETED elements are elements that we haven't
1530 // rehashed yet. Find them and re-insert them at their ideal
1531 // position.
1532 'outer: for i in 0..guard.buckets() {
1533 if *guard.ctrl(i) != DELETED {
1534 continue;
1535 }
1536
1537 let i_p = guard.bucket_ptr(i, size_of);
1538
1539 'inner: loop {
1540 // Hash the current item
1541 let hash = hasher(*guard, i);
1542
1543 // Search for a suitable place to put it
1544 let new_i = guard.find_insert_slot(hash);
1545
1546 // Probing works by scanning through all of the control
1547 // bytes in groups, which may not be aligned to the group
1548 // size. If both the new and old position fall within the
1549 // same unaligned group, then there is no benefit in moving
1550 // it and we can just continue to the next item.
1551 if likely(guard.is_in_same_group(i, new_i, hash)) {
1552 guard.set_ctrl_h2(i, hash);
1553 continue 'outer;
1554 }
1555
1556 let new_i_p = guard.bucket_ptr(new_i, size_of);
1557
1558 // We are moving the current item to a new position. Write
1559 // our H2 to the control byte of the new position.
1560 let prev_ctrl = guard.replace_ctrl_h2(new_i, hash);
1561 if prev_ctrl == EMPTY {
1562 guard.set_ctrl(i, EMPTY);
1563 // If the target slot is empty, simply move the current
1564 // element into the new slot and clear the old control
1565 // byte.
1566 ptr::copy_nonoverlapping(i_p, new_i_p, size_of);
1567 continue 'outer;
1568 } else {
1569 // If the target slot is occupied, swap the two elements
1570 // and then continue processing the element that we just
1571 // swapped into the old slot.
1572 debug_assert_eq!(prev_ctrl, DELETED);
1573 ptr::swap_nonoverlapping(i_p, new_i_p, size_of);
1574 continue 'inner;
1575 }
1576 }
1577 }
1578
1579 guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items;
1580
1581 mem::forget(guard);
1582 }
1583
1584 #[inline]
1585 unsafe fn free_buckets(&mut self, table_layout: TableLayout) {
1586 let (ptr, layout) = self.allocation_info(table_layout);
1587 self.alloc.deallocate(ptr, layout);
1588 }
1589
1590 #[inline]
1591 fn allocation_info(&self, table_layout: TableLayout) -> (NonNull<u8>, Layout) {
1592 debug_assert!(
1593 !self.is_empty_singleton(),
1594 "this function can only be called on non-empty tables"
1595 );
1596
1597 // Avoid `Option::unwrap_or_else` because it bloats LLVM IR.
1598 let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) {
1599 Some(lco) => lco,
1600 None => unsafe { hint::unreachable_unchecked() },
1601 };
1602 (
1603 unsafe { NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)) },
1604 layout,
1605 )
1606 }
1607
1608 #[cfg(feature = "raw")]
1609 fn allocation_info_or_zero(&self, table_layout: TableLayout) -> (NonNull<u8>, Layout) {
1610 if self.is_empty_singleton() {
1611 (NonNull::dangling(), Layout::new::<()>())
1612 } else {
1613 self.allocation_info(table_layout)
1614 }
1615 }
1616
1617 /// Marks all table buckets as empty without dropping their contents.
1618 #[inline]
1619 fn clear_no_drop(&mut self) {
1620 if !self.is_empty_singleton() {
1621 unsafe {
1622 self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes());
1623 }
1624 }
1625 self.items = 0;
1626 self.growth_left = bucket_mask_to_capacity(self.bucket_mask);
1627 }
1628
1629 #[inline]
1630 unsafe fn erase(&mut self, index: usize) {
1631 debug_assert!(self.is_bucket_full(index));
1632 let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask;
1633 let empty_before = Group::load(self.ctrl(index_before)).match_empty();
1634 let empty_after = Group::load(self.ctrl(index)).match_empty();
1635
1636 // If we are inside a continuous block of Group::WIDTH full or deleted
1637 // cells then a probe window may have seen a full block when trying to
1638 // insert. We therefore need to keep that block non-empty so that
1639 // lookups will continue searching to the next probe window.
1640 //
1641 // Note that in this context `leading_zeros` refers to the bytes at the
1642 // end of a group, while `trailing_zeros` refers to the bytes at the
1643 // beginning of a group.
1644 let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH {
1645 DELETED
1646 } else {
1647 self.growth_left += 1;
1648 EMPTY
1649 };
1650 self.set_ctrl(index, ctrl);
1651 self.items -= 1;
1652 }
1653 }
1654
1655 impl<T: Clone, A: Allocator + Clone> Clone for RawTable<T, A> {
1656 fn clone(&self) -> Self {
1657 if self.table.is_empty_singleton() {
1658 Self::new_in(self.table.alloc.clone())
1659 } else {
1660 unsafe {
1661 // Avoid `Result::ok_or_else` because it bloats LLVM IR.
1662 let new_table = match Self::new_uninitialized(
1663 self.table.alloc.clone(),
1664 self.table.buckets(),
1665 Fallibility::Infallible,
1666 ) {
1667 Ok(table) => table,
1668 Err(_) => hint::unreachable_unchecked(),
1669 };
1670
1671 // If cloning fails then we need to free the allocation for the
1672 // new table. However we don't run its drop since its control
1673 // bytes are not initialized yet.
1674 let mut guard = guard(ManuallyDrop::new(new_table), |new_table| {
1675 new_table.free_buckets();
1676 });
1677
1678 guard.clone_from_spec(self);
1679
1680 // Disarm the scope guard and return the newly created table.
1681 ManuallyDrop::into_inner(ScopeGuard::into_inner(guard))
1682 }
1683 }
1684 }
1685
1686 fn clone_from(&mut self, source: &Self) {
1687 if source.table.is_empty_singleton() {
1688 *self = Self::new_in(self.table.alloc.clone());
1689 } else {
1690 unsafe {
1691 // Make sure that if any panics occurs, we clear the table and
1692 // leave it in an empty state.
1693 let mut self_ = guard(self, |self_| {
1694 self_.clear_no_drop();
1695 });
1696
1697 // First, drop all our elements without clearing the control
1698 // bytes. If this panics then the scope guard will clear the
1699 // table, leaking any elements that were not dropped yet.
1700 //
1701 // This leak is unavoidable: we can't try dropping more elements
1702 // since this could lead to another panic and abort the process.
1703 self_.drop_elements();
1704
1705 // If necessary, resize our table to match the source.
1706 if self_.buckets() != source.buckets() {
1707 // Skip our drop by using ptr::write.
1708 if !self_.table.is_empty_singleton() {
1709 self_.free_buckets();
1710 }
1711 (&mut **self_ as *mut Self).write(
1712 // Avoid `Result::unwrap_or_else` because it bloats LLVM IR.
1713 match Self::new_uninitialized(
1714 self_.table.alloc.clone(),
1715 source.buckets(),
1716 Fallibility::Infallible,
1717 ) {
1718 Ok(table) => table,
1719 Err(_) => hint::unreachable_unchecked(),
1720 },
1721 );
1722 }
1723
1724 self_.clone_from_spec(source);
1725
1726 // Disarm the scope guard if cloning was successful.
1727 ScopeGuard::into_inner(self_);
1728 }
1729 }
1730 }
1731 }
1732
1733 /// Specialization of `clone_from` for `Copy` types
1734 trait RawTableClone {
1735 unsafe fn clone_from_spec(&mut self, source: &Self);
1736 }
1737 impl<T: Clone, A: Allocator + Clone> RawTableClone for RawTable<T, A> {
1738 default_fn! {
1739 #[cfg_attr(feature = "inline-more", inline)]
1740 unsafe fn clone_from_spec(&mut self, source: &Self) {
1741 self.clone_from_impl(source);
1742 }
1743 }
1744 }
1745 #[cfg(feature = "nightly")]
1746 impl<T: Copy, A: Allocator + Clone> RawTableClone for RawTable<T, A> {
1747 #[cfg_attr(feature = "inline-more", inline)]
1748 unsafe fn clone_from_spec(&mut self, source: &Self) {
1749 source
1750 .table
1751 .ctrl(0)
1752 .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes());
1753 source
1754 .data_start()
1755 .copy_to_nonoverlapping(self.data_start(), self.table.buckets());
1756
1757 self.table.items = source.table.items;
1758 self.table.growth_left = source.table.growth_left;
1759 }
1760 }
1761
1762 impl<T: Clone, A: Allocator + Clone> RawTable<T, A> {
1763 /// Common code for clone and clone_from. Assumes:
1764 /// - `self.buckets() == source.buckets()`.
1765 /// - Any existing elements have been dropped.
1766 /// - The control bytes are not initialized yet.
1767 #[cfg_attr(feature = "inline-more", inline)]
1768 unsafe fn clone_from_impl(&mut self, source: &Self) {
1769 // Copy the control bytes unchanged. We do this in a single pass
1770 source
1771 .table
1772 .ctrl(0)
1773 .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes());
1774
1775 // The cloning of elements may panic, in which case we need
1776 // to make sure we drop only the elements that have been
1777 // cloned so far.
1778 let mut guard = guard((0, &mut *self), |(index, self_)| {
1779 if Self::DATA_NEEDS_DROP && !self_.is_empty() {
1780 for i in 0..=*index {
1781 if self_.is_bucket_full(i) {
1782 self_.bucket(i).drop();
1783 }
1784 }
1785 }
1786 });
1787
1788 for from in source.iter() {
1789 let index = source.bucket_index(&from);
1790 let to = guard.1.bucket(index);
1791 to.write(from.as_ref().clone());
1792
1793 // Update the index in case we need to unwind.
1794 guard.0 = index;
1795 }
1796
1797 // Successfully cloned all items, no need to clean up.
1798 mem::forget(guard);
1799
1800 self.table.items = source.table.items;
1801 self.table.growth_left = source.table.growth_left;
1802 }
1803
1804 /// Variant of `clone_from` to use when a hasher is available.
1805 #[cfg(feature = "raw")]
1806 pub fn clone_from_with_hasher(&mut self, source: &Self, hasher: impl Fn(&T) -> u64) {
1807 // If we have enough capacity in the table, just clear it and insert
1808 // elements one by one. We don't do this if we have the same number of
1809 // buckets as the source since we can just copy the contents directly
1810 // in that case.
1811 if self.table.buckets() != source.table.buckets()
1812 && bucket_mask_to_capacity(self.table.bucket_mask) >= source.len()
1813 {
1814 self.clear();
1815
1816 let guard_self = guard(&mut *self, |self_| {
1817 // Clear the partially copied table if a panic occurs, otherwise
1818 // items and growth_left will be out of sync with the contents
1819 // of the table.
1820 self_.clear();
1821 });
1822
1823 unsafe {
1824 for item in source.iter() {
1825 // This may panic.
1826 let item = item.as_ref().clone();
1827 let hash = hasher(&item);
1828
1829 // We can use a simpler version of insert() here since:
1830 // - there are no DELETED entries.
1831 // - we know there is enough space in the table.
1832 // - all elements are unique.
1833 let (index, _) = guard_self.table.prepare_insert_slot(hash);
1834 guard_self.bucket(index).write(item);
1835 }
1836 }
1837
1838 // Successfully cloned all items, no need to clean up.
1839 mem::forget(guard_self);
1840
1841 self.table.items = source.table.items;
1842 self.table.growth_left -= source.table.items;
1843 } else {
1844 self.clone_from(source);
1845 }
1846 }
1847 }
1848
1849 impl<T, A: Allocator + Clone + Default> Default for RawTable<T, A> {
1850 #[inline]
1851 fn default() -> Self {
1852 Self::new_in(Default::default())
1853 }
1854 }
1855
1856 #[cfg(feature = "nightly")]
1857 unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable<T, A> {
1858 #[cfg_attr(feature = "inline-more", inline)]
1859 fn drop(&mut self) {
1860 if !self.table.is_empty_singleton() {
1861 unsafe {
1862 self.drop_elements();
1863 self.free_buckets();
1864 }
1865 }
1866 }
1867 }
1868 #[cfg(not(feature = "nightly"))]
1869 impl<T, A: Allocator + Clone> Drop for RawTable<T, A> {
1870 #[cfg_attr(feature = "inline-more", inline)]
1871 fn drop(&mut self) {
1872 if !self.table.is_empty_singleton() {
1873 unsafe {
1874 self.drop_elements();
1875 self.free_buckets();
1876 }
1877 }
1878 }
1879 }
1880
1881 impl<T, A: Allocator + Clone> IntoIterator for RawTable<T, A> {
1882 type Item = T;
1883 type IntoIter = RawIntoIter<T, A>;
1884
1885 #[cfg_attr(feature = "inline-more", inline)]
1886 fn into_iter(self) -> RawIntoIter<T, A> {
1887 unsafe {
1888 let iter = self.iter();
1889 self.into_iter_from(iter)
1890 }
1891 }
1892 }
1893
1894 /// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does
1895 /// not track an item count.
1896 pub(crate) struct RawIterRange<T> {
1897 // Mask of full buckets in the current group. Bits are cleared from this
1898 // mask as each element is processed.
1899 current_group: BitMask,
1900
1901 // Pointer to the buckets for the current group.
1902 data: Bucket<T>,
1903
1904 // Pointer to the next group of control bytes,
1905 // Must be aligned to the group size.
1906 next_ctrl: *const u8,
1907
1908 // Pointer one past the last control byte of this range.
1909 end: *const u8,
1910 }
1911
1912 impl<T> RawIterRange<T> {
1913 /// Returns a `RawIterRange` covering a subset of a table.
1914 ///
1915 /// The control byte address must be aligned to the group size.
1916 #[cfg_attr(feature = "inline-more", inline)]
1917 unsafe fn new(ctrl: *const u8, data: Bucket<T>, len: usize) -> Self {
1918 debug_assert_ne!(len, 0);
1919 debug_assert_eq!(ctrl as usize % Group::WIDTH, 0);
1920 let end = ctrl.add(len);
1921
1922 // Load the first group and advance ctrl to point to the next group
1923 let current_group = Group::load_aligned(ctrl).match_full();
1924 let next_ctrl = ctrl.add(Group::WIDTH);
1925
1926 Self {
1927 current_group,
1928 data,
1929 next_ctrl,
1930 end,
1931 }
1932 }
1933
1934 /// Splits a `RawIterRange` into two halves.
1935 ///
1936 /// Returns `None` if the remaining range is smaller than or equal to the
1937 /// group width.
1938 #[cfg_attr(feature = "inline-more", inline)]
1939 #[cfg(feature = "rayon")]
1940 pub(crate) fn split(mut self) -> (Self, Option<RawIterRange<T>>) {
1941 unsafe {
1942 if self.end <= self.next_ctrl {
1943 // Nothing to split if the group that we are current processing
1944 // is the last one.
1945 (self, None)
1946 } else {
1947 // len is the remaining number of elements after the group that
1948 // we are currently processing. It must be a multiple of the
1949 // group size (small tables are caught by the check above).
1950 let len = offset_from(self.end, self.next_ctrl);
1951 debug_assert_eq!(len % Group::WIDTH, 0);
1952
1953 // Split the remaining elements into two halves, but round the
1954 // midpoint down in case there is an odd number of groups
1955 // remaining. This ensures that:
1956 // - The tail is at least 1 group long.
1957 // - The split is roughly even considering we still have the
1958 // current group to process.
1959 let mid = (len / 2) & !(Group::WIDTH - 1);
1960
1961 let tail = Self::new(
1962 self.next_ctrl.add(mid),
1963 self.data.next_n(Group::WIDTH).next_n(mid),
1964 len - mid,
1965 );
1966 debug_assert_eq!(
1967 self.data.next_n(Group::WIDTH).next_n(mid).ptr,
1968 tail.data.ptr
1969 );
1970 debug_assert_eq!(self.end, tail.end);
1971 self.end = self.next_ctrl.add(mid);
1972 debug_assert_eq!(self.end.add(Group::WIDTH), tail.next_ctrl);
1973 (self, Some(tail))
1974 }
1975 }
1976 }
1977
1978 /// # Safety
1979 /// If DO_CHECK_PTR_RANGE is false, caller must ensure that we never try to iterate
1980 /// after yielding all elements.
1981 #[cfg_attr(feature = "inline-more", inline)]
1982 unsafe fn next_impl<const DO_CHECK_PTR_RANGE: bool>(&mut self) -> Option<Bucket<T>> {
1983 loop {
1984 if let Some(index) = self.current_group.lowest_set_bit() {
1985 self.current_group = self.current_group.remove_lowest_bit();
1986 return Some(self.data.next_n(index));
1987 }
1988
1989 if DO_CHECK_PTR_RANGE && self.next_ctrl >= self.end {
1990 return None;
1991 }
1992
1993 // We might read past self.end up to the next group boundary,
1994 // but this is fine because it only occurs on tables smaller
1995 // than the group size where the trailing control bytes are all
1996 // EMPTY. On larger tables self.end is guaranteed to be aligned
1997 // to the group size (since tables are power-of-two sized).
1998 self.current_group = Group::load_aligned(self.next_ctrl).match_full();
1999 self.data = self.data.next_n(Group::WIDTH);
2000 self.next_ctrl = self.next_ctrl.add(Group::WIDTH);
2001 }
2002 }
2003 }
2004
2005 // We make raw iterators unconditionally Send and Sync, and let the PhantomData
2006 // in the actual iterator implementations determine the real Send/Sync bounds.
2007 unsafe impl<T> Send for RawIterRange<T> {}
2008 unsafe impl<T> Sync for RawIterRange<T> {}
2009
2010 impl<T> Clone for RawIterRange<T> {
2011 #[cfg_attr(feature = "inline-more", inline)]
2012 fn clone(&self) -> Self {
2013 Self {
2014 data: self.data.clone(),
2015 next_ctrl: self.next_ctrl,
2016 current_group: self.current_group,
2017 end: self.end,
2018 }
2019 }
2020 }
2021
2022 impl<T> Iterator for RawIterRange<T> {
2023 type Item = Bucket<T>;
2024
2025 #[cfg_attr(feature = "inline-more", inline)]
2026 fn next(&mut self) -> Option<Bucket<T>> {
2027 unsafe {
2028 // SAFETY: We set checker flag to true.
2029 self.next_impl::<true>()
2030 }
2031 }
2032
2033 #[inline]
2034 fn size_hint(&self) -> (usize, Option<usize>) {
2035 // We don't have an item count, so just guess based on the range size.
2036 let remaining_buckets = if self.end > self.next_ctrl {
2037 unsafe { offset_from(self.end, self.next_ctrl) }
2038 } else {
2039 0
2040 };
2041
2042 // Add a group width to include the group we are currently processing.
2043 (0, Some(Group::WIDTH + remaining_buckets))
2044 }
2045 }
2046
2047 impl<T> FusedIterator for RawIterRange<T> {}
2048
2049 /// Iterator which returns a raw pointer to every full bucket in the table.
2050 ///
2051 /// For maximum flexibility this iterator is not bound by a lifetime, but you
2052 /// must observe several rules when using it:
2053 /// - You must not free the hash table while iterating (including via growing/shrinking).
2054 /// - It is fine to erase a bucket that has been yielded by the iterator.
2055 /// - Erasing a bucket that has not yet been yielded by the iterator may still
2056 /// result in the iterator yielding that bucket (unless `reflect_remove` is called).
2057 /// - It is unspecified whether an element inserted after the iterator was
2058 /// created will be yielded by that iterator (unless `reflect_insert` is called).
2059 /// - The order in which the iterator yields bucket is unspecified and may
2060 /// change in the future.
2061 pub struct RawIter<T> {
2062 pub(crate) iter: RawIterRange<T>,
2063 items: usize,
2064 }
2065
2066 impl<T> RawIter<T> {
2067 const DATA_NEEDS_DROP: bool = mem::needs_drop::<T>();
2068
2069 /// Refresh the iterator so that it reflects a removal from the given bucket.
2070 ///
2071 /// For the iterator to remain valid, this method must be called once
2072 /// for each removed bucket before `next` is called again.
2073 ///
2074 /// This method should be called _before_ the removal is made. It is not necessary to call this
2075 /// method if you are removing an item that this iterator yielded in the past.
2076 #[cfg(feature = "raw")]
2077 pub fn reflect_remove(&mut self, b: &Bucket<T>) {
2078 self.reflect_toggle_full(b, false);
2079 }
2080
2081 /// Refresh the iterator so that it reflects an insertion into the given bucket.
2082 ///
2083 /// For the iterator to remain valid, this method must be called once
2084 /// for each insert before `next` is called again.
2085 ///
2086 /// This method does not guarantee that an insertion of a bucket with a greater
2087 /// index than the last one yielded will be reflected in the iterator.
2088 ///
2089 /// This method should be called _after_ the given insert is made.
2090 #[cfg(feature = "raw")]
2091 pub fn reflect_insert(&mut self, b: &Bucket<T>) {
2092 self.reflect_toggle_full(b, true);
2093 }
2094
2095 /// Refresh the iterator so that it reflects a change to the state of the given bucket.
2096 #[cfg(feature = "raw")]
2097 fn reflect_toggle_full(&mut self, b: &Bucket<T>, is_insert: bool) {
2098 unsafe {
2099 if b.as_ptr() > self.iter.data.as_ptr() {
2100 // The iterator has already passed the bucket's group.
2101 // So the toggle isn't relevant to this iterator.
2102 return;
2103 }
2104
2105 if self.iter.next_ctrl < self.iter.end
2106 && b.as_ptr() <= self.iter.data.next_n(Group::WIDTH).as_ptr()
2107 {
2108 // The iterator has not yet reached the bucket's group.
2109 // We don't need to reload anything, but we do need to adjust the item count.
2110
2111 if cfg!(debug_assertions) {
2112 // Double-check that the user isn't lying to us by checking the bucket state.
2113 // To do that, we need to find its control byte. We know that self.iter.data is
2114 // at self.iter.next_ctrl - Group::WIDTH, so we work from there:
2115 let offset = offset_from(self.iter.data.as_ptr(), b.as_ptr());
2116 let ctrl = self.iter.next_ctrl.sub(Group::WIDTH).add(offset);
2117 // This method should be called _before_ a removal, or _after_ an insert,
2118 // so in both cases the ctrl byte should indicate that the bucket is full.
2119 assert!(is_full(*ctrl));
2120 }
2121
2122 if is_insert {
2123 self.items += 1;
2124 } else {
2125 self.items -= 1;
2126 }
2127
2128 return;
2129 }
2130
2131 // The iterator is at the bucket group that the toggled bucket is in.
2132 // We need to do two things:
2133 //
2134 // - Determine if the iterator already yielded the toggled bucket.
2135 // If it did, we're done.
2136 // - Otherwise, update the iterator cached group so that it won't
2137 // yield a to-be-removed bucket, or _will_ yield a to-be-added bucket.
2138 // We'll also need to update the item count accordingly.
2139 if let Some(index) = self.iter.current_group.lowest_set_bit() {
2140 let next_bucket = self.iter.data.next_n(index);
2141 if b.as_ptr() > next_bucket.as_ptr() {
2142 // The toggled bucket is "before" the bucket the iterator would yield next. We
2143 // therefore don't need to do anything --- the iterator has already passed the
2144 // bucket in question.
2145 //
2146 // The item count must already be correct, since a removal or insert "prior" to
2147 // the iterator's position wouldn't affect the item count.
2148 } else {
2149 // The removed bucket is an upcoming bucket. We need to make sure it does _not_
2150 // get yielded, and also that it's no longer included in the item count.
2151 //
2152 // NOTE: We can't just reload the group here, both since that might reflect
2153 // inserts we've already passed, and because that might inadvertently unset the
2154 // bits for _other_ removals. If we do that, we'd have to also decrement the
2155 // item count for those other bits that we unset. But the presumably subsequent
2156 // call to reflect for those buckets might _also_ decrement the item count.
2157 // Instead, we _just_ flip the bit for the particular bucket the caller asked
2158 // us to reflect.
2159 let our_bit = offset_from(self.iter.data.as_ptr(), b.as_ptr());
2160 let was_full = self.iter.current_group.flip(our_bit);
2161 debug_assert_ne!(was_full, is_insert);
2162
2163 if is_insert {
2164 self.items += 1;
2165 } else {
2166 self.items -= 1;
2167 }
2168
2169 if cfg!(debug_assertions) {
2170 if b.as_ptr() == next_bucket.as_ptr() {
2171 // The removed bucket should no longer be next
2172 debug_assert_ne!(self.iter.current_group.lowest_set_bit(), Some(index));
2173 } else {
2174 // We should not have changed what bucket comes next.
2175 debug_assert_eq!(self.iter.current_group.lowest_set_bit(), Some(index));
2176 }
2177 }
2178 }
2179 } else {
2180 // We must have already iterated past the removed item.
2181 }
2182 }
2183 }
2184
2185 unsafe fn drop_elements(&mut self) {
2186 if Self::DATA_NEEDS_DROP && self.len() != 0 {
2187 for item in self {
2188 item.drop();
2189 }
2190 }
2191 }
2192 }
2193
2194 impl<T> Clone for RawIter<T> {
2195 #[cfg_attr(feature = "inline-more", inline)]
2196 fn clone(&self) -> Self {
2197 Self {
2198 iter: self.iter.clone(),
2199 items: self.items,
2200 }
2201 }
2202 }
2203
2204 impl<T> Iterator for RawIter<T> {
2205 type Item = Bucket<T>;
2206
2207 #[cfg_attr(feature = "inline-more", inline)]
2208 fn next(&mut self) -> Option<Bucket<T>> {
2209 // Inner iterator iterates over buckets
2210 // so it can do unnecessary work if we already yielded all items.
2211 if self.items == 0 {
2212 return None;
2213 }
2214
2215 let nxt = unsafe {
2216 // SAFETY: We check number of items to yield using `items` field.
2217 self.iter.next_impl::<false>()
2218 };
2219
2220 if nxt.is_some() {
2221 self.items -= 1;
2222 }
2223
2224 nxt
2225 }
2226
2227 #[inline]
2228 fn size_hint(&self) -> (usize, Option<usize>) {
2229 (self.items, Some(self.items))
2230 }
2231 }
2232
2233 impl<T> ExactSizeIterator for RawIter<T> {}
2234 impl<T> FusedIterator for RawIter<T> {}
2235
2236 /// Iterator which consumes a table and returns elements.
2237 pub struct RawIntoIter<T, A: Allocator + Clone = Global> {
2238 iter: RawIter<T>,
2239 allocation: Option<(NonNull<u8>, Layout)>,
2240 marker: PhantomData<T>,
2241 alloc: A,
2242 }
2243
2244 impl<T, A: Allocator + Clone> RawIntoIter<T, A> {
2245 #[cfg_attr(feature = "inline-more", inline)]
2246 pub fn iter(&self) -> RawIter<T> {
2247 self.iter.clone()
2248 }
2249 }
2250
2251 unsafe impl<T, A: Allocator + Clone> Send for RawIntoIter<T, A>
2252 where
2253 T: Send,
2254 A: Send,
2255 {
2256 }
2257 unsafe impl<T, A: Allocator + Clone> Sync for RawIntoIter<T, A>
2258 where
2259 T: Sync,
2260 A: Sync,
2261 {
2262 }
2263
2264 #[cfg(feature = "nightly")]
2265 unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter<T, A> {
2266 #[cfg_attr(feature = "inline-more", inline)]
2267 fn drop(&mut self) {
2268 unsafe {
2269 // Drop all remaining elements
2270 self.iter.drop_elements();
2271
2272 // Free the table
2273 if let Some((ptr, layout)) = self.allocation {
2274 self.alloc.deallocate(ptr, layout);
2275 }
2276 }
2277 }
2278 }
2279 #[cfg(not(feature = "nightly"))]
2280 impl<T, A: Allocator + Clone> Drop for RawIntoIter<T, A> {
2281 #[cfg_attr(feature = "inline-more", inline)]
2282 fn drop(&mut self) {
2283 unsafe {
2284 // Drop all remaining elements
2285 self.iter.drop_elements();
2286
2287 // Free the table
2288 if let Some((ptr, layout)) = self.allocation {
2289 self.alloc.deallocate(ptr, layout);
2290 }
2291 }
2292 }
2293 }
2294
2295 impl<T, A: Allocator + Clone> Iterator for RawIntoIter<T, A> {
2296 type Item = T;
2297
2298 #[cfg_attr(feature = "inline-more", inline)]
2299 fn next(&mut self) -> Option<T> {
2300 unsafe { Some(self.iter.next()?.read()) }
2301 }
2302
2303 #[inline]
2304 fn size_hint(&self) -> (usize, Option<usize>) {
2305 self.iter.size_hint()
2306 }
2307 }
2308
2309 impl<T, A: Allocator + Clone> ExactSizeIterator for RawIntoIter<T, A> {}
2310 impl<T, A: Allocator + Clone> FusedIterator for RawIntoIter<T, A> {}
2311
2312 /// Iterator which consumes elements without freeing the table storage.
2313 pub struct RawDrain<'a, T, A: Allocator + Clone = Global> {
2314 iter: RawIter<T>,
2315
2316 // The table is moved into the iterator for the duration of the drain. This
2317 // ensures that an empty table is left if the drain iterator is leaked
2318 // without dropping.
2319 table: ManuallyDrop<RawTable<T, A>>,
2320 orig_table: NonNull<RawTable<T, A>>,
2321
2322 // We don't use a &'a mut RawTable<T> because we want RawDrain to be
2323 // covariant over T.
2324 marker: PhantomData<&'a RawTable<T, A>>,
2325 }
2326
2327 impl<T, A: Allocator + Clone> RawDrain<'_, T, A> {
2328 #[cfg_attr(feature = "inline-more", inline)]
2329 pub fn iter(&self) -> RawIter<T> {
2330 self.iter.clone()
2331 }
2332 }
2333
2334 unsafe impl<T, A: Allocator + Copy> Send for RawDrain<'_, T, A>
2335 where
2336 T: Send,
2337 A: Send,
2338 {
2339 }
2340 unsafe impl<T, A: Allocator + Copy> Sync for RawDrain<'_, T, A>
2341 where
2342 T: Sync,
2343 A: Sync,
2344 {
2345 }
2346
2347 impl<T, A: Allocator + Clone> Drop for RawDrain<'_, T, A> {
2348 #[cfg_attr(feature = "inline-more", inline)]
2349 fn drop(&mut self) {
2350 unsafe {
2351 // Drop all remaining elements. Note that this may panic.
2352 self.iter.drop_elements();
2353
2354 // Reset the contents of the table now that all elements have been
2355 // dropped.
2356 self.table.clear_no_drop();
2357
2358 // Move the now empty table back to its original location.
2359 self.orig_table
2360 .as_ptr()
2361 .copy_from_nonoverlapping(&*self.table, 1);
2362 }
2363 }
2364 }
2365
2366 impl<T, A: Allocator + Clone> Iterator for RawDrain<'_, T, A> {
2367 type Item = T;
2368
2369 #[cfg_attr(feature = "inline-more", inline)]
2370 fn next(&mut self) -> Option<T> {
2371 unsafe {
2372 let item = self.iter.next()?;
2373 Some(item.read())
2374 }
2375 }
2376
2377 #[inline]
2378 fn size_hint(&self) -> (usize, Option<usize>) {
2379 self.iter.size_hint()
2380 }
2381 }
2382
2383 impl<T, A: Allocator + Clone> ExactSizeIterator for RawDrain<'_, T, A> {}
2384 impl<T, A: Allocator + Clone> FusedIterator for RawDrain<'_, T, A> {}
2385
2386 /// Iterator over occupied buckets that could match a given hash.
2387 ///
2388 /// `RawTable` only stores 7 bits of the hash value, so this iterator may return
2389 /// items that have a hash value different than the one provided. You should
2390 /// always validate the returned values before using them.
2391 pub struct RawIterHash<'a, T, A: Allocator + Clone = Global> {
2392 inner: RawIterHashInner<'a, A>,
2393 _marker: PhantomData<T>,
2394 }
2395
2396 struct RawIterHashInner<'a, A: Allocator + Clone> {
2397 table: &'a RawTableInner<A>,
2398
2399 // The top 7 bits of the hash.
2400 h2_hash: u8,
2401
2402 // The sequence of groups to probe in the search.
2403 probe_seq: ProbeSeq,
2404
2405 group: Group,
2406
2407 // The elements within the group with a matching h2-hash.
2408 bitmask: BitMaskIter,
2409 }
2410
2411 impl<'a, T, A: Allocator + Clone> RawIterHash<'a, T, A> {
2412 #[cfg_attr(feature = "inline-more", inline)]
2413 #[cfg(feature = "raw")]
2414 fn new(table: &'a RawTable<T, A>, hash: u64) -> Self {
2415 RawIterHash {
2416 inner: RawIterHashInner::new(&table.table, hash),
2417 _marker: PhantomData,
2418 }
2419 }
2420 }
2421 impl<'a, A: Allocator + Clone> RawIterHashInner<'a, A> {
2422 #[cfg_attr(feature = "inline-more", inline)]
2423 #[cfg(feature = "raw")]
2424 fn new(table: &'a RawTableInner<A>, hash: u64) -> Self {
2425 unsafe {
2426 let h2_hash = h2(hash);
2427 let probe_seq = table.probe_seq(hash);
2428 let group = Group::load(table.ctrl(probe_seq.pos));
2429 let bitmask = group.match_byte(h2_hash).into_iter();
2430
2431 RawIterHashInner {
2432 table,
2433 h2_hash,
2434 probe_seq,
2435 group,
2436 bitmask,
2437 }
2438 }
2439 }
2440 }
2441
2442 impl<'a, T, A: Allocator + Clone> Iterator for RawIterHash<'a, T, A> {
2443 type Item = Bucket<T>;
2444
2445 fn next(&mut self) -> Option<Bucket<T>> {
2446 unsafe {
2447 match self.inner.next() {
2448 Some(index) => Some(self.inner.table.bucket(index)),
2449 None => None,
2450 }
2451 }
2452 }
2453 }
2454
2455 impl<'a, A: Allocator + Clone> Iterator for RawIterHashInner<'a, A> {
2456 type Item = usize;
2457
2458 fn next(&mut self) -> Option<Self::Item> {
2459 unsafe {
2460 loop {
2461 if let Some(bit) = self.bitmask.next() {
2462 let index = (self.probe_seq.pos + bit) & self.table.bucket_mask;
2463 return Some(index);
2464 }
2465 if likely(self.group.match_empty().any_bit_set()) {
2466 return None;
2467 }
2468 self.probe_seq.move_next(self.table.bucket_mask);
2469 self.group = Group::load(self.table.ctrl(self.probe_seq.pos));
2470 self.bitmask = self.group.match_byte(self.h2_hash).into_iter();
2471 }
2472 }
2473 }
2474 }
2475
2476 #[cfg(test)]
2477 mod test_map {
2478 use super::*;
2479
2480 fn rehash_in_place<T>(table: &mut RawTable<T>, hasher: impl Fn(&T) -> u64) {
2481 unsafe {
2482 table.table.rehash_in_place(
2483 &|table, index| hasher(table.bucket::<T>(index).as_ref()),
2484 mem::size_of::<T>(),
2485 if mem::needs_drop::<T>() {
2486 Some(mem::transmute(ptr::drop_in_place::<T> as unsafe fn(*mut T)))
2487 } else {
2488 None
2489 },
2490 );
2491 }
2492 }
2493
2494 #[test]
2495 fn rehash() {
2496 let mut table = RawTable::new();
2497 let hasher = |i: &u64| *i;
2498 for i in 0..100 {
2499 table.insert(i, i, hasher);
2500 }
2501
2502 for i in 0..100 {
2503 unsafe {
2504 assert_eq!(table.find(i, |x| *x == i).map(|b| b.read()), Some(i));
2505 }
2506 assert!(table.find(i + 100, |x| *x == i + 100).is_none());
2507 }
2508
2509 rehash_in_place(&mut table, hasher);
2510
2511 for i in 0..100 {
2512 unsafe {
2513 assert_eq!(table.find(i, |x| *x == i).map(|b| b.read()), Some(i));
2514 }
2515 assert!(table.find(i + 100, |x| *x == i + 100).is_none());
2516 }
2517 }
2518 }