Skip to content

What happens when calling HashTable::insert_unique multiple times with the same value? #744

Description

@gendx

The HashMap::insert_unique_unchecked() and HashSet::insert_unique_unchecked() methods are marked as unsafe, because calling them multiple times to insert the same value causes unspecified behavior (without violating memory safety).

However, the HashTable::insert_unique() method is safe. What kind of guarantees does it make about calling it multiple times with the same value?

pub fn insert_unique(
    &mut self,
    hash: u64,
    value: T,
    hasher: impl Fn(&T) -> u64,
) -> OccupiedEntry<'_, T, A>

Given that the hash is u64, hash collisions can obviously not be excluded (even if using a cryptographic hash function). And given that nothing in the signature imposes constraints such as T: Eq, the hash table has no way to know if two values that evaluate to the same hash are the same or not. So I assume it's safe to insert twice the same value, and that one of them will be returned upon lookup?

Note: find does know about the equality constraint, so maybe the question is rather: what happens if find gets multiple equality matches for the given hash value?

pub fn find(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T>

(Likewise .entry(...).remove() knows about equality, but my use case is insert-only so I don't care about removals misbehaving).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions