5 Star 0 Fork 0

Md / gu

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
manager.go 1.59 KB
一键复制 编辑 原始数据 按行查看 历史
liyafei 提交于 2023-02-15 14:11 . wsptc decode 修改
/*
web socket protocol
*/
package wsptc
import (
"encoding/binary"
"errors"
"reflect"
"strings"
"gitee.com/MikeDDD/gu/logs"
"google.golang.org/protobuf/proto"
)
var (
ErrorProtoMarshal = errors.New("proto marshal error")
ErrorInput = errors.New("input error")
ErrorProtoUnmarshal = errors.New("proto ummarshal error")
)
func Hash(name string) uint32 {
arrByte := []byte(name)
var nHash uint32 = 1315423911
for _, c := range arrByte {
nHash ^= (nHash << 5) + uint32(c) + (nHash >> 2)
}
return nHash & 0x7FFFFFFF
}
func Equal(s1 []byte, s2 []byte) bool {
if len(s1) != len(s2) {
return false
}
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
return false
}
}
return true
}
func MessageId(message any) []byte {
msgType := reflect.TypeOf(message)
arrMsgNameRes := strings.Split(msgType.String(), ".") // s := strings.Split("a.b.c.d.c2srequest",".")
hashValue := Hash(arrMsgNameRes[len(arrMsgNameRes)-1]) // hash("c2srequest")
hashByte := make([]byte, 4)
binary.BigEndian.PutUint32(hashByte, hashValue)
return hashByte
}
func Encode(message proto.Message) ([]byte, error) {
binaryData, err := proto.Marshal(message)
if err != nil {
logs.Error(err)
return nil, ErrorProtoMarshal
}
name := reflect.TypeOf(message).Elem().Name()
nameHash := Hash(name)
output := make([]byte, 4, 4)
binary.BigEndian.PutUint32(output, nameHash)
output = append(output, binaryData...)
return output, nil
}
func Decode(message []byte) (uint32, []byte, error) {
if len(message) < 4 {
return 0, nil, ErrorInput
}
return binary.BigEndian.Uint32(message[:4]), message[4:], nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/MikeDDD/gu.git
git@gitee.com:MikeDDD/gu.git
MikeDDD
gu
gu
v0.0.16-lyf-1

搜索帮助

344bd9b3 5694891 D2dac590 5694891