-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtake.go
More file actions
84 lines (67 loc) Β· 1.32 KB
/
Copy pathtake.go
File metadata and controls
84 lines (67 loc) Β· 1.32 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package streams
var (
_ Streamable = (*TakeTimpl)(nil)
_ Receivable = (*TakeTimpl)(nil)
)
// TakeTimpl is a stream operator that takes a number of elements from the input channel.
type TakeTimpl struct {
count int
in chan any
out chan any
}
// Take returns a new Take operator.
func Take(count int) *TakeTimpl {
return NewTake(count)
}
// NewTake creates a new Take operator.
func NewTake(count int) *TakeTimpl {
t := &TakeTimpl{
count: count,
in: make(chan any),
out: make(chan any),
}
go t.attach()
return t
}
// To streams data to the sink and waits for it to complete.
func (t *TakeTimpl) To(sink Sinkable) error {
t.stream(sink)
err := sink.Wait()
if err != nil {
return err
}
return nil
}
// In returns the input channel.
func (t *TakeTimpl) In() chan<- any {
return t.in
}
// Out returns the output channel.
func (t *TakeTimpl) Out() <-chan any {
return t.out
}
// Pipe pipes the output channel to the input channel.
func (t *TakeTimpl) Pipe(c Operatable) Operatable {
go t.stream(c)
return c
}
func (t *TakeTimpl) stream(recv Receivable) {
for x := range t.out {
recv.In() <- x
}
close(recv.In())
}
func (t *TakeTimpl) attach() {
go func() {
for x := range t.in {
if t.count > 0 {
t.count--
t.out <- x
}
if t.count == 0 {
break
}
}
close(t.out)
}()
}