Skip to content

Commit

Permalink
In Decode, reuse slices when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
cespare committed Feb 23, 2016
1 parent dacf173 commit 0c4ce10
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
3 changes: 2 additions & 1 deletion decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,9 +308,10 @@ func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error {
return badtype("slice", data)
}
sliceLen := datav.Len()
if rv.IsNil() || rv.Len() != datav.Len() {
if rv.IsNil() || rv.Len() < datav.Len() {
rv.Set(reflect.MakeSlice(rv.Type(), sliceLen, sliceLen))
}
rv.SetLen(datav.Len())
return md.unifySliceArray(datav, rv)
}

Expand Down
15 changes: 10 additions & 5 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,12 +498,17 @@ type ingredient struct {
Name string
}

func TestDecodeToEmptySlice(t *testing.T) {
func TestDecodeSlices(t *testing.T) {
s := struct{ Test []string }{Test: []string{}}

_, err := Decode(`Test = ["test"]`, &s)
if err != nil {
t.Fatal(err)
if _, err := Decode(`Test = ["test"]`, &s); err != nil {
t.Errorf("Error decoding into empty slice: %s", err)
}
s.Test = []string{"a", "b", "c"}
if _, err := Decode(`Test = ["test"]`, &s); err != nil {
t.Errorf("Error decoding into oversized slice: %s", err)
}
if want := []string{"test"}; !reflect.DeepEqual(s.Test, want) {
t.Errorf("Got %v; want %v", s.Test, want)
}
}

Expand Down

0 comments on commit 0c4ce10

Please sign in to comment.