-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuffer.go
More file actions
76 lines (64 loc) · 1.26 KB
/
buffer.go
File metadata and controls
76 lines (64 loc) · 1.26 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
71
72
73
74
75
76
package thingsdb
import (
"net"
)
// buffer is used to read data from a connection.
type buffer struct {
data []byte
len uint32
pkg *pkg
conn net.Conn
pkgCh chan *pkg
evCh 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,
conn: nil,
pkgCh: make(chan *pkg),
evCh: make(chan *pkg),
errCh: make(chan error, 1),
}
}
// read listens on a connection for data.
func (buf buffer) read() {
for {
// try to read the data
wbuf := make([]byte, 8192)
n, err := buf.conn.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)
// The reserved ThingsDB events range is between 0..15
if buf.pkg.tp <= 15 {
buf.evCh <- buf.pkg
} else {
buf.pkgCh <- buf.pkg
}
buf.data = buf.data[total:]
buf.len -= total
buf.pkg = nil
}
}
}