1
0
mirror of https://github.com/Mrs4s/MiraiGo.git synced 2025-05-05 03:23:50 +08:00
This commit is contained in:
Mrs4s 2021-01-30 20:01:46 +08:00
commit ba961e02e9

View File

@ -3,8 +3,10 @@ package jce
import ( import (
"bytes" "bytes"
goBinary "encoding/binary" goBinary "encoding/binary"
"github.com/modern-go/reflect2"
"reflect" "reflect"
"strconv" "strconv"
"sync"
) )
type JceWriter struct { type JceWriter struct {
@ -200,23 +202,46 @@ func (w *JceWriter) WriteObject(i interface{}, tag int) {
} }
} }
type decoder []struct {
fieldID int
id int
}
var decoderCache = sync.Map{}
// WriteJceStructRaw 写入 Jce 结构体
func (w *JceWriter) WriteJceStructRaw(s IJceStruct) { func (w *JceWriter) WriteJceStructRaw(s IJceStruct) {
var ( var (
t = reflect.TypeOf(s).Elem() v = reflect.ValueOf(s).Elem()
v = reflect.ValueOf(s).Elem() ty2 = reflect2.TypeOf(s)
jceDec decoder
) )
for i := 0; i < t.NumField(); i++ { dec, ok := decoderCache.Load(ty2)
strId := t.Field(i).Tag.Get("jceId") if ok { // 从缓存中加载
if strId == "" { jceDec = dec.(decoder)
continue } else { // 初次反射
jceDec = decoder{}
t := reflect.TypeOf(s).Elem()
for i := 0; i < t.NumField(); i++ {
strId := t.Field(i).Tag.Get("jceId")
if strId == "" {
continue
}
id, err := strconv.Atoi(strId)
if err != nil {
continue
}
jceDec = append(jceDec, struct {
fieldID int
id int
}{fieldID: i, id: id})
} }
id, err := strconv.Atoi(strId) decoderCache.Store(ty2, jceDec) // 存入缓存
if err != nil { }
continue for _, dec := range jceDec {
} obj := v.Field(dec.fieldID).Interface()
obj := v.Field(i).Interface()
if obj != nil { if obj != nil {
w.WriteObject(v.Field(i).Interface(), id) w.WriteObject(obj, dec.id)
} }
} }
} }