hashbrown/raw.rs
1use crate::TryReserveError;
2use crate::control::{BitMaskIter, Group, Tag, TagSliceExt};
3use crate::scopeguard::{ScopeGuard, guard};
4use crate::util::{likely, unlikely};
5use core::alloc::Layout;
6use core::array;
7use core::iter::FusedIterator;
8use core::marker::PhantomData;
9use core::mem::{self, ManuallyDrop};
10use core::ptr;
11use core::ptr::NonNull;
12use core::slice;
13use stdalloc::alloc::handle_alloc_error;
14
15#[cfg(test)]
16use crate::alloc::AllocError;
17use crate::alloc::{Allocator, Global, do_alloc};
18
19#[inline]
20unsafe fn offset_from<T>(to: *const T, from: *const T) -> usize {
21 unsafe { to.offset_from(from) as usize }
22}
23
24/// Whether memory allocation errors should return an error or abort.
25#[derive(Copy, Clone)]
26enum Fallibility {
27 Fallible,
28 Infallible,
29}
30
31impl Fallibility {
32 /// Error to return on capacity overflow.
33 #[cfg_attr(feature = "inline-more", inline)]
34 fn capacity_overflow(self) -> TryReserveError {
35 match self {
36 Fallibility::Fallible => TryReserveError::CapacityOverflow,
37 Fallibility::Infallible => panic!("Hash table capacity overflow"),
38 }
39 }
40
41 /// Error to return on allocation error.
42 #[cfg_attr(feature = "inline-more", inline)]
43 fn alloc_err(self, layout: Layout) -> TryReserveError {
44 match self {
45 Fallibility::Fallible => TryReserveError::AllocError { layout },
46 Fallibility::Infallible => handle_alloc_error(layout),
47 }
48 }
49}
50
51trait SizedTypeProperties: Sized {
52 const IS_ZERO_SIZED: bool = size_of::<Self>() == 0;
53 const NEEDS_DROP: bool = mem::needs_drop::<Self>();
54}
55
56impl<T> SizedTypeProperties for T {}
57
58/// Primary hash function, used to select the initial bucket to probe from.
59#[inline]
60#[expect(clippy::cast_possible_truncation)]
61fn h1(hash: u64) -> usize {
62 // On 32-bit platforms we simply ignore the higher hash bits.
63 hash as usize
64}
65
66/// Probe sequence based on triangular numbers, which is guaranteed (since our
67/// table size is a power of two) to visit every group of elements exactly once.
68///
69/// A triangular probe has us jump by 1 more group every time. So first we
70/// jump by 1 group (meaning we just continue our linear scan), then 2 groups
71/// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on.
72///
73/// Proof that the probe will visit every group in the table:
74/// <https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/>
75#[derive(Clone)]
76struct ProbeSeq {
77 pos: usize,
78 stride: usize,
79}
80
81impl ProbeSeq {
82 #[inline]
83 fn move_next(&mut self, bucket_mask: usize) {
84 // We should have found an empty bucket by now and ended the probe.
85 debug_assert!(
86 self.stride <= bucket_mask,
87 "Went past end of probe sequence"
88 );
89
90 self.stride = self.stride.wrapping_add(Group::WIDTH);
91 self.pos = self.pos.wrapping_add(self.stride) & bucket_mask;
92 }
93}
94
95/// Returns the number of buckets needed to hold the given number of items,
96/// taking the maximum load factor into account.
97///
98/// Returns `None` if an overflow occurs.
99///
100/// This ensures that `buckets * table_layout.size >= table_layout.ctrl_align`.
101// Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258
102#[cfg_attr(target_os = "emscripten", inline(never))]
103#[cfg_attr(not(target_os = "emscripten"), inline)]
104fn capacity_to_buckets(cap: usize, table_layout: TableLayout) -> Option<usize> {
105 debug_assert_ne!(cap, 0);
106
107 // For small tables we require at least 1 empty bucket so that lookups are
108 // guaranteed to terminate if an element doesn't exist in the table.
109 if cap < 15 {
110 // Consider a small TableLayout like { size: 1, ctrl_align: 16 } on a
111 // platform with Group::WIDTH of 16 (like x86_64 with SSE2). For small
112 // bucket sizes, this ends up wasting quite a few bytes just to pad to
113 // the relatively larger ctrl_align:
114 //
115 // | capacity | buckets | bytes allocated | bytes per item |
116 // | -------- | ------- | --------------- | -------------- |
117 // | 3 | 4 | 36 | (Yikes!) 12.0 |
118 // | 7 | 8 | 40 | (Poor) 5.7 |
119 // | 14 | 16 | 48 | 3.4 |
120 // | 28 | 32 | 80 | 3.3 |
121 //
122 // In general, buckets * table_layout.size >= table_layout.ctrl_align
123 // must be true to avoid these edges. This is implemented by adjusting
124 // the minimum capacity upwards for small items. This code only needs
125 // to handle ctrl_align which are less than or equal to Group::WIDTH,
126 // because valid layout sizes are always a multiple of the alignment,
127 // so anything with alignment over the Group::WIDTH won't hit this edge
128 // case.
129
130 // This is brittle, e.g. if we ever add 32 byte groups, it will select
131 // 3 regardless of the table_layout.size.
132 let min_cap = match (Group::WIDTH, table_layout.size) {
133 (16, 0..=1) => 14,
134 (16, 2..=3) | (8, 0..=1) => 7,
135 _ => 3,
136 };
137 let cap = min_cap.max(cap);
138 // We don't bother with a table size of 2 buckets since that can only
139 // hold a single element. Instead, we skip directly to a 4 bucket table
140 // which can hold 3 elements.
141 let buckets = if cap < 4 {
142 4
143 } else if cap < 8 {
144 8
145 } else {
146 16
147 };
148 ensure_bucket_bytes_at_least_ctrl_align(table_layout, buckets);
149 return Some(buckets);
150 }
151
152 // Otherwise require 1/8 buckets to be empty (87.5% load)
153 //
154 // Be careful when modifying this, calculate_layout relies on the
155 // overflow check here.
156 let adjusted_cap = cap.checked_mul(8)? / 7;
157
158 // Any overflows will have been caught by the checked_mul. Also, any
159 // rounding errors from the division above will be cleaned up by
160 // next_power_of_two (which can't overflow because of the previous division).
161 let buckets = adjusted_cap.next_power_of_two();
162 ensure_bucket_bytes_at_least_ctrl_align(table_layout, buckets);
163 Some(buckets)
164}
165
166// `maximum_buckets_in` relies on the property that for non-ZST `T`, any
167// chosen `buckets` will satisfy `buckets * table_layout.size >=
168// table_layout.ctrl_align`, so `calculate_layout_for` does not need to add
169// extra padding beyond `table_layout.size * buckets`. If small-table bucket
170// selection or growth policy changes, revisit `maximum_buckets_in`.
171#[inline]
172fn ensure_bucket_bytes_at_least_ctrl_align(table_layout: TableLayout, buckets: usize) {
173 if table_layout.size != 0 {
174 let prod = table_layout.size.saturating_mul(buckets);
175 debug_assert!(prod >= table_layout.ctrl_align);
176 }
177}
178
179/// Returns the maximum effective capacity for the given bucket mask, taking
180/// the maximum load factor into account.
181#[inline]
182fn bucket_mask_to_capacity(bucket_mask: usize) -> usize {
183 if bucket_mask < 8 {
184 // For tables with 1/2/4/8 buckets, we always reserve one empty slot.
185 // Keep in mind that the bucket mask is one less than the bucket count.
186 bucket_mask
187 } else {
188 // `bucket_mask` is bounded by the maximum allocation size, so it can
189 // never be `usize::MAX` and the `+ 1` below cannot overflow.
190 debug_assert!(bucket_mask != usize::MAX);
191 // For larger tables we reserve 12.5% of the slots as empty.
192 ((bucket_mask + 1) / 8) * 7
193 }
194}
195
196/// Helper which allows the max calculation for `ctrl_align` to be statically computed for each `T`
197/// while keeping the rest of `calculate_layout_for` independent of `T`
198#[derive(Copy, Clone)]
199struct TableLayout {
200 size: usize,
201 ctrl_align: usize,
202}
203
204impl TableLayout {
205 #[inline]
206 const fn new<T>() -> Self {
207 let layout = Layout::new::<T>();
208 Self {
209 size: layout.size(),
210 ctrl_align: if layout.align() > Group::WIDTH {
211 layout.align()
212 } else {
213 Group::WIDTH
214 },
215 }
216 }
217
218 #[inline]
219 fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> {
220 debug_assert!(buckets.is_power_of_two());
221
222 let TableLayout { size, ctrl_align } = self;
223 // Manual layout calculation since Layout methods are not yet stable.
224 let ctrl_offset =
225 size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1);
226 let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?;
227
228 // We need an additional check to ensure that the allocation doesn't
229 // exceed `isize::MAX` (https://github.com/rust-lang/rust/pull/95295).
230 if len > isize::MAX as usize - (ctrl_align - 1) {
231 return None;
232 }
233
234 Some((
235 unsafe { Layout::from_size_align_unchecked(len, ctrl_align) },
236 ctrl_offset,
237 ))
238 }
239}
240
241/// A reference to a hash table bucket containing a `T`.
242///
243/// This is usually just a pointer to the element itself. However if the element
244/// is a ZST, then we instead track the index of the element in the table so
245/// that `erase` works properly.
246pub(crate) struct Bucket<T> {
247 // Actually it is pointer to next element than element itself
248 // this is needed to maintain pointer arithmetic invariants
249 // keeping direct pointer to element introduces difficulty.
250 // Using `NonNull` for variance and niche layout
251 ptr: NonNull<T>,
252}
253
254// This Send impl is needed for rayon support. This is safe since Bucket is
255// never exposed in a public API.
256unsafe impl<T> Send for Bucket<T> {}
257
258impl<T> Clone for Bucket<T> {
259 #[inline]
260 fn clone(&self) -> Self {
261 Self { ptr: self.ptr }
262 }
263}
264
265impl<T> Bucket<T> {
266 /// Creates a [`Bucket`] that contain pointer to the data.
267 /// The pointer calculation is performed by calculating the
268 /// offset from given `base` pointer (convenience for
269 /// `base.as_ptr().sub(index)`).
270 ///
271 /// `index` is in units of `T`; e.g., an `index` of 3 represents a pointer
272 /// offset of `3 * size_of::<T>()` bytes.
273 ///
274 /// If the `T` is a ZST, then we instead track the index of the element
275 /// in the table so that `erase` works properly (return
276 /// `NonNull::new_unchecked((index + 1) as *mut T)`)
277 ///
278 /// # Safety
279 ///
280 /// If `size_of::<T>() != 0`, then the safety rules are directly derived
281 /// from the safety rules for [`<*mut T>::sub`] method of `*mut T` and the safety
282 /// rules of [`NonNull::new_unchecked`] function.
283 ///
284 /// Thus, in order to uphold the safety contracts for the [`<*mut T>::sub`] method
285 /// and [`NonNull::new_unchecked`] function, as well as for the correct
286 /// logic of the work of this crate, the following rules are necessary and
287 /// sufficient:
288 ///
289 /// * the `base` pointer must not be `dangling` and must points to the
290 /// end of the first `value element` from the `data part` of the table, i.e.
291 /// must be the pointer that returned by [`RawTable::data_end`] or by
292 /// [`RawTableInner::data_end<T>`];
293 ///
294 /// * `index` must not be greater than `RawTableInner.bucket_mask`, i.e.
295 /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)`
296 /// must be no greater than the number returned by the function
297 /// [`RawTable::num_buckets`] or [`RawTableInner::num_buckets`].
298 ///
299 /// If `size_of::<T>() == 0`, then the only requirement is that the
300 /// `index` must not be greater than `RawTableInner.bucket_mask`, i.e.
301 /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)`
302 /// must be no greater than the number returned by the function
303 /// [`RawTable::num_buckets`] or [`RawTableInner::num_buckets`].
304 #[inline]
305 unsafe fn from_base_index(base: NonNull<T>, index: usize) -> Self {
306 // If size_of::<T>() != 0 then return a pointer to an `element` in
307 // the data part of the table (we start counting from "0", so that
308 // in the expression T[last], the "last" index actually one less than the
309 // "buckets" number in the table, i.e. "last = RawTableInner.bucket_mask"):
310 //
311 // `from_base_index(base, 1).as_ptr()` returns a pointer that
312 // points here in the data part of the table
313 // (to the start of T1)
314 // |
315 // | `base: NonNull<T>` must point here
316 // | (to the end of T0 or to the start of C0)
317 // v v
318 // [Padding], Tlast, ..., |T1|, T0, |C0, C1, ..., Clast
319 // ^
320 // `from_base_index(base, 1)` returns a pointer
321 // that points here in the data part of the table
322 // (to the end of T1)
323 //
324 // where: T0...Tlast - our stored data; C0...Clast - control bytes
325 // or metadata for data.
326 let ptr = if T::IS_ZERO_SIZED {
327 // won't overflow because index must be less than length (bucket_mask)
328 // and bucket_mask is guaranteed to be less than `isize::MAX`
329 // (see TableLayout::calculate_layout_for method)
330 ptr::without_provenance_mut(index + 1)
331 } else {
332 unsafe { base.as_ptr().sub(index) }
333 };
334 Self {
335 ptr: unsafe { NonNull::new_unchecked(ptr) },
336 }
337 }
338
339 /// Calculates the index of a [`Bucket`] as distance between two pointers
340 /// (convenience for `base.as_ptr().offset_from(self.ptr.as_ptr()) as usize`).
341 /// The returned value is in units of T: the distance in bytes divided by
342 /// [`size_of::<T>()`].
343 ///
344 /// If the `T` is a ZST, then we return the index of the element in
345 /// the table so that `erase` works properly (return `self.ptr.as_ptr() as usize - 1`).
346 ///
347 /// This function is the inverse of [`from_base_index`].
348 ///
349 /// # Safety
350 ///
351 /// If `size_of::<T>() != 0`, then the safety rules are directly derived
352 /// from the safety rules for [`<*const T>::offset_from`] method of `*const T`.
353 ///
354 /// Thus, in order to uphold the safety contracts for [`<*const T>::offset_from`]
355 /// method, as well as for the correct logic of the work of this crate, the
356 /// following rules are necessary and sufficient:
357 ///
358 /// * `base` contained pointer must not be `dangling` and must point to the
359 /// end of the first `element` from the `data part` of the table, i.e.
360 /// must be a pointer that returns by [`RawTable::data_end`] or by
361 /// [`RawTableInner::data_end<T>`];
362 ///
363 /// * `self` also must not contain dangling pointer;
364 ///
365 /// * both `self` and `base` must be created from the same [`RawTable`]
366 /// (or [`RawTableInner`]).
367 ///
368 /// If `size_of::<T>() == 0`, this function is always safe.
369 #[inline]
370 unsafe fn to_base_index(&self, base: NonNull<T>) -> usize {
371 // If size_of::<T>() != 0 then return an index under which we used to store the
372 // `element` in the data part of the table (we start counting from "0", so
373 // that in the expression T[last], the "last" index actually is one less than the
374 // "buckets" number in the table, i.e. "last = RawTableInner.bucket_mask").
375 // For example for 5th element in table calculation is performed like this:
376 //
377 // size_of::<T>()
378 // |
379 // | `self = from_base_index(base, 5)` that returns pointer
380 // | that points here in the data part of the table
381 // | (to the end of T5)
382 // | | `base: NonNull<T>` must point here
383 // v | (to the end of T0 or to the start of C0)
384 // /???\ v v
385 // [Padding], Tlast, ..., |T10|, ..., T5|, T4, T3, T2, T1, T0, |C0, C1, C2, C3, C4, C5, ..., C10, ..., Clast
386 // \__________ __________/
387 // \/
388 // `bucket.to_base_index(base)` = 5
389 // (base.as_ptr() as usize - self.ptr.as_ptr() as usize) / size_of::<T>()
390 //
391 // where: T0...Tlast - our stored data; C0...Clast - control bytes or metadata for data.
392 if T::IS_ZERO_SIZED {
393 // this can not be UB
394 self.ptr.as_ptr().addr() - 1
395 } else {
396 unsafe { offset_from(base.as_ptr(), self.ptr.as_ptr()) }
397 }
398 }
399
400 /// Acquires the underlying raw pointer `*mut T` to `data`.
401 ///
402 /// # Note
403 ///
404 /// If `T` is not [`Copy`], do not use `*mut T` methods that can cause calling the
405 /// destructor of `T` (for example the [`<*mut T>::drop_in_place`] method), because
406 /// for properly dropping the data we also need to clear `data` control bytes. If we
407 /// drop data, but do not clear `data control byte` it leads to double drop when
408 /// [`RawTable`] goes out of scope.
409 ///
410 /// If you modify an already initialized `value`, so [`Hash`] and [`Eq`] on the new
411 /// `T` value and its borrowed form *must* match those for the old `T` value, as the map
412 /// will not re-evaluate where the new value should go, meaning the value may become
413 /// "lost" if their location does not reflect their state.
414 #[inline]
415 pub(crate) fn as_ptr(&self) -> *mut T {
416 if T::IS_ZERO_SIZED {
417 // Just return an arbitrary ZST pointer which is properly aligned
418 // invalid pointer is good enough for ZST
419 ptr::without_provenance_mut(align_of::<T>())
420 } else {
421 unsafe { self.ptr.as_ptr().sub(1) }
422 }
423 }
424
425 /// Acquires the underlying non-null pointer `*mut T` to `data`.
426 #[inline]
427 fn as_non_null(&self) -> NonNull<T> {
428 // SAFETY: `self.ptr` is already a `NonNull`
429 unsafe { NonNull::new_unchecked(self.as_ptr()) }
430 }
431
432 /// Create a new [`Bucket`] that is offset from the `self` by the given
433 /// `offset`. The pointer calculation is performed by calculating the
434 /// offset from `self` pointer (convenience for `self.ptr.as_ptr().sub(offset)`).
435 /// This function is used for iterators.
436 ///
437 /// `offset` is in units of `T`; e.g., a `offset` of 3 represents a pointer
438 /// offset of `3 * size_of::<T>()` bytes.
439 ///
440 /// # Safety
441 ///
442 /// If `size_of::<T>() != 0`, then the safety rules are directly derived
443 /// from the safety rules for [`<*mut T>::sub`] method of `*mut T` and safety
444 /// rules of [`NonNull::new_unchecked`] function.
445 ///
446 /// Thus, in order to uphold the safety contracts for [`<*mut T>::sub`] method
447 /// and [`NonNull::new_unchecked`] function, as well as for the correct
448 /// logic of the work of this crate, the following rules are necessary and
449 /// sufficient:
450 ///
451 /// * `self` contained pointer must not be `dangling`;
452 ///
453 /// * `self.to_base_index() + offset` must not be greater than `RawTableInner.bucket_mask`,
454 /// i.e. `(self.to_base_index() + offset) <= RawTableInner.bucket_mask` or, in other
455 /// words, `self.to_base_index() + offset + 1` must be no greater than the number returned
456 /// by the function [`RawTable::num_buckets`] or [`RawTableInner::num_buckets`].
457 ///
458 /// If `size_of::<T>() == 0`, then the only requirement is that the
459 /// `self.to_base_index() + offset` must not be greater than `RawTableInner.bucket_mask`,
460 /// i.e. `(self.to_base_index() + offset) <= RawTableInner.bucket_mask` or, in other words,
461 /// `self.to_base_index() + offset + 1` must be no greater than the number returned by the
462 /// function [`RawTable::num_buckets`] or [`RawTableInner::num_buckets`].
463 #[inline]
464 unsafe fn next_n(&self, offset: usize) -> Self {
465 let ptr = if T::IS_ZERO_SIZED {
466 // invalid pointer is good enough for ZST
467 ptr::without_provenance_mut(self.ptr.as_ptr().addr() + offset)
468 } else {
469 unsafe { self.ptr.as_ptr().sub(offset) }
470 };
471 Self {
472 ptr: unsafe { NonNull::new_unchecked(ptr) },
473 }
474 }
475
476 /// Executes the destructor (if any) of the pointed-to `data`.
477 ///
478 /// # Safety
479 ///
480 /// See [`ptr::drop_in_place`] for safety concerns.
481 ///
482 /// You should use [`RawTable::erase`] instead of this function,
483 /// or be careful with calling this function directly, because for
484 /// properly dropping the data we need also clear `data` control bytes.
485 /// If we drop data, but do not erase `data control byte` it leads to
486 /// double drop when [`RawTable`] goes out of scope.
487 #[cfg_attr(feature = "inline-more", inline)]
488 pub(crate) unsafe fn drop(&self) {
489 unsafe {
490 self.as_ptr().drop_in_place();
491 }
492 }
493
494 /// Reads the `value` from `self` without moving it. This leaves the
495 /// memory in `self` unchanged.
496 ///
497 /// # Safety
498 ///
499 /// See [`ptr::read`] for safety concerns.
500 ///
501 /// You should use [`RawTable::remove`] instead of this function,
502 /// or be careful with calling this function directly, because compiler
503 /// calls its destructor when the read `value` goes out of scope. It
504 /// can cause double dropping when [`RawTable`] goes out of scope,
505 /// because of not erased `data control byte`.
506 #[inline]
507 pub(crate) unsafe fn read(&self) -> T {
508 unsafe { self.as_ptr().read() }
509 }
510
511 /// Overwrites a memory location with the given `value` without reading
512 /// or dropping the old value (like [`ptr::write`] function).
513 ///
514 /// # Safety
515 ///
516 /// See [`ptr::write`] for safety concerns.
517 ///
518 /// # Note
519 ///
520 /// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match
521 /// those for the old `T` value, as the map will not re-evaluate where the new
522 /// value should go, meaning the value may become "lost" if their location
523 /// does not reflect their state.
524 #[inline]
525 pub(crate) unsafe fn write(&self, val: T) {
526 unsafe {
527 self.as_ptr().write(val);
528 }
529 }
530
531 /// Returns a shared immutable reference to the `value`.
532 ///
533 /// # Safety
534 ///
535 /// See [`NonNull::as_ref`] for safety concerns.
536 #[inline]
537 pub(crate) unsafe fn as_ref<'a>(&self) -> &'a T {
538 unsafe { &*self.as_ptr() }
539 }
540
541 /// Returns a unique mutable reference to the `value`.
542 ///
543 /// # Safety
544 ///
545 /// See [`NonNull::as_mut`] for safety concerns.
546 ///
547 /// # Note
548 ///
549 /// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match
550 /// those for the old `T` value, as the map will not re-evaluate where the new
551 /// value should go, meaning the value may become "lost" if their location
552 /// does not reflect their state.
553 #[inline]
554 pub(crate) unsafe fn as_mut<'a>(&self) -> &'a mut T {
555 unsafe { &mut *self.as_ptr() }
556 }
557}
558
559/// A raw hash table with an unsafe API.
560pub(crate) struct RawTable<T, A: Allocator = Global> {
561 table: RawTableInner,
562 alloc: A,
563 // Tell dropck that we own instances of T.
564 marker: PhantomData<T>,
565}
566
567/// Non-generic part of `RawTable` which allows functions to be instantiated only once regardless
568/// of how many different key-value types are used.
569struct RawTableInner {
570 // Mask to get an index from a hash value. The value is one less than the
571 // number of buckets in the table.
572 bucket_mask: usize,
573
574 // [Padding], T_n, ..., T1, T0, C0, C1, ...
575 // ^ points here
576 ctrl: NonNull<u8>,
577
578 // Number of elements that can be inserted before we need to grow the table
579 growth_left: usize,
580
581 // Number of elements in the table, only really used by len()
582 items: usize,
583}
584
585impl<T> RawTable<T, Global> {
586 /// Creates a new empty hash table without allocating any memory.
587 ///
588 /// In effect this returns a table with exactly 1 bucket. However we can
589 /// leave the data pointer dangling since that bucket is never written to
590 /// due to our load factor forcing us to always have at least 1 free bucket.
591 #[inline]
592 #[cfg_attr(feature = "rustc-dep-of-std", rustc_const_stable_indirect)]
593 pub(crate) const fn new() -> Self {
594 Self {
595 table: RawTableInner::NEW,
596 alloc: Global,
597 marker: PhantomData,
598 }
599 }
600
601 /// Allocates a new hash table with at least enough capacity for inserting
602 /// the given number of elements without reallocating.
603 pub(crate) fn with_capacity(capacity: usize) -> Self {
604 Self::with_capacity_in(capacity, Global)
605 }
606}
607
608impl<T, A: Allocator> RawTable<T, A> {
609 const TABLE_LAYOUT: TableLayout = TableLayout::new::<T>();
610
611 /// Creates a new empty hash table without allocating any memory, using the
612 /// given allocator.
613 ///
614 /// In effect this returns a table with exactly 1 bucket. However we can
615 /// leave the data pointer dangling since that bucket is never written to
616 /// due to our load factor forcing us to always have at least 1 free bucket.
617 #[inline]
618 #[cfg_attr(feature = "rustc-dep-of-std", rustc_const_stable_indirect)]
619 pub(crate) const fn new_in(alloc: A) -> Self {
620 Self {
621 table: RawTableInner::NEW,
622 alloc,
623 marker: PhantomData,
624 }
625 }
626
627 /// Allocates a new hash table with the given number of buckets.
628 ///
629 /// The control bytes are left uninitialized.
630 #[cfg_attr(feature = "inline-more", inline)]
631 unsafe fn new_uninitialized(
632 alloc: A,
633 buckets: usize,
634 fallibility: Fallibility,
635 ) -> Result<Self, TryReserveError> {
636 debug_assert!(buckets.is_power_of_two());
637
638 Ok(Self {
639 table: unsafe {
640 RawTableInner::new_uninitialized(&alloc, Self::TABLE_LAYOUT, buckets, fallibility)
641 }?,
642 alloc,
643 marker: PhantomData,
644 })
645 }
646
647 /// Allocates a new hash table using the given allocator, with at least enough capacity for
648 /// inserting the given number of elements without reallocating.
649 pub(crate) fn with_capacity_in(capacity: usize, alloc: A) -> Self {
650 Self {
651 table: RawTableInner::with_capacity(&alloc, Self::TABLE_LAYOUT, capacity),
652 alloc,
653 marker: PhantomData,
654 }
655 }
656
657 /// Returns a reference to the underlying allocator.
658 #[inline]
659 pub(crate) fn allocator(&self) -> &A {
660 &self.alloc
661 }
662
663 /// Returns pointer to one past last `data` element in the table as viewed from
664 /// the start point of the allocation.
665 ///
666 /// The caller must ensure that the `RawTable` outlives the returned [`NonNull<T>`],
667 /// otherwise using it may result in [`undefined behavior`].
668 ///
669 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
670 #[inline]
671 pub(crate) fn data_end(&self) -> NonNull<T> {
672 // `self.table.ctrl.cast()` returns pointer that
673 // points here (to the end of `T0`)
674 // ∨
675 // [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m
676 // \________ ________/
677 // \/
678 // `n = buckets - 1`, i.e. `RawTable::num_buckets() - 1`
679 //
680 // where: T0...T_n - our stored data;
681 // CT0...CT_n - control bytes or metadata for `data`.
682 // CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search
683 // with loading `Group` bytes from the heap works properly, even if the result
684 // of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also
685 // `RawTableInner::set_ctrl` function.
686 //
687 // P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.num_buckets()` because the number
688 // of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
689 self.table.ctrl.cast()
690 }
691
692 /// Returns pointer to start of data table.
693 #[inline]
694 #[cfg(feature = "nightly")]
695 pub(crate) unsafe fn data_start(&self) -> NonNull<T> {
696 unsafe { NonNull::new_unchecked(self.data_end().as_ptr().wrapping_sub(self.num_buckets())) }
697 }
698
699 /// Returns the total amount of memory allocated internally by the hash
700 /// table, in bytes.
701 ///
702 /// The returned number is informational only. It is intended to be
703 /// primarily used for memory profiling.
704 #[inline]
705 pub(crate) fn allocation_size(&self) -> usize {
706 // SAFETY: We use the same `table_layout` that was used to allocate
707 // this table.
708 unsafe { self.table.allocation_size_or_zero(Self::TABLE_LAYOUT) }
709 }
710
711 /// Returns the index of a bucket from a `Bucket`.
712 #[inline]
713 pub(crate) unsafe fn bucket_index(&self, bucket: &Bucket<T>) -> usize {
714 unsafe { bucket.to_base_index(self.data_end()) }
715 }
716
717 /// Returns a pointer to an element in the table.
718 ///
719 /// The caller must ensure that the `RawTable` outlives the returned [`Bucket<T>`],
720 /// otherwise using it may result in [`undefined behavior`].
721 ///
722 /// # Safety
723 ///
724 /// If `size_of::<T>() != 0`, then the caller of this function must observe the
725 /// following safety rules:
726 ///
727 /// * The table must already be allocated;
728 ///
729 /// * The `index` must not be greater than the number returned by the [`RawTable::num_buckets`]
730 /// function, i.e. `(index + 1) <= self.num_buckets()`.
731 ///
732 /// It is safe to call this function with index of zero (`index == 0`) on a table that has
733 /// not been allocated, but using the returned [`Bucket`] results in [`undefined behavior`].
734 ///
735 /// If `size_of::<T>() == 0`, then the only requirement is that the `index` must
736 /// not be greater than the number returned by the [`RawTable::num_buckets`] function, i.e.
737 /// `(index + 1) <= self.num_buckets()`.
738 ///
739 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
740 #[inline]
741 pub(crate) unsafe fn bucket(&self, index: usize) -> Bucket<T> {
742 // If size_of::<T>() != 0 then return a pointer to the `element` in the `data part` of the table
743 // (we start counting from "0", so that in the expression T[n], the "n" index actually one less than
744 // the "buckets" number of our `RawTable`, i.e. "n = RawTable::num_buckets() - 1"):
745 //
746 // `table.bucket(3).as_ptr()` returns a pointer that points here in the `data`
747 // part of the `RawTable`, i.e. to the start of T3 (see `Bucket::as_ptr`)
748 // |
749 // | `base = self.data_end()` points here
750 // | (to the start of CT0 or to the end of T0)
751 // v v
752 // [Pad], T_n, ..., |T3|, T2, T1, T0, |CT0, CT1, CT2, CT3, ..., CT_n, CTa_0, CTa_1, ..., CTa_m
753 // ^ \__________ __________/
754 // `table.bucket(3)` returns a pointer that points \/
755 // here in the `data` part of the `RawTable` (to additional control bytes
756 // the end of T3) `m = Group::WIDTH - 1`
757 //
758 // where: T0...T_n - our stored data;
759 // CT0...CT_n - control bytes or metadata for `data`;
760 // CTa_0...CTa_m - additional control bytes (so that the search with loading `Group` bytes from
761 // the heap works properly, even if the result of `h1(hash) & self.table.bucket_mask`
762 // is equal to `self.table.bucket_mask`). See also `RawTableInner::set_ctrl` function.
763 //
764 // P.S. `h1(hash) & self.table.bucket_mask` is the same as `hash as usize % self.num_buckets()` because the number
765 // of buckets is a power of two, and `self.table.bucket_mask = self.num_buckets() - 1`.
766 debug_assert_ne!(self.table.bucket_mask, 0);
767 debug_assert!(index < self.num_buckets());
768 unsafe { Bucket::from_base_index(self.data_end(), index) }
769 }
770
771 /// Erases an element from the table without dropping it.
772 #[cfg_attr(feature = "inline-more", inline)]
773 unsafe fn erase_no_drop(&mut self, item: &Bucket<T>) {
774 unsafe {
775 let index = self.bucket_index(item);
776 self.table.erase(index);
777 }
778 }
779
780 /// Erases an element from the table, dropping it in place.
781 #[cfg_attr(feature = "inline-more", inline)]
782 #[expect(clippy::needless_pass_by_value)]
783 pub(crate) unsafe fn erase(&mut self, item: Bucket<T>) {
784 unsafe {
785 // Erase the element from the table first since drop might panic.
786 self.erase_no_drop(&item);
787 item.drop();
788 }
789 }
790
791 /// Removes an element from the table, returning it.
792 ///
793 /// This also returns an index to the newly free bucket.
794 #[cfg_attr(feature = "inline-more", inline)]
795 #[expect(clippy::needless_pass_by_value)]
796 pub(crate) unsafe fn remove(&mut self, item: Bucket<T>) -> (T, usize) {
797 unsafe {
798 self.erase_no_drop(&item);
799 (item.read(), self.bucket_index(&item))
800 }
801 }
802
803 /// Removes an element from the table, returning it.
804 ///
805 /// This also returns an index to the newly free bucket
806 /// and the former `Tag` for that bucket.
807 #[cfg_attr(feature = "inline-more", inline)]
808 #[expect(clippy::needless_pass_by_value)]
809 pub(crate) unsafe fn remove_tagged(&mut self, item: Bucket<T>) -> (T, usize, Tag) {
810 unsafe {
811 let index = self.bucket_index(&item);
812 let tag = *self.table.ctrl(index);
813 self.table.erase(index);
814 (item.read(), index, tag)
815 }
816 }
817
818 /// Finds and removes an element from the table, returning it.
819 #[cfg_attr(feature = "inline-more", inline)]
820 pub(crate) fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<T> {
821 // Avoid `Option::map` because it bloats LLVM IR.
822 match self.find(hash, eq) {
823 Some(bucket) => Some(unsafe { self.remove(bucket).0 }),
824 None => None,
825 }
826 }
827
828 /// Marks all table buckets as empty without dropping their contents.
829 #[cfg_attr(feature = "inline-more", inline)]
830 pub(crate) fn clear_no_drop(&mut self) {
831 self.table.clear_no_drop();
832 }
833
834 /// Removes all elements from the table without freeing the backing memory.
835 #[cfg_attr(feature = "inline-more", inline)]
836 pub(crate) fn clear(&mut self) {
837 if self.is_empty() {
838 // Special case empty table to avoid surprising O(capacity) time.
839 return;
840 }
841 // Ensure that the table is reset even if one of the drops panic
842 let mut self_ = guard(self, |self_| self_.clear_no_drop());
843 unsafe {
844 // SAFETY: ScopeGuard sets to zero the `items` field of the table
845 // even in case of panic during the dropping of the elements so
846 // that there will be no double drop of the elements.
847 self_.table.drop_elements::<T>();
848 }
849 }
850
851 /// Shrinks the table to fit `max(self.len(), min_size)` elements.
852 #[cfg_attr(feature = "inline-more", inline)]
853 pub(crate) fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) {
854 // Calculate the minimal number of elements that we need to reserve
855 // space for.
856 let min_size = usize::max(self.table.items, min_size);
857 if min_size == 0 {
858 let mut old_inner = mem::replace(&mut self.table, RawTableInner::NEW);
859 unsafe {
860 // SAFETY:
861 // 1. We call the function only once;
862 // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`]
863 // and [`TableLayout`] that were used to allocate this table.
864 // 3. If any elements' drop function panics, then there will only be a memory leak,
865 // because we have replaced the inner table with a new one.
866 old_inner.drop_inner_table::<T, _>(&self.alloc, Self::TABLE_LAYOUT);
867 }
868 return;
869 }
870
871 // Calculate the number of buckets that we need for this number of
872 // elements. If the calculation overflows then the requested bucket
873 // count must be larger than what we have right and nothing needs to be
874 // done.
875 let Some(min_buckets) = capacity_to_buckets(min_size, Self::TABLE_LAYOUT) else {
876 return;
877 };
878
879 // If we have more buckets than we need, shrink the table.
880 if min_buckets < self.num_buckets() {
881 // Fast path if the table is empty
882 if self.table.items == 0 {
883 let new_inner =
884 RawTableInner::with_capacity(&self.alloc, Self::TABLE_LAYOUT, min_size);
885 let mut old_inner = mem::replace(&mut self.table, new_inner);
886 unsafe {
887 // SAFETY:
888 // 1. We call the function only once;
889 // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`]
890 // and [`TableLayout`] that were used to allocate this table.
891 // 3. If any elements' drop function panics, then there will only be a memory leak,
892 // because we have replaced the inner table with a new one.
893 old_inner.drop_inner_table::<T, _>(&self.alloc, Self::TABLE_LAYOUT);
894 }
895 } else {
896 // SAFETY:
897 // 1. We know for sure that `min_size >= self.table.items`.
898 // 2. The [`RawTableInner`] must already have properly initialized control bytes since
899 // we will never expose RawTable::new_uninitialized in a public API.
900 let result = unsafe { self.resize(min_size, hasher, Fallibility::Infallible) };
901
902 // SAFETY: The result of calling the `resize` function cannot be an error
903 // because `fallibility == Fallibility::Infallible.
904 unsafe { result.unwrap_unchecked() };
905 }
906 }
907 }
908
909 /// Ensures that at least `additional` items can be inserted into the table
910 /// without reallocation.
911 #[cfg_attr(feature = "inline-more", inline)]
912 pub(crate) fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) {
913 if unlikely(additional > self.table.growth_left) {
914 // SAFETY: The [`RawTableInner`] must already have properly initialized control
915 // bytes since we will never expose RawTable::new_uninitialized in a public API.
916 let result =
917 unsafe { self.reserve_rehash(additional, hasher, Fallibility::Infallible) };
918
919 // SAFETY: All allocation errors will be caught inside `RawTableInner::reserve_rehash`.
920 unsafe { result.unwrap_unchecked() };
921 }
922 }
923
924 /// Tries to ensure that at least `additional` items can be inserted into
925 /// the table without reallocation.
926 #[cfg_attr(feature = "inline-more", inline)]
927 pub(crate) fn try_reserve(
928 &mut self,
929 additional: usize,
930 hasher: impl Fn(&T) -> u64,
931 ) -> Result<(), TryReserveError> {
932 if additional > self.table.growth_left {
933 // SAFETY: The [`RawTableInner`] must already have properly initialized control
934 // bytes since we will never expose RawTable::new_uninitialized in a public API.
935 unsafe { self.reserve_rehash(additional, hasher, Fallibility::Fallible) }
936 } else {
937 Ok(())
938 }
939 }
940
941 /// Out-of-line slow path for `reserve` and `try_reserve`.
942 ///
943 /// # Safety
944 ///
945 /// The [`RawTableInner`] must have properly initialized control bytes,
946 /// otherwise calling this function results in [`undefined behavior`]
947 ///
948 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
949 #[cold]
950 #[inline(never)]
951 unsafe fn reserve_rehash(
952 &mut self,
953 additional: usize,
954 hasher: impl Fn(&T) -> u64,
955 fallibility: Fallibility,
956 ) -> Result<(), TryReserveError> {
957 unsafe {
958 // SAFETY:
959 // 1. We know for sure that `alloc` and `layout` matches the [`Allocator`] and
960 // [`TableLayout`] that were used to allocate this table.
961 // 2. The `drop` function is the actual drop function of the elements stored in
962 // the table.
963 // 3. The caller ensures that the control bytes of the `RawTableInner`
964 // are already initialized.
965 self.table.reserve_rehash_inner(
966 &self.alloc,
967 additional,
968 &|table, index| hasher(table.bucket::<T>(index).as_ref()),
969 fallibility,
970 Self::TABLE_LAYOUT,
971 if T::NEEDS_DROP {
972 Some(|ptr| ptr::drop_in_place(ptr.cast::<T>()))
973 } else {
974 None
975 },
976 )
977 }
978 }
979
980 /// Allocates a new table of a different size and moves the contents of the
981 /// current table into it.
982 ///
983 /// # Safety
984 ///
985 /// The [`RawTableInner`] must have properly initialized control bytes,
986 /// otherwise calling this function results in [`undefined behavior`]
987 ///
988 /// The caller of this function must ensure that `capacity >= self.table.items`
989 /// otherwise:
990 ///
991 /// * If `self.table.items != 0`, calling of this function with `capacity`
992 /// equal to 0 (`capacity == 0`) results in [`undefined behavior`].
993 ///
994 /// * If `self.table.items > capacity_to_buckets(capacity, Self::TABLE_LAYOUT)`
995 /// calling this function are never return (will loop infinitely).
996 ///
997 /// See [`RawTableInner::find_insert_index`] for more information.
998 ///
999 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1000 unsafe fn resize(
1001 &mut self,
1002 capacity: usize,
1003 hasher: impl Fn(&T) -> u64,
1004 fallibility: Fallibility,
1005 ) -> Result<(), TryReserveError> {
1006 // SAFETY:
1007 // 1. The caller of this function guarantees that `capacity >= self.table.items`.
1008 // 2. We know for sure that `alloc` and `layout` matches the [`Allocator`] and
1009 // [`TableLayout`] that were used to allocate this table.
1010 // 3. The caller ensures that the control bytes of the `RawTableInner`
1011 // are already initialized.
1012 unsafe {
1013 self.table.resize_inner(
1014 &self.alloc,
1015 capacity,
1016 &|table, index| hasher(table.bucket::<T>(index).as_ref()),
1017 fallibility,
1018 Self::TABLE_LAYOUT,
1019 )
1020 }
1021 }
1022
1023 /// Inserts a new element into the table, and returns its raw bucket.
1024 ///
1025 /// This does not check if the given element already exists in the table.
1026 #[cfg_attr(feature = "inline-more", inline)]
1027 pub(crate) fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket<T> {
1028 unsafe {
1029 // SAFETY:
1030 // 1. The [`RawTableInner`] must already have properly initialized control bytes since
1031 // we will never expose `RawTable::new_uninitialized` in a public API.
1032 //
1033 // 2. We reserve additional space (if necessary) right after calling this function.
1034 let mut index = self.table.find_insert_index(hash);
1035
1036 // We can avoid growing the table once we have reached our load factor if we are replacing
1037 // a tombstone. This works since the number of EMPTY slots does not change in this case.
1038 //
1039 // SAFETY: The function is guaranteed to return an index in the range `0..=self.num_buckets()`.
1040 let old_ctrl = *self.table.ctrl(index);
1041 if unlikely(self.table.growth_left == 0 && old_ctrl.special_is_empty()) {
1042 self.reserve(1, hasher);
1043 // SAFETY: We know for sure that `RawTableInner` has control bytes
1044 // initialized and that there is extra space in the table.
1045 index = self.table.find_insert_index(hash);
1046 }
1047
1048 self.insert_at_index(hash, index, value)
1049 }
1050 }
1051
1052 /// Inserts a new element into the table, and returns a mutable reference to it.
1053 ///
1054 /// This does not check if the given element already exists in the table.
1055 #[cfg_attr(feature = "inline-more", inline)]
1056 pub(crate) fn insert_entry(
1057 &mut self,
1058 hash: u64,
1059 value: T,
1060 hasher: impl Fn(&T) -> u64,
1061 ) -> &mut T {
1062 unsafe { self.insert(hash, value, hasher).as_mut() }
1063 }
1064
1065 /// Inserts a new element into the table, without growing the table.
1066 ///
1067 /// There must be enough space in the table to insert the new element.
1068 ///
1069 /// This does not check if the given element already exists in the table.
1070 #[cfg_attr(feature = "inline-more", inline)]
1071 #[cfg(feature = "rustc-internal-api")]
1072 pub(crate) unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket<T> {
1073 unsafe {
1074 let (index, old_ctrl) = self.table.prepare_insert_index(hash);
1075 let bucket = self.table.bucket(index);
1076
1077 // If we are replacing a DELETED entry then we don't need to update
1078 // the load counter.
1079 self.table.growth_left -= old_ctrl.special_is_empty() as usize;
1080
1081 bucket.write(value);
1082 self.table.items += 1;
1083 bucket
1084 }
1085 }
1086
1087 /// Temporarily removes a bucket, applying the given function to the removed
1088 /// element and optionally put back the returned value in the same bucket.
1089 ///
1090 /// Returns tag for bucket if the bucket is emptied out.
1091 ///
1092 /// This does not check if the given bucket is actually occupied.
1093 #[cfg_attr(feature = "inline-more", inline)]
1094 pub(crate) unsafe fn replace_bucket_with<F>(&mut self, bucket: Bucket<T>, f: F) -> Option<Tag>
1095 where
1096 F: FnOnce(T) -> Option<T>,
1097 {
1098 unsafe {
1099 let index = self.bucket_index(&bucket);
1100 let old_ctrl = *self.table.ctrl(index);
1101 debug_assert!(self.is_bucket_full(index));
1102 let old_growth_left = self.table.growth_left;
1103 let item = self.remove(bucket).0;
1104 if let Some(new_item) = f(item) {
1105 self.table.growth_left = old_growth_left;
1106 self.table.set_ctrl(index, old_ctrl);
1107 self.table.items += 1;
1108 self.bucket(index).write(new_item);
1109 None
1110 } else {
1111 Some(old_ctrl)
1112 }
1113 }
1114 }
1115
1116 /// Searches for an element in the table. If the element is not found,
1117 /// returns `Err` with the position of a slot where an element with the
1118 /// same hash could be inserted.
1119 ///
1120 /// This function may resize the table if additional space is required for
1121 /// inserting an element.
1122 #[inline]
1123 pub(crate) fn find_or_find_insert_index(
1124 &mut self,
1125 hash: u64,
1126 mut eq: impl FnMut(&T) -> bool,
1127 hasher: impl Fn(&T) -> u64,
1128 ) -> Result<Bucket<T>, usize> {
1129 self.reserve(1, hasher);
1130
1131 unsafe {
1132 // SAFETY:
1133 // 1. We know for sure that there is at least one empty `bucket` in the table.
1134 // 2. The [`RawTableInner`] must already have properly initialized control bytes since we will
1135 // never expose `RawTable::new_uninitialized` in a public API.
1136 // 3. The `find_or_find_insert_index_inner` function returns the `index` of only the full bucket,
1137 // which is in the range `0..self.num_buckets()` (since there is at least one empty `bucket` in
1138 // the table), so calling `self.bucket(index)` and `Bucket::as_ref` is safe.
1139 match self
1140 .table
1141 .find_or_find_insert_index_inner(hash, &mut |index| eq(self.bucket(index).as_ref()))
1142 {
1143 // SAFETY: See explanation above.
1144 Ok(index) => Ok(self.bucket(index)),
1145 Err(index) => Err(index),
1146 }
1147 }
1148 }
1149
1150 /// Inserts a new element into the table at the given index with the given hash,
1151 /// and returns its raw bucket.
1152 ///
1153 /// # Safety
1154 ///
1155 /// `index` must point to a slot previously returned by
1156 /// `find_or_find_insert_index`, and no mutation of the table must have
1157 /// occurred since that call.
1158 #[inline]
1159 pub(crate) unsafe fn insert_at_index(
1160 &mut self,
1161 hash: u64,
1162 index: usize,
1163 value: T,
1164 ) -> Bucket<T> {
1165 unsafe { self.insert_tagged_at_index(Tag::full(hash), index, value) }
1166 }
1167
1168 /// Inserts a new element into the table at the given index with the given tag,
1169 /// and returns its raw bucket.
1170 ///
1171 /// # Safety
1172 ///
1173 /// `index` must point to a slot previously returned by
1174 /// `find_or_find_insert_index`, and no mutation of the table must have
1175 /// occurred since that call.
1176 #[inline]
1177 pub(crate) unsafe fn insert_tagged_at_index(
1178 &mut self,
1179 tag: Tag,
1180 index: usize,
1181 value: T,
1182 ) -> Bucket<T> {
1183 unsafe {
1184 let old_ctrl = *self.table.ctrl(index);
1185 self.table.record_item_insert_at(index, old_ctrl, tag);
1186
1187 let bucket = self.bucket(index);
1188 bucket.write(value);
1189 bucket
1190 }
1191 }
1192
1193 /// Searches for an element in the table.
1194 #[inline]
1195 pub(crate) fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option<Bucket<T>> {
1196 unsafe {
1197 // SAFETY:
1198 // 1. The [`RawTableInner`] must already have properly initialized control bytes since we
1199 // will never expose `RawTable::new_uninitialized` in a public API.
1200 // 1. The `find_inner` function returns the `index` of only the full bucket, which is in
1201 // the range `0..self.num_buckets()`, so calling `self.bucket(index)` and `Bucket::as_ref`
1202 // is safe.
1203 let result = self
1204 .table
1205 .find_inner(hash, &mut |index| eq(self.bucket(index).as_ref()));
1206
1207 // Avoid `Option::map` because it bloats LLVM IR.
1208 match result {
1209 // SAFETY: See explanation above.
1210 Some(index) => Some(self.bucket(index)),
1211 None => None,
1212 }
1213 }
1214 }
1215
1216 /// Gets a reference to an element in the table.
1217 #[inline]
1218 pub(crate) fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> {
1219 // Avoid `Option::map` because it bloats LLVM IR.
1220 match self.find(hash, eq) {
1221 Some(bucket) => Some(unsafe { bucket.as_ref() }),
1222 None => None,
1223 }
1224 }
1225
1226 /// Gets a mutable reference to an element in the table.
1227 #[inline]
1228 pub(crate) fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> {
1229 // Avoid `Option::map` because it bloats LLVM IR.
1230 match self.find(hash, eq) {
1231 Some(bucket) => Some(unsafe { bucket.as_mut() }),
1232 None => None,
1233 }
1234 }
1235
1236 /// Gets a reference to an element in the table at the given bucket index.
1237 #[inline]
1238 pub(crate) fn get_bucket(&self, index: usize) -> Option<&T> {
1239 unsafe {
1240 if index < self.num_buckets() && self.is_bucket_full(index) {
1241 Some(self.bucket(index).as_ref())
1242 } else {
1243 None
1244 }
1245 }
1246 }
1247
1248 /// Gets a mutable reference to an element in the table at the given bucket index.
1249 #[inline]
1250 pub(crate) fn get_bucket_mut(&mut self, index: usize) -> Option<&mut T> {
1251 unsafe {
1252 if index < self.num_buckets() && self.is_bucket_full(index) {
1253 Some(self.bucket(index).as_mut())
1254 } else {
1255 None
1256 }
1257 }
1258 }
1259
1260 /// Returns a pointer to an element in the table, but only after verifying that
1261 /// the index is in-bounds and the bucket is occupied.
1262 #[inline]
1263 pub(crate) fn checked_bucket(&self, index: usize) -> Option<Bucket<T>> {
1264 unsafe {
1265 if index < self.num_buckets() && self.is_bucket_full(index) {
1266 Some(self.bucket(index))
1267 } else {
1268 None
1269 }
1270 }
1271 }
1272
1273 /// Attempts to get mutable references to `N` entries in the table at once.
1274 ///
1275 /// Returns an array of length `N` with the results of each query.
1276 ///
1277 /// At most one mutable reference will be returned to any entry. `None` will be returned if any
1278 /// of the hashes are duplicates. `None` will be returned if the hash is not found.
1279 ///
1280 /// The `eq` argument should be a closure such that `eq(i, k)` returns true if `k` is equal to
1281 /// the `i`th key to be looked up.
1282 pub(crate) fn get_disjoint_mut<const N: usize>(
1283 &mut self,
1284 hashes: [u64; N],
1285 eq: impl FnMut(usize, &T) -> bool,
1286 ) -> [Option<&'_ mut T>; N] {
1287 unsafe {
1288 let ptrs = self.get_disjoint_mut_pointers(hashes, eq);
1289
1290 for (i, cur) in ptrs.iter().enumerate() {
1291 assert!(
1292 !(cur.is_some() && ptrs[..i].contains(cur)),
1293 "duplicate keys found"
1294 );
1295 }
1296 // All bucket are distinct from all previous buckets so we're clear to return the result
1297 // of the lookup.
1298
1299 ptrs.map(|ptr| ptr.map(|mut ptr| ptr.as_mut()))
1300 }
1301 }
1302
1303 pub(crate) unsafe fn get_disjoint_unchecked_mut<const N: usize>(
1304 &mut self,
1305 hashes: [u64; N],
1306 eq: impl FnMut(usize, &T) -> bool,
1307 ) -> [Option<&'_ mut T>; N] {
1308 let ptrs = unsafe { self.get_disjoint_mut_pointers(hashes, eq) };
1309 ptrs.map(|ptr| ptr.map(|mut ptr| unsafe { ptr.as_mut() }))
1310 }
1311
1312 unsafe fn get_disjoint_mut_pointers<const N: usize>(
1313 &mut self,
1314 hashes: [u64; N],
1315 mut eq: impl FnMut(usize, &T) -> bool,
1316 ) -> [Option<NonNull<T>>; N] {
1317 array::from_fn(|i| {
1318 self.find(hashes[i], |k| eq(i, k))
1319 .map(|cur| cur.as_non_null())
1320 })
1321 }
1322
1323 /// Returns the number of elements the map can hold without reallocating.
1324 ///
1325 /// This number is a lower bound; the table might be able to hold
1326 /// more, but is guaranteed to be able to hold at least this many.
1327 #[inline]
1328 pub(crate) fn capacity(&self) -> usize {
1329 self.table.items + self.table.growth_left
1330 }
1331
1332 /// Returns the number of elements in the table.
1333 #[inline]
1334 pub(crate) fn len(&self) -> usize {
1335 self.table.items
1336 }
1337
1338 /// Returns `true` if the table contains no elements.
1339 #[inline]
1340 pub(crate) fn is_empty(&self) -> bool {
1341 self.len() == 0
1342 }
1343
1344 /// Returns the number of buckets in the table.
1345 #[inline]
1346 pub(crate) fn num_buckets(&self) -> usize {
1347 self.table.bucket_mask + 1
1348 }
1349
1350 /// Checks whether the bucket at `index` is full.
1351 ///
1352 /// # Safety
1353 ///
1354 /// The caller must ensure `index` is less than the number of buckets.
1355 #[inline]
1356 pub(crate) unsafe fn is_bucket_full(&self, index: usize) -> bool {
1357 unsafe { self.table.is_bucket_full(index) }
1358 }
1359
1360 /// Returns an iterator over every element in the table. It is up to
1361 /// the caller to ensure that the `RawTable` outlives the `RawIter`.
1362 /// Because we cannot make the `next` method unsafe on the `RawIter`
1363 /// struct, we have to make the `iter` method unsafe.
1364 #[inline]
1365 pub(crate) unsafe fn iter(&self) -> RawIter<T> {
1366 // SAFETY:
1367 // 1. The caller must uphold the safety contract for `iter` method.
1368 // 2. The [`RawTableInner`] must already have properly initialized control bytes since
1369 // we will never expose RawTable::new_uninitialized in a public API.
1370 unsafe { self.table.iter() }
1371 }
1372
1373 /// Returns an iterator over occupied buckets that could match a given hash.
1374 ///
1375 /// `RawTable` only stores 7 bits of the hash value, so this iterator may
1376 /// return items that have a hash value different than the one provided. You
1377 /// should always validate the returned values before using them.
1378 ///
1379 /// It is up to the caller to ensure that the `RawTable` outlives the
1380 /// `RawIterHash`. Because we cannot make the `next` method unsafe on the
1381 /// `RawIterHash` struct, we have to make the `iter_hash` method unsafe.
1382 #[cfg_attr(feature = "inline-more", inline)]
1383 pub(crate) unsafe fn iter_hash(&self, hash: u64) -> RawIterHash<T> {
1384 unsafe { RawIterHash::new(self, hash) }
1385 }
1386
1387 /// Returns an iterator over occupied bucket indices that could match a given hash.
1388 ///
1389 /// `RawTable` only stores 7 bits of the hash value, so this iterator may
1390 /// return items that have a hash value different than the one provided. You
1391 /// should always validate the returned values before using them.
1392 ///
1393 /// It is up to the caller to ensure that the `RawTable` outlives the
1394 /// `RawIterHashIndices`. Because we cannot make the `next` method unsafe on the
1395 /// `RawIterHashIndices` struct, we have to make the `iter_hash_buckets` method unsafe.
1396 #[cfg_attr(feature = "inline-more", inline)]
1397 pub(crate) unsafe fn iter_hash_buckets(&self, hash: u64) -> RawIterHashIndices {
1398 unsafe { RawIterHashIndices::new(&self.table, hash) }
1399 }
1400
1401 /// Returns an iterator over full buckets indices in the table.
1402 ///
1403 /// See [`RawTableInner::full_buckets_indices`] for safety conditions.
1404 #[inline(always)]
1405 pub(crate) unsafe fn full_buckets_indices(&self) -> FullBucketsIndices {
1406 unsafe { self.table.full_buckets_indices() }
1407 }
1408
1409 /// Returns an iterator which removes all elements from the table without
1410 /// freeing the memory.
1411 #[cfg_attr(feature = "inline-more", inline)]
1412 pub(crate) fn drain(&mut self) -> RawDrain<'_, T, A> {
1413 unsafe {
1414 let iter = self.iter();
1415 self.drain_iter_from(iter)
1416 }
1417 }
1418
1419 /// Returns an iterator which removes all elements from the table without
1420 /// freeing the memory.
1421 ///
1422 /// Iteration starts at the provided iterator's current location.
1423 ///
1424 /// It is up to the caller to ensure that the iterator is valid for this
1425 /// `RawTable` and covers all items that remain in the table.
1426 #[cfg_attr(feature = "inline-more", inline)]
1427 pub(crate) unsafe fn drain_iter_from(&mut self, iter: RawIter<T>) -> RawDrain<'_, T, A> {
1428 debug_assert_eq!(iter.len(), self.len());
1429 RawDrain {
1430 iter,
1431 table: mem::replace(&mut self.table, RawTableInner::NEW),
1432 orig_table: NonNull::from(&mut self.table),
1433 marker: PhantomData,
1434 }
1435 }
1436
1437 /// Returns an iterator which consumes all elements from the table.
1438 ///
1439 /// Iteration starts at the provided iterator's current location.
1440 ///
1441 /// It is up to the caller to ensure that the iterator is valid for this
1442 /// `RawTable` and covers all items that remain in the table.
1443 pub(crate) unsafe fn into_iter_from(self, iter: RawIter<T>) -> RawIntoIter<T, A> {
1444 debug_assert_eq!(iter.len(), self.len());
1445
1446 let allocation = self.into_allocation();
1447 RawIntoIter {
1448 iter,
1449 allocation,
1450 marker: PhantomData,
1451 }
1452 }
1453
1454 /// Converts the table into a raw allocation. The contents of the table
1455 /// should be dropped using a `RawIter` before freeing the allocation.
1456 #[cfg_attr(feature = "inline-more", inline)]
1457 pub(crate) fn into_allocation(self) -> Option<(NonNull<u8>, Layout, A)> {
1458 let this = ManuallyDrop::new(self);
1459 // SAFETY: `this` is never dropped, so ownership of the allocator is
1460 // moved out exactly once. If the table never allocated, the allocator
1461 // is dropped here rather than being leaked.
1462 let alloc = unsafe { ptr::read(&raw const this.alloc) };
1463 if this.table.is_empty_singleton() {
1464 None
1465 } else {
1466 let (layout, ctrl_offset) = {
1467 let option = Self::TABLE_LAYOUT.calculate_layout_for(this.table.num_buckets());
1468 unsafe { option.unwrap_unchecked() }
1469 };
1470 Some((
1471 unsafe { NonNull::new_unchecked(this.table.ctrl.as_ptr().sub(ctrl_offset).cast()) },
1472 layout,
1473 alloc,
1474 ))
1475 }
1476 }
1477}
1478
1479unsafe impl<T, A: Allocator> Send for RawTable<T, A>
1480where
1481 T: Send,
1482 A: Send,
1483{
1484}
1485unsafe impl<T, A: Allocator> Sync for RawTable<T, A>
1486where
1487 T: Sync,
1488 A: Sync,
1489{
1490}
1491
1492impl RawTableInner {
1493 const NEW: Self = RawTableInner::new();
1494
1495 /// Creates a new empty hash table without allocating any memory.
1496 ///
1497 /// In effect this returns a table with exactly 1 bucket. However we can
1498 /// leave the data pointer dangling since that bucket is never accessed
1499 /// due to our load factor forcing us to always have at least 1 free bucket.
1500 #[inline]
1501 const fn new() -> Self {
1502 Self {
1503 // Be careful to cast the entire slice to a raw pointer.
1504 ctrl: unsafe {
1505 NonNull::new_unchecked(Group::static_empty().as_ptr().cast_mut().cast())
1506 },
1507 bucket_mask: 0,
1508 items: 0,
1509 growth_left: 0,
1510 }
1511 }
1512}
1513
1514/// Find the previous power of 2. If it's already a power of 2, it's unchanged.
1515/// Passing zero is undefined behavior.
1516pub(crate) fn prev_pow2(z: usize) -> usize {
1517 let shift = usize::BITS as usize - 1;
1518 1 << (shift - (z.leading_zeros() as usize))
1519}
1520
1521/// Finds the largest number of buckets that can fit in `allocation_size`
1522/// provided the given TableLayout.
1523///
1524/// This relies on some invariants of `capacity_to_buckets`, so only feed in
1525/// an `allocation_size` calculated from `capacity_to_buckets`.
1526fn maximum_buckets_in(
1527 allocation_size: usize,
1528 table_layout: TableLayout,
1529 group_width: usize,
1530) -> usize {
1531 // Given an equation like:
1532 // z >= x * y + x + g
1533 // x can be maximized by doing:
1534 // x = (z - g) / (y + 1)
1535 // If you squint:
1536 // x is the number of buckets
1537 // y is the table_layout.size
1538 // z is the size of the allocation
1539 // g is the group width
1540 // But this is ignoring the padding needed for ctrl_align.
1541 // If we remember these restrictions:
1542 // x is always a power of 2
1543 // Layout size for T must always be a multiple of T
1544 // Then the alignment can be ignored if we add the constraint:
1545 // x * y >= table_layout.ctrl_align
1546 // This is taken care of by `capacity_to_buckets`.
1547 // It may be helpful to understand this if you remember that:
1548 // ctrl_offset = align(x * y, ctrl_align)
1549 let x = (allocation_size - group_width) / (table_layout.size + 1);
1550 prev_pow2(x)
1551}
1552
1553impl RawTableInner {
1554 /// Allocates a new [`RawTableInner`] with the given number of buckets.
1555 /// The control bytes and buckets are left uninitialized.
1556 ///
1557 /// # Safety
1558 ///
1559 /// The caller of this function must ensure that the `buckets` is power of two
1560 /// and also initialize all control bytes of the length `self.bucket_mask + 1 +
1561 /// Group::WIDTH` with the [`Tag::EMPTY`] bytes.
1562 ///
1563 /// See also [`Allocator`] API for other safety concerns.
1564 ///
1565 /// [`Allocator`]: stdalloc::alloc::Allocator
1566 #[cfg_attr(feature = "inline-more", inline)]
1567 unsafe fn new_uninitialized<A>(
1568 alloc: &A,
1569 table_layout: TableLayout,
1570 mut buckets: usize,
1571 fallibility: Fallibility,
1572 ) -> Result<Self, TryReserveError>
1573 where
1574 A: Allocator,
1575 {
1576 debug_assert!(buckets.is_power_of_two());
1577
1578 // Avoid `Option::ok_or_else` because it bloats LLVM IR.
1579 let Some((layout, mut ctrl_offset)) = table_layout.calculate_layout_for(buckets) else {
1580 return Err(fallibility.capacity_overflow());
1581 };
1582
1583 let ptr: NonNull<u8> = match do_alloc(alloc, layout) {
1584 Ok(block) => {
1585 // The allocator can't return a value smaller than was
1586 // requested, so this can be != instead of >=.
1587 if block.len() != layout.size() {
1588 // Utilize over-sized allocations.
1589 let x = maximum_buckets_in(block.len(), table_layout, Group::WIDTH);
1590 debug_assert!(x >= buckets);
1591 // Calculate the new ctrl_offset.
1592 let (oversized_layout, oversized_ctrl_offset) = {
1593 let option = table_layout.calculate_layout_for(x);
1594 unsafe { option.unwrap_unchecked() }
1595 };
1596 debug_assert!(oversized_layout.size() <= block.len());
1597 debug_assert!(oversized_ctrl_offset >= ctrl_offset);
1598 ctrl_offset = oversized_ctrl_offset;
1599 buckets = x;
1600 }
1601
1602 block.cast()
1603 }
1604 Err(_) => return Err(fallibility.alloc_err(layout)),
1605 };
1606
1607 // SAFETY: null pointer will be caught in above check
1608 let ctrl = unsafe { NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)) };
1609 Ok(Self {
1610 ctrl,
1611 bucket_mask: buckets - 1,
1612 items: 0,
1613 growth_left: bucket_mask_to_capacity(buckets - 1),
1614 })
1615 }
1616
1617 /// Attempts to allocate a new [`RawTableInner`] with at least enough
1618 /// capacity for inserting the given number of elements without reallocating.
1619 ///
1620 /// All the control bytes are initialized with the [`Tag::EMPTY`] bytes.
1621 #[inline]
1622 fn fallible_with_capacity<A>(
1623 alloc: &A,
1624 table_layout: TableLayout,
1625 capacity: usize,
1626 fallibility: Fallibility,
1627 ) -> Result<Self, TryReserveError>
1628 where
1629 A: Allocator,
1630 {
1631 if capacity == 0 {
1632 Ok(Self::NEW)
1633 } else {
1634 // SAFETY: We checked that we could successfully allocate the new table, and then
1635 // initialized all control bytes with the constant `Tag::EMPTY` byte.
1636 unsafe {
1637 let buckets = capacity_to_buckets(capacity, table_layout)
1638 .ok_or_else(|| fallibility.capacity_overflow())?;
1639
1640 let mut result =
1641 Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?;
1642 // SAFETY: We checked that the table is allocated and therefore the table already has
1643 // `self.bucket_mask + 1 + Group::WIDTH` number of control bytes (see TableLayout::calculate_layout_for)
1644 // so writing `self.num_ctrl_bytes() == bucket_mask + 1 + Group::WIDTH` bytes is safe.
1645 result.ctrl_slice().fill_empty();
1646
1647 Ok(result)
1648 }
1649 }
1650 }
1651
1652 /// Allocates a new [`RawTableInner`] with at least enough capacity for inserting
1653 /// the given number of elements without reallocating.
1654 ///
1655 /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
1656 /// in case of allocation error. Use [`fallible_with_capacity`] instead if you want to
1657 /// handle memory allocation failure.
1658 ///
1659 /// All the control bytes are initialized with the [`Tag::EMPTY`] bytes.
1660 ///
1661 /// [`fallible_with_capacity`]: RawTableInner::fallible_with_capacity
1662 /// [`abort`]: stdalloc::abort::handle_alloc_error
1663 fn with_capacity<A>(alloc: &A, table_layout: TableLayout, capacity: usize) -> Self
1664 where
1665 A: Allocator,
1666 {
1667 let result =
1668 Self::fallible_with_capacity(alloc, table_layout, capacity, Fallibility::Infallible);
1669
1670 // SAFETY: All allocation errors will be caught inside `RawTableInner::new_uninitialized`.
1671 unsafe { result.unwrap_unchecked() }
1672 }
1673
1674 /// Fixes up an insertion index returned by the [`RawTableInner::find_insert_index_in_group`] method.
1675 ///
1676 /// In tables smaller than the group width (`self.num_buckets() < Group::WIDTH`), trailing control
1677 /// bytes outside the range of the table are filled with [`Tag::EMPTY`] entries. These will unfortunately
1678 /// trigger a match of [`RawTableInner::find_insert_index_in_group`] function. This is because
1679 /// the `Some(bit)` returned by `group.match_empty_or_deleted().lowest_set_bit()` after masking
1680 /// (`(probe_seq.pos + bit) & self.bucket_mask`) may point to a full bucket that is already occupied.
1681 /// We detect this situation here and perform a second scan starting at the beginning of the table.
1682 /// This second scan is guaranteed to find an empty slot (due to the load factor) before hitting the
1683 /// trailing control bytes (containing [`Tag::EMPTY`] bytes).
1684 ///
1685 /// If this function is called correctly, it is guaranteed to return an index of an empty or
1686 /// deleted bucket in the range `0..self.num_buckets()` (see `Warning` and `Safety`).
1687 ///
1688 /// # Warning
1689 ///
1690 /// The table must have at least 1 empty or deleted `bucket`, otherwise if the table is less than
1691 /// the group width (`self.num_buckets() < Group::WIDTH`) this function returns an index outside of the
1692 /// table indices range `0..self.num_buckets()` (`0..=self.bucket_mask`). Attempt to write data at that
1693 /// index will cause immediate [`undefined behavior`].
1694 ///
1695 /// # Safety
1696 ///
1697 /// The safety rules are directly derived from the safety rules for [`RawTableInner::ctrl`] method.
1698 /// Thus, in order to uphold those safety contracts, as well as for the correct logic of the work
1699 /// of this crate, the following rules are necessary and sufficient:
1700 ///
1701 /// * The [`RawTableInner`] must have properly initialized control bytes otherwise calling this
1702 /// function results in [`undefined behavior`].
1703 ///
1704 /// * This function must only be used on insertion indices found by [`RawTableInner::find_insert_index_in_group`]
1705 /// (after the `find_insert_index_in_group` function, but before insertion into the table).
1706 ///
1707 /// * The `index` must not be greater than the `self.bucket_mask`, i.e. `(index + 1) <= self.num_buckets()`
1708 /// (this one is provided by the [`RawTableInner::find_insert_index_in_group`] function).
1709 ///
1710 /// Calling this function with an index not provided by [`RawTableInner::find_insert_index_in_group`]
1711 /// may result in [`undefined behavior`] even if the index satisfies the safety rules of the
1712 /// [`RawTableInner::ctrl`] function (`index < self.bucket_mask + 1 + Group::WIDTH`).
1713 ///
1714 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1715 #[inline]
1716 unsafe fn fix_insert_index(&self, mut index: usize) -> usize {
1717 // SAFETY: The caller of this function ensures that `index` is in the range `0..=self.bucket_mask`.
1718 if unlikely(unsafe { self.is_bucket_full(index) }) {
1719 debug_assert!(self.bucket_mask < Group::WIDTH);
1720 // SAFETY:
1721 //
1722 // * Since the caller of this function ensures that the control bytes are properly
1723 // initialized and `ptr = self.ctrl(0)` points to the start of the array of control
1724 // bytes, therefore: `ctrl` is valid for reads, properly aligned to `Group::WIDTH`
1725 // and points to the properly initialized control bytes (see also
1726 // `TableLayout::calculate_layout_for` and `ptr::read`);
1727 //
1728 // * Because the caller of this function ensures that the index was provided by the
1729 // `self.find_insert_index_in_group()` function, so for for tables larger than the
1730 // group width (self.num_buckets() >= Group::WIDTH), we will never end up in the given
1731 // branch, since `(probe_seq.pos + bit) & self.bucket_mask` in `find_insert_index_in_group`
1732 // cannot return a full bucket index. For tables smaller than the group width, calling
1733 // the `unwrap_unchecked` function is also safe, as the trailing control bytes outside
1734 // the range of the table are filled with EMPTY bytes (and we know for sure that there
1735 // is at least one FULL bucket), so this second scan either finds an empty slot (due to
1736 // the load factor) or hits the trailing control bytes (containing EMPTY).
1737 index = unsafe {
1738 Group::load_aligned(self.ctrl(0))
1739 .match_empty_or_deleted()
1740 .lowest_set_bit()
1741 .unwrap_unchecked()
1742 };
1743 }
1744 index
1745 }
1746
1747 /// Finds the position to insert something in a group.
1748 ///
1749 /// **This may have false positives and must be fixed up with `fix_insert_index`
1750 /// before it's used.**
1751 ///
1752 /// The function is guaranteed to return the index of an empty or deleted [`Bucket`]
1753 /// in the range `0..self.num_buckets()` (`0..=self.bucket_mask`).
1754 #[inline]
1755 fn find_insert_index_in_group(&self, group: &Group, probe_seq: &ProbeSeq) -> Option<usize> {
1756 let bit = group.match_empty_or_deleted().lowest_set_bit();
1757
1758 if likely(bit.is_some()) {
1759 // This is the same as `(probe_seq.pos + bit) % self.num_buckets()` because the number
1760 // of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
1761 Some((probe_seq.pos + bit.unwrap()) & self.bucket_mask)
1762 } else {
1763 None
1764 }
1765 }
1766
1767 /// Searches for an element in the table, or a potential slot where that element could
1768 /// be inserted (an empty or deleted [`Bucket`] index).
1769 ///
1770 /// This uses dynamic dispatch to reduce the amount of code generated, but that is
1771 /// eliminated by LLVM optimizations.
1772 ///
1773 /// This function does not make any changes to the `data` part of the table, or any
1774 /// changes to the `items` or `growth_left` field of the table.
1775 ///
1776 /// The table must have at least 1 empty or deleted `bucket`, otherwise, if the
1777 /// `eq: &mut dyn FnMut(usize) -> bool` function does not return `true`, this function
1778 /// will never return (will go into an infinite loop) for tables larger than the group
1779 /// width, or return an index outside of the table indices range if the table is less
1780 /// than the group width.
1781 ///
1782 /// This function is guaranteed to provide the `eq: &mut dyn FnMut(usize) -> bool`
1783 /// function with only `FULL` buckets' indices and return the `index` of the found
1784 /// element (as `Ok(index)`). If the element is not found and there is at least 1
1785 /// empty or deleted [`Bucket`] in the table, the function is guaranteed to return
1786 /// an index in the range `0..self.num_buckets()`, but in any case, if this function
1787 /// returns `Err`, it will contain an index in the range `0..=self.num_buckets()`.
1788 ///
1789 /// # Safety
1790 ///
1791 /// The [`RawTableInner`] must have properly initialized control bytes otherwise calling
1792 /// this function results in [`undefined behavior`].
1793 ///
1794 /// Attempt to write data at the index returned by this function when the table is less than
1795 /// the group width and if there was not at least one empty or deleted bucket in the table
1796 /// will cause immediate [`undefined behavior`]. This is because in this case the function
1797 /// will return `self.bucket_mask + 1` as an index due to the trailing [`Tag::EMPTY`] control
1798 /// bytes outside the table range.
1799 ///
1800 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1801 #[inline]
1802 unsafe fn find_or_find_insert_index_inner(
1803 &self,
1804 hash: u64,
1805 eq: &mut dyn FnMut(usize) -> bool,
1806 ) -> Result<usize, usize> {
1807 let mut insert_index = None;
1808
1809 let tag_hash = Tag::full(hash);
1810 let mut probe_seq = self.probe_seq(hash);
1811
1812 loop {
1813 // SAFETY:
1814 // * Caller of this function ensures that the control bytes are properly initialized.
1815 //
1816 // * `ProbeSeq.pos` cannot be greater than `self.bucket_mask = self.num_buckets() - 1`
1817 // of the table due to masking with `self.bucket_mask` and also because the number
1818 // of buckets is a power of two (see `self.probe_seq` function).
1819 //
1820 // * Even if `ProbeSeq.pos` returns `position == self.bucket_mask`, it is safe to
1821 // call `Group::load` due to the extended control bytes range, which is
1822 // `self.bucket_mask + 1 + Group::WIDTH` (in fact, this means that the last control
1823 // byte will never be read for the allocated table);
1824 //
1825 // * Also, even if `RawTableInner` is not already allocated, `ProbeSeq.pos` will
1826 // always return "0" (zero), so Group::load will read unaligned `Group::static_empty()`
1827 // bytes, which is safe (see RawTableInner::new).
1828 let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) };
1829
1830 for bit in group.match_tag(tag_hash) {
1831 let index = (probe_seq.pos + bit) & self.bucket_mask;
1832
1833 if likely(eq(index)) {
1834 return Ok(index);
1835 }
1836 }
1837
1838 // We didn't find the element we were looking for in the group, try to get an
1839 // insertion slot from the group if we don't have one yet.
1840 if likely(insert_index.is_none()) {
1841 insert_index = self.find_insert_index_in_group(&group, &probe_seq);
1842 }
1843
1844 if let Some(insert_index) = insert_index {
1845 // Only stop the search if the group contains at least one empty element.
1846 // Otherwise, the element that we are looking for might be in a following group.
1847 if likely(group.match_empty().any_bit_set()) {
1848 // We must have found a insert slot by now, since the current group contains at
1849 // least one. For tables smaller than the group width, there will still be an
1850 // empty element in the current (and only) group due to the load factor.
1851 unsafe {
1852 // SAFETY:
1853 // * Caller of this function ensures that the control bytes are properly initialized.
1854 //
1855 // * We use this function with the index found by `self.find_insert_index_in_group`
1856 return Err(self.fix_insert_index(insert_index));
1857 }
1858 }
1859 }
1860
1861 probe_seq.move_next(self.bucket_mask);
1862 }
1863 }
1864
1865 /// Searches for an empty or deleted bucket which is suitable for inserting a new
1866 /// element and sets the hash for that slot. Returns an index of that slot and the
1867 /// old control byte stored in the found index.
1868 ///
1869 /// This function does not check if the given element exists in the table. Also,
1870 /// this function does not check if there is enough space in the table to insert
1871 /// a new element. The caller of the function must make sure that the table has at
1872 /// least 1 empty or deleted `bucket`, otherwise this function will never return
1873 /// (will go into an infinite loop) for tables larger than the group width, or
1874 /// return an index outside of the table indices range if the table is less than
1875 /// the group width.
1876 ///
1877 /// If there is at least 1 empty or deleted `bucket` in the table, the function is
1878 /// guaranteed to return an `index` in the range `0..self.num_buckets()`, but in any case,
1879 /// if this function returns an `index` it will be in the range `0..=self.num_buckets()`.
1880 ///
1881 /// This function does not make any changes to the `data` parts of the table,
1882 /// or any changes to the `items` or `growth_left` field of the table.
1883 ///
1884 /// # Safety
1885 ///
1886 /// The safety rules are directly derived from the safety rules for the
1887 /// [`RawTableInner::set_ctrl_hash`] and [`RawTableInner::find_insert_index`] methods.
1888 /// Thus, in order to uphold the safety contracts for that methods, as well as for
1889 /// the correct logic of the work of this crate, you must observe the following rules
1890 /// when calling this function:
1891 ///
1892 /// * The [`RawTableInner`] has already been allocated and has properly initialized
1893 /// control bytes otherwise calling this function results in [`undefined behavior`].
1894 ///
1895 /// * The caller of this function must ensure that the "data" parts of the table
1896 /// will have an entry in the returned index (matching the given hash) right
1897 /// after calling this function.
1898 ///
1899 /// Attempt to write data at the `index` returned by this function when the table is
1900 /// less than the group width and if there was not at least one empty or deleted bucket in
1901 /// the table will cause immediate [`undefined behavior`]. This is because in this case the
1902 /// function will return `self.bucket_mask + 1` as an index due to the trailing [`Tag::EMPTY`]
1903 /// control bytes outside the table range.
1904 ///
1905 /// The caller must independently increase the `items` field of the table, and also,
1906 /// if the old control byte was [`Tag::EMPTY`], then decrease the table's `growth_left`
1907 /// field, and do not change it if the old control byte was [`Tag::DELETED`].
1908 ///
1909 /// See also [`Bucket::as_ptr`] method, for more information about of properly removing
1910 /// or saving `element` from / into the [`RawTable`] / [`RawTableInner`].
1911 ///
1912 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1913 #[inline]
1914 unsafe fn prepare_insert_index(&mut self, hash: u64) -> (usize, Tag) {
1915 unsafe {
1916 // SAFETY: Caller of this function ensures that the control bytes are properly initialized.
1917 let index: usize = self.find_insert_index(hash);
1918 // SAFETY:
1919 // 1. The `find_insert_index` function either returns an `index` less than or
1920 // equal to `self.num_buckets() = self.bucket_mask + 1` of the table, or never
1921 // returns if it cannot find an empty or deleted slot.
1922 // 2. The caller of this function guarantees that the table has already been
1923 // allocated
1924 let old_ctrl = *self.ctrl(index);
1925 self.set_ctrl_hash(index, hash);
1926 (index, old_ctrl)
1927 }
1928 }
1929
1930 /// Searches for an empty or deleted bucket which is suitable for inserting
1931 /// a new element, returning the `index` for the new [`Bucket`].
1932 ///
1933 /// This function does not make any changes to the `data` part of the table, or any
1934 /// changes to the `items` or `growth_left` field of the table.
1935 ///
1936 /// The table must have at least 1 empty or deleted `bucket`, otherwise this function
1937 /// will never return (will go into an infinite loop) for tables larger than the group
1938 /// width, or return an index outside of the table indices range if the table is less
1939 /// than the group width.
1940 ///
1941 /// If there is at least 1 empty or deleted `bucket` in the table, the function is
1942 /// guaranteed to return an index in the range `0..self.num_buckets()`, but in any case,
1943 /// it will contain an index in the range `0..=self.num_buckets()`.
1944 ///
1945 /// # Safety
1946 ///
1947 /// The [`RawTableInner`] must have properly initialized control bytes otherwise calling
1948 /// this function results in [`undefined behavior`].
1949 ///
1950 /// Attempt to write data at the index returned by this function when the table is
1951 /// less than the group width and if there was not at least one empty or deleted bucket in
1952 /// the table will cause immediate [`undefined behavior`]. This is because in this case the
1953 /// function will return `self.bucket_mask + 1` as an index due to the trailing [`Tag::EMPTY`]
1954 /// control bytes outside the table range.
1955 ///
1956 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1957 #[inline]
1958 unsafe fn find_insert_index(&self, hash: u64) -> usize {
1959 let mut probe_seq = self.probe_seq(hash);
1960 loop {
1961 // SAFETY:
1962 // * Caller of this function ensures that the control bytes are properly initialized.
1963 //
1964 // * `ProbeSeq.pos` cannot be greater than `self.bucket_mask = self.num_buckets() - 1`
1965 // of the table due to masking with `self.bucket_mask` and also because the number
1966 // of buckets is a power of two (see `self.probe_seq` function).
1967 //
1968 // * Even if `ProbeSeq.pos` returns `position == self.bucket_mask`, it is safe to
1969 // call `Group::load` due to the extended control bytes range, which is
1970 // `self.bucket_mask + 1 + Group::WIDTH` (in fact, this means that the last control
1971 // byte will never be read for the allocated table);
1972 //
1973 // * Also, even if `RawTableInner` is not already allocated, `ProbeSeq.pos` will
1974 // always return "0" (zero), so Group::load will read unaligned `Group::static_empty()`
1975 // bytes, which is safe (see RawTableInner::new).
1976 let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) };
1977
1978 let index = self.find_insert_index_in_group(&group, &probe_seq);
1979 if likely(index.is_some()) {
1980 // SAFETY:
1981 // * Caller of this function ensures that the control bytes are properly initialized.
1982 //
1983 // * We use this function with the slot / index found by `self.find_insert_index_in_group`
1984 unsafe {
1985 return self.fix_insert_index(index.unwrap_unchecked());
1986 }
1987 }
1988 probe_seq.move_next(self.bucket_mask);
1989 }
1990 }
1991
1992 /// Searches for an element in a table, returning the `index` of the found element.
1993 /// This uses dynamic dispatch to reduce the amount of code generated, but it is
1994 /// eliminated by LLVM optimizations.
1995 ///
1996 /// This function does not make any changes to the `data` part of the table, or any
1997 /// changes to the `items` or `growth_left` field of the table.
1998 ///
1999 /// The table must have at least 1 empty `bucket`, otherwise, if the
2000 /// `eq: &mut dyn FnMut(usize) -> bool` function does not return `true`,
2001 /// this function will also never return (will go into an infinite loop).
2002 ///
2003 /// This function is guaranteed to provide the `eq: &mut dyn FnMut(usize) -> bool`
2004 /// function with only `FULL` buckets' indices and return the `index` of the found
2005 /// element as `Some(index)`, so the index will always be in the range
2006 /// `0..self.num_buckets()`.
2007 ///
2008 /// # Safety
2009 ///
2010 /// The [`RawTableInner`] must have properly initialized control bytes otherwise calling
2011 /// this function results in [`undefined behavior`].
2012 ///
2013 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2014 #[inline(always)]
2015 unsafe fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option<usize> {
2016 let tag_hash = Tag::full(hash);
2017 let mut probe_seq = self.probe_seq(hash);
2018
2019 loop {
2020 // SAFETY:
2021 // * Caller of this function ensures that the control bytes are properly initialized.
2022 //
2023 // * `ProbeSeq.pos` cannot be greater than `self.bucket_mask = self.num_buckets() - 1`
2024 // of the table due to masking with `self.bucket_mask`.
2025 //
2026 // * Even if `ProbeSeq.pos` returns `position == self.bucket_mask`, it is safe to
2027 // call `Group::load` due to the extended control bytes range, which is
2028 // `self.bucket_mask + 1 + Group::WIDTH` (in fact, this means that the last control
2029 // byte will never be read for the allocated table);
2030 //
2031 // * Also, even if `RawTableInner` is not already allocated, `ProbeSeq.pos` will
2032 // always return "0" (zero), so Group::load will read unaligned `Group::static_empty()`
2033 // bytes, which is safe (see RawTableInner::new_in).
2034 let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) };
2035
2036 for bit in group.match_tag(tag_hash) {
2037 // This is the same as `(probe_seq.pos + bit) % self.num_buckets()` because the number
2038 // of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2039 let index = (probe_seq.pos + bit) & self.bucket_mask;
2040
2041 if likely(eq(index)) {
2042 return Some(index);
2043 }
2044 }
2045
2046 if likely(group.match_empty().any_bit_set()) {
2047 return None;
2048 }
2049
2050 probe_seq.move_next(self.bucket_mask);
2051 }
2052 }
2053
2054 /// Prepares for rehashing data in place (that is, without allocating new memory).
2055 /// Converts all full index `control bytes` to `Tag::DELETED` and all `Tag::DELETED` control
2056 /// bytes to `Tag::EMPTY`, i.e. performs the following conversion:
2057 ///
2058 /// - `Tag::EMPTY` control bytes -> `Tag::EMPTY`;
2059 /// - `Tag::DELETED` control bytes -> `Tag::EMPTY`;
2060 /// - `FULL` control bytes -> `Tag::DELETED`.
2061 ///
2062 /// This function does not make any changes to the `data` parts of the table,
2063 /// or any changes to the `items` or `growth_left` field of the table.
2064 ///
2065 /// # Safety
2066 ///
2067 /// You must observe the following safety rules when calling this function:
2068 ///
2069 /// * The [`RawTableInner`] has already been allocated;
2070 ///
2071 /// * The caller of this function must convert the `Tag::DELETED` bytes back to `FULL`
2072 /// bytes when re-inserting them into their ideal position (which was impossible
2073 /// to do during the first insert due to tombstones). If the caller does not do
2074 /// this, then calling this function may result in a memory leak.
2075 ///
2076 /// * The [`RawTableInner`] must have properly initialized control bytes otherwise
2077 /// calling this function results in [`undefined behavior`].
2078 ///
2079 /// Calling this function on a table that has not been allocated results in
2080 /// [`undefined behavior`].
2081 ///
2082 /// See also [`Bucket::as_ptr`] method, for more information about of properly removing
2083 /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
2084 ///
2085 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2086 #[inline]
2087 unsafe fn prepare_rehash_in_place(&mut self) {
2088 // Bulk convert all full control bytes to DELETED, and all DELETED control bytes to EMPTY.
2089 // This effectively frees up all buckets containing a DELETED entry.
2090 //
2091 // SAFETY:
2092 // 1. `i` is guaranteed to be within bounds since we are iterating from zero to `buckets - 1`;
2093 // 2. Even if `i` will be `i == self.bucket_mask`, it is safe to call `Group::load_aligned`
2094 // due to the extended control bytes range, which is `self.bucket_mask + 1 + Group::WIDTH`;
2095 // 3. The caller of this function guarantees that [`RawTableInner`] has already been allocated;
2096 // 4. We can use `Group::load_aligned` and `Group::store_aligned` here since we start from 0
2097 // and go to the end with a step equal to `Group::WIDTH` (see TableLayout::calculate_layout_for).
2098 unsafe {
2099 for i in (0..self.num_buckets()).step_by(Group::WIDTH) {
2100 let group = Group::load_aligned(self.ctrl(i));
2101 let group = group.convert_special_to_empty_and_full_to_deleted();
2102 group.store_aligned(self.ctrl(i));
2103 }
2104 }
2105
2106 // Fix up the trailing control bytes. See the comments in set_ctrl
2107 // for the handling of tables smaller than the group width.
2108 if unlikely(self.num_buckets() < Group::WIDTH) {
2109 // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of control bytes,
2110 // so copying `self.num_buckets() == self.bucket_mask + 1` bytes with offset equal to
2111 // `Group::WIDTH` is safe
2112 unsafe {
2113 self.ctrl(0)
2114 .copy_to(self.ctrl(Group::WIDTH), self.num_buckets());
2115 }
2116 } else {
2117 // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of
2118 // control bytes,so copying `Group::WIDTH` bytes with offset equal
2119 // to `self.num_buckets() == self.bucket_mask + 1` is safe
2120 unsafe {
2121 self.ctrl(0)
2122 .copy_to(self.ctrl(self.num_buckets()), Group::WIDTH);
2123 }
2124 }
2125 }
2126
2127 /// Returns an iterator over every element in the table.
2128 ///
2129 /// # Safety
2130 ///
2131 /// If any of the following conditions are violated, the result
2132 /// is [`undefined behavior`]:
2133 ///
2134 /// * The caller has to ensure that the `RawTableInner` outlives the
2135 /// `RawIter`. Because we cannot make the `next` method unsafe on
2136 /// the `RawIter` struct, we have to make the `iter` method unsafe.
2137 ///
2138 /// * The [`RawTableInner`] must have properly initialized control bytes.
2139 ///
2140 /// The type `T` must be the actual type of the elements stored in the table,
2141 /// otherwise using the returned [`RawIter`] results in [`undefined behavior`].
2142 ///
2143 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2144 #[inline]
2145 unsafe fn iter<T>(&self) -> RawIter<T> {
2146 // SAFETY:
2147 // 1. Since the caller of this function ensures that the control bytes
2148 // are properly initialized and `self.data_end()` points to the start
2149 // of the array of control bytes, therefore: `ctrl` is valid for reads,
2150 // properly aligned to `Group::WIDTH` and points to the properly initialized
2151 // control bytes.
2152 // 2. `data` bucket index in the table is equal to the `ctrl` index (i.e.
2153 // equal to zero).
2154 // 3. We pass the exact value of buckets of the table to the function.
2155 //
2156 // `ctrl` points here (to the start
2157 // of the first control byte `CT0`)
2158 // ∨
2159 // [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m
2160 // \________ ________/
2161 // \/
2162 // `n = buckets - 1`, i.e. `RawTableInner::num_buckets() - 1`
2163 //
2164 // where: T0...T_n - our stored data;
2165 // CT0...CT_n - control bytes or metadata for `data`.
2166 // CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search
2167 // with loading `Group` bytes from the heap works properly, even if the result
2168 // of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also
2169 // `RawTableInner::set_ctrl` function.
2170 //
2171 // P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.num_buckets()` because the number
2172 // of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2173 unsafe {
2174 let data = Bucket::from_base_index(self.data_end(), 0);
2175 RawIter {
2176 // SAFETY: See explanation above
2177 iter: RawIterRange::new(self.ctrl.as_ptr(), data, self.num_buckets()),
2178 items: self.items,
2179 }
2180 }
2181 }
2182
2183 /// Executes the destructors (if any) of the values stored in the table.
2184 ///
2185 /// # Note
2186 ///
2187 /// This function does not erase the control bytes of the table and does
2188 /// not make any changes to the `items` or `growth_left` fields of the
2189 /// table. If necessary, the caller of this function must manually set
2190 /// up these table fields, for example using the [`clear_no_drop`] function.
2191 ///
2192 /// Be careful during calling this function, because drop function of
2193 /// the elements can panic, and this can leave table in an inconsistent
2194 /// state.
2195 ///
2196 /// # Safety
2197 ///
2198 /// The type `T` must be the actual type of the elements stored in the table,
2199 /// otherwise calling this function may result in [`undefined behavior`].
2200 ///
2201 /// If `T` is a type that should be dropped and **the table is not empty**,
2202 /// calling this function more than once results in [`undefined behavior`].
2203 ///
2204 /// If `T` is not [`Copy`], attempting to use values stored in the table after
2205 /// calling this function may result in [`undefined behavior`].
2206 ///
2207 /// It is safe to call this function on a table that has not been allocated,
2208 /// on a table with uninitialized control bytes, and on a table with no actual
2209 /// data but with `Full` control bytes if `self.items == 0`.
2210 ///
2211 /// See also [`Bucket::drop`] / [`Bucket::as_ptr`] methods, for more information
2212 /// about of properly removing or saving `element` from / into the [`RawTable`] /
2213 /// [`RawTableInner`].
2214 ///
2215 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2216 unsafe fn drop_elements<T>(&mut self) {
2217 // Check that `self.items != 0`. Protects against the possibility
2218 // of creating an iterator on an table with uninitialized control bytes.
2219 if T::NEEDS_DROP && self.items != 0 {
2220 // SAFETY: We know for sure that RawTableInner will outlive the
2221 // returned `RawIter` iterator, and the caller of this function
2222 // must uphold the safety contract for `drop_elements` method.
2223 unsafe {
2224 for item in self.iter::<T>() {
2225 // SAFETY: The caller must uphold the safety contract for
2226 // `drop_elements` method.
2227 item.drop();
2228 }
2229 }
2230 }
2231 }
2232
2233 /// Executes the destructors (if any) of the values stored in the table and than
2234 /// deallocates the table.
2235 ///
2236 /// # Note
2237 ///
2238 /// Calling this function automatically makes invalid (dangling) all instances of
2239 /// buckets ([`Bucket`]) and makes invalid (dangling) the `ctrl` field of the table.
2240 ///
2241 /// This function does not make any changes to the `bucket_mask`, `items` or `growth_left`
2242 /// fields of the table. If necessary, the caller of this function must manually set
2243 /// up these table fields.
2244 ///
2245 /// # Safety
2246 ///
2247 /// If any of the following conditions are violated, the result is [`undefined behavior`]:
2248 ///
2249 /// * Calling this function more than once;
2250 ///
2251 /// * The type `T` must be the actual type of the elements stored in the table.
2252 ///
2253 /// * The `alloc` must be the same [`Allocator`] as the `Allocator` that was used
2254 /// to allocate this table.
2255 ///
2256 /// * The `table_layout` must be the same [`TableLayout`] as the `TableLayout` that
2257 /// was used to allocate this table.
2258 ///
2259 /// The caller of this function should pay attention to the possibility of the
2260 /// elements' drop function panicking, because this:
2261 ///
2262 /// * May leave the table in an inconsistent state;
2263 ///
2264 /// * Memory is never deallocated, so a memory leak may occur.
2265 ///
2266 /// Attempt to use the `ctrl` field of the table (dereference) after calling this
2267 /// function results in [`undefined behavior`].
2268 ///
2269 /// It is safe to call this function on a table that has not been allocated,
2270 /// on a table with uninitialized control bytes, and on a table with no actual
2271 /// data but with `Full` control bytes if `self.items == 0`.
2272 ///
2273 /// See also [`RawTableInner::drop_elements`] or [`RawTableInner::free_buckets`]
2274 /// for more information.
2275 ///
2276 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2277 unsafe fn drop_inner_table<T, A: Allocator>(&mut self, alloc: &A, table_layout: TableLayout) {
2278 if !self.is_empty_singleton() {
2279 // SAFETY: The caller must uphold the safety contract for `drop_inner_table` method.
2280 unsafe {
2281 self.drop_elements::<T>();
2282 }
2283 // SAFETY:
2284 // 1. We have checked that our table is allocated.
2285 // 2. The caller must uphold the safety contract for `drop_inner_table` method.
2286 unsafe {
2287 self.free_buckets(alloc, table_layout);
2288 }
2289 }
2290 }
2291
2292 /// Returns a pointer to an element in the table (convenience for
2293 /// `Bucket::from_base_index(self.data_end::<T>(), index)`).
2294 ///
2295 /// The caller must ensure that the `RawTableInner` outlives the returned [`Bucket<T>`],
2296 /// otherwise using it may result in [`undefined behavior`].
2297 ///
2298 /// # Safety
2299 ///
2300 /// If `size_of::<T>() != 0`, then the safety rules are directly derived from the
2301 /// safety rules of the [`Bucket::from_base_index`] function. Therefore, when calling
2302 /// this function, the following safety rules must be observed:
2303 ///
2304 /// * The table must already be allocated;
2305 ///
2306 /// * The `index` must not be greater than the number returned by the [`RawTableInner::num_buckets`]
2307 /// function, i.e. `(index + 1) <= self.num_buckets()`.
2308 ///
2309 /// * The type `T` must be the actual type of the elements stored in the table, otherwise
2310 /// using the returned [`Bucket`] may result in [`undefined behavior`].
2311 ///
2312 /// It is safe to call this function with index of zero (`index == 0`) on a table that has
2313 /// not been allocated, but using the returned [`Bucket`] results in [`undefined behavior`].
2314 ///
2315 /// If `size_of::<T>() == 0`, then the only requirement is that the `index` must
2316 /// not be greater than the number returned by the [`RawTable::num_buckets`] function, i.e.
2317 /// `(index + 1) <= self.num_buckets()`.
2318 ///
2319 /// ```none
2320 /// If size_of::<T>() != 0 then return a pointer to the `element` in the `data part` of the table
2321 /// (we start counting from "0", so that in the expression T[n], the "n" index actually one less than
2322 /// the "buckets" number of our `RawTableInner`, i.e. "n = RawTableInner::num_buckets() - 1"):
2323 ///
2324 /// `table.bucket(3).as_ptr()` returns a pointer that points here in the `data`
2325 /// part of the `RawTableInner`, i.e. to the start of T3 (see [`Bucket::as_ptr`])
2326 /// |
2327 /// | `base = table.data_end::<T>()` points here
2328 /// | (to the start of CT0 or to the end of T0)
2329 /// v v
2330 /// [Pad], T_n, ..., |T3|, T2, T1, T0, |CT0, CT1, CT2, CT3, ..., CT_n, CTa_0, CTa_1, ..., CTa_m
2331 /// ^ \__________ __________/
2332 /// `table.bucket(3)` returns a pointer that points \/
2333 /// here in the `data` part of the `RawTableInner` additional control bytes
2334 /// (to the end of T3) `m = Group::WIDTH - 1`
2335 ///
2336 /// where: T0...T_n - our stored data;
2337 /// CT0...CT_n - control bytes or metadata for `data`;
2338 /// CTa_0...CTa_m - additional control bytes (so that the search with loading `Group` bytes from
2339 /// the heap works properly, even if the result of `h1(hash) & self.bucket_mask`
2340 /// is equal to `self.bucket_mask`). See also `RawTableInner::set_ctrl` function.
2341 ///
2342 /// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.num_buckets()` because the number
2343 /// of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2344 /// ```
2345 ///
2346 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2347 #[inline]
2348 unsafe fn bucket<T>(&self, index: usize) -> Bucket<T> {
2349 debug_assert_ne!(self.bucket_mask, 0);
2350 debug_assert!(index < self.num_buckets());
2351 unsafe { Bucket::from_base_index(self.data_end(), index) }
2352 }
2353
2354 /// Returns a raw `*mut u8` pointer to the start of the `data` element in the table
2355 /// (convenience for `self.data_end::<u8>().as_ptr().sub((index + 1) * size_of)`).
2356 ///
2357 /// The caller must ensure that the `RawTableInner` outlives the returned `*mut u8`,
2358 /// otherwise using it may result in [`undefined behavior`].
2359 ///
2360 /// # Safety
2361 ///
2362 /// If any of the following conditions are violated, the result is [`undefined behavior`]:
2363 ///
2364 /// * The table must already be allocated;
2365 ///
2366 /// * The `index` must not be greater than the number returned by the [`RawTableInner::num_buckets`]
2367 /// function, i.e. `(index + 1) <= self.num_buckets()`;
2368 ///
2369 /// * The `size_of` must be equal to the size of the elements stored in the table;
2370 ///
2371 /// ```none
2372 /// If size_of::<T>() != 0 then return a pointer to the `element` in the `data part` of the table
2373 /// (we start counting from "0", so that in the expression T[n], the "n" index actually one less than
2374 /// the "buckets" number of our `RawTableInner`, i.e. "n = RawTableInner::num_buckets() - 1"):
2375 ///
2376 /// `table.bucket_ptr(3, size_of::<T>())` returns a pointer that points here in the
2377 /// `data` part of the `RawTableInner`, i.e. to the start of T3
2378 /// |
2379 /// | `base = table.data_end::<u8>()` points here
2380 /// | (to the start of CT0 or to the end of T0)
2381 /// v v
2382 /// [Pad], T_n, ..., |T3|, T2, T1, T0, |CT0, CT1, CT2, CT3, ..., CT_n, CTa_0, CTa_1, ..., CTa_m
2383 /// \__________ __________/
2384 /// \/
2385 /// additional control bytes
2386 /// `m = Group::WIDTH - 1`
2387 ///
2388 /// where: T0...T_n - our stored data;
2389 /// CT0...CT_n - control bytes or metadata for `data`;
2390 /// CTa_0...CTa_m - additional control bytes (so that the search with loading `Group` bytes from
2391 /// the heap works properly, even if the result of `h1(hash) & self.bucket_mask`
2392 /// is equal to `self.bucket_mask`). See also `RawTableInner::set_ctrl` function.
2393 ///
2394 /// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.num_buckets()` because the number
2395 /// of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2396 /// ```
2397 ///
2398 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2399 #[inline]
2400 unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 {
2401 debug_assert_ne!(self.bucket_mask, 0);
2402 debug_assert!(index < self.num_buckets());
2403 unsafe {
2404 let base: *mut u8 = self.data_end().as_ptr();
2405 base.sub((index + 1) * size_of)
2406 }
2407 }
2408
2409 /// Returns pointer to one past last `data` element in the table as viewed from
2410 /// the start point of the allocation (convenience for `self.ctrl.cast()`).
2411 ///
2412 /// This function actually returns a pointer to the end of the `data element` at
2413 /// index "0" (zero).
2414 ///
2415 /// The caller must ensure that the `RawTableInner` outlives the returned [`NonNull<T>`],
2416 /// otherwise using it may result in [`undefined behavior`].
2417 ///
2418 /// # Note
2419 ///
2420 /// The type `T` must be the actual type of the elements stored in the table, otherwise
2421 /// using the returned [`NonNull<T>`] may result in [`undefined behavior`].
2422 ///
2423 /// ```none
2424 /// `table.data_end::<T>()` returns pointer that points here
2425 /// (to the end of `T0`)
2426 /// ∨
2427 /// [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, CTa_0, CTa_1, ..., CTa_m
2428 /// \________ ________/
2429 /// \/
2430 /// `n = buckets - 1`, i.e. `RawTableInner::num_buckets() - 1`
2431 ///
2432 /// where: T0...T_n - our stored data;
2433 /// CT0...CT_n - control bytes or metadata for `data`.
2434 /// CTa_0...CTa_m - additional control bytes, where `m = Group::WIDTH - 1` (so that the search
2435 /// with loading `Group` bytes from the heap works properly, even if the result
2436 /// of `h1(hash) & self.bucket_mask` is equal to `self.bucket_mask`). See also
2437 /// `RawTableInner::set_ctrl` function.
2438 ///
2439 /// P.S. `h1(hash) & self.bucket_mask` is the same as `hash as usize % self.num_buckets()` because the number
2440 /// of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2441 /// ```
2442 ///
2443 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2444 #[inline]
2445 fn data_end<T>(&self) -> NonNull<T> {
2446 self.ctrl.cast()
2447 }
2448
2449 /// Returns an iterator-like object for a probe sequence on the table.
2450 ///
2451 /// This iterator never terminates, but is guaranteed to visit each bucket
2452 /// group exactly once. The loop using `probe_seq` must terminate upon
2453 /// reaching a group containing an empty bucket.
2454 #[inline]
2455 fn probe_seq(&self, hash: u64) -> ProbeSeq {
2456 ProbeSeq {
2457 // This is the same as `hash as usize % self.num_buckets()` because the number
2458 // of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2459 pos: h1(hash) & self.bucket_mask,
2460 stride: 0,
2461 }
2462 }
2463
2464 #[inline]
2465 unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: Tag, new_ctrl: Tag) {
2466 self.growth_left -= usize::from(old_ctrl.special_is_empty());
2467 unsafe {
2468 self.set_ctrl(index, new_ctrl);
2469 }
2470 self.items += 1;
2471 }
2472
2473 #[inline]
2474 fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool {
2475 let probe_seq_pos = self.probe_seq(hash).pos;
2476 let probe_index =
2477 |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH;
2478 probe_index(i) == probe_index(new_i)
2479 }
2480
2481 /// Sets a control byte to the hash, and possibly also the replicated control byte at
2482 /// the end of the array.
2483 ///
2484 /// This function does not make any changes to the `data` parts of the table,
2485 /// or any changes to the `items` or `growth_left` field of the table.
2486 ///
2487 /// # Safety
2488 ///
2489 /// The safety rules are directly derived from the safety rules for [`RawTableInner::set_ctrl`]
2490 /// method. Thus, in order to uphold the safety contracts for the method, you must observe the
2491 /// following rules when calling this function:
2492 ///
2493 /// * The [`RawTableInner`] has already been allocated;
2494 ///
2495 /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e.
2496 /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must
2497 /// be no greater than the number returned by the function [`RawTableInner::num_buckets`].
2498 ///
2499 /// Calling this function on a table that has not been allocated results in [`undefined behavior`].
2500 ///
2501 /// See also [`Bucket::as_ptr`] method, for more information about of properly removing
2502 /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
2503 ///
2504 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2505 #[inline]
2506 unsafe fn set_ctrl_hash(&mut self, index: usize, hash: u64) {
2507 unsafe {
2508 // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::set_ctrl_hash`]
2509 self.set_ctrl(index, Tag::full(hash));
2510 }
2511 }
2512
2513 /// Replaces the hash in the control byte at the given index with the provided one,
2514 /// and possibly also replicates the new control byte at the end of the array of control
2515 /// bytes, returning the old control byte.
2516 ///
2517 /// This function does not make any changes to the `data` parts of the table,
2518 /// or any changes to the `items` or `growth_left` field of the table.
2519 ///
2520 /// # Safety
2521 ///
2522 /// The safety rules are directly derived from the safety rules for [`RawTableInner::set_ctrl_hash`]
2523 /// and [`RawTableInner::ctrl`] methods. Thus, in order to uphold the safety contracts for both
2524 /// methods, you must observe the following rules when calling this function:
2525 ///
2526 /// * The [`RawTableInner`] has already been allocated;
2527 ///
2528 /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e.
2529 /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must
2530 /// be no greater than the number returned by the function [`RawTableInner::num_buckets`].
2531 ///
2532 /// Calling this function on a table that has not been allocated results in [`undefined behavior`].
2533 ///
2534 /// See also [`Bucket::as_ptr`] method, for more information about of properly removing
2535 /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
2536 ///
2537 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2538 #[inline]
2539 unsafe fn replace_ctrl_hash(&mut self, index: usize, hash: u64) -> Tag {
2540 unsafe {
2541 // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::replace_ctrl_hash`]
2542 let prev_ctrl = *self.ctrl(index);
2543 self.set_ctrl_hash(index, hash);
2544 prev_ctrl
2545 }
2546 }
2547
2548 /// Sets a control byte, and possibly also the replicated control byte at
2549 /// the end of the array.
2550 ///
2551 /// This function does not make any changes to the `data` parts of the table,
2552 /// or any changes to the `items` or `growth_left` field of the table.
2553 ///
2554 /// # Safety
2555 ///
2556 /// You must observe the following safety rules when calling this function:
2557 ///
2558 /// * The [`RawTableInner`] has already been allocated;
2559 ///
2560 /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e.
2561 /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must
2562 /// be no greater than the number returned by the function [`RawTableInner::num_buckets`].
2563 ///
2564 /// Calling this function on a table that has not been allocated results in [`undefined behavior`].
2565 ///
2566 /// See also [`Bucket::as_ptr`] method, for more information about of properly removing
2567 /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
2568 ///
2569 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2570 #[inline]
2571 unsafe fn set_ctrl(&mut self, index: usize, ctrl: Tag) {
2572 // Replicate the first Group::WIDTH control bytes at the end of
2573 // the array without using a branch. If the tables smaller than
2574 // the group width (self.num_buckets() < Group::WIDTH),
2575 // `index2 = Group::WIDTH + index`, otherwise `index2` is:
2576 //
2577 // - If index >= Group::WIDTH then index == index2.
2578 // - Otherwise index2 == self.bucket_mask + 1 + index.
2579 //
2580 // The very last replicated control byte is never actually read because
2581 // we mask the initial index for unaligned loads, but we write it
2582 // anyways because it makes the set_ctrl implementation simpler.
2583 //
2584 // If there are fewer buckets than Group::WIDTH then this code will
2585 // replicate the buckets at the end of the trailing group. For example
2586 // with 2 buckets and a group size of 4, the control bytes will look
2587 // like this:
2588 //
2589 // Real | Replicated
2590 // ---------------------------------------------
2591 // | [A] | [B] | [Tag::EMPTY] | [EMPTY] | [A] | [B] |
2592 // ---------------------------------------------
2593
2594 // This is the same as `(index.wrapping_sub(Group::WIDTH)) % self.num_buckets() + Group::WIDTH`
2595 // because the number of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
2596 let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH;
2597
2598 // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::set_ctrl`]
2599 unsafe {
2600 *self.ctrl(index) = ctrl;
2601 *self.ctrl(index2) = ctrl;
2602 }
2603 }
2604
2605 /// Returns a pointer to a control byte.
2606 ///
2607 /// # Safety
2608 ///
2609 /// For the allocated [`RawTableInner`], the result is [`Undefined Behavior`],
2610 /// if the `index` is greater than the `self.bucket_mask + 1 + Group::WIDTH`.
2611 /// In that case, calling this function with `index == self.bucket_mask + 1 + Group::WIDTH`
2612 /// will return a pointer to the end of the allocated table and it is useless on its own.
2613 ///
2614 /// Calling this function with `index >= self.bucket_mask + 1 + Group::WIDTH` on a
2615 /// table that has not been allocated results in [`Undefined Behavior`].
2616 ///
2617 /// So to satisfy both requirements you should always follow the rule that
2618 /// `index < self.bucket_mask + 1 + Group::WIDTH`
2619 ///
2620 /// Calling this function on [`RawTableInner`] that are not already allocated is safe
2621 /// for read-only purpose.
2622 ///
2623 /// See also [`Bucket::as_ptr()`] method, for more information about of properly removing
2624 /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
2625 ///
2626 /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2627 #[inline]
2628 unsafe fn ctrl(&self, index: usize) -> *mut Tag {
2629 debug_assert!(index < self.num_ctrl_bytes());
2630 // SAFETY: The caller must uphold the safety rules for the [`RawTableInner::ctrl`]
2631 unsafe { self.ctrl.as_ptr().add(index).cast() }
2632 }
2633
2634 /// Gets the slice of all control bytes, as possibily uninitialized tags.
2635 fn ctrl_slice(&mut self) -> &mut [mem::MaybeUninit<Tag>] {
2636 // SAFETY: We have the correct number of control bytes.
2637 unsafe { slice::from_raw_parts_mut(self.ctrl.as_ptr().cast(), self.num_ctrl_bytes()) }
2638 }
2639
2640 #[inline]
2641 fn num_buckets(&self) -> usize {
2642 self.bucket_mask + 1
2643 }
2644
2645 /// Checks whether the bucket at `index` is full.
2646 ///
2647 /// # Safety
2648 ///
2649 /// The caller must ensure `index` is less than the number of buckets.
2650 #[inline]
2651 unsafe fn is_bucket_full(&self, index: usize) -> bool {
2652 debug_assert!(index < self.num_buckets());
2653 unsafe { (*self.ctrl(index)).is_full() }
2654 }
2655
2656 #[inline]
2657 fn num_ctrl_bytes(&self) -> usize {
2658 self.bucket_mask + 1 + Group::WIDTH
2659 }
2660
2661 #[inline]
2662 fn is_empty_singleton(&self) -> bool {
2663 self.bucket_mask == 0
2664 }
2665
2666 /// Attempts to allocate a new hash table with at least enough capacity
2667 /// for inserting the given number of elements without reallocating,
2668 /// and return it inside `ScopeGuard` to protect against panic in the hash
2669 /// function.
2670 ///
2671 /// # Note
2672 ///
2673 /// It is recommended (but not required):
2674 ///
2675 /// * That the new table's `capacity` be greater than or equal to `self.items`.
2676 ///
2677 /// * The `alloc` is the same [`Allocator`] as the `Allocator` used
2678 /// to allocate this table.
2679 ///
2680 /// * The `table_layout` is the same [`TableLayout`] as the `TableLayout` used
2681 /// to allocate this table.
2682 ///
2683 /// If `table_layout` does not match the `TableLayout` that was used to allocate
2684 /// this table, then using `mem::swap` with the `self` and the new table returned
2685 /// by this function results in [`undefined behavior`].
2686 ///
2687 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2688 #[inline]
2689 fn prepare_resize<'a, A>(
2690 &self,
2691 alloc: &'a A,
2692 table_layout: TableLayout,
2693 capacity: usize,
2694 fallibility: Fallibility,
2695 ) -> Result<crate::scopeguard::ScopeGuard<Self, impl FnMut(&mut Self) + 'a>, TryReserveError>
2696 where
2697 A: Allocator,
2698 {
2699 debug_assert!(self.items <= capacity);
2700
2701 // Allocate and initialize the new table.
2702 let new_table =
2703 RawTableInner::fallible_with_capacity(alloc, table_layout, capacity, fallibility)?;
2704
2705 // The hash function may panic, in which case we simply free the new
2706 // table without dropping any elements that may have been copied into
2707 // it.
2708 //
2709 // This guard is also used to free the old table on success, see
2710 // the comment at the bottom of this function.
2711 Ok(guard(new_table, move |self_| {
2712 if !self_.is_empty_singleton() {
2713 // SAFETY:
2714 // 1. We have checked that our table is allocated.
2715 // 2. We know for sure that the `alloc` and `table_layout` matches the
2716 // [`Allocator`] and [`TableLayout`] used to allocate this table.
2717 unsafe { self_.free_buckets(alloc, table_layout) };
2718 }
2719 }))
2720 }
2721
2722 /// Reserves or rehashes to make room for `additional` more elements.
2723 ///
2724 /// This uses dynamic dispatch to reduce the amount of
2725 /// code generated, but it is eliminated by LLVM optimizations when inlined.
2726 ///
2727 /// # Safety
2728 ///
2729 /// If any of the following conditions are violated, the result is
2730 /// [`undefined behavior`]:
2731 ///
2732 /// * The `alloc` must be the same [`Allocator`] as the `Allocator` used
2733 /// to allocate this table.
2734 ///
2735 /// * The `layout` must be the same [`TableLayout`] as the `TableLayout`
2736 /// used to allocate this table.
2737 ///
2738 /// * The `drop` function (`fn(*mut u8)`) must be the actual drop function of
2739 /// the elements stored in the table.
2740 ///
2741 /// * The [`RawTableInner`] must have properly initialized control bytes.
2742 ///
2743 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2744 #[expect(clippy::inline_always)]
2745 #[inline(always)]
2746 unsafe fn reserve_rehash_inner<A>(
2747 &mut self,
2748 alloc: &A,
2749 additional: usize,
2750 hasher: &dyn Fn(&mut Self, usize) -> u64,
2751 fallibility: Fallibility,
2752 layout: TableLayout,
2753 drop: Option<unsafe fn(*mut u8)>,
2754 ) -> Result<(), TryReserveError>
2755 where
2756 A: Allocator,
2757 {
2758 // Avoid `Option::ok_or_else` because it bloats LLVM IR.
2759 let Some(new_items) = self.items.checked_add(additional) else {
2760 return Err(fallibility.capacity_overflow());
2761 };
2762 let full_capacity = bucket_mask_to_capacity(self.bucket_mask);
2763 if new_items <= full_capacity / 2 {
2764 // Rehash in-place without re-allocating if we have plenty of spare
2765 // capacity that is locked up due to DELETED entries.
2766
2767 // SAFETY:
2768 // 1. We know for sure that `[`RawTableInner`]` has already been allocated
2769 // (since new_items <= full_capacity / 2);
2770 // 2. The caller ensures that `drop` function is the actual drop function of
2771 // the elements stored in the table.
2772 // 3. The caller ensures that `layout` matches the [`TableLayout`] that was
2773 // used to allocate this table.
2774 // 4. The caller ensures that the control bytes of the `RawTableInner`
2775 // are already initialized.
2776 unsafe {
2777 self.rehash_in_place(hasher, layout.size, drop);
2778 }
2779 Ok(())
2780 } else {
2781 // Otherwise, conservatively resize to at least the next size up
2782 // to avoid churning deletes into frequent rehashes.
2783 //
2784 // SAFETY:
2785 // 1. We know for sure that `capacity >= self.items`.
2786 // 2. The caller ensures that `alloc` and `layout` matches the [`Allocator`] and
2787 // [`TableLayout`] that were used to allocate this table.
2788 // 3. The caller ensures that the control bytes of the `RawTableInner`
2789 // are already initialized.
2790 unsafe {
2791 self.resize_inner(
2792 alloc,
2793 usize::max(new_items, full_capacity + 1),
2794 hasher,
2795 fallibility,
2796 layout,
2797 )
2798 }
2799 }
2800 }
2801
2802 /// Returns an iterator over full buckets indices in the table.
2803 ///
2804 /// # Safety
2805 ///
2806 /// Behavior is undefined if any of the following conditions are violated:
2807 ///
2808 /// * The caller has to ensure that the `RawTableInner` outlives the
2809 /// `FullBucketsIndices`. Because we cannot make the `next` method
2810 /// unsafe on the `FullBucketsIndices` struct, we have to make the
2811 /// `full_buckets_indices` method unsafe.
2812 ///
2813 /// * The [`RawTableInner`] must have properly initialized control bytes.
2814 #[inline(always)]
2815 unsafe fn full_buckets_indices(&self) -> FullBucketsIndices {
2816 // SAFETY:
2817 // 1. Since the caller of this function ensures that the control bytes
2818 // are properly initialized and `self.ctrl(0)` points to the start
2819 // of the array of control bytes, therefore: `ctrl` is valid for reads,
2820 // properly aligned to `Group::WIDTH` and points to the properly initialized
2821 // control bytes.
2822 // 2. The value of `items` is equal to the amount of data (values) added
2823 // to the table.
2824 //
2825 // `ctrl` points here (to the start
2826 // of the first control byte `CT0`)
2827 // ∨
2828 // [Pad], T_n, ..., T1, T0, |CT0, CT1, ..., CT_n|, Group::WIDTH
2829 // \________ ________/
2830 // \/
2831 // `n = buckets - 1`, i.e. `RawTableInner::num_buckets() - 1`
2832 //
2833 // where: T0...T_n - our stored data;
2834 // CT0...CT_n - control bytes or metadata for `data`.
2835 unsafe {
2836 let ctrl = NonNull::new_unchecked(self.ctrl(0).cast::<u8>());
2837
2838 FullBucketsIndices {
2839 // Load the first group
2840 // SAFETY: See explanation above.
2841 current_group: Group::load_aligned(ctrl.as_ptr().cast())
2842 .match_full()
2843 .into_iter(),
2844 group_first_index: 0,
2845 ctrl,
2846 items: self.items,
2847 }
2848 }
2849 }
2850
2851 /// Allocates a new table of a different size and moves the contents of the
2852 /// current table into it.
2853 ///
2854 /// This uses dynamic dispatch to reduce the amount of
2855 /// code generated, but it is eliminated by LLVM optimizations when inlined.
2856 ///
2857 /// # Safety
2858 ///
2859 /// If any of the following conditions are violated, the result is
2860 /// [`undefined behavior`]:
2861 ///
2862 /// * The `alloc` must be the same [`Allocator`] as the `Allocator` used
2863 /// to allocate this table;
2864 ///
2865 /// * The `layout` must be the same [`TableLayout`] as the `TableLayout`
2866 /// used to allocate this table;
2867 ///
2868 /// * The [`RawTableInner`] must have properly initialized control bytes.
2869 ///
2870 /// The caller of this function must ensure that `capacity >= self.items`
2871 /// otherwise:
2872 ///
2873 /// * If `self.items != 0`, calling of this function with `capacity == 0`
2874 /// results in [`undefined behavior`].
2875 ///
2876 /// * If `capacity_to_buckets(capacity) < Group::WIDTH` and
2877 /// `self.items > capacity_to_buckets(capacity)` calling this function
2878 /// results in [`undefined behavior`].
2879 ///
2880 /// * If `capacity_to_buckets(capacity) >= Group::WIDTH` and
2881 /// `self.items > capacity_to_buckets(capacity)` calling this function
2882 /// are never return (will go into an infinite loop).
2883 ///
2884 /// Note: It is recommended (but not required) that the new table's `capacity`
2885 /// be greater than or equal to `self.items`. In case if `capacity <= self.items`
2886 /// this function can never return. See [`RawTableInner::find_insert_index`] for
2887 /// more information.
2888 ///
2889 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2890 #[expect(clippy::inline_always)]
2891 #[inline(always)]
2892 unsafe fn resize_inner<A>(
2893 &mut self,
2894 alloc: &A,
2895 capacity: usize,
2896 hasher: &dyn Fn(&mut Self, usize) -> u64,
2897 fallibility: Fallibility,
2898 layout: TableLayout,
2899 ) -> Result<(), TryReserveError>
2900 where
2901 A: Allocator,
2902 {
2903 // SAFETY: We know for sure that `alloc` and `layout` matches the [`Allocator`] and [`TableLayout`]
2904 // that were used to allocate this table.
2905 let mut new_table = self.prepare_resize(alloc, layout, capacity, fallibility)?;
2906
2907 // SAFETY: We know for sure that RawTableInner will outlive the
2908 // returned `FullBucketsIndices` iterator, and the caller of this
2909 // function ensures that the control bytes are properly initialized.
2910 unsafe {
2911 for full_byte_index in self.full_buckets_indices() {
2912 // This may panic.
2913 let hash = hasher(self, full_byte_index);
2914
2915 // SAFETY:
2916 // We can use a simpler version of insert() here since:
2917 // 1. There are no DELETED entries.
2918 // 2. We know there is enough space in the table.
2919 // 3. All elements are unique.
2920 // 4. The caller of this function guarantees that `capacity > 0`
2921 // so `new_table` must already have some allocated memory.
2922 // 5. We set `growth_left` and `items` fields of the new table
2923 // after the loop.
2924 // 6. We insert into the table, at the returned index, the data
2925 // matching the given hash immediately after calling this function.
2926 let (new_index, _) = new_table.prepare_insert_index(hash);
2927
2928 // SAFETY:
2929 //
2930 // * `src` is valid for reads of `layout.size` bytes, since the
2931 // table is alive and the `full_byte_index` is guaranteed to be
2932 // within bounds (see `FullBucketsIndices::next_impl`);
2933 //
2934 // * `dst` is valid for writes of `layout.size` bytes, since the
2935 // caller ensures that `table_layout` matches the [`TableLayout`]
2936 // that was used to allocate old table and we have the `new_index`
2937 // returned by `prepare_insert_index`.
2938 //
2939 // * Both `src` and `dst` are properly aligned.
2940 //
2941 // * Both `src` and `dst` point to different region of memory.
2942 ptr::copy_nonoverlapping(
2943 self.bucket_ptr(full_byte_index, layout.size),
2944 new_table.bucket_ptr(new_index, layout.size),
2945 layout.size,
2946 );
2947 }
2948 }
2949
2950 // The hash function didn't panic, so we can safely set the
2951 // `growth_left` and `items` fields of the new table.
2952 new_table.growth_left -= self.items;
2953 new_table.items = self.items;
2954
2955 // We successfully copied all elements without panicking. Now replace
2956 // self with the new table. The old table will have its memory freed but
2957 // the items will not be dropped (since they have been moved into the
2958 // new table).
2959 // SAFETY: The caller ensures that `table_layout` matches the [`TableLayout`]
2960 // that was used to allocate this table.
2961 mem::swap(self, &mut new_table);
2962
2963 Ok(())
2964 }
2965
2966 /// Rehashes the contents of the table in place (i.e. without changing the
2967 /// allocation).
2968 ///
2969 /// If `hasher` panics then some the table's contents may be lost.
2970 ///
2971 /// This uses dynamic dispatch to reduce the amount of
2972 /// code generated, but it is eliminated by LLVM optimizations when inlined.
2973 ///
2974 /// # Safety
2975 ///
2976 /// If any of the following conditions are violated, the result is [`undefined behavior`]:
2977 ///
2978 /// * The `size_of` must be equal to the size of the elements stored in the table;
2979 ///
2980 /// * The `drop` function (`fn(*mut u8)`) must be the actual drop function of
2981 /// the elements stored in the table.
2982 ///
2983 /// * The [`RawTableInner`] has already been allocated;
2984 ///
2985 /// * The [`RawTableInner`] must have properly initialized control bytes.
2986 ///
2987 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2988 #[cfg_attr(feature = "inline-more", expect(clippy::inline_always))]
2989 #[cfg_attr(feature = "inline-more", inline(always))]
2990 #[cfg_attr(not(feature = "inline-more"), inline)]
2991 unsafe fn rehash_in_place(
2992 &mut self,
2993 hasher: &dyn Fn(&mut Self, usize) -> u64,
2994 size_of: usize,
2995 drop: Option<unsafe fn(*mut u8)>,
2996 ) {
2997 // If the hash function panics then properly clean up any elements
2998 // that we haven't rehashed yet. We unfortunately can't preserve the
2999 // element since we lost their hash and have no way of recovering it
3000 // without risking another panic.
3001 unsafe {
3002 self.prepare_rehash_in_place();
3003 }
3004
3005 let mut guard = guard(self, move |self_| {
3006 for i in 0..self_.num_buckets() {
3007 unsafe {
3008 // Any elements that haven't been rehashed yet have a
3009 // DELETED tag. These need to be dropped and have their tag
3010 // reset to EMPTY.
3011 if *self_.ctrl(i) == Tag::DELETED {
3012 self_.set_ctrl(i, Tag::EMPTY);
3013 if let Some(drop) = drop {
3014 drop(self_.bucket_ptr(i, size_of));
3015 }
3016 self_.items -= 1;
3017 }
3018 }
3019 }
3020 self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items;
3021 });
3022
3023 // At this point, DELETED elements are elements that we haven't
3024 // rehashed yet. Find them and re-insert them at their ideal
3025 // position.
3026 'outer: for i in 0..guard.num_buckets() {
3027 unsafe {
3028 if *guard.ctrl(i) != Tag::DELETED {
3029 continue;
3030 }
3031 }
3032
3033 let i_p = unsafe { guard.bucket_ptr(i, size_of) };
3034
3035 loop {
3036 // Hash the current item
3037 let hash = hasher(*guard, i);
3038
3039 // Search for a suitable place to put it
3040 //
3041 // SAFETY: Caller of this function ensures that the control bytes
3042 // are properly initialized.
3043 let new_i = unsafe { guard.find_insert_index(hash) };
3044
3045 // Probing works by scanning through all of the control
3046 // bytes in groups, which may not be aligned to the group
3047 // size. If both the new and old position fall within the
3048 // same unaligned group, then there is no benefit in moving
3049 // it and we can just continue to the next item.
3050 if likely(guard.is_in_same_group(i, new_i, hash)) {
3051 unsafe { guard.set_ctrl_hash(i, hash) };
3052 continue 'outer;
3053 }
3054
3055 let new_i_p = unsafe { guard.bucket_ptr(new_i, size_of) };
3056
3057 // We are moving the current item to a new position. Write
3058 // our H2 to the control byte of the new position.
3059 let prev_ctrl = unsafe { guard.replace_ctrl_hash(new_i, hash) };
3060 if prev_ctrl == Tag::EMPTY {
3061 unsafe { guard.set_ctrl(i, Tag::EMPTY) };
3062 // If the target slot is empty, simply move the current
3063 // element into the new slot and clear the old control
3064 // byte.
3065 unsafe {
3066 ptr::copy_nonoverlapping(i_p, new_i_p, size_of);
3067 }
3068 continue 'outer;
3069 }
3070
3071 // If the target slot is occupied, swap the two elements
3072 // and then continue processing the element that we just
3073 // swapped into the old slot.
3074 debug_assert_eq!(prev_ctrl, Tag::DELETED);
3075 unsafe {
3076 ptr::swap_nonoverlapping(i_p, new_i_p, size_of);
3077 }
3078 }
3079 }
3080
3081 guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items;
3082
3083 mem::forget(guard);
3084 }
3085
3086 /// Deallocates the table without dropping any entries.
3087 ///
3088 /// # Note
3089 ///
3090 /// This function must be called only after [`drop_elements`](RawTableInner::drop_elements),
3091 /// else it can lead to leaking of memory. Also calling this function automatically
3092 /// makes invalid (dangling) all instances of buckets ([`Bucket`]) and makes invalid
3093 /// (dangling) the `ctrl` field of the table.
3094 ///
3095 /// # Safety
3096 ///
3097 /// If any of the following conditions are violated, the result is [`Undefined Behavior`]:
3098 ///
3099 /// * The [`RawTableInner`] has already been allocated;
3100 ///
3101 /// * The `alloc` must be the same [`Allocator`] as the `Allocator` that was used
3102 /// to allocate this table.
3103 ///
3104 /// * The `table_layout` must be the same [`TableLayout`] as the `TableLayout` that was used
3105 /// to allocate this table.
3106 ///
3107 /// See also [`GlobalAlloc::dealloc`] or [`Allocator::deallocate`] for more information.
3108 ///
3109 /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3110 /// [`GlobalAlloc::dealloc`]: stdalloc::alloc::GlobalAlloc::dealloc
3111 /// [`Allocator::deallocate`]: stdalloc::alloc::Allocator::deallocate
3112 #[inline]
3113 unsafe fn free_buckets<A>(&mut self, alloc: &A, table_layout: TableLayout)
3114 where
3115 A: Allocator,
3116 {
3117 unsafe {
3118 // SAFETY: The caller must uphold the safety contract for `free_buckets`
3119 // method.
3120 let (ptr, layout) = self.allocation_info(table_layout);
3121 alloc.deallocate(ptr, layout);
3122 }
3123 }
3124
3125 /// Returns a pointer to the allocated memory and the layout that was used to
3126 /// allocate the table.
3127 ///
3128 /// # Safety
3129 ///
3130 /// Caller of this function must observe the following safety rules:
3131 ///
3132 /// * The [`RawTableInner`] has already been allocated, otherwise
3133 /// calling this function results in [`undefined behavior`]
3134 ///
3135 /// * The `table_layout` must be the same [`TableLayout`] as the `TableLayout`
3136 /// that was used to allocate this table. Failure to comply with this condition
3137 /// may result in [`undefined behavior`].
3138 ///
3139 /// See also [`GlobalAlloc::dealloc`] or [`Allocator::deallocate`] for more information.
3140 ///
3141 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3142 /// [`GlobalAlloc::dealloc`]: stdalloc::GlobalAlloc::dealloc
3143 /// [`Allocator::deallocate`]: stdalloc::Allocator::deallocate
3144 #[inline]
3145 unsafe fn allocation_info(&self, table_layout: TableLayout) -> (NonNull<u8>, Layout) {
3146 debug_assert!(
3147 !self.is_empty_singleton(),
3148 "this function can only be called on non-empty tables"
3149 );
3150
3151 let (layout, ctrl_offset) = {
3152 let option = table_layout.calculate_layout_for(self.num_buckets());
3153 unsafe { option.unwrap_unchecked() }
3154 };
3155 (
3156 // SAFETY: The caller must uphold the safety contract for `allocation_info` method.
3157 unsafe { NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)) },
3158 layout,
3159 )
3160 }
3161
3162 /// Returns the total amount of memory allocated internally by the hash
3163 /// table, in bytes.
3164 ///
3165 /// The returned number is informational only. It is intended to be
3166 /// primarily used for memory profiling.
3167 ///
3168 /// # Safety
3169 ///
3170 /// The `table_layout` must be the same [`TableLayout`] as the `TableLayout`
3171 /// that was used to allocate this table. Failure to comply with this condition
3172 /// may result in [`undefined behavior`].
3173 ///
3174 ///
3175 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3176 #[inline]
3177 unsafe fn allocation_size_or_zero(&self, table_layout: TableLayout) -> usize {
3178 if self.is_empty_singleton() {
3179 0
3180 } else {
3181 // SAFETY:
3182 // 1. We have checked that our table is allocated.
3183 // 2. The caller ensures that `table_layout` matches the [`TableLayout`]
3184 // that was used to allocate this table.
3185 unsafe { self.allocation_info(table_layout).1.size() }
3186 }
3187 }
3188
3189 /// Marks all table buckets as empty without dropping their contents.
3190 #[inline]
3191 fn clear_no_drop(&mut self) {
3192 if !self.is_empty_singleton() {
3193 self.ctrl_slice().fill_empty();
3194 }
3195 self.items = 0;
3196 self.growth_left = bucket_mask_to_capacity(self.bucket_mask);
3197 }
3198
3199 /// Erases the [`Bucket`]'s control byte at the given index so that it does not
3200 /// triggered as full, decreases the `items` of the table and, if it can be done,
3201 /// increases `self.growth_left`.
3202 ///
3203 /// This function does not actually erase / drop the [`Bucket`] itself, i.e. it
3204 /// does not make any changes to the `data` parts of the table. The caller of this
3205 /// function must take care to properly drop the `data`, otherwise calling this
3206 /// function may result in a memory leak.
3207 ///
3208 /// # Safety
3209 ///
3210 /// You must observe the following safety rules when calling this function:
3211 ///
3212 /// * The [`RawTableInner`] has already been allocated;
3213 ///
3214 /// * It must be the full control byte at the given position;
3215 ///
3216 /// * The `index` must not be greater than the `RawTableInner.bucket_mask`, i.e.
3217 /// `index <= RawTableInner.bucket_mask` or, in other words, `(index + 1)` must
3218 /// be no greater than the number returned by the function [`RawTableInner::num_buckets`].
3219 ///
3220 /// Calling this function on a table that has not been allocated results in [`undefined behavior`].
3221 ///
3222 /// Calling this function on a table with no elements is unspecified, but calling subsequent
3223 /// functions is likely to result in [`undefined behavior`] due to overflow subtraction
3224 /// (`self.items -= 1 cause overflow when self.items == 0`).
3225 ///
3226 /// See also [`Bucket::as_ptr`] method, for more information about of properly removing
3227 /// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
3228 ///
3229 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3230 #[inline]
3231 unsafe fn erase(&mut self, index: usize) {
3232 unsafe {
3233 debug_assert!(self.is_bucket_full(index));
3234 }
3235
3236 // This is the same as `index.wrapping_sub(Group::WIDTH) % self.num_buckets()` because
3237 // the number of buckets is a power of two, and `self.bucket_mask = self.num_buckets() - 1`.
3238 let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask;
3239 // SAFETY:
3240 // - The caller must uphold the safety contract for `erase` method;
3241 // - `index_before` is guaranteed to be in range due to masking with `self.bucket_mask`
3242 let (empty_before, empty_after) = unsafe {
3243 (
3244 Group::load(self.ctrl(index_before)).match_empty(),
3245 Group::load(self.ctrl(index)).match_empty(),
3246 )
3247 };
3248
3249 // Inserting and searching in the map is performed by two key functions:
3250 //
3251 // - The `find_insert_index` function that looks up the index of any `Tag::EMPTY` or `Tag::DELETED`
3252 // slot in a group to be able to insert. If it doesn't find an `Tag::EMPTY` or `Tag::DELETED`
3253 // slot immediately in the first group, it jumps to the next `Group` looking for it,
3254 // and so on until it has gone through all the groups in the control bytes.
3255 //
3256 // - The `find_inner` function that looks for the index of the desired element by looking
3257 // at all the `FULL` bytes in the group. If it did not find the element right away, and
3258 // there is no `Tag::EMPTY` byte in the group, then this means that the `find_insert_index`
3259 // function may have found a suitable slot in the next group. Therefore, `find_inner`
3260 // jumps further, and if it does not find the desired element and again there is no `Tag::EMPTY`
3261 // byte, then it jumps further, and so on. The search stops only if `find_inner` function
3262 // finds the desired element or hits an `Tag::EMPTY` slot/byte.
3263 //
3264 // Accordingly, this leads to two consequences:
3265 //
3266 // - The map must have `Tag::EMPTY` slots (bytes);
3267 //
3268 // - You can't just mark the byte to be erased as `Tag::EMPTY`, because otherwise the `find_inner`
3269 // function may stumble upon an `Tag::EMPTY` byte before finding the desired element and stop
3270 // searching.
3271 //
3272 // Thus it is necessary to check all bytes after and before the erased element. If we are in
3273 // a contiguous `Group` of `FULL` or `Tag::DELETED` bytes (the number of `FULL` or `Tag::DELETED` bytes
3274 // before and after is greater than or equal to `Group::WIDTH`), then we must mark our byte as
3275 // `Tag::DELETED` in order for the `find_inner` function to go further. On the other hand, if there
3276 // is at least one `Tag::EMPTY` slot in the `Group`, then the `find_inner` function will still stumble
3277 // upon an `Tag::EMPTY` byte, so we can safely mark our erased byte as `Tag::EMPTY` as well.
3278 //
3279 // Finally, since `index_before == (index.wrapping_sub(Group::WIDTH) & self.bucket_mask) == index`
3280 // and given all of the above, tables smaller than the group width (self.num_buckets() < Group::WIDTH)
3281 // cannot have `Tag::DELETED` bytes.
3282 //
3283 // Note that in this context `leading_zeros` refers to the bytes at the end of a group, while
3284 // `trailing_zeros` refers to the bytes at the beginning of a group.
3285 let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH {
3286 Tag::DELETED
3287 } else {
3288 self.growth_left += 1;
3289 Tag::EMPTY
3290 };
3291 // SAFETY: the caller must uphold the safety contract for `erase` method.
3292 unsafe {
3293 self.set_ctrl(index, ctrl);
3294 }
3295 self.items -= 1;
3296 }
3297}
3298
3299impl<T: Clone, A: Allocator + Clone> Clone for RawTable<T, A> {
3300 fn clone(&self) -> Self {
3301 if self.table.is_empty_singleton() {
3302 Self::new_in(self.alloc.clone())
3303 } else {
3304 // SAFETY: This is safe as we are taking the size of an already allocated table
3305 // and therefore capacity overflow cannot occur, `self.table.num_buckets()` is power
3306 // of two and all allocator errors will be caught inside `RawTableInner::new_uninitialized`.
3307 let result = unsafe {
3308 Self::new_uninitialized(
3309 self.alloc.clone(),
3310 self.table.num_buckets(),
3311 Fallibility::Infallible,
3312 )
3313 };
3314
3315 // SAFETY: The result of calling the `new_uninitialized` function cannot be an error
3316 // because `fallibility == Fallibility::Infallible.
3317 let mut new_table = unsafe { result.unwrap_unchecked() };
3318
3319 // SAFETY:
3320 // Cloning elements may fail (the clone function may panic). But we don't
3321 // need to worry about uninitialized control bits, since:
3322 // 1. The number of items (elements) in the table is zero, which means that
3323 // the control bits will not be read by Drop function.
3324 // 2. The `clone_from_spec` method will first copy all control bits from
3325 // `self` (thus initializing them). But this will not affect the `Drop`
3326 // function, since the `clone_from_spec` function sets `items` only after
3327 // successfully cloning all elements.
3328 unsafe { new_table.clone_from_spec(self) };
3329 new_table
3330 }
3331 }
3332
3333 fn clone_from(&mut self, source: &Self) {
3334 if source.table.is_empty_singleton() {
3335 let mut old_inner = mem::replace(&mut self.table, RawTableInner::NEW);
3336 unsafe {
3337 // SAFETY:
3338 // 1. We call the function only once;
3339 // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`]
3340 // and [`TableLayout`] that were used to allocate this table.
3341 // 3. If any elements' drop function panics, then there will only be a memory leak,
3342 // because we have replaced the inner table with a new one.
3343 old_inner.drop_inner_table::<T, _>(&self.alloc, Self::TABLE_LAYOUT);
3344 }
3345 } else {
3346 unsafe {
3347 // Make sure that if any panics occurs, we clear the table and
3348 // leave it in an empty state.
3349 let mut self_ = guard(self, |self_| {
3350 self_.clear_no_drop();
3351 });
3352
3353 // First, drop all our elements without clearing the control
3354 // bytes. If this panics then the scope guard will clear the
3355 // table, leaking any elements that were not dropped yet.
3356 //
3357 // This leak is unavoidable: we can't try dropping more elements
3358 // since this could lead to another panic and abort the process.
3359 //
3360 // SAFETY: If something gets wrong we clear our table right after
3361 // dropping the elements, so there is no double drop, since `items`
3362 // will be equal to zero.
3363 self_.table.drop_elements::<T>();
3364
3365 // If necessary, resize our table to match the source.
3366 if self_.num_buckets() != source.num_buckets() {
3367 let new_inner = {
3368 let result = RawTableInner::new_uninitialized(
3369 &self_.alloc,
3370 Self::TABLE_LAYOUT,
3371 source.num_buckets(),
3372 Fallibility::Infallible,
3373 );
3374 result.unwrap_unchecked()
3375 };
3376 // Replace the old inner with new uninitialized one. It's ok, since if something gets
3377 // wrong `ScopeGuard` will initialize all control bytes and leave empty table.
3378 let mut old_inner = mem::replace(&mut self_.table, new_inner);
3379 if !old_inner.is_empty_singleton() {
3380 // SAFETY:
3381 // 1. We have checked that our table is allocated.
3382 // 2. We know for sure that `alloc` and `table_layout` matches
3383 // the [`Allocator`] and [`TableLayout`] that were used to allocate this table.
3384 old_inner.free_buckets(&self_.alloc, Self::TABLE_LAYOUT);
3385 }
3386 }
3387
3388 // Cloning elements may fail (the clone function may panic), but the `ScopeGuard`
3389 // inside the `clone_from_impl` function will take care of that, dropping all
3390 // cloned elements if necessary. Our `ScopeGuard` will clear the table.
3391 self_.clone_from_spec(source);
3392
3393 // Disarm the scope guard if cloning was successful.
3394 ScopeGuard::into_inner(self_);
3395 }
3396 }
3397 }
3398}
3399
3400/// Specialization of `clone_from` for `Copy` types
3401trait RawTableClone {
3402 unsafe fn clone_from_spec(&mut self, source: &Self);
3403}
3404impl<T: Clone, A: Allocator + Clone> RawTableClone for RawTable<T, A> {
3405 default_fn! {
3406 #[cfg_attr(feature = "inline-more", inline)]
3407 unsafe fn clone_from_spec(&mut self, source: &Self) {
3408 unsafe {
3409 self.clone_from_impl(source);
3410 }
3411 }
3412 }
3413}
3414#[cfg(feature = "nightly")]
3415impl<T: core::clone::TrivialClone, A: Allocator + Clone> RawTableClone for RawTable<T, A> {
3416 #[cfg_attr(feature = "inline-more", inline)]
3417 unsafe fn clone_from_spec(&mut self, source: &Self) {
3418 unsafe {
3419 source
3420 .table
3421 .ctrl(0)
3422 .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes());
3423 source
3424 .data_start()
3425 .as_ptr()
3426 .copy_to_nonoverlapping(self.data_start().as_ptr(), self.table.num_buckets());
3427 }
3428
3429 self.table.items = source.table.items;
3430 self.table.growth_left = source.table.growth_left;
3431 }
3432}
3433
3434impl<T: Clone, A: Allocator + Clone> RawTable<T, A> {
3435 /// Common code for `clone` and `clone_from`. Assumes:
3436 /// - `self.num_buckets() == source.num_buckets()`.
3437 /// - Any existing elements have been dropped.
3438 /// - The control bytes are not initialized yet.
3439 #[cfg_attr(feature = "inline-more", inline)]
3440 unsafe fn clone_from_impl(&mut self, source: &Self) {
3441 // Copy the control bytes unchanged. We do this in a single pass
3442 unsafe {
3443 source
3444 .table
3445 .ctrl(0)
3446 .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes());
3447 }
3448
3449 // The cloning of elements may panic, in which case we need
3450 // to make sure we drop only the elements that have been
3451 // cloned so far.
3452 let mut guard = guard((0, &mut *self), |(index, self_)| {
3453 if T::NEEDS_DROP {
3454 for i in 0..*index {
3455 unsafe {
3456 if self_.is_bucket_full(i) {
3457 self_.bucket(i).drop();
3458 }
3459 }
3460 }
3461 }
3462 });
3463
3464 unsafe {
3465 for from in source.iter() {
3466 let index = source.bucket_index(&from);
3467 let to = guard.1.bucket(index);
3468 to.write(from.as_ref().clone());
3469
3470 // Update the index in case we need to unwind.
3471 guard.0 = index + 1;
3472 }
3473 }
3474
3475 // Successfully cloned all items, no need to clean up.
3476 mem::forget(guard);
3477
3478 self.table.items = source.table.items;
3479 self.table.growth_left = source.table.growth_left;
3480 }
3481}
3482
3483impl<T, A: Allocator + Default> Default for RawTable<T, A> {
3484 #[inline]
3485 fn default() -> Self {
3486 Self::new_in(Default::default())
3487 }
3488}
3489
3490#[cfg(feature = "nightly")]
3491unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawTable<T, A> {
3492 #[cfg_attr(feature = "inline-more", inline)]
3493 fn drop(&mut self) {
3494 // SAFETY:
3495 // 1. We call the function only once;
3496 // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`]
3497 // and [`TableLayout`] that were used to allocate this table.
3498 // 3. If the drop function of any elements fails, then only a memory leak will occur,
3499 // and we don't care because we are inside the `Drop` function of the `RawTable`,
3500 // so there won't be any table left in an inconsistent state.
3501 unsafe {
3502 self.table
3503 .drop_inner_table::<T, _>(&self.alloc, Self::TABLE_LAYOUT);
3504 }
3505 }
3506}
3507#[cfg(not(feature = "nightly"))]
3508impl<T, A: Allocator> Drop for RawTable<T, A> {
3509 #[cfg_attr(feature = "inline-more", inline)]
3510 fn drop(&mut self) {
3511 // SAFETY:
3512 // 1. We call the function only once;
3513 // 2. We know for sure that `alloc` and `table_layout` matches the [`Allocator`]
3514 // and [`TableLayout`] that were used to allocate this table.
3515 // 3. If the drop function of any elements fails, then only a memory leak will occur,
3516 // and we don't care because we are inside the `Drop` function of the `RawTable`,
3517 // so there won't be any table left in an inconsistent state.
3518 unsafe {
3519 self.table
3520 .drop_inner_table::<T, _>(&self.alloc, Self::TABLE_LAYOUT);
3521 }
3522 }
3523}
3524
3525impl<T, A: Allocator> IntoIterator for RawTable<T, A> {
3526 type Item = T;
3527 type IntoIter = RawIntoIter<T, A>;
3528
3529 #[cfg_attr(feature = "inline-more", inline)]
3530 fn into_iter(self) -> RawIntoIter<T, A> {
3531 unsafe {
3532 let iter = self.iter();
3533 self.into_iter_from(iter)
3534 }
3535 }
3536}
3537
3538/// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does
3539/// not track an item count.
3540pub(crate) struct RawIterRange<T> {
3541 // Mask of full buckets in the current group. Bits are cleared from this
3542 // mask as each element is processed.
3543 current_group: BitMaskIter,
3544
3545 // Pointer to the buckets for the current group.
3546 data: Bucket<T>,
3547
3548 // Pointer to the next group of control bytes,
3549 // Must be aligned to the group size.
3550 next_ctrl: *const u8,
3551
3552 // Pointer one past the last control byte of this range.
3553 end: *const u8,
3554}
3555
3556impl<T> RawIterRange<T> {
3557 /// Returns a `RawIterRange` covering a subset of a table.
3558 ///
3559 /// # Safety
3560 ///
3561 /// If any of the following conditions are violated, the result is
3562 /// [`undefined behavior`]:
3563 ///
3564 /// * `ctrl` must be valid for reads, i.e. table outlives the `RawIterRange`;
3565 ///
3566 /// * `ctrl` must be properly aligned to the group size (`Group::WIDTH`);
3567 ///
3568 /// * `ctrl` must point to the array of properly initialized control bytes;
3569 ///
3570 /// * `data` must be the [`Bucket`] at the `ctrl` index in the table;
3571 ///
3572 /// * the value of `len` must be less than or equal to the number of table buckets,
3573 /// and the returned value of `ctrl.as_ptr().add(len).offset_from(ctrl.as_ptr())`
3574 /// must be positive.
3575 ///
3576 /// * The `ctrl.add(len)` pointer must be either in bounds or one
3577 /// byte past the end of the same [allocated table].
3578 ///
3579 /// * The `len` must be a power of two.
3580 ///
3581 /// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3582 #[cfg_attr(feature = "inline-more", inline)]
3583 unsafe fn new(ctrl: *const u8, data: Bucket<T>, len: usize) -> Self {
3584 debug_assert_ne!(len, 0);
3585 debug_assert!(ctrl.cast::<Group>().is_aligned());
3586 // SAFETY: The caller must uphold the safety rules for the [`RawIterRange::new`]
3587 let end = unsafe { ctrl.add(len) };
3588
3589 // Load the first group and advance ctrl to point to the next group
3590 // SAFETY: The caller must uphold the safety rules for the [`RawIterRange::new`]
3591 let (current_group, next_ctrl) = unsafe {
3592 (
3593 Group::load_aligned(ctrl.cast()).match_full(),
3594 ctrl.add(Group::WIDTH),
3595 )
3596 };
3597
3598 Self {
3599 current_group: current_group.into_iter(),
3600 data,
3601 next_ctrl,
3602 end,
3603 }
3604 }
3605
3606 /// Splits a `RawIterRange` into two halves.
3607 ///
3608 /// Returns `None` if the remaining range is smaller than or equal to the
3609 /// group width.
3610 #[cfg_attr(feature = "inline-more", inline)]
3611 #[cfg(feature = "rayon")]
3612 pub(crate) fn split(mut self) -> (Self, Option<RawIterRange<T>>) {
3613 unsafe {
3614 if self.end <= self.next_ctrl {
3615 // Nothing to split if the group that we are current processing
3616 // is the last one.
3617 (self, None)
3618 } else {
3619 // len is the remaining number of elements after the group that
3620 // we are currently processing. It must be a multiple of the
3621 // group size (small tables are caught by the check above).
3622 let len = offset_from(self.end, self.next_ctrl);
3623 debug_assert_eq!(len % Group::WIDTH, 0);
3624
3625 // Split the remaining elements into two halves, but round the
3626 // midpoint down in case there is an odd number of groups
3627 // remaining. This ensures that:
3628 // - The tail is at least 1 group long.
3629 // - The split is roughly even considering we still have the
3630 // current group to process.
3631 let mid = (len / 2) & !(Group::WIDTH - 1);
3632
3633 let tail = Self::new(
3634 self.next_ctrl.add(mid),
3635 self.data.next_n(Group::WIDTH).next_n(mid),
3636 len - mid,
3637 );
3638 debug_assert_eq!(
3639 self.data.next_n(Group::WIDTH).next_n(mid).ptr,
3640 tail.data.ptr
3641 );
3642 debug_assert_eq!(self.end, tail.end);
3643 self.end = self.next_ctrl.add(mid);
3644 debug_assert_eq!(self.end.add(Group::WIDTH), tail.next_ctrl);
3645 (self, Some(tail))
3646 }
3647 }
3648 }
3649
3650 /// # Safety
3651 /// If `DO_CHECK_PTR_RANGE` is false, caller must ensure that we never try to iterate
3652 /// after yielding all elements.
3653 #[cfg_attr(feature = "inline-more", inline)]
3654 unsafe fn next_impl<const DO_CHECK_PTR_RANGE: bool>(&mut self) -> Option<Bucket<T>> {
3655 loop {
3656 if let Some(index) = self.current_group.next() {
3657 return Some(unsafe { self.data.next_n(index) });
3658 }
3659
3660 if DO_CHECK_PTR_RANGE && self.next_ctrl >= self.end {
3661 return None;
3662 }
3663
3664 // We might read past self.end up to the next group boundary,
3665 // but this is fine because it only occurs on tables smaller
3666 // than the group size where the trailing control bytes are all
3667 // EMPTY. On larger tables self.end is guaranteed to be aligned
3668 // to the group size (since tables are power-of-two sized).
3669 unsafe {
3670 self.current_group = Group::load_aligned(self.next_ctrl.cast())
3671 .match_full()
3672 .into_iter();
3673 self.data = self.data.next_n(Group::WIDTH);
3674 self.next_ctrl = self.next_ctrl.add(Group::WIDTH);
3675 }
3676 }
3677 }
3678
3679 /// Folds every element into an accumulator by applying an operation,
3680 /// returning the final result.
3681 ///
3682 /// `fold_impl()` takes three arguments: the number of items remaining in
3683 /// the iterator, an initial value, and a closure with two arguments: an
3684 /// 'accumulator', and an element. The closure returns the value that the
3685 /// accumulator should have for the next iteration.
3686 ///
3687 /// The initial value is the value the accumulator will have on the first call.
3688 ///
3689 /// After applying this closure to every element of the iterator, `fold_impl()`
3690 /// returns the accumulator.
3691 ///
3692 /// # Safety
3693 ///
3694 /// If any of the following conditions are violated, the result is
3695 /// [`Undefined Behavior`]:
3696 ///
3697 /// * The [`RawTableInner`] / [`RawTable`] must be alive and not moved,
3698 /// i.e. table outlives the `RawIterRange`;
3699 ///
3700 /// * The provided `n` value must match the actual number of items
3701 /// in the table.
3702 ///
3703 /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3704 #[expect(clippy::while_let_on_iterator)]
3705 #[cfg_attr(feature = "inline-more", inline)]
3706 unsafe fn fold_impl<F, B>(mut self, mut n: usize, mut acc: B, mut f: F) -> B
3707 where
3708 F: FnMut(B, Bucket<T>) -> B,
3709 {
3710 loop {
3711 while let Some(index) = self.current_group.next() {
3712 // The returned `index` will always be in the range `0..Group::WIDTH`,
3713 // so that calling `self.data.next_n(index)` is safe (see detailed explanation below).
3714 debug_assert!(n != 0);
3715 let bucket = unsafe { self.data.next_n(index) };
3716 acc = f(acc, bucket);
3717 n -= 1;
3718 }
3719
3720 if n == 0 {
3721 return acc;
3722 }
3723
3724 // SAFETY: The caller of this function ensures that:
3725 //
3726 // 1. The provided `n` value matches the actual number of items in the table;
3727 // 2. The table is alive and did not moved.
3728 //
3729 // Taking the above into account, we always stay within the bounds, because:
3730 //
3731 // 1. For tables smaller than the group width (self.num_buckets() <= Group::WIDTH),
3732 // we will never end up in the given branch, since we should have already
3733 // yielded all the elements of the table.
3734 //
3735 // 2. For tables larger than the group width. The number of buckets is a
3736 // power of two (2 ^ n), Group::WIDTH is also power of two (2 ^ k). Since
3737 // `(2 ^ n) > (2 ^ k)`, than `(2 ^ n) % (2 ^ k) = 0`. As we start from the
3738 // start of the array of control bytes, and never try to iterate after
3739 // getting all the elements, the last `self.current_group` will read bytes
3740 // from the `self.num_buckets() - Group::WIDTH` index. We know also that
3741 // `self.current_group.next()` will always return indices within the range
3742 // `0..Group::WIDTH`.
3743 //
3744 // Knowing all of the above and taking into account that we are synchronizing
3745 // the `self.data` index with the index we used to read the `self.current_group`,
3746 // the subsequent `self.data.next_n(index)` will always return a bucket with
3747 // an index number less than `self.num_buckets()`.
3748 //
3749 // The last `self.next_ctrl`, whose index would be `self.num_buckets()`, will never
3750 // actually be read, since we should have already yielded all the elements of
3751 // the table.
3752 unsafe {
3753 self.current_group = Group::load_aligned(self.next_ctrl.cast())
3754 .match_full()
3755 .into_iter();
3756 self.data = self.data.next_n(Group::WIDTH);
3757 self.next_ctrl = self.next_ctrl.add(Group::WIDTH);
3758 }
3759 }
3760 }
3761}
3762
3763// We make raw iterators unconditionally Send and Sync, and let the PhantomData
3764// in the actual iterator implementations determine the real Send/Sync bounds.
3765unsafe impl<T> Send for RawIterRange<T> {}
3766unsafe impl<T> Sync for RawIterRange<T> {}
3767
3768impl<T> Clone for RawIterRange<T> {
3769 #[cfg_attr(feature = "inline-more", inline)]
3770 fn clone(&self) -> Self {
3771 Self {
3772 data: self.data.clone(),
3773 next_ctrl: self.next_ctrl,
3774 current_group: self.current_group.clone(),
3775 end: self.end,
3776 }
3777 }
3778}
3779
3780impl<T> Iterator for RawIterRange<T> {
3781 type Item = Bucket<T>;
3782
3783 #[cfg_attr(feature = "inline-more", inline)]
3784 fn next(&mut self) -> Option<Bucket<T>> {
3785 unsafe {
3786 // SAFETY: We set checker flag to true.
3787 self.next_impl::<true>()
3788 }
3789 }
3790
3791 #[inline]
3792 fn size_hint(&self) -> (usize, Option<usize>) {
3793 // We don't have an item count, so just guess based on the range size.
3794 let remaining_buckets = if self.end > self.next_ctrl {
3795 unsafe { offset_from(self.end, self.next_ctrl) }
3796 } else {
3797 0
3798 };
3799
3800 // Add a group width to include the group we are currently processing.
3801 (0, Some(Group::WIDTH + remaining_buckets))
3802 }
3803}
3804
3805impl<T> FusedIterator for RawIterRange<T> {}
3806
3807/// Iterator which returns a raw pointer to every full bucket in the table.
3808///
3809/// For maximum flexibility this iterator is not bound by a lifetime, but you
3810/// must observe several rules when using it:
3811/// - You must not free the hash table while iterating (including via growing/shrinking).
3812/// - It is fine to erase a bucket that has been yielded by the iterator.
3813/// - Erasing a bucket that has not yet been yielded by the iterator may still
3814/// result in the iterator yielding that bucket (unless `reflect_remove` is called).
3815/// - It is unspecified whether an element inserted after the iterator was
3816/// created will be yielded by that iterator (unless `reflect_insert` is called).
3817/// - The order in which the iterator yields bucket is unspecified and may
3818/// change in the future.
3819pub(crate) struct RawIter<T> {
3820 pub(crate) iter: RawIterRange<T>,
3821 items: usize,
3822}
3823
3824impl<T> RawIter<T> {
3825 unsafe fn drop_elements(&mut self) {
3826 unsafe {
3827 if T::NEEDS_DROP && self.items != 0 {
3828 for item in self {
3829 item.drop();
3830 }
3831 }
3832 }
3833 }
3834}
3835
3836impl<T> Clone for RawIter<T> {
3837 #[cfg_attr(feature = "inline-more", inline)]
3838 fn clone(&self) -> Self {
3839 Self {
3840 iter: self.iter.clone(),
3841 items: self.items,
3842 }
3843 }
3844}
3845impl<T> Default for RawIter<T> {
3846 #[cfg_attr(feature = "inline-more", inline)]
3847 fn default() -> Self {
3848 // SAFETY: Because the table is static, it always outlives the iter.
3849 unsafe { RawTableInner::NEW.iter() }
3850 }
3851}
3852
3853impl<T> Iterator for RawIter<T> {
3854 type Item = Bucket<T>;
3855
3856 #[cfg_attr(feature = "inline-more", inline)]
3857 fn next(&mut self) -> Option<Bucket<T>> {
3858 // Inner iterator iterates over buckets
3859 // so it can do unnecessary work if we already yielded all items.
3860 if self.items == 0 {
3861 return None;
3862 }
3863
3864 let nxt = unsafe {
3865 // SAFETY: We check number of items to yield using `items` field.
3866 self.iter.next_impl::<false>()
3867 };
3868
3869 debug_assert!(nxt.is_some());
3870 self.items -= 1;
3871
3872 nxt
3873 }
3874
3875 #[inline]
3876 fn size_hint(&self) -> (usize, Option<usize>) {
3877 (self.items, Some(self.items))
3878 }
3879
3880 #[inline]
3881 fn fold<B, F>(self, init: B, f: F) -> B
3882 where
3883 Self: Sized,
3884 F: FnMut(B, Self::Item) -> B,
3885 {
3886 unsafe { self.iter.fold_impl(self.items, init, f) }
3887 }
3888}
3889
3890impl<T> ExactSizeIterator for RawIter<T> {}
3891impl<T> FusedIterator for RawIter<T> {}
3892
3893/// Iterator which returns an index of every full bucket in the table.
3894///
3895/// For maximum flexibility this iterator is not bound by a lifetime, but you
3896/// must observe several rules when using it:
3897/// - You must not free the hash table while iterating (including via growing/shrinking).
3898/// - It is fine to erase a bucket that has been yielded by the iterator.
3899/// - Erasing a bucket that has not yet been yielded by the iterator may still
3900/// result in the iterator yielding index of that bucket.
3901/// - It is unspecified whether an element inserted after the iterator was
3902/// created will be yielded by that iterator.
3903/// - The order in which the iterator yields indices of the buckets is unspecified
3904/// and may change in the future.
3905#[derive(Clone)]
3906pub(crate) struct FullBucketsIndices {
3907 // Mask of full buckets in the current group. Bits are cleared from this
3908 // mask as each element is processed.
3909 current_group: BitMaskIter,
3910
3911 // Initial value of the bytes' indices of the current group (relative
3912 // to the start of the control bytes).
3913 group_first_index: usize,
3914
3915 // Pointer to the current group of control bytes,
3916 // Must be aligned to the group size (Group::WIDTH).
3917 ctrl: NonNull<u8>,
3918
3919 // Number of elements in the table.
3920 items: usize,
3921}
3922
3923impl Default for FullBucketsIndices {
3924 #[cfg_attr(feature = "inline-more", inline)]
3925 fn default() -> Self {
3926 // SAFETY: Because the table is static, it always outlives the iter.
3927 unsafe { RawTableInner::NEW.full_buckets_indices() }
3928 }
3929}
3930
3931impl FullBucketsIndices {
3932 /// Advances the iterator and returns the next value.
3933 ///
3934 /// # Safety
3935 ///
3936 /// If any of the following conditions are violated, the result is
3937 /// [`Undefined Behavior`]:
3938 ///
3939 /// * The [`RawTableInner`] / [`RawTable`] must be alive and not moved,
3940 /// i.e. table outlives the `FullBucketsIndices`;
3941 ///
3942 /// * It never tries to iterate after getting all elements.
3943 ///
3944 /// [`Undefined Behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
3945 #[inline(always)]
3946 unsafe fn next_impl(&mut self) -> Option<usize> {
3947 loop {
3948 if let Some(index) = self.current_group.next() {
3949 // The returned `self.group_first_index + index` will always
3950 // be in the range `0..self.num_buckets()`. See explanation below.
3951 return Some(self.group_first_index + index);
3952 }
3953
3954 // SAFETY: The caller of this function ensures that:
3955 //
3956 // 1. It never tries to iterate after getting all the elements;
3957 // 2. The table is alive and did not moved;
3958 // 3. The first `self.ctrl` pointed to the start of the array of control bytes.
3959 //
3960 // Taking the above into account, we always stay within the bounds, because:
3961 //
3962 // 1. For tables smaller than the group width (self.num_buckets() <= Group::WIDTH),
3963 // we will never end up in the given branch, since we should have already
3964 // yielded all the elements of the table.
3965 //
3966 // 2. For tables larger than the group width. The number of buckets is a
3967 // power of two (2 ^ n), Group::WIDTH is also power of two (2 ^ k). Since
3968 // `(2 ^ n) > (2 ^ k)`, than `(2 ^ n) % (2 ^ k) = 0`. As we start from the
3969 // the start of the array of control bytes, and never try to iterate after
3970 // getting all the elements, the last `self.ctrl` will be equal to
3971 // the `self.num_buckets() - Group::WIDTH`, so `self.current_group.next()`
3972 // will always contains indices within the range `0..Group::WIDTH`,
3973 // and subsequent `self.group_first_index + index` will always return a
3974 // number less than `self.num_buckets()`.
3975 unsafe {
3976 self.ctrl = NonNull::new_unchecked(self.ctrl.as_ptr().add(Group::WIDTH));
3977 }
3978
3979 // SAFETY: See explanation above.
3980 unsafe {
3981 self.current_group = Group::load_aligned(self.ctrl.as_ptr().cast())
3982 .match_full()
3983 .into_iter();
3984 self.group_first_index += Group::WIDTH;
3985 }
3986 }
3987 }
3988}
3989
3990impl Iterator for FullBucketsIndices {
3991 type Item = usize;
3992
3993 /// Advances the iterator and returns the next value. It is up to
3994 /// the caller to ensure that the `RawTable` outlives the `FullBucketsIndices`,
3995 /// because we cannot make the `next` method unsafe.
3996 #[inline(always)]
3997 fn next(&mut self) -> Option<usize> {
3998 // Return if we already yielded all items.
3999 if self.items == 0 {
4000 return None;
4001 }
4002
4003 // SAFETY:
4004 // 1. We check number of items to yield using `items` field.
4005 // 2. The caller ensures that the table is alive and has not moved.
4006 let nxt = unsafe { self.next_impl() };
4007
4008 debug_assert!(nxt.is_some());
4009 self.items -= 1;
4010
4011 nxt
4012 }
4013
4014 #[inline(always)]
4015 fn size_hint(&self) -> (usize, Option<usize>) {
4016 (self.items, Some(self.items))
4017 }
4018}
4019
4020impl ExactSizeIterator for FullBucketsIndices {}
4021impl FusedIterator for FullBucketsIndices {}
4022
4023/// Iterator which consumes a table and returns elements.
4024pub(crate) struct RawIntoIter<T, A: Allocator = Global> {
4025 iter: RawIter<T>,
4026 allocation: Option<(NonNull<u8>, Layout, A)>,
4027 marker: PhantomData<T>,
4028}
4029
4030impl<T, A: Allocator> RawIntoIter<T, A> {
4031 #[cfg_attr(feature = "inline-more", inline)]
4032 pub(crate) fn iter(&self) -> RawIter<T> {
4033 self.iter.clone()
4034 }
4035}
4036
4037unsafe impl<T, A: Allocator> Send for RawIntoIter<T, A>
4038where
4039 T: Send,
4040 A: Send,
4041{
4042}
4043unsafe impl<T, A: Allocator> Sync for RawIntoIter<T, A>
4044where
4045 T: Sync,
4046 A: Sync,
4047{
4048}
4049
4050#[cfg(feature = "nightly")]
4051unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawIntoIter<T, A> {
4052 #[cfg_attr(feature = "inline-more", inline)]
4053 fn drop(&mut self) {
4054 unsafe {
4055 // Drop all remaining elements
4056 self.iter.drop_elements();
4057
4058 // Free the table
4059 if let Some((ptr, layout, ref alloc)) = self.allocation {
4060 alloc.deallocate(ptr, layout);
4061 }
4062 }
4063 }
4064}
4065#[cfg(not(feature = "nightly"))]
4066impl<T, A: Allocator> Drop for RawIntoIter<T, A> {
4067 #[cfg_attr(feature = "inline-more", inline)]
4068 fn drop(&mut self) {
4069 unsafe {
4070 // Drop all remaining elements
4071 self.iter.drop_elements();
4072
4073 // Free the table
4074 if let Some((ptr, layout, ref alloc)) = self.allocation {
4075 alloc.deallocate(ptr, layout);
4076 }
4077 }
4078 }
4079}
4080
4081impl<T, A: Allocator> Default for RawIntoIter<T, A> {
4082 fn default() -> Self {
4083 Self {
4084 iter: Default::default(),
4085 allocation: None,
4086 marker: PhantomData,
4087 }
4088 }
4089}
4090impl<T, A: Allocator> Iterator for RawIntoIter<T, A> {
4091 type Item = T;
4092
4093 #[cfg_attr(feature = "inline-more", inline)]
4094 fn next(&mut self) -> Option<T> {
4095 unsafe { Some(self.iter.next()?.read()) }
4096 }
4097
4098 #[inline]
4099 fn size_hint(&self) -> (usize, Option<usize>) {
4100 self.iter.size_hint()
4101 }
4102}
4103
4104impl<T, A: Allocator> ExactSizeIterator for RawIntoIter<T, A> {}
4105impl<T, A: Allocator> FusedIterator for RawIntoIter<T, A> {}
4106
4107/// Iterator which consumes elements without freeing the table storage.
4108pub(crate) struct RawDrain<'a, T, A: Allocator = Global> {
4109 iter: RawIter<T>,
4110
4111 // The table is moved into the iterator for the duration of the drain. This
4112 // ensures that an empty table is left if the drain iterator is leaked
4113 // without dropping.
4114 table: RawTableInner,
4115 orig_table: NonNull<RawTableInner>,
4116
4117 // We don't use a &'a mut RawTable<T> because we want RawDrain to be
4118 // covariant over T.
4119 marker: PhantomData<&'a RawTable<T, A>>,
4120}
4121
4122impl<T, A: Allocator> RawDrain<'_, T, A> {
4123 #[cfg_attr(feature = "inline-more", inline)]
4124 pub(crate) fn iter(&self) -> RawIter<T> {
4125 self.iter.clone()
4126 }
4127}
4128
4129unsafe impl<T, A: Allocator> Send for RawDrain<'_, T, A>
4130where
4131 T: Send,
4132 A: Send,
4133{
4134}
4135unsafe impl<T, A: Allocator> Sync for RawDrain<'_, T, A>
4136where
4137 T: Sync,
4138 A: Sync,
4139{
4140}
4141
4142impl<T, A: Allocator> Drop for RawDrain<'_, T, A> {
4143 #[cfg_attr(feature = "inline-more", inline)]
4144 fn drop(&mut self) {
4145 unsafe {
4146 // Drop all remaining elements. Note that this may panic.
4147 self.iter.drop_elements();
4148
4149 // Reset the contents of the table now that all elements have been
4150 // dropped.
4151 self.table.clear_no_drop();
4152
4153 // Move the now empty table back to its original location.
4154 self.orig_table
4155 .as_ptr()
4156 .copy_from_nonoverlapping(&raw const self.table, 1);
4157 }
4158 }
4159}
4160
4161impl<T, A: Allocator> Iterator for RawDrain<'_, T, A> {
4162 type Item = T;
4163
4164 #[cfg_attr(feature = "inline-more", inline)]
4165 fn next(&mut self) -> Option<T> {
4166 unsafe {
4167 let item = self.iter.next()?;
4168 Some(item.read())
4169 }
4170 }
4171
4172 #[inline]
4173 fn size_hint(&self) -> (usize, Option<usize>) {
4174 self.iter.size_hint()
4175 }
4176}
4177
4178impl<T, A: Allocator> ExactSizeIterator for RawDrain<'_, T, A> {}
4179impl<T, A: Allocator> FusedIterator for RawDrain<'_, T, A> {}
4180
4181/// Iterator over occupied buckets that could match a given hash.
4182///
4183/// `RawTable` only stores 7 bits of the hash value, so this iterator may return
4184/// items that have a hash value different than the one provided. You should
4185/// always validate the returned values before using them.
4186///
4187/// For maximum flexibility this iterator is not bound by a lifetime, but you
4188/// must observe several rules when using it:
4189/// - You must not free the hash table while iterating (including via growing/shrinking).
4190/// - It is fine to erase a bucket that has been yielded by the iterator.
4191/// - Erasing a bucket that has not yet been yielded by the iterator may still
4192/// result in the iterator yielding that bucket.
4193/// - It is unspecified whether an element inserted after the iterator was
4194/// created will be yielded by that iterator.
4195/// - The order in which the iterator yields buckets is unspecified and may
4196/// change in the future.
4197pub(crate) struct RawIterHash<T> {
4198 inner: RawIterHashIndices,
4199 _marker: PhantomData<T>,
4200}
4201
4202#[derive(Clone)]
4203pub(crate) struct RawIterHashIndices {
4204 // See `RawTableInner`'s corresponding fields for details.
4205 // We can't store a `*const RawTableInner` as it would get
4206 // invalidated by the user calling `&mut` methods on `RawTable`.
4207 bucket_mask: usize,
4208 ctrl: NonNull<u8>,
4209
4210 // The top 7 bits of the hash.
4211 tag_hash: Tag,
4212
4213 // The sequence of groups to probe in the search.
4214 probe_seq: ProbeSeq,
4215
4216 group: Group,
4217
4218 // The elements within the group with a matching tag-hash.
4219 bitmask: BitMaskIter,
4220}
4221
4222impl<T> RawIterHash<T> {
4223 #[cfg_attr(feature = "inline-more", inline)]
4224 unsafe fn new<A: Allocator>(table: &RawTable<T, A>, hash: u64) -> Self {
4225 RawIterHash {
4226 inner: unsafe { RawIterHashIndices::new(&table.table, hash) },
4227 _marker: PhantomData,
4228 }
4229 }
4230}
4231
4232impl<T> Clone for RawIterHash<T> {
4233 #[cfg_attr(feature = "inline-more", inline)]
4234 fn clone(&self) -> Self {
4235 Self {
4236 inner: self.inner.clone(),
4237 _marker: PhantomData,
4238 }
4239 }
4240}
4241
4242impl<T> Default for RawIterHash<T> {
4243 #[cfg_attr(feature = "inline-more", inline)]
4244 fn default() -> Self {
4245 Self {
4246 inner: RawIterHashIndices::default(),
4247 _marker: PhantomData,
4248 }
4249 }
4250}
4251
4252impl Default for RawIterHashIndices {
4253 #[cfg_attr(feature = "inline-more", inline)]
4254 fn default() -> Self {
4255 // SAFETY: Because the table is static, it always outlives the iter.
4256 unsafe { RawIterHashIndices::new(&RawTableInner::NEW, 0) }
4257 }
4258}
4259
4260impl RawIterHashIndices {
4261 #[cfg_attr(feature = "inline-more", inline)]
4262 unsafe fn new(table: &RawTableInner, hash: u64) -> Self {
4263 let tag_hash = Tag::full(hash);
4264 let probe_seq = table.probe_seq(hash);
4265 let group = unsafe { Group::load(table.ctrl(probe_seq.pos)) };
4266 let bitmask = group.match_tag(tag_hash).into_iter();
4267
4268 RawIterHashIndices {
4269 bucket_mask: table.bucket_mask,
4270 ctrl: table.ctrl,
4271 tag_hash,
4272 probe_seq,
4273 group,
4274 bitmask,
4275 }
4276 }
4277}
4278
4279impl<T> Iterator for RawIterHash<T> {
4280 type Item = Bucket<T>;
4281
4282 fn next(&mut self) -> Option<Bucket<T>> {
4283 unsafe {
4284 match self.inner.next() {
4285 Some(index) => {
4286 // Can't use `RawTable::bucket` here as we don't have
4287 // an actual `RawTable` reference to use.
4288 debug_assert!(index <= self.inner.bucket_mask);
4289 let bucket = Bucket::from_base_index(self.inner.ctrl.cast(), index);
4290 Some(bucket)
4291 }
4292 None => None,
4293 }
4294 }
4295 }
4296}
4297
4298impl Iterator for RawIterHashIndices {
4299 type Item = usize;
4300
4301 fn next(&mut self) -> Option<Self::Item> {
4302 unsafe {
4303 loop {
4304 if let Some(bit) = self.bitmask.next() {
4305 let index = (self.probe_seq.pos + bit) & self.bucket_mask;
4306 return Some(index);
4307 }
4308 if likely(self.group.match_empty().any_bit_set()) {
4309 return None;
4310 }
4311 self.probe_seq.move_next(self.bucket_mask);
4312
4313 // Can't use `RawTableInner::ctrl` here as we don't have
4314 // an actual `RawTableInner` reference to use.
4315 let index = self.probe_seq.pos;
4316 debug_assert!(index < self.bucket_mask + 1 + Group::WIDTH);
4317 let group_ctrl = self.ctrl.as_ptr().add(index).cast();
4318
4319 self.group = Group::load(group_ctrl);
4320 self.bitmask = self.group.match_tag(self.tag_hash).into_iter();
4321 }
4322 }
4323 }
4324}
4325
4326pub(crate) struct RawExtractIf<'a, T, A: Allocator> {
4327 pub iter: RawIter<T>,
4328 pub table: &'a mut RawTable<T, A>,
4329}
4330
4331impl<T, A: Allocator> RawExtractIf<'_, T, A> {
4332 #[cfg_attr(feature = "inline-more", inline)]
4333 pub(crate) fn next<F>(&mut self, mut f: F) -> Option<T>
4334 where
4335 F: FnMut(&mut T) -> bool,
4336 {
4337 unsafe {
4338 for item in &mut self.iter {
4339 if f(item.as_mut()) {
4340 return Some(self.table.remove(item).0);
4341 }
4342 }
4343 }
4344 None
4345 }
4346}
4347
4348#[cfg(test)]
4349mod test_map {
4350 use super::*;
4351
4352 #[test]
4353 fn test_prev_pow2() {
4354 // Skip 0, not defined for that input.
4355 let mut pow2: usize = 1;
4356 while (pow2 << 1) > 0 {
4357 let next_pow2 = pow2 << 1;
4358 assert_eq!(pow2, prev_pow2(pow2));
4359 // Need to skip 2, because it's also a power of 2, so it doesn't
4360 // return the previous power of 2.
4361 if next_pow2 > 2 {
4362 assert_eq!(pow2, prev_pow2(pow2 + 1));
4363 assert_eq!(pow2, prev_pow2(next_pow2 - 1));
4364 }
4365 pow2 = next_pow2;
4366 }
4367 }
4368
4369 #[test]
4370 fn test_minimum_capacity_for_small_types() {
4371 #[track_caller]
4372 fn test_t<T>() {
4373 let raw_table: RawTable<T> = RawTable::with_capacity(1);
4374 let actual_buckets = raw_table.num_buckets();
4375 let min_buckets = Group::WIDTH / size_of::<T>();
4376 assert!(
4377 actual_buckets >= min_buckets,
4378 "expected at least {min_buckets} buckets, got {actual_buckets} buckets"
4379 );
4380 }
4381
4382 test_t::<u8>();
4383
4384 // This is only "small" for some platforms, like x86_64 with SSE2, but
4385 // there's no harm in running it on other platforms.
4386 test_t::<u16>();
4387 }
4388
4389 fn rehash_in_place<T>(table: &mut RawTable<T>, hasher: impl Fn(&T) -> u64) {
4390 unsafe {
4391 table.table.rehash_in_place(
4392 &|table, index| hasher(table.bucket::<T>(index).as_ref()),
4393 size_of::<T>(),
4394 if mem::needs_drop::<T>() {
4395 Some(|ptr| ptr::drop_in_place(ptr.cast::<T>()))
4396 } else {
4397 None
4398 },
4399 );
4400 }
4401 }
4402
4403 #[test]
4404 fn rehash() {
4405 let mut table = RawTable::new();
4406 let hasher = |i: &u64| *i;
4407 for i in 0..100 {
4408 table.insert(i, i, hasher);
4409 }
4410
4411 for i in 0..100 {
4412 unsafe {
4413 assert_eq!(table.find(i, |x| *x == i).map(|b| b.read()), Some(i));
4414 }
4415 assert!(table.find(i + 100, |x| *x == i + 100).is_none());
4416 }
4417
4418 rehash_in_place(&mut table, hasher);
4419
4420 for i in 0..100 {
4421 unsafe {
4422 assert_eq!(table.find(i, |x| *x == i).map(|b| b.read()), Some(i));
4423 }
4424 assert!(table.find(i + 100, |x| *x == i + 100).is_none());
4425 }
4426 }
4427
4428 /// CHECKING THAT WE ARE NOT TRYING TO READ THE MEMORY OF
4429 /// AN UNINITIALIZED TABLE DURING THE DROP
4430 #[test]
4431 fn test_drop_uninitialized() {
4432 use stdalloc::vec::Vec;
4433
4434 let table = unsafe {
4435 // SAFETY: The `buckets` is power of two and we're not
4436 // trying to actually use the returned RawTable.
4437 RawTable::<(u64, Vec<i32>)>::new_uninitialized(Global, 8, Fallibility::Infallible)
4438 .unwrap()
4439 };
4440 drop(table);
4441 }
4442
4443 /// CHECKING THAT WE DON'T TRY TO DROP DATA IF THE `ITEMS`
4444 /// ARE ZERO, EVEN IF WE HAVE `FULL` CONTROL BYTES.
4445 #[test]
4446 fn test_drop_zero_items() {
4447 use stdalloc::vec::Vec;
4448 unsafe {
4449 // SAFETY: The `buckets` is power of two and we're not
4450 // trying to actually use the returned RawTable.
4451 let mut table =
4452 RawTable::<(u64, Vec<i32>)>::new_uninitialized(Global, 8, Fallibility::Infallible)
4453 .unwrap();
4454
4455 // WE SIMULATE, AS IT WERE, A FULL TABLE.
4456
4457 // SAFETY: We checked that the table is allocated and therefore the table already has
4458 // `self.bucket_mask + 1 + Group::WIDTH` number of control bytes (see TableLayout::calculate_layout_for)
4459 // so writing `table.table.num_ctrl_bytes() == bucket_mask + 1 + Group::WIDTH` bytes is safe.
4460 table.table.ctrl_slice().fill_empty();
4461
4462 // SAFETY: table.capacity() is guaranteed to be smaller than table.num_buckets()
4463 table.table.ctrl(0).write_bytes(0, table.capacity());
4464
4465 // Fix up the trailing control bytes. See the comments in set_ctrl
4466 // for the handling of tables smaller than the group width.
4467 if table.num_buckets() < Group::WIDTH {
4468 // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of control bytes,
4469 // so copying `self.num_buckets() == self.bucket_mask + 1` bytes with offset equal to
4470 // `Group::WIDTH` is safe
4471 table
4472 .table
4473 .ctrl(0)
4474 .copy_to(table.table.ctrl(Group::WIDTH), table.table.num_buckets());
4475 } else {
4476 // SAFETY: We have `self.bucket_mask + 1 + Group::WIDTH` number of
4477 // control bytes,so copying `Group::WIDTH` bytes with offset equal
4478 // to `self.num_buckets() == self.bucket_mask + 1` is safe
4479 table
4480 .table
4481 .ctrl(0)
4482 .copy_to(table.table.ctrl(table.table.num_buckets()), Group::WIDTH);
4483 }
4484 drop(table);
4485 }
4486 }
4487
4488 /// CHECKING THAT WE DON'T TRY TO DROP DATA IF THE `ITEMS`
4489 /// ARE ZERO, EVEN IF WE HAVE `FULL` CONTROL BYTES.
4490 #[test]
4491 #[cfg(panic = "unwind")]
4492 fn test_catch_panic_clone_from() {
4493 use super::{AllocError, Allocator, Global};
4494 use core::sync::atomic::{AtomicI8, Ordering};
4495 use std::thread;
4496 use stdalloc::sync::Arc;
4497 use stdalloc::vec::Vec;
4498
4499 struct MyAllocInner {
4500 drop_count: Arc<AtomicI8>,
4501 }
4502
4503 #[derive(Clone)]
4504 struct MyAlloc {
4505 _inner: Arc<MyAllocInner>,
4506 }
4507
4508 impl Drop for MyAllocInner {
4509 fn drop(&mut self) {
4510 println!("MyAlloc freed.");
4511 self.drop_count.fetch_sub(1, Ordering::SeqCst);
4512 }
4513 }
4514
4515 unsafe impl Allocator for MyAlloc {
4516 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4517 let g = Global;
4518 g.allocate(layout)
4519 }
4520
4521 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
4522 unsafe {
4523 let g = Global;
4524 g.deallocate(ptr, layout);
4525 }
4526 }
4527 }
4528
4529 const DISARMED: bool = false;
4530 const ARMED: bool = true;
4531
4532 struct CheckedCloneDrop {
4533 panic_in_clone: bool,
4534 dropped: bool,
4535 need_drop: Vec<u64>,
4536 }
4537
4538 impl Clone for CheckedCloneDrop {
4539 fn clone(&self) -> Self {
4540 assert!(!self.panic_in_clone, "panic in clone");
4541 Self {
4542 panic_in_clone: self.panic_in_clone,
4543 dropped: self.dropped,
4544 need_drop: self.need_drop.clone(),
4545 }
4546 }
4547 }
4548
4549 impl Drop for CheckedCloneDrop {
4550 fn drop(&mut self) {
4551 assert!(!self.dropped, "double drop");
4552 self.dropped = true;
4553 }
4554 }
4555
4556 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
4557
4558 let mut table = RawTable::new_in(MyAlloc {
4559 _inner: Arc::new(MyAllocInner {
4560 drop_count: dropped.clone(),
4561 }),
4562 });
4563
4564 for (idx, panic_in_clone) in core::iter::repeat_n(DISARMED, 7).enumerate() {
4565 let idx = idx as u64;
4566 table.insert(
4567 idx,
4568 (
4569 idx,
4570 CheckedCloneDrop {
4571 panic_in_clone,
4572 dropped: false,
4573 need_drop: vec![idx],
4574 },
4575 ),
4576 |(k, _)| *k,
4577 );
4578 }
4579
4580 assert_eq!(table.len(), 7);
4581
4582 thread::scope(|s| {
4583 let result = s.spawn(|| {
4584 let armed_flags = [
4585 DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
4586 ];
4587 let mut scope_table = RawTable::new_in(MyAlloc {
4588 _inner: Arc::new(MyAllocInner {
4589 drop_count: dropped.clone(),
4590 }),
4591 });
4592 for (idx, &panic_in_clone) in armed_flags.iter().enumerate() {
4593 let idx = idx as u64;
4594 scope_table.insert(
4595 idx,
4596 (
4597 idx,
4598 CheckedCloneDrop {
4599 panic_in_clone,
4600 dropped: false,
4601 need_drop: vec![idx + 100],
4602 },
4603 ),
4604 |(k, _)| *k,
4605 );
4606 }
4607 table.clone_from(&scope_table);
4608 });
4609 assert!(result.join().is_err());
4610 });
4611
4612 // Let's check that all iterators work fine and do not return elements
4613 // (especially `RawIterRange`, which does not depend on the number of
4614 // elements in the table, but looks directly at the control bytes)
4615 //
4616 // SAFETY: We know for sure that `RawTable` will outlive
4617 // the returned `RawIter / RawIterRange` iterator.
4618 assert_eq!(table.len(), 0);
4619 assert_eq!(unsafe { table.iter().count() }, 0);
4620 assert_eq!(unsafe { table.iter().iter.count() }, 0);
4621
4622 for idx in 0..table.num_buckets() {
4623 let idx = idx as u64;
4624 assert!(
4625 table.find(idx, |(k, _)| *k == idx).is_none(),
4626 "Index: {idx}"
4627 );
4628 }
4629
4630 // All allocator clones should already be dropped.
4631 assert_eq!(dropped.load(Ordering::SeqCst), 1);
4632 }
4633}