Allow unmarshaling to top level maps (#273)
This commit is contained in:
committed by
Thomas Pelletier
parent
65b27e6823
commit
1d8903f1d0
+11
-3
@@ -514,11 +514,19 @@ func (d *Decoder) SetTagName(v string) *Decoder {
|
|||||||
|
|
||||||
func (d *Decoder) unmarshal(v interface{}) error {
|
func (d *Decoder) unmarshal(v interface{}) error {
|
||||||
mtype := reflect.TypeOf(v)
|
mtype := reflect.TypeOf(v)
|
||||||
if mtype.Kind() != reflect.Ptr || mtype.Elem().Kind() != reflect.Struct {
|
if mtype.Kind() != reflect.Ptr {
|
||||||
return errors.New("Only a pointer to struct can be unmarshaled from TOML")
|
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 {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-5
@@ -1103,12 +1103,42 @@ func TestUnmarshalCustomTag(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestUnmarshalMap(t *testing.T) {
|
func TestUnmarshalMap(t *testing.T) {
|
||||||
m := make(map[string]int)
|
testToml := []byte(`
|
||||||
m["a"] = 1
|
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)
|
expected := map[string]int{
|
||||||
if err.Error() != "Only a pointer to struct can be unmarshaled from TOML" {
|
"a": 1,
|
||||||
t.Fail()
|
"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")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user