-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.go
More file actions
49 lines (43 loc) · 822 Bytes
/
iterator.go
File metadata and controls
49 lines (43 loc) · 822 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
39
40
41
42
43
44
45
46
47
48
49
package eventstream
import (
"context"
"errors"
)
type iterator[T any] struct {
p Promise[T]
}
func (it *iterator[T]) Next(ctx context.Context) (T, error) {
var zero T
if it.p == nil {
return zero, ErrDone
}
if err := ctx.Err(); err != nil {
return zero, err
}
select {
case <-it.p.Ready():
v, p := it.p.Next()
it.p = p
if p == nil {
return zero, ErrDone
}
return v, nil
case <-ctx.Done():
return zero, ctx.Err()
}
}
func (it *iterator[T]) Consume(ctx context.Context, callback func(context.Context, T) error) error {
for {
if val, err := it.Next(ctx); err != nil {
return filterErrDone(err)
} else if err = callback(ctx, val); err != nil {
return filterErrDone(err)
}
}
}
func filterErrDone(err error) error {
if errors.Is(err, ErrDone) {
return nil
}
return err
}