Add MarshalVariable function

This commit is contained in:
David Vogel 2024-12-19 17:16:52 +01:00
parent ed5897c9f6
commit d65ae34abb
2 changed files with 38 additions and 1 deletions

View File

@ -6,6 +6,7 @@
package typst package typst
import ( import (
"bytes"
"encoding" "encoding"
"fmt" "fmt"
"io" "io"
@ -16,7 +17,17 @@ import (
"time" "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. // VariableMarshaler can be implemented by types to support custom typst marshaling.
type VariableMarshaler interface { type VariableMarshaler interface {

View File

@ -9,6 +9,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"math" "math"
"reflect"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -17,6 +18,31 @@ import (
"github.com/google/go-cmp/cmp" "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 type VariableMarshalerType []byte
func (v VariableMarshalerType) MarshalTypstVariable() ([]byte, error) { func (v VariableMarshalerType) MarshalTypstVariable() ([]byte, error) {