-
Notifications
You must be signed in to change notification settings - Fork 1
/
balancer.go
71 lines (59 loc) · 1.32 KB
/
balancer.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
package balancer
import (
"github.com/RealFax/RedQueen/pkg/maputil"
"slices"
"sync"
)
type Node[K comparable, V any] interface {
Key() K
Value() V
}
type LoadBalance[K comparable, V any] interface {
Size() int32
Append(node ...Node[K, V])
Remove(key K) bool
Next() (V, error)
}
type loadBalanceStore[K comparable, V any] struct {
rwm sync.RWMutex
size int32
filter *maputil.Map[K, struct{}]
nodes []Node[K, V]
}
func (s *loadBalanceStore[K, V]) Size() int32 {
s.rwm.RLock()
size := s.size
s.rwm.RUnlock()
return size
}
func (s *loadBalanceStore[K, V]) Append(nodes ...Node[K, V]) {
for i, node := range nodes {
if _, ok := s.filter.Load(node.Key()); ok {
nodes = append(nodes[:i], nodes[i+1:]...)
continue
}
s.filter.Store(node.Key(), struct{}{})
}
s.rwm.Lock()
s.nodes = append(s.nodes, nodes...)
s.size += int32(len(nodes))
s.rwm.Unlock()
}
func (s *loadBalanceStore[K, V]) Remove(key K) bool {
if _, ok := s.filter.LoadAndDelete(key); !ok {
return false
}
s.rwm.Lock()
s.nodes = slices.DeleteFunc(s.nodes, func(n Node[K, V]) bool {
return n.Key() == key
})
s.size -= 1
s.rwm.Unlock()
return true
}
func newLoadBalanceStore[K comparable, V any]() *loadBalanceStore[K, V] {
return &loadBalanceStore[K, V]{
filter: maputil.New[K, struct{}](),
nodes: make([]Node[K, V], 0, 64),
}
}