-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
51 lines (45 loc) · 919 Bytes
/
merge.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
package iterator
import (
"context"
"sync"
)
// Merge takes multiple iterators and consumes them concurrently into a single iterator
func Merge[T any](iters ...Iterator[T]) Iterator[T] {
c := make(chan ValErr[T], len(iters))
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(len(iters))
for i := range iters {
go func(i int) {
defer func() {
wg.Done()
}()
var stopped bool
_, err := Iterate(iters[i], func(index int, item T) (bool, error) {
select {
case <-ctx.Done():
stopped = true
return false, nil
case c <- ValErr[T]{Val: item, Err: nil}:
}
return true, nil
})
if stopped {
return
}
if err != nil {
select {
case <-ctx.Done():
case c <- ValErr[T]{Val: *new(T), Err: err}:
cancel()
}
}
}(i)
}
go func() {
wg.Wait()
cancel()
close(c)
}()
return FromValErrChannel(c)
}