-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframe.go
76 lines (61 loc) · 1.53 KB
/
frame.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
package framestream
import (
"bytes"
"encoding/binary"
)
/*
Frame struct
|------------------------------------|----------------------|
| Data length | 4 bytes |
|------------------------------------|----------------------|
| Payload | xx bytes |
|------------------------------------|----------------------|
If the data length is equal to zero then it's a control frame
otherwise we have a data frame.
*/
type Frame struct {
data []byte
control bool
}
func (frame Frame) Len() int {
return len(frame.data)
}
func (frame Frame) IsControl() bool {
return frame.control
}
func (frame Frame) Data() []byte {
return frame.data
}
func (frame *Frame) Write(payload []byte) error {
var buf bytes.Buffer
var flen uint32
// if it is a control frame then the frame length must be equal to zero
if frame.control {
flen = uint32(0)
} else {
flen = uint32(len(payload))
}
// add frame length
if err := binary.Write(&buf, binary.BigEndian, flen); err != nil {
return err
}
// append payload in the buffer
if _, err := buf.Write(payload); err != nil {
return err
}
frame.data = buf.Bytes()
return nil
}
func (frame *Frame) AppendData(payload []byte) error {
frame.data = append(frame.data, payload...)
return nil
}
func (frame *Frame) Encode() error {
var buf bytes.Buffer
length := len(frame.data)
if err := binary.Write(&buf, binary.BigEndian, uint32(length)); err != nil {
return err
}
frame.data = append(buf.Bytes(), frame.data...)
return nil
}