forked from Restream/reindexer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
409 lines (366 loc) · 9.87 KB
/
encoder.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package cjson
import (
"encoding/base64"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
)
type Encoder struct {
state *State
tagsMatcher *tagsMatcher
tmUpdated bool
}
type fieldInfo struct {
ctagName int
kind reflect.Kind
elemKind reflect.Kind
isAnon bool
isNullable bool
isPrivate bool
isOmitEmpty bool
isTime bool
isPtr bool
}
func mkFieldInfo(v reflect.Value, ctagName int, anon bool) fieldInfo {
t := v.Type()
k := t.Kind()
kk := k
if k == reflect.Ptr {
t = t.Elem()
kk = t.Kind()
}
f := fieldInfo{
isAnon: anon,
isNullable: (k == reflect.Ptr || k == reflect.Map || k == reflect.Slice || k == reflect.Interface),
isPtr: k == reflect.Ptr,
kind: kk,
ctagName: ctagName,
isTime: kk == reflect.Struct && t.String() == "time.Time",
}
if kk == reflect.Slice || kk == reflect.Array {
f.elemKind = t.Elem().Kind()
}
return f
}
// non allocating version of strings.Split
func splitStr(in string, sep byte) (s1, s2, s3 string) {
out := []*string{&s1, &s2, &s3}
for i := 0; i < len(out); i++ {
pos := strings.IndexByte(in, sep)
if pos != -1 {
*out[i] = in[:pos]
in = in[pos+1:]
} else {
*out[i] = in
break
}
}
return
}
func parseStructField(sf reflect.StructField) (name string, skip, omitEmpty bool) {
name, opt, _ := splitStr(sf.Tag.Get("json"), ',')
if name == "-" || len(sf.PkgPath) != 0 {
skip = true
} else if name == "" {
name = sf.Name
}
omitEmpty = (opt == "omitempty")
return
}
func (enc *Encoder) encodeStruct(v reflect.Value, rdser *Serializer, idx []int) {
for field := 0; field < v.NumField(); field++ {
iidx := idx
var ce *ctagsWCacheEntry
if iidx == nil {
// if idx is null - we have top level interface field,
// in this case we can have any untyped data in deep, so
// ctagsCache 'name path' -> type will not work
// So here is using slow path: use reflect to obtain info about each field
ce = &ctagsWCacheEntry{}
} else {
// We have not interface fields on top level, so using cache
iidx = append(idx, field)
ce = enc.state.ctagsWCache.Lookup(iidx, true)
}
if ce.ctagName == 0 && !ce.isPrivate {
// No data in cache: use reflect to get data about field
vv := v.Field(field)
f := v.Type().Field(field)
name, skip, omitempty := parseStructField(f)
ctagName := 0
if !skip {
ctagName = enc.name2tag(name)
}
if enc.tmUpdated {
// if tagsMatcher or lock is updated - we have temporary tags, do not cache them
ce = &ctagsWCacheEntry{}
}
ce.fieldInfo = mkFieldInfo(vv, ctagName, f.Anonymous)
ce.isPrivate = len(f.PkgPath) != 0 || skip
ce.isOmitEmpty = omitempty
}
if !ce.isPrivate {
// process field, except private unexported fields
enc.encodeValue(v.Field(field), rdser, ce.fieldInfo, iidx)
}
}
}
func (enc *Encoder) name2tag(name string) int {
tagName := enc.tagsMatcher.name2tag(name, false)
if tagName == 0 {
if !enc.tmUpdated {
enc.tagsMatcher = &tagsMatcher{Tags: enc.state.tagsMatcher.Tags, Names: make(map[string]int)}
for k, v := range enc.state.tagsMatcher.Names {
enc.tagsMatcher.Names[k] = v
}
enc.tmUpdated = true
}
tagName = enc.tagsMatcher.name2tag(name, true)
}
return tagName
}
func (enc *Encoder) encodeMap(v reflect.Value, rdser *Serializer, idx []int) {
keys := v.MapKeys()
f := fieldInfo{}
for i, k := range keys {
keyName := ""
vv := v.MapIndex(k)
if i == 0 {
f = mkFieldInfo(vv, 0, false)
}
switch k.Type().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
keyName = strconv.FormatInt(k.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
keyName = strconv.FormatUint(k.Uint(), 10)
case reflect.String:
keyName = k.String()
case reflect.Float32, reflect.Float64:
keyName = strconv.FormatFloat(k.Float(), 'g', -1, 64)
default:
panic(fmt.Errorf("Unsupported map key type %s ", k.Type().Kind().String()))
}
f.ctagName = enc.name2tag(keyName)
enc.encodeValue(vv, rdser, f, idx)
}
}
func (enc *Encoder) encodeSlice(v reflect.Value, rdser *Serializer, f fieldInfo, idx []int) {
l := v.Len()
if l == 0 && f.isOmitEmpty {
return
}
if f.elemKind == reflect.Uint8 {
rdser.PutVarUInt(mkctag(TAG_STRING, f.ctagName, 0))
rdser.PutVString(base64.StdEncoding.EncodeToString(v.Bytes()))
} else {
rdser.PutVarUInt(mkctag(TAG_ARRAY, f.ctagName, 0))
subTag := TAG_OBJECT
switch f.elemKind {
case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int8, reflect.Int32,
reflect.Uint, reflect.Uint16, reflect.Uint64, reflect.Uint32:
subTag = TAG_VARINT
case reflect.Float32, reflect.Float64:
subTag = TAG_DOUBLE
case reflect.String:
subTag = TAG_STRING
case reflect.Bool:
subTag = TAG_BOOL
}
rdser.PutUInt32(mkcarraytag(l, subTag))
var ptr unsafe.Pointer
if f.kind == reflect.Slice {
ptr = unsafe.Pointer(v.Pointer())
} else {
ptr = unsafe.Pointer(v.Index(0).Addr().Pointer())
}
switch f.elemKind {
case reflect.Int:
sl := (*[1 << 28]int)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Uint:
sl := (*[1 << 28]uint)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Int32:
sl := (*[1 << 28]int32)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Uint32:
sl := (*[1 << 28]uint32)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Int16:
sl := (*[1 << 29]int16)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Uint16:
sl := (*[1 << 29]uint16)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Int64:
sl := (*[1 << 27]int64)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Uint64:
sl := (*[1 << 27]uint64)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Int8:
sl := (*[1 << 30]int8)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVarInt(int64(v))
}
case reflect.Float32:
sl := (*[1 << 28]float32)(ptr)[:l:l]
for _, v := range sl {
rdser.PutDouble(float64(v))
}
case reflect.Float64:
sl := (*[1 << 27]float64)(ptr)[:l:l]
for _, v := range sl {
rdser.PutDouble(v)
}
case reflect.String:
sl := (*[1 << 27]string)(ptr)[:l:l]
for _, v := range sl {
rdser.PutVString(v)
}
case reflect.Bool:
sl := (*[1 << 30]bool)(ptr)[:l:l]
for _, v := range sl {
var vv uint64
if v {
vv = 1
}
rdser.PutVarUInt(vv)
}
default:
if subTag != TAG_OBJECT {
panic(fmt.Errorf("Internal error can't serialize array of type %s", f.elemKind.String()))
}
for i := 0; i < l; i++ {
vv := v.Index(i)
if i == 0 {
f = mkFieldInfo(vv, 0, false)
f.isOmitEmpty = false
}
enc.encodeValue(vv, rdser, f, idx)
}
}
}
}
func (enc *Encoder) encodeValue(v reflect.Value, rdser *Serializer, f fieldInfo, idx []int) {
if f.isNullable && v.IsNil() {
if !f.isOmitEmpty {
rdser.PutVarUInt(mkctag(TAG_NULL, f.ctagName, 0))
}
return
}
if f.isPtr {
v = v.Elem()
}
switch f.kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val := v.Int()
if val != 0 || !f.isOmitEmpty {
rdser.PutVarUInt(mkctag(TAG_VARINT, f.ctagName, 0))
rdser.PutVarInt(val)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
val := v.Uint()
if val != 0 || !f.isOmitEmpty {
rdser.PutVarUInt(mkctag(TAG_VARINT, f.ctagName, 0))
rdser.PutVarInt(int64(val))
}
case reflect.Float32, reflect.Float64:
val := v.Float()
if val != 0 || !f.isOmitEmpty {
rdser.PutVarUInt(mkctag(TAG_DOUBLE, f.ctagName, 0))
rdser.PutDouble(val)
}
case reflect.Bool:
vv := 0
if v.Bool() {
vv = 1
}
if vv != 0 || !f.isOmitEmpty {
rdser.PutVarUInt(mkctag(TAG_BOOL, f.ctagName, 0))
rdser.PutVarUInt(uint64(vv))
}
case reflect.String:
val := v.String()
if len(val) != 0 || !f.isOmitEmpty {
rdser.PutVarUInt(mkctag(TAG_STRING, f.ctagName, 0))
rdser.PutVString(val)
}
case reflect.Slice, reflect.Array:
enc.encodeSlice(v, rdser, f, idx)
case reflect.Struct:
if f.isTime && v.IsValid() {
if tm, ok := v.Interface().(time.Time); ok {
rdser.PutVarUInt(mkctag(TAG_STRING, f.ctagName, 0))
rdser.PutVString(tm.Format(time.RFC3339Nano))
return
}
}
if !f.isAnon {
rdser.PutVarUInt(mkctag(TAG_OBJECT, f.ctagName, 0))
enc.encodeStruct(v, rdser, idx)
rdser.PutVarUInt(mkctag(TAG_END, 0, 0))
} else {
enc.encodeStruct(v, rdser, idx)
}
case reflect.Map:
rdser.PutVarUInt(mkctag(TAG_OBJECT, f.ctagName, 0))
enc.encodeMap(v, rdser, idx)
rdser.PutVarUInt(mkctag(TAG_END, 0, 0))
case reflect.Interface:
vv := v.Elem()
enc.encodeValue(vv, rdser, mkFieldInfo(vv, f.ctagName, f.isAnon), nil)
default:
panic(fmt.Errorf("Unsupported type %s", f.kind.String()))
}
}
func (enc *Encoder) Encode(src interface{}, wrser *Serializer) (stateToken int, err error) {
v := reflect.ValueOf(src)
enc.state.lock.Lock()
pos := len(wrser.Bytes())
wrser.PutVarUInt(TAG_END)
wrser.PutUInt32(0)
enc.tagsMatcher = &enc.state.tagsMatcher
enc.tmUpdated = false
enc.encodeValue(v, wrser, mkFieldInfo(v, 0, false), make([]int, 0, 10))
if enc.tmUpdated {
*(*uint32)(unsafe.Pointer(&wrser.Bytes()[pos+1])) = uint32(len(wrser.buf) - pos)
enc.tagsMatcher.WriteUpdated(wrser)
} else {
wrser.TruncateStart(int(unsafe.Sizeof(uint32(0))) + 1)
}
stateToken = int(enc.state.StateToken)
enc.state.lock.Unlock()
return
}
func (enc *Encoder) EncodeRaw(src interface{}, wrser *Serializer) error {
v := reflect.ValueOf(src)
enc.state.lock.Lock()
enc.tmUpdated = false
enc.tagsMatcher = &enc.state.tagsMatcher
enc.encodeValue(v, wrser, mkFieldInfo(v, 0, false), make([]int, 0, 10))
if enc.tmUpdated {
enc.state.tagsMatcher = *enc.tagsMatcher
}
enc.state.lock.Unlock()
return nil
}