fix issue#414

This commit is contained in:
AllenX2018
2020-06-11 12:08:04 +08:00
parent 06838de5d2
commit 05bf3807d3
3 changed files with 40 additions and 4 deletions
+4 -2
View File
@@ -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):
+35 -1
View File
@@ -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 {
+1 -1
View File
@@ -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