-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.go
50 lines (42 loc) · 952 Bytes
/
channel.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
package iter
import (
"context"
types "github.com/patrickhuber/go-types"
"github.com/patrickhuber/go-types/option"
)
type ChannelOption[T any] func(*channelOption[T])
type channelOption[T any] struct {
cx context.Context
}
// WithContext provides an context.Context for channel operations
func WithContext[T any](cx context.Context) ChannelOption[T] {
return func(ci *channelOption[T]) {
ci.cx = cx
}
}
func FromChannel[T any](ch chan T, options ...ChannelOption[T]) Iterator[T] {
co := &channelOption[T]{}
for _, option := range options {
option(co)
}
if co.cx == nil {
co.cx = context.Background()
}
return &channelIterator[T]{
ch: ch,
cx: co.cx,
}
}
type channelIterator[T any] struct {
ch chan T
cx context.Context
}
// Next implements Iterator.
func (ci *channelIterator[T]) Next() types.Option[T] {
select {
case v, ok := <-ci.ch:
return option.New(v, ok)
case <-ci.cx.Done():
return option.None[T]()
}
}