Allow to marshal pointer to struct and map (#247)

This commit is contained in:
Andriy Senyshyn
2018-11-19 17:31:15 +02:00
committed by Thomas Pelletier
parent 0a1666a81f
commit 19cbd226da
2 changed files with 55 additions and 6 deletions
+10 -2
View File
@@ -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)
+45 -4
View File
@@ -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()
}
}