From d0d001625c115f3e000fd782a3715ea3ae883ef6 Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Mon, 25 Oct 2021 16:47:10 -0400 Subject: [PATCH] unmarshal: don't panic when storing table in slice (#641) New error message: ``` toml: cannot store a table in a slice 1| [things] | ~~~~~~ cannot store a table in a slice 2| foo = "bar" ``` Fixes #623 --- unmarshaler.go | 3 +++ unmarshaler_test.go | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/unmarshaler.go b/unmarshaler.go index 6e3abc6..5d589fa 100644 --- a/unmarshaler.go +++ b/unmarshaler.go @@ -488,6 +488,9 @@ func (d *decoder) handleArrayTablePart(key ast.Iterator, v reflect.Value) (refle // cannot handle it. func (d *decoder) handleTable(key ast.Iterator, v reflect.Value) (reflect.Value, error) { if v.Kind() == reflect.Slice { + if v.Len() == 0 { + return reflect.Value{}, newDecodeError(key.Node().Data, "cannot store a table in a slice") + } elem := v.Index(v.Len() - 1) x, err := d.handleTable(key, elem) if err != nil { diff --git a/unmarshaler_test.go b/unmarshaler_test.go index 362e937..b0ae20e 100644 --- a/unmarshaler_test.go +++ b/unmarshaler_test.go @@ -1810,6 +1810,18 @@ func TestIssue602(t *testing.T) { require.Equal(t, expected, v) } +func TestIssue623(t *testing.T) { + definition := struct { + Things []string + }{} + + values := `[things] +foo = "bar"` + + err := toml.Unmarshal([]byte(values), &definition) + require.Error(t, err) +} + //nolint:funlen func TestUnmarshalDecodeErrors(t *testing.T) { examples := []struct {