-
Notifications
You must be signed in to change notification settings - Fork 9
/
murmurhash1.go
138 lines (116 loc) · 2.09 KB
/
murmurhash1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package murmurhash
func MurmurHash1 (key []byte, seed uint32) (hash uint32) {
const m = 0xc6a4a793
const r = 16
l := len(key)
h := seed ^ uint32(l * m)
data := key
for l >= 4 {
k := uint32(data[0]) + uint32(data[1]) << 8 + uint32(data[2]) << 16 + uint32(data[3]) << 24
h += k
h *= m
h ^= h >> 16
data = data[4:]
l -= 4
}
switch l {
case 3:
h += uint32(data[2]) << 16
fallthrough
case 2:
h += uint32(data[1]) << 8
fallthrough
case 1:
h += uint32(data[0])
h *= m
h ^= h >> r
}
h *= m
h ^= h >> 10
h *= m
h ^= h >> 17
return h
}
func MurmurHash1Aligned(key []byte, seed uint32) (hash uint32) {
const m uint32 = 0xc6a4a793
const r = 16
l := len(key)
data := key
var h uint32 = seed ^ (uint32(l) * m)
var align int = int(uint64(data[0])) & 3
if align != 0 && l >= 4 {
var t, d uint32 = 0, 0
switch align {
case 1:
t |= uint32(data[2]) << 16
fallthrough
case 2:
t |= uint32(data[1]) << 8
fallthrough
case 3:
t |= uint32(data[0])
}
t <<= 8 * uint32(align)
data = data[4 - align:]
l -= 4 - align
var sl int = 8 * (4 - align)
var sr int = 8 * align
for l >= 4 {
d = uint32(data[0]) + uint32(data[1]) << 8 +
uint32(data[2]) << 16 + uint32(data[3]) << 24
t = (t >> uint32(sr)) | (d << uint32(sl))
h += t
h *= m
h ^= h >> r
t = d
data = data[4:]
l -= 4
}
var pack int
if l < align {
pack = l
} else {
pack = align
}
d = 0
switch pack {
case 3:
d |= uint32(data[2]) << 16
fallthrough
case 2:
d |= uint32(data[1]) << 8
fallthrough
case 1:
d |= uint32(data[0])
fallthrough
case 0:
h += (t >> uint32(sr)) | (d << uint32(sl))
h *= m
h ^= h >> r
}
data = data[pack:]
l -= pack
} else {
for l >= 4 {
h += uint32(data[0]) + uint32(data[1]) << 8 +
uint32(data[2]) << 16 + uint32(data[3]) << 24
}
}
switch l {
case 3:
h += uint32(data[2]) << 16
fallthrough
case 2:
h += uint32(data[1]) << 8
fallthrough
case 1:
h += uint32(data[0])
h *= m
h ^= h >> r
}
h *= m
h ^= h >> 10
h *= m
h ^= h >> 17
return h
}