diff --git a/marshal.go b/marshal.go index 3e92a57..e7ef802 100644 --- a/marshal.go +++ b/marshal.go @@ -244,9 +244,17 @@ func (e *Encoder) SetTagMultiline(v string) *Encoder { func (e *Encoder) marshal(v interface{}) ([]byte, error) { mtype := reflect.TypeOf(v) - if mtype.Kind() != reflect.Struct { - return []byte{}, errors.New("Only a struct can be marshaled to TOML") + + switch mtype.Kind() { + case reflect.Struct, reflect.Map: + case reflect.Ptr: + if mtype.Elem().Kind() != reflect.Struct { + return []byte{}, errors.New("Only pointer to struct can be marshaled to TOML") + } + default: + return []byte{}, errors.New("Only a struct or map can be marshaled to TOML") } + sval := reflect.ValueOf(v) if isCustomMarshaler(mtype) { return callCustomMarshaler(sval) diff --git a/marshal_test.go b/marshal_test.go index 9c401b3..87d8217 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -53,6 +53,17 @@ func TestBasicMarshal(t *testing.T) { } } +func TestBasicMarshalWithPointer(t *testing.T) { + result, err := Marshal(&basicTestData) + if err != nil { + t.Fatal(err) + } + expected := basicTestToml + if !bytes.Equal(result, expected) { + t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) + } +} + func TestBasicUnmarshal(t *testing.T) { result := basicMarshalTestStruct{} err := Unmarshal(basicTestToml, &result) @@ -163,6 +174,17 @@ func TestDocMarshal(t *testing.T) { } } +func TestDocMarshalPointer(t *testing.T) { + result, err := Marshal(&docData) + if err != nil { + t.Fatal(err) + } + expected, _ := ioutil.ReadFile("marshal_test.toml") + if !bytes.Equal(result, expected) { + t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) + } +} + func TestDocUnmarshal(t *testing.T) { result := testDoc{} tomlData, _ := ioutil.ReadFile("marshal_test.toml") @@ -992,13 +1014,32 @@ func TestUnmarshalMap(t *testing.T) { } } -func TestMarshalMap(t *testing.T) { - m := make(map[string]int) - m["a"] = 1 +func TestMarshalSlice(t *testing.T) { + m := make([]int, 1) + m[0] = 1 + + var buf bytes.Buffer + err := NewEncoder(&buf).Encode(&m) + if err == nil { + t.Error("expected error, got nil") + return + } + if err.Error() != "Only pointer to struct can be marshaled to TOML" { + t.Fail() + } +} + +func TestMarshalSlicePointer(t *testing.T) { + m := make([]int, 1) + m[0] = 1 var buf bytes.Buffer err := NewEncoder(&buf).Encode(m) - if err.Error() != "Only a struct can be marshaled to TOML" { + if err == nil { + t.Error("expected error, got nil") + return + } + if err.Error() != "Only a struct or map can be marshaled to TOML" { t.Fail() } }