-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmirror.go
92 lines (75 loc) · 1.56 KB
/
mirror.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
package iterator
import (
"github.com/wlMalk/iterator/internal/buffer"
)
// Mirror creates multiple synchronised iterators with the same underlying iterator
func Mirror[T any](iter Iterator[T], count int) []Iterator[T] {
nextChan := make(chan *buffer.Iterator[T])
closeChan := make(chan *buffer.Iterator[T])
buffers := make([]*buffer.Buffer[T], count)
mirrors := make([]Iterator[T], count)
for i := range buffers {
buffers[i] = buffer.New[T]()
mirrors[i] = buffer.NewIterator(buffers[i], nextChan, closeChan)
}
go func() {
var finished bool
var err error
var closedCount int
for {
select {
case curr := <-nextChan:
item, ok := curr.Buffer.Pop()
if ok {
curr.SendItem(item)
continue
}
if finished {
curr.End()
continue
}
if err != nil {
curr.SendErr(err)
continue
}
hasMore := iter.Next()
if !hasMore {
if err = iter.Err(); err != nil {
curr.SendErr(err)
continue
}
finished = true
curr.End()
continue
}
item, err := iter.Get()
if err != nil {
curr.SendErr(err)
continue
}
for _, b := range buffers {
if b == curr.Buffer || b.IsClosed() {
continue
}
b.Push(item)
}
curr.SendItem(item)
case curr := <-closeChan:
closedCount++
if curr.Buffer.IsEmpty() {
err = iter.Close()
finished = true
curr.SendErr(err)
} else {
curr.SendErr(nil)
}
if closedCount == count {
close(nextChan)
close(closeChan)
return
}
}
}
}()
return mirrors
}