-
Notifications
You must be signed in to change notification settings - Fork 1
/
roundrobin.go
107 lines (78 loc) · 1.94 KB
/
roundrobin.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
package ranges
type roundRobinResult[T any] struct {
ranges []InputRange[T]
index int
}
func (rr *roundRobinResult[T]) prime() {
start := rr.index
for rr.ranges[rr.index].Empty() {
rr.index++
if rr.index >= len(rr.ranges) {
rr.index = 0
}
if rr.index == start {
panic("RoundRobin was empty")
}
}
}
func (rr *roundRobinResult[T]) Empty() bool {
return AllS(rr.ranges, InputRange[T].Empty)
}
func (rr *roundRobinResult[T]) Front() T {
rr.prime()
return rr.ranges[rr.index].Front()
}
func (rr *roundRobinResult[T]) PopFront() {
rr.prime()
rr.ranges[rr.index].PopFront()
rr.index++
if rr.index >= len(rr.ranges) {
rr.index = 0
}
}
type roundRobinForwardResult[T any] struct {
ranges []ForwardRange[T]
index int
}
func (rr *roundRobinForwardResult[T]) prime() {
start := rr.index
for rr.ranges[rr.index].Empty() {
rr.index++
if rr.index >= len(rr.ranges) {
rr.index = 0
}
if rr.index == start {
panic("RoundRobin was empty")
}
}
}
func (rr *roundRobinForwardResult[T]) Empty() bool {
return AllS(rr.ranges, ForwardRange[T].Empty)
}
func (rr *roundRobinForwardResult[T]) Front() T {
rr.prime()
return rr.ranges[rr.index].Front()
}
func (rr *roundRobinForwardResult[T]) PopFront() {
rr.prime()
rr.ranges[rr.index].PopFront()
rr.index++
if rr.index >= len(rr.ranges) {
rr.index = 0
}
}
func (rr *roundRobinForwardResult[T]) Save() ForwardRange[T] {
ranges := make([]ForwardRange[T], len(rr.ranges))
for i := range rr.ranges {
ranges[i] = rr.ranges[i].Save()
}
return &roundRobinForwardResult[T]{ranges, rr.index}
}
// RoundRobin yields the first elements of the ranges and cycles back around until all are consumed.
func RoundRobin[T any](ranges ...InputRange[T]) InputRange[T] {
return &roundRobinResult[T]{ranges, 0}
}
// RoundRobinF is `RoundRobin` producing a ForwardRange
func RoundRobinF[T any](ranges ...ForwardRange[T]) ForwardRange[T] {
return &roundRobinForwardResult[T]{ranges, 0}
}