#[cfg(feature = "secure-hash")]
use core::hash::Hasher;
pub trait KeyHasher<const K: usize> {
fn hash(&self, key: &[u8; K]) -> u64;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FastHasher;
impl<const K: usize> KeyHasher<K> for FastHasher {
#[inline]
fn hash(&self, key: &[u8; K]) -> u64 {
hash_fast(key)
}
}
#[cfg(feature = "secure-hash")]
pub struct SecureHasher {
key: [u8; 16],
}
#[cfg(feature = "secure-hash")]
impl SecureHasher {
pub const fn new(key: [u8; 16]) -> Self {
Self { key }
}
}
#[cfg(feature = "secure-hash")]
impl<const K: usize> KeyHasher<K> for SecureHasher {
#[inline]
fn hash(&self, key: &[u8; K]) -> u64 {
let mut hasher = siphasher::sip::SipHasher24::new_with_key(&self.key);
hasher.write(key);
hasher.finish()
}
}
#[inline]
fn hash_fast<const K: usize>(key: &[u8; K]) -> u64 {
const MULTIPLIER: u64 = 0x517cc1b727220a95;
let mut hash = 0x9e3779b97f4a7c15_u64;
let (chunks, remainder) = key.as_slice().as_chunks::<8>();
for chunk in chunks {
hash = (hash.rotate_left(5) ^ u64::from_le_bytes(*chunk)).wrapping_mul(MULTIPLIER);
}
if !remainder.is_empty() {
let mut tail = [0; 8];
tail[..remainder.len()].copy_from_slice(remainder);
hash = (hash.rotate_left(5) ^ u64::from_le_bytes(tail)).wrapping_mul(MULTIPLIER);
}
hash ^= hash >> 32;
hash = hash.wrapping_mul(0xd6e8feb86659fd93);
hash ^ (hash >> 32)
}