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

Commit

Permalink
Merge pull request #266 from ozgursoy/master
Browse files Browse the repository at this point in the history
slice mapping bug fix
  • Loading branch information
mitchellh authored Apr 23, 2022
2 parents 3908fe7 + c9d3eae commit 1f85f72
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,8 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
if valSlice.IsNil() || d.config.ZeroFields {
// Make a new slice to hold our result, same size as the original data.
valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
} else if valSlice.Len() > dataVal.Len() {
valSlice = valSlice.Slice(0, dataVal.Len())
}

// Accumulate any errors
Expand Down
33 changes: 33 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ type Slice struct {
Vbar []string
}

type SliceOfByte struct {
Vfoo string
Vbar []byte
}

type SliceOfAlias struct {
Vfoo string
Vbar SliceAlias
Expand Down Expand Up @@ -1654,6 +1659,34 @@ func TestSlice(t *testing.T) {
testSliceInput(t, inputStringSlicePointer, outputStringSlice)
}

func TestNotEmptyByteSlice(t *testing.T) {
t.Parallel()

inputByteSlice := map[string]interface{}{
"vfoo": "foo",
"vbar": []byte(`{"bar": "bar"}`),
}

result := SliceOfByte{
Vfoo: "another foo",
Vbar: []byte(`{"bar": "bar bar bar bar bar bar bar bar"}`),
}

err := Decode(inputByteSlice, &result)
if err != nil {
t.Fatalf("got unexpected error: %s", err)
}

expected := SliceOfByte{
Vfoo: "foo",
Vbar: []byte(`{"bar": "bar"}`),
}

if !reflect.DeepEqual(result, expected) {
t.Errorf("bad: %#v", result)
}
}

func TestInvalidSlice(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 1f85f72

Please sign in to comment.