From d65ae34abb949be587cc52aed4311ab1bde24adf Mon Sep 17 00:00:00 2001 From: David Vogel Date: Thu, 19 Dec 2024 17:16:52 +0100 Subject: [PATCH] Add MarshalVariable function --- variable-encoder.go | 13 ++++++++++++- variable-encoder_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/variable-encoder.go b/variable-encoder.go index c08f1e9..76cd335 100644 --- a/variable-encoder.go +++ b/variable-encoder.go @@ -6,6 +6,7 @@ package typst import ( + "bytes" "encoding" "fmt" "io" @@ -16,7 +17,17 @@ import ( "time" ) -// TODO: Add simple marshal function that returns a byte slice +// MarshalVariable takes any go type and returns a typst markup representation as a byte slice. +func MarshalVariable(v any) ([]byte, error) { + var buf bytes.Buffer + + enc := NewVariableEncoder(&buf) + if err := enc.Encode(v); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} // VariableMarshaler can be implemented by types to support custom typst marshaling. type VariableMarshaler interface { diff --git a/variable-encoder_test.go b/variable-encoder_test.go index 14da265..d66f06a 100644 --- a/variable-encoder_test.go +++ b/variable-encoder_test.go @@ -9,6 +9,7 @@ import ( "bytes" "fmt" "math" + "reflect" "strings" "testing" "time" @@ -17,6 +18,31 @@ import ( "github.com/google/go-cmp/cmp" ) +func TestMarshalVariable(t *testing.T) { + tests := []struct { + name string + arg any + want []byte + wantErr bool + }{ + {"nil", nil, []byte(`none`), false}, + {"string", "Hey\nThere!", []byte(`"Hey\nThere!"`), false}, + {"int", -123, []byte(`{-123}`), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := typst.MarshalVariable(tt.arg) + if (err != nil) != tt.wantErr { + t.Errorf("MarshalVariable() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MarshalVariable() = %v, want %v", got, tt.want) + } + }) + } +} + type VariableMarshalerType []byte func (v VariableMarshalerType) MarshalTypstVariable() ([]byte, error) {