Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a insert_unique_hashed_nocheck method #452

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3205,6 +3205,33 @@ impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> {
}
}

impl<'a, K: Hash, V, S: BuildHasher, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> {
/// Insert a key-value pair into the map without checking if the key already exists in the map.
/// The hash provided is used for the key instead of hashing the key.
///
/// For correct operation of the hash table, the key must not already be in the map and the hash
/// must match they hash the maps's hash build would produce.
#[cfg_attr(feature = "inline-more", inline)]
#[allow(clippy::wrong_self_convention)]
pub fn insert_unique_hashed_nocheck(
self,
hash: u64,
key: K,
value: V,
) -> RawOccupiedEntryMut<'a, K, V, S, A> {
let elem = self.map.table.insert(
hash,
(key, value),
make_hasher::<_, V, S>(&self.map.hash_builder),
);
RawOccupiedEntryMut {
elem,
table: &mut self.map.table,
hash_builder: &self.map.hash_builder,
}
}
}

impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> {
/// Creates a `RawEntryMut` from the given hash and matching function.
///
Expand Down Expand Up @@ -8154,6 +8181,28 @@ mod test_map {
}
}

#[test]
fn test_raw_entry_insert_unique_hashed_nocheck() {
let xs = [(1_i32, 10_i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];

let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
super::make_hash::<i32, _>(map.hasher(), &k)
};

let mut map: HashMap<_, _> = HashMap::new();

for (k, v) in xs.iter().copied() {
let hash = compute_hash(&map, k);
map.raw_entry_mut().insert_unique_hashed_nocheck(hash, k, v);
}

for (k, v) in xs.iter().copied() {
assert_eq!(map.remove(&k), Some(v));
}

assert_eq!(map.len(), 0);
}

#[test]
fn test_raw_entry() {
use super::RawEntryMut::{Occupied, Vacant};
Expand Down
Loading