-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
91 lines (78 loc) · 1.64 KB
/
util.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package enodolib
import (
"net"
"strings"
"github.com/google/uuid"
)
func GenerateEnodoId() string {
uuidWithHyphen := uuid.New()
uuid := strings.Replace(uuidWithHyphen.String(), "-", "", -1)
return uuid
}
type pkg struct {
header []byte
data []byte
}
func (p *pkg) GetHeader() []byte {
return p.header
}
func (p *pkg) GetData() []byte {
return p.data
}
// buffer is used to read data from a connection.
type buffer struct {
conn net.Conn
data []byte
dataSize uint32
len uint32
pkg *pkg
pkgCh chan *pkg
}
// newBuffer retur a pointer to a new buffer.
func NewBuffer() *buffer {
return &buffer{
conn: nil,
data: make([]byte, 0),
dataSize: 0,
len: 0,
pkg: nil,
pkgCh: make(chan *pkg),
}
}
func (buf *buffer) SetConn(c net.Conn) {
buf.conn = c
}
func (buf *buffer) GetPkgChan() chan *pkg {
return buf.pkgCh
}
func (buf buffer) ReadToBuffer(headerSize uint32, getDataSize func([]byte) (uint32, error)) {
for {
// try to read the data
wbuf := make([]byte, 8192)
n, err := buf.conn.Read(wbuf)
if err != nil {
return
}
buf.len += uint32(n)
buf.data = append(buf.data, wbuf[:n]...)
for buf.len >= headerSize {
if buf.pkg == nil {
buf.dataSize, err = getDataSize(buf.data[:headerSize])
buf.pkg = &pkg{make([]byte, headerSize), make([]byte, buf.dataSize)}
if err != nil {
return
}
}
total := buf.dataSize + headerSize
if buf.len < total {
break
}
buf.pkg.header = buf.data[0:headerSize]
buf.pkg.data = buf.data[headerSize:total]
buf.pkgCh <- buf.pkg
buf.data = buf.data[total:]
buf.len -= total
buf.pkg = nil
}
}
}