Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add support for JSON marshalling #21

Merged
merged 3 commits into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions scripts/gen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path"
"strconv"
"strings"
"text/template"
)
Expand All @@ -14,8 +15,6 @@ import (
type templateContext struct {
Indexes []int
Len int
TypeName string
TypeDecl string
GenericTypesForward string
}

Expand All @@ -24,7 +23,7 @@ const maxTupleLength = 9

var funcMap = template.FuncMap{
"quote": func(value interface{}) string {
return fmt.Sprintf("%q", fmt.Sprint(value))
return strconv.Quote(fmt.Sprint(value))
},
"inc": func(value int) int {
return value + 1
Expand All @@ -43,6 +42,14 @@ var funcMap = template.FuncMap{
},
"genericTypesDecl": genTypesDecl,
"genericTypesDeclGenericConstraint": genTypesDeclGenericConstraint,
"buildSingleTypedOverload": func(indexes []int, typ string) string {
typesArray := make([]string, 0, len(indexes))
for range indexes {
typesArray = append(typesArray, typ)
}

return fmt.Sprintf("T%d[%s]", len(indexes), strings.Join(typesArray, ", "))
},
}

//go:embed tuple.tpl
Expand Down
23 changes: 23 additions & 0 deletions scripts/gen/tuple.tpl
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package tuple

import (
"encoding/json"
"fmt"

"golang.org/x/exp/constraints"
)

Expand Down Expand Up @@ -229,3 +231,24 @@ func GreaterOrEqual{{.Len}}[{{genericTypesDecl .Indexes "constraints.Ordered"}}]
func GreaterOrEqual{{.Len}}C[{{genericTypesDeclGenericConstraint .Indexes "Comparable"}}](host, guest T{{.Len}}[{{.GenericTypesForward}}]) bool {
return Compare{{.Len}}C(host, guest).GE()
}

// MarshalJSON marshals the tuple into a JSON array.
func (t {{$typeRef}}) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Slice())
}

