Skip to main content

fixed_hashmap/
hash.rs

1#[cfg(feature = "secure-hash")]
2use core::hash::Hasher;
3
4/// Hash strategy used by a fixed map.
5pub trait KeyHasher<const K: usize> {
6    /// Hashes a fixed-size key to a 64-bit value.
7    fn hash(&self, key: &[u8; K]) -> u64;
8}
9
10/// Fast, non-cryptographic key hasher used by default.
11#[derive(Clone, Copy, Debug, Default)]
12pub struct FastHasher;
13
14impl<const K: usize> KeyHasher<K> for FastHasher {
15    #[inline]
16    fn hash(&self, key: &[u8; K]) -> u64 {
17        hash_fast(key)
18    }
19}
20
21/// Keyed SipHash-2-4 hasher for resistance to attacker-chosen collisions.
22///
23/// Create this with a fresh, secret 128-bit key from a cryptographically
24/// secure random source. The hasher does not generate entropy itself.
25#[cfg(feature = "secure-hash")]
26pub struct SecureHasher {
27    key: [u8; 16],
28}
29
30#[cfg(feature = "secure-hash")]
31impl SecureHasher {
32    /// Creates a hasher from a caller-provided 128-bit secret key.
33    pub const fn new(key: [u8; 16]) -> Self {
34        Self { key }
35    }
36}
37
38#[cfg(feature = "secure-hash")]
39impl<const K: usize> KeyHasher<K> for SecureHasher {
40    #[inline]
41    fn hash(&self, key: &[u8; K]) -> u64 {
42        let mut hasher = siphasher::sip::SipHasher24::new_with_key(&self.key);
43        hasher.write(key);
44        hasher.finish()
45    }
46}
47
48#[inline]
49fn hash_fast<const K: usize>(key: &[u8; K]) -> u64 {
50    const MULTIPLIER: u64 = 0x517cc1b727220a95;
51    let mut hash = 0x9e3779b97f4a7c15_u64;
52    let (chunks, remainder) = key.as_slice().as_chunks::<8>();
53
54    for chunk in chunks {
55        hash = (hash.rotate_left(5) ^ u64::from_le_bytes(*chunk)).wrapping_mul(MULTIPLIER);
56    }
57
58    if !remainder.is_empty() {
59        let mut tail = [0; 8];
60        tail[..remainder.len()].copy_from_slice(remainder);
61        hash = (hash.rotate_left(5) ^ u64::from_le_bytes(tail)).wrapping_mul(MULTIPLIER);
62    }
63
64    hash ^= hash >> 32;
65    hash = hash.wrapping_mul(0xd6e8feb86659fd93);
66    hash ^ (hash >> 32)
67}