Tree.Marshal returns the TOML encoding of Tree (#306)

The Tree.Marshal tried to marshal the Tree struct itself rather than the nodes being part of the tree.

Fixes #295
This commit is contained in:
Marcin Białoń
2019-09-26 22:39:15 +02:00
committed by Thomas Pelletier
parent 091e2dc498
commit 75654e60b8
3 changed files with 31 additions and 5 deletions
+5 -2
View File
@@ -445,8 +445,11 @@ func (t *Tree) Unmarshal(v interface{}) error {
// See Marshal() documentation for types mapping table.
func (t *Tree) Marshal() ([]byte, error) {
var buf bytes.Buffer
err := NewEncoder(&buf).Encode(t)
return buf.Bytes(), err
_, err := t.WriteTo(&buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Unmarshal parses the TOML-encoded data and stores the result in the value
+24
View File
@@ -1675,3 +1675,27 @@ func TestUnmarshalPreservesUnexportedFields(t *testing.T) {
}
})
}
func TestTreeMarshal(t *testing.T) {
cases := [][]byte{
basicTestToml,
marshalTestToml,
emptyTestToml,
pointerTestToml,
}
for _, expected := range cases {
t.Run("", func(t *testing.T) {
tree, err := LoadBytes(expected)
if err != nil {
t.Fatal(err)
}
result, err := tree.Marshal()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(result, expected) {
t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
}
})
}
}
+2 -3
View File
@@ -423,12 +423,11 @@ func (t *Tree) WriteTo(w io.Writer) (int64, error) {
// Output spans multiple lines, and is suitable for ingest by a TOML parser.
// If the conversion cannot be performed, ToString returns a non-nil error.
func (t *Tree) ToTomlString() (string, error) {
var buf bytes.Buffer
_, err := t.WriteTo(&buf)
b, err := t.Marshal()
if err != nil {
return "", err
}
return buf.String(), nil
return string(b), nil
}
// String generates a human-readable representation of the current tree.