// MarshalJSON unmarshals the tuple from a JSON array.
func (t *{{$typeRef}}) UnmarshalJSON(data []byte) error {
var slice []any
if err := json.Unmarshal(data, &slice); err != nil {
return err
}

unmarshalled, err := FromSlice{{.Len}}[{{.GenericTypesForward}}](slice)
if err != nil {
return err
}

*t = unmarshalled
return nil
}
103 changes: 99 additions & 4 deletions scripts/gen/tuple_test.tpl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tuple

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -9,10 +10,11 @@ import (
{{/* These variables can be used when the context of dot changes. */}}
{{$indexes := .Indexes}}
{{$len := .Len}}
{{$stringOverload := buildSingleTypedOverload $indexes "string"}}

func TestT{{.Len}}_New(t *testing.T) {
tup := New{{.Len}}({{range .Indexes}}{{. | quote}},{{end}})
require.Equal(t, T{{.Len}}[{{range $i, $index := .Indexes}}{{if gt $i 0}}, {{end}}string{{end}}]{
require.Equal(t, {{$stringOverload}}{
{{range .Indexes -}}
V{{.}}: {{. | quote}},
{{end}}
Expand Down Expand Up @@ -227,7 +229,7 @@ func TestT{{.Len}}_String(t *testing.T) {

func TestT{{.Len}}_GoString(t *testing.T) {
tup := New{{.Len}}({{range .Indexes}}{{. | quote}},{{end}})
require.Equal(t, `tuple.T{{.Len}}[{{range $i, $index := .Indexes}}{{if gt $i 0}}, {{end}}string{{end}}]{
require.Equal(t, `tuple.{{$stringOverload}}{
{{- range $i, $index := .Indexes -}}
{{- if gt $i 0}}, {{end -}}
V{{$index}}: {{$index | quote}}
Expand Down Expand Up @@ -281,7 +283,7 @@ func TestT{{.Len}}_FromArrayX(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
do := func () T{{.Len}}[{{range $i, $index := .Indexes}}{{if gt $i 0}}, {{end}}string{{end}}] {
do := func () {{$stringOverload}} {
return FromArray{{.Len}}X[{{range $i, $index := .Indexes}}{{if gt $i 0}}, {{end}}string{{end}}](tt.array)
}

Expand Down Expand Up @@ -393,7 +395,7 @@ func TestT{{.Len}}_FromSliceX(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
do := func () T{{.Len}}[{{range $i, $index := .Indexes}}{{if gt $i 0}}, {{end}}string{{end}}] {
do := func () {{$stringOverload}} {
return FromSlice{{.Len}}X[{{range $i, $index := .Indexes}}{{if gt $i 0}}, {{end}}string{{end}}](tt.slice)
}

Expand Down Expand Up @@ -472,3 +474,96 @@ func TestT{{.Len}}_FromSlice(t *testing.T) {
})
}
}

func TestT{{.Len}}_MarshalJSON(t *testing.T) {
tup := New{{.Len}}({{range .Indexes}}{{. | quote}},{{end}})

got, err := json.Marshal(tup)
require.NoError(t, err)
require.Equal(t, got, []byte(`[{{range .Indexes}}{{if ne . 1}},{{end}}{{. | quote}}{{end}}]`))
}

func TestT{{.Len}}_UnmarshalJSON(t *testing.T) {
tests := []struct{
name string
data []byte
want {{$stringOverload}}
wantErr bool
}{
{
name: "nil data",
data: nil,
wantErr: true,
},
{
name: "empty data",
data: []byte{},
wantErr: true,
},
{
name: "string data",
data: []byte(`"hi"`),
wantErr: true,
},
{
name: "empty json array",
data: []byte(`[]`),
wantErr: true,
},
{
name: "longer json array",
data: []byte(`["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]`),
wantErr: true,
},
{
name: "json array of invalid types",
data: []byte(`[{{range $.Indexes}}{{if ne . 1}},{{end}}{{.}}{{end}}]`),
wantErr: true,
},
{{if gt .Len 1 -}}
{
name: "json array with 1 invalid type",
data: []byte(`[{{range $.Indexes}}{{if ne . 1}},{{end}}{{if eq . 1}}{{.}}{{else}}{{. | quote}}{{end}}{{end}}]`),
wantErr: true,
},
{{- end}}
{
name: "json array of valid types",
data: []byte(`[{{range $.Indexes}}{{if ne . 1}},{{end}}{{. | quote}}{{end}}]`),
want: New{{.Len}}({{range .Indexes}}{{. | quote}},{{end}}),
wantErr: false,
},
{
name: "json object of valid types",
data: []byte(`{{"{"}}{{range $.Indexes}}{{if ne . 1}},{{end}}"V{{.}}": {{. | quote}}{{end}}{{"}"}}`),
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got {{$stringOverload}}
err := json.Unmarshal(tt.data, &got)
if tt.wantErr {
require.Error(t, err)
return
}

require.NoError(t, err)
require.Equal(t, tt.want, got)
})
}
}

func TestT{{.Len}}_Marshal_Unmarshal(t *testing.T) {
tup := New{{.Len}}({{range .Indexes}}{{. | quote}},{{end}})

marshalled, err := json.Marshal(tup)
require.NoError(t, err)

var unmarshalled {{$stringOverload}}
err = json.Unmarshal(marshalled, &unmarshalled)

require.NoError(t, err)
require.Equal(t, tup, unmarshalled)
}
23 changes: 23 additions & 0 deletions tuple1.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package tuple

import (
"encoding/json"
"fmt"

"golang.org/x/exp/constraints"
)

Expand Down Expand Up @@ -194,3 +196,24 @@ func GreaterOrEqual1[Ty1 constraints.Ordered](host, guest T1[Ty1]) bool {
func GreaterOrEqual1C[Ty1 Comparable[Ty1]](host, guest T1[Ty1]) bool {
return Compare1C(host, guest).GE()
}

// MarshalJSON marshals the tuple into a JSON array.
func (t T1[Ty1]) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Slice())
}

// MarshalJSON unmarshals the tuple from a JSON array.
func (t *T1[Ty1]) UnmarshalJSON(data []byte) error {
var slice []any
if err := json.Unmarshal(data, &slice); err != nil {
return err
}

unmarshalled, err := FromSlice1[Ty1](slice)
if err != nil {
return err
}

*t = unmarshalled
return nil
}
88 changes: 88 additions & 0 deletions tuple1_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tuple

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -419,3 +420,90 @@ func TestT1_FromSlice(t *testing.T) {
})
}
}

func TestT1_MarshalJSON(t *testing.T) {
tup := New1("1")

got, err := json.Marshal(tup)
require.NoError(t, err)
require.Equal(t, got, []byte(`["1"]`))
}

func TestT1_UnmarshalJSON(t *testing.T) {
tests := []struct {
name string
data []byte
want T1[string]
wantErr bool
}{
{
name: "nil data",
data: nil,
wantErr: true,
},
{
name: "empty data",
data: []byte{},
wantErr: true,
},
{
name: "string data",
data: []byte(`"hi"`),
wantErr: true,
},
{
name: "empty json array",
data: []byte(`[]`),
wantErr: true,
},
{
name: "longer json array",
data: []byte(`["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]`),
wantErr: true,
},
{
name: "json array of invalid types",
data: []byte(`[1]`),
wantErr: true,
},

{
name: "json array of valid types",
data: []byte(`["1"]`),
want: New1("1"),
wantErr: false,
},
{
name: "json object of valid types",
data: []byte(`{"V1": "1"}`),
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got T1[string]
err := json.Unmarshal(tt.data, &got)
if tt.wantErr {
require.Error(t, err)
return
}

require.NoError(t, err)
require.Equal(t, tt.want, got)
})
}
}

func TestT1_Marshal_Unmarshal(t *testing.T) {
tup := New1("1")

marshalled, err := json.Marshal(tup)
require.NoError(t, err)

var unmarshalled T1[string]
err = json.Unmarshal(marshalled, &unmarshalled)

require.NoError(t, err)
require.Equal(t, tup, unmarshalled)
}
23 changes: 23 additions & 0 deletions tuple2.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package tuple

import (
"encoding/json"
"fmt"

"golang.org/x/exp/constraints"
)

Expand Down Expand Up @@ -210,3 +212,24 @@ func GreaterOrEqual2[Ty1, Ty2 constraints.Ordered](host, guest T2[Ty1, Ty2]) boo
func GreaterOrEqual2C[Ty1 Comparable[Ty1], Ty2 Comparable[Ty2]](host, guest T2[Ty1, Ty2]) bool {
return Compare2C(host, guest).GE()
}

// MarshalJSON marshals the tuple into a JSON array.
func (t T2[Ty1, Ty2]) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Slice())
}

// MarshalJSON unmarshals the tuple from a JSON array.
func (t *T2[Ty1, Ty2]) UnmarshalJSON(data []byte) error {
var slice []any
if err := json.Unmarshal(data, &slice); err != nil {
return err
}

unmarshalled, err := FromSlice2[Ty1, Ty2](slice)
if err != nil {
return err
}

*t = unmarshalled
return nil
}
Loading