Incoming update to Murmur
[awesomized/libmemcached] / libmemcached / murmur_hash.c
1 /*
2 "Murmur" hash provided by Austin, tanjent@gmail.com
3 http://murmurhash.googlepages.com/
4
5 Note - This code makes a few assumptions about how your machine behaves -
6
7 1. We can read a 4-byte value from any address without crashing
8 2. sizeof(int) == 4
9
10 And it has a few limitations -
11 1. It will not work incrementally.
12 2. It will not produce the same results on little-endian and big-endian
13 machines.
14
15 Updated to murmur2 hash - BP
16 */
17
18 #include "common.h"
19
20 uint32_t murmur_hash(const char *key, size_t length)
21 {
22 /*
23 'm' and 'r' are mixing constants generated offline. They're not
24 really 'magic', they just happen to work well.
25 */
26
27 const unsigned int m= 0x5bd1e995;
28 const unsigned int seed= (0xdeadbeef * length);
29 const int r= 24;
30
31
32 // Initialize the hash to a 'random' value
33
34 unsigned int h= seed ^ length;
35
36 // Mix 4 bytes at a time into the hash
37
38 const unsigned char * data= (const unsigned char *)key;
39
40 while(length >= 4)
41 {
42 unsigned int k = *(unsigned int *)data;
43
44 k *= m;
45 k ^= k >> r;
46 k *= m;
47
48 h *= m;
49 h ^= k;
50
51 data += 4;
52 length -= 4;
53 }
54
55 // Handle the last few bytes of the input array
56
57 switch(length)
58 {
59 case 3: h ^= data[2] << 16;
60 case 2: h ^= data[1] << 8;
61 case 1: h ^= data[0];
62 h *= m;
63 };
64
65 /*
66 Do a few final mixes of the hash to ensure the last few bytes are
67 well-incorporated.
68 */
69
70 h ^= h >> 13;
71 h *= m;
72 h ^= h >> 15;
73
74 return h;
75 }