-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.go
59 lines (44 loc) · 1.27 KB
/
filter.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
package pipes
func Filter[T any](size int, filter func(T) bool, in <-chan T) ChanPull[T] {
out := make(chan T, size)
go filterWorker(filter, in, out)
return out
}
func filterWorker[T any](filter func(T) bool, in <-chan T, out ChanPush[T]) {
defer close(out)
for t := range in {
if filter(t) {
out <- t
}
}
}
func FilterWithError[T any](size int, filter func(T) (bool, error), in <-chan T) (ChanPull[T], ChanPull[error]) {
out, err := make(chan T, size), make(chan error, size)
go filterWithErrorWorker(filter, in, out, err)
return out, err
}
func filterWithErrorWorker[T any](filter func(T) (bool, error), in <-chan T, out chan<- T, err chan<- error) {
defer func() { close(out); close(err) }()
for t := range in {
if keep, er := filter(t); er != nil {
err <- er
} else if keep {
out <- t
}
}
}
func FilterWithErrorSink[T any](size int, filter func(T) (bool, error), sink func(error), in <-chan T) ChanPull[T] {
out := make(chan T, size)
go filterWithErrorSinkWorker(filter, sink, in, out)
return out
}
func filterWithErrorSinkWorker[T any](filter func(T) (bool, error), sink func(error), in <-chan T, out chan<- T) {
defer close(out)
for t := range in {
if keep, er := filter(t); er != nil {
sink(er)
} else if keep {
out <- t
}
}
}