-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
156 lines (142 loc) · 2.41 KB
/
io.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package examples
import (
"bytes"
"errors"
"io"
"sync"
)
type (
// MultiplexReader let a reader be read by multiple consumer.
MultiplexReader struct {
sync.Mutex
closed bool
r io.Reader
bufs map[*xbuf]struct{}
}
xbuf struct {
sync.Mutex
closedq chan struct{}
mr *MultiplexReader
ready chan struct{}
buf *bytes.Buffer
}
)
var (
// ErrClosed is the error used for operation on a closed object.
ErrClosed = errors.New("object closed")
)
// NewMultiplexReader create a MultiplexReader
func NewMultiplexReader(r io.Reader) *MultiplexReader {
mr := &MultiplexReader{
r: r,
bufs: make(map[*xbuf]struct{}),
}
go mr.run()
return mr
}
func (mr *MultiplexReader) run() {
var (
n int
err error
)
p := make([]byte, 32*1024)
for {
n, err = mr.r.Read(p)
if n > 0 {
bufs := mr.getBufs()
for _, buf := range bufs {
n, err = buf.buf.Write(p[:n])
// ready signal, best effort
select {
case buf.ready <- struct{}{}:
default:
}
if err != nil {
buf.Close()
}
}
}
if err != nil {
break
}
}
mr.Close()
}
func (mr *MultiplexReader) getBufs() []*xbuf {
bufs := make([]*xbuf, len(mr.bufs))
mr.Lock()
idx := 0
for buf := range mr.bufs {
bufs[idx] = buf
idx++
}
mr.Unlock()
return bufs
}
// Close close all readers.
func (mr *MultiplexReader) Close() error {
mr.Lock()
if mr.closed {
mr.Unlock()
return io.EOF
}
mr.closed = true
mr.Unlock()
bufs := mr.getBufs()
for _, buf := range bufs {
buf.Close()
}
return nil
}
// NewReader create a new reader from source
func (mr *MultiplexReader) NewReader() (io.ReadCloser, error) {
mr.Lock()
if mr.closed {
mr.Unlock()
return nil, ErrClosed
}
mr.Unlock()
buf := &xbuf{
mr: mr,
closedq: make(chan struct{}),
ready: make(chan struct{}, 1),
buf: bytes.NewBuffer(nil),
}
mr.Lock()
mr.bufs[buf] = struct{}{}
mr.Unlock()
return buf, nil
}
func (b *xbuf) Read(p []byte) (n int, err error) {
select {
case <-b.closedq:
err = io.EOF
return
case <-b.ready:
n, err = b.buf.Read(p)
if err == nil {
// err is nil means buf may has more data to read.
select {
case b.ready <- struct{}{}:
default:
}
}
err = nil
}
return
}
func (b *xbuf) Close() error {
b.Lock()
select {
case <-b.closedq:
b.Unlock()
return ErrClosed
default:
close(b.closedq)
}
b.Unlock()
b.mr.Lock()
delete(b.mr.bufs, b)
b.mr.Unlock()
return nil
}