forked from hamba/avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec_union.go
460 lines (383 loc) · 9.52 KB
/
codec_union.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
package avro
import (
"errors"
"fmt"
"reflect"
"strings"
"unsafe"
"github.com/modern-go/reflect2"
)
func createDecoderOfUnion(d *decoderContext, schema *UnionSchema, typ reflect2.Type) ValDecoder {
switch typ.Kind() {
case reflect.Map:
if typ.(reflect2.MapType).Key().Kind() != reflect.String ||
typ.(reflect2.MapType).Elem().Kind() != reflect.Interface {
break
}
return decoderOfMapUnion(d, schema, typ)
case reflect.Slice:
if !schema.Nullable() {
break
}
return decoderOfNullableUnion(d, schema, typ)
case reflect.Ptr:
if !schema.Nullable() {
break
}
return decoderOfNullableUnion(d, schema, typ)
case reflect.Interface:
if _, ok := typ.(*reflect2.UnsafeIFaceType); !ok {
dec, err := decoderOfResolvedUnion(d, schema)
if err != nil {
return &errorDecoder{err: fmt.Errorf("avro: problem resolving decoder for Avro %s: %w", schema.Type(), err)}
}
return dec
}
}
return &errorDecoder{err: fmt.Errorf("avro: %s is unsupported for Avro %s", typ.String(), schema.Type())}
}
func createEncoderOfUnion(e *encoderContext, schema *UnionSchema, typ reflect2.Type) ValEncoder {
switch typ.Kind() {
case reflect.Map:
if typ.(reflect2.MapType).Key().Kind() != reflect.String ||
typ.(reflect2.MapType).Elem().Kind() != reflect.Interface {
break
}
return encoderOfMapUnion(e, schema, typ)
case reflect.Slice:
if !schema.Nullable() {
break
}
return encoderOfNullableUnion(e, schema, typ)
case reflect.Ptr:
if !schema.Nullable() {
break
}
return encoderOfNullableUnion(e, schema, typ)
}
return encoderOfResolverUnion(e, schema, typ)
}
func decoderOfMapUnion(d *decoderContext, union *UnionSchema, typ reflect2.Type) ValDecoder {
mapType := typ.(*reflect2.UnsafeMapType)
typeDecs := make([]ValDecoder, len(union.Types()))
for i, s := range union.Types() {
if s.Type() == Null {
continue
}
typeDecs[i] = newEfaceDecoder(d, s)
}
return &mapUnionDecoder{
cfg: d.cfg,
schema: union,
mapType: mapType,
elemType: mapType.Elem(),
typeDecs: typeDecs,
}
}
type mapUnionDecoder struct {
cfg *frozenConfig
schema *UnionSchema
mapType *reflect2.UnsafeMapType
elemType reflect2.Type
typeDecs []ValDecoder
}
func (d *mapUnionDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
idx, resSchema := getUnionSchema(d.schema, r)
if resSchema == nil {
return
}
// In a null case, just return
if resSchema.Type() == Null {
return
}
if d.mapType.UnsafeIsNil(ptr) {
d.mapType.UnsafeSet(ptr, d.mapType.UnsafeMakeMap(1))
}
key := schemaTypeName(resSchema)
keyPtr := reflect2.PtrOf(key)
elemPtr := d.elemType.UnsafeNew()
d.typeDecs[idx].Decode(elemPtr, r)
d.mapType.UnsafeSetIndex(ptr, keyPtr, elemPtr)
}
func encoderOfMapUnion(e *encoderContext, union *UnionSchema, _ reflect2.Type) ValEncoder {
return &mapUnionEncoder{
cfg: e.cfg,
schema: union,
}
}
type mapUnionEncoder struct {
cfg *frozenConfig
schema *UnionSchema
}
func (e *mapUnionEncoder) Encode(ptr unsafe.Pointer, w *Writer) {
m := *((*map[string]any)(ptr))
if len(m) > 1 {
w.Error = errors.New("avro: cannot encode union map with multiple entries")
return
}
name := "null"
val := any(nil)
for k, v := range m {
name = k
val = v
break
}
schema, pos := e.schema.Types().Get(name)
if schema == nil {
w.Error = fmt.Errorf("avro: unknown union type %s", name)
return
}
w.WriteInt(int32(pos))
if schema.Type() == Null && val == nil {
return
}
elemType := reflect2.TypeOf(val)
elemPtr := reflect2.PtrOf(val)
encoder := encoderOfType(newEncoderContext(e.cfg), schema, elemType)
if elemType.LikePtr() {
encoder = &onePtrEncoder{encoder}
}
encoder.Encode(elemPtr, w)
}
func decoderOfNullableUnion(d *decoderContext, schema Schema, typ reflect2.Type) ValDecoder {
union := schema.(*UnionSchema)
_, typeIdx := union.Indices()
var (
baseTyp reflect2.Type
isPtr bool
)
switch v := typ.(type) {
case *reflect2.UnsafePtrType:
baseTyp = v.Elem()
isPtr = true
case *reflect2.UnsafeSliceType:
baseTyp = v
}
decoder := decoderOfType(d, union.Types()[typeIdx], baseTyp)
return &unionNullableDecoder{
schema: union,
typ: baseTyp,
isPtr: isPtr,
decoder: decoder,
}
}
type unionNullableDecoder struct {
schema *UnionSchema
typ reflect2.Type
isPtr bool
decoder ValDecoder
}
func (d *unionNullableDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
_, schema := getUnionSchema(d.schema, r)
if schema == nil {
return
}
if schema.Type() == Null {
*((*unsafe.Pointer)(ptr)) = nil
return
}
// Handle the non-ptr case separately.
if !d.isPtr {
if d.typ.UnsafeIsNil(ptr) {
// Create a new instance.
newPtr := d.typ.UnsafeNew()
d.decoder.Decode(newPtr, r)
d.typ.UnsafeSet(ptr, newPtr)
return
}
// Reuse the existing instance.
d.decoder.Decode(ptr, r)
return
}
if *((*unsafe.Pointer)(ptr)) == nil {
// Create new instance.
newPtr := d.typ.UnsafeNew()
d.decoder.Decode(newPtr, r)
*((*unsafe.Pointer)(ptr)) = newPtr
return
}
// Reuse existing instance.
d.decoder.Decode(*((*unsafe.Pointer)(ptr)), r)
}
func encoderOfNullableUnion(e *encoderContext, schema Schema, typ reflect2.Type) ValEncoder {
union := schema.(*UnionSchema)
nullIdx, typeIdx := union.Indices()
var (
baseTyp reflect2.Type
isPtr bool
)
switch v := typ.(type) {
case *reflect2.UnsafePtrType:
baseTyp = v.Elem()
isPtr = true
case *reflect2.UnsafeSliceType:
baseTyp = v
}
encoder := encoderOfType(e, union.Types()[typeIdx], baseTyp)
return &unionNullableEncoder{
schema: union,
encoder: encoder,
isPtr: isPtr,
nullIdx: int32(nullIdx),
typeIdx: int32(typeIdx),
}
}
type unionNullableEncoder struct {
schema *UnionSchema
encoder ValEncoder
isPtr bool
nullIdx int32
typeIdx int32
}
func (e *unionNullableEncoder) Encode(ptr unsafe.Pointer, w *Writer) {
if *((*unsafe.Pointer)(ptr)) == nil {
w.WriteInt(e.nullIdx)
return
}
w.WriteInt(e.typeIdx)
newPtr := ptr
if e.isPtr {
newPtr = *((*unsafe.Pointer)(ptr))
}
e.encoder.Encode(newPtr, w)
}
func decoderOfResolvedUnion(d *decoderContext, schema Schema) (ValDecoder, error) {
union := schema.(*UnionSchema)
types := make([]reflect2.Type, len(union.Types()))
decoders := make([]ValDecoder, len(union.Types()))
for i, schema := range union.Types() {
name := unionResolutionName(schema)
typ, err := d.cfg.resolver.Type(name)
if err != nil {
if d.cfg.config.UnionResolutionError {
return nil, err
}
if d.cfg.config.PartialUnionTypeResolution {
decoders[i] = nil
types[i] = nil
continue
}
decoders = []ValDecoder{}
types = []reflect2.Type{}
break
}
decoder := decoderOfType(d, schema, typ)
decoders[i] = decoder
types[i] = typ
}
return &unionResolvedDecoder{
cfg: d.cfg,
schema: union,
types: types,
decoders: decoders,
}, nil
}
type unionResolvedDecoder struct {
cfg *frozenConfig
schema *UnionSchema
types []reflect2.Type
decoders []ValDecoder
}
func (d *unionResolvedDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
i, schema := getUnionSchema(d.schema, r)
if schema == nil {
return
}
pObj := (*any)(ptr)
if schema.Type() == Null {
*pObj = nil
return
}
if i >= len(d.decoders) || d.decoders[i] == nil {
if d.cfg.config.UnionResolutionError {
r.ReportError("decode union type", "unknown union type")
return
}
// We cannot resolve this, set it to the map type
name := schemaTypeName(schema)
obj := map[string]any{}
vTyp, err := genericReceiver(schema)
if err != nil {
r.ReportError("Union", err.Error())
return
}
obj[name] = genericDecode(vTyp, decoderOfType(newDecoderContext(d.cfg), schema, vTyp), r)
*pObj = obj
return
}
typ := d.types[i]
var newPtr unsafe.Pointer
switch typ.Kind() {
case reflect.Map:
mapType := typ.(*reflect2.UnsafeMapType)
newPtr = mapType.UnsafeMakeMap(1)
case reflect.Slice:
mapType := typ.(*reflect2.UnsafeSliceType)
newPtr = mapType.UnsafeMakeSlice(1, 1)
case reflect.Ptr:
elemType := typ.(*reflect2.UnsafePtrType).Elem()
newPtr = elemType.UnsafeNew()
default:
newPtr = typ.UnsafeNew()
}
d.decoders[i].Decode(newPtr, r)
*pObj = typ.UnsafeIndirect(newPtr)
}
func unionResolutionName(schema Schema) string {
name := schemaTypeName(schema)
switch schema.Type() {
case Map:
name += ":"
valSchema := schema.(*MapSchema).Values()
valName := schemaTypeName(valSchema)
name += valName
case Array:
name += ":"
itemSchema := schema.(*ArraySchema).Items()
itemName := schemaTypeName(itemSchema)
name += itemName
}
return name
}
func encoderOfResolverUnion(e *encoderContext, schema Schema, typ reflect2.Type) ValEncoder {
union := schema.(*UnionSchema)
names, err := e.cfg.resolver.Name(typ)
if err != nil {
return &errorEncoder{err: err}
}
var pos int
for _, name := range names {
if idx := strings.Index(name, ":"); idx > 0 {
name = name[:idx]
}
schema, pos = union.Types().Get(name)
if schema != nil {
break
}
}
if schema == nil {
return &errorEncoder{err: fmt.Errorf("avro: unknown union type %s", names[0])}
}
encoder := encoderOfType(e, schema, typ)
return &unionResolverEncoder{
pos: pos,
encoder: encoder,
}
}
type unionResolverEncoder struct {
pos int
encoder ValEncoder
}
func (e *unionResolverEncoder) Encode(ptr unsafe.Pointer, w *Writer) {
w.WriteInt(int32(e.pos))
e.encoder.Encode(ptr, w)
}
func getUnionSchema(schema *UnionSchema, r *Reader) (int, Schema) {
types := schema.Types()
idx := int(r.ReadInt())
if idx < 0 || idx > len(types)-1 {
r.ReportError("decode union type", "unknown union type")
return 0, nil
}
return idx, types[idx]
}