-
Notifications
You must be signed in to change notification settings - Fork 0
/
packet-factory.go
53 lines (48 loc) · 1.08 KB
/
packet-factory.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
package clientpacket
import (
"log"
)
// packetFactory creates client packets from slices of bytes
type packetFactory struct {
// Packet constructors
ctors []func([]byte) Packet
}
// Add adds a constructor to the factory.
func (f *packetFactory) Add(id byte, ctor func([]byte) Packet) {
if f.ctors == nil {
f.ctors = make([]func([]byte) Packet, 0xFF)
}
if f.ctors[id] != nil {
log.Fatalf("duplicate packet ctor for packet %02X", id)
}
f.ctors[id] = ctor
}
// Ignore ignores the given packet ID
func (f *packetFactory) Ignore(id byte) {
f.Add(id, func(in []byte) Packet {
p := &IgnoredPacket{
basePacket: basePacket{id: id},
}
return p
})
}
// New creates a new client packet.
func (f *packetFactory) New(id byte, in []byte) Packet {
if id > 0xFF {
log.Printf("error: packet id 0x%08X out of range", id)
return nil
}
ctor := f.ctors[id]
if ctor == nil {
up := NewUnsupportedPacket("client", in)
up.basePacket.id = id
return up
}
p := ctor(in)
if p == nil {
up := NewUnsupportedPacket("client-packets", in)
up.basePacket.id = id
return up
}
return p
}