-
Notifications
You must be signed in to change notification settings - Fork 61
/
readwritecloser.go
74 lines (56 loc) · 1.33 KB
/
readwritecloser.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
package can
import (
"io"
)
// The Reader interface extends the `io.Reader` interface by method
// to read a frame.
type Reader interface {
io.Reader
ReadFrame(*Frame) error
}
// The Writer interface extends the `io.Writer` interface by method
// to write a frame.
type Writer interface {
io.Writer
WriteFrame(Frame) error
}
// The ReadWriteCloser interface combines the Reader and Writer and
// `io.Closer` interface.
type ReadWriteCloser interface {
Reader
Writer
io.Closer
}
type readWriteCloser struct {
rwc io.ReadWriteCloser
}
// NewReadWriteCloser returns a ReadWriteCloser for an `io.ReadWriteCloser`.
func NewReadWriteCloser(rwc io.ReadWriteCloser) ReadWriteCloser {
return &readWriteCloser{rwc}
}
func (rwc *readWriteCloser) ReadFrame(frame *Frame) error {
b := make([]byte, 256) // TODO(brutella) optimize size
n, err := rwc.Read(b)
if err != nil {
return err
}
err = Unmarshal(b[:n], frame)
return err
}
func (rwc *readWriteCloser) WriteFrame(frame Frame) error {
b, err := Marshal(frame)
if err != nil {
return err
}
_, err = rwc.Write(b)
return err
}
func (rwc *readWriteCloser) Read(b []byte) (n int, err error) {
return rwc.rwc.Read(b)
}
func (rwc *readWriteCloser) Write(b []byte) (n int, err error) {
return rwc.rwc.Write(b)
}
func (rwc *readWriteCloser) Close() error {
return rwc.rwc.Close()
}