-
Notifications
You must be signed in to change notification settings - Fork 7
/
pipe.go
67 lines (52 loc) · 1.12 KB
/
pipe.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package progrock
import (
"errors"
"sync"
"google.golang.org/protobuf/proto"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
)
func Pipe() (Reader, Writer) {
pipe := &unboundedPipe{
cond: sync.NewCond(&sync.Mutex{}),
}
return pipe, pipe
}
type unboundedPipe struct {
cond *sync.Cond
buffer []*StatusUpdate
closed bool
}
func (p *unboundedPipe) WriteStatus(value *StatusUpdate) error {
p.cond.L.Lock()
defer p.cond.L.Unlock()
if p.closed {
return errors.New("pipe is closed")
}
p.buffer = append(p.buffer, value)
p.cond.Signal()
return nil
}
func (p *unboundedPipe) ReadStatus() (*StatusUpdate, bool) {
p.cond.L.Lock()
defer p.cond.L.Unlock()
for len(p.buffer) == 0 && !p.closed {
p.cond.Wait()
}
if len(p.buffer) == 0 && p.closed {
return nil, false
}
value := p.buffer[0]
if value.Received == nil {
value = proto.Clone(value).(*StatusUpdate)
value.Received = timestamppb.New(Clock.Now())
}
p.buffer = p.buffer[1:]
return value, true
}
func (p *unboundedPipe) Close() error {
p.cond.L.Lock()
defer p.cond.L.Unlock()
p.closed = true
p.cond.Broadcast()
return nil
}