-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchanreaderwriter.go
More file actions
45 lines (38 loc) · 827 Bytes
/
chanreaderwriter.go
File metadata and controls
45 lines (38 loc) · 827 Bytes
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
package main
import "io"
// chanReader receives on the channel when its
// Read method is called. Extra data received is
// buffered until read.
type chanReader struct {
buf []byte
c <-chan []byte
}
func newChanReader(c <-chan []byte) *chanReader {
return &chanReader{c: c}
}
func (r *chanReader) Read(buf []byte) (int, error) {
for len(r.buf) == 0 {
var ok bool
r.buf, ok = <-r.c
if !ok {
return 0, io.EOF
}
}
n := copy(buf, r.buf)
r.buf = r.buf[n:]
return n, nil
}
// chanWriter writes on the channel when its
// Write method is called.
type chanWriter struct {
c chan<- []byte
}
func newChanWriter(c chan<- []byte) *chanWriter {
return &chanWriter{c: c}
}
func (w *chanWriter) Write(buf []byte) (n int, err error) {
b := make([]byte, len(buf))
copy(b, buf)
w.c <- b
return len(buf), nil
}