Bugfix unmarshalling struct

improvement of Decode
This commit is contained in:
Matthias Fulz 2021-09-07 21:35:35 +02:00
parent c228d3fcce
commit 9c17eb866b
2 changed files with 20 additions and 4 deletions

View File

@ -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
}

View File

@ -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
}
}