-
Notifications
You must be signed in to change notification settings - Fork 52
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 (random) seed api #22
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
8deba44
Add a way to create `FxHasher` with a given seed
WaffleLapkin 9ff57de
Add a way to seed `FxHasher` with random seeds
WaffleLapkin 3a5e0c4
Add `FxSeededState` & co
WaffleLapkin 71de84e
Add a test that different seeds cause different hashes
WaffleLapkin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
use std::collections::{HashMap, HashSet}; | ||
|
||
use crate::FxHasher; | ||
|
||
/// Type alias for a hashmap using the `fx` hash algorithm with [`FxRandomState`]. | ||
pub type FxHashMapRand<K, V> = HashMap<K, V, FxRandomState>; | ||
|
||
/// Type alias for a hashmap using the `fx` hash algorithm with [`FxRandomState`]. | ||
pub type FxHashSetRand<V> = HashSet<V, FxRandomState>; | ||
|
||
/// `FxRandomState` is an alternative state for `HashMap` types. | ||
/// | ||
/// A particular instance `FxRandomState` will create the same instances of | ||
/// [`Hasher`], but the hashers created by two different `FxRandomState` | ||
/// instances are unlikely to produce the same result for the same values. | ||
pub struct FxRandomState { | ||
seed: usize, | ||
} | ||
|
||
impl FxRandomState { | ||
/// Constructs a new `FxRandomState` that is initialized with random seed. | ||
pub fn new() -> FxRandomState { | ||
use rand::Rng; | ||
use std::{cell::Cell, thread_local}; | ||
|
||
// This mirrors what `std::collections::hash_map::RandomState` does, as of 2024-01-14. | ||
// | ||
// Basically | ||
// 1. Cache result of the rng in a thread local, so repeatedly | ||
// creating maps is cheaper | ||
// 2. Change the cached result on every creation, so maps created | ||
// on the same thread don't have the same iteration order | ||
thread_local!(static SEED: Cell<usize> = { | ||
Cell::new(rand::thread_rng().gen()) | ||
}); | ||
|
||
SEED.with(|seed| { | ||
let s = seed.get(); | ||
seed.set(s.wrapping_add(1)); | ||
FxRandomState { seed: s } | ||
}) | ||
} | ||
} | ||
|
||
impl core::hash::BuildHasher for FxRandomState { | ||
type Hasher = FxHasher; | ||
|
||
fn build_hasher(&self) -> Self::Hasher { | ||
FxHasher::with_seed(self.seed) | ||
} | ||
} | ||
|
||
impl Default for FxRandomState { | ||
fn default() -> Self { | ||
Self::new() | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::thread; | ||
|
||
use crate::FxHashMapRand; | ||
|
||
#[test] | ||
fn random_states_are_different() { | ||
let a = FxHashMapRand::<&str, u32>::default(); | ||
let b = FxHashMapRand::<&str, u32>::default(); | ||
|
||
// That's the whole point of them being random! | ||
// | ||
// N.B.: `FxRandomState` uses a thread-local set to a random value and then incremented, | ||
// which means that this is *guaranteed* to pass :> | ||
assert_ne!(a.hasher().seed, b.hasher().seed); | ||
} | ||
|
||
#[test] | ||
fn random_states_are_different_cross_thread() { | ||
// This is similar to the test above, but uses two different threads, so they both get | ||
// completely random, unrelated values. | ||
// | ||
// This means that this test is technically flaky, but the probability of it failing is | ||
// `1 / 2.pow(bit_size_of::<usize>())`. Or 1/1.7e19 for 64 bit platforms or 1/4294967295 | ||
// for 32 bit platforms. I suppose this is acceptable. | ||
let a = FxHashMapRand::<&str, u32>::default(); | ||
let b = thread::spawn(|| FxHashMapRand::<&str, u32>::default()) | ||
.join() | ||
.unwrap(); | ||
|
||
assert_ne!(a.hasher().seed, b.hasher().seed); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
use std::collections::{HashMap, HashSet}; | ||
|
||
use crate::FxHasher; | ||
|
||
/// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. | ||
pub type FxHashMapSeed<K, V> = HashMap<K, V, FxSeededState>; | ||
|
||
/// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. | ||
pub type FxHashSetSeed<V> = HashSet<V, FxSeededState>; | ||
|
||
/// [`FxSetState`] is an alternative state for `HashMap` types, allowing to use [`FxHasher`] with a set seed. | ||
/// | ||
/// ``` | ||
/// # use std::collections::HashMap; | ||
/// use rustc_hash::FxSeededState; | ||
/// | ||
/// let mut map = HashMap::with_hasher(FxSeededState::with_seed(12)); | ||
/// map.insert(15, 610); | ||
/// assert_eq!(map[&15], 610); | ||
/// ``` | ||
pub struct FxSeededState { | ||
seed: usize, | ||
} | ||
|
||
impl FxSeededState { | ||
/// Constructs a new `FxSeededState` that is initialized with a `seed`. | ||
pub fn with_seed(seed: usize) -> FxSeededState { | ||
Self { seed } | ||
} | ||
} | ||
|
||
impl core::hash::BuildHasher for FxSeededState { | ||
type Hasher = FxHasher; | ||
|
||
fn build_hasher(&self) -> Self::Hasher { | ||
FxHasher::with_seed(self.seed) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use core::hash::BuildHasher; | ||
|
||
use crate::{FxHashMapSeed, FxSeededState}; | ||
|
||
#[test] | ||
fn different_states_are_different() { | ||
let a = FxHashMapSeed::<&str, u32>::with_hasher(FxSeededState::with_seed(1)); | ||
let b = FxHashMapSeed::<&str, u32>::with_hasher(FxSeededState::with_seed(2)); | ||
|
||
assert_ne!( | ||
a.hasher().build_hasher().hash, | ||
b.hasher().build_hasher().hash | ||
); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we add a newline between the modules to make it more obvious that only the former is cfged?