-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.go
More file actions
70 lines (58 loc) · 1.14 KB
/
buffer.go
File metadata and controls
70 lines (58 loc) · 1.14 KB
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
package timod
import (
"bufio"
"os"
)
// Buffer is used to read data from a connection.
type Buffer struct {
data []byte
len uint32
pkg *Pkg
reader *bufio.Reader
PkgCh chan *Pkg
ErrCh chan error
}
// NewBuffer retur a pointer to a new buffer.
func NewBuffer() *Buffer {
return &Buffer{
data: make([]byte, 0),
len: 0,
pkg: nil,
reader: bufio.NewReader(os.Stdin),
PkgCh: make(chan *Pkg),
ErrCh: make(chan error, 1),
}
}
// Listen listens on a connection for data.
func (buf Buffer) Listen() {
for {
// try to read the data
wbuf := make([]byte, 4)
n, err := buf.reader.Read(wbuf)
if err != nil {
// send an error if it's encountered
buf.ErrCh <- err
return
}
buf.len += uint32(n)
buf.data = append(buf.data, wbuf[:n]...)
for buf.len >= pkgHeaderSize {
if buf.pkg == nil {
buf.pkg, err = newPkg(buf.data)
if err != nil {
buf.ErrCh <- err
return
}
}
total := buf.pkg.Size + pkgHeaderSize
if buf.len < total {
break
}
buf.pkg.setData(&buf.data, total)
buf.PkgCh <- buf.pkg
buf.data = buf.data[total:]
buf.len -= total
buf.pkg = nil
}
}
}