all repos — mgba @ 6f591996a8307bde8d424ab37a0db67956097187

mGBA Game Boy Advance Emulator

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 "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  for(int i = -nblocks; i; i++)
64  {
65    uint32_t k1 = getblock32(blocks,i);
66
67    k1 *= c1;
68    k1 = ROTL32(k1,15);
69    k1 *= c2;
70    
71    h1 ^= k1;
72    h1 = ROTL32(h1,13); 
73    h1 = h1*5+0xe6546b64;
74  }
75
76  //----------
77  // tail
78
79  const uint8_t * tail = (const uint8_t*)(data + nblocks*4);
80
81  uint32_t k1 = 0;
82
83  switch(len & 3)
84  {
85  case 3: k1 ^= tail[2] << 16;
86  case 2: k1 ^= tail[1] << 8;
87  case 1: k1 ^= tail[0];
88          k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
89  };
90
91  //----------
92  // finalization
93
94  h1 ^= len;
95
96  h1 = fmix32(h1);
97
98  return h1;
99}