-
Notifications
You must be signed in to change notification settings - Fork 95
/
codec_record.go
511 lines (425 loc) · 11.7 KB
/
codec_record.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package avro
import (
"errors"
"fmt"
"io"
"reflect"
"unsafe"
"github.com/modern-go/reflect2"
)
func createDecoderOfRecord(d *decoderContext, schema Schema, typ reflect2.Type) ValDecoder {
switch typ.Kind() {
case reflect.Struct:
return decoderOfStruct(d, schema, typ)
case reflect.Map:
if typ.(reflect2.MapType).Key().Kind() != reflect.String ||
typ.(reflect2.MapType).Elem().Kind() != reflect.Interface {
break
}
return decoderOfRecord(d, schema, typ)
case reflect.Ptr:
return decoderOfPtr(d, schema, typ)
case reflect.Interface:
if ifaceType, ok := typ.(*reflect2.UnsafeIFaceType); ok {
return &recordIfaceDecoder{schema: schema, valType: ifaceType}
}
}
return &errorDecoder{err: fmt.Errorf("avro: %s is unsupported for avro %s", typ.String(), schema.Type())}
}
func createEncoderOfRecord(e *encoderContext, schema *RecordSchema, typ reflect2.Type) ValEncoder {
switch typ.Kind() {
case reflect.Struct:
return encoderOfStruct(e, schema, typ)
case reflect.Map:
if typ.(reflect2.MapType).Key().Kind() != reflect.String ||
typ.(reflect2.MapType).Elem().Kind() != reflect.Interface {
break
}
return encoderOfRecord(e, schema, typ)
case reflect.Ptr:
return encoderOfPtr(e, schema, typ)
}
return &errorEncoder{err: fmt.Errorf("avro: %s is unsupported for avro %s", typ.String(), schema.Type())}
}
func decoderOfStruct(d *decoderContext, schema Schema, typ reflect2.Type) ValDecoder {
rec := schema.(*RecordSchema)
structDesc := describeStruct(d.cfg.getTagKey(), typ)
fields := make([]*structFieldDecoder, 0, len(rec.Fields()))
for _, field := range rec.Fields() {
if field.action == FieldIgnore {
fields = append(fields, &structFieldDecoder{
decoder: createSkipDecoder(field.Type()),
})
continue
}
sf := structDesc.Fields.Get(field.Name())
if sf == nil {
for _, alias := range field.Aliases() {
sf = structDesc.Fields.Get(alias)
if sf != nil {
break
}
}
}
// Skip field if it doesn't exist
if sf == nil {
// If the field value doesn't exist in the binary, ignore it instead of
// appending a 'SkipDecoder'.
//
// Note: 'SkipDecoder' performs a read and moves the cursor, which,
// in this case, will lead to a dirty read.
if field.action == FieldSetDefault {
continue
}
fields = append(fields, &structFieldDecoder{
decoder: createSkipDecoder(field.Type()),
})
continue
}
if field.action == FieldSetDefault {
if field.hasDef {
fields = append(fields, &structFieldDecoder{
field: sf.Field,
decoder: createDefaultDecoder(d, field, sf.Field[len(sf.Field)-1].Type()),
})
continue
}
}
dec := decoderOfType(d, field.Type(), sf.Field[len(sf.Field)-1].Type())
fields = append(fields, &structFieldDecoder{
field: sf.Field,
decoder: dec,
})
}
return &structDecoder{typ: typ, fields: fields}
}
type structFieldDecoder struct {
field []*reflect2.UnsafeStructField
decoder ValDecoder
}
type structDecoder struct {
typ reflect2.Type
fields []*structFieldDecoder
}
func (d *structDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
for _, field := range d.fields {
// Skip case
if field.field == nil {
field.decoder.Decode(nil, r)
continue
}
fieldPtr := ptr
for i, f := range field.field {
fieldPtr = f.UnsafeGet(fieldPtr)
if i == len(field.field)-1 {
break
}
if f.Type().Kind() == reflect.Ptr {
if *((*unsafe.Pointer)(fieldPtr)) == nil {
newPtr := f.Type().(*reflect2.UnsafePtrType).Elem().UnsafeNew()
*((*unsafe.Pointer)(fieldPtr)) = newPtr
}
fieldPtr = *((*unsafe.Pointer)(fieldPtr))
}
}
field.decoder.Decode(fieldPtr, r)
if r.Error != nil && !errors.Is(r.Error, io.EOF) {
for _, f := range field.field {
r.Error = fmt.Errorf("%s: %w", f.Name(), r.Error)
return
}
}
}
}
func encoderOfStruct(e *encoderContext, rec *RecordSchema, typ reflect2.Type) ValEncoder {
structDesc := describeStruct(e.cfg.getTagKey(), typ)
fields := make([]*structFieldEncoder, 0, len(rec.Fields()))
for _, field := range rec.Fields() {
sf := structDesc.Fields.Get(field.Name())
if sf != nil {
fields = append(fields, &structFieldEncoder{
field: sf.Field,
encoder: encoderOfType(e, field.Type(), sf.Field[len(sf.Field)-1].Type()),
})
continue
}
if !field.HasDefault() {
// In all other cases, this is a required field
err := fmt.Errorf("avro: record %s is missing required field %q", rec.FullName(), field.Name())
return &errorEncoder{err: err}
}
def := field.Default()
if field.Default() == nil {
if field.Type().Type() == Null {
// We write nothing in a Null case, just skip it
continue
}
if field.Type().Type() == Union && field.Type().(*UnionSchema).Nullable() {
defaultType := reflect2.TypeOf(&def)
fields = append(fields, &structFieldEncoder{
defaultPtr: reflect2.PtrOf(&def),
encoder: encoderOfNullableUnion(e, field.Type(), defaultType),
})
continue
}
}
defaultType := reflect2.TypeOf(def)
defaultEncoder := encoderOfType(e, field.Type(), defaultType)
if defaultType.LikePtr() {
defaultEncoder = &onePtrEncoder{defaultEncoder}
}
fields = append(fields, &structFieldEncoder{
defaultPtr: reflect2.PtrOf(def),
encoder: defaultEncoder,
})
}
return &structEncoder{typ: typ, fields: fields}
}
type structFieldEncoder struct {
field []*reflect2.UnsafeStructField
defaultPtr unsafe.Pointer
encoder ValEncoder
}
type structEncoder struct {
typ reflect2.Type
fields []*structFieldEncoder
}
func (e *structEncoder) Encode(ptr unsafe.Pointer, w *Writer) {
for _, field := range e.fields {
// Default case
if field.field == nil {
field.encoder.Encode(field.defaultPtr, w)
continue
}
fieldPtr := ptr
for i, f := range field.field {
fieldPtr = f.UnsafeGet(fieldPtr)
if i == len(field.field)-1 {
break
}
if f.Type().Kind() == reflect.Ptr {
if *((*unsafe.Pointer)(fieldPtr)) == nil {
w.Error = fmt.Errorf("embedded field %q is nil", f.Name())
return
}
fieldPtr = *((*unsafe.Pointer)(fieldPtr))
}
}
field.encoder.Encode(fieldPtr, w)
if w.Error != nil && !errors.Is(w.Error, io.EOF) {
for _, f := range field.field {
w.Error = fmt.Errorf("%s: %w", f.Name(), w.Error)
return
}
}
}
}
func decoderOfRecord(d *decoderContext, schema Schema, typ reflect2.Type) ValDecoder {
rec := schema.(*RecordSchema)
mapType := typ.(*reflect2.UnsafeMapType)
fields := make([]recordMapDecoderField, len(rec.Fields()))
for i, field := range rec.Fields() {
switch field.action {
case FieldIgnore:
fields[i] = recordMapDecoderField{
name: field.Name(),
decoder: createSkipDecoder(field.Type()),
skip: true,
}
continue
case FieldSetDefault:
if field.hasDef {
fields[i] = recordMapDecoderField{
name: field.Name(),
decoder: createDefaultDecoder(d, field, mapType.Elem()),
}
continue
}
}
fields[i] = recordMapDecoderField{
name: field.Name(),
decoder: decoderOfType(d, field.Type(), mapType.Elem()),
}
}
return &recordMapDecoder{
mapType: mapType,
elemType: mapType.Elem(),
fields: fields,
}
}
type recordMapDecoderField struct {
name string
decoder ValDecoder
skip bool
}
type recordMapDecoder struct {
mapType *reflect2.UnsafeMapType
elemType reflect2.Type
fields []recordMapDecoderField
}
func (d *recordMapDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
if d.mapType.UnsafeIsNil(ptr) {
d.mapType.UnsafeSet(ptr, d.mapType.UnsafeMakeMap(len(d.fields)))
}
for _, field := range d.fields {
elemPtr := d.elemType.UnsafeNew()
field.decoder.Decode(elemPtr, r)
if field.skip {
continue
}
d.mapType.UnsafeSetIndex(ptr, reflect2.PtrOf(field), elemPtr)
}
if r.Error != nil && !errors.Is(r.Error, io.EOF) {
r.Error = fmt.Errorf("%v: %w", d.mapType, r.Error)
}
}
func encoderOfRecord(e *encoderContext, rec *RecordSchema, typ reflect2.Type) ValEncoder {
mapType := typ.(*reflect2.UnsafeMapType)
fields := make([]mapEncoderField, len(rec.Fields()))
for i, field := range rec.Fields() {
fields[i] = mapEncoderField{
name: field.Name(),
hasDef: field.HasDefault(),
def: field.Default(),
encoder: encoderOfType(e, field.Type(), mapType.Elem()),
}
if field.HasDefault() {
switch {
case field.Type().Type() == Union:
union := field.Type().(*UnionSchema)
fields[i].def = map[string]any{
string(union.Types()[0].Type()): field.Default(),
}
case field.Default() == nil:
continue
}
defaultType := reflect2.TypeOf(fields[i].def)
fields[i].defEncoder = encoderOfType(e, field.Type(), defaultType)
if defaultType.LikePtr() {
fields[i].defEncoder = &onePtrEncoder{fields[i].defEncoder}
}
}
}
return &recordMapEncoder{
mapType: mapType,
fields: fields,
}
}
type mapEncoderField struct {
name string
hasDef bool
def any
defEncoder ValEncoder
encoder ValEncoder
}
type recordMapEncoder struct {
mapType *reflect2.UnsafeMapType
fields []mapEncoderField
}
func (e *recordMapEncoder) Encode(ptr unsafe.Pointer, w *Writer) {
for _, field := range e.fields {
// The first property of mapEncoderField is the name, so a pointer
// to field is a pointer to the name.
valPtr := e.mapType.UnsafeGetIndex(ptr, reflect2.PtrOf(field))
if valPtr == nil {
// Missing required field
if !field.hasDef {
w.Error = fmt.Errorf("avro: missing required field %s", field.name)
return
}
// Null default
if field.def == nil {
continue
}
defPtr := reflect2.PtrOf(field.def)
field.defEncoder.Encode(defPtr, w)
continue
}
field.encoder.Encode(valPtr, w)
if w.Error != nil && !errors.Is(w.Error, io.EOF) {
w.Error = fmt.Errorf("%s: %w", field.name, w.Error)
return
}
}
}
type recordIfaceDecoder struct {
schema Schema
valType *reflect2.UnsafeIFaceType
}
func (d *recordIfaceDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
obj := d.valType.UnsafeIndirect(ptr)
if reflect2.IsNil(obj) {
r.ReportError("decode non empty interface", "can not unmarshal into nil")
return
}
r.ReadVal(d.schema, obj)
}
type structDescriptor struct {
Type reflect2.Type
Fields structFields
}
type structFields []*structField
func (sf structFields) Get(name string) *structField {
for _, f := range sf {
if f.Name == name {
return f
}
}
return nil
}
type structField struct {
Name string
Field []*reflect2.UnsafeStructField
anon *reflect2.UnsafeStructType
}
func describeStruct(tagKey string, typ reflect2.Type) *structDescriptor {
structType := typ.(*reflect2.UnsafeStructType)
fields := structFields{}
var curr []structField
next := []structField{{anon: structType}}
visited := map[uintptr]bool{}
for len(next) > 0 {
curr, next = next, curr[:0]
for _, f := range curr {
rtype := f.anon.RType()
if visited[f.anon.RType()] {
continue
}
visited[rtype] = true
for i := range f.anon.NumField() {
field := f.anon.Field(i).(*reflect2.UnsafeStructField)
isUnexported := field.PkgPath() != ""
chain := make([]*reflect2.UnsafeStructField, len(f.Field)+1)
copy(chain, f.Field)
chain[len(f.Field)] = field
if field.Anonymous() {
t := field.Type()
if t.Kind() == reflect.Ptr {
t = t.(*reflect2.UnsafePtrType).Elem()
}
if t.Kind() != reflect.Struct {
continue
}
next = append(next, structField{Field: chain, anon: t.(*reflect2.UnsafeStructType)})
continue
}
// Ignore unexported fields.
if isUnexported {
continue
}
fieldName := field.Name()
if tag, ok := field.Tag().Lookup(tagKey); ok {
fieldName = tag
}
fields = append(fields, &structField{
Name: fieldName,
Field: chain,
})
}
}
}
return &structDescriptor{
Type: structType,
Fields: fields,
}
}