From 9c17eb866b3bb2c981803a6d26910410b744498b Mon Sep 17 00:00:00 2001 From: Matthias Fulz Date: Tue, 7 Sep 2021 21:35:35 +0200 Subject: [PATCH] Bugfix unmarshalling struct improvement of Decode --- decoder.go | 21 +++++++++++++++++++-- unmarshal.go | 3 +-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/decoder.go b/decoder.go index 9526fba..9b49cb9 100644 --- a/decoder.go +++ b/decoder.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "io" + "reflect" "sync" ) @@ -18,7 +19,7 @@ func NewDecoder(r io.Reader) *Decoder { return dec } -func (dec *Decoder) Decode() (ret interface{}, err error) { +func (dec *Decoder) Decode(e interface{}) (ret interface{}, err error) { st := make([]byte, ST_ID_SIZE) dec.mutex.Lock() @@ -39,5 +40,21 @@ func (dec *Decoder) Decode() (ret interface{}, err error) { if err != nil { return ret, err } - return getVal(ret).Interface(), err + ret = getVal(ret).Interface() + + if e != nil { + var v reflect.Value + if v, err = indirectValue(reflect.ValueOf(e)); err != nil { + return ret, ErrValueInvalid + } + if valueIsNil(v) { + return ret, ErrValueInvalid + } + if v.Type() != reflect.TypeOf(ret) { + return ret, ErrTypeMismatch + } + v.Set(reflect.ValueOf(ret)) + } + + return ret, err } diff --git a/unmarshal.go b/unmarshal.go index c64e466..40c357c 100644 --- a/unmarshal.go +++ b/unmarshal.go @@ -363,7 +363,7 @@ func unmarshalStruct(e []byte, ntype *NType) (ie []byte, ret interface{}, err er var v interface{} for i, field := range stype.structFields { - if i > rv.NumField() { + if field.SId > rv.NumField() { return ie, ret, ErrTypeInvalid } if rv.Field(field.SId).CanSet() { @@ -378,7 +378,6 @@ func unmarshalStruct(e []byte, ntype *NType) (ie []byte, ret interface{}, err er } // TODO: checks? rv.Field(i).Set(getVal(v)) - break } }