Skip to content

Commit 069761b

Browse files
committed
Add HashTable::get_bucket_entry_unchecked
1 parent 65bb2dd commit 069761b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/table.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,52 @@ where
471471
}
472472
}
473473

474+
/// Returns an `OccupiedEntry` for the given bucket index in the table,
475+
/// without checking whether the index is in-bounds or occupied.
476+
///
477+
/// For a safe alternative, see [`get_bucket_entry`](Self::get_bucket_entry).
478+
///
479+
/// # Safety
480+
///
481+
/// It is *[undefined behavior]* to call this method with an index that is
482+
/// out-of-bounds or unoccupied, even if the resulting reference is not used.
483+
///
484+
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
485+
///
486+
/// # Examples
487+
///
488+
/// ```
489+
/// # #[cfg(feature = "nightly")]
490+
/// # fn test() {
491+
/// use hashbrown::{HashTable, DefaultHashBuilder};
492+
/// use std::hash::BuildHasher;
493+
///
494+
/// let mut table = HashTable::new();
495+
/// let hasher = DefaultHashBuilder::default();
496+
/// let hasher = |val: &_| hasher.hash_one(val);
497+
/// table.insert_unique(hasher(&1), (1, 'a'), |val| hasher(&val.0));
498+
/// table.insert_unique(hasher(&2), (2, 'b'), |val| hasher(&val.0));
499+
/// table.insert_unique(hasher(&3), (3, 'c'), |val| hasher(&val.0));
500+
///
501+
/// let index = table.find_bucket_index(hasher(&2), |val| val.0 == 2).unwrap();
502+
/// assert!(std::ptr::eq(
503+
/// table.get_bucket_entry(index).unwrap().into_mut(),
504+
/// unsafe { table.get_bucket_entry_unchecked(index).into_mut() },
505+
/// ));
506+
/// # }
507+
/// # fn main() {
508+
/// # #[cfg(feature = "nightly")]
509+
/// # test()
510+
/// # }
511+
/// ```
512+
#[inline]
513+
pub unsafe fn get_bucket_entry_unchecked(&mut self, index: usize) -> OccupiedEntry<'_, T, A> {
514+
OccupiedEntry {
515+
bucket: self.raw.bucket(index),
516+
table: self,
517+
}
518+
}
519+
474520
/// Gets a reference to an entry in the table at the given bucket index,
475521
/// or `None` if it is unoccupied or out of bounds.
476522
///

0 commit comments

Comments
 (0)