Debian Codegraph @

decode_retention_test.go

raw
1 //go:build go1.24
2
3 package json_test
4
5 import (
6 "runtime"
7 "strings"
8 "testing"
9 "weak"
10
11 json "github.com/goccy/go-json"
12 )
13
14 // The decoders keep buffers and contexts in pools between the calls. Nothing in them may refer to
15 // what a call decoded: a decoded string refers to the copy of the input, so a pointer left behind
16 // keeps the whole input of a previous call alive, and a program which decodes large inputs at a high
17 // rate keeps as many of them alive as its pools hold objects.
18
19 type retentionNode struct {
20 Name string
21 Kids []*retentionNode
22 }
23
24 func retentionInput() []byte {
25 var b strings.Builder
26 b.WriteString(`{"Name":"root","Kids":[`)
27 for i := 0; i < 64; i++ {
28 if i > 0 {
29 b.WriteString(",")
30 }
31 b.WriteString(`{"Name":"` + strings.Repeat("n", 64) + `","Kids":[{"Name":"leaf","Kids":[]},{"Name":"leaf","Kids":[]}]}`)
32 }
33 b.WriteString(`]}`)
34 return []byte(b.String())
35 }
36
37 func decodedIsCollected(t *testing.T, decode func() any) {
38 t.Helper()
39 var refs []weak.Pointer[retentionNode]
40 for i := 0; i < 8; i++ {
41 switch v := decode().(type) {
42 case *retentionNode:
43 refs = append(refs, weak.Make(v), weak.Make(v.Kids[0]), weak.Make(v.Kids[63].Kids[1]))
44 case map[string]any:
45 // the values of interface{} are checked through the node decoded beside them
46 refs = append(refs, weak.Make(v["node"].(*retentionNode)))
47 }
48 }
49 // A pool keeps its objects over one collection ( its victim cache ): what they refer to is alive
50 // through that collection, so one collection tells whether a pooled object refers to a decoded value.
51 runtime.GC()
52 for i, r := range refs {
53 if r.Value() != nil {
54 t.Fatalf("a value decoded by a previous call is still alive ( %d )", i)
55 }
56 }
57 }
58
59 func TestDecodeKeepsNothingOfPreviousCall(t *testing.T) {
60 input := retentionInput()
61 t.Run("Unmarshal", func(t *testing.T) {
62 decodedIsCollected(t, func() any {
63 v := new(retentionNode)
64 if err := json.Unmarshal(input, v); err != nil {
65 t.Fatal(err)
66 }
67 return v
68 })
69 })
70 t.Run("Decoder", func(t *testing.T) {
71 decodedIsCollected(t, func() any {
72 v := new(retentionNode)
73 if err := json.NewDecoder(strings.NewReader(string(input))).Decode(v); err != nil {
74 t.Fatal(err)
75 }
76 return v
77 })
78 })
79 }