-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimeout.go
More file actions
98 lines (78 loc) Β· 1.48 KB
/
Copy pathtimeout.go
File metadata and controls
98 lines (78 loc) Β· 1.48 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package streams
import (
"time"
)
var (
_ Streamable = (*TimeoutImpl)(nil)
_ Receivable = (*TimeoutImpl)(nil)
)
// TimeoutImpl is an operator that closes the stream after a set amount of time.
type TimeoutImpl struct {
dur time.Duration
in chan any
out chan any
}
// Timeout returns a new timeout pipe.
func Timeout(dur time.Duration) *TimeoutImpl {
return NewTimeout(dur)
}
// NewTimeout creates a new Timeout operator.
func NewTimeout(dur time.Duration) *TimeoutImpl {
t := &TimeoutImpl{
dur: dur,
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 *TimeoutImpl) To(sink Sinkable) error {
t.stream(sink)
err := sink.Wait()
if err != nil {
return err
}
return nil
}
// In returns the input channel.
func (t *TimeoutImpl) In() chan<- any {
return t.in
}
// Out returns the output channel.
func (t *TimeoutImpl) Out() <-chan any {
return t.out
}
// Pipe pipes the output channel to the input channel.
func (t *TimeoutImpl) Pipe(c Operatable) Operatable {
go t.stream(c)
return c
}
func (t *TimeoutImpl) stream(r Receivable) {
elapsed := time.After(t.dur)
defer close(t.out)
OUTTER:
for {
select {
case v, ok := <-t.in:
if !ok {
break OUTTER
}
r.In() <- v
case <-elapsed:
break OUTTER
}
}
close(r.In())
}
func (t *TimeoutImpl) attach() {
go func() {
for x := range t.in {
_, ok := <-t.out
if ok {
t.out <- x
}
}
close(t.out)
}()
}