-
Notifications
You must be signed in to change notification settings - Fork 78
/
binary-decode.go
978 lines (898 loc) · 23.7 KB
/
binary-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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
package amino
import (
"fmt"
"math"
"reflect"
"time"
"github.com/pkg/errors"
"github.com/davecgh/go-spew/spew"
)
//----------------------------------------
// cdc.decodeReflectBinary
var (
ErrOverflowInt = errors.New("encoded integer value overflows int(32)")
)
const (
// architecture dependent int limits:
maxInt = int(^uint(0) >> 1)
minInt = -maxInt - 1
)
// This is the main entrypoint for decoding all types from binary form. This
// function calls decodeReflectBinary*, and generally those functions should
// only call this one, for the prefix bytes are consumed here when present.
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectBinary(bz []byte, info *TypeInfo,
rv reflect.Value, fopts FieldOptions, bare bool) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if info.Type.Kind() == reflect.Interface && rv.Kind() == reflect.Ptr {
panic("should not happen")
}
if printLog {
spew.Printf("(D) decodeReflectBinary(bz: %X, info: %v, rv: %#v (%v), fopts: %v)\n",
bz, info, rv.Interface(), rv.Type(), fopts)
defer func() {
fmt.Printf("(D) -> n: %v, err: %v\n", n, err)
}()
}
var _n int
// TODO consider the binary equivalent of json.Unmarshaller.
// Dereference-and-construct pointers all the way.
// This works for pointer-pointers.
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
newPtr := reflect.New(rv.Type().Elem())
rv.Set(newPtr)
}
rv = rv.Elem()
}
// Handle override if a pointer to rv implements UnmarshalAmino.
if info.IsAminoUnmarshaler {
// First, decode repr instance from bytes.
rrv := reflect.New(info.AminoUnmarshalReprType).Elem()
var rinfo *TypeInfo
rinfo, err = cdc.getTypeInfoWlock(info.AminoUnmarshalReprType)
if err != nil {
return
}
_n, err = cdc.decodeReflectBinary(bz, rinfo, rrv, fopts, bare)
if slide(&bz, &n, _n) && err != nil {
return
}
// Then, decode from repr instance.
uwrm := rv.Addr().MethodByName("UnmarshalAmino")
uwouts := uwrm.Call([]reflect.Value{rrv})
erri := uwouts[0].Interface()
if erri != nil {
err = erri.(error)
}
return
}
switch info.Type.Kind() {
//----------------------------------------
// Complex
case reflect.Interface:
_n, err = cdc.decodeReflectBinaryInterface(bz, info, rv, fopts, bare)
n += _n
return
case reflect.Array:
ert := info.Type.Elem()
if ert.Kind() == reflect.Uint8 {
_n, err = cdc.decodeReflectBinaryByteArray(bz, info, rv, fopts)
n += _n
} else {
_n, err = cdc.decodeReflectBinaryArray(bz, info, rv, fopts, bare)
n += _n
}
return
case reflect.Slice:
ert := info.Type.Elem()
if ert.Kind() == reflect.Uint8 {
_n, err = cdc.decodeReflectBinaryByteSlice(bz, info, rv, fopts)
n += _n
} else {
_n, err = cdc.decodeReflectBinarySlice(bz, info, rv, fopts, bare)
n += _n
}
return
case reflect.Struct:
_n, err = cdc.decodeReflectBinaryStruct(bz, info, rv, fopts, bare)
n += _n
return
//----------------------------------------
// Signed
case reflect.Int64:
var num int64
if fopts.BinFixed64 {
num, _n, err = DecodeInt64(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetInt(num)
} else {
var u64 uint64
u64, _n, err = DecodeUvarint(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetInt(int64(u64))
}
return
case reflect.Int32:
if fopts.BinFixed32 {
var num int32
num, _n, err = DecodeInt32(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetInt(int64(num))
} else {
var num uint64
num, _n, err = DecodeUvarint(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
if int64(num) > math.MaxInt32 || int64(num) < math.MinInt32 {
err = ErrOverflowInt
return
}
rv.SetInt(int64(num))
}
return
case reflect.Int16:
var num int16
num, _n, err = DecodeInt16(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetInt(int64(num))
return
case reflect.Int8:
var num int8
num, _n, err = DecodeInt8(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetInt(int64(num))
return
case reflect.Int:
var num uint64
num, _n, err = DecodeUvarint(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
if int64(num) > int64(maxInt) || int64(num) < int64(minInt) {
err = ErrOverflowInt
return
}
rv.SetInt(int64(num))
return
//----------------------------------------
// Unsigned
case reflect.Uint64:
var num uint64
if fopts.BinFixed64 {
num, _n, err = DecodeUint64(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(num)
} else {
num, _n, err = DecodeUvarint(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(num)
}
return
case reflect.Uint32:
if fopts.BinFixed32 {
var num uint32
num, _n, err = DecodeUint32(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(uint64(num))
} else {
var num uint64
num, _n, err = DecodeUvarint(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(num)
}
return
case reflect.Uint16:
var num uint16
num, _n, err = DecodeUint16(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(uint64(num))
return
case reflect.Uint8:
var num uint8
num, _n, err = DecodeUint8(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(uint64(num))
return
case reflect.Uint:
var num uint64
num, _n, err = DecodeUvarint(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetUint(num)
return
//----------------------------------------
// Misc.
case reflect.Bool:
var b bool
b, _n, err = DecodeBool(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetBool(b)
return
case reflect.Float64:
var f float64
if !fopts.Unsafe {
err = errors.New("float support requires `amino:\"unsafe\"`")
return
}
f, _n, err = DecodeFloat64(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetFloat(f)
return
case reflect.Float32:
var f float32
if !fopts.Unsafe {
err = errors.New("float support requires `amino:\"unsafe\"`")
return
}
f, _n, err = DecodeFloat32(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetFloat(float64(f))
return
case reflect.String:
var str string
str, _n, err = DecodeString(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.SetString(str)
return
default:
panic(fmt.Sprintf("unknown field type %v", info.Type.Kind()))
}
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectBinaryInterface(bz []byte, iinfo *TypeInfo, rv reflect.Value,
fopts FieldOptions, bare bool) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectBinaryInterface")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
if !rv.IsNil() {
// JAE: Heed this note, this is very tricky.
// I've forgotten the reason a second time,
// but I'm pretty sure that reason exists.
err = errors.New("decoding to a non-nil interface is not supported yet")
return
}
if !bare {
// Read byte-length prefixed byteslice.
var (
buf []byte
_n int
)
buf, _n, err = DecodeByteSlice(bz)
if slide(&bz, nil, _n) && err != nil {
return
}
// This is a trick for debuggability -- we slide on &n more later.
n += UvarintSize(uint64(len(buf)))
bz = buf
}
// Consume disambiguation / prefix bytes.
disamb, hasDisamb, prefix, hasPrefix, _n, err := DecodeDisambPrefixBytes(bz)
if slide(&bz, &n, _n) && err != nil {
return n, err
}
// Get concrete type info from disfix/prefix.
var cinfo *TypeInfo
switch {
case hasDisamb:
cinfo, err = cdc.getTypeInfoFromDisfixRlock(toDisfix(disamb, prefix))
case hasPrefix:
cinfo, err = cdc.getTypeInfoFromPrefixRlock(iinfo, prefix)
default:
err = errors.New("expected disambiguation or prefix bytes")
}
if err != nil {
return
}
// Construct the concrete type.
var crv, irvSet = constructConcreteType(cinfo)
isKnownType := (cinfo.Type.Kind() != reflect.Map) && (cinfo.Type.Kind() != reflect.Func)
if !isStructOrRepeatedStruct(cinfo) &&
!isPointerToStructOrToRepeatedStruct(crv, cinfo.Type) &&
len(bz) > 0 &&
(crv.Kind() != reflect.Interface) &&
isKnownType &&
fopts.BinFieldNum == 1 {
var (
fnum uint32
typ Typ3
nFnumTyp3 int
)
fnum, typ, nFnumTyp3, err = decodeFieldNumberAndTyp3(bz)
if err != nil {
return n, errors.Wrap(err, "could not decode field number and type")
}
if fnum != 1 {
return n, fmt.Errorf("expected field number: 1; got: %v", fnum)
}
typWanted := typeToTyp3(cinfo.Type, FieldOptions{})
if typ != typWanted {
return n, fmt.Errorf("expected field type %v for # %v of %v, got %v",
typWanted, fnum, cinfo.Type, typ)
}
slide(&bz, &n, nFnumTyp3)
}
// Decode into the concrete type.
_n, err = cdc.decodeReflectBinary(bz, cinfo, crv, fopts, true)
if slide(&bz, &n, _n) && err != nil {
rv.Set(irvSet) // Helps with debugging
return
}
// Earlier, we set bz to the byteslice read from buf.
// Ensure that all of bz was consumed.
if len(bz) > 0 {
err = errors.New("bytes left over after reading interface contents")
return
}
// We need to set here, for when !PointerPreferred and the type
// is say, an array of bytes (e.g. [32]byte), then we must call
// rv.Set() *after* the value was acquired.
// NOTE: rv.Set() should succeed because it was validated
// already during Register[Interface/Concrete].
rv.Set(irvSet)
return n, err
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectBinaryByteArray(bz []byte, info *TypeInfo, rv reflect.Value,
fopts FieldOptions) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectBinaryByteArray")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
if ert.Kind() != reflect.Uint8 {
panic("should not happen")
}
length := info.Type.Len()
if len(bz) < length {
return 0, fmt.Errorf("insufficient bytes to decode [%v]byte", length)
}
// Read byte-length prefixed byteslice.
byteslice, _n, err := DecodeByteSlice(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
if len(byteslice) != length {
err = fmt.Errorf("mismatched byte array length: Expected %v, got %v",
length, len(byteslice))
return
}
// Copy read byteslice to rv array.
reflect.Copy(rv, reflect.ValueOf(byteslice))
return n, err
}
// CONTRACT: rv.CanAddr() is true.
// NOTE: Keep the code structure similar to decodeReflectBinarySlice.
func (cdc *Codec) decodeReflectBinaryArray(bz []byte, info *TypeInfo, rv reflect.Value,
fopts FieldOptions, bare bool) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectBinaryArray")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
if ert.Kind() == reflect.Uint8 {
panic("should not happen")
}
length := info.Type.Len()
einfo, err := cdc.getTypeInfoWlock(ert)
if err != nil {
return
}
if !bare {
// Read byte-length prefixed byteslice.
var (
buf []byte
_n int
)
buf, _n, err = DecodeByteSlice(bz)
if slide(&bz, nil, _n) && err != nil {
return
}
// This is a trick for debuggability -- we slide on &n more later.
n += UvarintSize(uint64(len(buf)))
bz = buf
}
// If elem is not already a ByteLength type, read in packed form.
// This is a Proto wart due to Proto backwards compatibility issues.
// Amino2 will probably migrate to use the List typ3.
typ3 := typeToTyp3(einfo.Type, fopts)
if typ3 != Typ3ByteLength {
// Read elements in packed form.
for i := 0; i < length; i++ {
erv := rv.Index(i)
var _n int
_n, err = cdc.decodeReflectBinary(bz, einfo, erv, fopts, false)
if slide(&bz, &n, _n) && err != nil {
err = fmt.Errorf("error reading array contents: %v", err)
return
}
// Special case when reading default value, prefer nil.
if erv.Kind() == reflect.Ptr {
_, isDefault := isDefaultValue(erv)
if isDefault {
erv.Set(reflect.Zero(erv.Type()))
continue
}
}
}
// Ensure that we read the whole buffer.
if len(bz) > 0 {
err = errors.New("bytes left over after reading array contents")
return
}
} else {
// NOTE: ert is for the element value, while einfo.Type is dereferenced.
isErtStructPointer := ert.Kind() == reflect.Ptr && einfo.Type.Kind() == reflect.Struct
// Read elements in unpacked form.
for i := 0; i < length; i++ {
// Read field key (number and type).
var (
fnum uint32
typ Typ3
_n int
)
fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz)
// Validate field number and typ3.
if fnum != fopts.BinFieldNum {
err = errors.New(fmt.Sprintf("expected repeated field number %v, got %v", fopts.BinFieldNum, fnum))
return
}
if typ != Typ3ByteLength {
err = errors.New(fmt.Sprintf("expected repeated field type %v, got %v", Typ3ByteLength, typ))
return
}
if slide(&bz, &n, _n) && err != nil {
return
}
// Decode the next ByteLength bytes into erv.
var erv = rv.Index(i)
// Special case if:
// * next ByteLength bytes are 0x00, and
// * - erv is not a struct pointer, or
// - field option doesn't have EmptyElements set
// (the condition below uses demorgan's law)
if (len(bz) > 0 && bz[0] == 0x00) &&
!(isErtStructPointer && fopts.EmptyElements) {
slide(&bz, &n, 1)
erv.Set(defaultValue(erv.Type()))
continue
}
// Normal case, read next non-nil element from bz.
// In case of any inner lists in unpacked form.
efopts := fopts
efopts.BinFieldNum = 1
_n, err = cdc.decodeReflectBinary(bz, einfo, erv, efopts, false)
if slide(&bz, &n, _n) && err != nil {
err = fmt.Errorf("error reading array contents: %v", err)
return
}
}
// Ensure that there are no more elements left,
// and no field number regression either.
// This is to provide better error messages.
if len(bz) > 0 {
var fnum uint32
fnum, _, _, err = decodeFieldNumberAndTyp3(bz)
if err != nil {
return
}
if fnum <= fopts.BinFieldNum {
err = fmt.Errorf("unexpected field number %v after repeated field number %v", fnum, fopts.BinFieldNum)
return
}
}
}
return n, err
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectBinaryByteSlice(bz []byte, info *TypeInfo, rv reflect.Value,
fopts FieldOptions) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectByteSlice")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
if ert.Kind() != reflect.Uint8 {
panic("should not happen")
}
// If len(bz) == 0 the code below will err
if len(bz) == 0 {
rv.Set(info.ZeroValue)
return 0, nil
}
// Read byte-length prefixed byteslice.
var (
byteslice []byte
_n int
)
byteslice, _n, err = DecodeByteSlice(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
if len(byteslice) == 0 {
// Special case when length is 0.
// NOTE: We prefer nil slices.
rv.Set(info.ZeroValue)
} else {
rv.Set(reflect.ValueOf(byteslice))
}
return n, err
}
// CONTRACT: rv.CanAddr() is true.
// NOTE: Keep the code structure similar to decodeReflectBinaryArray.
func (cdc *Codec) decodeReflectBinarySlice(bz []byte, info *TypeInfo, rv reflect.Value,
fopts FieldOptions, bare bool) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectBinarySlice")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
if ert.Kind() == reflect.Uint8 {
panic("should not happen")
}
einfo, err := cdc.getTypeInfoWlock(ert)
if err != nil {
return
}
// Construct slice to collect decoded items to.
// NOTE: This is due to Proto3. How to best optimize?
esrt := reflect.SliceOf(ert)
var srv = reflect.Zero(esrt)
if !bare {
// Read byte-length prefixed byteslice.
var (
buf []byte
_n int
)
buf, _n, err = DecodeByteSlice(bz)
if slide(&bz, nil, _n) && err != nil {
return
}
// This is a trick for debuggability -- we slide on &n more later.
n += UvarintSize(uint64(len(buf)))
bz = buf
}
// If elem is not already a ByteLength type, read in packed form.
// This is a Proto wart due to Proto backwards compatibility issues.
// Amino2 will probably migrate to use the List typ3.
typ3 := typeToTyp3(einfo.Type, fopts)
if typ3 != Typ3ByteLength {
// Read elems in packed form.
for {
if len(bz) == 0 {
break
}
erv, _n := reflect.New(ert).Elem(), int(0)
_n, err = cdc.decodeReflectBinary(bz, einfo, erv, fopts, false)
if slide(&bz, &n, _n) && err != nil {
err = fmt.Errorf("error reading array contents: %v", err)
return
}
// Special case when reading default value, prefer nil.
if ert.Kind() == reflect.Ptr {
_, isDefault := isDefaultValue(erv)
if isDefault {
srv = reflect.Append(srv, reflect.Zero(ert))
continue
}
}
// Otherwise append to slice.
srv = reflect.Append(srv, erv)
}
} else {
// NOTE: ert is for the element value, while einfo.Type is dereferenced.
isErtStructPointer := ert.Kind() == reflect.Ptr && einfo.Type.Kind() == reflect.Struct
// Read elements in unpacked form.
for {
if len(bz) == 0 {
break
}
// Read field key (number and type).
var (
typ Typ3
_n int
fnum uint32
)
fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz)
// Validate field number and typ3.
if fnum < fopts.BinFieldNum {
err = errors.New(fmt.Sprintf("expected repeated field number %v or greater, got %v", fopts.BinFieldNum, fnum))
return
}
if fnum > fopts.BinFieldNum {
break
}
if typ != Typ3ByteLength {
err = errors.New(fmt.Sprintf("expected repeated field type %v, got %v", Typ3ByteLength, typ))
return
}
if slide(&bz, &n, _n) && err != nil {
return
}
// Decode the next ByteLength bytes into erv.
erv, _n := reflect.New(ert).Elem(), int(0)
// Special case if:
// * next ByteLength bytes are 0x00, and
// * - erv is not a struct pointer, or
// - field option doesn't have EmptyElements set
// (the condition below uses demorgan's law)
if (len(bz) > 0 && bz[0] == 0x00) &&
!(isErtStructPointer && fopts.EmptyElements) {
slide(&bz, &n, 1)
erv.Set(defaultValue(erv.Type()))
srv = reflect.Append(srv, erv)
continue
}
// Normal case, read next non-nil element from bz.
// In case of any inner lists in unpacked form.
efopts := fopts
efopts.BinFieldNum = 1
_n, err = cdc.decodeReflectBinary(bz, einfo, erv, efopts, false)
if slide(&bz, &n, _n) && err != nil {
err = fmt.Errorf("error reading array contents: %v", err)
return
}
srv = reflect.Append(srv, erv)
}
}
rv.Set(srv)
return n, err
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectBinaryStruct(bz []byte, info *TypeInfo, rv reflect.Value,
_ FieldOptions, bare bool) (n int, err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectBinaryStruct")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
_n := 0 // nolint: ineffassign
// NOTE: The "Struct" typ3 doesn't get read here.
// It's already implied, either by struct-key or list-element-type-byte.
if !bare {
// Read byte-length prefixed byteslice.
var buf []byte
buf, _n, err = DecodeByteSlice(bz)
if slide(&bz, nil, _n) && err != nil {
return
}
// This is a trick for debuggability -- we slide on &n more later.
n += UvarintSize(uint64(len(buf)))
bz = buf
}
switch info.Type {
case timeType:
// Special case: time.Time
var t time.Time
t, _n, err = DecodeTime(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
rv.Set(reflect.ValueOf(t))
default:
// Track the last seen field number.
var lastFieldNum uint32
// Read each field.
for _, field := range info.Fields {
// Get field rv and info.
var frv = rv.Field(field.Index)
var finfo *TypeInfo
finfo, err = cdc.getTypeInfoWlock(field.Type)
if err != nil {
return
}
// We're done if we've consumed all the bytes.
if len(bz) == 0 {
frv.Set(defaultValue(frv.Type()))
continue
}
if field.UnpackedList {
// This is a list that was encoded unpacked, e.g.
// with repeated field entries for each list item.
_n, err = cdc.decodeReflectBinary(bz, finfo, frv, field.FieldOptions, true)
if slide(&bz, &n, _n) && err != nil {
return
}
} else {
// Read field key (number and type).
var (
fnum uint32
typ Typ3
)
fnum, typ, _n, err = decodeFieldNumberAndTyp3(bz)
if field.BinFieldNum < fnum {
// Set zero field value.
frv.Set(defaultValue(frv.Type()))
continue
// Do not slide, we will read it again.
}
if fnum <= lastFieldNum {
err = fmt.Errorf("encountered fieldnNum: %v, but we have already seen fnum: %v\nbytes:%X",
fnum, lastFieldNum, bz)
return
}
lastFieldNum = fnum
if slide(&bz, &n, _n) && err != nil {
return
}
// Validate fnum and typ.
// NOTE: In the future, we'll support upgradeability.
// So in the future, this may not match,
// so we will need to remove this sanity check.
if field.BinFieldNum != fnum {
err = errors.New(fmt.Sprintf("expected field # %v of %v, got %v",
field.BinFieldNum, info.Type, fnum))
return
}
typWanted := typeToTyp3(finfo.Type, field.FieldOptions)
if typ != typWanted {
err = errors.New(fmt.Sprintf("expected field type %v for # %v of %v, got %v",
typWanted, fnum, info.Type, typ))
return
}
// Decode field into frv.
_n, err = cdc.decodeReflectBinary(bz, finfo, frv, field.FieldOptions, false)
if slide(&bz, &n, _n) && err != nil {
return
}
}
}
// Consume any remaining fields.
var (
fnum uint32
typ3 Typ3
)
for len(bz) > 0 {
fnum, typ3, _n, err = decodeFieldNumberAndTyp3(bz)
if slide(&bz, &n, _n) && err != nil {
return
}
if fnum <= lastFieldNum {
err = fmt.Errorf("encountered fieldnNum: %v, but we have already seen fnum: %v\nbytes:%X",
fnum, lastFieldNum, bz)
return
}
lastFieldNum = fnum
_n, err = consumeAny(typ3, bz)
if slide(&bz, &n, _n) && err != nil {
return
}
}
}
return n, err
}
//----------------------------------------
// consume* for skipping struct fields
// Read everything without doing anything with it. Report errors if they occur.
func consumeAny(typ3 Typ3, bz []byte) (n int, err error) {
var _n int
switch typ3 {
case Typ3Varint:
_, _n, err = DecodeVarint(bz)
case Typ38Byte:
_, _n, err = DecodeInt64(bz)
case Typ3ByteLength:
_, _n, err = DecodeByteSlice(bz)
case Typ3_4Byte:
_, _n, err = DecodeInt32(bz)
default:
err = fmt.Errorf("invalid typ3 bytes %v", typ3)
return
}
if err != nil {
// do not slide
return
}
slide(&bz, &n, _n)
return
}
//----------------------------------------
func DecodeDisambPrefixBytes(bz []byte) (db DisambBytes, hasDb bool, pb PrefixBytes, hasPb bool, n int, err error) {
// Validate
if len(bz) < 4 {
err = errors.New("while reading prefix bytes, EOF was encountered")
return // hasPb = false
}
if bz[0] == 0x00 { // Disfix
// Validate
if len(bz) < 8 {
err = errors.New("while reading prefix bytes, EOF was encountered")
return // hasPb = false
}
copy(db[0:3], bz[1:4])
copy(pb[0:4], bz[4:8])
hasDb = true
hasPb = true
n = 8
return
}
// Prefix
// General case with no disambiguation
copy(pb[0:4], bz[0:4])
hasDb = false
hasPb = true
n = 4
return
}
// Read field key.
func decodeFieldNumberAndTyp3(bz []byte) (num uint32, typ Typ3, n int, err error) {
// Read uvarint value.
value64, n, err := DecodeUvarint(bz)
if err != nil {
return
}
// Decode first typ3 byte.
typ = Typ3(value64 & 0x07)
// Decode num.
num64 := value64 >> 3
if num64 > (1<<29 - 1) {
err = fmt.Errorf("invalid field num %v", num64)
return
}
num = uint32(num64)
return
}