Skip to content

Commit

Permalink
Decode: convert table key to correct type (#741)
Browse files Browse the repository at this point in the history
Fixes #740.
  • Loading branch information
oschwald authored Mar 2, 2022
1 parent 3f5d8a6 commit 3229a0a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
23 changes: 23 additions & 0 deletions internal/imported_tests/unmarshal_imported_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,29 @@ func TestUnmarshalMapWithTypedKey(t *testing.T) {
}
}

func TestUnmarshalTypeTableHeader(t *testing.T) {
testToml := []byte(`
[test]
a = 1
`)

type header string
var result map[header]map[string]int
err := toml.Unmarshal(testToml, &result)
if err != nil {
t.Errorf("Received unexpected error: %s", err)
return
}

expected := map[header]map[string]int{
"test": map[string]int{"a": 1},
}

if !reflect.DeepEqual(result, expected) {
t.Errorf("Bad unmarshal: expected %v, got %v", expected, result)
}
}

func TestUnmarshalNonPointer(t *testing.T) {
a := 1
err := toml.Unmarshal([]byte{}, a)
Expand Down
6 changes: 3 additions & 3 deletions unmarshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,9 +412,10 @@ func (d *decoder) handleKeyPart(key ast.Iterator, v reflect.Value, nextFn handle
elem = v.Elem()
return d.handleKeyPart(key, elem, nextFn, makeFn)
case reflect.Map:
vt := v.Type()

// Create the key for the map element. For now assume it's a string.
mk := reflect.ValueOf(string(key.Node().Data))
// Create the key for the map element. Convert to key type.
mk := reflect.ValueOf(string(key.Node().Data)).Convert(vt.Key())

// If the map does not exist, create it.
if v.IsNil() {
Expand All @@ -431,7 +432,6 @@ func (d *decoder) handleKeyPart(key ast.Iterator, v reflect.Value, nextFn handle
// map[string]interface{} or a []interface{} depending on whether
// this is the last part of the array table key.

vt := v.Type()
t := vt.Elem()
if t.Kind() == reflect.Interface {
mv = makeFn()
Expand Down

0 comments on commit 3229a0a

Please sign in to comment.