| 1 |
package json_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"runtime" |
| 7 |
"sync" |
| 8 |
"testing" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/goccy/go-json" |
| 12 |
) |
| 13 |
|
| 14 |
type marshalOfInner struct { |
| 15 |
ID int |
| 16 |
Tags []string |
| 17 |
} |
| 18 |
|
| 19 |
type marshalOfStruct struct { |
| 20 |
Name string |
| 21 |
Inner marshalOfInner |
| 22 |
Ptr *marshalOfInner |
| 23 |
Any any |
| 24 |
Map map[string]int |
| 25 |
List []marshalOfInner |
| 26 |
Skip string `json:"-"` |
| 27 |
Omit string `json:"omit,omitempty"` |
| 28 |
} |
| 29 |
|
| 30 |
// marshalOfPtrReceiver has MarshalJSON on the pointer receiver, which is not called for a value which is not |
| 31 |
// addressable, such as the argument of Marshal. |
| 32 |
type marshalOfPtrReceiver struct{ V int } |
| 33 |
|
| 34 |
func (v *marshalOfPtrReceiver) MarshalJSON() ([]byte, error) { |
| 35 |
return []byte(`"pointer receiver"`), nil |
| 36 |
} |
| 37 |
|
| 38 |
type marshalOfValueReceiver struct{ V int } |
| 39 |
|
| 40 |
func (v marshalOfValueReceiver) MarshalJSON() ([]byte, error) { |
| 41 |
return []byte(fmt.Sprintf(`"value receiver %d"`, v.V)), nil |
| 42 |
} |
| 43 |
|
| 44 |
type marshalOfHolder struct { |
| 45 |
P marshalOfPtrReceiver |
| 46 |
V marshalOfValueReceiver |
| 47 |
} |
| 48 |
|
| 49 |
type marshalOfSinglePointer struct{ P *int } |
| 50 |
|
| 51 |
// marshalOfNested calls MarshalOf for the same type while it is encoded. |
| 52 |
type marshalOfNested struct{ Depth int } |
| 53 |
|
| 54 |
func (v marshalOfNested) MarshalJSON() ([]byte, error) { |
| 55 |
if v.Depth == 0 { |
| 56 |
return []byte(`"leaf"`), nil |
| 57 |
} |
| 58 |
b, err := json.MarshalOf(marshalOfNestedHolder{Child: marshalOfNested{Depth: v.Depth - 1}, Pad: "p"}) |
| 59 |
if err != nil { |
| 60 |
return nil, err |
| 61 |
} |
| 62 |
return b, nil |
| 63 |
} |
| 64 |
|
| 65 |
type marshalOfNestedHolder struct { |
| 66 |
Child marshalOfNested |
| 67 |
Pad string |
| 68 |
} |
| 69 |
|
| 70 |
func assertMarshalOf[T any](t *testing.T, name string, v T, optFuncs ...json.EncodeOptionFunc) { |
| 71 |
t.Helper() |
| 72 |
t.Run(name, func(t *testing.T) { |
| 73 |
t.Helper() |
| 74 |
expected, expectedErr := json.MarshalWithOption(v, optFuncs...) |
| 75 |
// twice, so that the value which is reused is used. |
| 76 |
for i := 0; i < 2; i++ { |
| 77 |
got, err := json.MarshalOf(v, optFuncs...) |
| 78 |
if (expectedErr == nil) != (err == nil) { |
| 79 |
t.Fatalf("expected error %v but got %v", expectedErr, err) |
| 80 |
} |
| 81 |
if !bytes.Equal(expected, got) { |
| 82 |
t.Fatalf("expected %s but got %s", expected, got) |
| 83 |
} |
| 84 |
} |
| 85 |
}) |
| 86 |
} |
| 87 |
|
| 88 |
func TestMarshalOf(t *testing.T) { |
| 89 |
n := 10 |
| 90 |
inner := marshalOfInner{ID: 1, Tags: []string{"a", "b"}} |
| 91 |
full := marshalOfStruct{ |
| 92 |
Name: "name", |
| 93 |
Inner: inner, |
| 94 |
Ptr: &inner, |
| 95 |
Any: inner, |
| 96 |
Map: map[string]int{"b": 2, "a": 1}, |
| 97 |
List: []marshalOfInner{inner, {}}, |
| 98 |
Skip: "skip", |
| 99 |
} |
| 100 |
var nilAny any |
| 101 |
var nilStringer fmt.Stringer |
| 102 |
var nilPtr *marshalOfStruct |
| 103 |
var nilMap map[string]int |
| 104 |
var nilSlice []int |
| 105 |
|
| 106 |
assertMarshalOf(t, "struct", full) |
| 107 |
assertMarshalOf(t, "zero struct", marshalOfStruct{}) |
| 108 |
assertMarshalOf(t, "pointer to struct", &full) |
| 109 |
assertMarshalOf(t, "nil pointer", nilPtr) |
| 110 |
assertMarshalOf(t, "pointer to pointer", func() **marshalOfStruct { p := &full; return &p }()) |
| 111 |
assertMarshalOf(t, "int", 42) |
| 112 |
assertMarshalOf(t, "float", 1.5) |
| 113 |
assertMarshalOf(t, "string", "<str>") |
| 114 |
assertMarshalOf(t, "bool", true) |
| 115 |
assertMarshalOf(t, "bytes", []byte("bytes")) |
| 116 |
assertMarshalOf(t, "slice", []marshalOfInner{inner, inner}) |
| 117 |
assertMarshalOf(t, "nil slice", nilSlice) |
| 118 |
assertMarshalOf(t, "array", [3]int{1, 2, 3}) |
| 119 |
assertMarshalOf(t, "empty array", [0]int{}) |
| 120 |
assertMarshalOf(t, "array of a pointer", [1]*int{&n}) |
| 121 |
assertMarshalOf(t, "large array", [1024]int{1, 2, 3}) |
| 122 |
assertMarshalOf(t, "map", map[string]marshalOfInner{"x": inner}) |
| 123 |
assertMarshalOf(t, "nil map", nilMap) |
| 124 |
assertMarshalOf(t, "struct of a pointer", marshalOfSinglePointer{P: &n}) |
| 125 |
assertMarshalOf(t, "struct of a nil pointer", marshalOfSinglePointer{}) |
| 126 |
assertMarshalOf(t, "interface", any(full)) |
| 127 |
assertMarshalOf(t, "nil interface", nilAny) |
| 128 |
assertMarshalOf(t, "nil non-empty interface", nilStringer) |
| 129 |
assertMarshalOf(t, "non-empty interface", fmt.Stringer(time.Second)) |
| 130 |
assertMarshalOf(t, "pointer receiver marshaler", marshalOfPtrReceiver{V: 1}) |
| 131 |
assertMarshalOf(t, "pointer to pointer receiver marshaler", &marshalOfPtrReceiver{V: 1}) |
| 132 |
assertMarshalOf(t, "value receiver marshaler", marshalOfValueReceiver{V: 1}) |
| 133 |
assertMarshalOf(t, "marshalers in a struct", marshalOfHolder{V: marshalOfValueReceiver{V: 2}}) |
| 134 |
assertMarshalOf(t, "marshalers in a slice", []marshalOfHolder{{}, {}}) |
| 135 |
assertMarshalOf(t, "marshaler which calls MarshalOf", marshalOfNestedHolder{Child: marshalOfNested{Depth: 5}}) |
| 136 |
assertMarshalOf(t, "time", time.Date(2026, 9, 21, 1, 2, 3, 0, time.UTC)) |
| 137 |
assertMarshalOf(t, "unsupported type", struct{ C chan int }{}) |
| 138 |
assertMarshalOf(t, "unsupported value", struct{ F float64 }{F: nan()}) |
| 139 |
|
| 140 |
assertMarshalOf(t, "option: unordered map", map[string]int{"a": 1}, json.UnorderedMap()) |
| 141 |
assertMarshalOf(t, "option: disable html escape", "<str>", json.DisableHTMLEscape()) |
| 142 |
assertMarshalOf(t, "option: colorize", full, json.Colorize(json.DefaultColorScheme)) |
| 143 |
} |
| 144 |
|
| 145 |
func nan() float64 { |
| 146 |
var zero float64 |
| 147 |
return zero / zero |
| 148 |
} |
| 149 |
|
| 150 |
func TestMarshalOfAllocs(t *testing.T) { |
| 151 |
if raceEnabled { |
| 152 |
t.Skip("the runtime context, which keeps the value to reuse, is dropped from its pool at random") |
| 153 |
} |
| 154 |
inner := marshalOfInner{ID: 1, Tags: []string{"a", "b"}} |
| 155 |
v := marshalOfStruct{Name: "name", Inner: inner, Ptr: &inner, List: []marshalOfInner{inner}} |
| 156 |
if _, err := json.MarshalOf(v); err != nil { |
| 157 |
t.Fatal(err) |
| 158 |
} |
| 159 |
// the result is the only allocation. |
| 160 |
if allocs := testing.AllocsPerRun(100, func() { _, _ = json.MarshalOf(v) }); allocs > 1 { |
| 161 |
t.Fatalf("MarshalOf: %v allocations", allocs) |
| 162 |
} |
| 163 |
if allocs := testing.AllocsPerRun(100, func() { _, _ = json.MarshalOf(inner) }); allocs > 1 { |
| 164 |
t.Fatalf("MarshalOf after another type: %v allocations", allocs) |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
func TestMarshalOfConcurrently(t *testing.T) { |
| 169 |
inner := marshalOfInner{ID: 1, Tags: []string{"a", "b"}} |
| 170 |
expectedInner, _ := json.Marshal(inner) |
| 171 |
var wg sync.WaitGroup |
| 172 |
for g := 0; g < 32; g++ { |
| 173 |
wg.Add(1) |
| 174 |
go func(g int) { |
| 175 |
defer wg.Done() |
| 176 |
for i := 0; i < 200; i++ { |
| 177 |
// the types alternate, so that the value a runtime context keeps is replaced. |
| 178 |
v := marshalOfStruct{Name: fmt.Sprint(g, "-", i), Inner: inner, List: []marshalOfInner{inner}} |
| 179 |
expected, _ := json.Marshal(v) |
| 180 |
got, err := json.MarshalOf(v) |
| 181 |
if err != nil || !bytes.Equal(expected, got) { |
| 182 |
t.Errorf("expected %s but got %s ( %v )", expected, got, err) |
| 183 |
return |
| 184 |
} |
| 185 |
got, err = json.MarshalOf(inner) |
| 186 |
if err != nil || !bytes.Equal(expectedInner, got) { |
| 187 |
t.Errorf("expected %s but got %s ( %v )", expectedInner, got, err) |
| 188 |
return |
| 189 |
} |
| 190 |
} |
| 191 |
}(g) |
| 192 |
} |
| 193 |
wg.Wait() |
| 194 |
} |
| 195 |
|
| 196 |
// MarshalOf copies the value to a value which is reused. It must not keep what the value refers to alive. |
| 197 |
func TestMarshalOfDoesNotKeepValueAlive(t *testing.T) { |
| 198 |
for _, test := range []struct { |
| 199 |
name string |
| 200 |
broken bool |
| 201 |
}{ |
| 202 |
{name: "encoded"}, |
| 203 |
{name: "error", broken: true}, |
| 204 |
} { |
| 205 |
t.Run(test.name, func(t *testing.T) { |
| 206 |
collected := make(chan struct{}, 1) |
| 207 |
func() { |
| 208 |
inner := &marshalOfInner{ID: 1} |
| 209 |
runtime.SetFinalizer(inner, func(*marshalOfInner) { collected <- struct{}{} }) |
| 210 |
v := marshalOfStruct{Ptr: inner} |
| 211 |
if test.broken { |
| 212 |
v.Any = make(chan int) |
| 213 |
} |
| 214 |
if _, err := json.MarshalOf(v); (err != nil) != test.broken { |
| 215 |
t.Fatalf("unexpected error: %v", err) |
| 216 |
} |
| 217 |
}() |
| 218 |
// Only one GC: the pool releases what it has after a few, whatever it holds. |
| 219 |
runtime.GC() |
| 220 |
select { |
| 221 |
case <-collected: |
| 222 |
case <-time.After(10 * time.Second): |
| 223 |
t.Fatal("the value is kept alive after the encoding") |
| 224 |
} |
| 225 |
}) |
| 226 |
} |
| 227 |
} |