Skip to content

Commit

Permalink
Clean up slice decoding handling
Browse files Browse the repository at this point in the history
Add some test cases as well.
  • Loading branch information
cespare authored and IMAZU Mitsumasa committed Jul 19, 2016
1 parent d1385e5 commit 11fb26e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
8 changes: 4 additions & 4 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,11 @@ func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error {
if datav.Kind() != reflect.Slice {
return badtype("slice", data)
}
sliceLen := datav.Len()
if rv.IsNil() || rv.Len() < datav.Len() {
rv.Set(reflect.MakeSlice(rv.Type(), sliceLen, sliceLen))
n := datav.Len()
if rv.IsNil() || rv.Cap() < n {
rv.Set(reflect.MakeSlice(rv.Type(), n, n))
}
rv.SetLen(datav.Len())
rv.SetLen(n)
return md.unifySliceArray(datav, rv)
}

Expand Down
33 changes: 24 additions & 9 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -523,16 +523,31 @@ type ingredient struct {
}

func TestDecodeSlices(t *testing.T) {
s := struct{ Test []string }{Test: []string{}}
if _, err := Decode(`Test = ["test"]`, &s); err != nil {
t.Errorf("Error decoding into empty slice: %s", err)
type T struct {
S []string
}
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)
for i, tt := range []struct {
v T
input string
want T
}{
{T{}, "", T{}},
{T{[]string{}}, "", T{[]string{}}},
{T{[]string{"a", "b"}}, "", T{[]string{"a", "b"}}},
{T{}, "S = []", T{[]string{}}},
{T{[]string{}}, "S = []", T{[]string{}}},
{T{[]string{"a", "b"}}, "S = []", T{[]string{}}},
{T{}, `S = ["x"]`, T{[]string{"x"}}},
{T{[]string{}}, `S = ["x"]`, T{[]string{"x"}}},
{T{[]string{"a", "b"}}, `S = ["x"]`, T{[]string{"x"}}},
} {
if _, err := Decode(tt.input, &tt.v); err != nil {
t.Errorf("[%d] %s", i, err)
continue
}
if !reflect.DeepEqual(tt.v, tt.want) {
t.Errorf("[%d] got %#v; want %#v", i, tt.v, tt.want)
}
}
}

Expand Down

0 comments on commit 11fb26e

Please sign in to comment.