-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtee.go
More file actions
38 lines (33 loc) · 687 Bytes
/
tee.go
File metadata and controls
38 lines (33 loc) · 687 Bytes
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
package tee
// NewTee takes an input channel and returns n output channels that each receive all items from the input channel.
//
// A buffer size can be specified for the output channels; if buf is 0 or negative, unbuffered channels are created.
func NewTee[I any](in <-chan I, n int, buf int) []chan I {
if n <= 0 {
n = 1
}
if buf <= 0 {
buf = 0
}
outs := make([]chan I, n)
for i := range n {
if buf <= 0 {
outs[i] = make(chan I)
} else {
outs[i] = make(chan I, buf)
}
}
go func() {
defer func() {
for _, out := range outs {
close(out)
}
}()
for item := range in {
for _, out := range outs {
out <- item
}
}
}()
return outs
}