-
Notifications
You must be signed in to change notification settings - Fork 10
/
hasher.go
38 lines (29 loc) · 646 Bytes
/
hasher.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
package mc
//
import (
"hash"
"hash/fnv"
)
type hasher interface {
update(servers []*server)
getServerIndex(key string) (uint, error)
}
type moduloHasher struct {
nServers uint
h32 hash.Hash32
}
func NewModuloHasher() hasher {
var h hasher = &moduloHasher{h32: fnv.New32a()}
return h
}
func (h *moduloHasher) update(servers []*server) {
h.nServers = uint(len(servers))
}
func (h *moduloHasher) getServerIndex(key string) (uint, error) {
if h.nServers < 1 {
return 0, &Error{StatusNetworkError, "No server available", nil}
}
h.h32.Write([]byte(key))
defer h.h32.Reset()
return uint(h.h32.Sum32()) % h.nServers, nil
}