-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpush.go
41 lines (38 loc) · 1.03 KB
/
push.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
package iterutil
import (
"iter"
)
// Push converts the “pull-style” iterator
// accessed by the two functions next and stop
// into a “push-style” iterator sequence.
// Push essentially is the inverse of [iter.Pull].
// Note that you must consume the resulting iterator;
// otherwise, the underlying pull-based iterator may leak.
func Push[E any](next func() (E, bool), stop func()) iter.Seq[E] {
return func(yield func(E) bool) {
defer stop()
for {
e, ok := next()
if !ok || !yield(e) {
return
}
}
}
}
// Push2 converts the “pull-style” iterator
// accessed by the two functions next and stop
// into a “push-style” iterator sequence.
// Push2 essentially is the inverse of [iter.Pull2].
// Note that you must consume the resulting iterator;
// otherwise, the underlying pull-based iterator may leak.
func Push2[K, V any](next func() (K, V, bool), stop func()) iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
defer stop()
for {
k, v, ok := next()
if !ok || !yield(k, v) {
return
}
}
}
}