Skip to main content

zu_common/
ids.rs

1//! A hash for maps whose key is an id.
2//!
3//! The default hash is SipHash, which is there so a map fed keys by a
4//! stranger cannot be made to collide on purpose. Nothing in the engine
5//! is fed keys by a stranger: a table id, a column id, a block offset
6//! and a chunk number all come from the catalog or the file, and the
7//! maps they key are small and read once or twice a statement. What
8//! SipHash costs on those is a round of mixing per lookup for a
9//! guarantee nobody needs, and it shows: on a point write the two
10//! lookups of the props map alone were near a tenth of the processor
11//! time the statement spent outside the file.
12//!
13//! So ids get their own hash, one multiply and one shift. The multiply
14//! is by an odd constant, which is a bijection on 64 bits and puts the
15//! entropy of the whole key in the top bits; the shift folds those back
16//! down, because a hash table reads the top bits and the bottom bits for
17//! two different things and both have to be mixed. Sequential ids, which
18//! is what these keys mostly are, come out spread rather than adjacent.
19//!
20//! This is not a hash to key anything on that arrives from outside. Use
21//! it for ids and use the default for the rest.
22
23use std::hash::{BuildHasherDefault, Hasher};
24
25/// The odd constant, 2^64 over the golden ratio.
26const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
27
28/// Spreads one key over the whole word, top and bottom.
29const fn mix(key: u64) -> u64 {
30    let spread = key.wrapping_mul(GOLDEN);
31    spread ^ (spread >> 32)
32}
33
34/// A [`Hasher`] for keys that are one integer.
35///
36/// A key written as several pieces, or as bytes, still hashes, just
37/// without the one-multiply shape: each piece mixes into what came
38/// before. That is here so a misuse is slow rather than wrong.
39#[derive(Default, Clone, Copy)]
40pub struct IdHasher(u64);
41
42impl Hasher for IdHasher {
43    fn finish(&self) -> u64 {
44        self.0
45    }
46
47    fn write(&mut self, bytes: &[u8]) {
48        for &byte in bytes {
49            self.0 = mix(self.0 ^ u64::from(byte));
50        }
51    }
52
53    fn write_u8(&mut self, n: u8) {
54        self.write_u64(u64::from(n));
55    }
56
57    fn write_u16(&mut self, n: u16) {
58        self.write_u64(u64::from(n));
59    }
60
61    fn write_u32(&mut self, n: u32) {
62        self.write_u64(u64::from(n));
63    }
64
65    fn write_u64(&mut self, n: u64) {
66        self.0 = mix(self.0.rotate_left(5) ^ n);
67    }
68
69    fn write_usize(&mut self, n: usize) {
70        self.write_u64(n as u64);
71    }
72
73    fn write_i8(&mut self, n: i8) {
74        self.write_u64(n as u64);
75    }
76
77    fn write_i16(&mut self, n: i16) {
78        self.write_u64(n as u64);
79    }
80
81    fn write_i32(&mut self, n: i32) {
82        self.write_u64(n as u64);
83    }
84
85    fn write_i64(&mut self, n: i64) {
86        self.write_u64(n as u64);
87    }
88
89    fn write_isize(&mut self, n: isize) {
90        self.write_u64(n as u64);
91    }
92}
93
94/// The [`BuildHasher`](std::hash::BuildHasher) of [`IdHasher`], which
95/// is what the map types below carry.
96pub type BuildIdHasher = BuildHasherDefault<IdHasher>;
97
98/// A [`HashMap`](std::collections::HashMap) keyed by an id.
99pub type IdMap<K, V> = std::collections::HashMap<K, V, BuildIdHasher>;
100
101/// A [`HashSet`](std::collections::HashSet) of ids.
102pub type IdSet<K> = std::collections::HashSet<K, BuildIdHasher>;
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use std::collections::HashSet;
108    use std::hash::Hash;
109
110    fn hash<K: Hash>(key: K) -> u64 {
111        let mut h = IdHasher::default();
112        key.hash(&mut h);
113        h.finish()
114    }
115
116    #[test]
117    fn a_map_keyed_by_an_id_reads_back_what_was_put_in_it() {
118        let mut m: IdMap<u32, &str> = IdMap::default();
119        for i in 0..1000u32 {
120            m.insert(i, "row");
121        }
122        assert_eq!(m.len(), 1000);
123        assert_eq!(m.get(&999), Some(&"row"));
124        assert_eq!(m.get(&1000), None);
125    }
126
127    #[test]
128    fn the_ids_a_catalog_hands_out_do_not_land_on_one_another() {
129        let seen: HashSet<u64> = (0..4096u32).map(hash).collect();
130        assert_eq!(seen.len(), 4096, "sequential ids all differ");
131    }
132
133    /// What a hash table reads: the top bits pick the control byte and
134    /// the bottom bits pick the bucket, so neither end may be the key
135    /// itself.
136    #[test]
137    fn both_ends_of_the_word_move_with_the_key() {
138        for shift in [0u32, 7, 25, 57] {
139            let ends = |h: u64| (h >> 57, h & 0x7f);
140            let (top, bottom) = ends(hash(1u64 << shift));
141            let (next_top, next_bottom) = ends(hash((1u64 << shift) + 1));
142            assert_ne!(top, next_top, "top bits at shift {shift}");
143            assert_ne!(bottom, next_bottom, "bottom bits at shift {shift}");
144        }
145    }
146
147    #[test]
148    fn a_key_written_as_bytes_still_separates() {
149        let seen: HashSet<u64> = ["age", "name", "since", "id", ""]
150            .map(hash)
151            .into_iter()
152            .collect();
153        assert_eq!(seen.len(), 5);
154    }
155
156    #[test]
157    fn two_ids_in_a_pair_are_not_the_same_pair_swapped() {
158        assert_ne!(hash((1u32, 2u32)), hash((2u32, 1u32)));
159    }
160}