github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/codec/codec.go (about) 1 package codec 2 3 import ( 4 "hash/crc32" 5 "strings" 6 ) 7 8 type ( 9 // SerializeType defines serialization type of payload. 10 SerializeType byte 11 12 // Codec defines the interface that decode/encode payload. 13 ICodec interface { 14 Encode(interface{}) ([]byte, error) 15 Decode([]byte, interface{}) error 16 String() string 17 } 18 ) 19 20 // Codecs are codecs supported by rpc. 21 var codecs = make(map[SerializeType]ICodec) 22 var names = make(map[string]SerializeType) 23 24 func (self SerializeType) String() string { 25 if c, has := codecs[self]; has { 26 return c.String() 27 } 28 29 return "Unknown" 30 } 31 32 // RegisterCodec register customized codec. 33 func RegisterCodec(name string, codec ICodec) SerializeType { 34 h := HashName(name) 35 codecs[h] = codec 36 names[strings.ToLower(name)] = h 37 return h 38 } 39 40 // 提供编码类型 41 func Use(name string) SerializeType { 42 if v, has := names[strings.ToLower(name)]; has { 43 return v 44 } 45 return 0 46 } 47 48 func IdentifyCodec(st SerializeType) ICodec { 49 return codecs[st] 50 } 51 52 func HashName(s string) SerializeType { 53 v := int(crc32.ChecksumIEEE([]byte(s))) // 输入一个字符等到唯一标识 54 if v >= 0 { 55 return SerializeType(v) 56 } 57 if -v >= 0 { 58 return SerializeType(-v) 59 } 60 // v == MinInt 61 return SerializeType(0) 62 }