forked from rancher/remotedialer
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreadbuffer.go
106 lines (90 loc) · 1.51 KB
/
readbuffer.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
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
99
100
101
102
103
104
105
106
package remotedialer
import (
"bytes"
"errors"
"io"
"sync"
"time"
)
const (
MaxBuffer = 1 << 20
)
type readBuffer struct {
cond sync.Cond
deadline time.Time
buf bytes.Buffer
err error
}
func newReadBuffer() *readBuffer {
return &readBuffer{
cond: sync.Cond{
L: &sync.Mutex{},
},
}
}
func (r *readBuffer) Offer(reader io.Reader) error {
r.cond.L.Lock()
defer r.cond.L.Unlock()
for {
if r.err != nil {
return r.err
}
if n, err := io.Copy(&r.buf, reader); err != nil {
return err
} else if n > 0 {
r.cond.Broadcast()
}
if r.buf.Len() < MaxBuffer {
return nil
}
r.cond.Wait()
}
}
func (r *readBuffer) Read(b []byte) (int, error) {
r.cond.L.Lock()
defer r.cond.L.Unlock()
for {
var (
n int
err error
)
if r.buf.Len() > 0 {
n, err = r.buf.Read(b)
r.cond.Broadcast()
if err != io.EOF {
return n, err
}
// buffer remains to be read
if r.err == io.EOF && r.buf.Len() > 0 {
return n, nil
}
return n, r.err
}
if r.err != nil {
return n, r.err
}
now := time.Now()
if !r.deadline.IsZero() {
if now.After(r.deadline) {
return 0, errors.New("deadline exceeded")
}
}
var t *time.Timer
if !r.deadline.IsZero() {
t = time.AfterFunc(r.deadline.Sub(now), func() { r.cond.Broadcast() })
}
r.cond.Wait()
if t != nil {
t.Stop()
}
}
}
func (r *readBuffer) Close(err error) error {
r.cond.L.Lock()
defer r.cond.L.Unlock()
if r.err == nil {
r.err = err
}
r.cond.Broadcast()
return nil
}