Skip to content

Commit

Permalink
fix issue#414
Browse files Browse the repository at this point in the history
  • Loading branch information
AllenX2018 committed Jun 11, 2020
1 parent 06838de commit 05bf380
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
6 changes: 4 additions & 2 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand All @@ -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):
Expand Down
36 changes: 35 additions & 1 deletion marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1079,7 +1113,7 @@ type customPointerMarshaler struct {
}

func (m *customPointerMarshaler) MarshalTOML() ([]byte, error) {
return []byte("hidden"), nil
return []byte(`"hidden"`), nil
}

type textPointerMarshaler struct {
Expand Down
2 changes: 1 addition & 1 deletion tomltree_write.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 05bf380

Please sign in to comment.