encoder: support TextMarshaler (#522)

Fixes #521
This commit is contained in:
Thomas Pelletier
2021-04-22 10:13:41 -04:00
committed by GitHub
parent 2b1c52dddd
commit e443b4fdb8
3 changed files with 52 additions and 16 deletions
@@ -4,6 +4,7 @@ package imported_tests
// defaults of v2.
import (
"fmt"
"testing"
"time"
@@ -164,3 +165,34 @@ stringlist = []
require.Equal(t, string(expected), string(result))
}
type textMarshaler struct {
FirstName string
LastName string
}
func (m textMarshaler) MarshalText() ([]byte, error) {
fullName := fmt.Sprintf("%s %s", m.FirstName, m.LastName)
return []byte(fullName), nil
}
func TestTextMarshaler(t *testing.T) {
type wrap struct {
TM textMarshaler
}
m := textMarshaler{FirstName: "Sally", LastName: "Fields"}
t.Run("at root", func(t *testing.T) {
_, err := toml.Marshal(m)
// in v2 we do not allow TextMarshaler at root
require.Error(t, err)
})
t.Run("leaf", func(t *testing.T) {
res, err := toml.Marshal(wrap{m})
require.NoError(t, err)
require.Equal(t, "TM = 'Sally Fields'\n", string(res))
})
}
@@ -612,16 +612,6 @@ func (x *IntOrString) MarshalTOML() ([]byte, error) {
return []byte(s), nil
}
type textMarshaler struct {
FirstName string
LastName string
}
func (m textMarshaler) MarshalText() ([]byte, error) {
fullName := fmt.Sprintf("%s %s", m.FirstName, m.LastName)
return []byte(fullName), nil
}
func TestUnmarshalTextMarshaler(t *testing.T) {
var nested = struct {
Friends textMarshaler `toml:"friends"`