Skip to content

Commit

Permalink
fix pre-existing maps not getting cleared on unmarshal (#196)
Browse files Browse the repository at this point in the history
  • Loading branch information
guregu committed May 4, 2022
1 parent 757bab6 commit 178cb03
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
10 changes: 6 additions & 4 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,14 +401,16 @@ func unmarshalItem(item map[string]*dynamodb.AttributeValue, out interface{}) er
var err error
fields := fieldsInStruct(rv.Elem())
for name, fv := range fields {
// we need to zero-out all fields to avoid weird data sticking around
// when iterating by unmarshaling to the same object over and over
if fv.CanSet() {
fv.Set(reflect.Zero(fv.Type()))
}

if av, ok := item[name]; ok {
if innerErr := unmarshalReflect(av, fv); innerErr != nil {
err = innerErr
}
} else {
// we need to zero-out omitted fields to avoid weird data sticking around
// when iterating by unmarshaling to the same object over and over
fv.Set(reflect.Zero(fv.Type()))
}
}
return err
Expand Down
30 changes: 30 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,33 @@ func TestUnmarshalMissing(t *testing.T) {
t.Error("bad unmarshal missing. want:", want, "got:", w)
}
}

func TestUnmarshalClearFields(t *testing.T) {
// tests against a regression from v1.12.0 in which map fields were not properly getting reset

type Foo struct {
Map map[string]bool
}

items := []Foo{
{Map: map[string]bool{"a": true}},
{Map: map[string]bool{"b": true}}, // before fix: {a: true, b: true}
{Map: map[string]bool{"c": true}}, // before fix: {a: true, b: true, c: true}
}

var foo Foo
for _, item := range items {
raw, err := MarshalItem(item)
if err != nil {
t.Fatal(err)
}

if err := UnmarshalItem(raw, &foo); err != nil {
t.Fatal(err)
}

if !reflect.DeepEqual(item, foo) {
t.Error("bad result. want:", item, "got:", foo)
}
}
}

0 comments on commit 178cb03

Please sign in to comment.