-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
58 lines (49 loc) · 1.22 KB
/
codec.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 codec
import (
"encoding/binary"
"io"
)
// codec 接口
type Codec interface {
Marshal(v any) ([]byte, error)
MarshalTo(v any, w io.Writer) error
Unmarshal(data []byte, v any) error
UnmarshalFrom(r io.Reader, v any) error
String() string
}
type CodecType string
const (
CodeTypeNone CodecType = "code/none"
CodeTypeBinary CodecType = "code/binary"
CodeTypeGob CodecType = "code/gob"
CodeTypeJce CodecType = "code/jce"
CodeTypeJson CodecType = "code/json"
CodeTypePb CodecType = "code/pb"
CodeTypeThrift CodecType = "code/thrift"
CodeTypeMsgpack CodecType = "code/msgpack"
)
func (t CodecType) String() string {
return string(t)
}
// 默认序列化的字节序
// 默认为大端
var (
defaultOrder = binary.LittleEndian
)
var Codecs = map[CodecType]Codec{
CodeTypeNone: NewRawCoder(),
CodeTypeBinary: NewBinaryCoder(),
CodeTypeGob: NewGobCoder(),
CodeTypeJce: NewJceCoder(),
CodeTypeJson: NewJsonCoder(),
CodeTypePb: NewPbCoder(),
CodeTypeThrift: NewThriftCoder(),
CodeTypeMsgpack: NewMsgpackCoder(),
}
// 自定义注册编码方案
func RegisterCodec(t CodecType, c Codec) {
Codecs[t] = c
}
func UnRegisterCodec(t CodecType, c Codec) {
delete(Codecs, t)
}