-
Notifications
You must be signed in to change notification settings - Fork 375
/
amino.go
945 lines (819 loc) · 22.7 KB
/
amino.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
package amino
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"path/filepath"
"reflect"
"runtime"
"time"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/gnolang/gno/tm2/pkg/amino/pkg"
"github.com/gnolang/gno/tm2/pkg/errors"
)
// Package "pkg" exists So dependencies can create Packages.
// We export it here so this amino package can use it natively.
type (
Package = pkg.Package
Type = pkg.Type
)
var (
// Global methods for global auto-sealing codec.
gcdc *Codec
// we use this time to init. an empty value (opposed to reflect.Zero which gives time.Time{} / 01-01-01 00:00:00)
emptyTime time.Time
// ErrNoPointer is thrown when you call a method that expects a pointer, e.g. Unmarshal
ErrNoPointer = errors.New("expected a pointer")
)
const (
unixEpochStr = "1970-01-01 00:00:00 +0000 UTC"
epochFmt = "2006-01-02 15:04:05 +0000 UTC"
)
func init() {
gcdc = NewCodec().WithPBBindings().Autoseal()
var err error
emptyTime, err = time.Parse(epochFmt, unixEpochStr)
if err != nil {
panic("couldn't parse empty value for time")
}
}
// XXX reorder global and cdc methods for consistency and logic.
func Marshal(o interface{}) ([]byte, error) {
return gcdc.Marshal(o)
}
func MustMarshal(o interface{}) []byte {
return gcdc.MustMarshal(o)
}
func MarshalSized(o interface{}) ([]byte, error) {
return gcdc.MarshalSized(o)
}
func MarshalSizedWriter(w io.Writer, o interface{}) (n int64, err error) {
return gcdc.MarshalSizedWriter(w, o)
}
func MustMarshalSized(o interface{}) []byte {
return gcdc.MustMarshalSized(o)
}
func MarshalAny(o interface{}) ([]byte, error) {
return gcdc.MarshalAny(o)
}
func MustMarshalAny(o interface{}) []byte {
return gcdc.MustMarshalAny(o)
}
func MarshalAnySized(o interface{}) ([]byte, error) {
return gcdc.MarshalAnySized(o)
}
func MustMarshalAnySized(o interface{}) []byte {
return gcdc.MustMarshalAnySized(o)
}
func MarshalAnySizedWriter(w io.Writer, o interface{}) (n int64, err error) {
return gcdc.MarshalAnySizedWriter(w, o)
}
func Unmarshal(bz []byte, ptr interface{}) error {
return gcdc.Unmarshal(bz, ptr)
}
func MustUnmarshal(bz []byte, ptr interface{}) {
gcdc.MustUnmarshal(bz, ptr)
}
func UnmarshalSized(bz []byte, ptr interface{}) error {
return gcdc.UnmarshalSized(bz, ptr)
}
func UnmarshalSizedReader(r io.Reader, ptr interface{}, maxSize int64) (n int64, err error) {
return gcdc.UnmarshalSizedReader(r, ptr, maxSize)
}
func MustUnmarshalSized(bz []byte, ptr interface{}) {
gcdc.MustUnmarshalSized(bz, ptr)
}
func UnmarshalAny(bz []byte, ptr interface{}) error {
return gcdc.UnmarshalAny(bz, ptr)
}
func UnmarshalAny2(typeURL string, value []byte, ptr interface{}) error {
return gcdc.UnmarshalAny2(typeURL, value, ptr)
}
func MustUnmarshalAny(bz []byte, ptr interface{}) {
gcdc.MustUnmarshalAny(bz, ptr)
}
func UnmarshalAnySized(bz []byte, ptr interface{}) error {
return gcdc.UnmarshalAnySized(bz, ptr)
}
func MarshalJSON(o interface{}) ([]byte, error) {
return gcdc.JSONMarshal(o)
}
func MarshalJSONAny(o interface{}) ([]byte, error) {
return gcdc.MarshalJSONAny(o)
}
func MustMarshalJSON(o interface{}) []byte {
return gcdc.MustMarshalJSON(o)
}
func MustMarshalJSONAny(o interface{}) []byte {
return gcdc.MustMarshalJSONAny(o)
}
func UnmarshalJSON(bz []byte, ptr interface{}) error {
return gcdc.JSONUnmarshal(bz, ptr)
}
func MustUnmarshalJSON(bz []byte, ptr interface{}) {
gcdc.MustUnmarshalJSON(bz, ptr)
}
func MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
return gcdc.MarshalJSONIndent(o, prefix, indent)
}
// XXX unstable API.
func GetTypeURL(o interface{}) string {
return gcdc.GetTypeURL(o)
}
// ----------------------------------------
// Typ3
type Typ3 uint8
const (
// Typ3 types
Typ3Varint = Typ3(0)
Typ38Byte = Typ3(1)
Typ3ByteLength = Typ3(2)
// Typ3_Struct = Typ3(3)
// Typ3_StructTerm = Typ3(4)
Typ34Byte = Typ3(5)
// Typ3_List = Typ3(6)
// Typ3_Interface = Typ3(7)
)
func (typ Typ3) String() string {
switch typ {
case Typ3Varint:
return "(U)Varint"
case Typ38Byte:
return "8Byte"
case Typ3ByteLength:
return "ByteLength"
// case Typ3_Struct:
// return "Struct"
// case Typ3_StructTerm:
// return "StructTerm"
case Typ34Byte:
return "4Byte"
// case Typ3_List:
// return "List"
// case Typ3_Interface:
// return "Interface"
default:
return fmt.Sprintf("<Invalid Typ3 %X>", byte(typ))
}
}
// ----------------------------------------
// *Codec methods
// ----------------------------------------
// Marshal* methods
// MarshalSized encodes the object o according to the Amino spec,
// but prefixed by a uvarint encoding of the object to encode.
// Use Marshal if you don't want byte-length prefixing.
//
// For consistency, MarshalSized will first dereference pointers
// before encoding. MarshalSized will panic if o is a nil-pointer,
// or if o is invalid.
func (cdc *Codec) MarshalSized(o interface{}) ([]byte, error) {
cdc.doAutoseal()
// Write the bytes here.
buf := new(bytes.Buffer)
// Write the bz without length-prefixing.
bz, err := cdc.Marshal(o)
if err != nil {
return nil, err
}
// Write uvarint(len(bz)).
err = EncodeUvarint(buf, uint64(len(bz)))
if err != nil {
return nil, err
}
// Write bz.
_, err = buf.Write(bz)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// MarshalSizedWriter writes the bytes as would be returned from
// MarshalSized to the writer w.
func (cdc *Codec) MarshalSizedWriter(w io.Writer, o interface{}) (n int64, err error) {
var (
bz []byte
_n int
)
bz, err = cdc.MarshalSized(o)
if err != nil {
return 0, err
}
_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
n = int64(_n)
return
}
// Panics if error.
func (cdc *Codec) MustMarshalSized(o interface{}) []byte {
bz, err := cdc.MarshalSized(o)
if err != nil {
panic(err)
}
return bz
}
func (cdc *Codec) MarshalAnySized(o interface{}) ([]byte, error) {
cdc.doAutoseal()
// Write the bytes here.
buf := new(bytes.Buffer)
// Write the bz without length-prefixing.
bz, err := cdc.MarshalAny(o)
if err != nil {
return nil, err
}
// Write uvarint(len(bz)).
err = EncodeUvarint(buf, uint64(len(bz)))
if err != nil {
return nil, err
}
// Write bz.
_, err = buf.Write(bz)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (cdc *Codec) MustMarshalAnySized(o interface{}) []byte {
bz, err := cdc.MarshalAnySized(o)
if err != nil {
panic(err)
}
return bz
}
func (cdc *Codec) MarshalAnySizedWriter(w io.Writer, o interface{}) (n int64, err error) {
var (
bz []byte
_n int
)
bz, err = cdc.MarshalAnySized(o)
if err != nil {
return 0, err
}
_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
n = int64(_n)
return
}
// Marshal encodes the object o according to the Amino spec.
// Marshal doesn't prefix the byte-length of the encoding,
// so the caller must handle framing.
// Type information as in google.protobuf.Any isn't included, so manually wrap
// before calling if you need to decode into an interface.
// NOTE: nil-struct-pointers have no encoding. In the context of a struct,
// the absence of a field does denote a nil-struct-pointer, but in general
// this is not the case, so unlike MarshalJSON.
func (cdc *Codec) Marshal(o interface{}) ([]byte, error) {
cdc.doAutoseal()
if cdc.usePBBindings {
pbm, ok := o.(PBMessager)
if ok {
return cdc.MarshalPBBindings(pbm)
} else {
// Fall back to using reflection for native primitive types.
}
}
return cdc.MarshalReflect(o)
}
// Use reflection.
func (cdc *Codec) MarshalReflect(o interface{}) ([]byte, error) {
// Dereference value if pointer.
rv := reflect.ValueOf(o)
if rv.Kind() == reflect.Ptr {
if rv.IsNil() {
panic("Marshal cannot marshal a nil pointer directly. Try wrapping in a struct?")
// NOTE: You can still do so by calling
// `.MarshalSized(struct{ *SomeType })` or so on.
}
rv = rv.Elem()
if rv.Kind() == reflect.Ptr {
panic("nested pointers not allowed")
}
}
// Encode Amino:binary bytes.
var bz []byte
buf := new(bytes.Buffer)
rt := rv.Type()
info, err := cdc.getTypeInfoWLock(rt)
if err != nil {
return nil, err
}
// Implicit struct or not?
// NOTE: similar to binary interface encoding.
fopts := FieldOptions{}
if !info.IsStructOrUnpacked(fopts) {
writeEmpty := false
// Encode with an implicit struct, with a single field with number 1.
// The type of this implicit field determines whether any
// length-prefixing happens after the typ3 byte.
// The second FieldOptions is empty, because this isn't a list of
// Typ3_ByteLength things, so however it is encoded, that option is no
// longer needed.
if err = cdc.writeFieldIfNotEmpty(buf, 1, info, FieldOptions{}, FieldOptions{}, rv, writeEmpty); err != nil {
return nil, err
}
bz = buf.Bytes()
} else {
// The passed in BinFieldNum is only relevant for when the type is to
// be encoded unpacked (elements are Typ3_ByteLength). In that case,
// encodeReflectBinary will repeat the field number as set here, as if
// encoded with an implicit struct.
err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{BinFieldNum: 1}, true, 0)
if err != nil {
return nil, err
}
bz = buf.Bytes()
}
// If bz is empty, prefer nil.
if len(bz) == 0 {
bz = nil
}
return bz, nil
}
// Use pbbindings.
func (cdc *Codec) MarshalPBBindings(pbm PBMessager) ([]byte, error) {
pbo, err := pbm.ToPBMessage(cdc)
if err != nil {
return nil, err
}
bz, err := proto.Marshal(pbo)
return bz, err
}
// Panics if error.
func (cdc *Codec) MustMarshal(o interface{}) []byte {
bz, err := cdc.Marshal(o)
if err != nil {
panic(err)
}
return bz
}
// MarshalAny encodes the registered object
// wrapped with google.protobuf.Any.
func (cdc *Codec) MarshalAny(o interface{}) ([]byte, error) {
cdc.doAutoseal()
// o cannot be nil, otherwise we don't know what type it is.
if o == nil {
return nil, errors.New("MarshalAny() requires non-nil argument")
}
// Dereference value if pointer.
rv, _, _ := maybeDerefValue(reflect.ValueOf(o))
rt := rv.Type()
// rv cannot be an interface.
if rv.Kind() == reflect.Interface {
return nil, errors.New("MarshalAny() requires registered concrete type")
}
// Make a temporary interface var, to contain the value of o.
ivar := rv.Interface()
var iinfo *TypeInfo
iinfo, err := cdc.getTypeInfoWLock(rt)
if err != nil {
return nil, err
}
// Encode as interface.
buf := new(bytes.Buffer)
err = cdc.encodeReflectBinaryInterface(buf, iinfo, reflect.ValueOf(&ivar).Elem(), FieldOptions{}, true)
if err != nil {
return nil, err
}
bz := buf.Bytes()
return bz, nil
}
// Panics if error.
func (cdc *Codec) MustMarshalAny(o interface{}) []byte {
bz, err := cdc.MarshalAny(o)
if err != nil {
panic(err)
}
return bz
}
// ----------------------------------------
// Unmarshal* methods
// Like Unmarshal, but will first decode the byte-length prefix.
// UnmarshalSized will panic if ptr is a nil-pointer.
// Returns an error if not all of bz is consumed.
func (cdc *Codec) UnmarshalSized(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("unmarshalSized cannot decode empty bytes")
}
// Read byte-length prefix.
u64, n := binary.Uvarint(bz)
if n < 0 {
return errors.New("Error reading msg byte-length prefix: got code %v", n)
}
if u64 > uint64(len(bz)-n) {
return errors.New("Not enough bytes to read in UnmarshalSized, want %v more bytes but only have %v",
u64, len(bz)-n)
} else if u64 < uint64(len(bz)-n) {
return errors.New("Bytes left over in UnmarshalSized, should read %v more bytes but have %v",
u64, len(bz)-n)
}
bz = bz[n:]
// Decode.
return cdc.Unmarshal(bz, ptr)
}
// Like Unmarshal, but will first read the byte-length prefix.
// UnmarshalSizedReader will panic if ptr is a nil-pointer.
// If maxSize is 0, there is no limit (not recommended).
func (cdc *Codec) UnmarshalSizedReader(r io.Reader, ptr interface{},
maxSize int64,
) (n int64, err error) {
if maxSize < 0 {
panic("maxSize cannot be negative.")
}
// Read byte-length prefix.
var l int64
var buf [binary.MaxVarintLen64]byte
for i := 0; i < len(buf); i++ {
_, err = r.Read(buf[i : i+1])
if err != nil {
return
}
n++
if buf[i]&0x80 == 0 {
break
}
if n >= maxSize {
err = errors.New(
"read overflow, maxSize is %v but uvarint(length-prefix) is itself greater than maxSize",
maxSize,
)
}
}
u64, _ := binary.Uvarint(buf[:])
if err != nil {
return
}
if maxSize > 0 {
if uint64(maxSize) < u64 {
err = errors.New("read overflow, maxSize is %v but this amino binary object is %v bytes", maxSize, u64)
return
}
if (maxSize - n) < int64(u64) {
err = errors.New(
"read overflow, maxSize is %v but this length-prefixed amino binary object is %v+%v bytes",
maxSize, n, u64,
)
return
}
}
l = int64(u64)
if l < 0 {
_ = errors.New( //nolint:errcheck
"read overflow, this implementation can't read this because, why would anyone have this much data? Hello from 2018",
)
}
// Read that many bytes.
bz := make([]byte, l)
_, err = io.ReadFull(r, bz)
if err != nil {
return
}
n += l
// Decode.
err = cdc.Unmarshal(bz, ptr)
return n, err
}
// Panics if error.
func (cdc *Codec) MustUnmarshalSized(bz []byte, ptr interface{}) {
err := cdc.UnmarshalSized(bz, ptr)
if err != nil {
panic(err)
}
}
// Like UnmarshalAny, but will first decode the byte-length prefix.
func (cdc *Codec) UnmarshalAnySized(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("unmarshalSized cannot decode empty bytes")
}
// Read byte-length prefix.
u64, n := binary.Uvarint(bz)
if n < 0 {
return errors.New("Error reading msg byte-length prefix: got code %v", n)
}
if u64 > uint64(len(bz)-n) {
return errors.New("Not enough bytes to read in UnmarshalAnySized, want %v more bytes but only have %v",
u64, len(bz)-n)
} else if u64 < uint64(len(bz)-n) {
return errors.New("Bytes left over in UnmarshalAnySized, should read %v more bytes but have %v",
u64, len(bz)-n)
}
bz = bz[n:]
// Decode.
return cdc.UnmarshalAny(bz, ptr)
}
// Unmarshal will panic if ptr is a nil-pointer.
func (cdc *Codec) Unmarshal(bz []byte, ptr interface{}) error {
cdc.doAutoseal()
if cdc.usePBBindings {
pbm, ok := ptr.(PBMessager)
if ok {
return cdc.unmarshalPBBindings(bz, pbm)
} else {
// Fall back to using reflection for native primitive types.
}
}
return cdc.unmarshalReflect(bz, ptr)
}
// Use reflection.
func (cdc *Codec) unmarshalReflect(bz []byte, ptr interface{}) error {
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
return ErrNoPointer
}
rv = rv.Elem()
rt := rv.Type()
info, err := cdc.getTypeInfoWLock(rt)
if err != nil {
return err
}
// See if we need to read the typ3 encoding of an implicit struct.
//
// If the dest ptr is an interface, it is assumed that the object is
// wrapped in a google.protobuf.Any object, so skip this step.
//
// See corresponding encoding message in this file, and also
// binary-decode.
bare := true
var nWrap int
if !info.IsStructOrUnpacked(FieldOptions{}) &&
len(bz) > 0 &&
(rv.Kind() != reflect.Interface) {
var (
fnum uint32
typ Typ3
nFnumTyp3 int
)
fnum, typ, nFnumTyp3, err = decodeFieldNumberAndTyp3(bz)
if err != nil {
return errors.Wrap(err, "could not decode field number and type")
}
if fnum != 1 {
return fmt.Errorf("expected field number: 1; got: %v", fnum)
}
typWanted := info.GetTyp3(FieldOptions{})
if typ != typWanted {
return fmt.Errorf("expected field type %v for # %v of %v, got %v",
typWanted, fnum, info.Type, typ)
}
slide(&bz, &nWrap, nFnumTyp3)
// "bare" is ignored when primitive, byteslice, bytearray.
// When typ3 != ByteLength, then typ3 is one of Typ3Varint, Typ38Byte,
// Typ34Byte; and they are all primitive.
bare = false
}
// Decode contents into rv.
n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{BinFieldNum: 1}, bare, 0)
if err != nil {
return fmt.Errorf(
"unmarshal to %v failed after %d bytes (%w): %X",
info.Type,
n+nWrap,
err,
bz,
)
}
if n != len(bz) {
return fmt.Errorf(
"unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X",
info.Type,
len(bz),
n+nWrap,
bz,
)
}
return nil
}
// Use pbbindings.
func (cdc *Codec) unmarshalPBBindings(bz []byte, pbm PBMessager) error {
pbo := pbm.EmptyPBMessage(cdc)
err := proto.Unmarshal(bz, pbo)
if err != nil {
rt := reflect.TypeOf(pbm)
info, err2 := cdc.getTypeInfoWLock(rt)
if err2 != nil {
return err2
}
return errors.New("unmarshal to %v failed: %v",
info.Type, err)
}
err = pbm.FromPBMessage(cdc, pbo)
if err != nil {
rt := reflect.TypeOf(pbm)
info, err2 := cdc.getTypeInfoWLock(rt)
if err2 != nil {
return err2
}
return errors.New("unmarshal to %v failed: %v",
info.Type, err)
}
return nil
}
// Panics if error.
func (cdc *Codec) MustUnmarshal(bz []byte, ptr interface{}) {
err := cdc.Unmarshal(bz, ptr)
if err != nil {
panic(err)
}
}
// UnmarshalAny decodes the registered object
// from an Any.
func (cdc *Codec) UnmarshalAny(bz []byte, ptr interface{}) (err error) {
cdc.doAutoseal()
// Dereference ptr which must be pointer to interface.
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
return ErrNoPointer
}
rv = rv.Elem()
// Get interface *TypeInfo.
iinfo, err := cdc.getTypeInfoWLock(rv.Type())
if err != nil {
return err
}
_, err = cdc.decodeReflectBinaryInterface(bz, iinfo, rv, FieldOptions{}, true)
return
}
// like UnmarshalAny() but with typeURL and value destructured.
func (cdc *Codec) UnmarshalAny2(typeURL string, value []byte, ptr interface{}) (err error) {
cdc.doAutoseal()
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
return ErrNoPointer
}
rv = rv.Elem()
_, err = cdc.decodeReflectBinaryAny(typeURL, value, rv, FieldOptions{})
return
}
func (cdc *Codec) MustUnmarshalAny(bz []byte, ptr interface{}) {
err := cdc.UnmarshalAny(bz, ptr)
if err != nil {
panic(err)
}
return
}
func (cdc *Codec) JSONMarshal(o interface{}) ([]byte, error) {
cdc.doAutoseal()
rv := reflect.ValueOf(o)
if !rv.IsValid() {
return []byte("null"), nil
}
rt := rv.Type()
w := new(bytes.Buffer)
info, err := cdc.getTypeInfoWLock(rt)
if err != nil {
return nil, err
}
if err = cdc.encodeReflectJSON(w, info, rv, FieldOptions{}); err != nil {
return nil, err
}
return w.Bytes(), nil
}
func (cdc *Codec) MarshalJSONAny(o interface{}) ([]byte, error) {
// o cannot be nil, otherwise we don't know what type it is.
if o == nil {
return nil, errors.New("MarshalJSONAny() requires non-nil argument")
}
// Dereference value if pointer.
rv := reflect.ValueOf(o)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
rt := rv.Type()
// rv cannot be an interface.
if rv.Kind() == reflect.Interface {
return nil, errors.New("MarshalJSONAny() requires registered concrete type")
}
// Make a temporary interface var, to contain the value of o.
ivar := rv.Interface()
var iinfo *TypeInfo
iinfo, err := cdc.getTypeInfoWLock(rt)
if err != nil {
return nil, err
}
// Encode as interface.
buf := new(bytes.Buffer)
err = cdc.encodeReflectJSONInterface(buf, iinfo, reflect.ValueOf(&ivar).Elem(), FieldOptions{})
if err != nil {
return nil, err
}
bz := buf.Bytes()
return bz, nil
}
// MustMarshalJSON panics if an error occurs. Besides tha behaves exactly like MarshalJSON.
func (cdc *Codec) MustMarshalJSON(o interface{}) []byte {
bz, err := cdc.JSONMarshal(o)
if err != nil {
panic(err)
}
return bz
}
// MustMarshalJSONAny panics if an error occurs. Besides tha behaves exactly like MarshalJSONAny.
func (cdc *Codec) MustMarshalJSONAny(o interface{}) []byte {
bz, err := cdc.MarshalJSONAny(o)
if err != nil {
panic(err)
}
return bz
}
func (cdc *Codec) JSONUnmarshal(bz []byte, ptr interface{}) error {
cdc.doAutoseal()
if len(bz) == 0 {
return errors.New("cannot decode empty bytes")
}
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
return errors.New("expected a pointer")
}
rv = rv.Elem()
rt := rv.Type()
info, err := cdc.getTypeInfoWLock(rt)
if err != nil {
return err
}
return cdc.decodeReflectJSON(bz, info, rv, FieldOptions{})
}
// MustUnmarshalJSON panics if an error occurs. Besides tha behaves exactly like UnmarshalJSON.
func (cdc *Codec) MustUnmarshalJSON(bz []byte, ptr interface{}) {
if err := cdc.JSONUnmarshal(bz, ptr); err != nil {
panic(err)
}
}
// MarshalJSONIndent calls json.Indent on the output of cdc.MarshalJSON
// using the given prefix and indent string.
func (cdc *Codec) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
bz, err := cdc.JSONMarshal(o)
if err != nil {
return nil, err
}
var out bytes.Buffer
err = json.Indent(&out, bz, prefix, indent)
if err != nil {
return nil, err
}
return out.Bytes(), nil
}
// ----------------------------------------
// Other
// NOTE: do not modify the result.
func RegisterPackage(pi *pkg.Package) *Package {
gcdc.RegisterPackage(pi)
return pi
}
func NewPackage(gopkg string, p3pkg string, dirname string) *Package {
return pkg.NewPackage(gopkg, p3pkg, dirname)
}
// NOTE: duplicated in pkg/pkg.go
func GetCallersDirname() string {
dirname := "" // derive from caller.
_, filename, _, ok := runtime.Caller(1)
if !ok {
panic("could not get caller to derive caller's package directory")
}
dirname = filepath.Dir(filename)
if filename == "" || dirname == "" {
panic("could not derive caller's package directory")
}
return dirname
}
// ----------------------------------------
// Object
// All concrete types must implement the Object interface for genproto
// bindings. They are generated automatically by genproto/bindings.go
type Object interface {
GetTypeURL() string
}
// TODO: this does need the cdc receiver,
// as it should also work for non-pbbindings-optimized types.
// Returns the default type url for the given concrete type.
// NOTE: It must be fast, as it is used in pbbindings.
// XXX Unstable API.
func (cdc *Codec) GetTypeURL(o interface{}) string {
if obj, ok := o.(Object); ok {
return obj.GetTypeURL()
}
switch o.(type) {
case time.Time, *time.Time, *timestamppb.Timestamp:
return "/google.protobuf.Timestamp"
case time.Duration, *time.Duration, *durationpb.Duration:
return "/google.protobuf.Duration"
}
rt := reflect.TypeOf(o)
// Doesn't have .GetTypeURL() and isn't well known.
// Do the slow thing (not relevant if pbbindings exists).
info, err := cdc.GetTypeInfo(rt)
if err != nil {
panic(err)
}
if info.TypeURL == "" {
panic("not yet supported")
}
return info.TypeURL
}
// ----------------------------------------
// Methods generated by genproto/bindings.go for faster encoding.
type PBMessager interface {
ToPBMessage(*Codec) (proto.Message, error)
EmptyPBMessage(*Codec) proto.Message
FromPBMessage(*Codec, proto.Message) error
}