From 77ce8589413d1fc280be524c8992599c42027c61 Mon Sep 17 00:00:00 2001 From: Sam Autry Date: Thu, 2 May 2024 17:39:40 -0600 Subject: [PATCH] Add Marshal Function (#405) Added the Marshal function which returns the TOML representation of the Go value as bytes along with any error that may occur while marshaling. --- encode.go | 12 ++++++++++++ encode_test.go | 7 +++++++ 2 files changed, 19 insertions(+) diff --git a/encode.go b/encode.go index 231ae63f..73366c0d 100644 --- a/encode.go +++ b/encode.go @@ -2,6 +2,7 @@ package toml import ( "bufio" + "bytes" "encoding" "encoding/json" "errors" @@ -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 diff --git a/encode_test.go b/encode_test.go index 4605e2c9..fbf17de4 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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) {