Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

Commit 1f85f72

Browse files
authored
Merge pull request #266 from ozgursoy/master
slice mapping bug fix
2 parents 3908fe7 + c9d3eae commit 1f85f72

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

mapstructure.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,6 +1123,8 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
11231123
if valSlice.IsNil() || d.config.ZeroFields {
11241124
// Make a new slice to hold our result, same size as the original data.
11251125
valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
1126+
} else if valSlice.Len() > dataVal.Len() {
1127+
valSlice = valSlice.Slice(0, dataVal.Len())
11261128
}
11271129

11281130
// Accumulate any errors

mapstructure_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,11 @@ type Slice struct {
138138
Vbar []string
139139
}
140140

141+
type SliceOfByte struct {
142+
Vfoo string
143+
Vbar []byte
144+
}
145+
141146
type SliceOfAlias struct {
142147
Vfoo string
143148
Vbar SliceAlias
@@ -1654,6 +1659,34 @@ func TestSlice(t *testing.T) {
16541659
testSliceInput(t, inputStringSlicePointer, outputStringSlice)
16551660
}
16561661

1662+
func TestNotEmptyByteSlice(t *testing.T) {
1663+
t.Parallel()
1664+
1665+
inputByteSlice := map[string]interface{}{
1666+
"vfoo": "foo",
1667+
"vbar": []byte(`{"bar": "bar"}`),
1668+
}
1669+
1670+
result := SliceOfByte{
1671+
Vfoo: "another foo",
1672+
Vbar: []byte(`{"bar": "bar bar bar bar bar bar bar bar"}`),
1673+
}
1674+
1675+
err := Decode(inputByteSlice, &result)
1676+
if err != nil {
1677+
t.Fatalf("got unexpected error: %s", err)
1678+
}
1679+
1680+
expected := SliceOfByte{
1681+
Vfoo: "foo",
1682+
Vbar: []byte(`{"bar": "bar"}`),
1683+
}
1684+
1685+
if !reflect.DeepEqual(result, expected) {
1686+
t.Errorf("bad: %#v", result)
1687+
}
1688+
}
1689+
16571690
func TestInvalidSlice(t *testing.T) {
16581691
t.Parallel()
16591692

0 commit comments

Comments
 (0)