forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
msgmeta.go
123 lines (93 loc) · 2.09 KB
/
msgmeta.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package cellnet
import (
"bytes"
"fmt"
"path"
"reflect"
)
type MessageMeta struct {
Type reflect.Type
Name string
ID uint32
Codec Codec
}
var (
metaByName = map[string]*MessageMeta{}
metaByID = map[uint32]*MessageMeta{}
metaByType = map[reflect.Type]*MessageMeta{}
)
// 注册消息元信息(代码生成专用)
func RegisterMessageMeta(codecName string, name string, msgType reflect.Type, id uint32) {
meta := &MessageMeta{
Type: msgType,
Name: name,
ID: id,
Codec: FetchCodec(codecName),
}
if meta.Codec == nil {
panic("codec not register! " + codecName)
}
if _, ok := metaByName[name]; ok {
panic("duplicate message meta register by name: " + name)
}
if _, ok := metaByID[meta.ID]; ok {
panic(fmt.Sprintf("duplicate message meta register by id: %d", meta.ID))
}
if _, ok := metaByType[msgType]; ok {
panic(fmt.Sprintf("duplicate message meta register by type: %d", meta.ID))
}
metaByName[name] = meta
metaByID[meta.ID] = meta
metaByType[msgType] = meta
}
// 根据名字查找消息元信息
func MessageMetaByName(name string) *MessageMeta {
if v, ok := metaByName[name]; ok {
return v
}
return nil
}
// 根据类型查找消息元信息
func MessageMetaByType(t reflect.Type) *MessageMeta {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if v, ok := metaByType[t]; ok {
return v
}
return nil
}
// 消息全名
func MessageFullName(rtype reflect.Type) string {
if rtype == nil {
panic("empty msg type")
}
if rtype.Kind() == reflect.Ptr {
rtype = rtype.Elem()
}
var b bytes.Buffer
b.WriteString(path.Base(rtype.PkgPath()))
b.WriteString(".")
b.WriteString(rtype.Name())
return b.String()
}
// 根据id查找消息元信息
func MessageMetaByID(id uint32) *MessageMeta {
if v, ok := metaByID[id]; ok {
return v
}
return nil
}
// 根据id查找消息名, 没找到返回空
func MessageNameByID(id uint32) string {
if meta := MessageMetaByID(id); meta != nil {
return meta.Name
}
return ""
}
// 遍历消息元信息
func VisitMessageMeta(callback func(*MessageMeta)) {
for _, meta := range metaByName {
callback(meta)
}
}