Skip to content

Commit

Permalink
Add Marshal Function (#405)
Browse files Browse the repository at this point in the history
Added the Marshal function which returns the TOML representation of the Go value as bytes along with any error that may occur while marshaling.
  • Loading branch information
samawise authored May 2, 2024
1 parent 0e879cb commit 77ce858
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
12 changes: 12 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package toml

import (
"bufio"
"bytes"
"encoding"
"encoding/json"
"errors"
Expand Down Expand Up @@ -76,6 +77,17 @@ type Marshaler interface {
MarshalTOML() ([]byte, error)
}

// Marshal returns a TOML representation of the Go value.
//
// See [Encoder] for a description of the encoding process.
func Marshal(v any) ([]byte, error) {
buff := new(bytes.Buffer)
if err := NewEncoder(buff).Encode(v); err != nil {
return nil, err
}
return buff.Bytes(), nil
}

// Encoder encodes a Go to a TOML document.
//
// The mapping between Go values and TOML values should be precisely the same as
Expand Down
7 changes: 7 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ func TestEncodeRoundTrip(t *testing.T) {
if firstBuffer.String() != secondBuffer.String() {
t.Errorf("%s\n\nIS NOT IDENTICAL TO\n\n%s", firstBuffer.String(), secondBuffer.String())
}
out, err := Marshal(inputs)
if err != nil {
t.Fatal(err)
}
if firstBuffer.String() != string(out) {
t.Errorf("%s\n\nIS NOT IDENTICAL TO\n\n%s", firstBuffer.String(), string(out))
}
}

func TestEncodeArrayHashWithNormalHashOrder(t *testing.T) {
Expand Down

0 comments on commit 77ce858

Please sign in to comment.