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

Allow unmarshaling to top level maps #273

Merged
merged 3 commits into from
Apr 25, 2019
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -514,11 +514,19 @@ func (d *Decoder) SetTagName(v string) *Decoder {

func (d *Decoder) unmarshal(v interface{}) error {
mtype := reflect.TypeOf(v)
if mtype.Kind() != reflect.Ptr || mtype.Elem().Kind() != reflect.Struct {
return errors.New("Only a pointer to struct can be unmarshaled from TOML")
if mtype.Kind() != reflect.Ptr {
return errors.New("only a pointer to struct or map can be unmarshaled from TOML")
}

sval, err := d.valueFromTree(mtype.Elem(), d.tval)
elem := mtype.Elem()

switch elem.Kind() {
case reflect.Struct, reflect.Map:
default:
return errors.New("only a pointer to struct or map can be unmarshaled from TOML")
}

sval, err := d.valueFromTree(elem, d.tval)
if err != nil {
return err
}
Expand Down
40 changes: 35 additions & 5 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1103,12 +1103,42 @@ func TestUnmarshalCustomTag(t *testing.T) {
}

func TestUnmarshalMap(t *testing.T) {
m := make(map[string]int)
m["a"] = 1
testToml := []byte(`
a = 1
b = 2
c = 3
`)
var result map[string]int
err := Unmarshal(testToml, &result)
if err != nil {
t.Errorf("Received unexpected error: %s", err)
return
}

err := Unmarshal(basicTestToml, m)
if err.Error() != "Only a pointer to struct can be unmarshaled from TOML" {
t.Fail()
expected := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}

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

func TestUnmarshalNonPointer(t *testing.T) {
a := 1
err := Unmarshal([]byte{}, a)
if err == nil {
t.Fatal("unmarshal should err when given a non pointer")
}
}

func TestUnmarshalInvalidPointerKind(t *testing.T) {
a := 1
err := Unmarshal([]byte{}, &a)
if err == nil {
t.Fatal("unmarshal should err when given an invalid pointer type")
}
}

Expand Down