-
Notifications
You must be signed in to change notification settings - Fork 2
/
murmur32.go
125 lines (101 loc) · 2.41 KB
/
murmur32.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
package murmur3
import (
"math/bits"
"reflect"
"unsafe"
)
func New32() *MurmurHash32 {
return New32WithSeed(0)
}
func New32WithSeed(seed int) *MurmurHash32 {
h := &MurmurHash32{}
h.seed = seed
return h
}
type MurmurHash32 struct {
MurmurHash
}
func (h *MurmurHash32) HashInt(i int) *Int32HashCode {
if bits.UintSize == 32 {
return h.HashInt32(int32(i))
}
return h.HashInt64(int64(i))
}
func (h *MurmurHash32) HashInt32(i int32) *Int32HashCode {
k1 := h.mixK1(uint32(i))
h1 := h.mixH1(uint32(h.seed), k1)
h1 = h.fmix(h1, 4)
return h.makeHash(h1)
}
func (h *MurmurHash32) HashInt64(i int64) *Int32HashCode {
low := uint32(i)
high := uint32(i >> 32)
k1 := h.mixK1(low)
h1 := h.mixH1(uint32(h.seed), k1)
k1 = h.mixK1(high)
h1 = h.mixH1(h1, k1)
h1 = h.fmix(h1, 8)
return h.makeHash(h1)
}
func (h *MurmurHash32) HashString(s string) *Int32HashCode {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
return h.HashBytes(*(*[]byte)(unsafe.Pointer(&bh)))
}
func (h *MurmurHash32) HashBytes(bytes []byte) *Int32HashCode {
return h.make(bytes)
}
func (h *MurmurHash32) HashBytesWithOffset(bytes []byte, offset, length int) *Int32HashCode {
return h.make(bytes[offset : offset+length])
}
func (h *MurmurHash32) make(bytes []byte) *Int32HashCode {
length := uint32(len(bytes))
h1, buffer := h.bmix(uint32(h.seed), bytes)
var k1 uint32
switch len(buffer) & 3 {
case 3:
k1 ^= uint32(buffer[2]) << 16
fallthrough
case 2:
k1 ^= uint32(buffer[1]) << 8
fallthrough
case 1:
k1 ^= uint32(buffer[0])
}
h1 ^= h.mixK1(k1)
h1 = h.fmix(h1, length)
return h.makeHash(h1)
}
func (h *MurmurHash32) mixK1(k1 uint32) uint32 {
k1 *= 0xcc9e2d51
k1 = bits.RotateLeft32(k1, 15)
k1 *= 0x1b873593
return k1
}
func (h *MurmurHash32) mixH1(h1, k1 uint32) uint32 {
h1 ^= k1
h1 = bits.RotateLeft32(h1, 13)
h1 = h1*5 + 0xe6546b64
return h1
}
func (h *MurmurHash32) bmix(h1 uint32, bytes []byte) (uint32, []byte) {
blocks := len(bytes) / 4
for i := 0; i < blocks; i++ {
k1 := *(*uint32)(unsafe.Pointer(&bytes[i*4]))
k1 = h.mixK1(k1)
h1 = h.mixH1(h1, k1)
}
return h1, bytes[blocks*4:]
}
func (h *MurmurHash32) fmix(h1, length uint32) uint32 {
h1 ^= length
h1 ^= h1 >> 16
h1 *= 0x85ebca6b
h1 ^= h1 >> 13
h1 *= 0xc2b2ae35
h1 ^= h1 >> 16
return h1
}
func (h *MurmurHash32) makeHash(h1 uint32) *Int32HashCode {
return &Int32HashCode{int32(h1)}
}