github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/amino/amino.go (about)

     1  package amino
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"encoding/json"
     7  	"fmt"
     8  	"io"
     9  	"path/filepath"
    10  	"reflect"
    11  	"runtime"
    12  	"time"
    13  
    14  	"github.com/gnolang/gno/tm2/pkg/amino/pkg"
    15  	"github.com/gnolang/gno/tm2/pkg/errors"
    16  	"google.golang.org/protobuf/proto"
    17  	"google.golang.org/protobuf/types/known/durationpb"
    18  	"google.golang.org/protobuf/types/known/timestamppb"
    19  )
    20  
    21  // Package "pkg" exists So dependencies can create Packages.
    22  // We export it here so this amino package can use it natively.
    23  type (
    24  	Package = pkg.Package
    25  	Type    = pkg.Type
    26  )
    27  
    28  var (
    29  	// Global methods for global auto-sealing codec.
    30  	gcdc *Codec
    31  
    32  	// we use this time to init. an empty value (opposed to reflect.Zero which gives time.Time{} / 01-01-01 00:00:00)
    33  	emptyTime time.Time
    34  
    35  	// ErrNoPointer is thrown when you call a method that expects a pointer, e.g. Unmarshal
    36  	ErrNoPointer = errors.New("expected a pointer")
    37  )
    38  
    39  const (
    40  	unixEpochStr = "1970-01-01 00:00:00 +0000 UTC"
    41  	epochFmt     = "2006-01-02 15:04:05 +0000 UTC"
    42  )
    43  
    44  func init() {
    45  	gcdc = NewCodec().WithPBBindings().Autoseal()
    46  	var err error
    47  	emptyTime, err = time.Parse(epochFmt, unixEpochStr)
    48  	if err != nil {
    49  		panic("couldn't parse empty value for time")
    50  	}
    51  }
    52  
    53  // XXX reorder global and cdc methods for consistency and logic.
    54  
    55  func Marshal(o interface{}) ([]byte, error) {
    56  	return gcdc.Marshal(o)
    57  }
    58  
    59  func MustMarshal(o interface{}) []byte {
    60  	return gcdc.MustMarshal(o)
    61  }
    62  
    63  func MarshalSized(o interface{}) ([]byte, error) {
    64  	return gcdc.MarshalSized(o)
    65  }
    66  
    67  func MarshalSizedWriter(w io.Writer, o interface{}) (n int64, err error) {
    68  	return gcdc.MarshalSizedWriter(w, o)
    69  }
    70  
    71  func MustMarshalSized(o interface{}) []byte {
    72  	return gcdc.MustMarshalSized(o)
    73  }
    74  
    75  func MarshalAny(o interface{}) ([]byte, error) {
    76  	return gcdc.MarshalAny(o)
    77  }
    78  
    79  func MustMarshalAny(o interface{}) []byte {
    80  	return gcdc.MustMarshalAny(o)
    81  }
    82  
    83  func MarshalAnySized(o interface{}) ([]byte, error) {
    84  	return gcdc.MarshalAnySized(o)
    85  }
    86  
    87  func MustMarshalAnySized(o interface{}) []byte {
    88  	return gcdc.MustMarshalAnySized(o)
    89  }
    90  
    91  func MarshalAnySizedWriter(w io.Writer, o interface{}) (n int64, err error) {
    92  	return gcdc.MarshalAnySizedWriter(w, o)
    93  }
    94  
    95  func Unmarshal(bz []byte, ptr interface{}) error {
    96  	return gcdc.Unmarshal(bz, ptr)
    97  }
    98  
    99  func MustUnmarshal(bz []byte, ptr interface{}) {
   100  	gcdc.MustUnmarshal(bz, ptr)
   101  }
   102  
   103  func UnmarshalSized(bz []byte, ptr interface{}) error {
   104  	return gcdc.UnmarshalSized(bz, ptr)
   105  }
   106  
   107  func UnmarshalSizedReader(r io.Reader, ptr interface{}, maxSize int64) (n int64, err error) {
   108  	return gcdc.UnmarshalSizedReader(r, ptr, maxSize)
   109  }
   110  
   111  func MustUnmarshalSized(bz []byte, ptr interface{}) {
   112  	gcdc.MustUnmarshalSized(bz, ptr)
   113  }
   114  
   115  func UnmarshalAny(bz []byte, ptr interface{}) error {
   116  	return gcdc.UnmarshalAny(bz, ptr)
   117  }
   118  
   119  func UnmarshalAny2(typeURL string, value []byte, ptr interface{}) error {
   120  	return gcdc.UnmarshalAny2(typeURL, value, ptr)
   121  }
   122  
   123  func MustUnmarshalAny(bz []byte, ptr interface{}) {
   124  	gcdc.MustUnmarshalAny(bz, ptr)
   125  }
   126  
   127  func UnmarshalAnySized(bz []byte, ptr interface{}) error {
   128  	return gcdc.UnmarshalAnySized(bz, ptr)
   129  }
   130  
   131  func MarshalJSON(o interface{}) ([]byte, error) {
   132  	return gcdc.MarshalJSON(o)
   133  }
   134  
   135  func MarshalJSONAny(o interface{}) ([]byte, error) {
   136  	return gcdc.MarshalJSONAny(o)
   137  }
   138  
   139  func MustMarshalJSON(o interface{}) []byte {
   140  	return gcdc.MustMarshalJSON(o)
   141  }
   142  
   143  func MustMarshalJSONAny(o interface{}) []byte {
   144  	return gcdc.MustMarshalJSONAny(o)
   145  }
   146  
   147  func UnmarshalJSON(bz []byte, ptr interface{}) error {
   148  	return gcdc.UnmarshalJSON(bz, ptr)
   149  }
   150  
   151  func MustUnmarshalJSON(bz []byte, ptr interface{}) {
   152  	gcdc.MustUnmarshalJSON(bz, ptr)
   153  }
   154  
   155  func MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
   156  	return gcdc.MarshalJSONIndent(o, prefix, indent)
   157  }
   158  
   159  // XXX unstable API.
   160  func GetTypeURL(o interface{}) string {
   161  	return gcdc.GetTypeURL(o)
   162  }
   163  
   164  // ----------------------------------------
   165  // Typ3
   166  
   167  type Typ3 uint8
   168  
   169  const (
   170  	// Typ3 types
   171  	Typ3Varint     = Typ3(0)
   172  	Typ38Byte      = Typ3(1)
   173  	Typ3ByteLength = Typ3(2)
   174  	// Typ3_Struct     = Typ3(3)
   175  	// Typ3_StructTerm = Typ3(4)
   176  	Typ34Byte = Typ3(5)
   177  	// Typ3_List       = Typ3(6)
   178  	// Typ3_Interface  = Typ3(7)
   179  )
   180  
   181  func (typ Typ3) String() string {
   182  	switch typ {
   183  	case Typ3Varint:
   184  		return "(U)Varint"
   185  	case Typ38Byte:
   186  		return "8Byte"
   187  	case Typ3ByteLength:
   188  		return "ByteLength"
   189  	// case Typ3_Struct:
   190  	//	return "Struct"
   191  	// case Typ3_StructTerm:
   192  	//	return "StructTerm"
   193  	case Typ34Byte:
   194  		return "4Byte"
   195  	// case Typ3_List:
   196  	//	return "List"
   197  	// case Typ3_Interface:
   198  	//	return "Interface"
   199  	default:
   200  		return fmt.Sprintf("<Invalid Typ3 %X>", byte(typ))
   201  	}
   202  }
   203  
   204  // ----------------------------------------
   205  // *Codec methods
   206  
   207  // ----------------------------------------
   208  // Marshal* methods
   209  
   210  // MarshalSized encodes the object o according to the Amino spec,
   211  // but prefixed by a uvarint encoding of the object to encode.
   212  // Use Marshal if you don't want byte-length prefixing.
   213  //
   214  // For consistency, MarshalSized will first dereference pointers
   215  // before encoding.  MarshalSized will panic if o is a nil-pointer,
   216  // or if o is invalid.
   217  func (cdc *Codec) MarshalSized(o interface{}) ([]byte, error) {
   218  	cdc.doAutoseal()
   219  
   220  	// Write the bytes here.
   221  	buf := new(bytes.Buffer)
   222  
   223  	// Write the bz without length-prefixing.
   224  	bz, err := cdc.Marshal(o)
   225  	if err != nil {
   226  		return nil, err
   227  	}
   228  
   229  	// Write uvarint(len(bz)).
   230  	err = EncodeUvarint(buf, uint64(len(bz)))
   231  	if err != nil {
   232  		return nil, err
   233  	}
   234  
   235  	// Write bz.
   236  	_, err = buf.Write(bz)
   237  	if err != nil {
   238  		return nil, err
   239  	}
   240  
   241  	return buf.Bytes(), nil
   242  }
   243  
   244  // MarshalSizedWriter writes the bytes as would be returned from
   245  // MarshalSized to the writer w.
   246  func (cdc *Codec) MarshalSizedWriter(w io.Writer, o interface{}) (n int64, err error) {
   247  	var (
   248  		bz []byte
   249  		_n int
   250  	)
   251  	bz, err = cdc.MarshalSized(o)
   252  	if err != nil {
   253  		return 0, err
   254  	}
   255  	_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
   256  	n = int64(_n)
   257  	return
   258  }
   259  
   260  // Panics if error.
   261  func (cdc *Codec) MustMarshalSized(o interface{}) []byte {
   262  	bz, err := cdc.MarshalSized(o)
   263  	if err != nil {
   264  		panic(err)
   265  	}
   266  	return bz
   267  }
   268  
   269  func (cdc *Codec) MarshalAnySized(o interface{}) ([]byte, error) {
   270  	cdc.doAutoseal()
   271  
   272  	// Write the bytes here.
   273  	buf := new(bytes.Buffer)
   274  
   275  	// Write the bz without length-prefixing.
   276  	bz, err := cdc.MarshalAny(o)
   277  	if err != nil {
   278  		return nil, err
   279  	}
   280  
   281  	// Write uvarint(len(bz)).
   282  	err = EncodeUvarint(buf, uint64(len(bz)))
   283  	if err != nil {
   284  		return nil, err
   285  	}
   286  
   287  	// Write bz.
   288  	_, err = buf.Write(bz)
   289  	if err != nil {
   290  		return nil, err
   291  	}
   292  
   293  	return buf.Bytes(), nil
   294  }
   295  
   296  func (cdc *Codec) MustMarshalAnySized(o interface{}) []byte {
   297  	bz, err := cdc.MarshalAnySized(o)
   298  	if err != nil {
   299  		panic(err)
   300  	}
   301  	return bz
   302  }
   303  
   304  func (cdc *Codec) MarshalAnySizedWriter(w io.Writer, o interface{}) (n int64, err error) {
   305  	var (
   306  		bz []byte
   307  		_n int
   308  	)
   309  	bz, err = cdc.MarshalAnySized(o)
   310  	if err != nil {
   311  		return 0, err
   312  	}
   313  	_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
   314  	n = int64(_n)
   315  	return
   316  }
   317  
   318  // Marshal encodes the object o according to the Amino spec.
   319  // Marshal doesn't prefix the byte-length of the encoding,
   320  // so the caller must handle framing.
   321  // Type information as in google.protobuf.Any isn't included, so manually wrap
   322  // before calling if you need to decode into an interface.
   323  // NOTE: nil-struct-pointers have no encoding. In the context of a struct,
   324  // the absence of a field does denote a nil-struct-pointer, but in general
   325  // this is not the case, so unlike MarshalJSON.
   326  func (cdc *Codec) Marshal(o interface{}) ([]byte, error) {
   327  	cdc.doAutoseal()
   328  
   329  	if cdc.usePBBindings {
   330  		pbm, ok := o.(PBMessager)
   331  		if ok {
   332  			return cdc.MarshalPBBindings(pbm)
   333  		} else {
   334  			// Fall back to using reflection for native primitive types.
   335  		}
   336  	}
   337  
   338  	return cdc.MarshalReflect(o)
   339  }
   340  
   341  // Use reflection.
   342  func (cdc *Codec) MarshalReflect(o interface{}) ([]byte, error) {
   343  	// Dereference value if pointer.
   344  	rv := reflect.ValueOf(o)
   345  	if rv.Kind() == reflect.Ptr {
   346  		if rv.IsNil() {
   347  			panic("Marshal cannot marshal a nil pointer directly. Try wrapping in a struct?")
   348  			// NOTE: You can still do so by calling
   349  			// `.MarshalSized(struct{ *SomeType })` or so on.
   350  		}
   351  		rv = rv.Elem()
   352  		if rv.Kind() == reflect.Ptr {
   353  			panic("nested pointers not allowed")
   354  		}
   355  	}
   356  
   357  	// Encode Amino:binary bytes.
   358  	var bz []byte
   359  	buf := new(bytes.Buffer)
   360  	rt := rv.Type()
   361  	info, err := cdc.getTypeInfoWLock(rt)
   362  	if err != nil {
   363  		return nil, err
   364  	}
   365  	// Implicit struct or not?
   366  	// NOTE: similar to binary interface encoding.
   367  	fopts := FieldOptions{}
   368  	if !info.IsStructOrUnpacked(fopts) {
   369  		writeEmpty := false
   370  		// Encode with an implicit struct, with a single field with number 1.
   371  		// The type of this implicit field determines whether any
   372  		// length-prefixing happens after the typ3 byte.
   373  		// The second FieldOptions is empty, because this isn't a list of
   374  		// Typ3_ByteLength things, so however it is encoded, that option is no
   375  		// longer needed.
   376  		if err = cdc.writeFieldIfNotEmpty(buf, 1, info, FieldOptions{}, FieldOptions{}, rv, writeEmpty); err != nil {
   377  			return nil, err
   378  		}
   379  		bz = buf.Bytes()
   380  	} else {
   381  		// The passed in BinFieldNum is only relevant for when the type is to
   382  		// be encoded unpacked (elements are Typ3_ByteLength).  In that case,
   383  		// encodeReflectBinary will repeat the field number as set here, as if
   384  		// encoded with an implicit struct.
   385  		err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{BinFieldNum: 1}, true, 0)
   386  		if err != nil {
   387  			return nil, err
   388  		}
   389  		bz = buf.Bytes()
   390  	}
   391  	// If bz is empty, prefer nil.
   392  	if len(bz) == 0 {
   393  		bz = nil
   394  	}
   395  	return bz, nil
   396  }
   397  
   398  // Use pbbindings.
   399  func (cdc *Codec) MarshalPBBindings(pbm PBMessager) ([]byte, error) {
   400  	pbo, err := pbm.ToPBMessage(cdc)
   401  	if err != nil {
   402  		return nil, err
   403  	}
   404  	bz, err := proto.Marshal(pbo)
   405  	return bz, err
   406  }
   407  
   408  // Panics if error.
   409  func (cdc *Codec) MustMarshal(o interface{}) []byte {
   410  	bz, err := cdc.Marshal(o)
   411  	if err != nil {
   412  		panic(err)
   413  	}
   414  	return bz
   415  }
   416  
   417  // MarshalAny encodes the registered object
   418  // wrapped with google.protobuf.Any.
   419  func (cdc *Codec) MarshalAny(o interface{}) ([]byte, error) {
   420  	cdc.doAutoseal()
   421  
   422  	// o cannot be nil, otherwise we don't know what type it is.
   423  	if o == nil {
   424  		return nil, errors.New("MarshalAny() requires non-nil argument")
   425  	}
   426  
   427  	// Dereference value if pointer.
   428  	rv, _, _ := maybeDerefValue(reflect.ValueOf(o))
   429  	rt := rv.Type()
   430  
   431  	// rv cannot be an interface.
   432  	if rv.Kind() == reflect.Interface {
   433  		return nil, errors.New("MarshalAny() requires registered concrete type")
   434  	}
   435  
   436  	// Make a temporary interface var, to contain the value of o.
   437  	ivar := rv.Interface()
   438  	var iinfo *TypeInfo
   439  	iinfo, err := cdc.getTypeInfoWLock(rt)
   440  	if err != nil {
   441  		return nil, err
   442  	}
   443  
   444  	// Encode as interface.
   445  	buf := new(bytes.Buffer)
   446  	err = cdc.encodeReflectBinaryInterface(buf, iinfo, reflect.ValueOf(&ivar).Elem(), FieldOptions{}, true)
   447  	if err != nil {
   448  		return nil, err
   449  	}
   450  	bz := buf.Bytes()
   451  
   452  	return bz, nil
   453  }
   454  
   455  // Panics if error.
   456  func (cdc *Codec) MustMarshalAny(o interface{}) []byte {
   457  	bz, err := cdc.MarshalAny(o)
   458  	if err != nil {
   459  		panic(err)
   460  	}
   461  	return bz
   462  }
   463  
   464  // ----------------------------------------
   465  // Unmarshal* methods
   466  
   467  // Like Unmarshal, but will first decode the byte-length prefix.
   468  // UnmarshalSized will panic if ptr is a nil-pointer.
   469  // Returns an error if not all of bz is consumed.
   470  func (cdc *Codec) UnmarshalSized(bz []byte, ptr interface{}) error {
   471  	if len(bz) == 0 {
   472  		return errors.New("unmarshalSized cannot decode empty bytes")
   473  	}
   474  
   475  	// Read byte-length prefix.
   476  	u64, n := binary.Uvarint(bz)
   477  	if n < 0 {
   478  		return errors.New("Error reading msg byte-length prefix: got code %v", n)
   479  	}
   480  	if u64 > uint64(len(bz)-n) {
   481  		return errors.New("Not enough bytes to read in UnmarshalSized, want %v more bytes but only have %v",
   482  			u64, len(bz)-n)
   483  	} else if u64 < uint64(len(bz)-n) {
   484  		return errors.New("Bytes left over in UnmarshalSized, should read %v more bytes but have %v",
   485  			u64, len(bz)-n)
   486  	}
   487  	bz = bz[n:]
   488  
   489  	// Decode.
   490  	return cdc.Unmarshal(bz, ptr)
   491  }
   492  
   493  // Like Unmarshal, but will first read the byte-length prefix.
   494  // UnmarshalSizedReader will panic if ptr is a nil-pointer.
   495  // If maxSize is 0, there is no limit (not recommended).
   496  func (cdc *Codec) UnmarshalSizedReader(r io.Reader, ptr interface{},
   497  	maxSize int64,
   498  ) (n int64, err error) {
   499  	if maxSize < 0 {
   500  		panic("maxSize cannot be negative.")
   501  	}
   502  
   503  	// Read byte-length prefix.
   504  	var l int64
   505  	var buf [binary.MaxVarintLen64]byte
   506  	for i := 0; i < len(buf); i++ {
   507  		_, err = r.Read(buf[i : i+1])
   508  		if err != nil {
   509  			return
   510  		}
   511  		n++
   512  		if buf[i]&0x80 == 0 {
   513  			break
   514  		}
   515  		if n >= maxSize {
   516  			err = errors.New(
   517  				"read overflow, maxSize is %v but uvarint(length-prefix) is itself greater than maxSize",
   518  				maxSize,
   519  			)
   520  		}
   521  	}
   522  	u64, _ := binary.Uvarint(buf[:])
   523  	if err != nil {
   524  		return
   525  	}
   526  	if maxSize > 0 {
   527  		if uint64(maxSize) < u64 {
   528  			err = errors.New("read overflow, maxSize is %v but this amino binary object is %v bytes", maxSize, u64)
   529  			return
   530  		}
   531  		if (maxSize - n) < int64(u64) {
   532  			err = errors.New(
   533  				"read overflow, maxSize is %v but this length-prefixed amino binary object is %v+%v bytes",
   534  				maxSize, n, u64,
   535  			)
   536  			return
   537  		}
   538  	}
   539  	l = int64(u64)
   540  	if l < 0 {
   541  		_ = errors.New( //nolint:errcheck
   542  			"read overflow, this implementation can't read this because, why would anyone have this much data? Hello from 2018",
   543  		)
   544  	}
   545  
   546  	// Read that many bytes.
   547  	bz := make([]byte, l)
   548  	_, err = io.ReadFull(r, bz)
   549  	if err != nil {
   550  		return
   551  	}
   552  	n += l
   553  
   554  	// Decode.
   555  	err = cdc.Unmarshal(bz, ptr)
   556  	return n, err
   557  }
   558  
   559  // Panics if error.
   560  func (cdc *Codec) MustUnmarshalSized(bz []byte, ptr interface{}) {
   561  	err := cdc.UnmarshalSized(bz, ptr)
   562  	if err != nil {
   563  		panic(err)
   564  	}
   565  }
   566  
   567  // Like UnmarshalAny, but will first decode the byte-length prefix.
   568  func (cdc *Codec) UnmarshalAnySized(bz []byte, ptr interface{}) error {
   569  	if len(bz) == 0 {
   570  		return errors.New("unmarshalSized cannot decode empty bytes")
   571  	}
   572  
   573  	// Read byte-length prefix.
   574  	u64, n := binary.Uvarint(bz)
   575  	if n < 0 {
   576  		return errors.New("Error reading msg byte-length prefix: got code %v", n)
   577  	}
   578  	if u64 > uint64(len(bz)-n) {
   579  		return errors.New("Not enough bytes to read in UnmarshalAnySized, want %v more bytes but only have %v",
   580  			u64, len(bz)-n)
   581  	} else if u64 < uint64(len(bz)-n) {
   582  		return errors.New("Bytes left over in UnmarshalAnySized, should read %v more bytes but have %v",
   583  			u64, len(bz)-n)
   584  	}
   585  	bz = bz[n:]
   586  
   587  	// Decode.
   588  	return cdc.UnmarshalAny(bz, ptr)
   589  }
   590  
   591  // Unmarshal will panic if ptr is a nil-pointer.
   592  func (cdc *Codec) Unmarshal(bz []byte, ptr interface{}) error {
   593  	cdc.doAutoseal()
   594  
   595  	if cdc.usePBBindings {
   596  		pbm, ok := ptr.(PBMessager)
   597  		if ok {
   598  			return cdc.unmarshalPBBindings(bz, pbm)
   599  		} else {
   600  			// Fall back to using reflection for native primitive types.
   601  		}
   602  	}
   603  
   604  	return cdc.unmarshalReflect(bz, ptr)
   605  }
   606  
   607  // Use reflection.
   608  func (cdc *Codec) unmarshalReflect(bz []byte, ptr interface{}) error {
   609  	rv := reflect.ValueOf(ptr)
   610  	if rv.Kind() != reflect.Ptr {
   611  		return ErrNoPointer
   612  	}
   613  	rv = rv.Elem()
   614  	rt := rv.Type()
   615  	info, err := cdc.getTypeInfoWLock(rt)
   616  	if err != nil {
   617  		return err
   618  	}
   619  
   620  	// See if we need to read the typ3 encoding of an implicit struct.
   621  	//
   622  	// If the dest ptr is an interface, it is assumed that the object is
   623  	// wrapped in a google.protobuf.Any object, so skip this step.
   624  	//
   625  	// See corresponding encoding message in this file, and also
   626  	// binary-decode.
   627  	bare := true
   628  	var nWrap int
   629  	if !info.IsStructOrUnpacked(FieldOptions{}) &&
   630  		len(bz) > 0 &&
   631  		(rv.Kind() != reflect.Interface) {
   632  		var (
   633  			fnum      uint32
   634  			typ       Typ3
   635  			nFnumTyp3 int
   636  		)
   637  		fnum, typ, nFnumTyp3, err = decodeFieldNumberAndTyp3(bz)
   638  		if err != nil {
   639  			return errors.Wrap(err, "could not decode field number and type")
   640  		}
   641  		if fnum != 1 {
   642  			return fmt.Errorf("expected field number: 1; got: %v", fnum)
   643  		}
   644  		typWanted := info.GetTyp3(FieldOptions{})
   645  		if typ != typWanted {
   646  			return fmt.Errorf("expected field type %v for # %v of %v, got %v",
   647  				typWanted, fnum, info.Type, typ)
   648  		}
   649  
   650  		slide(&bz, &nWrap, nFnumTyp3)
   651  		// "bare" is ignored when primitive, byteslice, bytearray.
   652  		// When typ3 != ByteLength, then typ3 is one of Typ3Varint, Typ38Byte,
   653  		// Typ34Byte; and they are all primitive.
   654  		bare = false
   655  	}
   656  
   657  	// Decode contents into rv.
   658  	n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{BinFieldNum: 1}, bare, 0)
   659  	if err != nil {
   660  		return fmt.Errorf(
   661  			"unmarshal to %v failed after %d bytes (%w): %X",
   662  			info.Type,
   663  			n+nWrap,
   664  			err,
   665  			bz,
   666  		)
   667  	}
   668  	if n != len(bz) {
   669  		return fmt.Errorf(
   670  			"unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X",
   671  			info.Type,
   672  			len(bz),
   673  			n+nWrap,
   674  			bz,
   675  		)
   676  	}
   677  
   678  	return nil
   679  }
   680  
   681  // Use pbbindings.
   682  func (cdc *Codec) unmarshalPBBindings(bz []byte, pbm PBMessager) error {
   683  	pbo := pbm.EmptyPBMessage(cdc)
   684  	err := proto.Unmarshal(bz, pbo)
   685  	if err != nil {
   686  		rt := reflect.TypeOf(pbm)
   687  		info, err2 := cdc.getTypeInfoWLock(rt)
   688  		if err2 != nil {
   689  			return err2
   690  		}
   691  		return errors.New("unmarshal to %v failed: %v",
   692  			info.Type, err)
   693  	}
   694  	err = pbm.FromPBMessage(cdc, pbo)
   695  	if err != nil {
   696  		rt := reflect.TypeOf(pbm)
   697  		info, err2 := cdc.getTypeInfoWLock(rt)
   698  		if err2 != nil {
   699  			return err2
   700  		}
   701  		return errors.New("unmarshal to %v failed: %v",
   702  			info.Type, err)
   703  	}
   704  	return nil
   705  }
   706  
   707  // Panics if error.
   708  func (cdc *Codec) MustUnmarshal(bz []byte, ptr interface{}) {
   709  	err := cdc.Unmarshal(bz, ptr)
   710  	if err != nil {
   711  		panic(err)
   712  	}
   713  }
   714  
   715  // UnmarshalAny decodes the registered object
   716  // from an Any.
   717  func (cdc *Codec) UnmarshalAny(bz []byte, ptr interface{}) (err error) {
   718  	cdc.doAutoseal()
   719  
   720  	// Dereference ptr which must be pointer to interface.
   721  	rv := reflect.ValueOf(ptr)
   722  	if rv.Kind() != reflect.Ptr {
   723  		return ErrNoPointer
   724  	}
   725  	rv = rv.Elem()
   726  
   727  	// Get interface *TypeInfo.
   728  	iinfo, err := cdc.getTypeInfoWLock(rv.Type())
   729  	if err != nil {
   730  		return err
   731  	}
   732  
   733  	_, err = cdc.decodeReflectBinaryInterface(bz, iinfo, rv, FieldOptions{}, true)
   734  	return
   735  }
   736  
   737  // like UnmarshalAny() but with typeURL and value destructured.
   738  func (cdc *Codec) UnmarshalAny2(typeURL string, value []byte, ptr interface{}) (err error) {
   739  	cdc.doAutoseal()
   740  
   741  	rv := reflect.ValueOf(ptr)
   742  	if rv.Kind() != reflect.Ptr {
   743  		return ErrNoPointer
   744  	}
   745  	rv = rv.Elem()
   746  	_, err = cdc.decodeReflectBinaryAny(typeURL, value, rv, FieldOptions{})
   747  	return
   748  }
   749  
   750  func (cdc *Codec) MustUnmarshalAny(bz []byte, ptr interface{}) {
   751  	err := cdc.UnmarshalAny(bz, ptr)
   752  	if err != nil {
   753  		panic(err)
   754  	}
   755  	return
   756  }
   757  
   758  func (cdc *Codec) MarshalJSON(o interface{}) ([]byte, error) {
   759  	cdc.doAutoseal()
   760  
   761  	rv := reflect.ValueOf(o)
   762  	if rv.Kind() == reflect.Invalid {
   763  		return []byte("null"), nil
   764  	}
   765  	rt := rv.Type()
   766  	w := new(bytes.Buffer)
   767  	info, err := cdc.getTypeInfoWLock(rt)
   768  	if err != nil {
   769  		return nil, err
   770  	}
   771  	if err = cdc.encodeReflectJSON(w, info, rv, FieldOptions{}); err != nil {
   772  		return nil, err
   773  	}
   774  	return w.Bytes(), nil
   775  }
   776  
   777  func (cdc *Codec) MarshalJSONAny(o interface{}) ([]byte, error) {
   778  	// o cannot be nil, otherwise we don't know what type it is.
   779  	if o == nil {
   780  		return nil, errors.New("MarshalJSONAny() requires non-nil argument")
   781  	}
   782  
   783  	// Dereference value if pointer.
   784  	rv := reflect.ValueOf(o)
   785  	if rv.Kind() == reflect.Ptr {
   786  		rv = rv.Elem()
   787  	}
   788  	rt := rv.Type()
   789  
   790  	// rv cannot be an interface.
   791  	if rv.Kind() == reflect.Interface {
   792  		return nil, errors.New("MarshalJSONAny() requires registered concrete type")
   793  	}
   794  
   795  	// Make a temporary interface var, to contain the value of o.
   796  	ivar := rv.Interface()
   797  	var iinfo *TypeInfo
   798  	iinfo, err := cdc.getTypeInfoWLock(rt)
   799  	if err != nil {
   800  		return nil, err
   801  	}
   802  
   803  	// Encode as interface.
   804  	buf := new(bytes.Buffer)
   805  	err = cdc.encodeReflectJSONInterface(buf, iinfo, reflect.ValueOf(&ivar).Elem(), FieldOptions{})
   806  	if err != nil {
   807  		return nil, err
   808  	}
   809  	bz := buf.Bytes()
   810  
   811  	return bz, nil
   812  }
   813  
   814  // MustMarshalJSON panics if an error occurs. Besides tha behaves exactly like MarshalJSON.
   815  func (cdc *Codec) MustMarshalJSON(o interface{}) []byte {
   816  	bz, err := cdc.MarshalJSON(o)
   817  	if err != nil {
   818  		panic(err)
   819  	}
   820  	return bz
   821  }
   822  
   823  // MustMarshalJSONAny panics if an error occurs. Besides tha behaves exactly like MarshalJSONAny.
   824  func (cdc *Codec) MustMarshalJSONAny(o interface{}) []byte {
   825  	bz, err := cdc.MarshalJSONAny(o)
   826  	if err != nil {
   827  		panic(err)
   828  	}
   829  	return bz
   830  }
   831  
   832  func (cdc *Codec) UnmarshalJSON(bz []byte, ptr interface{}) error {
   833  	cdc.doAutoseal()
   834  	if len(bz) == 0 {
   835  		return errors.New("cannot decode empty bytes")
   836  	}
   837  
   838  	rv := reflect.ValueOf(ptr)
   839  	if rv.Kind() != reflect.Ptr {
   840  		return errors.New("expected a pointer")
   841  	}
   842  	rv = rv.Elem()
   843  	rt := rv.Type()
   844  	info, err := cdc.getTypeInfoWLock(rt)
   845  	if err != nil {
   846  		return err
   847  	}
   848  	return cdc.decodeReflectJSON(bz, info, rv, FieldOptions{})
   849  }
   850  
   851  // MustUnmarshalJSON panics if an error occurs. Besides tha behaves exactly like UnmarshalJSON.
   852  func (cdc *Codec) MustUnmarshalJSON(bz []byte, ptr interface{}) {
   853  	if err := cdc.UnmarshalJSON(bz, ptr); err != nil {
   854  		panic(err)
   855  	}
   856  }
   857  
   858  // MarshalJSONIndent calls json.Indent on the output of cdc.MarshalJSON
   859  // using the given prefix and indent string.
   860  func (cdc *Codec) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
   861  	bz, err := cdc.MarshalJSON(o)
   862  	if err != nil {
   863  		return nil, err
   864  	}
   865  	var out bytes.Buffer
   866  	err = json.Indent(&out, bz, prefix, indent)
   867  	if err != nil {
   868  		return nil, err
   869  	}
   870  	return out.Bytes(), nil
   871  }
   872  
   873  // ----------------------------------------
   874  // Other
   875  
   876  // NOTE: do not modify the result.
   877  func RegisterPackage(pi *pkg.Package) *Package {
   878  	gcdc.RegisterPackage(pi)
   879  	return pi
   880  }
   881  
   882  func NewPackage(gopkg string, p3pkg string, dirname string) *Package {
   883  	return pkg.NewPackage(gopkg, p3pkg, dirname)
   884  }
   885  
   886  // NOTE: duplicated in pkg/pkg.go
   887  func GetCallersDirname() string {
   888  	dirname := "" // derive from caller.
   889  	_, filename, _, ok := runtime.Caller(1)
   890  	if !ok {
   891  		panic("could not get caller to derive caller's package directory")
   892  	}
   893  	dirname = filepath.Dir(filename)
   894  	if filename == "" || dirname == "" {
   895  		panic("could not derive caller's package directory")
   896  	}
   897  	return dirname
   898  }
   899  
   900  // ----------------------------------------
   901  // Object
   902  
   903  // All concrete types must implement the Object interface for genproto
   904  // bindings.  They are generated automatically by genproto/bindings.go
   905  type Object interface {
   906  	GetTypeURL() string
   907  }
   908  
   909  // TODO: this does need the cdc receiver,
   910  // as it should also work for non-pbbindings-optimized types.
   911  // Returns the default type url for the given concrete type.
   912  // NOTE: It must be fast, as it is used in pbbindings.
   913  // XXX Unstable API.
   914  func (cdc *Codec) GetTypeURL(o interface{}) string {
   915  	if obj, ok := o.(Object); ok {
   916  		return obj.GetTypeURL()
   917  	}
   918  	switch o.(type) {
   919  	case time.Time, *time.Time, *timestamppb.Timestamp:
   920  		return "/google.protobuf.Timestamp"
   921  	case time.Duration, *time.Duration, *durationpb.Duration:
   922  		return "/google.protobuf.Duration"
   923  	}
   924  	rt := reflect.TypeOf(o)
   925  	// Doesn't have .GetTypeURL() and isn't well known.
   926  	// Do the slow thing (not relevant if pbbindings exists).
   927  	info, err := cdc.GetTypeInfo(rt)
   928  	if err != nil {
   929  		panic(err)
   930  	}
   931  	if info.TypeURL == "" {
   932  		panic("not yet supported")
   933  	}
   934  	return info.TypeURL
   935  }
   936  
   937  // ----------------------------------------
   938  
   939  // Methods generated by genproto/bindings.go for faster encoding.
   940  type PBMessager interface {
   941  	ToPBMessage(*Codec) (proto.Message, error)
   942  	EmptyPBMessage(*Codec) proto.Message
   943  	FromPBMessage(*Codec, proto.Message) error
   944  }