-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_pipelines.go
102 lines (86 loc) · 1.85 KB
/
util_pipelines.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
package pipelines
import (
"context"
"sync"
)
func OrDone[R any](ctx context.Context, inStream <-chan R) <-chan R {
outStream := make(chan R)
if inStream == nil {
close(outStream)
panic("OrDone: the provided inStream argument has nil value")
}
go func() {
defer close(outStream)
for {
select {
case <-ctx.Done():
return
case res, ok := <-inStream:
if !ok {
return
}
select {
case outStream <- res:
case <-ctx.Done():
return
}
}
}
}()
return outStream
}
// TeeSplitter should take a single stream and return 2 identical copies of it
func TeeSplitter[R any](ctx context.Context, inStream <-chan R) (_, _ <-chan R) {
outStream1 := make(chan R)
outStream2 := make(chan R)
if inStream == nil {
close(outStream1)
close(outStream2)
panic("TeeSplitter: the provided inStream argument has nil value")
}
go func() {
defer close(outStream1)
defer close(outStream2)
for item := range OrDone(ctx, inStream) {
var outStream1, outStream2 = outStream1, outStream2
for i := 0; i < 2; i++ {
select {
case <-ctx.Done():
return
case outStream1 <- item:
outStream1 = nil
case outStream2 <- item:
outStream2 = nil
}
}
}
}()
return outStream1, outStream2
}
// Combine takes a context and any amount of channels of a type and combines them into one single channel of that same type.
func Combine[T any](ctx context.Context, channels ...<-chan T) <-chan T {
outStream := make(chan T)
wg := sync.WaitGroup{}
worker := func(inStream <-chan T) {
defer wg.Done()
if inStream == nil {
return
}
for val := range OrDone(ctx, inStream) {
select {
case <-ctx.Done():
return
case outStream <- val:
}
}
}
wg.Add(len(channels))
for _, c := range channels {
go worker(c)
}
go func() {
wg.Wait()
defer close(outStream)
}()
return outStream
}