Debian Codegraph @

debian/rust-vendor/zerovec/src/hashmap/algorithms.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use alloc::vec;
6 use alloc::vec::Vec;
7 use core::hash::{Hash, Hasher};
8 use twox_hash::XxHash64;
9
10 // Const seed to be used with [`XxHash64::with_seed`].
11 const SEED: u64 = 0xaabbccdd;
12
13 /// Split the 64bit `hash` into (g, f0, f1).
14 ///
15 /// g denotes the highest 16bits of the hash modulo `m`, and is referred to as first level hash.
16 /// (f0, f1) denotes the middle, and lower 24bits of the hash respectively.
17 /// (f0, f1) are used to distribute the keys with same g, into distinct slots.
18 ///
19 /// # Arguments
20 ///
21 /// * `hash` - The hash to split.
22 /// * `m` - The modulo used to split the hash.
23 pub const fn split_hash64(hash: u64, m: usize) -> (usize, u32, u32) {
24 (
25 ((hash >> 48) as usize % m),
26 ((hash >> 24) as u32 & 0xffffff),
27 ((hash & 0xffffff) as u32),
28 )
29 }
30
31 /// Compute hash using [`XxHash64`].
32 pub fn compute_hash<K: Hash + ?Sized>(key: &K) -> u64 {
33 let mut hasher = XxHash64::with_seed(SEED);
34 key.hash(&mut hasher);
35 hasher.finish()
36 }
37
38 /// Calculate the index using (f0, f1), (d0, d1) in modulo m.
39 /// Returns [`None`] if d is (0, 0) or modulo is 0
40 /// else returns the index computed using (f0 + f1 * d0 + d1) mod m.
41 pub fn compute_index(f: (u32, u32), d: (u32, u32), m: u32) -> Option<usize> {
42 if d == (0, 0) || m == 0 {
43 None
44 } else {
45 Some((f.1.wrapping_mul(d.0).wrapping_add(f.0).wrapping_add(d.1) % m) as usize)
46 }
47 }
48
49 /// Compute displacements for the given `key_hashes`, which split the keys into distinct slots by a
50 /// two-level hashing schema.
51 ///
52 /// Returns a tuple of where the first item is the displacement array and the second item is the
53 /// reverse mapping used to permute keys, values into their slots.
54 ///
55 /// 1. Split the hashes into (g, f0, f1).
56 /// 2. Bucket and sort the split hash on g in descending order.
57 /// 3. In decreasing order of bucket size, try until a (d0, d1) is found that splits the keys
58 /// in the bucket into distinct slots.
59 /// 4. Mark the slots for current bucket as occupied and store the reverse mapping.
60 /// 5. Repeat untill all the keys have been assigned distinct slots.
61 ///
62 /// # Arguments
63 ///
64 /// * `key_hashes` - [`ExactSizeIterator`] over the hashed key values
65 ///
66 /// # Panics
67 ///
68 /// Panics if the `key_hashes` iterator claims to have more elements than can fit in a u32.
69 #[expect(
70 clippy::indexing_slicing,
71 clippy::unwrap_used,
72 clippy::expect_used,
73 reason = "Documented panic"
74 )]
75 pub fn compute_displacements(
76 key_hashes: impl ExactSizeIterator<Item = u64>,
77 ) -> (Vec<(u32, u32)>, Vec<usize>) {
78 let len = key_hashes.len();
79 let len_u32 = u32::try_from(len).expect("Hashmap too large for u32");
80
81 // A vector to track the size of buckets for sorting.
82 let mut bucket_sizes = vec![0; len];
83
84 // A flattened representation of items in the buckets after applying first level hash function
85 let mut bucket_flatten = Vec::with_capacity(len);
86
87 // Compute initial displacement and bucket sizes
88
89 key_hashes.into_iter().enumerate().for_each(|(i, kh)| {
90 let h = split_hash64(kh, len);
91 bucket_sizes[h.0] += 1;
92 bucket_flatten.push((h, i))
93 });
94
95 // Sort by decreasing order of bucket_sizes.
96 bucket_flatten.sort_by(|&(ha, _), &(hb, _)| {
97 // ha.0, hb.0 are always within bounds of `bucket_sizes`
98 (bucket_sizes[hb.0], hb).cmp(&(bucket_sizes[ha.0], ha))
99 });
100
101 // Generation count while iterating buckets.
102 // Each trial of ((d0, d1), bucket chain) is a new generation.
103 // We use this to track which all slots are assigned for the current bucket chain.
104 let mut generation = 0;
105
106 // Whether a slot has been occupied by previous buckets with a different first level hash (different
107 // bucket chain).
108 let mut occupied = vec![false; len];
109
110 // Track generation count for the slots.
111 // A slot is empty if either it is unoccupied by the previous bucket chains and the
112 // assignment is not equal to generation.
113 let mut assignments = vec![0; len];
114
115 // Vec to store the displacements (saves us a recomputation of hash while assigning slots).
116 let mut current_displacements = Vec::with_capacity(16);
117
118 // (d0, d1) which splits the bucket into different slots
119 let mut displacements = vec![(0, 0); len];
120
121 // Vec to store mapping to the original order of keys.
122 // This is a permutation which will be applied to keys, values at the end.
123 let mut reverse_mapping = vec![0; len];
124
125 let mut start = 0;
126 while start < len {
127 // Bucket span with the same first level hash
128 // start is always within bounds of `bucket_flatten`
129 let g = bucket_flatten[start].0 .0;
130 // g is always within bounds of `bucket_sizes`
131 let end = start + bucket_sizes[g];
132 // start, end - 1 are always within bounds of `bucket_sizes`
133 let buckets = &bucket_flatten[start..end];
134
135 'd0: for d0 in 0..len_u32 {
136 'd1: for d1 in 0..len_u32 {
137 if (d0, d1) == (0, 0) {
138 continue;
139 }
140 current_displacements.clear();
141 generation += 1;
142
143 for ((_, f0, f1), _) in buckets {
144 let displacement_idx = compute_index((*f0, *f1), (d0, d1), len_u32).unwrap();
145
146 // displacement_idx is always within bounds
147 if occupied[displacement_idx] || assignments[displacement_idx] == generation {
148 continue 'd1;
149 }
150 assignments[displacement_idx] = generation;
151 current_displacements.push(displacement_idx);
152 }
153
154 // Successfully found a (d0, d1), store it as index g.
155 // g < displacements.len() due to modulo operation
156 displacements[g] = (d0, d1);
157
158 for (i, displacement_idx) in current_displacements.iter().enumerate() {
159 // `current_displacements` has same size as `buckets`
160 let (_, idx) = &buckets[i];
161
162 // displacement_idx is always within bounds
163 occupied[*displacement_idx] = true;
164 reverse_mapping[*displacement_idx] = *idx;
165 }
166 break 'd0;
167 }
168 }
169
170 start = end;
171 }
172
173 (displacements, reverse_mapping)
174 }