Debian Codegraph @

debian/missing-sources/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 #[expect(clippy::indexing_slicing, clippy::unwrap_used)]
66 pub fn compute_displacements(
67 key_hashes: impl ExactSizeIterator<Item = u64>,
68 ) -> (Vec<(u32, u32)>, Vec<usize>) {
69 let len = key_hashes.len();
70
71 // A vector to track the size of buckets for sorting.
72 let mut bucket_sizes = vec![0; len];
73
74 // A flattened representation of items in the buckets after applying first level hash function
75 let mut bucket_flatten = Vec::with_capacity(len);
76
77 // Compute initial displacement and bucket sizes
78
79 key_hashes.into_iter().enumerate().for_each(|(i, kh)| {
80 let h = split_hash64(kh, len);
81 bucket_sizes[h.0] += 1;
82 bucket_flatten.push((h, i))
83 });
84
85 // Sort by decreasing order of bucket_sizes.
86 bucket_flatten.sort_by(|&(ha, _), &(hb, _)| {
87 // ha.0, hb.0 are always within bounds of `bucket_sizes`
88 (bucket_sizes[hb.0], hb).cmp(&(bucket_sizes[ha.0], ha))
89 });
90
91 // Generation count while iterating buckets.
92 // Each trial of ((d0, d1), bucket chain) is a new generation.
93 // We use this to track which all slots are assigned for the current bucket chain.
94 let mut generation = 0;
95
96 // Whether a slot has been occupied by previous buckets with a different first level hash (different
97 // bucket chain).
98 let mut occupied = vec![false; len];
99
100 // Track generation count for the slots.
101 // A slot is empty if either it is unoccupied by the previous bucket chains and the
102 // assignment is not equal to generation.
103 let mut assignments = vec![0; len];
104
105 // Vec to store the displacements (saves us a recomputation of hash while assigning slots).
106 let mut current_displacements = Vec::with_capacity(16);
107
108 // (d0, d1) which splits the bucket into different slots
109 let mut displacements = vec![(0, 0); len];
110
111 // Vec to store mapping to the original order of keys.
112 // This is a permutation which will be applied to keys, values at the end.
113 let mut reverse_mapping = vec![0; len];
114
115 let mut start = 0;
116 while start < len {
117 // Bucket span with the same first level hash
118 // start is always within bounds of `bucket_flatten`
119 let g = bucket_flatten[start].0 .0;
120 // g is always within bounds of `bucket_sizes`
121 let end = start + bucket_sizes[g];
122 // start, end - 1 are always within bounds of `bucket_sizes`
123 let buckets = &bucket_flatten[start..end];
124
125 'd0: for d0 in 0..len as u32 {
126 'd1: for d1 in 0..len as u32 {
127 if (d0, d1) == (0, 0) {
128 continue;
129 }
130 current_displacements.clear();
131 generation += 1;
132
133 for ((_, f0, f1), _) in buckets {
134 let displacement_idx = compute_index((*f0, *f1), (d0, d1), len as u32).unwrap();
135
136 // displacement_idx is always within bounds
137 if occupied[displacement_idx] || assignments[displacement_idx] == generation {
138 continue 'd1;
139 }
140 assignments[displacement_idx] = generation;
141 current_displacements.push(displacement_idx);
142 }
143
144 // Successfully found a (d0, d1), store it as index g.
145 // g < displacements.len() due to modulo operation
146 displacements[g] = (d0, d1);
147
148 for (i, displacement_idx) in current_displacements.iter().enumerate() {
149 // `current_displacements` has same size as `buckets`
150 let (_, idx) = &buckets[i];
151
152 // displacement_idx is always within bounds
153 occupied[*displacement_idx] = true;
154 reverse_mapping[*displacement_idx] = *idx;
155 }
156 break 'd0;
157 }
158 }
159
160 start = end;
161 }
162
163 (displacements, reverse_mapping)
164 }