Blame


1 b343c297 2021-10-11 stsp //-----------------------------------------------------------------------------
2 b343c297 2021-10-11 stsp // MurmurHash2 was written by Austin Appleby, and is placed in the public
3 b343c297 2021-10-11 stsp // domain. The author hereby disclaims copyright to this source code.
4 b343c297 2021-10-11 stsp
5 b343c297 2021-10-11 stsp /* Obtained from https://github.com/aappleby/smhasher */
6 b343c297 2021-10-11 stsp
7 b343c297 2021-10-11 stsp #include <stdint.h>
8 b343c297 2021-10-11 stsp
9 b343c297 2021-10-11 stsp #include "murmurhash2.h"
10 b343c297 2021-10-11 stsp
11 b343c297 2021-10-11 stsp uint32_t
12 b343c297 2021-10-11 stsp murmurhash2(const void * key, int len, uint32_t seed)
13 b343c297 2021-10-11 stsp {
14 b343c297 2021-10-11 stsp // 'm' and 'r' are mixing constants generated offline.
15 b343c297 2021-10-11 stsp // They're not really 'magic', they just happen to work well.
16 b343c297 2021-10-11 stsp
17 b343c297 2021-10-11 stsp const uint32_t m = 0x5bd1e995;
18 b343c297 2021-10-11 stsp const int r = 24;
19 b343c297 2021-10-11 stsp
20 b343c297 2021-10-11 stsp // Initialize the hash to a 'random' value
21 b343c297 2021-10-11 stsp
22 b343c297 2021-10-11 stsp uint32_t h = seed ^ len;
23 b343c297 2021-10-11 stsp
24 b343c297 2021-10-11 stsp // Mix 4 bytes at a time into the hash
25 b343c297 2021-10-11 stsp
26 b343c297 2021-10-11 stsp const unsigned char *data = (const unsigned char *)key;
27 b343c297 2021-10-11 stsp
28 b343c297 2021-10-11 stsp while(len >= 4)
29 b343c297 2021-10-11 stsp {
30 b343c297 2021-10-11 stsp uint32_t k = *(uint32_t*)data;
31 b343c297 2021-10-11 stsp
32 b343c297 2021-10-11 stsp k *= m;
33 b343c297 2021-10-11 stsp k ^= k >> r;
34 b343c297 2021-10-11 stsp k *= m;
35 b343c297 2021-10-11 stsp
36 b343c297 2021-10-11 stsp h *= m;
37 b343c297 2021-10-11 stsp h ^= k;
38 b343c297 2021-10-11 stsp
39 b343c297 2021-10-11 stsp data += 4;
40 b343c297 2021-10-11 stsp len -= 4;
41 b343c297 2021-10-11 stsp }
42 b343c297 2021-10-11 stsp
43 b343c297 2021-10-11 stsp // Handle the last few bytes of the input array
44 b343c297 2021-10-11 stsp
45 b343c297 2021-10-11 stsp switch(len)
46 b343c297 2021-10-11 stsp {
47 b343c297 2021-10-11 stsp case 3: h ^= data[2] << 16;
48 b343c297 2021-10-11 stsp case 2: h ^= data[1] << 8;
49 b343c297 2021-10-11 stsp case 1: h ^= data[0];
50 b343c297 2021-10-11 stsp h *= m;
51 b343c297 2021-10-11 stsp };
52 b343c297 2021-10-11 stsp
53 b343c297 2021-10-11 stsp // Do a few final mixes of the hash to ensure the last few
54 b343c297 2021-10-11 stsp // bytes are well-incorporated.
55 b343c297 2021-10-11 stsp
56 b343c297 2021-10-11 stsp h ^= h >> 13;
57 b343c297 2021-10-11 stsp h *= m;
58 b343c297 2021-10-11 stsp h ^= h >> 15;
59 b343c297 2021-10-11 stsp
60 b343c297 2021-10-11 stsp return h;
61 b343c297 2021-10-11 stsp }