Skip to content

Commit

Permalink
detailed documentation of how hashing is done
Browse files Browse the repository at this point in the history
  • Loading branch information
pali6 committed Oct 8, 2022
1 parent a9f182f commit 2b90f7c
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/cachedhash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,27 @@ use crate::atomic::AtomicOptionNonZeroU64;
///
/// You can run `cargo bench` to see some simple naive benchmarks comparing
/// a plain `HashSet` with a `HashSet` that stores values wrapped in [`CachedHash`].
///
/// # Details
///
/// Whenever the hash is requested if it is not already computed it is computed
/// using the hasher provided by the `BH` [`BuildHasher`] and stored as an "internal
/// hash". Note that this is not the same as the hash returned by the [`Hash`] implementation.
/// That implementation feeds the internal hash into the hasher provided to the `hash`
/// function. This means that the resulting hash is the hash of the hash of the stored
/// value.
///
/// However, there is one more issue. If we wanted to represent both the full
/// range of hash values and the possibility of the hash not being computed yet,
/// we would need 65 bits. In order to save space we need to reserve one value
/// as a sentinel (this also lets us work with the stored "maybe-hash" atomically).
/// This means that we need to artificially create a hash collision. Current
/// implementation does this by changing the "internal hash" from 0 to 1 if it ends
/// up being zero. This is generally not an issue. However, if you are using a custom hasher
/// this might affect you.
///
/// This behaviour is not guaranteed and may change in the future. If this
/// behaviour does not fit for your use case please open an issue.
#[derive(Debug)]
pub struct CachedHash<T: Eq + Hash, BH: BuildHasher = BuildHasherDefault<DefaultHasher>> {
value: T,
Expand Down

0 comments on commit 2b90f7c

Please sign in to comment.