From e73be166bd9f854091ea0dae100a3aa704bae60a Mon Sep 17 00:00:00 2001 From: Tnze Date: Tue, 17 May 2022 12:15:24 +0800 Subject: [PATCH] Support decode ByteArray as []int8 --- nbt/decode.go | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/nbt/decode.go b/nbt/decode.go index 8401ca4..96b4ea4 100644 --- a/nbt/decode.go +++ b/nbt/decode.go @@ -213,13 +213,34 @@ func (d *Decoder) unmarshal(val reflect.Value, tagType byte) error { return err } - switch vt := val.Type(); { - default: - return errors.New("cannot parse TagByteArray to " + vt.String() + ", use []byte in this instance") - case vt == reflect.TypeOf(ba): + vt := val.Type() + if vt == reflect.TypeOf(ba) { val.SetBytes(ba) - case vt.Kind() == reflect.Interface: + } else if vt.Kind() == reflect.Slice { + switch ve := vt.Elem(); ve.Kind() { + case reflect.Int8, reflect.Uint8: + length := int(aryLen) + if val.Cap() < length { + val.Set(reflect.MakeSlice(vt, length, length)) + } + val.SetLen(length) + switch ve.Kind() { + case reflect.Int8: + for i := 0; i < length; i++ { + val.Index(i).Set(reflect.ValueOf(int8(ba[i]))) + } + case reflect.Uint8: + for i := 0; i < length; i++ { + val.Index(i).Set(reflect.ValueOf(ba[i])) + } + } + default: + return errors.New("cannot parse TagByteArray to slice of" + ve.String()) + } + } else if vt.Kind() == reflect.Interface { val.Set(reflect.ValueOf(ba)) + } else { + return errors.New("cannot parse TagByteArray to " + vt.String()) } case TagIntArray: