-
Notifications
You must be signed in to change notification settings - Fork 2
/
decoder_config.go
248 lines (227 loc) · 6.32 KB
/
decoder_config.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package jzon
import (
"io"
"reflect"
"sync"
"sync/atomic"
)
var (
// DefaultDecoderConfig is compatible with standard lib
DefaultDecoderConfig = NewDecoderConfig(nil)
)
// DecoderOption can be used to customize the decoder config
type DecoderOption struct {
// custom value decoders
ValDecoders map[reflect.Type]ValDecoder
// if the object key is case sensitive
// `false` by default
CaseSensitive bool
// the tag name for structures
// `json` by default
Tag string
OnlyTaggedField bool
UseNumber bool
DisallowUnknownFields bool
}
type decoderCache = map[rtype]ValDecoder
// DecoderConfig is a frozen config for decoding
type DecoderConfig struct {
cacheMu sync.Mutex
decoderCache atomic.Value
// fixed config, cannot override during runtime
caseSensitive bool
tag string
onlyTaggedField bool
// can override during runtime
useNumber bool
disallowUnknownFields bool
}
// NewDecoderConfig returns a new decoder config
// If the input option is nil, the default option will be applied
func NewDecoderConfig(opt *DecoderOption) *DecoderConfig {
decCfg := DecoderConfig{
tag: "json",
}
// add decoders to cache
cache := decoderCache{}
if opt != nil {
for elemTyp, valDec := range opt.ValDecoders {
cache[rtypeOfType(reflect.PtrTo(elemTyp))] = valDec
}
decCfg.caseSensitive = opt.CaseSensitive
if opt.Tag != "" {
decCfg.tag = opt.Tag
}
decCfg.onlyTaggedField = opt.OnlyTaggedField
decCfg.useNumber = opt.UseNumber
decCfg.disallowUnknownFields = opt.DisallowUnknownFields
}
decCfg.decoderCache.Store(cache)
return &decCfg
}
// Unmarshal behave like json.Unmarshal
func (decCfg *DecoderConfig) Unmarshal(data []byte, obj interface{}) error {
it := decCfg.NewIterator()
err := it.Unmarshal(data, obj)
if err != nil {
err = it.WrapError(err)
}
it.Release()
return err
}
// UnmarshalFromString behave like json.Unmarshal but with a string
func (decCfg *DecoderConfig) UnmarshalFromString(s string, obj interface{}) error {
return decCfg.Unmarshal(localStringToBytes(s), obj)
}
// UnmarshalFromReader behave like json.Unmarshal but with an io.Reader
func (decCfg *DecoderConfig) UnmarshalFromReader(r io.Reader, obj interface{}) error {
it := decCfg.NewIterator()
err := it.UnmarshalFromReader(r, obj)
if err != nil {
err = it.WrapError(err)
}
it.Release()
return err
}
func (decCfg *DecoderConfig) getDecoderFromCache(rType rtype) ValDecoder {
return decCfg.decoderCache.Load().(decoderCache)[rType]
}
// NewDecoder returns a new decoder that reads from r.
func (decCfg *DecoderConfig) NewDecoder(r io.Reader) *Decoder {
it := decCfg.NewIterator()
it.Reset(r)
return &Decoder{
it: it,
}
}
// the typ must be a pointer type
func (decCfg *DecoderConfig) createDecoder(rType rtype, ptrType reflect.Type) ValDecoder {
decCfg.cacheMu.Lock()
defer decCfg.cacheMu.Unlock()
cache := decCfg.decoderCache.Load().(decoderCache)
// double check
if vd := cache[rType]; vd != nil {
return vd
}
// make copy
newCache := decoderCache{}
for k, v := range cache {
newCache[k] = v
}
var q typeQueue
q.push(ptrType)
decCfg.createDecoderInternal(newCache, q)
decCfg.decoderCache.Store(newCache)
return newCache[rType]
}
type decoderBuilder interface {
build(cache decoderCache)
}
func (decCfg *DecoderConfig) createDecoderInternal(cache decoderCache, typesToCreate typeQueue) {
rebuildMap := map[rtype]decoderBuilder{}
for ptrType := typesToCreate.pop(); ptrType != nil; ptrType = typesToCreate.pop() {
rType := rtypeOfType(ptrType)
if _, ok := cache[rType]; ok { // check if visited
continue
}
// check global decoders
if v, ok := globalValDecoders[rType]; ok {
cache[rType] = v
continue
}
// check json.Unmarshaler interface
if ptrType.Implements(jsonUnmarshalerType) {
cache[rType] = jsonUnmarshalerDecoder(rType)
continue
}
if ptrType.Implements(textUnmarshalerType) {
cache[rType] = textUnmarshalerDecoder(rType)
continue
}
elem := ptrType.Elem()
elemKind := elem.Kind()
if elemNativeRType := decoderKindMap[elemKind]; elemNativeRType != 0 {
// TODO: shall we make this an option?
// TODO: so that only the native type is affected?
// check if the native type has a custom decoder
if v, ok := cache[elemNativeRType]; ok {
cache[rType] = v
continue
}
// otherwise check default native type decoder
if v := kindDecoders[elemKind]; v != nil {
cache[rType] = v
continue
}
}
switch elemKind {
case reflect.Interface:
if elem.NumMethod() == 0 {
cache[rType] = (*efaceDecoder)(nil)
} else {
cache[rType] = (*ifaceDecoder)(nil)
}
case reflect.Struct:
fields := describeStruct(elem, decCfg.tag, decCfg.onlyTaggedField)
numFields := len(fields)
if numFields == 0 {
cache[rType] = (*emptyObjectDecoder)(nil)
continue
}
for i := range fields {
fi := &fields[i]
typesToCreate.push(fi.ptrType)
}
if numFields == 1 {
w := newOneFieldStructDecoder(&fields[0], decCfg.caseSensitive)
cache[rType] = w.decoder
rebuildMap[rType] = w
} else if numFields <= 10 {
// TODO: determinate the threshold, several factors may be involved:
// TODO: 1. number of fields
// TODO: 2. (average) field length
// TODO: 3. field similarity
w := newSmallStructDecoder(fields)
cache[rType] = w.decoder
rebuildMap[rType] = w
} else {
w := newStructDecoder(fields)
cache[rType] = w.decoder
rebuildMap[rType] = w
}
case reflect.Ptr:
typesToCreate.push(elem)
w := newPointerDecoder(elem)
cache[rType] = w.decoder
rebuildMap[rType] = w
case reflect.Array:
elemPtrType := reflect.PtrTo(elem.Elem())
typesToCreate.push(elemPtrType)
w := newArrayDecoder(elem)
cache[rType] = w.decoder
rebuildMap[rType] = w
case reflect.Slice:
elemPtrType := reflect.PtrTo(elem.Elem())
typesToCreate.push(elemPtrType)
w := newSliceDecoder(elem)
cache[rType] = w.decoder
rebuildMap[rType] = w
case reflect.Map:
w := newMapDecoder(elem)
if w == nil {
cache[rType] = notSupportedDecoder(ptrType.String())
} else {
valuePtrType := reflect.PtrTo(elem.Elem())
typesToCreate.push(valuePtrType)
cache[rType] = w.decoder
rebuildMap[rType] = w
}
default:
cache[rType] = notSupportedDecoder(ptrType.String())
}
}
// rebuild some decoders
for _, builder := range rebuildMap {
builder.build(cache)
}
}