-
Notifications
You must be signed in to change notification settings - Fork 8
/
pointer.go
110 lines (102 loc) · 2.2 KB
/
pointer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package sonnet
import (
"reflect"
"sync"
)
func compilePointerDecoder(typ reflect.Type) decoder {
elm := typ.Elem()
fnc, ok := decs.get(elm)
rep := func() {
if !ok {
fnc = compileDecoder(elm)
decs.set(elm, fnc)
}
}
var once sync.Once
return func(head byte, val reflect.Value, dec *Decoder) error {
const ull = "ull"
if head == 'n' {
part, err := dec.readn(len(ull))
if err != nil {
return err
}
if string(part) != ull {
return dec.buildErrSyntax(head, ull, part)
}
val.SetZero()
return nil
}
once.Do(rep)
if val.IsNil() {
val.Set(reflect.New(elm))
}
return addPointer(fnc(head, val.Elem(), dec))
}
}
func compilePointerEncoder(typ reflect.Type) encoder {
elm := typ.Elem()
fnc, ok := encs.get(elm)
rep := func() {
if !ok {
fnc = compileEncoder(elm, true)
encs.set(elm, fnc)
}
}
var once sync.Once
return func(dst []byte, val reflect.Value, enc *Encoder) ([]byte, error) {
if val.IsNil() {
return append(dst, "null"...), nil
}
once.Do(rep)
enc.level++
if enc.level > maxCycles {
if enc.seen == nil {
enc.seen = make(map[any]struct{})
}
head := val.Pointer()
if _, ok := enc.seen[head]; ok {
return nil, &UnsupportedValueError{
Value: val,
Str: "encountered a cycle via: " + typ.String(),
}
}
enc.seen[head] = struct{}{}
defer delete(enc.seen, head)
}
var err error
dst, err = fnc(dst, val.Elem(), enc)
if err != nil {
return nil, err
}
enc.level--
return dst, nil
}
}
func compilePointerMarshalerEncoder(typ reflect.Type) encoder {
var fnc encoder
rep := func() {
fnc = compileEncoder(typ, false)
}
var once sync.Once
return func(dst []byte, val reflect.Value, enc *Encoder) ([]byte, error) {
if !val.CanAddr() {
once.Do(rep)
return fnc(dst, val, enc)
}
return encodeMarshaler(dst, val.Addr(), enc)
}
}
func compilePointerTextMarshalerEncoder(typ reflect.Type) encoder {
var fnc encoder
rep := func() {
fnc = compileEncoder(typ, false)
}
var once sync.Once
return func(dst []byte, val reflect.Value, enc *Encoder) ([]byte, error) {
if !val.CanAddr() {
once.Do(rep)
return fnc(dst, val, enc)
}
return encodeTextMarshaler(dst, val.Addr(), enc)
}
}