Any way to have HashSet use precomputed hash on the value type?

Say I've got a struct something like:

    struct MyStruct {
        hash: u64,
        // ... more data...
    }

Is there a way to have a HashSet use the hash value on my struct rather than trying to hash it again? I know I can implement Hash for my type, but that will try and hash the hash if I pass it to Hash::hash() I think?

1 Like

The standard library HashMap and HashSet don't have a built-in stable way memoize hashes like this, yet. HashMap has an experimental raw_entry API on nightly that supports this use case; see this thread for some more details. It's not implemented on HashSet (yet?) but you could implement your own set type on top of HashMap for now.

Or, I believe you could also make this work using a custom Hash impl for your struct and a custom Hasher type for your HashSet. The custom Hasher would just use the identity function as its hash function.

Or, the trashmap crate might work for you.

1 Like

Note that to prevent DDoS attack stdlib uses randomized hasher so every hashmap/set instances will produces different hash from same value.

Thanks! The raw_entry API looks like it's probably what I need.