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