-
Notifications
You must be signed in to change notification settings - Fork 0
/
jump.go
51 lines (43 loc) · 971 Bytes
/
jump.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
package jump
import (
"hash"
"hash/maphash"
"io"
"sync"
)
var hashPool = sync.Pool{
New: func() interface{} {
var h = &maphash.Hash{}
h.SetSeed(maphash.MakeSeed())
return h
},
}
// Hash consistently chooses a hash bucket number in the range [0, numBuckets) for the given key.
// numBuckets must be >= 1.
func Hash(key uint64, numBuckets int) int32 {
var b int64 = -1
var j int64
for j < int64(numBuckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int32(b)
}
// HashString works like hash but accept string as an input.
func HashString(key string, numBuckets int) int32 {
// jump.Hash returns values from 0.
k := Hash(Sum64(key), numBuckets)
return k
}
// Sum64 ...
func Sum64(key string) uint64 {
h := hashPool.Get().(hash.Hash64)
if _, err := io.WriteString(h, key); err != nil {
panic(err)
}
r := h.Sum64()
h.Reset()
hashPool.Put(h)
return r
}