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 5df018ff 2021-10-14 stsp #include <string.h>
9 b343c297 2021-10-11 stsp
10 b343c297 2021-10-11 stsp #include "murmurhash2.h"
11 b343c297 2021-10-11 stsp
12 b343c297 2021-10-11 stsp uint32_t
13 5df018ff 2021-10-14 stsp murmurhash2(const unsigned char * key, int len, uint32_t seed)
14 b343c297 2021-10-11 stsp {
15 b343c297 2021-10-11 stsp // 'm' and 'r' are mixing constants generated offline.
16 b343c297 2021-10-11 stsp // They're not really 'magic', they just happen to work well.
17 b343c297 2021-10-11 stsp
18 b343c297 2021-10-11 stsp const uint32_t m = 0x5bd1e995;
19 b343c297 2021-10-11 stsp const int r = 24;
20 b343c297 2021-10-11 stsp
21 b343c297 2021-10-11 stsp // Initialize the hash to a 'random' value
22 b343c297 2021-10-11 stsp
23 b343c297 2021-10-11 stsp uint32_t h = seed ^ len;
24 b343c297 2021-10-11 stsp
25 b343c297 2021-10-11 stsp // Mix 4 bytes at a time into the hash
26 b343c297 2021-10-11 stsp
27 5df018ff 2021-10-14 stsp const unsigned char *data = key;
28 b343c297 2021-10-11 stsp
29 b343c297 2021-10-11 stsp while(len >= 4)
30 b343c297 2021-10-11 stsp {
31 5df018ff 2021-10-14 stsp uint32_t k;
32 b343c297 2021-10-11 stsp
33 5df018ff 2021-10-14 stsp memcpy(&k, data, sizeof(k));
34 5df018ff 2021-10-14 stsp
35 b343c297 2021-10-11 stsp k *= m;
36 b343c297 2021-10-11 stsp k ^= k >> r;
37 b343c297 2021-10-11 stsp k *= m;
38 b343c297 2021-10-11 stsp
39 b343c297 2021-10-11 stsp h *= m;
40 b343c297 2021-10-11 stsp h ^= k;
41 b343c297 2021-10-11 stsp
42 b343c297 2021-10-11 stsp data += 4;
43 b343c297 2021-10-11 stsp len -= 4;
44 b343c297 2021-10-11 stsp }
45 b343c297 2021-10-11 stsp
46 b343c297 2021-10-11 stsp // Handle the last few bytes of the input array
47 b343c297 2021-10-11 stsp
48 b343c297 2021-10-11 stsp switch(len)
49 b343c297 2021-10-11 stsp {
50 b343c297 2021-10-11 stsp case 3: h ^= data[2] << 16;
51 b343c297 2021-10-11 stsp case 2: h ^= data[1] << 8;
52 b343c297 2021-10-11 stsp case 1: h ^= data[0];
53 b343c297 2021-10-11 stsp h *= m;
54 b343c297 2021-10-11 stsp };
55 b343c297 2021-10-11 stsp
56 b343c297 2021-10-11 stsp // Do a few final mixes of the hash to ensure the last few
57 b343c297 2021-10-11 stsp // bytes are well-incorporated.
58 b343c297 2021-10-11 stsp
59 b343c297 2021-10-11 stsp h ^= h >> 13;
60 b343c297 2021-10-11 stsp h *= m;
61 b343c297 2021-10-11 stsp h ^= h >> 15;
62 b343c297 2021-10-11 stsp
63 b343c297 2021-10-11 stsp return h;
64 5df018ff 2021-10-14 stsp }