xref: /unit/src/nxt_murmur_hash.c (revision 0:a63ceefd6ab0)
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
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     case 2:
41         h ^= p[1] << 8;
42     case 1:
43         h ^= p[0];
44         h *= m;
45     }
46 
47     h ^= h >> 13;
48     h *= m;
49     h ^= h >> 15;
50 
51     return h;
52 }
53 
54 
55 /* The MurmurHash2 for fixed 4 byte length. */
56 
57 uint32_t
58 nxt_murmur_hash2_uint32(const void *data)
59 {
60     uint32_t        h, k;
61     const u_char    *p;
62     const uint32_t  m = 0x5bd1e995;
63 
64     p = data;
65 
66     k  = p[0];
67     k |= p[1] << 8;
68     k |= p[2] << 16;
69     k |= p[3] << 24;
70 
71     k *= m;
72     k ^= k >> 24;
73     k *= m;
74 
75     h = 0 ^ 4;
76     h *= m;
77     h ^= k;
78 
79     h ^= h >> 13;
80     h *= m;
81     h ^= h >> 15;
82 
83     return h;
84 }
85