mirror of
https://github.com/Dadido3/go-typst.git
synced 2025-04-11 12:13:16 +00:00
Add MarshalVariable function
This commit is contained in:
parent
ed5897c9f6
commit
d65ae34abb
@ -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 {
|
||||
|
@ -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) {
|
||||
|
Loading…
Reference in New Issue
Block a user