-
Notifications
You must be signed in to change notification settings - Fork 60
/
codec.go
71 lines (60 loc) · 1.4 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
67
68
69
70
71
package zero
import (
"bytes"
"encoding/binary"
"errors"
)
// Encode from Message to []byte
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
}
// Decode from []byte to Message
func Decode(data []byte) (*Message, error) {
bufReader := bytes.NewReader(data)
dataSize := len(data)
// 读取消息ID
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
}
// 检查checksum
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")
}