From 0c4ce1091295da76305f1a7a7387e1d3ddb943ee Mon Sep 17 00:00:00 2001 From: Caleb Spare Date: Mon, 22 Feb 2016 20:33:49 -0800 Subject: [PATCH] In Decode, reuse slices when possible --- decode.go | 3 ++- decode_test.go | 15 ++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/decode.go b/decode.go index 8e76f02e..58d1c26f 100644 --- a/decode.go +++ b/decode.go @@ -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) } diff --git a/decode_test.go b/decode_test.go index 418269b3..995f1d8b 100644 --- a/decode_test.go +++ b/decode_test.go @@ -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) } }