From 67806abcdb744eebeca5f3a1d8d0107a2d5cbf46 Mon Sep 17 00:00:00 2001 From: Tnze Date: Mon, 30 Nov 2020 14:29:15 +0800 Subject: [PATCH] fix #88 --- chat/chatMsg.go | 6 +++--- chat/chatMsg_test.go | 6 ++++++ net/packet/util.go | 51 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 net/packet/util.go diff --git a/chat/chatMsg.go b/chat/chatMsg.go index 2e5b8b9..ac52737 100644 --- a/chat/chatMsg.go +++ b/chat/chatMsg.go @@ -33,7 +33,7 @@ type jsonChat struct { Translate string `json:"translate,omitempty"` With []json.RawMessage `json:"with,omitempty"` // How can go handle an JSON array with Object and String? - Extra []jsonChat `json:"extra,omitempty"` + Extra []Message `json:"extra,omitempty"` } //UnmarshalJSON decode json to Message @@ -73,12 +73,12 @@ func (m *Message) Append(extraMsg ...Message) { finalLen := origLen + len(extraMsg) if cap(m.Extra) < len(m.Extra)+len(extraMsg) { // pre expansion - extra := make([]jsonChat, finalLen) + extra := make([]Message, finalLen) copy(extra, m.Extra) m.Extra = extra } for _, v := range extraMsg { - m.Extra = append(m.Extra, jsonChat(v)) + m.Extra = append(m.Extra, v) } } diff --git a/chat/chatMsg_test.go b/chat/chatMsg_test.go index fd190e0..f01ca71 100644 --- a/chat/chatMsg_test.go +++ b/chat/chatMsg_test.go @@ -34,6 +34,8 @@ var jsons = []string{ `"Tnze"`, `"§0Tnze"`, `"§list"`, + + `{"extra":[" "],"text":""}`, } var texts = []string{ @@ -49,6 +51,8 @@ var texts = []string{ "Tnze", "\033[30mTnze\033[0m", "\033[1mist\033[0m", + + " ", } var ctexts = []string{ @@ -64,6 +68,8 @@ var ctexts = []string{ "Tnze", "Tnze", "ist", + + " ", } func TestChatMsgFormatString(t *testing.T) { diff --git a/net/packet/util.go b/net/packet/util.go new file mode 100644 index 0000000..2f1fa6c --- /dev/null +++ b/net/packet/util.go @@ -0,0 +1,51 @@ +package packet + +import ( + "reflect" +) + +type Ary struct { + Len Field + Ary interface{} +} + +func (a Ary) Encode() (data []byte) { + length := int(reflect.ValueOf(a.Len).Int()) + array := reflect.ValueOf(a.Ary).Elem() + for i := 0; i < length; i++ { + elem := array.Index(i) + data = append(data, elem.Interface().(FieldEncoder).Encode()...) + } + return +} + +func (a Ary) Decode(r DecodeReader) error { + length := int(reflect.ValueOf(a.Len).Int()) + array := reflect.ValueOf(a.Ary).Elem() + for i := 0; i < length; i++ { + elem := array.Index(i) + if err := elem.Interface().(FieldDecoder).Decode(r); err != nil { + return err + } + } + return nil +} + +type Opt struct { + Has func() bool + Field interface{} +} + +func (o Opt) Encode() []byte { + if o.Has() { + return nil + } + return o.Field.(FieldEncoder).Encode() +} + +func (o Opt) Decode(r DecodeReader) error { + if o.Has() { + return nil + } + return o.Field.(FieldDecoder).Decode(r) +}