Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: panic when Decode's input is array and output is a slice #265

Merged
merged 2 commits into from Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion mapstructure.go
Expand Up @@ -1088,7 +1088,7 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
}

// If the input value is nil, then don't allocate since empty != nil
if dataVal.IsNil() {
if dataValKind != reflect.Array && dataVal.IsNil() {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://pkg.go.dev/reflect#Value.IsNil

The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics.

return nil
}

Expand Down
32 changes: 32 additions & 0 deletions mapstructure_test.go
Expand Up @@ -556,6 +556,38 @@ func TestDecode_EmbeddedArray(t *testing.T) {
}
}

func TestDecode_decodeSliceWithArray(t *testing.T) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry but I don't know how to add tests in this repository.
If this isn't good, please let me know.
I'll fix.

t.Parallel()

data := []struct {
title string
input interface{}
result interface{}
exp interface{}
}{
{
title: "input is array and result is slice",
input: [1]int{1},
result: []int{},
exp: []int{1},
},
}

for _, d := range data {
d := d
t.Run(d.title, func(t *testing.T) {
t.Parallel()
if err := Decode(d.input, &d.result); err != nil {
t.Fatalf("got an err: %s", err.Error())
}

if !reflect.DeepEqual(d.exp, d.result) {
t.Errorf("wanted %+v, got %+v", d.exp, d.result)
}
})
}
}

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

Expand Down