radicle/
collections.rs

1//! Useful collections for peer-to-peer networking.
2use siphasher::sip::SipHasher13;
3
4/// A `HashMap` which uses [`fastrand::Rng`] for its random state.
5pub type RandomMap<K, V> = std::collections::HashMap<K, V, RandomState>;
6
7/// A `HashSet` which uses [`fastrand::Rng`] for its random state.
8pub type RandomSet<K> = std::collections::HashSet<K, RandomState>;
9
10/// Random hasher state.
11#[derive(Clone)]
12pub struct RandomState {
13    key1: u64,
14    key2: u64,
15}
16
17impl Default for RandomState {
18    fn default() -> Self {
19        Self::new(crate::profile::env::rng())
20    }
21}
22
23impl RandomState {
24    fn new(mut rng: fastrand::Rng) -> Self {
25        Self {
26            key1: rng.u64(..),
27            key2: rng.u64(..),
28        }
29    }
30}
31
32impl std::hash::BuildHasher for RandomState {
33    type Hasher = SipHasher13;
34
35    fn build_hasher(&self) -> Self::Hasher {
36        SipHasher13::new_with_keys(self.key1, self.key2)
37    }
38}
39
40impl From<fastrand::Rng> for RandomState {
41    fn from(rng: fastrand::Rng) -> Self {
42        Self::new(rng)
43    }
44}