/
packetfactory.go
52 lines (42 loc) · 1.01 KB
/
packetfactory.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
package netlib
import (
"fmt"
"reflect"
)
var factories = make(map[int]PacketFactory)
var packetQuickMap = make(map[reflect.Type]packetInfo)
type packetInfo struct {
ptype int
pid int
}
type PacketFactory interface {
CreatePacket() interface{}
}
type PacketFactoryWrapper func() interface{}
func (pfw PacketFactoryWrapper) CreatePacket() interface{} {
return pfw()
}
func RegisterFactory(packetId int, factory PacketFactory) {
if _, ok := factories[packetId]; ok {
panic(fmt.Sprintf("repeate register packet factory: %v", packetId))
}
factories[packetId] = factory
tp := factory.CreatePacket()
if tp != nil {
pt := typetest(tp)
packetQuickMap[reflect.TypeOf(tp)] = packetInfo{ptype: pt, pid: packetId}
}
}
func CreatePacket(packetId int) interface{} {
if v, ok := factories[packetId]; ok {
return v.CreatePacket()
}
return nil
}
func GetPacketTypeAndId(pack interface{}) (int, int) {
t := reflect.TypeOf(pack)
if tp, exist := packetQuickMap[t]; exist {
return tp.ptype, tp.pid
}
return 0, 0
}