/
msgpacket.go
58 lines (43 loc) · 1.04 KB
/
msgpacket.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
package gap
import "git.golaxy.org/framework/util/binaryutil"
// MsgPacket 消息包
type MsgPacket struct {
Head MsgHead // 消息头
Msg Msg // 消息
}
// Read implements io.Reader
func (mp MsgPacket) Read(p []byte) (int, error) {
bs := binaryutil.NewBigEndianStream(p)
if _, err := binaryutil.ReadFrom(&bs, mp.Head); err != nil {
return bs.BytesWritten(), err
}
if mp.Msg == nil {
return bs.BytesWritten(), nil
}
if _, err := binaryutil.ReadFrom(&bs, mp.Msg); err != nil {
return bs.BytesWritten(), err
}
return bs.BytesWritten(), nil
}
// Write implements io.Writer
func (mp *MsgPacket) Write(p []byte) (int, error) {
bs := binaryutil.NewBigEndianStream(p)
if _, err := bs.WriteTo(&mp.Head); err != nil {
return bs.BytesRead(), err
}
if mp.Msg == nil {
return bs.BytesRead(), nil
}
if _, err := bs.WriteTo(mp.Msg); err != nil {
return bs.BytesRead(), err
}
return bs.BytesRead(), nil
}
// Size 大小
func (mp MsgPacket) Size() int {
n := mp.Head.Size()
if mp.Msg != nil {
n += mp.Msg.Size()
}
return n
}