diff --git a/marshal.go b/marshal.go index db5a7b4..737cc7d 100644 --- a/marshal.go +++ b/marshal.go @@ -522,7 +522,8 @@ func (e *Encoder) valueToToml(mtype reflect.Type, mval reflect.Value) (interface case isCustomMarshaler(mtype): return callCustomMarshaler(mval) case isTextMarshaler(mtype): - return callTextMarshaler(mval) + b, err := callTextMarshaler(mval) + return string(b), err default: return e.valueToToml(mtype.Elem(), mval.Elem()) } @@ -534,7 +535,8 @@ func (e *Encoder) valueToToml(mtype reflect.Type, mval reflect.Value) (interface case isCustomMarshaler(mtype): return callCustomMarshaler(mval) case isTextMarshaler(mtype): - return callTextMarshaler(mval) + b, err := callTextMarshaler(mval) + return string(b), err case isTree(mtype): return e.valueToTree(mtype, mval) case isOtherSequence(mtype), isCustomMarshalerSequence(mtype), isTextMarshalerSequence(mtype): diff --git a/marshal_test.go b/marshal_test.go index c5a440d..061c490 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -979,6 +979,40 @@ func TestCustomMarshaler(t *testing.T) { } } +type IntOrString string + +func (x *IntOrString) MarshalTOML() ([]byte, error) { + s := *(*string)(x) + _, err := strconv.Atoi(s) + if err != nil { + return []byte(fmt.Sprintf(`"%s"`, s)), nil + } + return []byte(s), nil +} + +func TestNestedCustomMarshaler(t *testing.T) { + num := IntOrString("100") + str := IntOrString("hello") + var parent = struct { + IntField *IntOrString `toml:"int"` + StringField *IntOrString `toml:"string"` + }{ + &num, + &str, + } + + result, err := Marshal(parent) + if err != nil { + t.Fatal(err) + } + expected := `int = 100 +string = "hello" +` + if !bytes.Equal(result, []byte(expected)) { + t.Errorf("Bad nested text marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) + } +} + type textMarshaler struct { FirstName string LastName string @@ -1079,7 +1113,7 @@ type customPointerMarshaler struct { } func (m *customPointerMarshaler) MarshalTOML() ([]byte, error) { - return []byte("hidden"), nil + return []byte(`"hidden"`), nil } type textPointerMarshaler struct { diff --git a/tomltree_write.go b/tomltree_write.go index 2d6487e..ae6dac4 100644 --- a/tomltree_write.go +++ b/tomltree_write.go @@ -163,7 +163,7 @@ func tomlValueStringRepresentation(v interface{}, commented string, indent strin return "\"" + encodeTomlString(value) + "\"", nil case []byte: b, _ := v.([]byte) - return tomlValueStringRepresentation(string(b), commented, indent, ord, arraysOneElementPerLine) + return string(b), nil case bool: if value { return "true", nil