| 1 |
/* SPDX-License-Identifier: LicenseRef-murmurhash2-public-domain */ |
| 2 |
//----------------------------------------------------------------------------- |
| 3 |
// MurmurHash2 was written by Austin Appleby, and is placed in the public |
| 4 |
// domain. The author hereby disclaims copyright to this source code. |
| 5 |
|
| 6 |
// Note - This code makes a few assumptions about how your machine behaves - |
| 7 |
|
| 8 |
// 1. We can read a 4-byte value from any address without crashing |
| 9 |
// 2. sizeof(int) == 4 |
| 10 |
|
| 11 |
// And it has a few limitations - |
| 12 |
|
| 13 |
// 1. It will not work incrementally. |
| 14 |
// 2. It will not produce the same results on little-endian and big-endian |
| 15 |
// machines. |
| 16 |
|
| 17 |
#include "MurmurHash2.h" |
| 18 |
|
| 19 |
_Pragma("GCC diagnostic ignored \"-Wimplicit-fallthrough\"") |
| 20 |
|
| 21 |
//----------------------------------------------------------------------------- |
| 22 |
// Platform-specific functions and macros |
| 23 |
|
| 24 |
// Microsoft Visual Studio |
| 25 |
|
| 26 |
#if defined(_MSC_VER) |
| 27 |
|
| 28 |
#define BIG_CONSTANT(x) (x) |
| 29 |
|
| 30 |
// Other compilers |
| 31 |
|
| 32 |
#else // defined(_MSC_VER) |
| 33 |
|
| 34 |
#define BIG_CONSTANT(x) (x##LLU) |
| 35 |
|
| 36 |
#endif // !defined(_MSC_VER) |
| 37 |
|
| 38 |
//----------------------------------------------------------------------------- |
| 39 |
|
| 40 |
uint32_t MurmurHash2 ( const void * key, int len, uint32_t seed ) |
| 41 |
{ |
| 42 |
// 'm' and 'r' are mixing constants generated offline. |
| 43 |
// They're not really 'magic', they just happen to work well. |
| 44 |
|
| 45 |
const uint32_t m = 0x5bd1e995; |
| 46 |
const int r = 24; |
| 47 |
|
| 48 |
// Initialize the hash to a 'random' value |
| 49 |
|
| 50 |
uint32_t h = seed ^ len; |
| 51 |
|
| 52 |
// Mix 4 bytes at a time into the hash |
| 53 |
|
| 54 |
const unsigned char * data = (const unsigned char *)key; |
| 55 |
|
| 56 |
while (len >= 4) |
| 57 |
{ |
| 58 |
uint32_t k = *(uint32_t*)data; |
| 59 |
|
| 60 |
k *= m; |
| 61 |
k ^= k >> r; |
| 62 |
k *= m; |
| 63 |
|
| 64 |
h *= m; |
| 65 |
h ^= k; |
| 66 |
|
| 67 |
data += 4; |
| 68 |
len -= 4; |
| 69 |
} |
| 70 |
|
| 71 |
// Handle the last few bytes of the input array |
| 72 |
|
| 73 |
switch(len) |
| 74 |
{ |
| 75 |
case 3: h ^= data[2] << 16; /* fall through */ |
| 76 |
case 2: h ^= data[1] << 8; /* fall through */ |
| 77 |
case 1: h ^= data[0]; /* fall through */ |
| 78 |
h *= m; |
| 79 |
}; |
| 80 |
|
| 81 |
// Do a few final mixes of the hash to ensure the last few |
| 82 |
// bytes are well-incorporated. |
| 83 |
|
| 84 |
h ^= h >> 13; |
| 85 |
h *= m; |
| 86 |
h ^= h >> 15; |
| 87 |
|
| 88 |
return h; |
| 89 |
} |