rework murmurhash2() to avoid potential unaligned memory access
[got-portable.git] / lib / murmurhash2.c
blobd3a67547fa3ddbd12660f688766bd387d6ed905b
1 //-----------------------------------------------------------------------------
2 // MurmurHash2 was written by Austin Appleby, and is placed in the public
3 // domain. The author hereby disclaims copyright to this source code.
5 /* Obtained from https://github.com/aappleby/smhasher */
7 #include <stdint.h>
8 #include <string.h>
10 #include "murmurhash2.h"
12 uint32_t
13 murmurhash2(const unsigned char * key, int len, uint32_t seed)
15 // 'm' and 'r' are mixing constants generated offline.
16 // They're not really 'magic', they just happen to work well.
18 const uint32_t m = 0x5bd1e995;
19 const int r = 24;
21 // Initialize the hash to a 'random' value
23 uint32_t h = seed ^ len;
25 // Mix 4 bytes at a time into the hash
27 const unsigned char *data = key;
29 while(len >= 4)
31 uint32_t k;
33 memcpy(&k, data, sizeof(k));
35 k *= m;
36 k ^= k >> r;
37 k *= m;
39 h *= m;
40 h ^= k;
42 data += 4;
43 len -= 4;
46 // Handle the last few bytes of the input array
48 switch(len)
50 case 3: h ^= data[2] << 16;
51 case 2: h ^= data[1] << 8;
52 case 1: h ^= data[0];
53 h *= m;
56 // Do a few final mixes of the hash to ensure the last few
57 // bytes are well-incorporated.
59 h ^= h >> 13;
60 h *= m;
61 h ^= h >> 15;
63 return h;