Skip to main content

zu_vector/kernels/
hash.rs

1//! Key hashing for joins and grouping. One multiply-xor finalizer per
2//! key (the splitmix64 tail): two multiplies and three shifts, no data
3//! dependence between rows, so the slice form streams at memory speed.
4
5/// Mix a 64-bit key. Full-avalanche: every input bit flips ~half the
6/// output bits, which is what a radix-partitioned join table needs from
7/// both ends of the hash.
8#[inline]
9pub fn hash64(x: u64) -> u64 {
10    let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
11    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
12    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
13    z ^ (z >> 31)
14}
15
16/// Hash a slice of keys into `out`. Unrolled by four so the multiply
17/// chains of neighboring keys overlap instead of waiting on the loop
18/// bookkeeping.
19pub fn hash_slice(keys: &[u64], out: &mut [u64]) {
20    debug_assert_eq!(keys.len(), out.len());
21    // Fours as arrays rather than as slices, which is the same unroll
22    // with the length in the type, so the four stores need no bounds
23    // check to prove.
24    let (fours, tail) = keys.as_chunks::<4>();
25    let (outs, out_tail) = out.as_chunks_mut::<4>();
26    for (k4, o4) in fours.iter().zip(outs) {
27        o4[0] = hash64(k4[0]);
28        o4[1] = hash64(k4[1]);
29        o4[2] = hash64(k4[2]);
30        o4[3] = hash64(k4[3]);
31    }
32    for (o, &k) in out_tail.iter_mut().zip(tail) {
33        *o = hash64(k);
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn distinct_and_deterministic() {
43        let keys: Vec<u64> = (0..1000).collect();
44        let mut out = vec![0u64; 1000];
45        hash_slice(&keys, &mut out);
46        let mut seen = out.clone();
47        seen.sort_unstable();
48        seen.dedup();
49        assert_eq!(seen.len(), 1000, "no collisions on a small dense domain");
50        assert_eq!(hash64(42), hash64(42));
51        assert_ne!(hash64(42), hash64(43));
52    }
53
54    #[test]
55    fn low_bits_avalanche() {
56        // Sequential keys must not produce sequential low bits, or a
57        // power-of-two partition count degenerates.
58        let buckets: std::collections::BTreeSet<u64> = (0..64u64).map(|k| hash64(k) & 7).collect();
59        assert!(buckets.len() > 4);
60    }
61}