fixed-hashmap 0.1.0

A fixed-capacity, allocation-free hashmap for fixed-size byte keys and values
Documentation
#[cfg(feature = "secure-hash")]
use core::hash::Hasher;

/// Hash strategy used by a fixed map.
pub trait KeyHasher<const K: usize> {
    /// Hashes a fixed-size key to a 64-bit value.
    fn hash(&self, key: &[u8; K]) -> u64;
}

/// Fast, non-cryptographic key hasher used by default.
#[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)
    }
}

/// Keyed SipHash-2-4 hasher for resistance to attacker-chosen collisions.
///
/// Create this with a fresh, secret 128-bit key from a cryptographically
/// secure random source. The hasher does not generate entropy itself.
#[cfg(feature = "secure-hash")]
pub struct SecureHasher {
    key: [u8; 16],
}

#[cfg(feature = "secure-hash")]
impl SecureHasher {
    /// Creates a hasher from a caller-provided 128-bit secret key.
    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)
}