1use std::collections::hash_map::DefaultHasher;
10use std::hash::Hash;
11use std::hash::Hasher;
12
13pub fn hash_with_max<TKey>(key: &TKey, excluded_max: usize) -> usize
15where
16 TKey: Hash,
17{
18 let mut dh = DefaultHasher::new();
19 key.hash(&mut dh);
20 let bounded_hash = dh.finish() % (excluded_max as u64);
21 bounded_hash as usize
22}
23
24#[cfg(test)]
25mod tests {
26
27 use super::*;
28
29 #[derive(Hash)]
30 struct TestHashable(u128);
31
32 #[test]
33 fn test_bounded_hashing() {
34 let test_values = [
35 TestHashable(0),
36 TestHashable(10),
37 TestHashable(23),
38 TestHashable(128),
39 TestHashable(u64::MAX as u128),
40 ];
41
42 let test_results = [0usize, 2, 1, 0, 0];
43
44 for (test_value, test_result) in test_values.iter().zip(test_results) {
45 let hashed = hash_with_max(test_value, 3);
46 assert_eq!(test_result, hashed);
47 }
48 }
49}