Skip to main content

axhash_core/hasher/
build.rs

1use core::hash::BuildHasher;
2
3use crate::constants::SECRET;
4
5use super::AxHasher;
6
7#[derive(Clone, Copy)]
8pub struct AxBuildHasher {
9    pub(crate) prepared_seed: u64,
10}
11
12impl AxBuildHasher {
13    #[inline(always)]
14    pub const fn new() -> Self {
15        Self {
16            prepared_seed: SECRET[0],
17        }
18    }
19
20    #[inline(always)]
21    pub const fn with_seed(seed: u64) -> Self {
22        Self {
23            prepared_seed: seed ^ SECRET[0],
24        }
25    }
26
27    /// Create a new build hasher with a randomized seed drawn from OS entropy.
28    /// Panics if the OS entropy source is unavailable.
29    #[inline]
30    pub fn random() -> Self {
31        let mut buf = [0u8; 8];
32        match getrandom::getrandom(&mut buf) {
33            Ok(()) => Self::with_seed(u64::from_le_bytes(buf)),
34            Err(e) => panic!("failed to obtain random seed for AxBuildHasher: {e:?}"),
35        }
36    }
37}
38
39impl Default for AxBuildHasher {
40    #[inline(always)]
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl BuildHasher for AxBuildHasher {
47    type Hasher = AxHasher;
48
49    #[inline(always)]
50    fn build_hasher(&self) -> Self::Hasher {
51        AxHasher {
52            acc: self.prepared_seed,
53            sponge: 0,
54            sponge_bits: 0,
55        }
56    }
57}