Debian Codegraph @

internal/decoder/ptr.go

raw
1 package decoder
2
3 import (
4 "fmt"
5 "reflect"
6 "unsafe"
7 )
8
9 type ptrDecoder struct {
10 dec Decoder
11 typ reflect.Type
12 structName string
13 fieldName string
14 }
15
16 // newPtrDecoder returns the decoder of a pointer to typ: a basicPtrDecoder if typ has an allocator of its own
17 // ( see allocatorOf ), and else a ptrDecoder.
18 func newPtrDecoder(dec Decoder, typ reflect.Type, structName, fieldName string) Decoder {
19 d := ptrDecoder{
20 dec: dec,
21 typ: typ,
22 structName: structName,
23 fieldName: fieldName,
24 }
25 if alloc := allocatorOf(typ); alloc != nil {
26 return &basicPtrDecoder{ptrDecoder: d, alloc: alloc}
27 }
28 return &d
29 }
30
31 func (d *ptrDecoder) contentDecoder() Decoder {
32 switch dec := d.dec.(type) {
33 case *ptrDecoder:
34 return dec.contentDecoder()
35 case *basicPtrDecoder:
36 return dec.contentDecoder()
37 }
38 return d.dec
39 }
40
41 func (d *ptrDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
42 buf := ctx.Buf
43 cursor = skipWhiteSpace(buf, cursor)
44 if buf[cursor] == 'n' {
45 if err := validateNull(buf, cursor); err != nil {
46 return 0, err
47 }
48 if p != nil {
49 *(*unsafe.Pointer)(p) = nil
50 }
51 cursor += 4
52 return cursor, nil
53 }
54 var newptr unsafe.Pointer
55 if *(*unsafe.Pointer)(p) == nil {
56 newptr = newValue(d.typ)
57 *(*unsafe.Pointer)(p) = newptr
58 } else {
59 newptr = *(*unsafe.Pointer)(p)
60 }
61 c, err := d.dec.Decode(ctx, cursor, depth, newptr)
62 if err != nil {
63 *(*unsafe.Pointer)(p) = nil
64 return 0, err
65 }
66 cursor = c
67 return cursor, nil
68 }
69
70 // basicPtrDecoder is the decoder of a pointer to a type which has an allocator of its own ( see allocatorOf ),
71 // which allocates the value a nil pointer is set to. It is a type of its own, so that the decoder of a pointer
72 // to any other type is the one it was.
73 type basicPtrDecoder struct {
74 ptrDecoder
75 alloc func() unsafe.Pointer
76 }
77
78 func (d *basicPtrDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
79 buf := ctx.Buf
80 cursor = skipWhiteSpace(buf, cursor)
81 if buf[cursor] == 'n' {
82 if err := validateNull(buf, cursor); err != nil {
83 return 0, err
84 }
85 if p != nil {
86 *(*unsafe.Pointer)(p) = nil
87 }
88 return cursor + 4, nil
89 }
90 newptr := *(*unsafe.Pointer)(p)
91 if newptr == nil {
92 newptr = d.alloc()
93 *(*unsafe.Pointer)(p) = newptr
94 }
95 c, err := d.dec.Decode(ctx, cursor, depth, newptr)
96 if err != nil {
97 *(*unsafe.Pointer)(p) = nil
98 return 0, err
99 }
100 return c, nil
101 }
102
103 func (d *ptrDecoder) DecodePath(ctx *RuntimeContext, cursor, depth int64) ([][]byte, int64, error) {
104 return nil, 0, fmt.Errorf("json: ptr decoder does not support decode path")
105 }