Skip to content

Commit

Permalink
marshall: allow missing fields in UDT structs (apache#957)
Browse files Browse the repository at this point in the history
Allow unmarshalling UDT's into structs which do not contain all the
fields in the UDT.

Tidy up unmarshallUDT a little.
  • Loading branch information
Zariel authored Aug 12, 2017
1 parent 7743160 commit 44be8dc
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import (
)

var (
bigOne = big.NewInt(1)
bigOne = big.NewInt(1)
emptyValue reflect.Value
)

var (
Expand Down Expand Up @@ -1927,8 +1928,16 @@ func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
}

fields := make(map[string]reflect.Value)
if len(data) == 0 {
if k.CanSet() {
k.Set(reflect.Zero(k.Type()))
}

return nil
}

t := k.Type()
fields := make(map[string]reflect.Value, t.NumField())
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)

Expand All @@ -1937,14 +1946,6 @@ func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
}
}

if len(data) == 0 {
if k.CanSet() {
k.Set(reflect.Zero(k.Type()))
}

return nil
}

udt := info.(UDTTypeInfo)
for _, e := range udt.Elements {
if len(data) < 4 {
Expand All @@ -1955,11 +1956,15 @@ func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
size := readInt(data[:4])
data = data[4:]

var err error
if size >= 0 {
f, ok := fields[e.Name]
if !ok {
f = k.FieldByName(e.Name)
if f == emptyValue {
// skip fields which exist in the UDT but not in
// the struct passed in
continue
}
}

if !f.IsValid() || !f.CanAddr() {
Expand All @@ -1972,10 +1977,6 @@ func unmarshalUDT(info TypeInfo, data []byte, value interface{}) error {
}
data = data[size:]
}

if err != nil {
return err
}
}

return nil
Expand Down

0 comments on commit 44be8dc

Please sign in to comment.