-
Notifications
You must be signed in to change notification settings - Fork 22
/
map_decode.go
518 lines (433 loc) · 15.4 KB
/
map_decode.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
512
513
514
515
516
517
518
package serix
import (
"context"
"reflect"
"strconv"
"unicode/utf8"
"github.com/iotaledger/hive.go/ierrors"
"github.com/iotaledger/hive.go/serializer/v2"
)
func (api *API) mapDecode(ctx context.Context, mapVal any, value reflect.Value, ts TypeSettings, opts *options) (err error) {
var deserializable DeserializableJSON
if _, ok := value.Interface().(DeserializableJSON); ok {
if value.Kind() == reflect.Ptr && value.IsNil() {
value.Set(reflect.New(value.Type().Elem()))
}
//nolint:forcetypeassert // false positive
deserializable = value.Interface().(DeserializableJSON)
} else if value.CanAddr() {
if addrDeserializable, ok := value.Addr().Interface().(DeserializableJSON); ok {
deserializable = addrDeserializable
}
}
if deserializable != nil {
err = deserializable.DecodeJSON(mapVal)
if err != nil {
return ierrors.WithStack(err)
}
if contextAwareDeserializable, ok := deserializable.(ContextAwareDeserializable); ok {
contextAwareDeserializable.SetDeserializationContext(ctx)
}
} else {
if err = api.mapDecodeBasedOnType(ctx, mapVal, value, value.Type(), ts, opts); err != nil {
return ierrors.WithStack(err)
}
}
if opts.validation {
if err := api.callSyntacticValidator(ctx, value, value.Type()); err != nil {
return ierrors.Wrap(err, "post-serialization validation failed")
}
}
return nil
}
func (api *API) mapDecodeBasedOnType(ctx context.Context, mapVal any, value reflect.Value,
valueType reflect.Type, ts TypeSettings, opts *options) error {
globalTS, _ := api.typeSettingsRegistry.GetByType(valueType)
ts = ts.merge(globalTS)
switch value.Kind() {
case reflect.Ptr:
if valueType == bigIntPtrType {
bigIntHexStr, ok := mapVal.(string)
if !ok {
return ierrors.Errorf("non string value in map when decoding a big.Int, got %T instead", mapVal)
}
bigInt, err := DecodeUint256(bigIntHexStr)
if err != nil {
return ierrors.Wrap(err, "failed to read big.Int from map")
}
value.Addr().Elem().Set(reflect.ValueOf(bigInt))
return nil
}
elemType := valueType.Elem()
if elemType.Kind() == reflect.Struct {
if value.IsNil() {
value.Set(reflect.New(elemType))
}
elemValue := value.Elem()
if contextAwareDeserializable, ok := value.Interface().(ContextAwareDeserializable); ok {
contextAwareDeserializable.SetDeserializationContext(ctx)
}
return api.mapDecodeStruct(ctx, mapVal, elemValue, elemType, ts, opts)
}
if elemType.Kind() == reflect.Interface {
if value.IsNil() {
value.Set(reflect.New(elemType))
}
elemValue := value.Elem()
return api.mapDecodeInterface(ctx, mapVal, elemValue, elemType, ts, opts)
}
if elemType.Kind() == reflect.Array {
if value.IsNil() {
value.Set(reflect.New(elemType))
}
sliceValue := sliceFromArray(value.Elem())
sliceValueType := sliceValue.Type()
if sliceValueType.AssignableTo(bytesType) {
innerTS, ok := api.typeSettingsRegistry.GetByType(valueType)
if !ok {
return ierrors.Errorf("missing type settings for interface %s", valueType)
}
fieldKey := keyDefaultSliceArray
if innerTS.fieldKey != nil {
fieldKey = *innerTS.fieldKey
}
//nolint:forcetypeassert
fieldValStr := mapVal.(map[string]any)[fieldKey].(string)
byteSlice, err := DecodeHex(fieldValStr)
if err != nil {
return ierrors.Wrap(err, "failed to read byte slice from map")
}
if opts.validation {
if err := ts.checkMinMaxBoundsLength(len(byteSlice)); err != nil {
return ierrors.Wrapf(err, "can't deserialize '%s' type", value.Kind())
}
}
copy(sliceValue.Bytes(), byteSlice)
fillArrayFromSlice(value.Elem(), sliceValue)
return nil
}
return api.mapDecodeSlice(ctx, mapVal, sliceValue, sliceValueType, ts, opts)
}
case reflect.Struct:
if contextAwareDeserializable, ok := value.Interface().(ContextAwareDeserializable); ok {
contextAwareDeserializable.SetDeserializationContext(ctx)
}
return api.mapDecodeStruct(ctx, mapVal, value, valueType, ts, opts)
case reflect.Slice:
return api.mapDecodeSlice(ctx, mapVal, value, valueType, ts, opts)
case reflect.Map:
return api.mapDecodeMap(ctx, mapVal, value, valueType, ts, opts)
case reflect.Array:
sliceValue := sliceFromArray(value)
sliceValueType := sliceValue.Type()
if sliceValueType.AssignableTo(bytesType) {
byteSlice, err := DecodeHex(mapVal.(string))
if err != nil {
return ierrors.Wrap(err, "failed to read byte slice from map")
}
copy(sliceValue.Bytes(), byteSlice)
fillArrayFromSlice(value, sliceValue)
return nil
}
return api.mapDecodeSlice(ctx, mapVal, sliceValue, sliceValueType, ts, opts)
case reflect.Interface:
return api.mapDecodeInterface(ctx, mapVal, value, valueType, ts, opts)
case reflect.String:
str, ok := mapVal.(string)
if !ok {
return ierrors.New("non string value for string field")
}
if opts.validation {
if err := ts.checkMinMaxBoundsLength(len(str)); err != nil {
return ierrors.Wrapf(err, "can't deserialize '%s' type", value.Kind())
}
// check the string for UTF-8 validity
if !utf8.ValidString(str) {
return ErrNonUTF8String
}
}
addrValue := value.Addr().Convert(reflect.TypeOf((*string)(nil)))
addrValue.Elem().Set(reflect.ValueOf(mapVal))
return nil
case reflect.Bool:
addrValue := value.Addr().Convert(reflect.TypeOf((*bool)(nil)))
addrValue.Elem().Set(reflect.ValueOf(mapVal))
return nil
case reflect.Int8, reflect.Int16, reflect.Int32:
//nolint:forcetypeassert // false positive, we already checked the type via reflect
return api.mapDecodeNum(value, valueType, float64NumParser(mapVal.(float64), value.Kind(), true))
case reflect.Int64:
//nolint:forcetypeassert // false positive, we already checked the type via reflect
return api.mapDecodeNum(value, valueType, strNumParser(mapVal.(string), 64, true))
case reflect.Uint8, reflect.Uint16, reflect.Uint32:
//nolint:forcetypeassert // false positive, we already checked the type via reflect
return api.mapDecodeNum(value, valueType, float64NumParser(mapVal.(float64), value.Kind(), false))
case reflect.Uint64:
//nolint:forcetypeassert // false positive, we already checked the type via reflect
return api.mapDecodeNum(value, valueType, strNumParser(mapVal.(string), 64, false))
case reflect.Float32, reflect.Float64:
return api.mapDecodeFloat(value, valueType, mapVal)
default:
}
return ierrors.Errorf("can't map decode: unsupported type %s", valueType)
}
// num parse func returns a num or an error.
type numParseFunc func() (any, error)
func float64NumParser(v float64, ty reflect.Kind, signed bool) numParseFunc {
return func() (any, error) {
if signed {
switch ty {
case reflect.Int8:
return int8(v), nil
case reflect.Int16:
return int16(v), nil
case reflect.Int32:
return int32(v), nil
default:
return nil, ierrors.Errorf("can not map decode kind %s to signed integer", ty)
}
}
switch ty {
case reflect.Uint8:
return uint8(v), nil
case reflect.Uint16:
return uint16(v), nil
case reflect.Uint32:
return uint32(v), nil
default:
return nil, ierrors.Errorf("can not map decode kind %s to unsigned integer", ty)
}
}
}
func strNumParser(str string, bitSize int, signed bool) numParseFunc {
return func() (any, error) {
if signed {
return strconv.ParseInt(str, 10, bitSize)
}
return strconv.ParseUint(str, 10, bitSize)
}
}
func (api *API) mapDecodeNum(value reflect.Value, valueType reflect.Type, parser numParseFunc) error {
addrValue := value.Addr()
_, _, addrTypeToConvert := getNumberTypeToConvert(valueType.Kind())
addrValue = addrValue.Convert(addrTypeToConvert)
num, err := parser()
if err != nil {
return err
}
addrValue.Elem().Set(reflect.ValueOf(num))
return nil
}
func (api *API) mapDecodeFloat(value reflect.Value, valueType reflect.Type, mapVal any) error {
addrValue := value.Addr()
bitSize, _, addrTypeToConvert := getNumberTypeToConvert(valueType.Kind())
addrValue = addrValue.Convert(addrTypeToConvert)
f, err := strconv.ParseFloat(mapVal.(string), bitSize)
if err != nil {
return err
}
addrValue.Elem().SetFloat(f)
return nil
}
func (api *API) mapDecodeInterface(
ctx context.Context, mapVal any, value reflect.Value, valueType reflect.Type, ts TypeSettings, opts *options,
) error {
iObjects := api.getInterfaceObjects(valueType)
if iObjects == nil {
return ierrors.Errorf("interface %s hasn't been registered", valueType)
}
m, ok := mapVal.(map[string]any)
if !ok {
return ierrors.Errorf("non map[string]any in struct map decode, got %T instead", mapVal)
}
objectCodeAny, has := m[keyType]
if !has {
return ierrors.Errorf("no object type defined in map for interface %s", valueType)
}
//nolint:forcetypeassert // false positive
objectCode := uint32(objectCodeAny.(float64))
objectType, exists := iObjects.GetObjectTypeByCode(objectCode)
if !exists || objectType == nil {
return ierrors.Wrapf(ErrInterfaceUnderlyingTypeNotRegistered, "object code: %d, interface: %s", objectCode, valueType)
}
objectValue := reflect.New(objectType).Elem()
if err := api.mapDecode(ctx, m, objectValue, ts, opts); err != nil {
return ierrors.WithStack(err)
}
value.Set(objectValue)
return nil
}
func (api *API) mapDecodeStruct(ctx context.Context, mapVal any, value reflect.Value,
valueType reflect.Type, ts TypeSettings, opts *options) error {
if valueType == timeType {
//nolint:forcetypeassert // false positive, we already checked the type via reflect
strVal := mapVal.(string)
nanoTime, err := DecodeUint64(strVal)
if err != nil {
return ierrors.Wrapf(err, "unable to parse time %s map value", strVal)
}
value.Set(reflect.ValueOf(serializer.Uint64ToTime(nanoTime)))
return nil
}
m, ok := mapVal.(map[string]any)
if !ok {
return ierrors.Errorf("non map[string]any in struct map decode, got %T instead", mapVal)
}
if objectType := ts.ObjectType(); objectType != nil {
_, objectCode, err := getTypeDenotationAndCode(objectType)
if err != nil {
return ierrors.WithStack(err)
}
mapObjectCode, has := m[keyType]
if !has {
return ierrors.Wrap(err, "missing type key in struct")
}
if castedMapObjectCode, ok := mapObjectCode.(float64); !ok || uint32(castedMapObjectCode) != objectCode {
return ierrors.Errorf("map type key (%d) not equal registered object code (%d)", mapObjectCode, objectCode)
}
}
if err := api.mapDecodeStructFields(ctx, m, value, valueType, opts); err != nil {
return ierrors.WithStack(err)
}
return nil
}
func (api *API) mapDecodeStructFields(
ctx context.Context, m map[string]any, structVal reflect.Value, valueType reflect.Type, opts *options,
) error {
structFields, err := api.getStructFields(valueType)
if err != nil {
return ierrors.Wrapf(err, "can't parse struct type %s", valueType)
}
if len(structFields) == 0 {
return nil
}
for _, sField := range structFields {
fieldValue := structVal.Field(sField.index)
if sField.isEmbedded && !sField.settings.inlined {
fieldType := sField.fType
if fieldType.Kind() == reflect.Ptr {
if fieldValue.IsNil() {
if sField.isUnexported {
return ierrors.Errorf(
"embedded field %s is a nil pointer, can't initialize because it's unexported",
sField.name,
)
}
fieldValue.Set(reflect.New(fieldType.Elem()))
}
fieldValue = fieldValue.Elem()
fieldType = fieldType.Elem()
}
if err := api.mapDecodeStructFields(ctx, m, fieldValue, fieldType, opts); err != nil {
return ierrors.Wrapf(err, "can't deserialize embedded struct %s", sField.name)
}
continue
}
if sField.settings.inlined {
if err := api.mapDecode(ctx, m, fieldValue, sField.settings.ts, opts); err != nil {
return ierrors.Wrapf(err, "failed to deserialize inlined struct field %s", sField.name)
}
continue
}
fieldKey := FieldKeyString(sField.name)
if sField.settings.ts.fieldKey != nil {
fieldKey = sField.settings.ts.MustFieldKey()
}
mapVal, has := m[fieldKey]
if !has {
if sField.settings.isOptional || sField.settings.omitEmpty {
// initialize an empty slice if the kind is slice and its a nil pointer
if fieldValue.Kind() == reflect.Slice && fieldValue.IsNil() {
fieldValue.Set(reflect.MakeSlice(fieldValue.Type(), 0, 0))
}
continue
}
return ierrors.Errorf("missing map entry for field %s", sField.name)
}
if err := api.mapDecode(ctx, mapVal, fieldValue, sField.settings.ts, opts); err != nil {
return ierrors.Wrapf(err, "failed to deserialize struct field %s", sField.name)
}
}
return nil
}
func (api *API) mapDecodeSlice(ctx context.Context, mapVal any, value reflect.Value,
valueType reflect.Type, ts TypeSettings, opts *options) error {
if valueType.AssignableTo(bytesType) {
//nolint:forcetypeassert // false positive, we already checked the type via reflect
fieldValStr := mapVal.(string)
byteSlice, err := DecodeHex(fieldValStr)
if err != nil {
return ierrors.Wrap(err, "failed to read byte slice from map")
}
if opts.validation {
if err := ts.checkMinMaxBoundsLength(len(byteSlice)); err != nil {
return ierrors.Wrapf(err, "can't deserialize '%s' type", value.Kind())
}
}
addrValue := value.Addr().Convert(reflect.TypeOf((*[]byte)(nil)))
addrValue.Elem().SetBytes(byteSlice)
return nil
}
refVal := reflect.ValueOf(mapVal)
for i := range refVal.Len() {
elemValue := reflect.New(valueType.Elem()).Elem()
if err := api.mapDecode(ctx, refVal.Index(i).Interface(), elemValue, TypeSettings{}, opts); err != nil {
return ierrors.WithStack(err)
}
value.Set(reflect.Append(value, elemValue))
}
if opts.validation {
if err := ts.checkMinMaxBounds(value); err != nil {
return ierrors.Wrapf(err, "can't serialize '%s' type", value.Kind())
}
}
// check if the slice is a nil pointer to the slice type (in case the sliceLength is zero and the slice was not initialized before)
if value.IsNil() {
// initialize a new empty slice
value.Set(reflect.MakeSlice(valueType, 0, 0))
}
if opts.validation {
if err := api.checkArrayMustOccur(value, ts); err != nil {
return ierrors.Wrapf(err, "can't deserialize '%s' type", value.Kind())
}
}
return nil
}
func (api *API) mapDecodeMap(ctx context.Context, mapVal any, value reflect.Value,
valueType reflect.Type, ts TypeSettings, opts *options) error {
m, ok := mapVal.(map[string]any)
if !ok {
return ierrors.Errorf("non map[string]any in struct map decode, got %T instead", mapVal)
}
if value.IsNil() {
value.Set(reflect.MakeMap(valueType))
}
var typeSettingsSet bool
var keyTypeSettings, valueTypeSettings TypeSettings
for k, v := range m {
keyValue := reflect.New(valueType.Key()).Elem()
elemValue := reflect.New(valueType.Elem()).Elem()
if !typeSettingsSet {
keyTypeSettings = api.typeSettingsRegistry.GetByValue(keyValue)
valueTypeSettings = api.typeSettingsRegistry.GetByValue(elemValue)
typeSettingsSet = true
}
if err := api.mapDecode(ctx, k, keyValue, keyTypeSettings, opts); err != nil {
return ierrors.Wrapf(err, "failed to map decode map key of type %s", keyValue.Type())
}
if value.MapIndex(keyValue).IsValid() {
// map entry already exists
return ierrors.Wrapf(ErrMapValidationViolatesUniqueness, "map entry with key %v already exists", keyValue.Interface())
}
if err := api.mapDecode(ctx, v, elemValue, valueTypeSettings, opts); err != nil {
return ierrors.Wrapf(err, "failed to map decode map element of type %s", elemValue.Type())
}
value.SetMapIndex(keyValue, elemValue)
}
if opts.validation {
if err := ts.checkMinMaxBounds(value); err != nil {
return err
}
}
return nil
}