-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
66 lines (55 loc) · 1.29 KB
/
codec.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
package gosocket
import (
"bytes"
"encoding/binary"
"errors"
)
func Encode(msg *Message) ([]byte, error) {
buffer := new(bytes.Buffer)
err := binary.Write(buffer, binary.LittleEndian, msg.msgSize)
if err != nil {
return nil, err
}
err = binary.Write(buffer, binary.LittleEndian, msg.msgID)
if err != nil {
return nil, err
}
err = binary.Write(buffer, binary.LittleEndian, msg.data)
if err != nil {
return nil, err
}
err = binary.Write(buffer, binary.LittleEndian, msg.checksum)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func Decode(data []byte) (*Message, error) {
bufReader := bytes.NewReader(data)
dataSize := len(data)
var msgID int32
err := binary.Read(bufReader, binary.LittleEndian, &msgID)
if err != nil {
return nil, err
}
dataBufLength := dataSize - 4 - 4
dataBuf := make([]byte, dataBufLength)
err = binary.Read(bufReader, binary.LittleEndian, &dataBuf)
if err != nil {
return nil, err
}
var checksum uint32
err = binary.Read(bufReader, binary.LittleEndian, &checksum)
if err != nil {
return nil, err
}
message := &Message{}
message.msgSize = int32(dataSize)
message.msgID = msgID
message.data = dataBuf
message.checksum = checksum
if message.Verify() {
return message, nil
}
return nil, errors.New("checksum error")
}