src/util/hash.c (view raw)
1// MurmurHash3 was written by Austin Appleby, and is placed in the public
2// domain. The author hereby disclaims copyright to this source code.
3
4#include <mgba-util/hash.h>
5
6#if defined(_MSC_VER)
7
8#define FORCE_INLINE __forceinline
9
10#include <stdlib.h>
11
12#define ROTL32(x,y) _rotl(x,y)
13
14#else
15
16#define FORCE_INLINE inline __attribute__((always_inline))
17
18static inline uint32_t rotl32 ( uint32_t x, int8_t r ) {
19 return (x << r) | (x >> (32 - r));
20}
21
22#define ROTL32(x,y) rotl32(x,y)
23
24#endif
25
26//-----------------------------------------------------------------------------
27// Block read - if your platform needs to do endian-swapping or can only
28// handle aligned reads, do the conversion here
29
30static FORCE_INLINE uint32_t getblock32 ( const uint32_t * p, int i ) {
31 return p[i];
32}
33
34//-----------------------------------------------------------------------------
35// Finalization mix - force all bits of a hash block to avalanche
36
37static FORCE_INLINE uint32_t fmix32 (uint32_t h) {
38 h ^= h >> 16;
39 h *= 0x85ebca6b;
40 h ^= h >> 13;
41 h *= 0xc2b2ae35;
42 h ^= h >> 16;
43
44 return h;
45}
46
47//-----------------------------------------------------------------------------
48
49uint32_t hash32(const void* key, int len, uint32_t seed) {
50 const uint8_t * data = (const uint8_t*)key;
51 const int nblocks = len / 4;
52
53 uint32_t h1 = seed;
54
55 const uint32_t c1 = 0xcc9e2d51;
56 const uint32_t c2 = 0x1b873593;
57
58 //----------
59 // body
60
61 const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
62
63 int i;
64 for(i = -nblocks; i; i++)
65 {
66 uint32_t k1 = getblock32(blocks,i);
67
68 k1 *= c1;
69 k1 = ROTL32(k1,15);
70 k1 *= c2;
71
72 h1 ^= k1;
73 h1 = ROTL32(h1,13);
74 h1 = h1*5+0xe6546b64;
75 }
76
77 //----------
78 // tail
79
80 const uint8_t * tail = (const uint8_t*)(data + nblocks*4);
81
82 uint32_t k1 = 0;
83
84 switch(len & 3)
85 {
86 case 3:
87 k1 ^= tail[2] << 16;
88 // Fall through
89 case 2:
90 k1 ^= tail[1] << 8;
91 // Fall through
92 case 1:
93 k1 ^= tail[0];
94 k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
95 };
96
97 //----------
98 // finalization
99
100 h1 ^= len;
101
102 h1 = fmix32(h1);
103
104 return h1;
105}