-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtap.go
56 lines (41 loc) · 1.1 KB
/
tap.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
package pipes
func Tap[T any](size int, tap func(T), in <-chan T) ChanPull[T] {
out := make(chan T, size)
go tapWorker(tap, in, out)
return out
}
func tapWorker[T any](tap func(T), in <-chan T, out chan<- T) {
defer close(out)
for t := range in {
tap(t)
out <- t
}
}
func TapWithError[T any](size int, tap func(T) error, in <-chan T) (ChanPull[T], ChanPull[error]) {
out, err := make(chan T, size), make(chan error, size)
go tapWithErrorWorker(tap, in, out, err)
return out, err
}
func tapWithErrorWorker[T any](tap func(T) error, in <-chan T, out chan<- T, err chan<- error) {
defer func() { close(out); close(err) }()
for t := range in {
if er := tap(t); er != nil {
err <- er
}
out <- t
}
}
func TapWithErrorSink[T any](size int, tap func(T) error, sink func(error), in <-chan T) ChanPull[T] {
out := make(chan T, size)
go tapWithErrorSinkWorker(tap, sink, in, out)
return out
}
func tapWithErrorSinkWorker[T any](mp func(T) error, sink func(error), in <-chan T, out chan<- T) {
defer close(out)
for t := range in {
if er := mp(t); er != nil {
sink(er)
}
out <- t
}
}