xref: /unit/src/nxt_murmur_hash.c (revision 611:323e11065f83)
1 
2 /*
3  * The code is based on the code by Austin Appleby,
4  * released to the public domain.
5  */
6 
7 #include <nxt_main.h>
8 
9 
10 uint32_t
nxt_murmur_hash2(const void * data,size_t len)11 nxt_murmur_hash2(const void *data, size_t len)
12 {
13     uint32_t        h, k;
14     const u_char    *p;
15     const uint32_t  m = 0x5BD1E995;
16 
17     p = data;
18     h = 0 ^ (uint32_t) len;
19 
20     while (len >= 4) {
21         k  = p[0];
22         k |= p[1] << 8;
23         k |= p[2] << 16;
24         k |= p[3] << 24;
25 
26         k *= m;
27         k ^= k >> 24;
28         k *= m;
29 
30         h *= m;
31         h ^= k;
32 
33         p += 4;
34         len -= 4;
35     }
36 
37     switch (len) {
38     case 3:
39         h ^= p[2] << 16;
40         /* Fall through. */
41     case 2:
42         h ^= p[1] << 8;
43         /* Fall through. */
44     case 1:
45         h ^= p[0];
46         h *= m;
47     }
48 
49     h ^= h >> 13;
50     h *= m;
51     h ^= h >> 15;
52 
53     return h;
54 }
55 
56 
57 /* The MurmurHash2 for fixed 4 byte length. */
58 
59 uint32_t
nxt_murmur_hash2_uint32(const void * data)60 nxt_murmur_hash2_uint32(const void *data)
61 {
62     uint32_t        h, k;
63     const u_char    *p;
64     const uint32_t  m = 0x5BD1E995;
65 
66     p = data;
67 
68     k  = p[0];
69     k |= p[1] << 8;
70     k |= p[2] << 16;
71     k |= p[3] << 24;
72 
73     k *= m;
74     k ^= k >> 24;
75     k *= m;
76 
77     h = 0 ^ 4;
78     h *= m;
79     h ^= k;
80 
81     h ^= h >> 13;
82     h *= m;
83     h ^= h >> 15;
84 
85     return h;
86 }
87