Debian Codegraph @

src/murmur_hash.rs

raw symbols SCIP
1 /// MurmurHash2 was written by Austin Appleby, and is placed in the public
2 /// domain. The author hereby disclaims copyright to this source code.
3 ///
4 /// Note - This code makes a few assumptions about how your machine behaves -
5 ///
6 /// 1. We can read a 4-byte value from any address without crashing
7 /// 2. sizeof(int) == 4
8 ///
9 /// And it has a few limitations -
10 ///
11 /// 1. It will not work incrementally.
12 /// 2. It will not produce the same results on little-endian and big-endian
13 /// machines.
14 pub fn murmur_hash2(key: &[u8], seed: u32) -> u32 {
15 // 'm' and 'r' are mixing constants generated offline.
16 // They're not really 'magic', they just happen to work well.
17
18 const M: u32 = 0x5bd1e995;
19 const R: u32 = 24;
20
21 // Initialize the hash to a 'random' value
22
23 let mut h = seed ^ (key.len() as u32);
24
25 // Mix 4 bytes at a time into the hash
26 key.chunks_exact(4).for_each(|data| {
27 let mut k = u32::from_ne_bytes(data.try_into().unwrap_or([0u8; 4]));
28
29 k = k.saturating_mul(M);
30 k ^= k >> R;
31 k = k.saturating_mul(M);
32
33 h = h.saturating_mul(M);
34 h ^= k;
35 });
36
37 let key_len = key.len();
38 let mod_len = key_len % 4;
39
40 // Handle the last few bytes of the input array
41
42 match mod_len {
43 3 => {
44 h ^= (key[key_len - 1] as u32) << 16;
45 h ^= (key[key_len - 2] as u32) << 8;
46 h ^= key[key_len - 3] as u32;
47 }
48 2 => {
49 h ^= (key[key_len - 1] as u32) << 8;
50 h ^= key[key_len - 2] as u32;
51 }
52 1 => h ^= key[key_len - 1] as u32,
53 _ => (),
54 }
55
56 h = h.saturating_mul(M);
57
58 // Do a few final mixes of the hash to ensure the last few
59 // bytes are well-incorporated.
60
61 h ^= h >> 13;
62 h = h.saturating_mul(M);
63 h ^= h >> 15;
64
65 h
66 }