Debian Codegraph @

decode_pointer_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "reflect"
6 "runtime"
7 "strconv"
8 "strings"
9 "testing"
10 "time"
11
12 json "github.com/goccy/go-json"
13 )
14
15 type pointeeLevel int8
16
17 type pointeeName string
18
19 func (n pointeeName) Upper() string { return strings.ToUpper(string(n)) }
20
21 // pointeeComplex and pointeeComplex64 are of the complex kinds, which are decoded only by their methods.
22 type pointeeComplex complex128
23
24 func (c *pointeeComplex) UnmarshalJSON(b []byte) error {
25 f, err := strconv.ParseFloat(string(b), 64)
26 *c = pointeeComplex(complex(f, -f))
27 return err
28 }
29
30 type pointeeComplex64 complex64
31
32 func (c *pointeeComplex64) UnmarshalText(b []byte) error {
33 f, err := strconv.ParseFloat(string(b), 32)
34 *c = pointeeComplex64(complex(float32(f), 1))
35 return err
36 }
37
38 type pointeeFields struct {
39 Bool *bool
40 Int *int
41 Int8 *int8
42 Int16 *int16
43 Int32 *int32
44 Int64 *int64
45 Uint *uint
46 Uint8 *uint8
47 Uint16 *uint16
48 Uint32 *uint32
49 Uint64 *uint64
50 Uintptr *uintptr
51 Float32 *float32
52 Float64 *float64
53 String *string
54 Time *time.Time
55 Level *pointeeLevel
56 Name *pointeeName
57 Names []*pointeeName
58 PtrPtr **string
59 Struct *struct{ A *string }
60 StringKind *json.Number
61 Complex *pointeeComplex
62 Complex64 *pointeeComplex64
63 }
64
65 func TestDecodePointees(t *testing.T) {
66 // The values which pointers are set to are allocated by the kinds of their types: the named types of the
67 // basic kinds are decoded as encoding/json does, and are still intact after the collections of the garbage
68 // which the decoding of other values causes.
69 doc := `{"Bool":true,"Int":-1,"Int8":-8,"Int16":-16,"Int32":-32,"Int64":-64,"Uint":1,"Uint8":8,"Uint16":16,
70 "Uint32":32,"Uint64":64,"Uintptr":7,"Float32":1.5,"Float64":2.5,"String":"string",
71 "Time":"2026-09-25T12:00:00Z","Level":3,"Name":"name","Names":["a","b",null,"c"],"PtrPtr":"pp",
72 "Struct":{"A":"a"},"StringKind":12.5,"Complex":1.5,"Complex64":"2.5"}`
73 var want pointeeFields
74 if err := stdjson.Unmarshal([]byte(doc), &want); err != nil {
75 t.Fatal(err)
76 }
77 var values []*pointeeFields
78 for i := 0; i < 64; i++ {
79 var got pointeeFields
80 if err := json.Unmarshal([]byte(doc), &got); err != nil {
81 t.Fatal(err)
82 }
83 values = append(values, &got)
84 if i%8 == 0 {
85 runtime.GC()
86 }
87 }
88 runtime.GC()
89 for _, got := range values {
90 if !reflect.DeepEqual(*got, want) {
91 t.Fatalf("got %+v, want %+v", *got, want)
92 }
93 if got.Name.Upper() != "NAME" {
94 t.Fatalf("got the method of the name %q", got.Name.Upper())
95 }
96 }
97 }