-
Notifications
You must be signed in to change notification settings - Fork 34
/
stream.go
72 lines (58 loc) · 1.1 KB
/
stream.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
package fscache
import (
"encoding/json"
"errors"
"io"
)
type decoder interface {
Decode(interface{}) error
}
type encoder interface {
Encode(interface{}) error
}
type pktReader struct {
dec decoder
}
type pktWriter struct {
enc encoder
}
type packet struct {
Err int
Data []byte
}
const eof = 1
func (t *pktReader) ReadAt(p []byte, off int64) (n int, err error) {
// TODO not implemented
return 0, errors.New("not implemented")
}
func (t *pktReader) Read(p []byte) (int, error) {
var pkt packet
err := t.dec.Decode(&pkt)
if err != nil {
return 0, err
}
if pkt.Err == eof {
return 0, io.EOF
}
return copy(p, pkt.Data), nil
}
func (t *pktReader) Close() error {
return nil
}
func (t *pktWriter) Write(p []byte) (int, error) {
pkt := packet{Data: p}
err := t.enc.Encode(pkt)
if err != nil {
return 0, err
}
return len(p), nil
}
func (t *pktWriter) Close() error {
return t.enc.Encode(packet{Err: eof})
}
func newEncoder(w io.Writer) io.WriteCloser {
return &pktWriter{enc: json.NewEncoder(w)}
}
func newDecoder(r io.Reader) ReadAtCloser {
return &pktReader{dec: json.NewDecoder(r)}
}