model-core 0.11.1

Language-neutral source code metamodel
Documentation
//! Fast hashing for the builder's tables. `std`'s SipHash dominated the
//! composition of large models (keys of ~100 bytes, millions of them); this
//! multiply-rotate hash (as `rustc-hash`) reads 8 bytes at a time and is
//! finished by `splitmix64`'s mixer. Its seed is random per process, so a
//! crafted source tree cannot count on colliding keys.

use std::hash::{BuildHasher, Hasher, RandomState};
use std::sync::OnceLock;

const K: u64 = 0xf135_7aea_2e62_a9c5;

fn seed() -> u64 {
    static SEED: OnceLock<u64> = OnceLock::new();
    *SEED.get_or_init(|| RandomState::new().hash_one(0x5eed_u64))
}

/// [`BuildHasher`] of the process seed.
#[derive(Debug, Clone, Copy)]
pub(crate) struct FastState(u64);

impl Default for FastState {
    fn default() -> Self {
        FastState(seed())
    }
}

impl BuildHasher for FastState {
    type Hasher = FastHasher;

    fn build_hasher(&self) -> FastHasher {
        FastHasher(self.0)
    }
}

pub(crate) type FastMap<K, V> = std::collections::HashMap<K, V, FastState>;

pub(crate) struct FastHasher(u64);

impl FastHasher {
    #[inline]
    fn add(&mut self, word: u64) {
        self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(K);
    }
}

impl Hasher for FastHasher {
    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        let (words, rest) = bytes.as_chunks::<8>();
        for w in words {
            self.add(u64::from_le_bytes(*w));
        }
        let mut w = [0u8; 8];
        w[..rest.len()].copy_from_slice(rest);
        // The length tells `ab` from `ab\0`.
        self.add(u64::from_le_bytes(w) ^ ((bytes.len() as u64) << 56));
    }

    #[inline]
    fn write_u8(&mut self, i: u8) {
        self.add(u64::from(i));
    }

    #[inline]
    fn write_u16(&mut self, i: u16) {
        self.add(u64::from(i));
    }

    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.add(u64::from(i));
    }

    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.add(i);
    }

    #[inline]
    fn write_usize(&mut self, i: usize) {
        self.add(i as u64);
    }

    #[inline]
    fn finish(&self) -> u64 {
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^ (z >> 31)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn equal_inputs_hash_equal_and_lengths_matter() {
        let s = FastState::default();
        assert_eq!(
            s.hash_one("scip-java maven a/B#"),
            s.hash_one("scip-java maven a/B#")
        );
        assert_ne!(s.hash_one("ab"), s.hash_one("ab\0"));
        assert_ne!(s.hash_one(b"ab".as_slice()), s.hash_one(b"ab\0".as_slice()));
        assert_ne!(s.hash_one(1u32), s.hash_one(2u32));
        // Low bits (bucket index) spread over short similar keys.
        let mut buckets = std::collections::HashSet::new();
        for i in 0..1000 {
            buckets.insert(s.hash_one(format!("k{i}")) & 1023);
        }
        assert!(buckets.len() > 550, "{}", buckets.len());
    }
}