-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
65 lines (55 loc) · 1.13 KB
/
node.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
package hashring
import (
"strconv"
"github.com/lockp111/consistent-hashring/hashring"
)
type Node[T any] struct {
Data T
key string
weight int
}
func NewNode[T any](key string, data T) *Node[T] {
return &Node[T]{
Data: data,
key: key,
weight: 1,
}
}
func (n *Node[T]) virtualKey(index int) string {
return n.key + "#" + strconv.FormatInt(int64(index), 10)
}
// Virtuals returns virtual nodes
func (n *Node[T]) Virtuals(replicas int) []hashring.Slot[T] {
var (
total = n.weight * replicas
slots = make([]hashring.Slot[T], 0, total)
)
for i := 0; i < total; i++ {
key := n.virtualKey(i)
slots = append(slots, hashring.NewSlot(key, n.Data))
}
return slots
}
// VirtualKeys returns virtual keys
func (n *Node[T]) VirtualKeys(replicas int) []string {
var (
total = n.weight * replicas
keys = make([]string, 0, total)
)
for i := 0; i < total; i++ {
keys = append(keys, n.virtualKey(i))
}
return keys
}
// SetWeight
func (n *Node[T]) SetWeight(w int) {
n.weight = w
}
// GetWeight
func (n *Node[T]) GetWeight() int {
return n.weight
}
// GetKey
func (n *Node[T]) GetKey() string {
return n.key
}