-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket.go
60 lines (47 loc) · 1.2 KB
/
packet.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
// Copyright 2023-24 Kirill Scherba <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Teonet messages queue. Packet module.
package teomq
import (
"bytes"
"encoding/binary"
)
// Packet defines answer message
type Packet struct {
id uint32
data []byte
}
// NewPacket creates new packet.
func NewPacket(id uint32, data []byte) *Packet {
return &Packet{id, data}
}
// ID returns message ID.
func (p Packet) ID() int {
return int(p.id)
}
// Data returns message data.
func (p Packet) Data() []byte {
return p.data
}
// MarshalBinary marshals binary packet
func (p Packet) MarshalBinary() (data []byte, err error) {
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, p.id)
binary.Write(buf, binary.LittleEndian, p.data)
data = buf.Bytes()
return
}
// UnmarshalBinary unmarshals binary packet
func (p *Packet) UnmarshalBinary(data []byte) (err error) {
var buf = bytes.NewBuffer(data)
if err = binary.Read(buf, binary.LittleEndian, &p.id); err != nil {
return
}
d := make([]byte, buf.Len())
if err = binary.Read(buf, binary.LittleEndian, d); err != nil {
return
}
p.data = d
return
}