diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go
index 8da52c067..8adc0f014 100644
--- a/accounts/abi/abi.go
+++ b/accounts/abi/abi.go
@@ -80,39 +80,59 @@ func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
return append(method.ID, arguments...), nil
}
-// Unpack output in v according to the abi specification
-func (abi ABI) Unpack(v interface{}, name string, data []byte) (err error) {
+func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
// since there can't be naming collisions with contracts and events,
// we need to decide whether we're calling a method or an event
+ var args Arguments
if method, ok := abi.Methods[name]; ok {
if len(data)%32 != 0 {
- return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
+ return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
}
- return method.Outputs.Unpack(v, data)
+ args = method.Outputs
}
if event, ok := abi.Events[name]; ok {
- return event.Inputs.Unpack(v, data)
+ args = event.Inputs
}
- return fmt.Errorf("abi: could not locate named method or event")
+ if args == nil {
+ return nil, errors.New("abi: could not locate named method or event")
+ }
+ return args, nil
}
-// UnpackIntoMap unpacks a log into the provided map[string]interface{}
-func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
- // since there can't be naming collisions with contracts and events,
- // we need to decide whether we're calling a method or an event
- if method, ok := abi.Methods[name]; ok {
- if len(data)%32 != 0 {
- return fmt.Errorf("abi: improperly formatted output")
- }
- return method.Outputs.UnpackIntoMap(v, data)
+// Unpack unpacks the output according to the abi specification.
+func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) {
+ args, err := abi.getArguments(name, data)
+ if err != nil {
+ return nil, err
}
- if event, ok := abi.Events[name]; ok {
- return event.Inputs.UnpackIntoMap(v, data)
+ return args.Unpack(data)
+}
+
+// UnpackIntoInterface unpacks the output in v according to the abi specification.
+// It performs an additional copy. Please only use, if you want to unpack into a
+// structure that does not strictly conform to the abi structure (e.g. has additional arguments)
+func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error {
+ args, err := abi.getArguments(name, data)
+ if err != nil {
+ return err
+ }
+ unpacked, err := args.Unpack(data)
+ if err != nil {
+ return err
+ }
+ return args.Copy(v, unpacked)
+}
+
+// UnpackIntoMap unpacks a log into the provided map[string]interface{}.
+func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
+ args, err := abi.getArguments(name, data)
+ if err != nil {
+ return err
}
- return fmt.Errorf("abi: could not locate named method or event")
+ return args.UnpackIntoMap(v, data)
}
-// UnmarshalJSON implements json.Unmarshaler interface
+// UnmarshalJSON implements json.Unmarshaler interface.
func (abi *ABI) UnmarshalJSON(data []byte) error {
var fields []struct {
Type string
@@ -201,8 +221,8 @@ func (abi *ABI) overloadedEventName(rawName string) string {
return name
}
-// MethodById looks up a method by the 4-byte id
-// returns nil if none found
+// MethodById looks up a method by the 4-byte id,
+// returns nil if none found.
func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
if len(sigdata) < 4 {
return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
@@ -250,10 +270,10 @@ func UnpackRevert(data []byte) (string, error) {
if !bytes.Equal(data[:4], revertSelector) {
return "", errors.New("invalid data for unpacking")
}
- var reason string
typ, _ := NewType("string", "", nil)
- if err := (Arguments{{Type: typ}}).Unpack(&reason, data[4:]); err != nil {
+ unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
+ if err != nil {
return "", err
}
- return reason, nil
+ return unpacked[0].(string), nil
}
diff --git a/accounts/abi/argument.go b/accounts/abi/argument.go
index f954b0e71..04dbdbd51 100644
--- a/accounts/abi/argument.go
+++ b/accounts/abi/argument.go
@@ -75,32 +75,24 @@ func (arguments Arguments) isTuple() bool {
return len(arguments) > 1
}
-// Unpack performs the operation hexdata -> Go format
-func (arguments Arguments) Unpack(v interface{}, data []byte) error {
+// Unpack performs the operation hexdata -> Go format.
+func (arguments Arguments) Unpack(data []byte) ([]interface{}, error) {
if len(data) == 0 {
if len(arguments) != 0 {
- return fmt.Errorf("abi: attempting to unmarshall an empty string while arguments are expected")
+ return nil, fmt.Errorf("abi: attempting to unmarshall an empty string while arguments are expected")
}
- return nil // Nothing to unmarshal, return
- }
- // make sure the passed value is arguments pointer
- if reflect.Ptr != reflect.ValueOf(v).Kind() {
- return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
- }
- marshalledValues, err := arguments.UnpackValues(data)
- if err != nil {
- return err
- }
- if len(marshalledValues) == 0 {
- return fmt.Errorf("abi: Unpack(no-values unmarshalled %T)", v)
- }
- if arguments.isTuple() {
- return arguments.unpackTuple(v, marshalledValues)
+ // Nothing to unmarshal, return default variables
+ nonIndexedArgs := arguments.NonIndexed()
+ defaultVars := make([]interface{}, len(nonIndexedArgs))
+ for index, arg := range nonIndexedArgs {
+ defaultVars[index] = reflect.New(arg.Type.GetType())
+ }
+ return defaultVars, nil
}
- return arguments.unpackAtomic(v, marshalledValues[0])
+ return arguments.UnpackValues(data)
}
-// UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value
+// UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value.
func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error {
// Make sure map is not nil
if v == nil {
@@ -122,8 +114,26 @@ func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte)
return nil
}
+// Copy performs the operation go format -> provided struct.
+func (arguments Arguments) Copy(v interface{}, values []interface{}) error {
+ // make sure the passed value is arguments pointer
+ if reflect.Ptr != reflect.ValueOf(v).Kind() {
+ return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
+ }
+ if len(values) == 0 {
+ if len(arguments) != 0 {
+ return fmt.Errorf("abi: attempting to copy no values while %d arguments are expected", len(arguments))
+ }
+ return nil // Nothing to copy, return
+ }
+ if arguments.isTuple() {
+ return arguments.copyTuple(v, values)
+ }
+ return arguments.copyAtomic(v, values[0])
+}
+
// unpackAtomic unpacks ( hexdata -> go ) a single value
-func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues interface{}) error {
+func (arguments Arguments) copyAtomic(v interface{}, marshalledValues interface{}) error {
dst := reflect.ValueOf(v).Elem()
src := reflect.ValueOf(marshalledValues)
@@ -133,8 +143,8 @@ func (arguments Arguments) unpackAtomic(v interface{}, marshalledValues interfac
return set(dst, src)
}
-// unpackTuple unpacks ( hexdata -> go ) a batch of values.
-func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error {
+// copyTuple copies a batch of values from marshalledValues to v.
+func (arguments Arguments) copyTuple(v interface{}, marshalledValues []interface{}) error {
value := reflect.ValueOf(v).Elem()
nonIndexedArgs := arguments.NonIndexed()
@@ -207,13 +217,13 @@ func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error) {
return retval, nil
}
-// PackValues performs the operation Go format -> Hexdata
-// It is the semantic opposite of UnpackValues
+// PackValues performs the operation Go format -> Hexdata.
+// It is the semantic opposite of UnpackValues.
func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) {
return arguments.Pack(args...)
}
-// Pack performs the operation Go format -> Hexdata
+// Pack performs the operation Go format -> Hexdata.
func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) {
// Make sure arguments match up and pack them
abiArgs := arguments
diff --git a/accounts/abi/bind/auth.go b/accounts/abi/bind/auth.go
index 97733020e..9b4806b53 100644
--- a/accounts/abi/bind/auth.go
+++ b/accounts/abi/bind/auth.go
@@ -19,19 +19,31 @@ package bind
import (
"crypto/ecdsa"
"errors"
+ "github.com/truechain/truechain-engineering-code/accounts/external"
"io"
"io/ioutil"
+ "math/big"
- "github.com/truechain/truechain-engineering-code/common"
- "github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/accounts/keystore"
+ "github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/core/types"
+ "github.com/truechain/truechain-engineering-code/crypto"
+ "github.com/truechain/truechain-engineering-code/log"
)
+// ErrNoChainID is returned whenever the user failed to specify a chain id.
+var ErrNoChainID = errors.New("no chain id specified")
+
+// ErrNotAuthorized is returned when an account is not properly unlocked.
+var ErrNotAuthorized = errors.New("not authorized to sign this account")
+
// NewTransactor is a utility method to easily create a transaction signer from
// an encrypted json key stream and the associated passphrase.
+//
+// Deprecated: Use NewTransactorWithChainID instead.
func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
+ log.Warn("WARNING: NewTransactor has been deprecated in favour of NewTransactorWithChainID")
json, err := ioutil.ReadAll(keyin)
if err != nil {
return nil, err
@@ -44,13 +56,17 @@ func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
}
// NewKeyStoreTransactor is a utility method to easily create a transaction signer from
-// an decrypted key from a keystore
+// an decrypted key from a keystore.
+//
+// Deprecated: Use NewKeyStoreTransactorWithChainID instead.
func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account) (*TransactOpts, error) {
+ log.Warn("WARNING: NewKeyStoreTransactor has been deprecated in favour of NewTransactorWithChainID")
+ signer := types.TIP1Signer{}
return &TransactOpts{
From: account.Address,
- Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
+ Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
if address != account.Address {
- return nil, errors.New("not authorized to sign this account")
+ return nil, ErrNotAuthorized
}
signature, err := keystore.SignHash(account, signer.Hash(tx).Bytes())
if err != nil {
@@ -63,13 +79,17 @@ func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account
// NewKeyedTransactor is a utility method to easily create a transaction signer
// from a single private key.
+//
+// Deprecated: Use NewKeyedTransactorWithChainID instead.
func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
+ log.Warn("WARNING: NewKeyedTransactor has been deprecated in favour of NewKeyedTransactorWithChainID")
keyAddr := crypto.PubkeyToAddress(key.PublicKey)
+ signer := types.TIP1Signer{}
return &TransactOpts{
From: keyAddr,
- Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
+ Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
if address != keyAddr {
- return nil, errors.New("not authorized to sign this account")
+ return nil, ErrNotAuthorized
}
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
if err != nil {
@@ -80,16 +100,75 @@ func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
}
}
+// NewTransactorWithChainID is a utility method to easily create a transaction signer from
+// an encrypted json key stream and the associated passphrase.
+func NewTransactorWithChainID(keyin io.Reader, passphrase string, chainID *big.Int) (*TransactOpts, error) {
+ json, err := ioutil.ReadAll(keyin)
+ if err != nil {
+ return nil, err
+ }
+ key, err := keystore.DecryptKey(json, passphrase)
+ if err != nil {
+ return nil, err
+ }
+ return NewKeyedTransactorWithChainID(key.PrivateKey, chainID)
+}
+
+// NewKeyStoreTransactorWithChainID is a utility method to easily create a transaction signer from
+// an decrypted key from a keystore.
+func NewKeyStoreTransactorWithChainID(keystore *keystore.KeyStore, account accounts.Account, chainID *big.Int) (*TransactOpts, error) {
+ if chainID == nil {
+ return nil, ErrNoChainID
+ }
+ signer := types.LatestSignerForChainID(chainID)
+ return &TransactOpts{
+ From: account.Address,
+ Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
+ if address != account.Address {
+ return nil, ErrNotAuthorized
+ }
+ signature, err := keystore.SignHash(account, signer.Hash(tx).Bytes())
+ if err != nil {
+ return nil, err
+ }
+ return tx.WithSignature(signer, signature)
+ },
+ }, nil
+}
+
+// NewKeyedTransactorWithChainID is a utility method to easily create a transaction signer
+// from a single private key.
+func NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainID *big.Int) (*TransactOpts, error) {
+ keyAddr := crypto.PubkeyToAddress(key.PublicKey)
+ if chainID == nil {
+ return nil, ErrNoChainID
+ }
+ signer := types.LatestSignerForChainID(chainID)
+ return &TransactOpts{
+ From: keyAddr,
+ Signer: func(address common.Address, tx *types.Transaction) (*types.Transaction, error) {
+ if address != keyAddr {
+ return nil, ErrNotAuthorized
+ }
+ signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
+ if err != nil {
+ return nil, err
+ }
+ return tx.WithSignature(signer, signature)
+ },
+ }, nil
+}
+
// NewClefTransactor is a utility method to easily create a transaction signer
// with a clef backend.
-// func NewClefTransactor(clef *external.ExternalSigner, account accounts.Account) *TransactOpts {
-// return &TransactOpts{
-// From: account.Address,
-// Signer: func(signer types.Signer, address common.Address, transaction *types.Transaction) (*types.Transaction, error) {
-// if address != account.Address {
-// return nil, errors.New("not authorized to sign this account")
-// }
-// return clef.SignTx(account, transaction, nil) // Clef enforces its own chain id
-// },
-// }
-// }
+func NewClefTransactor(clef *external.ExternalSigner, account accounts.Account) *TransactOpts {
+ return &TransactOpts{
+ From: account.Address,
+ Signer: func(address common.Address, transaction *types.Transaction) (*types.Transaction, error) {
+ if address != account.Address {
+ return nil, ErrNotAuthorized
+ }
+ return clef.SignTx(account, transaction, nil) // Clef enforces its own chain id
+ },
+ }
+}
diff --git a/accounts/abi/bind/backend.go b/accounts/abi/bind/backend.go
index 6134a691c..68347bf9d 100644
--- a/accounts/abi/bind/backend.go
+++ b/accounts/abi/bind/backend.go
@@ -21,8 +21,8 @@ import (
"errors"
"math/big"
- "github.com/truechain/truechain-engineering-code/common"
truechain "github.com/truechain/truechain-engineering-code"
+ "github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/core/types"
)
@@ -32,22 +32,23 @@ var (
// have any code associated with it (i.e. suicided).
ErrNoCode = errors.New("no contract code at given address")
- // This error is raised when attempting to perform a pending state action
+ // ErrNoPendingState is raised when attempting to perform a pending state action
// on a backend that doesn't implement PendingContractCaller.
ErrNoPendingState = errors.New("backend does not support pending state")
- // This error is returned by WaitDeployed if contract creation leaves an
- // empty contract behind.
+ // ErrNoCodeAfterDeploy is returned by WaitDeployed if contract creation leaves
+ // an empty contract behind.
ErrNoCodeAfterDeploy = errors.New("no contract code after deployment")
)
-// ContractCaller defines the methods needed to allow operating with contract on a read
+// ContractCaller defines the methods needed to allow operating with a contract on a read
// only basis.
type ContractCaller interface {
// CodeAt returns the code of the given account. This is needed to differentiate
// between contract internal errors and the local chain being out of sync.
CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error)
- // ContractCall executes an Ethereum contract call with the specified data as the
+
+ // CallContract executes an Ethereum contract call with the specified data as the
// input.
CallContract(ctx context.Context, call truechain.CallMsg, blockNumber *big.Int) ([]byte, error)
}
@@ -58,22 +59,34 @@ type ContractCaller interface {
type PendingContractCaller interface {
// PendingCodeAt returns the code of the given account in the pending state.
PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error)
+
// PendingCallContract executes an Ethereum contract call against the pending state.
PendingCallContract(ctx context.Context, call truechain.CallMsg) ([]byte, error)
}
-// ContractTransactor defines the methods needed to allow operating with contract
-// on a write only basis. Beside the transacting method, the remainder are helpers
+// ContractTransactor defines the methods needed to allow operating with a contract
+// on a write only basis. Besides the transacting method, the remainder are helpers
// used when the user does not provide some needed values, but rather leaves it up
// to the transactor to decide.
type ContractTransactor interface {
+ // HeaderByNumber returns a block header from the current canonical chain. If
+ // number is nil, the latest known header is returned.
+ HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
+
// PendingCodeAt returns the code of the given account in the pending state.
PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
+
// PendingNonceAt retrieves the current pending nonce associated with an account.
PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
+
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
// execution of a transaction.
SuggestGasPrice(ctx context.Context) (*big.Int, error)
+
+ // SuggestGasTipCap retrieves the currently suggested 1559 priority fee to allow
+ // a timely execution of a transaction.
+ SuggestGasTipCap(ctx context.Context) (*big.Int, error)
+
// EstimateGas tries to estimate the gas needed to execute a specific
// transaction based on the current pending state of the backend blockchain.
// There is no guarantee that this is the true gas limit requirement as other
diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go
index 4121fc70d..1f1f98627 100644
--- a/accounts/abi/bind/base.go
+++ b/accounts/abi/bind/base.go
@@ -20,7 +20,6 @@ import (
"context"
"errors"
"fmt"
- "github.com/truechain/truechain-engineering-code/params"
"math/big"
truechain "github.com/truechain/truechain-engineering-code"
@@ -33,7 +32,7 @@ import (
// SignerFn is a signer function callback when a contract requires a method to
// sign the transaction before submission.
-type SignerFn func(types.Signer, common.Address, *types.Transaction) (*types.Transaction, error)
+type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
// CallOpts is the collection of options to fine tune a contract call request.
type CallOpts struct {
@@ -50,11 +49,15 @@ type TransactOpts struct {
Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state)
Signer SignerFn // Method to use for signing the transaction (mandatory)
- Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
- GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
- GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
+ Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
+ GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
+ GasFeeCap *big.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle)
+ GasTipCap *big.Int // Gas priority fee cap to use for the 1559 transaction execution (nil = gas price oracle)
+ GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
+
+ NoSend bool // Do all transact steps but do not send the transaction
}
// FilterOpts is the collection of options to fine tune filtering for events
@@ -118,11 +121,14 @@ func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend Co
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
-func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, params ...interface{}) error {
+func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error {
// Don't crash on a lazy user
if opts == nil {
opts = new(CallOpts)
}
+ if results == nil {
+ results = new([]interface{})
+ }
// Pack the input, call and unpack the results
input, err := c.abi.Pack(method, params...)
if err != nil {
@@ -150,7 +156,10 @@ func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string,
}
} else {
output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
- if err == nil && len(output) == 0 {
+ if err != nil {
+ return err
+ }
+ if len(output) == 0 {
// Make sure we have a contract to operate on, and bail out otherwise.
if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
return err
@@ -159,10 +168,14 @@ func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string,
}
}
}
- if err != nil {
+
+ if len(*results) == 0 {
+ res, err := c.abi.Unpack(method, output)
+ *results = res
return err
}
- return c.abi.Unpack(result, method, output)
+ res := *results
+ return c.abi.UnpackIntoInterface(res[0], method, output)
}
// Transact invokes the (paid) contract method with params as input values.
@@ -178,7 +191,7 @@ func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...in
}
// RawTransact initiates a transaction with the given raw calldata as the input.
-// It's usually used to initiates transaction for invoking **Fallback** function.
+// It's usually used to initiate transactions for invoking **Fallback** function.
func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
// todo(rjl493456442) check the method is payable or not,
// reject invalid transaction at the first place
@@ -212,12 +225,42 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
} else {
nonce = opts.Nonce.Uint64()
}
- // Figure out the gas allowance and gas price values
- gasPrice := opts.GasPrice
- if gasPrice == nil {
- gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
- if err != nil {
- return nil, fmt.Errorf("failed to suggest gas price: %v", err)
+ // Figure out reasonable gas price values
+ if opts.GasPrice != nil && (opts.GasFeeCap != nil || opts.GasTipCap != nil) {
+ return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
+ }
+ head, err := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil)
+ if err != nil {
+ return nil, err
+ }
+ if head.BaseFee != nil && opts.GasPrice == nil {
+ if opts.GasTipCap == nil {
+ tip, err := c.transactor.SuggestGasTipCap(ensureContext(opts.Context))
+ if err != nil {
+ return nil, err
+ }
+ opts.GasTipCap = tip
+ }
+ if opts.GasFeeCap == nil {
+ gasFeeCap := new(big.Int).Add(
+ opts.GasTipCap,
+ new(big.Int).Mul(head.BaseFee, big.NewInt(2)),
+ )
+ opts.GasFeeCap = gasFeeCap
+ }
+ if opts.GasFeeCap.Cmp(opts.GasTipCap) < 0 {
+ return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", opts.GasFeeCap, opts.GasTipCap)
+ }
+ } else {
+ if opts.GasFeeCap != nil || opts.GasTipCap != nil {
+ return nil, errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet")
+ }
+ if opts.GasPrice == nil {
+ price, err := c.transactor.SuggestGasPrice(ensureContext(opts.Context))
+ if err != nil {
+ return nil, err
+ }
+ opts.GasPrice = price
}
}
gasLimit := opts.GasLimit
@@ -231,7 +274,7 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
}
}
// If the contract surely has code (or code is not needed), estimate the transaction
- msg := truechain.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input}
+ msg := truechain.CallMsg{From: opts.From, To: contract, GasPrice: opts.GasPrice, Value: value, Data: input}
gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
if err != nil {
return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
@@ -240,14 +283,14 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
// Create the transaction, sign it and schedule it for execution
var rawTx *types.Transaction
if contract == nil {
- rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
+ rawTx = types.NewContractCreation(nonce, value, gasLimit, opts.GasPrice, input)
} else {
- rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
+ rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, opts.GasPrice, input)
}
if opts.Signer == nil {
return nil, errors.New("no signer to authorize the transaction with")
}
- signedTx, err := opts.Signer(types.NewTIP1Signer(params.AllMinervaProtocolChanges.ChainID), opts.From, rawTx)
+ signedTx, err := opts.Signer(opts.From, rawTx)
if err != nil {
return nil, err
}
@@ -340,7 +383,7 @@ func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]inter
// UnpackLog unpacks a retrieved log into the provided output structure.
func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
if len(log.Data) > 0 {
- if err := c.abi.Unpack(out, event, log.Data); err != nil {
+ if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
return err
}
}
@@ -373,7 +416,7 @@ func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event strin
// user specified it as such.
func ensureContext(ctx context.Context) context.Context {
if ctx == nil {
- return context.TODO()
+ return context.Background()
}
return ctx
}
diff --git a/accounts/abi/bind/base_test.go b/accounts/abi/bind/base_test.go
index e9e65d5ad..a61cc05cd 100644
--- a/accounts/abi/bind/base_test.go
+++ b/accounts/abi/bind/base_test.go
@@ -71,11 +71,10 @@ func TestPassingBlockNumber(t *testing.T) {
},
},
}, mc, nil, nil)
- var ret string
blockNumber := big.NewInt(42)
- bc.Call(&bind.CallOpts{BlockNumber: blockNumber}, &ret, "something")
+ bc.Call(&bind.CallOpts{BlockNumber: blockNumber}, nil, "something")
if mc.callContractBlockNumber != blockNumber {
t.Fatalf("CallContract() was not passed the block number")
@@ -85,7 +84,7 @@ func TestPassingBlockNumber(t *testing.T) {
t.Fatalf("CodeAt() was not passed the block number")
}
- bc.Call(&bind.CallOpts{}, &ret, "something")
+ bc.Call(&bind.CallOpts{}, nil, "something")
if mc.callContractBlockNumber != nil {
t.Fatalf("CallContract() was passed a block number when it should not have been")
@@ -95,7 +94,7 @@ func TestPassingBlockNumber(t *testing.T) {
t.Fatalf("CodeAt() was passed a block number when it should not have been")
}
- bc.Call(&bind.CallOpts{BlockNumber: blockNumber, Pending: true}, &ret, "something")
+ bc.Call(&bind.CallOpts{BlockNumber: blockNumber, Pending: true}, nil, "something")
if !mc.pendingCallContractCalled {
t.Fatalf("CallContract() was not passed the block number")
diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go
index b299b5c98..087a41399 100644
--- a/accounts/abi/bind/template.go
+++ b/accounts/abi/bind/template.go
@@ -30,7 +30,7 @@ type tmplData struct {
type tmplContract struct {
Type string // Type name of the main contract binding
InputABI string // JSON ABI used as the input to generate the binding from
- InputBin string // Optional EVM bytecode used to denetare deploy code from
+ InputBin string // Optional EVM bytecode used to generate deploy code from
FuncSigs map[string]string // Optional map: string signature -> 4-byte signature
Constructor abi.Method // Contract constructor for deploy parametrization
Calls map[string]*tmplMethod // Contract calls that only read state data
@@ -50,7 +50,8 @@ type tmplMethod struct {
Structured bool // Whether the returns should be accumulated into a struct
}
-// tmplEvent is a wrapper around an a
+// tmplEvent is a wrapper around an abi.Event that contains a few preprocessed
+// and cached data fields.
type tmplEvent struct {
Original abi.Event // Original event as parsed by the abi package
Normalized abi.Event // Normalized version of the parsed fields
@@ -64,7 +65,7 @@ type tmplField struct {
SolKind abi.Type // Raw abi type information
}
-// tmplStruct is a wrapper around an abi.tuple contains an auto-generated
+// tmplStruct is a wrapper around an abi.tuple and contains an auto-generated
// struct name.
type tmplStruct struct {
Name string // Auto-generated struct name(before solidity v0.5.11) or raw name.
@@ -78,8 +79,8 @@ var tmplSource = map[Lang]string{
LangJava: tmplSourceJava,
}
-// tmplSourceGo is the Go source template use to generate the contract binding
-// based on.
+// tmplSourceGo is the Go source template that the generated Go contract binding
+// is based on.
const tmplSourceGo = `
// Code generated - DO NOT EDIT.
// This file is a generated binding and any manual changes will be lost.
@@ -260,7 +261,7 @@ var (
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
- func (_{{$contract.Type}} *{{$contract.Type}}Raw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
+ func (_{{$contract.Type}} *{{$contract.Type}}Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _{{$contract.Type}}.Contract.{{$contract.Type}}Caller.contract.Call(opts, result, method, params...)
}
@@ -279,7 +280,7 @@ var (
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
- func (_{{$contract.Type}} *{{$contract.Type}}CallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
+ func (_{{$contract.Type}} *{{$contract.Type}}CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _{{$contract.Type}}.Contract.contract.Call(opts, result, method, params...)
}
@@ -299,19 +300,26 @@ var (
//
// Solidity: {{.Original.String}}
func (_{{$contract.Type}} *{{$contract.Type}}Caller) {{.Normalized.Name}}(opts *bind.CallOpts {{range .Normalized.Inputs}}, {{.Name}} {{bindtype .Type $structs}} {{end}}) ({{if .Structured}}struct{ {{range .Normalized.Outputs}}{{.Name}} {{bindtype .Type $structs}};{{end}} },{{else}}{{range .Normalized.Outputs}}{{bindtype .Type $structs}},{{end}}{{end}} error) {
- {{if .Structured}}ret := new(struct{
- {{range .Normalized.Outputs}}{{.Name}} {{bindtype .Type $structs}}
- {{end}}
- }){{else}}var (
- {{range $i, $_ := .Normalized.Outputs}}ret{{$i}} = new({{bindtype .Type $structs}})
- {{end}}
- ){{end}}
- out := {{if .Structured}}ret{{else}}{{if eq (len .Normalized.Outputs) 1}}ret0{{else}}&[]interface{}{
- {{range $i, $_ := .Normalized.Outputs}}ret{{$i}},
- {{end}}
- }{{end}}{{end}}
- err := _{{$contract.Type}}.contract.Call(opts, out, "{{.Original.Name}}" {{range .Normalized.Inputs}}, {{.Name}}{{end}})
- return {{if .Structured}}*ret,{{else}}{{range $i, $_ := .Normalized.Outputs}}*ret{{$i}},{{end}}{{end}} err
+ var out []interface{}
+ err := _{{$contract.Type}}.contract.Call(opts, &out, "{{.Original.Name}}" {{range .Normalized.Inputs}}, {{.Name}}{{end}})
+ {{if .Structured}}
+ outstruct := new(struct{ {{range .Normalized.Outputs}} {{.Name}} {{bindtype .Type $structs}}; {{end}} })
+ if err != nil {
+ return *outstruct, err
+ }
+ {{range $i, $t := .Normalized.Outputs}}
+ outstruct.{{.Name}} = *abi.ConvertType(out[{{$i}}], new({{bindtype .Type $structs}})).(*{{bindtype .Type $structs}}){{end}}
+
+ return *outstruct, err
+ {{else}}
+ if err != nil {
+ return {{range $i, $_ := .Normalized.Outputs}}*new({{bindtype .Type $structs}}), {{end}} err
+ }
+ {{range $i, $t := .Normalized.Outputs}}
+ out{{$i}} := *abi.ConvertType(out[{{$i}}], new({{bindtype .Type $structs}})).(*{{bindtype .Type $structs}}){{end}}
+
+ return {{range $i, $t := .Normalized.Outputs}}out{{$i}}, {{end}} err
+ {{end}}
}
// {{.Normalized.Name}} is a free data retrieval call binding the contract method 0x{{printf "%x" .Original.ID}}.
@@ -536,6 +544,7 @@ var (
if err := _{{$contract.Type}}.contract.UnpackLog(event, "{{.Original.Name}}", log); err != nil {
return nil, err
}
+ event.Raw = log
return event, nil
}
@@ -543,8 +552,8 @@ var (
{{end}}
`
-// tmplSourceJava is the Java source template use to generate the contract binding
-// based on.
+// tmplSourceJava is the Java source template that the generated Java contract binding
+// is based on.
const tmplSourceJava = `
// This file is an automatically generated Java binding. Do not modify as any
// change will likely be lost upon the next re-generation!
diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go
index 5a273625b..d65279e58 100644
--- a/accounts/abi/bind/util_test.go
+++ b/accounts/abi/bind/util_test.go
@@ -53,16 +53,19 @@ var waitDeployedTests = map[string]struct {
func TestWaitDeployed(t *testing.T) {
for name, test := range waitDeployedTests {
backend := backends.NewSimulatedBackend(
- types.GenesisAlloc{
- crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)},
+ core.GenesisAlloc{
+ crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000000000)},
},
10000000,
)
defer backend.Close()
- // Create the transaction.
- tx := types.NewContractCreation(0, big.NewInt(0), test.gas, big.NewInt(1), common.FromHex(test.code))
- tx, _ = types.SignTx(tx, types.NewTIP1Signer(params.TestChainConfig.ChainID), testKey)
+ // Create the transaction
+ head, _ := backend.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
+ gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
+
+ tx := types.NewContractCreation(0, big.NewInt(0), test.gas, gasPrice, common.FromHex(test.code))
+ tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
// Wait for it to get mined in the background.
var (
@@ -83,7 +86,7 @@ func TestWaitDeployed(t *testing.T) {
select {
case <-mined:
if err != test.wantErr {
- t.Errorf("test %q: error mismatch: got %q, want %q", name, err, test.wantErr)
+ t.Errorf("test %q: error mismatch: want %q, got %q", name, test.wantErr, err)
}
if address != test.wantAddress {
t.Errorf("test %q: unexpected contract address %s", name, address.Hex())
@@ -93,3 +96,43 @@ func TestWaitDeployed(t *testing.T) {
}
}
}
+
+func TestWaitDeployedCornerCases(t *testing.T) {
+ backend := backends.NewSimulatedBackend(
+ core.GenesisAlloc{
+ crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000000000)},
+ },
+ 10000000,
+ )
+ defer backend.Close()
+
+ head, _ := backend.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
+ gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
+
+ // Create a transaction to an account.
+ code := "6060604052600a8060106000396000f360606040526008565b00"
+ tx := types.NewTransaction(0, common.HexToAddress("0x01"), big.NewInt(0), 3000000, gasPrice, common.FromHex(code))
+ tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ backend.SendTransaction(ctx, tx)
+ backend.Commit()
+ notContentCreation := errors.New("tx is not contract creation")
+ if _, err := bind.WaitDeployed(ctx, backend, tx); err.Error() != notContentCreation.Error() {
+ t.Errorf("error missmatch: want %q, got %q, ", notContentCreation, err)
+ }
+
+ // Create a transaction that is not mined.
+ tx = types.NewContractCreation(1, big.NewInt(0), 3000000, gasPrice, common.FromHex(code))
+ tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
+
+ go func() {
+ contextCanceled := errors.New("context canceled")
+ if _, err := bind.WaitDeployed(ctx, backend, tx); err.Error() != contextCanceled.Error() {
+ t.Errorf("error missmatch: want %q, got %q, ", contextCanceled, err)
+ }
+ }()
+
+ backend.SendTransaction(ctx, tx)
+ cancel()
+}
diff --git a/accounts/abi/error.go b/accounts/abi/error.go
index b63a215ad..f0f71b6c9 100644
--- a/accounts/abi/error.go
+++ b/accounts/abi/error.go
@@ -52,7 +52,7 @@ func sliceTypeCheck(t Type, val reflect.Value) error {
}
}
- if elemKind := val.Type().Elem().Kind(); elemKind != t.Elem.GetType().Kind() {
+ if val.Type().Elem().Kind() != t.Elem.GetType().Kind() {
return typeErr(formatSliceString(t.Elem.GetType().Kind(), t.Size), val.Type())
}
return nil
diff --git a/accounts/abi/event.go b/accounts/abi/event.go
index d4c61db6f..9502223e5 100644
--- a/accounts/abi/event.go
+++ b/accounts/abi/event.go
@@ -32,7 +32,7 @@ type Event struct {
// the raw name and a suffix will be added in the case of a event overload.
//
// e.g.
- // There are two events have same name:
+ // These are two events that have the same name:
// * foo(int,int)
// * foo(uint,uint)
// The event name of the first one wll be resolved as foo while the second one
diff --git a/accounts/abi/method.go b/accounts/abi/method.go
index 7c36312d1..4fa42607f 100644
--- a/accounts/abi/method.go
+++ b/accounts/abi/method.go
@@ -45,7 +45,7 @@ const (
// If the method is `Const` no transaction needs to be created for this
// particular Method call. It can easily be simulated using a local VM.
// For example a `Balance()` method only needs to retrieve something
-// from the storage and therefore requires no Tx to be send to the
+// from the storage and therefore requires no Tx to be sent to the
// network. A method such as `Transact` does require a Tx and thus will
// be flagged `false`.
// Input specifies the required input parameters for this gives method.
@@ -54,7 +54,7 @@ type Method struct {
// the raw name and a suffix will be added in the case of a function overload.
//
// e.g.
- // There are two functions have same name:
+ // These are two functions that have the same name:
// * foo(int,int)
// * foo(uint,uint)
// The method name of the first one will be resolved as foo while the second one
diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go
index 778d370f3..c57274e53 100644
--- a/accounts/abi/pack.go
+++ b/accounts/abi/pack.go
@@ -17,6 +17,8 @@
package abi
import (
+ "errors"
+ "fmt"
"math/big"
"reflect"
@@ -25,7 +27,7 @@ import (
)
// packBytesSlice packs the given bytes as [L, V] as the canonical representation
-// bytes slice
+// bytes slice.
func packBytesSlice(bytes []byte, l int) []byte {
len := packNum(reflect.ValueOf(l))
return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...)
@@ -33,39 +35,42 @@ func packBytesSlice(bytes []byte, l int) []byte {
// packElement packs the given reflect value according to the abi specification in
// t.
-func packElement(t Type, reflectValue reflect.Value) []byte {
+func packElement(t Type, reflectValue reflect.Value) ([]byte, error) {
switch t.T {
case IntTy, UintTy:
- return packNum(reflectValue)
+ return packNum(reflectValue), nil
case StringTy:
- return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len())
+ return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len()), nil
case AddressTy:
if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue)
}
- return common.LeftPadBytes(reflectValue.Bytes(), 32)
+ return common.LeftPadBytes(reflectValue.Bytes(), 32), nil
case BoolTy:
if reflectValue.Bool() {
- return math.PaddedBigBytes(common.Big1, 32)
+ return math.PaddedBigBytes(common.Big1, 32), nil
}
- return math.PaddedBigBytes(common.Big0, 32)
+ return math.PaddedBigBytes(common.Big0, 32), nil
case BytesTy:
if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue)
}
- return packBytesSlice(reflectValue.Bytes(), reflectValue.Len())
+ if reflectValue.Type() != reflect.TypeOf([]byte{}) {
+ return []byte{}, errors.New("Bytes type is neither slice nor array")
+ }
+ return packBytesSlice(reflectValue.Bytes(), reflectValue.Len()), nil
case FixedBytesTy, FunctionTy:
if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue)
}
- return common.RightPadBytes(reflectValue.Bytes(), 32)
+ return common.RightPadBytes(reflectValue.Bytes(), 32), nil
default:
- panic("abi: fatal error")
+ return []byte{}, fmt.Errorf("Could not pack element, unknown type: %v", t.T)
}
}
-// packNum packs the given number (using the reflect value) and will cast it to appropriate number representation
+// packNum packs the given number (using the reflect value) and will cast it to appropriate number representation.
func packNum(value reflect.Value) []byte {
switch kind := value.Kind(); kind {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
@@ -77,5 +82,4 @@ func packNum(value reflect.Value) []byte {
default:
panic("abi: fatal error")
}
-
}
diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go
index 39c8b2c59..f62f591d3 100644
--- a/accounts/abi/pack_test.go
+++ b/accounts/abi/pack_test.go
@@ -44,18 +44,7 @@ func TestPack(t *testing.T) {
t.Fatalf("invalid ABI definition %s, %v", inDef, err)
}
var packed []byte
- if reflect.TypeOf(test.unpacked).Kind() != reflect.Struct {
- packed, err = inAbi.Pack("method", test.unpacked)
- } else {
- // if want is a struct we need to use the components.
- elem := reflect.ValueOf(test.unpacked)
- var values []interface{}
- for i := 0; i < elem.NumField(); i++ {
- field := elem.Field(i)
- values = append(values, field.Interface())
- }
- packed, err = inAbi.Pack("method", values...)
- }
+ packed, err = inAbi.Pack("method", test.unpacked)
if err != nil {
t.Fatalf("test %d (%v) failed: %v", i, test.def, err)
diff --git a/accounts/abi/packing_test.go b/accounts/abi/packing_test.go
index 5e823bac3..c9242f15f 100644
--- a/accounts/abi/packing_test.go
+++ b/accounts/abi/packing_test.go
@@ -620,7 +620,7 @@ var packUnpackTests = []packUnpackTest{
{
def: `[{"type": "bytes32[]"}]`,
- unpacked: []common.Hash{{1}, {2}},
+ unpacked: [][32]byte{{1}, {2}},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0100000000000000000000000000000000000000000000000000000000000000" +
@@ -722,7 +722,7 @@ var packUnpackTests = []packUnpackTest{
},
// struct outputs
{
- def: `[{"name":"int1","type":"int256"},{"name":"int2","type":"int256"}]`,
+ def: `[{"components": [{"name":"int1","type":"int256"},{"name":"int2","type":"int256"}], "type":"tuple"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: struct {
@@ -731,28 +731,28 @@ var packUnpackTests = []packUnpackTest{
}{big.NewInt(1), big.NewInt(2)},
},
{
- def: `[{"name":"int_one","type":"int256"}]`,
+ def: `[{"components": [{"name":"int_one","type":"int256"}], "type":"tuple"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: struct {
IntOne *big.Int
}{big.NewInt(1)},
},
{
- def: `[{"name":"int__one","type":"int256"}]`,
+ def: `[{"components": [{"name":"int__one","type":"int256"}], "type":"tuple"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: struct {
IntOne *big.Int
}{big.NewInt(1)},
},
{
- def: `[{"name":"int_one_","type":"int256"}]`,
+ def: `[{"components": [{"name":"int_one_","type":"int256"}], "type":"tuple"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: struct {
IntOne *big.Int
}{big.NewInt(1)},
},
{
- def: `[{"name":"int_one","type":"int256"}, {"name":"intone","type":"int256"}]`,
+ def: `[{"components": [{"name":"int_one","type":"int256"}, {"name":"intone","type":"int256"}], "type":"tuple"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: struct {
@@ -831,11 +831,11 @@ var packUnpackTests = []packUnpackTest{
},
{
// static tuple
- def: `[{"name":"a","type":"int64"},
+ def: `[{"components": [{"name":"a","type":"int64"},
{"name":"b","type":"int256"},
{"name":"c","type":"int256"},
{"name":"d","type":"bool"},
- {"name":"e","type":"bytes32[3][2]"}]`,
+ {"name":"e","type":"bytes32[3][2]"}], "type":"tuple"}]`,
unpacked: struct {
A int64
B *big.Int
@@ -855,21 +855,22 @@ var packUnpackTests = []packUnpackTest{
"0500000000000000000000000000000000000000000000000000000000000000", // struct[e] array[1][2]
},
{
- def: `[{"name":"a","type":"string"},
+ def: `[{"components": [{"name":"a","type":"string"},
{"name":"b","type":"int64"},
{"name":"c","type":"bytes"},
{"name":"d","type":"string[]"},
{"name":"e","type":"int256[]"},
- {"name":"f","type":"address[]"}]`,
+ {"name":"f","type":"address[]"}], "type":"tuple"}]`,
unpacked: struct {
- FieldA string `abi:"a"` // Test whether abi tag works
- FieldB int64 `abi:"b"`
- C []byte
- D []string
- E []*big.Int
- F []common.Address
+ A string
+ B int64
+ C []byte
+ D []string
+ E []*big.Int
+ F []common.Address
}{"foobar", 1, []byte{1}, []string{"foo", "bar"}, []*big.Int{big.NewInt(1), big.NewInt(-1)}, []common.Address{{1}, {2}}},
- packed: "00000000000000000000000000000000000000000000000000000000000000c0" + // struct[a] offset
+ packed: "0000000000000000000000000000000000000000000000000000000000000020" + // struct a
+ "00000000000000000000000000000000000000000000000000000000000000c0" + // struct[a] offset
"0000000000000000000000000000000000000000000000000000000000000001" + // struct[b]
"0000000000000000000000000000000000000000000000000000000000000100" + // struct[c] offset
"0000000000000000000000000000000000000000000000000000000000000140" + // struct[d] offset
@@ -894,23 +895,24 @@ var packUnpackTests = []packUnpackTest{
"0000000000000000000000000200000000000000000000000000000000000000", // common.Address{2}
},
{
- def: `[{"components": [{"name": "a","type": "uint256"},
+ def: `[{"components": [{ "type": "tuple","components": [{"name": "a","type": "uint256"},
{"name": "b","type": "uint256[]"}],
"name": "a","type": "tuple"},
- {"name": "b","type": "uint256[]"}]`,
+ {"name": "b","type": "uint256[]"}], "type": "tuple"}]`,
unpacked: struct {
A struct {
- FieldA *big.Int `abi:"a"`
- B []*big.Int
+ A *big.Int
+ B []*big.Int
}
B []*big.Int
}{
A: struct {
- FieldA *big.Int `abi:"a"` // Test whether abi tag works for nested tuple
- B []*big.Int
+ A *big.Int
+ B []*big.Int
}{big.NewInt(1), []*big.Int{big.NewInt(1), big.NewInt(2)}},
B: []*big.Int{big.NewInt(1), big.NewInt(2)}},
- packed: "0000000000000000000000000000000000000000000000000000000000000040" + // a offset
+ packed: "0000000000000000000000000000000000000000000000000000000000000020" + // struct a
+ "0000000000000000000000000000000000000000000000000000000000000040" + // a offset
"00000000000000000000000000000000000000000000000000000000000000e0" + // b offset
"0000000000000000000000000000000000000000000000000000000000000001" + // a.a value
"0000000000000000000000000000000000000000000000000000000000000040" + // a.b offset
diff --git a/accounts/abi/reflect.go b/accounts/abi/reflect.go
index 75f1a00a5..11248e073 100644
--- a/accounts/abi/reflect.go
+++ b/accounts/abi/reflect.go
@@ -24,6 +24,29 @@ import (
"strings"
)
+// ConvertType converts an interface of a runtime type into a interface of the
+// given type
+// e.g. turn
+// var fields []reflect.StructField
+// fields = append(fields, reflect.StructField{
+// Name: "X",
+// Type: reflect.TypeOf(new(big.Int)),
+// Tag: reflect.StructTag("json:\"" + "x" + "\""),
+// }
+// into
+// type TupleT struct { X *big.Int }
+func ConvertType(in interface{}, proto interface{}) interface{} {
+ protoType := reflect.TypeOf(proto)
+ if reflect.TypeOf(in).ConvertibleTo(protoType) {
+ return reflect.ValueOf(in).Convert(protoType).Interface()
+ }
+ // Use set as a last ditch effort
+ if err := set(reflect.ValueOf(proto), reflect.ValueOf(in)); err != nil {
+ panic(err)
+ }
+ return proto
+}
+
// indirect recursively dereferences the value until it either gets the value
// or finds a big.Int
func indirect(v reflect.Value) reflect.Value {
@@ -61,7 +84,7 @@ func reflectIntType(unsigned bool, size int) reflect.Type {
return reflect.TypeOf(&big.Int{})
}
-// mustArrayToBytesSlice creates a new byte slice with the exact same size as value
+// mustArrayToByteSlice creates a new byte slice with the exact same size as value
// and copies the bytes in value to the new slice.
func mustArrayToByteSlice(value reflect.Value) reflect.Value {
slice := reflect.MakeSlice(reflect.TypeOf([]byte{}), value.Len(), value.Len())
@@ -119,6 +142,9 @@ func setSlice(dst, src reflect.Value) error {
}
func setArray(dst, src reflect.Value) error {
+ if src.Kind() == reflect.Ptr {
+ return set(dst, indirect(src))
+ }
array := reflect.New(dst.Type()).Elem()
min := src.Len()
if src.Len() > dst.Len() {
diff --git a/accounts/abi/reflect_test.go b/accounts/abi/reflect_test.go
index c425e6e54..cf13a79da 100644
--- a/accounts/abi/reflect_test.go
+++ b/accounts/abi/reflect_test.go
@@ -17,6 +17,7 @@
package abi
import (
+ "math/big"
"reflect"
"testing"
)
@@ -189,3 +190,72 @@ func TestReflectNameToStruct(t *testing.T) {
})
}
}
+
+func TestConvertType(t *testing.T) {
+ // Test Basic Struct
+ type T struct {
+ X *big.Int
+ Y *big.Int
+ }
+ // Create on-the-fly structure
+ var fields []reflect.StructField
+ fields = append(fields, reflect.StructField{
+ Name: "X",
+ Type: reflect.TypeOf(new(big.Int)),
+ Tag: "json:\"" + "x" + "\"",
+ })
+ fields = append(fields, reflect.StructField{
+ Name: "Y",
+ Type: reflect.TypeOf(new(big.Int)),
+ Tag: "json:\"" + "y" + "\"",
+ })
+ val := reflect.New(reflect.StructOf(fields))
+ val.Elem().Field(0).Set(reflect.ValueOf(big.NewInt(1)))
+ val.Elem().Field(1).Set(reflect.ValueOf(big.NewInt(2)))
+ // ConvertType
+ out := *ConvertType(val.Interface(), new(T)).(*T)
+ if out.X.Cmp(big.NewInt(1)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out.X, big.NewInt(1))
+ }
+ if out.Y.Cmp(big.NewInt(2)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out.Y, big.NewInt(2))
+ }
+ // Slice Type
+ val2 := reflect.MakeSlice(reflect.SliceOf(reflect.StructOf(fields)), 2, 2)
+ val2.Index(0).Field(0).Set(reflect.ValueOf(big.NewInt(1)))
+ val2.Index(0).Field(1).Set(reflect.ValueOf(big.NewInt(2)))
+ val2.Index(1).Field(0).Set(reflect.ValueOf(big.NewInt(3)))
+ val2.Index(1).Field(1).Set(reflect.ValueOf(big.NewInt(4)))
+ out2 := *ConvertType(val2.Interface(), new([]T)).(*[]T)
+ if out2[0].X.Cmp(big.NewInt(1)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out2[0].X, big.NewInt(1))
+ }
+ if out2[0].Y.Cmp(big.NewInt(2)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out2[1].Y, big.NewInt(2))
+ }
+ if out2[1].X.Cmp(big.NewInt(3)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out2[0].X, big.NewInt(1))
+ }
+ if out2[1].Y.Cmp(big.NewInt(4)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out2[1].Y, big.NewInt(2))
+ }
+ // Array Type
+ val3 := reflect.New(reflect.ArrayOf(2, reflect.StructOf(fields)))
+ val3.Elem().Index(0).Field(0).Set(reflect.ValueOf(big.NewInt(1)))
+ val3.Elem().Index(0).Field(1).Set(reflect.ValueOf(big.NewInt(2)))
+ val3.Elem().Index(1).Field(0).Set(reflect.ValueOf(big.NewInt(3)))
+ val3.Elem().Index(1).Field(1).Set(reflect.ValueOf(big.NewInt(4)))
+ out3 := *ConvertType(val3.Interface(), new([2]T)).(*[2]T)
+ if out3[0].X.Cmp(big.NewInt(1)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out3[0].X, big.NewInt(1))
+ }
+ if out3[0].Y.Cmp(big.NewInt(2)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out3[1].Y, big.NewInt(2))
+ }
+ if out3[1].X.Cmp(big.NewInt(3)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out3[0].X, big.NewInt(1))
+ }
+ if out3[1].Y.Cmp(big.NewInt(4)) != 0 {
+ t.Errorf("ConvertType failed, got %v want %v", out3[1].Y, big.NewInt(2))
+ }
+}
diff --git a/accounts/abi/topics.go b/accounts/abi/topics.go
index 6dd0a923a..14f9b13d4 100644
--- a/accounts/abi/topics.go
+++ b/accounts/abi/topics.go
@@ -102,7 +102,7 @@ func genIntType(rule int64, size uint) []byte {
var topic [common.HashLength]byte
if rule < 0 {
// if a rule is negative, we need to put it into two's complement.
- // extended to common.Hashlength bytes.
+ // extended to common.HashLength bytes.
topic = [common.HashLength]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}
}
for i := uint(0); i < size; i++ {
@@ -120,7 +120,7 @@ func ParseTopics(out interface{}, fields Arguments, topics []common.Hash) error
})
}
-// ParseTopicsIntoMap converts the indexed topic field-value pairs into map key-value pairs
+// ParseTopicsIntoMap converts the indexed topic field-value pairs into map key-value pairs.
func ParseTopicsIntoMap(out map[string]interface{}, fields Arguments, topics []common.Hash) error {
return parseTopicWithSetter(fields, topics,
func(arg Argument, reconstr interface{}) {
diff --git a/accounts/abi/type.go b/accounts/abi/type.go
index 724cbf6a2..4e5d3c1f0 100644
--- a/accounts/abi/type.go
+++ b/accounts/abi/type.go
@@ -43,7 +43,7 @@ const (
FunctionTy
)
-// Type is the reflection of the supported argument type
+// Type is the reflection of the supported argument type.
type Type struct {
Elem *Type
Size int
@@ -263,7 +263,7 @@ func overloadedArgName(rawName string, names map[string]string) (string, error)
return fieldName, nil
}
-// String implements Stringer
+// String implements Stringer.
func (t Type) String() (out string) {
return t.stringKind
}
@@ -345,7 +345,7 @@ func (t Type) pack(v reflect.Value) ([]byte, error) {
return append(ret, tail...), nil
default:
- return packElement(t, v), nil
+ return packElement(t, v)
}
}
@@ -385,7 +385,7 @@ func isDynamicType(t Type) bool {
func getTypeSize(t Type) int {
if t.T == ArrayTy && !isDynamicType(*t.Elem) {
// Recursively calculate type size if it is a nested array
- if t.Elem.T == ArrayTy {
+ if t.Elem.T == ArrayTy || t.Elem.T == TupleTy {
return t.Size * getTypeSize(*t.Elem)
}
return t.Size * 32
diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go
index 403a838be..e83288e99 100644
--- a/accounts/abi/unpack.go
+++ b/accounts/abi/unpack.go
@@ -26,13 +26,13 @@ import (
)
var (
- // MaxUint256 is the maximum value that can be represented by a uint256
+ // MaxUint256 is the maximum value that can be represented by a uint256.
MaxUint256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 256), common.Big1)
- // MaxInt256 is the maximum value that can be represented by a int256
+ // MaxInt256 is the maximum value that can be represented by a int256.
MaxInt256 = new(big.Int).Sub(new(big.Int).Lsh(common.Big1, 255), common.Big1)
)
-// ReadInteger reads the integer based on its kind and returns the appropriate value
+// ReadInteger reads the integer based on its kind and returns the appropriate value.
func ReadInteger(typ Type, b []byte) interface{} {
if typ.T == UintTy {
switch typ.Size {
@@ -73,7 +73,7 @@ func ReadInteger(typ Type, b []byte) interface{} {
}
}
-// reads a bool
+// readBool reads a bool.
func readBool(word []byte) (bool, error) {
for _, b := range word[:31] {
if b != 0 {
@@ -91,7 +91,8 @@ func readBool(word []byte) (bool, error) {
}
// A function type is simply the address with the function selection signature at the end.
-// This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
+//
+// readFunctionType enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes)
func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
if t.T != FunctionTy {
return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
@@ -104,7 +105,7 @@ func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
return
}
-// ReadFixedBytes uses reflection to create a fixed array to be read from
+// ReadFixedBytes uses reflection to create a fixed array to be read from.
func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
if t.T != FixedBytesTy {
return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
@@ -117,7 +118,7 @@ func ReadFixedBytes(t Type, word []byte) (interface{}, error) {
}
-// iteratively unpack elements
+// forEachUnpack iteratively unpack elements.
func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
if size < 0 {
return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
@@ -224,7 +225,10 @@ func toGoType(index int, t Type, output []byte) (interface{}, error) {
return forEachUnpack(t, output[begin:], 0, length)
case ArrayTy:
if isDynamicType(*t.Elem) {
- offset := int64(binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:]))
+ offset := binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:])
+ if offset > uint64(len(output)) {
+ return nil, fmt.Errorf("abi: toGoType offset greater than output length: offset: %d, len(output): %d", offset, len(output))
+ }
return forEachUnpack(t, output[offset:], 0, t.Size)
}
return forEachUnpack(t, output[index:], 0, t.Size)
@@ -249,7 +253,7 @@ func toGoType(index int, t Type, output []byte) (interface{}, error) {
}
}
-// interprets a 32 byte slice as an offset and then determines which indice to look to decode the type.
+// lengthPrefixPointsTo interprets a 32 byte slice as an offset and then determines which indices to look to decode the type.
func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go
index c7084703e..787e10600 100644
--- a/accounts/abi/unpack_test.go
+++ b/accounts/abi/unpack_test.go
@@ -44,15 +44,13 @@ func TestUnpack(t *testing.T) {
if err != nil {
t.Fatalf("invalid hex %s: %v", test.packed, err)
}
- outptr := reflect.New(reflect.TypeOf(test.unpacked))
- err = abi.Unpack(outptr.Interface(), "method", encb)
+ out, err := abi.Unpack("method", encb)
if err != nil {
t.Errorf("test %d (%v) failed: %v", i, test.def, err)
return
}
- out := outptr.Elem().Interface()
- if !reflect.DeepEqual(test.unpacked, out) {
- t.Errorf("test %d (%v) failed: expected %v, got %v", i, test.def, test.unpacked, out)
+ if !reflect.DeepEqual(test.unpacked, ConvertType(out[0], test.unpacked)) {
+ t.Errorf("test %d (%v) failed: expected %v, got %v", i, test.def, test.unpacked, out[0])
}
})
}
@@ -221,7 +219,7 @@ func TestLocalUnpackTests(t *testing.T) {
t.Fatalf("invalid hex %s: %v", test.enc, err)
}
outptr := reflect.New(reflect.TypeOf(test.want))
- err = abi.Unpack(outptr.Interface(), "method", encb)
+ err = abi.UnpackIntoInterface(outptr.Interface(), "method", encb)
if err := test.checkError(err); err != nil {
t.Errorf("test %d (%v) failed: %v", i, test.def, err)
return
@@ -234,7 +232,7 @@ func TestLocalUnpackTests(t *testing.T) {
}
}
-func TestUnpackSetDynamicArrayOutput(t *testing.T) {
+func TestUnpackIntoInterfaceSetDynamicArrayOutput(t *testing.T) {
abi, err := JSON(strings.NewReader(`[{"constant":true,"inputs":[],"name":"testDynamicFixedBytes15","outputs":[{"name":"","type":"bytes15[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"testDynamicFixedBytes32","outputs":[{"name":"","type":"bytes32[]"}],"payable":false,"stateMutability":"view","type":"function"}]`))
if err != nil {
t.Fatal(err)
@@ -249,7 +247,7 @@ func TestUnpackSetDynamicArrayOutput(t *testing.T) {
)
// test 32
- err = abi.Unpack(&out32, "testDynamicFixedBytes32", marshalledReturn32)
+ err = abi.UnpackIntoInterface(&out32, "testDynamicFixedBytes32", marshalledReturn32)
if err != nil {
t.Fatal(err)
}
@@ -266,7 +264,7 @@ func TestUnpackSetDynamicArrayOutput(t *testing.T) {
}
// test 15
- err = abi.Unpack(&out15, "testDynamicFixedBytes32", marshalledReturn15)
+ err = abi.UnpackIntoInterface(&out15, "testDynamicFixedBytes32", marshalledReturn15)
if err != nil {
t.Fatal(err)
}
@@ -367,7 +365,7 @@ func TestMethodMultiReturn(t *testing.T) {
tc := tc
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
- err := abi.Unpack(tc.dest, "multi", data)
+ err := abi.UnpackIntoInterface(tc.dest, "multi", data)
if tc.error == "" {
require.Nil(err, "Should be able to unpack method outputs.")
require.Equal(tc.expected, tc.dest)
@@ -390,7 +388,7 @@ func TestMultiReturnWithArray(t *testing.T) {
ret1, ret1Exp := new([3]uint64), [3]uint64{9, 9, 9}
ret2, ret2Exp := new(uint64), uint64(8)
- if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
+ if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(*ret1, ret1Exp) {
@@ -414,7 +412,7 @@ func TestMultiReturnWithStringArray(t *testing.T) {
ret2, ret2Exp := new(common.Address), common.HexToAddress("ab1257528b3782fb40d7ed5f72e624b744dffb2f")
ret3, ret3Exp := new([2]string), [2]string{"Ethereum", "Hello, Ethereum!"}
ret4, ret4Exp := new(bool), false
- if err := abi.Unpack(&[]interface{}{ret1, ret2, ret3, ret4}, "multi", buff.Bytes()); err != nil {
+ if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2, ret3, ret4}, "multi", buff.Bytes()); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(*ret1, ret1Exp) {
@@ -452,7 +450,7 @@ func TestMultiReturnWithStringSlice(t *testing.T) {
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000065")) // output[1][1] value
ret1, ret1Exp := new([]string), []string{"ethereum", "go-ethereum"}
ret2, ret2Exp := new([]*big.Int), []*big.Int{big.NewInt(100), big.NewInt(101)}
- if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
+ if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(*ret1, ret1Exp) {
@@ -492,7 +490,7 @@ func TestMultiReturnWithDeeplyNestedArray(t *testing.T) {
{{0x411, 0x412, 0x413}, {0x421, 0x422, 0x423}},
}
ret2, ret2Exp := new(uint64), uint64(0x9876)
- if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
+ if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(*ret1, ret1Exp) {
@@ -531,7 +529,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000000a"))
buff.Write(common.Hex2Bytes("0102000000000000000000000000000000000000000000000000000000000000"))
- err = abi.Unpack(&mixedBytes, "mixedBytes", buff.Bytes())
+ err = abi.UnpackIntoInterface(&mixedBytes, "mixedBytes", buff.Bytes())
if err != nil {
t.Error(err)
} else {
@@ -546,7 +544,7 @@ func TestUnmarshal(t *testing.T) {
// marshal int
var Int *big.Int
- err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
+ err = abi.UnpackIntoInterface(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
if err != nil {
t.Error(err)
}
@@ -557,7 +555,7 @@ func TestUnmarshal(t *testing.T) {
// marshal bool
var Bool bool
- err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
+ err = abi.UnpackIntoInterface(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
if err != nil {
t.Error(err)
}
@@ -574,7 +572,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(bytesOut)
var Bytes []byte
- err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
+ err = abi.UnpackIntoInterface(&Bytes, "bytes", buff.Bytes())
if err != nil {
t.Error(err)
}
@@ -590,7 +588,7 @@ func TestUnmarshal(t *testing.T) {
bytesOut = common.RightPadBytes([]byte("hello"), 64)
buff.Write(bytesOut)
- err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
+ err = abi.UnpackIntoInterface(&Bytes, "bytes", buff.Bytes())
if err != nil {
t.Error(err)
}
@@ -606,7 +604,7 @@ func TestUnmarshal(t *testing.T) {
bytesOut = common.RightPadBytes([]byte("hello"), 64)
buff.Write(bytesOut)
- err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
+ err = abi.UnpackIntoInterface(&Bytes, "bytes", buff.Bytes())
if err != nil {
t.Error(err)
}
@@ -616,7 +614,7 @@ func TestUnmarshal(t *testing.T) {
}
// marshal dynamic bytes output empty
- err = abi.Unpack(&Bytes, "bytes", nil)
+ err = abi.UnpackIntoInterface(&Bytes, "bytes", nil)
if err == nil {
t.Error("expected error")
}
@@ -627,7 +625,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
buff.Write(common.RightPadBytes([]byte("hello"), 32))
- err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
+ err = abi.UnpackIntoInterface(&Bytes, "bytes", buff.Bytes())
if err != nil {
t.Error(err)
}
@@ -641,7 +639,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.RightPadBytes([]byte("hello"), 32))
var hash common.Hash
- err = abi.Unpack(&hash, "fixed", buff.Bytes())
+ err = abi.UnpackIntoInterface(&hash, "fixed", buff.Bytes())
if err != nil {
t.Error(err)
}
@@ -654,12 +652,12 @@ func TestUnmarshal(t *testing.T) {
// marshal error
buff.Reset()
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
- err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
+ err = abi.UnpackIntoInterface(&Bytes, "bytes", buff.Bytes())
if err == nil {
t.Error("expected error")
}
- err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
+ err = abi.UnpackIntoInterface(&Bytes, "multi", make([]byte, 64))
if err == nil {
t.Error("expected error")
}
@@ -670,7 +668,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000003"))
// marshal int array
var intArray [3]*big.Int
- err = abi.Unpack(&intArray, "intArraySingle", buff.Bytes())
+ err = abi.UnpackIntoInterface(&intArray, "intArraySingle", buff.Bytes())
if err != nil {
t.Error(err)
}
@@ -691,7 +689,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
var outAddr []common.Address
- err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
+ err = abi.UnpackIntoInterface(&outAddr, "addressSliceSingle", buff.Bytes())
if err != nil {
t.Fatal("didn't expect error:", err)
}
@@ -718,7 +716,7 @@ func TestUnmarshal(t *testing.T) {
A []common.Address
B []common.Address
}
- err = abi.Unpack(&outAddrStruct, "addressSliceDouble", buff.Bytes())
+ err = abi.UnpackIntoInterface(&outAddrStruct, "addressSliceDouble", buff.Bytes())
if err != nil {
t.Fatal("didn't expect error:", err)
}
@@ -746,7 +744,7 @@ func TestUnmarshal(t *testing.T) {
buff.Reset()
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000100"))
- err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
+ err = abi.UnpackIntoInterface(&outAddr, "addressSliceSingle", buff.Bytes())
if err == nil {
t.Fatal("expected error:", err)
}
@@ -769,7 +767,7 @@ func TestUnpackTuple(t *testing.T) {
B *big.Int
}{new(big.Int), new(big.Int)}
- err = abi.Unpack(&v, "tuple", buff.Bytes())
+ err = abi.UnpackIntoInterface(&v, "tuple", buff.Bytes())
if err != nil {
t.Error(err)
} else {
@@ -841,7 +839,7 @@ func TestUnpackTuple(t *testing.T) {
A: big.NewInt(1),
}
- err = abi.Unpack(&ret, "tuple", buff.Bytes())
+ err = abi.UnpackIntoInterface(&ret, "tuple", buff.Bytes())
if err != nil {
t.Error(err)
}
diff --git a/accounts/accounts.go b/accounts/accounts.go
index 7a3e29c5c..a305025f8 100644
--- a/accounts/accounts.go
+++ b/accounts/accounts.go
@@ -18,6 +18,8 @@
package accounts
import (
+ "fmt"
+ "golang.org/x/crypto/sha3"
"math/big"
"github.com/truechain/truechain-engineering-code"
@@ -33,6 +35,13 @@ type Account struct {
URL URL `json:"url"` // Optional resource locator within a backend
}
+const (
+ MimetypeDataWithValidator = "data/validator"
+ MimetypeTypedData = "data/typed"
+ MimetypeClique = "application/x-clique-header"
+ MimetypeTextPlain = "text/plain"
+)
+
// Wallet represents a software or hardware wallet that might contain one or more
// accounts (derived from the same seed).
type Wallet interface {
@@ -79,16 +88,38 @@ type Wallet interface {
// to discover non zero accounts and automatically add them to list of tracked
// accounts.
//
- // Note, self derivaton will increment the last component of the specified path
+ // Note, self derivation will increment the last component of the specified path
// opposed to decending into a child path to allow discovering accounts starting
// from non zero components.
//
+ // Some hardware wallets switched derivation paths through their evolution, so
+ // this method supports providing multiple bases to discover old user accounts
+ // too. Only the last base will be used to derive the next empty account.
+ //
// You can disable automatic account discovery by calling SelfDerive with a nil
// chain state reader.
- SelfDerive(base DerivationPath, chain truechain.ChainStateReader)
+ SelfDerive(bases []DerivationPath, chain truechain.ChainStateReader)
- // SignHash requests the wallet to sign the given hash.
+ // SignData requests the wallet to sign the hash of the given data
+ // It looks up the account specified either solely via its address contained within,
+ // or optionally with the aid of any location metadata from the embedded URL field.
//
+ // If the wallet requires additional authentication to sign the request (e.g.
+ // a password to decrypt the account, or a PIN code o verify the transaction),
+ // an AuthNeededError instance will be returned, containing infos for the user
+ // about which fields or actions are needed. The user may retry by providing
+ // the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
+ // the account in a keystore).
+ SignData(account Account, mimeType string, data []byte) ([]byte, error)
+
+ // SignDataWithPassphrase is identical to SignData, but also takes a password
+ // NOTE: there's a chance that an erroneous call might mistake the two strings, and
+ // supply password in the mimetype field, or vice versa. Thus, an implementation
+ // should never echo the mimetype or return the mimetype in the error-response
+ SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error)
+
+ // SignText requests the wallet to sign the hash of a given piece of data, prefixed
+ // by the Ethereum prefix scheme
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
//
@@ -96,9 +127,14 @@ type Wallet interface {
// a password to decrypt the account, or a PIN code o verify the transaction),
// an AuthNeededError instance will be returned, containing infos for the user
// about which fields or actions are needed. The user may retry by providing
- // the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
+ // the needed details via SignTextWithPassphrase, or by other means (e.g. unlock
// the account in a keystore).
- SignHash(account Account, hash []byte) ([]byte, error)
+ //
+ // This method should return the signature in 'canonical' format, with v 0 or 1
+ SignText(account Account, text []byte) ([]byte, error)
+
+ // SignTextWithPassphrase is identical to Signtext, but also takes a password
+ SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
// SignTx requests the wallet to sign the given transaction.
//
@@ -113,20 +149,7 @@ type Wallet interface {
// the account in a keystore).
SignTx(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
- SignTx_Payment(account Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
-
- // SignHashWithPassphrase requests the wallet to sign the given hash with the
- // given passphrase as extra authentication information.
- //
- // It looks up the account specified either solely via its address contained within,
- // or optionally with the aid of any location metadata from the embedded URL field.
- SignHashWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
-
- // SignTxWithPassphrase requests the wallet to sign the given transaction, with the
- // given passphrase as extra authentication information.
- //
- // It looks up the account specified either solely via its address contained within,
- // or optionally with the aid of any location metadata from the embedded URL field.
+ // SignTxWithPassphrase is identical to SignTx, but also takes a password
SignTxWithPassphrase(account Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
}
@@ -150,6 +173,32 @@ type Backend interface {
Subscribe(sink chan<- WalletEvent) event.Subscription
}
+// TextHash is a helper function that calculates a hash for the given message that can be
+// safely used to calculate a signature from.
+//
+// The hash is calulcated as
+// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
+//
+// This gives context to the signed message and prevents signing of transactions.
+func TextHash(data []byte) []byte {
+ hash, _ := TextAndHash(data)
+ return hash
+}
+
+// TextAndHash is a helper function that calculates a hash for the given message that can be
+// safely used to calculate a signature from.
+//
+// The hash is calulcated as
+// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
+//
+// This gives context to the signed message and prevents signing of transactions.
+func TextAndHash(data []byte) ([]byte, string) {
+ msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), string(data))
+ hasher := sha3.NewLegacyKeccak256()
+ hasher.Write([]byte(msg))
+ return hasher.Sum(nil), msg
+}
+
// WalletEventType represents the different event types that can be fired by
// the wallet subscription subsystem.
type WalletEventType int
diff --git a/accounts/errors.go b/accounts/errors.go
index 40b21ed17..2fed35f9d 100644
--- a/accounts/errors.go
+++ b/accounts/errors.go
@@ -35,7 +35,7 @@ var ErrNotSupported = errors.New("not supported")
// ErrInvalidPassphrase is returned when a decryption operation receives a bad
// passphrase.
-var ErrInvalidPassphrase = errors.New("invalid passphrase")
+var ErrInvalidPassphrase = errors.New("invalid password")
// ErrWalletAlreadyOpen is returned if a wallet is attempted to be opened the
// second time.
diff --git a/accounts/hd.go b/accounts/hd.go
index 6ed631807..54acea3b2 100644
--- a/accounts/hd.go
+++ b/accounts/hd.go
@@ -17,6 +17,7 @@
package accounts
import (
+ "encoding/json"
"errors"
"fmt"
"math"
@@ -34,10 +35,10 @@ var DefaultRootDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60,
// at m/44'/60'/0'/0/1, etc.
var DefaultBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0, 0}
-// DefaultLedgerBaseDerivationPath is the base path from which custom derivation endpoints
-// are incremented. As such, the first account will be at m/44'/60'/0'/0, the second
-// at m/44'/60'/0'/1, etc.
-var DefaultLedgerBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0}
+// LegacyLedgerBaseDerivationPath is the legacy base path from which custom derivation
+// endpoints are incremented. As such, the first account will be at m/44'/60'/0'/0, the
+// second at m/44'/60'/0'/1, etc.
+var LegacyLedgerBaseDerivationPath = DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0}
// DerivationPath represents the computer friendly version of a hierarchical
// deterministic wallet account derivaion path.
@@ -133,3 +134,47 @@ func (path DerivationPath) String() string {
}
return result
}
+
+// MarshalJSON turns a derivation path into its json-serialized string
+func (path DerivationPath) MarshalJSON() ([]byte, error) {
+ return json.Marshal(path.String())
+}
+
+// UnmarshalJSON a json-serialized string back into a derivation path
+func (path *DerivationPath) UnmarshalJSON(b []byte) error {
+ var dp string
+ var err error
+ if err = json.Unmarshal(b, &dp); err != nil {
+ return err
+ }
+ *path, err = ParseDerivationPath(dp)
+ return err
+}
+
+// DefaultIterator creates a BIP-32 path iterator, which progresses by increasing the last component:
+// i.e. m/44'/60'/0'/0/0, m/44'/60'/0'/0/1, m/44'/60'/0'/0/2, ... m/44'/60'/0'/0/N.
+func DefaultIterator(base DerivationPath) func() DerivationPath {
+ path := make(DerivationPath, len(base))
+ copy(path[:], base[:])
+ // Set it back by one, so the first call gives the first result
+ path[len(path)-1]--
+ return func() DerivationPath {
+ path[len(path)-1]++
+ return path
+ }
+}
+
+// LedgerLiveIterator creates a bip44 path iterator for Ledger Live.
+// Ledger Live increments the third component rather than the fifth component
+// i.e. m/44'/60'/0'/0/0, m/44'/60'/1'/0/0, m/44'/60'/2'/0/0, ... m/44'/60'/N'/0/0.
+func LedgerLiveIterator(base DerivationPath) func() DerivationPath {
+ path := make(DerivationPath, len(base))
+ copy(path[:], base[:])
+ // Set it back by one, so the first call gives the first result
+ path[2]--
+ return func() DerivationPath {
+ // ledgerLivePathIterator iterates on the third component
+ path[2]++
+ return path
+ }
+}
diff --git a/accounts/hd_test.go b/accounts/hd_test.go
index b6b23230d..0743bbe66 100644
--- a/accounts/hd_test.go
+++ b/accounts/hd_test.go
@@ -17,6 +17,7 @@
package accounts
import (
+ "fmt"
"reflect"
"testing"
)
@@ -61,7 +62,7 @@ func TestHDPathParsing(t *testing.T) {
// Weird inputs just to ensure they work
{" m / 44 '\n/\n 60 \n\n\t' /\n0 ' /\t\t 0", DerivationPath{0x80000000 + 44, 0x80000000 + 60, 0x80000000 + 0, 0}},
- // Invaid derivation paths
+ // Invalid derivation paths
{"", nil}, // Empty relative derivation path
{"m", nil}, // Empty absolute derivation path
{"m/", nil}, // Missing last derivation component
@@ -77,3 +78,41 @@ func TestHDPathParsing(t *testing.T) {
}
}
}
+
+func testDerive(t *testing.T, next func() DerivationPath, expected []string) {
+ t.Helper()
+ for i, want := range expected {
+ if have := next(); fmt.Sprintf("%v", have) != want {
+ t.Errorf("step %d, have %v, want %v", i, have, want)
+ }
+ }
+}
+
+func TestHdPathIteration(t *testing.T) {
+ testDerive(t, DefaultIterator(DefaultBaseDerivationPath),
+ []string{
+ "m/44'/60'/0'/0/0", "m/44'/60'/0'/0/1",
+ "m/44'/60'/0'/0/2", "m/44'/60'/0'/0/3",
+ "m/44'/60'/0'/0/4", "m/44'/60'/0'/0/5",
+ "m/44'/60'/0'/0/6", "m/44'/60'/0'/0/7",
+ "m/44'/60'/0'/0/8", "m/44'/60'/0'/0/9",
+ })
+
+ testDerive(t, DefaultIterator(LegacyLedgerBaseDerivationPath),
+ []string{
+ "m/44'/60'/0'/0", "m/44'/60'/0'/1",
+ "m/44'/60'/0'/2", "m/44'/60'/0'/3",
+ "m/44'/60'/0'/4", "m/44'/60'/0'/5",
+ "m/44'/60'/0'/6", "m/44'/60'/0'/7",
+ "m/44'/60'/0'/8", "m/44'/60'/0'/9",
+ })
+
+ testDerive(t, LedgerLiveIterator(DefaultBaseDerivationPath),
+ []string{
+ "m/44'/60'/0'/0/0", "m/44'/60'/1'/0/0",
+ "m/44'/60'/2'/0/0", "m/44'/60'/3'/0/0",
+ "m/44'/60'/4'/0/0", "m/44'/60'/5'/0/0",
+ "m/44'/60'/6'/0/0", "m/44'/60'/7'/0/0",
+ "m/44'/60'/8'/0/0", "m/44'/60'/9'/0/0",
+ })
+}
diff --git a/accounts/keystore/account_cache.go b/accounts/keystore/account_cache.go
index cdf1534c5..9edb29827 100644
--- a/accounts/keystore/account_cache.go
+++ b/accounts/keystore/account_cache.go
@@ -262,10 +262,13 @@ func (ac *accountCache) scanAccounts() error {
switch {
case err != nil:
log.Debug("Failed to decode keystore key", "path", path, "err", err)
- case (addr == common.Address{}):
+ case addr == common.Address{}:
log.Debug("Failed to decode keystore key", "path", path, "err", "missing or zero address")
default:
- return &accounts.Account{Address: addr, URL: accounts.URL{Scheme: KeyStoreScheme, Path: path}}
+ return &accounts.Account{
+ Address: addr,
+ URL: accounts.URL{Scheme: KeyStoreScheme, Path: path},
+ }
}
return nil
}
diff --git a/accounts/keystore/file_cache.go b/accounts/keystore/file_cache.go
index 0c21eae75..9a173764e 100644
--- a/accounts/keystore/file_cache.go
+++ b/accounts/keystore/file_cache.go
@@ -32,7 +32,7 @@ import (
type fileCache struct {
all mapset.Set // Set of all files from the keystore folder
lastMod time.Time // Last time instance when a file was modified
- mu sync.RWMutex
+ mu sync.Mutex
}
// scan performs a new scan on the given directory, compares against the already
diff --git a/accounts/keystore/key.go b/accounts/keystore/key.go
index b7e9ff3fe..0de2d58a6 100644
--- a/accounts/keystore/key.go
+++ b/accounts/keystore/key.go
@@ -29,10 +29,10 @@ import (
"strings"
"time"
+ "github.com/google/uuid"
"github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/crypto"
- "github.com/pborman/uuid"
)
const (
@@ -110,7 +110,10 @@ func (k *Key) UnmarshalJSON(j []byte) (err error) {
}
u := new(uuid.UUID)
- *u = uuid.Parse(keyJSON.Id)
+ *u, err = uuid.Parse(keyJSON.Id)
+ if err != nil {
+ return err
+ }
k.Id = *u
addr, err := hex.DecodeString(keyJSON.Address)
if err != nil {
@@ -128,7 +131,10 @@ func (k *Key) UnmarshalJSON(j []byte) (err error) {
}
func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
- id := uuid.NewRandom()
+ id, err := uuid.NewRandom()
+ if err != nil {
+ panic(fmt.Sprintf("Could not create random uuid: %v", err))
+ }
key := &Key{
Id: id,
Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
@@ -171,7 +177,10 @@ func storeNewKey(ks keyStore, rand io.Reader, auth string) (*Key, accounts.Accou
if err != nil {
return nil, accounts.Account{}, err
}
- a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.JoinPath(keyFileName(key.Address))}}
+ a := accounts.Account{
+ Address: key.Address,
+ URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.JoinPath(keyFileName(key.Address))},
+ }
if err := ks.StoreKey(a.URL.Path, key, auth); err != nil {
zeroKey(key.PrivateKey)
return nil, a, err
@@ -224,5 +233,6 @@ func toISO8601(t time.Time) string {
} else {
tz = fmt.Sprintf("%03d00", offset/3600)
}
- return fmt.Sprintf("%04d-%02d-%02dT%02d-%02d-%02d.%09d%s", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), tz)
+ return fmt.Sprintf("%04d-%02d-%02dT%02d-%02d-%02d.%09d%s",
+ t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), tz)
}
diff --git a/accounts/keystore/keystore.go b/accounts/keystore/keystore.go
index e9d859ef2..512159b40 100644
--- a/accounts/keystore/keystore.go
+++ b/accounts/keystore/keystore.go
@@ -24,7 +24,6 @@ import (
"crypto/ecdsa"
crand "crypto/rand"
"errors"
- "fmt"
"math/big"
"os"
"path/filepath"
@@ -33,17 +32,21 @@ import (
"sync"
"time"
- "github.com/truechain/truechain-engineering-code/common"
- "github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/accounts"
+ "github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/core/types"
+ "github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/event"
)
var (
ErrLocked = accounts.NewAuthNeededError("password or unlock")
ErrNoMatch = errors.New("no key for given address or file")
- ErrDecrypt = errors.New("could not decrypt key with given passphrase")
+ ErrDecrypt = errors.New("could not decrypt key with given password")
+
+ // ErrAccountAlreadyExists is returned if an account attempted to import is
+ // already present in the keystore.
+ ErrAccountAlreadyExists = errors.New("account already exists")
)
// KeyStoreType is the reflect type of a keystore backend.
@@ -67,7 +70,8 @@ type KeyStore struct {
updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
updating bool // Whether the event notification loop is running
- mu sync.RWMutex
+ mu sync.RWMutex
+ importMu sync.Mutex // Import Mutex locks the import to prevent two insertions from racing
}
type unlocked struct {
@@ -137,8 +141,10 @@ func (ks *KeyStore) refreshWallets() {
accs := ks.cache.accounts()
// Transform the current list of wallets into the new one
- wallets := make([]accounts.Wallet, 0, len(accs))
- events := []accounts.WalletEvent{}
+ var (
+ wallets = make([]accounts.Wallet, 0, len(accs))
+ events []accounts.WalletEvent
+ )
for _, account := range accs {
// Drop wallets while they were in front of the next account
@@ -277,21 +283,9 @@ func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *b
if !found {
return nil, ErrLocked
}
- // Depending on the presence of the chain ID, sign with EIP155 or homestead
- return types.SignTx(tx, types.NewTIP1Signer(chainID), unlockedKey.PrivateKey)
-}
-
-func (ks *KeyStore) SignTx_Payment(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
- // Look up the key to sign with and abort if it cannot be found
- ks.mu.RLock()
- defer ks.mu.RUnlock()
-
- unlockedKey, found := ks.unlocked[a.Address]
- if !found {
- return nil, ErrLocked
- }
- // Depending on the presence of the chain ID, sign with EIP155 or homestead
- return types.SignTx_Payment(tx, types.NewTIP1Signer(chainID), unlockedKey.PrivateKey)
+ // Depending on the presence of the chain ID, sign with 2718 or homestead
+ signer := types.LatestSignerForChainID(chainID)
+ return types.SignTx(tx, signer, unlockedKey.PrivateKey)
}
// SignHashWithPassphrase signs hash if the private key matching the given address
@@ -314,9 +308,9 @@ func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string,
return nil, err
}
defer zeroKey(key.PrivateKey)
-
- // Depending on the presence of the chain ID, sign with EIP155 or homestead
- return types.SignTx(tx, types.NewTIP1Signer(chainID), key.PrivateKey)
+ // Depending on the presence of the chain ID, sign with or without replay protection.
+ signer := types.LatestSignerForChainID(chainID)
+ return types.SignTx(tx, signer, key.PrivateKey)
}
// Unlock unlocks the given account indefinitely.
@@ -448,14 +442,27 @@ func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (ac
if err != nil {
return accounts.Account{}, err
}
+ ks.importMu.Lock()
+ defer ks.importMu.Unlock()
+
+ if ks.cache.hasAddress(key.Address) {
+ return accounts.Account{
+ Address: key.Address,
+ }, ErrAccountAlreadyExists
+ }
return ks.importKey(key, newPassphrase)
}
// ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
+ ks.importMu.Lock()
+ defer ks.importMu.Unlock()
+
key := newKeyFromECDSA(priv)
if ks.cache.hasAddress(key.Address) {
- return accounts.Account{}, fmt.Errorf("account already exists")
+ return accounts.Account{
+ Address: key.Address,
+ }, ErrAccountAlreadyExists
}
return ks.importKey(key, passphrase)
}
diff --git a/accounts/keystore/keystore_passphrase.go b/accounts/keystore/keystore_passphrase.go
index f5769497c..f6d4d2157 100644
--- a/accounts/keystore/keystore_passphrase.go
+++ b/accounts/keystore/keystore_passphrase.go
@@ -38,7 +38,7 @@ import (
"os"
"path/filepath"
- "github.com/pborman/uuid"
+ "github.com/google/uuid"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/common/math"
"github.com/truechain/truechain-engineering-code/crypto"
@@ -227,9 +227,12 @@ func DecryptKey(keyjson []byte, auth string) (*Key, error) {
return nil, err
}
key := crypto.ToECDSAUnsafe(keyBytes)
-
+ id, err := uuid.FromBytes(keyId)
+ if err != nil {
+ return nil, err
+ }
return &Key{
- Id: uuid.UUID(keyId),
+ Id: id,
Address: crypto.PubkeyToAddress(key.PublicKey),
PrivateKey: key,
}, nil
@@ -274,7 +277,11 @@ func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byt
if keyProtected.Version != version {
return nil, nil, fmt.Errorf("Version not supported: %v", keyProtected.Version)
}
- keyId = uuid.Parse(keyProtected.Id)
+ keyUUID, err := uuid.Parse(keyProtected.Id)
+ if err != nil {
+ return nil, nil, err
+ }
+ keyId = keyUUID[:]
plainText, err := DecryptDataV3(keyProtected.Crypto, auth)
if err != nil {
return nil, nil, err
@@ -283,7 +290,11 @@ func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byt
}
func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
- keyId = uuid.Parse(keyProtected.Id)
+ keyUUID, err := uuid.Parse(keyProtected.Id)
+ if err != nil {
+ return nil, nil, err
+ }
+ keyId = keyUUID[:]
mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
if err != nil {
return nil, nil, err
diff --git a/accounts/keystore/keystore_test.go b/accounts/keystore/keystore_test.go
index e818870d1..34c409ce1 100644
--- a/accounts/keystore/keystore_test.go
+++ b/accounts/keystore/keystore_test.go
@@ -23,6 +23,8 @@ import (
"runtime"
"sort"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -333,11 +335,95 @@ func TestWalletNotifications(t *testing.T) {
// Shut down the event collector and check events.
sub.Unsubscribe()
- <-updates
+ for ev := range updates {
+ events = append(events, walletEvent{ev, ev.Wallet.Accounts()[0]})
+ }
checkAccounts(t, live, ks.Wallets())
checkEvents(t, wantEvents, events)
}
+// TestImportExport tests the import functionality of a keystore.
+func TestImportECDSA(t *testing.T) {
+ dir, ks := tmpKeyStore(t, true)
+ defer os.RemoveAll(dir)
+ key, err := crypto.GenerateKey()
+ if err != nil {
+ t.Fatalf("failed to generate key: %v", key)
+ }
+ if _, err = ks.ImportECDSA(key, "old"); err != nil {
+ t.Errorf("importing failed: %v", err)
+ }
+ if _, err = ks.ImportECDSA(key, "old"); err == nil {
+ t.Errorf("importing same key twice succeeded")
+ }
+ if _, err = ks.ImportECDSA(key, "new"); err == nil {
+ t.Errorf("importing same key twice succeeded")
+ }
+}
+
+// TestImportECDSA tests the import and export functionality of a keystore.
+func TestImportExport(t *testing.T) {
+ dir, ks := tmpKeyStore(t, true)
+ defer os.RemoveAll(dir)
+ acc, err := ks.NewAccount("old")
+ if err != nil {
+ t.Fatalf("failed to create account: %v", acc)
+ }
+ json, err := ks.Export(acc, "old", "new")
+ if err != nil {
+ t.Fatalf("failed to export account: %v", acc)
+ }
+ dir2, ks2 := tmpKeyStore(t, true)
+ defer os.RemoveAll(dir2)
+ if _, err = ks2.Import(json, "old", "old"); err == nil {
+ t.Errorf("importing with invalid password succeeded")
+ }
+ acc2, err := ks2.Import(json, "new", "new")
+ if err != nil {
+ t.Errorf("importing failed: %v", err)
+ }
+ if acc.Address != acc2.Address {
+ t.Error("imported account does not match exported account")
+ }
+ if _, err = ks2.Import(json, "new", "new"); err == nil {
+ t.Errorf("importing a key twice succeeded")
+ }
+
+}
+
+// TestImportRace tests the keystore on races.
+// This test should fail under -race if importing races.
+func TestImportRace(t *testing.T) {
+ dir, ks := tmpKeyStore(t, true)
+ defer os.RemoveAll(dir)
+ acc, err := ks.NewAccount("old")
+ if err != nil {
+ t.Fatalf("failed to create account: %v", acc)
+ }
+ json, err := ks.Export(acc, "old", "new")
+ if err != nil {
+ t.Fatalf("failed to export account: %v", acc)
+ }
+ dir2, ks2 := tmpKeyStore(t, true)
+ defer os.RemoveAll(dir2)
+ var atom uint32
+ var wg sync.WaitGroup
+ wg.Add(2)
+ for i := 0; i < 2; i++ {
+ go func() {
+ defer wg.Done()
+ if _, err := ks2.Import(json, "new", "new"); err != nil {
+ atomic.AddUint32(&atom, 1)
+ }
+
+ }()
+ }
+ wg.Wait()
+ if atom != 1 {
+ t.Errorf("Import is racy")
+ }
+}
+
// checkAccounts checks that all known live accounts are present in the wallet list.
func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, wallets []accounts.Wallet) {
if len(live) != len(wallets) {
@@ -379,9 +465,9 @@ func tmpKeyStore(t *testing.T, encrypted bool) (string, *KeyStore) {
if err != nil {
t.Fatal(err)
}
- new := NewPlaintextKeyStore
+ newKs := NewPlaintextKeyStore
if encrypted {
- new = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
+ newKs = func(kd string) *KeyStore { return NewKeyStore(kd, veryLightScryptN, veryLightScryptP) }
}
- return d, new(d)
+ return d, newKs(d)
}
diff --git a/accounts/keystore/keystore_wallet.go b/accounts/keystore/keystore_wallet.go
index 677599c49..e9a0c92d6 100644
--- a/accounts/keystore/keystore_wallet.go
+++ b/accounts/keystore/keystore_wallet.go
@@ -19,9 +19,10 @@ package keystore
import (
"math/big"
- ethereum "github.com/truechain/truechain-engineering-code"
+ "github.com/truechain/truechain-engineering-code"
"github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/core/types"
+ "github.com/truechain/truechain-engineering-code/crypto"
)
// keystoreWallet implements the accounts.Wallet interface for the original
@@ -76,7 +77,8 @@ func (w *keystoreWallet) Derive(path accounts.DerivationPath, pin bool) (account
// SelfDerive implements accounts.Wallet, but is a noop for plain wallets since
// there is no notion of hierarchical account derivation for plain keystore accounts.
-func (w *keystoreWallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {}
+func (w *keystoreWallet) SelfDerive(base []accounts.DerivationPath, chain truechain.ChainStateReader) {
+}
// SignHash implements accounts.Wallet, attempting to sign the given hash with
// the given account. If the wallet does not wrap this particular account, an
@@ -110,18 +112,6 @@ func (w *keystoreWallet) SignTx(account accounts.Account, tx *types.Transaction,
return w.keystore.SignTx(account, tx, chainID)
}
-func (w *keystoreWallet) SignTx_Payment(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
- // Make sure the requested account is contained within
- if account.Address != w.account.Address {
- return nil, accounts.ErrUnknownAccount
- }
- if account.URL != (accounts.URL{}) && account.URL != w.account.URL {
- return nil, accounts.ErrUnknownAccount
- }
- // Account seems valid, request the keystore to sign
- return w.keystore.SignTx_Payment(account, tx, chainID)
-}
-
// SignHashWithPassphrase implements accounts.Wallet, attempting to sign the
// given hash with the given account using passphrase as extra authentication.
func (w *keystoreWallet) SignHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
@@ -149,3 +139,48 @@ func (w *keystoreWallet) SignTxWithPassphrase(account accounts.Account, passphra
// Account seems valid, request the keystore to sign
return w.keystore.SignTxWithPassphrase(account, passphrase, tx, chainID)
}
+
+// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed.
+func (w *keystoreWallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
+ return w.signHash(account, crypto.Keccak256(data))
+}
+
+// SignDataWithPassphrase signs keccak256(data). The mimetype parameter describes the type of data being signed.
+func (w *keystoreWallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
+ // Make sure the requested account is contained within
+ if !w.Contains(account) {
+ return nil, accounts.ErrUnknownAccount
+ }
+ // Account seems valid, request the keystore to sign
+ return w.keystore.SignHashWithPassphrase(account, passphrase, crypto.Keccak256(data))
+}
+
+// SignText implements accounts.Wallet, attempting to sign the hash of
+// the given text with the given account.
+func (w *keystoreWallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
+ return w.signHash(account, accounts.TextHash(text))
+}
+
+// SignTextWithPassphrase implements accounts.Wallet, attempting to sign the
+// hash of the given text with the given account using passphrase as extra authentication.
+func (w *keystoreWallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
+ // Make sure the requested account is contained within
+ if !w.Contains(account) {
+ return nil, accounts.ErrUnknownAccount
+ }
+ // Account seems valid, request the keystore to sign
+ return w.keystore.SignHashWithPassphrase(account, passphrase, accounts.TextHash(text))
+}
+
+// signHash attempts to sign the given hash with
+// the given account. If the wallet does not wrap this particular account, an
+// error is returned to avoid account leakage (even though in theory we may be
+// able to sign via our shared keystore backend).
+func (w *keystoreWallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
+ // Make sure the requested account is contained within
+ if !w.Contains(account) {
+ return nil, accounts.ErrUnknownAccount
+ }
+ // Account seems valid, request the keystore to sign
+ return w.keystore.SignHash(account, hash)
+}
diff --git a/accounts/keystore/presale.go b/accounts/keystore/presale.go
index 162a933d2..234b057bb 100644
--- a/accounts/keystore/presale.go
+++ b/accounts/keystore/presale.go
@@ -25,9 +25,9 @@ import (
"errors"
"fmt"
+ "github.com/google/uuid"
"github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/crypto"
- "github.com/pborman/uuid"
"golang.org/x/crypto/pbkdf2"
)
@@ -37,8 +37,17 @@ func importPreSaleKey(keyStore keyStore, keyJSON []byte, password string) (accou
if err != nil {
return accounts.Account{}, nil, err
}
- key.Id = uuid.NewRandom()
- a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: keyStore.JoinPath(keyFileName(key.Address))}}
+ key.Id, err = uuid.NewRandom()
+ if err != nil {
+ return accounts.Account{}, nil, err
+ }
+ a := accounts.Account{
+ Address: key.Address,
+ URL: accounts.URL{
+ Scheme: KeyStoreScheme,
+ Path: keyStore.JoinPath(keyFileName(key.Address)),
+ },
+ }
err = keyStore.StoreKey(a.URL.Path, key, password)
return a, key, err
}
@@ -80,7 +89,7 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error
ecKey := crypto.ToECDSAUnsafe(ethPriv)
key = &Key{
- Id: nil,
+ Id: uuid.UUID{},
Address: crypto.PubkeyToAddress(ecKey.PublicKey),
PrivateKey: ecKey,
}
diff --git a/accounts/manager.go b/accounts/manager.go
index 5f59a64cc..84438704f 100644
--- a/accounts/manager.go
+++ b/accounts/manager.go
@@ -21,12 +21,22 @@ import (
"sort"
"sync"
+ "github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/event"
)
+// Config contains the settings of the global account manager.
+//
+// TODO(rjl493456442, karalabe, holiman): Get rid of this when account management
+// is removed in favor of Clef.
+type Config struct {
+ InsecureUnlockAllowed bool // Whether account unlocking in insecure environment is allowed
+}
+
// Manager is an overarching account manager that can communicate with various
// backends for signing transactions.
type Manager struct {
+ config *Config // Global account manager configurations
backends map[reflect.Type][]Backend // Index of backends currently registered
updaters []event.Subscription // Wallet update subscriptions for all backends
updates chan WalletEvent // Subscription sink for backend wallet changes
@@ -40,7 +50,7 @@ type Manager struct {
// NewManager creates a generic account manager to sign transaction via various
// supported backends.
-func NewManager(backends ...Backend) *Manager {
+func NewManager(config *Config, backends ...Backend) *Manager {
// Retrieve the initial list of wallets from the backends and sort by URL
var wallets []Wallet
for _, backend := range backends {
@@ -55,6 +65,7 @@ func NewManager(backends ...Backend) *Manager {
}
// Assemble the account manager and return
am := &Manager{
+ config: config,
backends: make(map[reflect.Type][]Backend),
updaters: subs,
updates: updates,
@@ -77,6 +88,11 @@ func (am *Manager) Close() error {
return <-errc
}
+// Config returns the configuration of account manager.
+func (am *Manager) Config() *Config {
+ return am.config
+}
+
// update is the wallet event loop listening for notifications from the backends
// and updating the cache of wallets.
func (am *Manager) update() {
@@ -125,6 +141,11 @@ func (am *Manager) Wallets() []Wallet {
am.lock.RLock()
defer am.lock.RUnlock()
+ return am.walletsNoLock()
+}
+
+// walletsNoLock returns all registered wallets. Callers must hold am.lock.
+func (am *Manager) walletsNoLock() []Wallet {
cpy := make([]Wallet, len(am.wallets))
copy(cpy, am.wallets)
return cpy
@@ -139,7 +160,7 @@ func (am *Manager) Wallet(url string) (Wallet, error) {
if err != nil {
return nil, err
}
- for _, wallet := range am.Wallets() {
+ for _, wallet := range am.walletsNoLock() {
if wallet.URL() == parsed {
return wallet, nil
}
@@ -147,6 +168,20 @@ func (am *Manager) Wallet(url string) (Wallet, error) {
return nil, ErrUnknownWallet
}
+// Accounts returns all account addresses of all wallets within the account manager
+func (am *Manager) Accounts() []common.Address {
+ am.lock.RLock()
+ defer am.lock.RUnlock()
+
+ addresses := make([]common.Address, 0) // return [] instead of nil if empty
+ for _, wallet := range am.wallets {
+ for _, account := range wallet.Accounts() {
+ addresses = append(addresses, account.Address)
+ }
+ }
+ return addresses
+}
+
// Find attempts to locate the wallet corresponding to a specific account. Since
// accounts can be dynamically added to and removed from wallets, this method has
// a linear runtime in the number of wallets.
diff --git a/accounts/sort.go b/accounts/sort.go
new file mode 100644
index 000000000..f46762114
--- /dev/null
+++ b/accounts/sort.go
@@ -0,0 +1,31 @@
+// Copyright 2018 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package accounts
+
+// AccountsByURL implements sort.Interface for []Account based on the URL field.
+type AccountsByURL []Account
+
+func (a AccountsByURL) Len() int { return len(a) }
+func (a AccountsByURL) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a AccountsByURL) Less(i, j int) bool { return a[i].URL.Cmp(a[j].URL) < 0 }
+
+// WalletsByURL implements sort.Interface for []Wallet based on the URL field.
+type WalletsByURL []Wallet
+
+func (w WalletsByURL) Len() int { return len(w) }
+func (w WalletsByURL) Swap(i, j int) { w[i], w[j] = w[j], w[i] }
+func (w WalletsByURL) Less(i, j int) bool { return w[i].URL().Cmp(w[j].URL()) < 0 }
diff --git a/accounts/url.go b/accounts/url.go
index a5add1021..12a84414a 100644
--- a/accounts/url.go
+++ b/accounts/url.go
@@ -64,7 +64,7 @@ func (u URL) String() string {
func (u URL) TerminalString() string {
url := u.String()
if len(url) > 32 {
- return url[:31] + "…"
+ return url[:31] + ".."
}
return url
}
diff --git a/accounts/url_test.go b/accounts/url_test.go
index 802772871..bd6f35fa2 100644
--- a/accounts/url_test.go
+++ b/accounts/url_test.go
@@ -1,4 +1,4 @@
-// Copyright 2017 The go-ethereum Authors
+// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
diff --git a/accounts/usbwallet/hub.go b/accounts/usbwallet/hub.go
index 6b76aea04..05eed80a5 100644
--- a/accounts/usbwallet/hub.go
+++ b/accounts/usbwallet/hub.go
@@ -20,12 +20,13 @@ import (
"errors"
"runtime"
"sync"
+ "sync/atomic"
"time"
+ "github.com/karalabe/usb"
"github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/event"
"github.com/truechain/truechain-engineering-code/log"
- "github.com/karalabe/hid"
)
// LedgerScheme is the protocol scheme prefixing account and wallet URLs.
@@ -64,21 +65,41 @@ type Hub struct {
// TODO(karalabe): remove if hotplug lands on Windows
commsPend int // Number of operations blocking enumeration
commsLock sync.Mutex // Lock protecting the pending counter and enumeration
+ enumFails uint32 // Number of times enumeration has failed
}
// NewLedgerHub creates a new hardware wallet manager for Ledger devices.
func NewLedgerHub() (*Hub, error) {
- return newHub(LedgerScheme, 0x2c97, []uint16{0x0000 /* Ledger Blue */, 0x0001 /* Ledger Nano S */}, 0xffa0, 0, newLedgerDriver)
+ return newHub(LedgerScheme, 0x2c97, []uint16{
+ // Original product IDs
+ 0x0000, /* Ledger Blue */
+ 0x0001, /* Ledger Nano S */
+ 0x0004, /* Ledger Nano X */
+
+ // Upcoming product IDs: https://www.ledger.com/2019/05/17/windows-10-update-sunsetting-u2f-tunnel-transport-for-ledger-devices/
+ 0x0015, /* HID + U2F + WebUSB Ledger Blue */
+ 0x1015, /* HID + U2F + WebUSB Ledger Nano S */
+ 0x4015, /* HID + U2F + WebUSB Ledger Nano X */
+ 0x0011, /* HID + WebUSB Ledger Blue */
+ 0x1011, /* HID + WebUSB Ledger Nano S */
+ 0x4011, /* HID + WebUSB Ledger Nano X */
+ }, 0xffa0, 0, newLedgerDriver)
}
-// NewTrezorHub creates a new hardware wallet manager for Trezor devices.
-func NewTrezorHub() (*Hub, error) {
- return newHub(TrezorScheme, 0x534c, []uint16{0x0001 /* Trezor 1 */}, 0xff00, 0, newTrezorDriver)
+// NewTrezorHubWithHID creates a new hardware wallet manager for Trezor devices.
+func NewTrezorHubWithHID() (*Hub, error) {
+ return newHub(TrezorScheme, 0x534c, []uint16{0x0001 /* Trezor HID */}, 0xff00, 0, newTrezorDriver)
+}
+
+// NewTrezorHubWithWebUSB creates a new hardware wallet manager for Trezor devices with
+// firmware version > 1.8.0
+func NewTrezorHubWithWebUSB() (*Hub, error) {
+ return newHub(TrezorScheme, 0x1209, []uint16{0x53c1 /* Trezor WebUSB */}, 0xffff /* No usage id on webusb, don't match unset (0) */, 0, newTrezorDriver)
}
// newHub creates a new hardware wallet manager for generic USB devices.
func newHub(scheme string, vendorID uint16, productIDs []uint16, usageID uint16, endpointID int, makeDriver func(log.Logger) driver) (*Hub, error) {
- if !hid.Supported() {
+ if !usb.Supported() {
return nil, errors.New("unsupported platform")
}
hub := &Hub{
@@ -119,8 +140,12 @@ func (hub *Hub) refreshWallets() {
if elapsed < refreshThrottling {
return
}
+ // If USB enumeration is continually failing, don't keep trying indefinitely
+ if atomic.LoadUint32(&hub.enumFails) > 2 {
+ return
+ }
// Retrieve the current list of USB wallet devices
- var devices []hid.DeviceInfo
+ var devices []usb.DeviceInfo
if runtime.GOOS == "linux" {
// hidapi on Linux opens the device during enumeration to retrieve some infos,
@@ -135,8 +160,22 @@ func (hub *Hub) refreshWallets() {
return
}
}
- for _, info := range hid.Enumerate(hub.vendorID, 0) {
+ infos, err := usb.Enumerate(hub.vendorID, 0)
+ if err != nil {
+ failcount := atomic.AddUint32(&hub.enumFails, 1)
+ if runtime.GOOS == "linux" {
+ // See rationale before the enumeration why this is needed and only on Linux.
+ hub.commsLock.Unlock()
+ }
+ log.Error("Failed to enumerate USB devices", "hub", hub.scheme,
+ "vendor", hub.vendorID, "failcount", failcount, "err", err)
+ return
+ }
+ atomic.StoreUint32(&hub.enumFails, 0)
+
+ for _, info := range infos {
for _, id := range hub.productIDs {
+ // Windows and Macos use UsageID matching, Linux uses Interface matching
if info.ProductID == id && (info.UsagePage == hub.usageID || info.Interface == hub.endpointID) {
devices = append(devices, info)
break
@@ -150,8 +189,10 @@ func (hub *Hub) refreshWallets() {
// Transform the current list of wallets into the new one
hub.stateLock.Lock()
- wallets := make([]accounts.Wallet, 0, len(devices))
- events := []accounts.WalletEvent{}
+ var (
+ wallets = make([]accounts.Wallet, 0, len(devices))
+ events []accounts.WalletEvent
+ )
for _, device := range devices {
url := accounts.URL{Scheme: hub.scheme, Path: device.Path}
diff --git a/accounts/usbwallet/internal/trezor/messages.pb.go b/accounts/usbwallet/internal/trezor/messages.pb.go
deleted file mode 100644
index 15bb6fb73..000000000
--- a/accounts/usbwallet/internal/trezor/messages.pb.go
+++ /dev/null
@@ -1,3081 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: messages.proto
-
-package trezor
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// *
-// Mapping between Trezor wire identifier (uint) and a protobuf message
-type MessageType int32
-
-const (
- MessageType_MessageType_Initialize MessageType = 0
- MessageType_MessageType_Ping MessageType = 1
- MessageType_MessageType_Success MessageType = 2
- MessageType_MessageType_Failure MessageType = 3
- MessageType_MessageType_ChangePin MessageType = 4
- MessageType_MessageType_WipeDevice MessageType = 5
- MessageType_MessageType_FirmwareErase MessageType = 6
- MessageType_MessageType_FirmwareUpload MessageType = 7
- MessageType_MessageType_FirmwareRequest MessageType = 8
- MessageType_MessageType_GetEntropy MessageType = 9
- MessageType_MessageType_Entropy MessageType = 10
- MessageType_MessageType_GetPublicKey MessageType = 11
- MessageType_MessageType_PublicKey MessageType = 12
- MessageType_MessageType_LoadDevice MessageType = 13
- MessageType_MessageType_ResetDevice MessageType = 14
- MessageType_MessageType_SignTx MessageType = 15
- MessageType_MessageType_SimpleSignTx MessageType = 16
- MessageType_MessageType_Features MessageType = 17
- MessageType_MessageType_PinMatrixRequest MessageType = 18
- MessageType_MessageType_PinMatrixAck MessageType = 19
- MessageType_MessageType_Cancel MessageType = 20
- MessageType_MessageType_TxRequest MessageType = 21
- MessageType_MessageType_TxAck MessageType = 22
- MessageType_MessageType_CipherKeyValue MessageType = 23
- MessageType_MessageType_ClearSession MessageType = 24
- MessageType_MessageType_ApplySettings MessageType = 25
- MessageType_MessageType_ButtonRequest MessageType = 26
- MessageType_MessageType_ButtonAck MessageType = 27
- MessageType_MessageType_ApplyFlags MessageType = 28
- MessageType_MessageType_GetAddress MessageType = 29
- MessageType_MessageType_Address MessageType = 30
- MessageType_MessageType_SelfTest MessageType = 32
- MessageType_MessageType_BackupDevice MessageType = 34
- MessageType_MessageType_EntropyRequest MessageType = 35
- MessageType_MessageType_EntropyAck MessageType = 36
- MessageType_MessageType_SignMessage MessageType = 38
- MessageType_MessageType_VerifyMessage MessageType = 39
- MessageType_MessageType_MessageSignature MessageType = 40
- MessageType_MessageType_PassphraseRequest MessageType = 41
- MessageType_MessageType_PassphraseAck MessageType = 42
- MessageType_MessageType_EstimateTxSize MessageType = 43
- MessageType_MessageType_TxSize MessageType = 44
- MessageType_MessageType_RecoveryDevice MessageType = 45
- MessageType_MessageType_WordRequest MessageType = 46
- MessageType_MessageType_WordAck MessageType = 47
- MessageType_MessageType_CipheredKeyValue MessageType = 48
- MessageType_MessageType_EncryptMessage MessageType = 49
- MessageType_MessageType_EncryptedMessage MessageType = 50
- MessageType_MessageType_DecryptMessage MessageType = 51
- MessageType_MessageType_DecryptedMessage MessageType = 52
- MessageType_MessageType_SignIdentity MessageType = 53
- MessageType_MessageType_SignedIdentity MessageType = 54
- MessageType_MessageType_GetFeatures MessageType = 55
- MessageType_MessageType_EthereumGetAddress MessageType = 56
- MessageType_MessageType_EthereumAddress MessageType = 57
- MessageType_MessageType_EthereumSignTx MessageType = 58
- MessageType_MessageType_EthereumTxRequest MessageType = 59
- MessageType_MessageType_EthereumTxAck MessageType = 60
- MessageType_MessageType_GetECDHSessionKey MessageType = 61
- MessageType_MessageType_ECDHSessionKey MessageType = 62
- MessageType_MessageType_SetU2FCounter MessageType = 63
- MessageType_MessageType_EthereumSignMessage MessageType = 64
- MessageType_MessageType_EthereumVerifyMessage MessageType = 65
- MessageType_MessageType_EthereumMessageSignature MessageType = 66
- MessageType_MessageType_DebugLinkDecision MessageType = 100
- MessageType_MessageType_DebugLinkGetState MessageType = 101
- MessageType_MessageType_DebugLinkState MessageType = 102
- MessageType_MessageType_DebugLinkStop MessageType = 103
- MessageType_MessageType_DebugLinkLog MessageType = 104
- MessageType_MessageType_DebugLinkMemoryRead MessageType = 110
- MessageType_MessageType_DebugLinkMemory MessageType = 111
- MessageType_MessageType_DebugLinkMemoryWrite MessageType = 112
- MessageType_MessageType_DebugLinkFlashErase MessageType = 113
-)
-
-var MessageType_name = map[int32]string{
- 0: "MessageType_Initialize",
- 1: "MessageType_Ping",
- 2: "MessageType_Success",
- 3: "MessageType_Failure",
- 4: "MessageType_ChangePin",
- 5: "MessageType_WipeDevice",
- 6: "MessageType_FirmwareErase",
- 7: "MessageType_FirmwareUpload",
- 8: "MessageType_FirmwareRequest",
- 9: "MessageType_GetEntropy",
- 10: "MessageType_Entropy",
- 11: "MessageType_GetPublicKey",
- 12: "MessageType_PublicKey",
- 13: "MessageType_LoadDevice",
- 14: "MessageType_ResetDevice",
- 15: "MessageType_SignTx",
- 16: "MessageType_SimpleSignTx",
- 17: "MessageType_Features",
- 18: "MessageType_PinMatrixRequest",
- 19: "MessageType_PinMatrixAck",
- 20: "MessageType_Cancel",
- 21: "MessageType_TxRequest",
- 22: "MessageType_TxAck",
- 23: "MessageType_CipherKeyValue",
- 24: "MessageType_ClearSession",
- 25: "MessageType_ApplySettings",
- 26: "MessageType_ButtonRequest",
- 27: "MessageType_ButtonAck",
- 28: "MessageType_ApplyFlags",
- 29: "MessageType_GetAddress",
- 30: "MessageType_Address",
- 32: "MessageType_SelfTest",
- 34: "MessageType_BackupDevice",
- 35: "MessageType_EntropyRequest",
- 36: "MessageType_EntropyAck",
- 38: "MessageType_SignMessage",
- 39: "MessageType_VerifyMessage",
- 40: "MessageType_MessageSignature",
- 41: "MessageType_PassphraseRequest",
- 42: "MessageType_PassphraseAck",
- 43: "MessageType_EstimateTxSize",
- 44: "MessageType_TxSize",
- 45: "MessageType_RecoveryDevice",
- 46: "MessageType_WordRequest",
- 47: "MessageType_WordAck",
- 48: "MessageType_CipheredKeyValue",
- 49: "MessageType_EncryptMessage",
- 50: "MessageType_EncryptedMessage",
- 51: "MessageType_DecryptMessage",
- 52: "MessageType_DecryptedMessage",
- 53: "MessageType_SignIdentity",
- 54: "MessageType_SignedIdentity",
- 55: "MessageType_GetFeatures",
- 56: "MessageType_EthereumGetAddress",
- 57: "MessageType_EthereumAddress",
- 58: "MessageType_EthereumSignTx",
- 59: "MessageType_EthereumTxRequest",
- 60: "MessageType_EthereumTxAck",
- 61: "MessageType_GetECDHSessionKey",
- 62: "MessageType_ECDHSessionKey",
- 63: "MessageType_SetU2FCounter",
- 64: "MessageType_EthereumSignMessage",
- 65: "MessageType_EthereumVerifyMessage",
- 66: "MessageType_EthereumMessageSignature",
- 100: "MessageType_DebugLinkDecision",
- 101: "MessageType_DebugLinkGetState",
- 102: "MessageType_DebugLinkState",
- 103: "MessageType_DebugLinkStop",
- 104: "MessageType_DebugLinkLog",
- 110: "MessageType_DebugLinkMemoryRead",
- 111: "MessageType_DebugLinkMemory",
- 112: "MessageType_DebugLinkMemoryWrite",
- 113: "MessageType_DebugLinkFlashErase",
-}
-var MessageType_value = map[string]int32{
- "MessageType_Initialize": 0,
- "MessageType_Ping": 1,
- "MessageType_Success": 2,
- "MessageType_Failure": 3,
- "MessageType_ChangePin": 4,
- "MessageType_WipeDevice": 5,
- "MessageType_FirmwareErase": 6,
- "MessageType_FirmwareUpload": 7,
- "MessageType_FirmwareRequest": 8,
- "MessageType_GetEntropy": 9,
- "MessageType_Entropy": 10,
- "MessageType_GetPublicKey": 11,
- "MessageType_PublicKey": 12,
- "MessageType_LoadDevice": 13,
- "MessageType_ResetDevice": 14,
- "MessageType_SignTx": 15,
- "MessageType_SimpleSignTx": 16,
- "MessageType_Features": 17,
- "MessageType_PinMatrixRequest": 18,
- "MessageType_PinMatrixAck": 19,
- "MessageType_Cancel": 20,
- "MessageType_TxRequest": 21,
- "MessageType_TxAck": 22,
- "MessageType_CipherKeyValue": 23,
- "MessageType_ClearSession": 24,
- "MessageType_ApplySettings": 25,
- "MessageType_ButtonRequest": 26,
- "MessageType_ButtonAck": 27,
- "MessageType_ApplyFlags": 28,
- "MessageType_GetAddress": 29,
- "MessageType_Address": 30,
- "MessageType_SelfTest": 32,
- "MessageType_BackupDevice": 34,
- "MessageType_EntropyRequest": 35,
- "MessageType_EntropyAck": 36,
- "MessageType_SignMessage": 38,
- "MessageType_VerifyMessage": 39,
- "MessageType_MessageSignature": 40,
- "MessageType_PassphraseRequest": 41,
- "MessageType_PassphraseAck": 42,
- "MessageType_EstimateTxSize": 43,
- "MessageType_TxSize": 44,
- "MessageType_RecoveryDevice": 45,
- "MessageType_WordRequest": 46,
- "MessageType_WordAck": 47,
- "MessageType_CipheredKeyValue": 48,
- "MessageType_EncryptMessage": 49,
- "MessageType_EncryptedMessage": 50,
- "MessageType_DecryptMessage": 51,
- "MessageType_DecryptedMessage": 52,
- "MessageType_SignIdentity": 53,
- "MessageType_SignedIdentity": 54,
- "MessageType_GetFeatures": 55,
- "MessageType_EthereumGetAddress": 56,
- "MessageType_EthereumAddress": 57,
- "MessageType_EthereumSignTx": 58,
- "MessageType_EthereumTxRequest": 59,
- "MessageType_EthereumTxAck": 60,
- "MessageType_GetECDHSessionKey": 61,
- "MessageType_ECDHSessionKey": 62,
- "MessageType_SetU2FCounter": 63,
- "MessageType_EthereumSignMessage": 64,
- "MessageType_EthereumVerifyMessage": 65,
- "MessageType_EthereumMessageSignature": 66,
- "MessageType_DebugLinkDecision": 100,
- "MessageType_DebugLinkGetState": 101,
- "MessageType_DebugLinkState": 102,
- "MessageType_DebugLinkStop": 103,
- "MessageType_DebugLinkLog": 104,
- "MessageType_DebugLinkMemoryRead": 110,
- "MessageType_DebugLinkMemory": 111,
- "MessageType_DebugLinkMemoryWrite": 112,
- "MessageType_DebugLinkFlashErase": 113,
-}
-
-func (x MessageType) Enum() *MessageType {
- p := new(MessageType)
- *p = x
- return p
-}
-func (x MessageType) String() string {
- return proto.EnumName(MessageType_name, int32(x))
-}
-func (x *MessageType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(MessageType_value, data, "MessageType")
- if err != nil {
- return err
- }
- *x = MessageType(value)
- return nil
-}
-func (MessageType) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
-
-// *
-// Request: Reset device to default state and ask for device details
-// @next Features
-type Initialize struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Initialize) Reset() { *m = Initialize{} }
-func (m *Initialize) String() string { return proto.CompactTextString(m) }
-func (*Initialize) ProtoMessage() {}
-func (*Initialize) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
-
-// *
-// Request: Ask for device details (no device reset)
-// @next Features
-type GetFeatures struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GetFeatures) Reset() { *m = GetFeatures{} }
-func (m *GetFeatures) String() string { return proto.CompactTextString(m) }
-func (*GetFeatures) ProtoMessage() {}
-func (*GetFeatures) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
-
-// *
-// Response: Reports various information about the device
-// @prev Initialize
-// @prev GetFeatures
-type Features struct {
- Vendor *string `protobuf:"bytes,1,opt,name=vendor" json:"vendor,omitempty"`
- MajorVersion *uint32 `protobuf:"varint,2,opt,name=major_version,json=majorVersion" json:"major_version,omitempty"`
- MinorVersion *uint32 `protobuf:"varint,3,opt,name=minor_version,json=minorVersion" json:"minor_version,omitempty"`
- PatchVersion *uint32 `protobuf:"varint,4,opt,name=patch_version,json=patchVersion" json:"patch_version,omitempty"`
- BootloaderMode *bool `protobuf:"varint,5,opt,name=bootloader_mode,json=bootloaderMode" json:"bootloader_mode,omitempty"`
- DeviceId *string `protobuf:"bytes,6,opt,name=device_id,json=deviceId" json:"device_id,omitempty"`
- PinProtection *bool `protobuf:"varint,7,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
- PassphraseProtection *bool `protobuf:"varint,8,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
- Language *string `protobuf:"bytes,9,opt,name=language" json:"language,omitempty"`
- Label *string `protobuf:"bytes,10,opt,name=label" json:"label,omitempty"`
- Coins []*CoinType `protobuf:"bytes,11,rep,name=coins" json:"coins,omitempty"`
- Initialized *bool `protobuf:"varint,12,opt,name=initialized" json:"initialized,omitempty"`
- Revision []byte `protobuf:"bytes,13,opt,name=revision" json:"revision,omitempty"`
- BootloaderHash []byte `protobuf:"bytes,14,opt,name=bootloader_hash,json=bootloaderHash" json:"bootloader_hash,omitempty"`
- Imported *bool `protobuf:"varint,15,opt,name=imported" json:"imported,omitempty"`
- PinCached *bool `protobuf:"varint,16,opt,name=pin_cached,json=pinCached" json:"pin_cached,omitempty"`
- PassphraseCached *bool `protobuf:"varint,17,opt,name=passphrase_cached,json=passphraseCached" json:"passphrase_cached,omitempty"`
- FirmwarePresent *bool `protobuf:"varint,18,opt,name=firmware_present,json=firmwarePresent" json:"firmware_present,omitempty"`
- NeedsBackup *bool `protobuf:"varint,19,opt,name=needs_backup,json=needsBackup" json:"needs_backup,omitempty"`
- Flags *uint32 `protobuf:"varint,20,opt,name=flags" json:"flags,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Features) Reset() { *m = Features{} }
-func (m *Features) String() string { return proto.CompactTextString(m) }
-func (*Features) ProtoMessage() {}
-func (*Features) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
-
-func (m *Features) GetVendor() string {
- if m != nil && m.Vendor != nil {
- return *m.Vendor
- }
- return ""
-}
-
-func (m *Features) GetMajorVersion() uint32 {
- if m != nil && m.MajorVersion != nil {
- return *m.MajorVersion
- }
- return 0
-}
-
-func (m *Features) GetMinorVersion() uint32 {
- if m != nil && m.MinorVersion != nil {
- return *m.MinorVersion
- }
- return 0
-}
-
-func (m *Features) GetPatchVersion() uint32 {
- if m != nil && m.PatchVersion != nil {
- return *m.PatchVersion
- }
- return 0
-}
-
-func (m *Features) GetBootloaderMode() bool {
- if m != nil && m.BootloaderMode != nil {
- return *m.BootloaderMode
- }
- return false
-}
-
-func (m *Features) GetDeviceId() string {
- if m != nil && m.DeviceId != nil {
- return *m.DeviceId
- }
- return ""
-}
-
-func (m *Features) GetPinProtection() bool {
- if m != nil && m.PinProtection != nil {
- return *m.PinProtection
- }
- return false
-}
-
-func (m *Features) GetPassphraseProtection() bool {
- if m != nil && m.PassphraseProtection != nil {
- return *m.PassphraseProtection
- }
- return false
-}
-
-func (m *Features) GetLanguage() string {
- if m != nil && m.Language != nil {
- return *m.Language
- }
- return ""
-}
-
-func (m *Features) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *Features) GetCoins() []*CoinType {
- if m != nil {
- return m.Coins
- }
- return nil
-}
-
-func (m *Features) GetInitialized() bool {
- if m != nil && m.Initialized != nil {
- return *m.Initialized
- }
- return false
-}
-
-func (m *Features) GetRevision() []byte {
- if m != nil {
- return m.Revision
- }
- return nil
-}
-
-func (m *Features) GetBootloaderHash() []byte {
- if m != nil {
- return m.BootloaderHash
- }
- return nil
-}
-
-func (m *Features) GetImported() bool {
- if m != nil && m.Imported != nil {
- return *m.Imported
- }
- return false
-}
-
-func (m *Features) GetPinCached() bool {
- if m != nil && m.PinCached != nil {
- return *m.PinCached
- }
- return false
-}
-
-func (m *Features) GetPassphraseCached() bool {
- if m != nil && m.PassphraseCached != nil {
- return *m.PassphraseCached
- }
- return false
-}
-
-func (m *Features) GetFirmwarePresent() bool {
- if m != nil && m.FirmwarePresent != nil {
- return *m.FirmwarePresent
- }
- return false
-}
-
-func (m *Features) GetNeedsBackup() bool {
- if m != nil && m.NeedsBackup != nil {
- return *m.NeedsBackup
- }
- return false
-}
-
-func (m *Features) GetFlags() uint32 {
- if m != nil && m.Flags != nil {
- return *m.Flags
- }
- return 0
-}
-
-// *
-// Request: clear session (removes cached PIN, passphrase, etc).
-// @next Success
-type ClearSession struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ClearSession) Reset() { *m = ClearSession{} }
-func (m *ClearSession) String() string { return proto.CompactTextString(m) }
-func (*ClearSession) ProtoMessage() {}
-func (*ClearSession) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} }
-
-// *
-// Request: change language and/or label of the device
-// @next Success
-// @next Failure
-// @next ButtonRequest
-// @next PinMatrixRequest
-type ApplySettings struct {
- Language *string `protobuf:"bytes,1,opt,name=language" json:"language,omitempty"`
- Label *string `protobuf:"bytes,2,opt,name=label" json:"label,omitempty"`
- UsePassphrase *bool `protobuf:"varint,3,opt,name=use_passphrase,json=usePassphrase" json:"use_passphrase,omitempty"`
- Homescreen []byte `protobuf:"bytes,4,opt,name=homescreen" json:"homescreen,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ApplySettings) Reset() { *m = ApplySettings{} }
-func (m *ApplySettings) String() string { return proto.CompactTextString(m) }
-func (*ApplySettings) ProtoMessage() {}
-func (*ApplySettings) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} }
-
-func (m *ApplySettings) GetLanguage() string {
- if m != nil && m.Language != nil {
- return *m.Language
- }
- return ""
-}
-
-func (m *ApplySettings) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *ApplySettings) GetUsePassphrase() bool {
- if m != nil && m.UsePassphrase != nil {
- return *m.UsePassphrase
- }
- return false
-}
-
-func (m *ApplySettings) GetHomescreen() []byte {
- if m != nil {
- return m.Homescreen
- }
- return nil
-}
-
-// *
-// Request: set flags of the device
-// @next Success
-// @next Failure
-type ApplyFlags struct {
- Flags *uint32 `protobuf:"varint,1,opt,name=flags" json:"flags,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ApplyFlags) Reset() { *m = ApplyFlags{} }
-func (m *ApplyFlags) String() string { return proto.CompactTextString(m) }
-func (*ApplyFlags) ProtoMessage() {}
-func (*ApplyFlags) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} }
-
-func (m *ApplyFlags) GetFlags() uint32 {
- if m != nil && m.Flags != nil {
- return *m.Flags
- }
- return 0
-}
-
-// *
-// Request: Starts workflow for setting/changing/removing the PIN
-// @next ButtonRequest
-// @next PinMatrixRequest
-type ChangePin struct {
- Remove *bool `protobuf:"varint,1,opt,name=remove" json:"remove,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ChangePin) Reset() { *m = ChangePin{} }
-func (m *ChangePin) String() string { return proto.CompactTextString(m) }
-func (*ChangePin) ProtoMessage() {}
-func (*ChangePin) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} }
-
-func (m *ChangePin) GetRemove() bool {
- if m != nil && m.Remove != nil {
- return *m.Remove
- }
- return false
-}
-
-// *
-// Request: Test if the device is alive, device sends back the message in Success response
-// @next Success
-type Ping struct {
- Message *string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
- ButtonProtection *bool `protobuf:"varint,2,opt,name=button_protection,json=buttonProtection" json:"button_protection,omitempty"`
- PinProtection *bool `protobuf:"varint,3,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
- PassphraseProtection *bool `protobuf:"varint,4,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Ping) Reset() { *m = Ping{} }
-func (m *Ping) String() string { return proto.CompactTextString(m) }
-func (*Ping) ProtoMessage() {}
-func (*Ping) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} }
-
-func (m *Ping) GetMessage() string {
- if m != nil && m.Message != nil {
- return *m.Message
- }
- return ""
-}
-
-func (m *Ping) GetButtonProtection() bool {
- if m != nil && m.ButtonProtection != nil {
- return *m.ButtonProtection
- }
- return false
-}
-
-func (m *Ping) GetPinProtection() bool {
- if m != nil && m.PinProtection != nil {
- return *m.PinProtection
- }
- return false
-}
-
-func (m *Ping) GetPassphraseProtection() bool {
- if m != nil && m.PassphraseProtection != nil {
- return *m.PassphraseProtection
- }
- return false
-}
-
-// *
-// Response: Success of the previous request
-type Success struct {
- Message *string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Success) Reset() { *m = Success{} }
-func (m *Success) String() string { return proto.CompactTextString(m) }
-func (*Success) ProtoMessage() {}
-func (*Success) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} }
-
-func (m *Success) GetMessage() string {
- if m != nil && m.Message != nil {
- return *m.Message
- }
- return ""
-}
-
-// *
-// Response: Failure of the previous request
-type Failure struct {
- Code *FailureType `protobuf:"varint,1,opt,name=code,enum=FailureType" json:"code,omitempty"`
- Message *string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Failure) Reset() { *m = Failure{} }
-func (m *Failure) String() string { return proto.CompactTextString(m) }
-func (*Failure) ProtoMessage() {}
-func (*Failure) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{9} }
-
-func (m *Failure) GetCode() FailureType {
- if m != nil && m.Code != nil {
- return *m.Code
- }
- return FailureType_Failure_UnexpectedMessage
-}
-
-func (m *Failure) GetMessage() string {
- if m != nil && m.Message != nil {
- return *m.Message
- }
- return ""
-}
-
-// *
-// Response: Device is waiting for HW button press.
-// @next ButtonAck
-// @next Cancel
-type ButtonRequest struct {
- Code *ButtonRequestType `protobuf:"varint,1,opt,name=code,enum=ButtonRequestType" json:"code,omitempty"`
- Data *string `protobuf:"bytes,2,opt,name=data" json:"data,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ButtonRequest) Reset() { *m = ButtonRequest{} }
-func (m *ButtonRequest) String() string { return proto.CompactTextString(m) }
-func (*ButtonRequest) ProtoMessage() {}
-func (*ButtonRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{10} }
-
-func (m *ButtonRequest) GetCode() ButtonRequestType {
- if m != nil && m.Code != nil {
- return *m.Code
- }
- return ButtonRequestType_ButtonRequest_Other
-}
-
-func (m *ButtonRequest) GetData() string {
- if m != nil && m.Data != nil {
- return *m.Data
- }
- return ""
-}
-
-// *
-// Request: Computer agrees to wait for HW button press
-// @prev ButtonRequest
-type ButtonAck struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ButtonAck) Reset() { *m = ButtonAck{} }
-func (m *ButtonAck) String() string { return proto.CompactTextString(m) }
-func (*ButtonAck) ProtoMessage() {}
-func (*ButtonAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{11} }
-
-// *
-// Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
-// @next PinMatrixAck
-// @next Cancel
-type PinMatrixRequest struct {
- Type *PinMatrixRequestType `protobuf:"varint,1,opt,name=type,enum=PinMatrixRequestType" json:"type,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PinMatrixRequest) Reset() { *m = PinMatrixRequest{} }
-func (m *PinMatrixRequest) String() string { return proto.CompactTextString(m) }
-func (*PinMatrixRequest) ProtoMessage() {}
-func (*PinMatrixRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{12} }
-
-func (m *PinMatrixRequest) GetType() PinMatrixRequestType {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return PinMatrixRequestType_PinMatrixRequestType_Current
-}
-
-// *
-// Request: Computer responds with encoded PIN
-// @prev PinMatrixRequest
-type PinMatrixAck struct {
- Pin *string `protobuf:"bytes,1,req,name=pin" json:"pin,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PinMatrixAck) Reset() { *m = PinMatrixAck{} }
-func (m *PinMatrixAck) String() string { return proto.CompactTextString(m) }
-func (*PinMatrixAck) ProtoMessage() {}
-func (*PinMatrixAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{13} }
-
-func (m *PinMatrixAck) GetPin() string {
- if m != nil && m.Pin != nil {
- return *m.Pin
- }
- return ""
-}
-
-// *
-// Request: Abort last operation that required user interaction
-// @prev ButtonRequest
-// @prev PinMatrixRequest
-// @prev PassphraseRequest
-type Cancel struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Cancel) Reset() { *m = Cancel{} }
-func (m *Cancel) String() string { return proto.CompactTextString(m) }
-func (*Cancel) ProtoMessage() {}
-func (*Cancel) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{14} }
-
-// *
-// Response: Device awaits encryption passphrase
-// @next PassphraseAck
-// @next Cancel
-type PassphraseRequest struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PassphraseRequest) Reset() { *m = PassphraseRequest{} }
-func (m *PassphraseRequest) String() string { return proto.CompactTextString(m) }
-func (*PassphraseRequest) ProtoMessage() {}
-func (*PassphraseRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{15} }
-
-// *
-// Request: Send passphrase back
-// @prev PassphraseRequest
-type PassphraseAck struct {
- Passphrase *string `protobuf:"bytes,1,req,name=passphrase" json:"passphrase,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PassphraseAck) Reset() { *m = PassphraseAck{} }
-func (m *PassphraseAck) String() string { return proto.CompactTextString(m) }
-func (*PassphraseAck) ProtoMessage() {}
-func (*PassphraseAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{16} }
-
-func (m *PassphraseAck) GetPassphrase() string {
- if m != nil && m.Passphrase != nil {
- return *m.Passphrase
- }
- return ""
-}
-
-// *
-// Request: Request a sample of random data generated by hardware RNG. May be used for testing.
-// @next ButtonRequest
-// @next Entropy
-// @next Failure
-type GetEntropy struct {
- Size *uint32 `protobuf:"varint,1,req,name=size" json:"size,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GetEntropy) Reset() { *m = GetEntropy{} }
-func (m *GetEntropy) String() string { return proto.CompactTextString(m) }
-func (*GetEntropy) ProtoMessage() {}
-func (*GetEntropy) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{17} }
-
-func (m *GetEntropy) GetSize() uint32 {
- if m != nil && m.Size != nil {
- return *m.Size
- }
- return 0
-}
-
-// *
-// Response: Reply with random data generated by internal RNG
-// @prev GetEntropy
-type Entropy struct {
- Entropy []byte `protobuf:"bytes,1,req,name=entropy" json:"entropy,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Entropy) Reset() { *m = Entropy{} }
-func (m *Entropy) String() string { return proto.CompactTextString(m) }
-func (*Entropy) ProtoMessage() {}
-func (*Entropy) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{18} }
-
-func (m *Entropy) GetEntropy() []byte {
- if m != nil {
- return m.Entropy
- }
- return nil
-}
-
-// *
-// Request: Ask device for public key corresponding to address_n path
-// @next PassphraseRequest
-// @next PublicKey
-// @next Failure
-type GetPublicKey struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- EcdsaCurveName *string `protobuf:"bytes,2,opt,name=ecdsa_curve_name,json=ecdsaCurveName" json:"ecdsa_curve_name,omitempty"`
- ShowDisplay *bool `protobuf:"varint,3,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
- CoinName *string `protobuf:"bytes,4,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GetPublicKey) Reset() { *m = GetPublicKey{} }
-func (m *GetPublicKey) String() string { return proto.CompactTextString(m) }
-func (*GetPublicKey) ProtoMessage() {}
-func (*GetPublicKey) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{19} }
-
-const Default_GetPublicKey_CoinName string = "Bitcoin"
-
-func (m *GetPublicKey) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *GetPublicKey) GetEcdsaCurveName() string {
- if m != nil && m.EcdsaCurveName != nil {
- return *m.EcdsaCurveName
- }
- return ""
-}
-
-func (m *GetPublicKey) GetShowDisplay() bool {
- if m != nil && m.ShowDisplay != nil {
- return *m.ShowDisplay
- }
- return false
-}
-
-func (m *GetPublicKey) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_GetPublicKey_CoinName
-}
-
-// *
-// Response: Contains public key derived from device private seed
-// @prev GetPublicKey
-type PublicKey struct {
- Node *HDNodeType `protobuf:"bytes,1,req,name=node" json:"node,omitempty"`
- Xpub *string `protobuf:"bytes,2,opt,name=xpub" json:"xpub,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PublicKey) Reset() { *m = PublicKey{} }
-func (m *PublicKey) String() string { return proto.CompactTextString(m) }
-func (*PublicKey) ProtoMessage() {}
-func (*PublicKey) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{20} }
-
-func (m *PublicKey) GetNode() *HDNodeType {
- if m != nil {
- return m.Node
- }
- return nil
-}
-
-func (m *PublicKey) GetXpub() string {
- if m != nil && m.Xpub != nil {
- return *m.Xpub
- }
- return ""
-}
-
-// *
-// Request: Ask device for address corresponding to address_n path
-// @next PassphraseRequest
-// @next Address
-// @next Failure
-type GetAddress struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- CoinName *string `protobuf:"bytes,2,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- ShowDisplay *bool `protobuf:"varint,3,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
- Multisig *MultisigRedeemScriptType `protobuf:"bytes,4,opt,name=multisig" json:"multisig,omitempty"`
- ScriptType *InputScriptType `protobuf:"varint,5,opt,name=script_type,json=scriptType,enum=InputScriptType,def=0" json:"script_type,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GetAddress) Reset() { *m = GetAddress{} }
-func (m *GetAddress) String() string { return proto.CompactTextString(m) }
-func (*GetAddress) ProtoMessage() {}
-func (*GetAddress) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{21} }
-
-const Default_GetAddress_CoinName string = "Bitcoin"
-const Default_GetAddress_ScriptType InputScriptType = InputScriptType_SPENDADDRESS
-
-func (m *GetAddress) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *GetAddress) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_GetAddress_CoinName
-}
-
-func (m *GetAddress) GetShowDisplay() bool {
- if m != nil && m.ShowDisplay != nil {
- return *m.ShowDisplay
- }
- return false
-}
-
-func (m *GetAddress) GetMultisig() *MultisigRedeemScriptType {
- if m != nil {
- return m.Multisig
- }
- return nil
-}
-
-func (m *GetAddress) GetScriptType() InputScriptType {
- if m != nil && m.ScriptType != nil {
- return *m.ScriptType
- }
- return Default_GetAddress_ScriptType
-}
-
-// *
-// Request: Ask device for Ethereum address corresponding to address_n path
-// @next PassphraseRequest
-// @next EthereumAddress
-// @next Failure
-type EthereumGetAddress struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- ShowDisplay *bool `protobuf:"varint,2,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumGetAddress) Reset() { *m = EthereumGetAddress{} }
-func (m *EthereumGetAddress) String() string { return proto.CompactTextString(m) }
-func (*EthereumGetAddress) ProtoMessage() {}
-func (*EthereumGetAddress) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{22} }
-
-func (m *EthereumGetAddress) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *EthereumGetAddress) GetShowDisplay() bool {
- if m != nil && m.ShowDisplay != nil {
- return *m.ShowDisplay
- }
- return false
-}
-
-// *
-// Response: Contains address derived from device private seed
-// @prev GetAddress
-type Address struct {
- Address *string `protobuf:"bytes,1,req,name=address" json:"address,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Address) Reset() { *m = Address{} }
-func (m *Address) String() string { return proto.CompactTextString(m) }
-func (*Address) ProtoMessage() {}
-func (*Address) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{23} }
-
-func (m *Address) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-// *
-// Response: Contains an Ethereum address derived from device private seed
-// @prev EthereumGetAddress
-type EthereumAddress struct {
- Address []byte `protobuf:"bytes,1,req,name=address" json:"address,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumAddress) Reset() { *m = EthereumAddress{} }
-func (m *EthereumAddress) String() string { return proto.CompactTextString(m) }
-func (*EthereumAddress) ProtoMessage() {}
-func (*EthereumAddress) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{24} }
-
-func (m *EthereumAddress) GetAddress() []byte {
- if m != nil {
- return m.Address
- }
- return nil
-}
-
-// *
-// Request: Request device to wipe all sensitive data and settings
-// @next ButtonRequest
-type WipeDevice struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *WipeDevice) Reset() { *m = WipeDevice{} }
-func (m *WipeDevice) String() string { return proto.CompactTextString(m) }
-func (*WipeDevice) ProtoMessage() {}
-func (*WipeDevice) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{25} }
-
-// *
-// Request: Load seed and related internal settings from the computer
-// @next ButtonRequest
-// @next Success
-// @next Failure
-type LoadDevice struct {
- Mnemonic *string `protobuf:"bytes,1,opt,name=mnemonic" json:"mnemonic,omitempty"`
- Node *HDNodeType `protobuf:"bytes,2,opt,name=node" json:"node,omitempty"`
- Pin *string `protobuf:"bytes,3,opt,name=pin" json:"pin,omitempty"`
- PassphraseProtection *bool `protobuf:"varint,4,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
- Language *string `protobuf:"bytes,5,opt,name=language,def=english" json:"language,omitempty"`
- Label *string `protobuf:"bytes,6,opt,name=label" json:"label,omitempty"`
- SkipChecksum *bool `protobuf:"varint,7,opt,name=skip_checksum,json=skipChecksum" json:"skip_checksum,omitempty"`
- U2FCounter *uint32 `protobuf:"varint,8,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *LoadDevice) Reset() { *m = LoadDevice{} }
-func (m *LoadDevice) String() string { return proto.CompactTextString(m) }
-func (*LoadDevice) ProtoMessage() {}
-func (*LoadDevice) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{26} }
-
-const Default_LoadDevice_Language string = "english"
-
-func (m *LoadDevice) GetMnemonic() string {
- if m != nil && m.Mnemonic != nil {
- return *m.Mnemonic
- }
- return ""
-}
-
-func (m *LoadDevice) GetNode() *HDNodeType {
- if m != nil {
- return m.Node
- }
- return nil
-}
-
-func (m *LoadDevice) GetPin() string {
- if m != nil && m.Pin != nil {
- return *m.Pin
- }
- return ""
-}
-
-func (m *LoadDevice) GetPassphraseProtection() bool {
- if m != nil && m.PassphraseProtection != nil {
- return *m.PassphraseProtection
- }
- return false
-}
-
-func (m *LoadDevice) GetLanguage() string {
- if m != nil && m.Language != nil {
- return *m.Language
- }
- return Default_LoadDevice_Language
-}
-
-func (m *LoadDevice) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *LoadDevice) GetSkipChecksum() bool {
- if m != nil && m.SkipChecksum != nil {
- return *m.SkipChecksum
- }
- return false
-}
-
-func (m *LoadDevice) GetU2FCounter() uint32 {
- if m != nil && m.U2FCounter != nil {
- return *m.U2FCounter
- }
- return 0
-}
-
-// *
-// Request: Ask device to do initialization involving user interaction
-// @next EntropyRequest
-// @next Failure
-type ResetDevice struct {
- DisplayRandom *bool `protobuf:"varint,1,opt,name=display_random,json=displayRandom" json:"display_random,omitempty"`
- Strength *uint32 `protobuf:"varint,2,opt,name=strength,def=256" json:"strength,omitempty"`
- PassphraseProtection *bool `protobuf:"varint,3,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
- PinProtection *bool `protobuf:"varint,4,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
- Language *string `protobuf:"bytes,5,opt,name=language,def=english" json:"language,omitempty"`
- Label *string `protobuf:"bytes,6,opt,name=label" json:"label,omitempty"`
- U2FCounter *uint32 `protobuf:"varint,7,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
- SkipBackup *bool `protobuf:"varint,8,opt,name=skip_backup,json=skipBackup" json:"skip_backup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ResetDevice) Reset() { *m = ResetDevice{} }
-func (m *ResetDevice) String() string { return proto.CompactTextString(m) }
-func (*ResetDevice) ProtoMessage() {}
-func (*ResetDevice) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{27} }
-
-const Default_ResetDevice_Strength uint32 = 256
-const Default_ResetDevice_Language string = "english"
-
-func (m *ResetDevice) GetDisplayRandom() bool {
- if m != nil && m.DisplayRandom != nil {
- return *m.DisplayRandom
- }
- return false
-}
-
-func (m *ResetDevice) GetStrength() uint32 {
- if m != nil && m.Strength != nil {
- return *m.Strength
- }
- return Default_ResetDevice_Strength
-}
-
-func (m *ResetDevice) GetPassphraseProtection() bool {
- if m != nil && m.PassphraseProtection != nil {
- return *m.PassphraseProtection
- }
- return false
-}
-
-func (m *ResetDevice) GetPinProtection() bool {
- if m != nil && m.PinProtection != nil {
- return *m.PinProtection
- }
- return false
-}
-
-func (m *ResetDevice) GetLanguage() string {
- if m != nil && m.Language != nil {
- return *m.Language
- }
- return Default_ResetDevice_Language
-}
-
-func (m *ResetDevice) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *ResetDevice) GetU2FCounter() uint32 {
- if m != nil && m.U2FCounter != nil {
- return *m.U2FCounter
- }
- return 0
-}
-
-func (m *ResetDevice) GetSkipBackup() bool {
- if m != nil && m.SkipBackup != nil {
- return *m.SkipBackup
- }
- return false
-}
-
-// *
-// Request: Perform backup of the device seed if not backed up using ResetDevice
-// @next ButtonRequest
-type BackupDevice struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *BackupDevice) Reset() { *m = BackupDevice{} }
-func (m *BackupDevice) String() string { return proto.CompactTextString(m) }
-func (*BackupDevice) ProtoMessage() {}
-func (*BackupDevice) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{28} }
-
-// *
-// Response: Ask for additional entropy from host computer
-// @prev ResetDevice
-// @next EntropyAck
-type EntropyRequest struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EntropyRequest) Reset() { *m = EntropyRequest{} }
-func (m *EntropyRequest) String() string { return proto.CompactTextString(m) }
-func (*EntropyRequest) ProtoMessage() {}
-func (*EntropyRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{29} }
-
-// *
-// Request: Provide additional entropy for seed generation function
-// @prev EntropyRequest
-// @next ButtonRequest
-type EntropyAck struct {
- Entropy []byte `protobuf:"bytes,1,opt,name=entropy" json:"entropy,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EntropyAck) Reset() { *m = EntropyAck{} }
-func (m *EntropyAck) String() string { return proto.CompactTextString(m) }
-func (*EntropyAck) ProtoMessage() {}
-func (*EntropyAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{30} }
-
-func (m *EntropyAck) GetEntropy() []byte {
- if m != nil {
- return m.Entropy
- }
- return nil
-}
-
-// *
-// Request: Start recovery workflow asking user for specific words of mnemonic
-// Used to recovery device safely even on untrusted computer.
-// @next WordRequest
-type RecoveryDevice struct {
- WordCount *uint32 `protobuf:"varint,1,opt,name=word_count,json=wordCount" json:"word_count,omitempty"`
- PassphraseProtection *bool `protobuf:"varint,2,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
- PinProtection *bool `protobuf:"varint,3,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
- Language *string `protobuf:"bytes,4,opt,name=language,def=english" json:"language,omitempty"`
- Label *string `protobuf:"bytes,5,opt,name=label" json:"label,omitempty"`
- EnforceWordlist *bool `protobuf:"varint,6,opt,name=enforce_wordlist,json=enforceWordlist" json:"enforce_wordlist,omitempty"`
- // 7 reserved for unused recovery method
- Type *uint32 `protobuf:"varint,8,opt,name=type" json:"type,omitempty"`
- U2FCounter *uint32 `protobuf:"varint,9,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
- DryRun *bool `protobuf:"varint,10,opt,name=dry_run,json=dryRun" json:"dry_run,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *RecoveryDevice) Reset() { *m = RecoveryDevice{} }
-func (m *RecoveryDevice) String() string { return proto.CompactTextString(m) }
-func (*RecoveryDevice) ProtoMessage() {}
-func (*RecoveryDevice) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{31} }
-
-const Default_RecoveryDevice_Language string = "english"
-
-func (m *RecoveryDevice) GetWordCount() uint32 {
- if m != nil && m.WordCount != nil {
- return *m.WordCount
- }
- return 0
-}
-
-func (m *RecoveryDevice) GetPassphraseProtection() bool {
- if m != nil && m.PassphraseProtection != nil {
- return *m.PassphraseProtection
- }
- return false
-}
-
-func (m *RecoveryDevice) GetPinProtection() bool {
- if m != nil && m.PinProtection != nil {
- return *m.PinProtection
- }
- return false
-}
-
-func (m *RecoveryDevice) GetLanguage() string {
- if m != nil && m.Language != nil {
- return *m.Language
- }
- return Default_RecoveryDevice_Language
-}
-
-func (m *RecoveryDevice) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *RecoveryDevice) GetEnforceWordlist() bool {
- if m != nil && m.EnforceWordlist != nil {
- return *m.EnforceWordlist
- }
- return false
-}
-
-func (m *RecoveryDevice) GetType() uint32 {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return 0
-}
-
-func (m *RecoveryDevice) GetU2FCounter() uint32 {
- if m != nil && m.U2FCounter != nil {
- return *m.U2FCounter
- }
- return 0
-}
-
-func (m *RecoveryDevice) GetDryRun() bool {
- if m != nil && m.DryRun != nil {
- return *m.DryRun
- }
- return false
-}
-
-// *
-// Response: Device is waiting for user to enter word of the mnemonic
-// Its position is shown only on device's internal display.
-// @prev RecoveryDevice
-// @prev WordAck
-type WordRequest struct {
- Type *WordRequestType `protobuf:"varint,1,opt,name=type,enum=WordRequestType" json:"type,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *WordRequest) Reset() { *m = WordRequest{} }
-func (m *WordRequest) String() string { return proto.CompactTextString(m) }
-func (*WordRequest) ProtoMessage() {}
-func (*WordRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{32} }
-
-func (m *WordRequest) GetType() WordRequestType {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return WordRequestType_WordRequestType_Plain
-}
-
-// *
-// Request: Computer replies with word from the mnemonic
-// @prev WordRequest
-// @next WordRequest
-// @next Success
-// @next Failure
-type WordAck struct {
- Word *string `protobuf:"bytes,1,req,name=word" json:"word,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *WordAck) Reset() { *m = WordAck{} }
-func (m *WordAck) String() string { return proto.CompactTextString(m) }
-func (*WordAck) ProtoMessage() {}
-func (*WordAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{33} }
-
-func (m *WordAck) GetWord() string {
- if m != nil && m.Word != nil {
- return *m.Word
- }
- return ""
-}
-
-// *
-// Request: Ask device to sign message
-// @next MessageSignature
-// @next Failure
-type SignMessage struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- Message []byte `protobuf:"bytes,2,req,name=message" json:"message,omitempty"`
- CoinName *string `protobuf:"bytes,3,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- ScriptType *InputScriptType `protobuf:"varint,4,opt,name=script_type,json=scriptType,enum=InputScriptType,def=0" json:"script_type,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SignMessage) Reset() { *m = SignMessage{} }
-func (m *SignMessage) String() string { return proto.CompactTextString(m) }
-func (*SignMessage) ProtoMessage() {}
-func (*SignMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{34} }
-
-const Default_SignMessage_CoinName string = "Bitcoin"
-const Default_SignMessage_ScriptType InputScriptType = InputScriptType_SPENDADDRESS
-
-func (m *SignMessage) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *SignMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-func (m *SignMessage) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_SignMessage_CoinName
-}
-
-func (m *SignMessage) GetScriptType() InputScriptType {
- if m != nil && m.ScriptType != nil {
- return *m.ScriptType
- }
- return Default_SignMessage_ScriptType
-}
-
-// *
-// Request: Ask device to verify message
-// @next Success
-// @next Failure
-type VerifyMessage struct {
- Address *string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
- Message []byte `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"`
- CoinName *string `protobuf:"bytes,4,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *VerifyMessage) Reset() { *m = VerifyMessage{} }
-func (m *VerifyMessage) String() string { return proto.CompactTextString(m) }
-func (*VerifyMessage) ProtoMessage() {}
-func (*VerifyMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{35} }
-
-const Default_VerifyMessage_CoinName string = "Bitcoin"
-
-func (m *VerifyMessage) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-func (m *VerifyMessage) GetSignature() []byte {
- if m != nil {
- return m.Signature
- }
- return nil
-}
-
-func (m *VerifyMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-func (m *VerifyMessage) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_VerifyMessage_CoinName
-}
-
-// *
-// Response: Signed message
-// @prev SignMessage
-type MessageSignature struct {
- Address *string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageSignature) Reset() { *m = MessageSignature{} }
-func (m *MessageSignature) String() string { return proto.CompactTextString(m) }
-func (*MessageSignature) ProtoMessage() {}
-func (*MessageSignature) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{36} }
-
-func (m *MessageSignature) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-func (m *MessageSignature) GetSignature() []byte {
- if m != nil {
- return m.Signature
- }
- return nil
-}
-
-// *
-// Request: Ask device to encrypt message
-// @next EncryptedMessage
-// @next Failure
-type EncryptMessage struct {
- Pubkey []byte `protobuf:"bytes,1,opt,name=pubkey" json:"pubkey,omitempty"`
- Message []byte `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
- DisplayOnly *bool `protobuf:"varint,3,opt,name=display_only,json=displayOnly" json:"display_only,omitempty"`
- AddressN []uint32 `protobuf:"varint,4,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- CoinName *string `protobuf:"bytes,5,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EncryptMessage) Reset() { *m = EncryptMessage{} }
-func (m *EncryptMessage) String() string { return proto.CompactTextString(m) }
-func (*EncryptMessage) ProtoMessage() {}
-func (*EncryptMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{37} }
-
-const Default_EncryptMessage_CoinName string = "Bitcoin"
-
-func (m *EncryptMessage) GetPubkey() []byte {
- if m != nil {
- return m.Pubkey
- }
- return nil
-}
-
-func (m *EncryptMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-func (m *EncryptMessage) GetDisplayOnly() bool {
- if m != nil && m.DisplayOnly != nil {
- return *m.DisplayOnly
- }
- return false
-}
-
-func (m *EncryptMessage) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *EncryptMessage) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_EncryptMessage_CoinName
-}
-
-// *
-// Response: Encrypted message
-// @prev EncryptMessage
-type EncryptedMessage struct {
- Nonce []byte `protobuf:"bytes,1,opt,name=nonce" json:"nonce,omitempty"`
- Message []byte `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
- Hmac []byte `protobuf:"bytes,3,opt,name=hmac" json:"hmac,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EncryptedMessage) Reset() { *m = EncryptedMessage{} }
-func (m *EncryptedMessage) String() string { return proto.CompactTextString(m) }
-func (*EncryptedMessage) ProtoMessage() {}
-func (*EncryptedMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{38} }
-
-func (m *EncryptedMessage) GetNonce() []byte {
- if m != nil {
- return m.Nonce
- }
- return nil
-}
-
-func (m *EncryptedMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-func (m *EncryptedMessage) GetHmac() []byte {
- if m != nil {
- return m.Hmac
- }
- return nil
-}
-
-// *
-// Request: Ask device to decrypt message
-// @next Success
-// @next Failure
-type DecryptMessage struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- Nonce []byte `protobuf:"bytes,2,opt,name=nonce" json:"nonce,omitempty"`
- Message []byte `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"`
- Hmac []byte `protobuf:"bytes,4,opt,name=hmac" json:"hmac,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DecryptMessage) Reset() { *m = DecryptMessage{} }
-func (m *DecryptMessage) String() string { return proto.CompactTextString(m) }
-func (*DecryptMessage) ProtoMessage() {}
-func (*DecryptMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{39} }
-
-func (m *DecryptMessage) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *DecryptMessage) GetNonce() []byte {
- if m != nil {
- return m.Nonce
- }
- return nil
-}
-
-func (m *DecryptMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-func (m *DecryptMessage) GetHmac() []byte {
- if m != nil {
- return m.Hmac
- }
- return nil
-}
-
-// *
-// Response: Decrypted message
-// @prev DecryptedMessage
-type DecryptedMessage struct {
- Message []byte `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
- Address *string `protobuf:"bytes,2,opt,name=address" json:"address,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DecryptedMessage) Reset() { *m = DecryptedMessage{} }
-func (m *DecryptedMessage) String() string { return proto.CompactTextString(m) }
-func (*DecryptedMessage) ProtoMessage() {}
-func (*DecryptedMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{40} }
-
-func (m *DecryptedMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-func (m *DecryptedMessage) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-// *
-// Request: Ask device to encrypt or decrypt value of given key
-// @next CipheredKeyValue
-// @next Failure
-type CipherKeyValue struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- Key *string `protobuf:"bytes,2,opt,name=key" json:"key,omitempty"`
- Value []byte `protobuf:"bytes,3,opt,name=value" json:"value,omitempty"`
- Encrypt *bool `protobuf:"varint,4,opt,name=encrypt" json:"encrypt,omitempty"`
- AskOnEncrypt *bool `protobuf:"varint,5,opt,name=ask_on_encrypt,json=askOnEncrypt" json:"ask_on_encrypt,omitempty"`
- AskOnDecrypt *bool `protobuf:"varint,6,opt,name=ask_on_decrypt,json=askOnDecrypt" json:"ask_on_decrypt,omitempty"`
- Iv []byte `protobuf:"bytes,7,opt,name=iv" json:"iv,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CipherKeyValue) Reset() { *m = CipherKeyValue{} }
-func (m *CipherKeyValue) String() string { return proto.CompactTextString(m) }
-func (*CipherKeyValue) ProtoMessage() {}
-func (*CipherKeyValue) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{41} }
-
-func (m *CipherKeyValue) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *CipherKeyValue) GetKey() string {
- if m != nil && m.Key != nil {
- return *m.Key
- }
- return ""
-}
-
-func (m *CipherKeyValue) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *CipherKeyValue) GetEncrypt() bool {
- if m != nil && m.Encrypt != nil {
- return *m.Encrypt
- }
- return false
-}
-
-func (m *CipherKeyValue) GetAskOnEncrypt() bool {
- if m != nil && m.AskOnEncrypt != nil {
- return *m.AskOnEncrypt
- }
- return false
-}
-
-func (m *CipherKeyValue) GetAskOnDecrypt() bool {
- if m != nil && m.AskOnDecrypt != nil {
- return *m.AskOnDecrypt
- }
- return false
-}
-
-func (m *CipherKeyValue) GetIv() []byte {
- if m != nil {
- return m.Iv
- }
- return nil
-}
-
-// *
-// Response: Return ciphered/deciphered value
-// @prev CipherKeyValue
-type CipheredKeyValue struct {
- Value []byte `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CipheredKeyValue) Reset() { *m = CipheredKeyValue{} }
-func (m *CipheredKeyValue) String() string { return proto.CompactTextString(m) }
-func (*CipheredKeyValue) ProtoMessage() {}
-func (*CipheredKeyValue) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{42} }
-
-func (m *CipheredKeyValue) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-// *
-// Request: Estimated size of the transaction
-// This behaves exactly like SignTx, which means that it can ask using TxRequest
-// This call is non-blocking (except possible PassphraseRequest to unlock the seed)
-// @next TxSize
-// @next Failure
-type EstimateTxSize struct {
- OutputsCount *uint32 `protobuf:"varint,1,req,name=outputs_count,json=outputsCount" json:"outputs_count,omitempty"`
- InputsCount *uint32 `protobuf:"varint,2,req,name=inputs_count,json=inputsCount" json:"inputs_count,omitempty"`
- CoinName *string `protobuf:"bytes,3,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EstimateTxSize) Reset() { *m = EstimateTxSize{} }
-func (m *EstimateTxSize) String() string { return proto.CompactTextString(m) }
-func (*EstimateTxSize) ProtoMessage() {}
-func (*EstimateTxSize) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{43} }
-
-const Default_EstimateTxSize_CoinName string = "Bitcoin"
-
-func (m *EstimateTxSize) GetOutputsCount() uint32 {
- if m != nil && m.OutputsCount != nil {
- return *m.OutputsCount
- }
- return 0
-}
-
-func (m *EstimateTxSize) GetInputsCount() uint32 {
- if m != nil && m.InputsCount != nil {
- return *m.InputsCount
- }
- return 0
-}
-
-func (m *EstimateTxSize) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_EstimateTxSize_CoinName
-}
-
-// *
-// Response: Estimated size of the transaction
-// @prev EstimateTxSize
-type TxSize struct {
- TxSize *uint32 `protobuf:"varint,1,opt,name=tx_size,json=txSize" json:"tx_size,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxSize) Reset() { *m = TxSize{} }
-func (m *TxSize) String() string { return proto.CompactTextString(m) }
-func (*TxSize) ProtoMessage() {}
-func (*TxSize) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{44} }
-
-func (m *TxSize) GetTxSize() uint32 {
- if m != nil && m.TxSize != nil {
- return *m.TxSize
- }
- return 0
-}
-
-// *
-// Request: Ask device to sign transaction
-// @next PassphraseRequest
-// @next PinMatrixRequest
-// @next TxRequest
-// @next Failure
-type SignTx struct {
- OutputsCount *uint32 `protobuf:"varint,1,req,name=outputs_count,json=outputsCount" json:"outputs_count,omitempty"`
- InputsCount *uint32 `protobuf:"varint,2,req,name=inputs_count,json=inputsCount" json:"inputs_count,omitempty"`
- CoinName *string `protobuf:"bytes,3,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- Version *uint32 `protobuf:"varint,4,opt,name=version,def=1" json:"version,omitempty"`
- LockTime *uint32 `protobuf:"varint,5,opt,name=lock_time,json=lockTime,def=0" json:"lock_time,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SignTx) Reset() { *m = SignTx{} }
-func (m *SignTx) String() string { return proto.CompactTextString(m) }
-func (*SignTx) ProtoMessage() {}
-func (*SignTx) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{45} }
-
-const Default_SignTx_CoinName string = "Bitcoin"
-const Default_SignTx_Version uint32 = 1
-const Default_SignTx_LockTime uint32 = 0
-
-func (m *SignTx) GetOutputsCount() uint32 {
- if m != nil && m.OutputsCount != nil {
- return *m.OutputsCount
- }
- return 0
-}
-
-func (m *SignTx) GetInputsCount() uint32 {
- if m != nil && m.InputsCount != nil {
- return *m.InputsCount
- }
- return 0
-}
-
-func (m *SignTx) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_SignTx_CoinName
-}
-
-func (m *SignTx) GetVersion() uint32 {
- if m != nil && m.Version != nil {
- return *m.Version
- }
- return Default_SignTx_Version
-}
-
-func (m *SignTx) GetLockTime() uint32 {
- if m != nil && m.LockTime != nil {
- return *m.LockTime
- }
- return Default_SignTx_LockTime
-}
-
-// *
-// Request: Simplified transaction signing
-// This method doesn't support streaming, so there are hardware limits in number of inputs and outputs.
-// In case of success, the result is returned using TxRequest message.
-// @next PassphraseRequest
-// @next PinMatrixRequest
-// @next TxRequest
-// @next Failure
-type SimpleSignTx struct {
- Inputs []*TxInputType `protobuf:"bytes,1,rep,name=inputs" json:"inputs,omitempty"`
- Outputs []*TxOutputType `protobuf:"bytes,2,rep,name=outputs" json:"outputs,omitempty"`
- Transactions []*TransactionType `protobuf:"bytes,3,rep,name=transactions" json:"transactions,omitempty"`
- CoinName *string `protobuf:"bytes,4,opt,name=coin_name,json=coinName,def=Bitcoin" json:"coin_name,omitempty"`
- Version *uint32 `protobuf:"varint,5,opt,name=version,def=1" json:"version,omitempty"`
- LockTime *uint32 `protobuf:"varint,6,opt,name=lock_time,json=lockTime,def=0" json:"lock_time,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SimpleSignTx) Reset() { *m = SimpleSignTx{} }
-func (m *SimpleSignTx) String() string { return proto.CompactTextString(m) }
-func (*SimpleSignTx) ProtoMessage() {}
-func (*SimpleSignTx) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{46} }
-
-const Default_SimpleSignTx_CoinName string = "Bitcoin"
-const Default_SimpleSignTx_Version uint32 = 1
-const Default_SimpleSignTx_LockTime uint32 = 0
-
-func (m *SimpleSignTx) GetInputs() []*TxInputType {
- if m != nil {
- return m.Inputs
- }
- return nil
-}
-
-func (m *SimpleSignTx) GetOutputs() []*TxOutputType {
- if m != nil {
- return m.Outputs
- }
- return nil
-}
-
-func (m *SimpleSignTx) GetTransactions() []*TransactionType {
- if m != nil {
- return m.Transactions
- }
- return nil
-}
-
-func (m *SimpleSignTx) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return Default_SimpleSignTx_CoinName
-}
-
-func (m *SimpleSignTx) GetVersion() uint32 {
- if m != nil && m.Version != nil {
- return *m.Version
- }
- return Default_SimpleSignTx_Version
-}
-
-func (m *SimpleSignTx) GetLockTime() uint32 {
- if m != nil && m.LockTime != nil {
- return *m.LockTime
- }
- return Default_SimpleSignTx_LockTime
-}
-
-// *
-// Response: Device asks for information for signing transaction or returns the last result
-// If request_index is set, device awaits TxAck message (with fields filled in according to request_type)
-// If signature_index is set, 'signature' contains signed input of signature_index's input
-// @prev SignTx
-// @prev SimpleSignTx
-// @prev TxAck
-type TxRequest struct {
- RequestType *RequestType `protobuf:"varint,1,opt,name=request_type,json=requestType,enum=RequestType" json:"request_type,omitempty"`
- Details *TxRequestDetailsType `protobuf:"bytes,2,opt,name=details" json:"details,omitempty"`
- Serialized *TxRequestSerializedType `protobuf:"bytes,3,opt,name=serialized" json:"serialized,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxRequest) Reset() { *m = TxRequest{} }
-func (m *TxRequest) String() string { return proto.CompactTextString(m) }
-func (*TxRequest) ProtoMessage() {}
-func (*TxRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{47} }
-
-func (m *TxRequest) GetRequestType() RequestType {
- if m != nil && m.RequestType != nil {
- return *m.RequestType
- }
- return RequestType_TXINPUT
-}
-
-func (m *TxRequest) GetDetails() *TxRequestDetailsType {
- if m != nil {
- return m.Details
- }
- return nil
-}
-
-func (m *TxRequest) GetSerialized() *TxRequestSerializedType {
- if m != nil {
- return m.Serialized
- }
- return nil
-}
-
-// *
-// Request: Reported transaction data
-// @prev TxRequest
-// @next TxRequest
-type TxAck struct {
- Tx *TransactionType `protobuf:"bytes,1,opt,name=tx" json:"tx,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxAck) Reset() { *m = TxAck{} }
-func (m *TxAck) String() string { return proto.CompactTextString(m) }
-func (*TxAck) ProtoMessage() {}
-func (*TxAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{48} }
-
-func (m *TxAck) GetTx() *TransactionType {
- if m != nil {
- return m.Tx
- }
- return nil
-}
-
-// *
-// Request: Ask device to sign transaction
-// All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
-// Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
-// @next PassphraseRequest
-// @next PinMatrixRequest
-// @next EthereumTxRequest
-// @next Failure
-type EthereumSignTx struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- Nonce []byte `protobuf:"bytes,2,opt,name=nonce" json:"nonce,omitempty"`
- GasPrice []byte `protobuf:"bytes,3,opt,name=gas_price,json=gasPrice" json:"gas_price,omitempty"`
- GasLimit []byte `protobuf:"bytes,4,opt,name=gas_limit,json=gasLimit" json:"gas_limit,omitempty"`
- To []byte `protobuf:"bytes,5,opt,name=to" json:"to,omitempty"`
- Value []byte `protobuf:"bytes,6,opt,name=value" json:"value,omitempty"`
- DataInitialChunk []byte `protobuf:"bytes,7,opt,name=data_initial_chunk,json=dataInitialChunk" json:"data_initial_chunk,omitempty"`
- DataLength *uint32 `protobuf:"varint,8,opt,name=data_length,json=dataLength" json:"data_length,omitempty"`
- ChainId *uint32 `protobuf:"varint,9,opt,name=chain_id,json=chainId" json:"chain_id,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumSignTx) Reset() { *m = EthereumSignTx{} }
-func (m *EthereumSignTx) String() string { return proto.CompactTextString(m) }
-func (*EthereumSignTx) ProtoMessage() {}
-func (*EthereumSignTx) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{49} }
-
-func (m *EthereumSignTx) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetNonce() []byte {
- if m != nil {
- return m.Nonce
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetGasPrice() []byte {
- if m != nil {
- return m.GasPrice
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetGasLimit() []byte {
- if m != nil {
- return m.GasLimit
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetTo() []byte {
- if m != nil {
- return m.To
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetDataInitialChunk() []byte {
- if m != nil {
- return m.DataInitialChunk
- }
- return nil
-}
-
-func (m *EthereumSignTx) GetDataLength() uint32 {
- if m != nil && m.DataLength != nil {
- return *m.DataLength
- }
- return 0
-}
-
-func (m *EthereumSignTx) GetChainId() uint32 {
- if m != nil && m.ChainId != nil {
- return *m.ChainId
- }
- return 0
-}
-
-// *
-// Response: Device asks for more data from transaction payload, or returns the signature.
-// If data_length is set, device awaits that many more bytes of payload.
-// Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
-// @prev EthereumSignTx
-// @next EthereumTxAck
-type EthereumTxRequest struct {
- DataLength *uint32 `protobuf:"varint,1,opt,name=data_length,json=dataLength" json:"data_length,omitempty"`
- SignatureV *uint32 `protobuf:"varint,2,opt,name=signature_v,json=signatureV" json:"signature_v,omitempty"`
- SignatureR []byte `protobuf:"bytes,3,opt,name=signature_r,json=signatureR" json:"signature_r,omitempty"`
- SignatureS []byte `protobuf:"bytes,4,opt,name=signature_s,json=signatureS" json:"signature_s,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumTxRequest) Reset() { *m = EthereumTxRequest{} }
-func (m *EthereumTxRequest) String() string { return proto.CompactTextString(m) }
-func (*EthereumTxRequest) ProtoMessage() {}
-func (*EthereumTxRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{50} }
-
-func (m *EthereumTxRequest) GetDataLength() uint32 {
- if m != nil && m.DataLength != nil {
- return *m.DataLength
- }
- return 0
-}
-
-func (m *EthereumTxRequest) GetSignatureV() uint32 {
- if m != nil && m.SignatureV != nil {
- return *m.SignatureV
- }
- return 0
-}
-
-func (m *EthereumTxRequest) GetSignatureR() []byte {
- if m != nil {
- return m.SignatureR
- }
- return nil
-}
-
-func (m *EthereumTxRequest) GetSignatureS() []byte {
- if m != nil {
- return m.SignatureS
- }
- return nil
-}
-
-// *
-// Request: Transaction payload data.
-// @prev EthereumTxRequest
-// @next EthereumTxRequest
-type EthereumTxAck struct {
- DataChunk []byte `protobuf:"bytes,1,opt,name=data_chunk,json=dataChunk" json:"data_chunk,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumTxAck) Reset() { *m = EthereumTxAck{} }
-func (m *EthereumTxAck) String() string { return proto.CompactTextString(m) }
-func (*EthereumTxAck) ProtoMessage() {}
-func (*EthereumTxAck) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{51} }
-
-func (m *EthereumTxAck) GetDataChunk() []byte {
- if m != nil {
- return m.DataChunk
- }
- return nil
-}
-
-// *
-// Request: Ask device to sign message
-// @next EthereumMessageSignature
-// @next Failure
-type EthereumSignMessage struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- Message []byte `protobuf:"bytes,2,req,name=message" json:"message,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumSignMessage) Reset() { *m = EthereumSignMessage{} }
-func (m *EthereumSignMessage) String() string { return proto.CompactTextString(m) }
-func (*EthereumSignMessage) ProtoMessage() {}
-func (*EthereumSignMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{52} }
-
-func (m *EthereumSignMessage) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *EthereumSignMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-// *
-// Request: Ask device to verify message
-// @next Success
-// @next Failure
-type EthereumVerifyMessage struct {
- Address []byte `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
- Message []byte `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumVerifyMessage) Reset() { *m = EthereumVerifyMessage{} }
-func (m *EthereumVerifyMessage) String() string { return proto.CompactTextString(m) }
-func (*EthereumVerifyMessage) ProtoMessage() {}
-func (*EthereumVerifyMessage) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{53} }
-
-func (m *EthereumVerifyMessage) GetAddress() []byte {
- if m != nil {
- return m.Address
- }
- return nil
-}
-
-func (m *EthereumVerifyMessage) GetSignature() []byte {
- if m != nil {
- return m.Signature
- }
- return nil
-}
-
-func (m *EthereumVerifyMessage) GetMessage() []byte {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-// *
-// Response: Signed message
-// @prev EthereumSignMessage
-type EthereumMessageSignature struct {
- Address []byte `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *EthereumMessageSignature) Reset() { *m = EthereumMessageSignature{} }
-func (m *EthereumMessageSignature) String() string { return proto.CompactTextString(m) }
-func (*EthereumMessageSignature) ProtoMessage() {}
-func (*EthereumMessageSignature) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{54} }
-
-func (m *EthereumMessageSignature) GetAddress() []byte {
- if m != nil {
- return m.Address
- }
- return nil
-}
-
-func (m *EthereumMessageSignature) GetSignature() []byte {
- if m != nil {
- return m.Signature
- }
- return nil
-}
-
-// *
-// Request: Ask device to sign identity
-// @next SignedIdentity
-// @next Failure
-type SignIdentity struct {
- Identity *IdentityType `protobuf:"bytes,1,opt,name=identity" json:"identity,omitempty"`
- ChallengeHidden []byte `protobuf:"bytes,2,opt,name=challenge_hidden,json=challengeHidden" json:"challenge_hidden,omitempty"`
- ChallengeVisual *string `protobuf:"bytes,3,opt,name=challenge_visual,json=challengeVisual" json:"challenge_visual,omitempty"`
- EcdsaCurveName *string `protobuf:"bytes,4,opt,name=ecdsa_curve_name,json=ecdsaCurveName" json:"ecdsa_curve_name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SignIdentity) Reset() { *m = SignIdentity{} }
-func (m *SignIdentity) String() string { return proto.CompactTextString(m) }
-func (*SignIdentity) ProtoMessage() {}
-func (*SignIdentity) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{55} }
-
-func (m *SignIdentity) GetIdentity() *IdentityType {
- if m != nil {
- return m.Identity
- }
- return nil
-}
-
-func (m *SignIdentity) GetChallengeHidden() []byte {
- if m != nil {
- return m.ChallengeHidden
- }
- return nil
-}
-
-func (m *SignIdentity) GetChallengeVisual() string {
- if m != nil && m.ChallengeVisual != nil {
- return *m.ChallengeVisual
- }
- return ""
-}
-
-func (m *SignIdentity) GetEcdsaCurveName() string {
- if m != nil && m.EcdsaCurveName != nil {
- return *m.EcdsaCurveName
- }
- return ""
-}
-
-// *
-// Response: Device provides signed identity
-// @prev SignIdentity
-type SignedIdentity struct {
- Address *string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- PublicKey []byte `protobuf:"bytes,2,opt,name=public_key,json=publicKey" json:"public_key,omitempty"`
- Signature []byte `protobuf:"bytes,3,opt,name=signature" json:"signature,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SignedIdentity) Reset() { *m = SignedIdentity{} }
-func (m *SignedIdentity) String() string { return proto.CompactTextString(m) }
-func (*SignedIdentity) ProtoMessage() {}
-func (*SignedIdentity) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{56} }
-
-func (m *SignedIdentity) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-func (m *SignedIdentity) GetPublicKey() []byte {
- if m != nil {
- return m.PublicKey
- }
- return nil
-}
-
-func (m *SignedIdentity) GetSignature() []byte {
- if m != nil {
- return m.Signature
- }
- return nil
-}
-
-// *
-// Request: Ask device to generate ECDH session key
-// @next ECDHSessionKey
-// @next Failure
-type GetECDHSessionKey struct {
- Identity *IdentityType `protobuf:"bytes,1,opt,name=identity" json:"identity,omitempty"`
- PeerPublicKey []byte `protobuf:"bytes,2,opt,name=peer_public_key,json=peerPublicKey" json:"peer_public_key,omitempty"`
- EcdsaCurveName *string `protobuf:"bytes,3,opt,name=ecdsa_curve_name,json=ecdsaCurveName" json:"ecdsa_curve_name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GetECDHSessionKey) Reset() { *m = GetECDHSessionKey{} }
-func (m *GetECDHSessionKey) String() string { return proto.CompactTextString(m) }
-func (*GetECDHSessionKey) ProtoMessage() {}
-func (*GetECDHSessionKey) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{57} }
-
-func (m *GetECDHSessionKey) GetIdentity() *IdentityType {
- if m != nil {
- return m.Identity
- }
- return nil
-}
-
-func (m *GetECDHSessionKey) GetPeerPublicKey() []byte {
- if m != nil {
- return m.PeerPublicKey
- }
- return nil
-}
-
-func (m *GetECDHSessionKey) GetEcdsaCurveName() string {
- if m != nil && m.EcdsaCurveName != nil {
- return *m.EcdsaCurveName
- }
- return ""
-}
-
-// *
-// Response: Device provides ECDH session key
-// @prev GetECDHSessionKey
-type ECDHSessionKey struct {
- SessionKey []byte `protobuf:"bytes,1,opt,name=session_key,json=sessionKey" json:"session_key,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ECDHSessionKey) Reset() { *m = ECDHSessionKey{} }
-func (m *ECDHSessionKey) String() string { return proto.CompactTextString(m) }
-func (*ECDHSessionKey) ProtoMessage() {}
-func (*ECDHSessionKey) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{58} }
-
-func (m *ECDHSessionKey) GetSessionKey() []byte {
- if m != nil {
- return m.SessionKey
- }
- return nil
-}
-
-// *
-// Request: Set U2F counter
-// @next Success
-type SetU2FCounter struct {
- U2FCounter *uint32 `protobuf:"varint,1,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SetU2FCounter) Reset() { *m = SetU2FCounter{} }
-func (m *SetU2FCounter) String() string { return proto.CompactTextString(m) }
-func (*SetU2FCounter) ProtoMessage() {}
-func (*SetU2FCounter) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{59} }
-
-func (m *SetU2FCounter) GetU2FCounter() uint32 {
- if m != nil && m.U2FCounter != nil {
- return *m.U2FCounter
- }
- return 0
-}
-
-// *
-// Request: Ask device to erase its firmware (so it can be replaced via FirmwareUpload)
-// @next Success
-// @next FirmwareRequest
-// @next Failure
-type FirmwareErase struct {
- Length *uint32 `protobuf:"varint,1,opt,name=length" json:"length,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *FirmwareErase) Reset() { *m = FirmwareErase{} }
-func (m *FirmwareErase) String() string { return proto.CompactTextString(m) }
-func (*FirmwareErase) ProtoMessage() {}
-func (*FirmwareErase) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{60} }
-
-func (m *FirmwareErase) GetLength() uint32 {
- if m != nil && m.Length != nil {
- return *m.Length
- }
- return 0
-}
-
-// *
-// Response: Ask for firmware chunk
-// @next FirmwareUpload
-type FirmwareRequest struct {
- Offset *uint32 `protobuf:"varint,1,opt,name=offset" json:"offset,omitempty"`
- Length *uint32 `protobuf:"varint,2,opt,name=length" json:"length,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *FirmwareRequest) Reset() { *m = FirmwareRequest{} }
-func (m *FirmwareRequest) String() string { return proto.CompactTextString(m) }
-func (*FirmwareRequest) ProtoMessage() {}
-func (*FirmwareRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{61} }
-
-func (m *FirmwareRequest) GetOffset() uint32 {
- if m != nil && m.Offset != nil {
- return *m.Offset
- }
- return 0
-}
-
-func (m *FirmwareRequest) GetLength() uint32 {
- if m != nil && m.Length != nil {
- return *m.Length
- }
- return 0
-}
-
-// *
-// Request: Send firmware in binary form to the device
-// @next Success
-// @next Failure
-type FirmwareUpload struct {
- Payload []byte `protobuf:"bytes,1,req,name=payload" json:"payload,omitempty"`
- Hash []byte `protobuf:"bytes,2,opt,name=hash" json:"hash,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *FirmwareUpload) Reset() { *m = FirmwareUpload{} }
-func (m *FirmwareUpload) String() string { return proto.CompactTextString(m) }
-func (*FirmwareUpload) ProtoMessage() {}
-func (*FirmwareUpload) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{62} }
-
-func (m *FirmwareUpload) GetPayload() []byte {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func (m *FirmwareUpload) GetHash() []byte {
- if m != nil {
- return m.Hash
- }
- return nil
-}
-
-// *
-// Request: Perform a device self-test
-// @next Success
-// @next Failure
-type SelfTest struct {
- Payload []byte `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SelfTest) Reset() { *m = SelfTest{} }
-func (m *SelfTest) String() string { return proto.CompactTextString(m) }
-func (*SelfTest) ProtoMessage() {}
-func (*SelfTest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{63} }
-
-func (m *SelfTest) GetPayload() []byte {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-// *
-// Request: "Press" the button on the device
-// @next Success
-type DebugLinkDecision struct {
- YesNo *bool `protobuf:"varint,1,req,name=yes_no,json=yesNo" json:"yes_no,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkDecision) Reset() { *m = DebugLinkDecision{} }
-func (m *DebugLinkDecision) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkDecision) ProtoMessage() {}
-func (*DebugLinkDecision) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{64} }
-
-func (m *DebugLinkDecision) GetYesNo() bool {
- if m != nil && m.YesNo != nil {
- return *m.YesNo
- }
- return false
-}
-
-// *
-// Request: Computer asks for device state
-// @next DebugLinkState
-type DebugLinkGetState struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkGetState) Reset() { *m = DebugLinkGetState{} }
-func (m *DebugLinkGetState) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkGetState) ProtoMessage() {}
-func (*DebugLinkGetState) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{65} }
-
-// *
-// Response: Device current state
-// @prev DebugLinkGetState
-type DebugLinkState struct {
- Layout []byte `protobuf:"bytes,1,opt,name=layout" json:"layout,omitempty"`
- Pin *string `protobuf:"bytes,2,opt,name=pin" json:"pin,omitempty"`
- Matrix *string `protobuf:"bytes,3,opt,name=matrix" json:"matrix,omitempty"`
- Mnemonic *string `protobuf:"bytes,4,opt,name=mnemonic" json:"mnemonic,omitempty"`
- Node *HDNodeType `protobuf:"bytes,5,opt,name=node" json:"node,omitempty"`
- PassphraseProtection *bool `protobuf:"varint,6,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
- ResetWord *string `protobuf:"bytes,7,opt,name=reset_word,json=resetWord" json:"reset_word,omitempty"`
- ResetEntropy []byte `protobuf:"bytes,8,opt,name=reset_entropy,json=resetEntropy" json:"reset_entropy,omitempty"`
- RecoveryFakeWord *string `protobuf:"bytes,9,opt,name=recovery_fake_word,json=recoveryFakeWord" json:"recovery_fake_word,omitempty"`
- RecoveryWordPos *uint32 `protobuf:"varint,10,opt,name=recovery_word_pos,json=recoveryWordPos" json:"recovery_word_pos,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkState) Reset() { *m = DebugLinkState{} }
-func (m *DebugLinkState) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkState) ProtoMessage() {}
-func (*DebugLinkState) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{66} }
-
-func (m *DebugLinkState) GetLayout() []byte {
- if m != nil {
- return m.Layout
- }
- return nil
-}
-
-func (m *DebugLinkState) GetPin() string {
- if m != nil && m.Pin != nil {
- return *m.Pin
- }
- return ""
-}
-
-func (m *DebugLinkState) GetMatrix() string {
- if m != nil && m.Matrix != nil {
- return *m.Matrix
- }
- return ""
-}
-
-func (m *DebugLinkState) GetMnemonic() string {
- if m != nil && m.Mnemonic != nil {
- return *m.Mnemonic
- }
- return ""
-}
-
-func (m *DebugLinkState) GetNode() *HDNodeType {
- if m != nil {
- return m.Node
- }
- return nil
-}
-
-func (m *DebugLinkState) GetPassphraseProtection() bool {
- if m != nil && m.PassphraseProtection != nil {
- return *m.PassphraseProtection
- }
- return false
-}
-
-func (m *DebugLinkState) GetResetWord() string {
- if m != nil && m.ResetWord != nil {
- return *m.ResetWord
- }
- return ""
-}
-
-func (m *DebugLinkState) GetResetEntropy() []byte {
- if m != nil {
- return m.ResetEntropy
- }
- return nil
-}
-
-func (m *DebugLinkState) GetRecoveryFakeWord() string {
- if m != nil && m.RecoveryFakeWord != nil {
- return *m.RecoveryFakeWord
- }
- return ""
-}
-
-func (m *DebugLinkState) GetRecoveryWordPos() uint32 {
- if m != nil && m.RecoveryWordPos != nil {
- return *m.RecoveryWordPos
- }
- return 0
-}
-
-// *
-// Request: Ask device to restart
-type DebugLinkStop struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkStop) Reset() { *m = DebugLinkStop{} }
-func (m *DebugLinkStop) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkStop) ProtoMessage() {}
-func (*DebugLinkStop) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{67} }
-
-// *
-// Response: Device wants host to log event
-type DebugLinkLog struct {
- Level *uint32 `protobuf:"varint,1,opt,name=level" json:"level,omitempty"`
- Bucket *string `protobuf:"bytes,2,opt,name=bucket" json:"bucket,omitempty"`
- Text *string `protobuf:"bytes,3,opt,name=text" json:"text,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkLog) Reset() { *m = DebugLinkLog{} }
-func (m *DebugLinkLog) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkLog) ProtoMessage() {}
-func (*DebugLinkLog) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{68} }
-
-func (m *DebugLinkLog) GetLevel() uint32 {
- if m != nil && m.Level != nil {
- return *m.Level
- }
- return 0
-}
-
-func (m *DebugLinkLog) GetBucket() string {
- if m != nil && m.Bucket != nil {
- return *m.Bucket
- }
- return ""
-}
-
-func (m *DebugLinkLog) GetText() string {
- if m != nil && m.Text != nil {
- return *m.Text
- }
- return ""
-}
-
-// *
-// Request: Read memory from device
-// @next DebugLinkMemory
-type DebugLinkMemoryRead struct {
- Address *uint32 `protobuf:"varint,1,opt,name=address" json:"address,omitempty"`
- Length *uint32 `protobuf:"varint,2,opt,name=length" json:"length,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkMemoryRead) Reset() { *m = DebugLinkMemoryRead{} }
-func (m *DebugLinkMemoryRead) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkMemoryRead) ProtoMessage() {}
-func (*DebugLinkMemoryRead) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{69} }
-
-func (m *DebugLinkMemoryRead) GetAddress() uint32 {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return 0
-}
-
-func (m *DebugLinkMemoryRead) GetLength() uint32 {
- if m != nil && m.Length != nil {
- return *m.Length
- }
- return 0
-}
-
-// *
-// Response: Device sends memory back
-// @prev DebugLinkMemoryRead
-type DebugLinkMemory struct {
- Memory []byte `protobuf:"bytes,1,opt,name=memory" json:"memory,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkMemory) Reset() { *m = DebugLinkMemory{} }
-func (m *DebugLinkMemory) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkMemory) ProtoMessage() {}
-func (*DebugLinkMemory) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{70} }
-
-func (m *DebugLinkMemory) GetMemory() []byte {
- if m != nil {
- return m.Memory
- }
- return nil
-}
-
-// *
-// Request: Write memory to device.
-// WARNING: Writing to the wrong location can irreparably break the device.
-type DebugLinkMemoryWrite struct {
- Address *uint32 `protobuf:"varint,1,opt,name=address" json:"address,omitempty"`
- Memory []byte `protobuf:"bytes,2,opt,name=memory" json:"memory,omitempty"`
- Flash *bool `protobuf:"varint,3,opt,name=flash" json:"flash,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkMemoryWrite) Reset() { *m = DebugLinkMemoryWrite{} }
-func (m *DebugLinkMemoryWrite) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkMemoryWrite) ProtoMessage() {}
-func (*DebugLinkMemoryWrite) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{71} }
-
-func (m *DebugLinkMemoryWrite) GetAddress() uint32 {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return 0
-}
-
-func (m *DebugLinkMemoryWrite) GetMemory() []byte {
- if m != nil {
- return m.Memory
- }
- return nil
-}
-
-func (m *DebugLinkMemoryWrite) GetFlash() bool {
- if m != nil && m.Flash != nil {
- return *m.Flash
- }
- return false
-}
-
-// *
-// Request: Erase block of flash on device
-// WARNING: Writing to the wrong location can irreparably break the device.
-type DebugLinkFlashErase struct {
- Sector *uint32 `protobuf:"varint,1,opt,name=sector" json:"sector,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DebugLinkFlashErase) Reset() { *m = DebugLinkFlashErase{} }
-func (m *DebugLinkFlashErase) String() string { return proto.CompactTextString(m) }
-func (*DebugLinkFlashErase) ProtoMessage() {}
-func (*DebugLinkFlashErase) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{72} }
-
-func (m *DebugLinkFlashErase) GetSector() uint32 {
- if m != nil && m.Sector != nil {
- return *m.Sector
- }
- return 0
-}
-
-func init() {
- proto.RegisterType((*Initialize)(nil), "Initialize")
- proto.RegisterType((*GetFeatures)(nil), "GetFeatures")
- proto.RegisterType((*Features)(nil), "Features")
- proto.RegisterType((*ClearSession)(nil), "ClearSession")
- proto.RegisterType((*ApplySettings)(nil), "ApplySettings")
- proto.RegisterType((*ApplyFlags)(nil), "ApplyFlags")
- proto.RegisterType((*ChangePin)(nil), "ChangePin")
- proto.RegisterType((*Ping)(nil), "Ping")
- proto.RegisterType((*Success)(nil), "Success")
- proto.RegisterType((*Failure)(nil), "Failure")
- proto.RegisterType((*ButtonRequest)(nil), "ButtonRequest")
- proto.RegisterType((*ButtonAck)(nil), "ButtonAck")
- proto.RegisterType((*PinMatrixRequest)(nil), "PinMatrixRequest")
- proto.RegisterType((*PinMatrixAck)(nil), "PinMatrixAck")
- proto.RegisterType((*Cancel)(nil), "Cancel")
- proto.RegisterType((*PassphraseRequest)(nil), "PassphraseRequest")
- proto.RegisterType((*PassphraseAck)(nil), "PassphraseAck")
- proto.RegisterType((*GetEntropy)(nil), "GetEntropy")
- proto.RegisterType((*Entropy)(nil), "Entropy")
- proto.RegisterType((*GetPublicKey)(nil), "GetPublicKey")
- proto.RegisterType((*PublicKey)(nil), "PublicKey")
- proto.RegisterType((*GetAddress)(nil), "GetAddress")
- proto.RegisterType((*EthereumGetAddress)(nil), "EthereumGetAddress")
- proto.RegisterType((*Address)(nil), "Address")
- proto.RegisterType((*EthereumAddress)(nil), "EthereumAddress")
- proto.RegisterType((*WipeDevice)(nil), "WipeDevice")
- proto.RegisterType((*LoadDevice)(nil), "LoadDevice")
- proto.RegisterType((*ResetDevice)(nil), "ResetDevice")
- proto.RegisterType((*BackupDevice)(nil), "BackupDevice")
- proto.RegisterType((*EntropyRequest)(nil), "EntropyRequest")
- proto.RegisterType((*EntropyAck)(nil), "EntropyAck")
- proto.RegisterType((*RecoveryDevice)(nil), "RecoveryDevice")
- proto.RegisterType((*WordRequest)(nil), "WordRequest")
- proto.RegisterType((*WordAck)(nil), "WordAck")
- proto.RegisterType((*SignMessage)(nil), "SignMessage")
- proto.RegisterType((*VerifyMessage)(nil), "VerifyMessage")
- proto.RegisterType((*MessageSignature)(nil), "MessageSignature")
- proto.RegisterType((*EncryptMessage)(nil), "EncryptMessage")
- proto.RegisterType((*EncryptedMessage)(nil), "EncryptedMessage")
- proto.RegisterType((*DecryptMessage)(nil), "DecryptMessage")
- proto.RegisterType((*DecryptedMessage)(nil), "DecryptedMessage")
- proto.RegisterType((*CipherKeyValue)(nil), "CipherKeyValue")
- proto.RegisterType((*CipheredKeyValue)(nil), "CipheredKeyValue")
- proto.RegisterType((*EstimateTxSize)(nil), "EstimateTxSize")
- proto.RegisterType((*TxSize)(nil), "TxSize")
- proto.RegisterType((*SignTx)(nil), "SignTx")
- proto.RegisterType((*SimpleSignTx)(nil), "SimpleSignTx")
- proto.RegisterType((*TxRequest)(nil), "TxRequest")
- proto.RegisterType((*TxAck)(nil), "TxAck")
- proto.RegisterType((*EthereumSignTx)(nil), "EthereumSignTx")
- proto.RegisterType((*EthereumTxRequest)(nil), "EthereumTxRequest")
- proto.RegisterType((*EthereumTxAck)(nil), "EthereumTxAck")
- proto.RegisterType((*EthereumSignMessage)(nil), "EthereumSignMessage")
- proto.RegisterType((*EthereumVerifyMessage)(nil), "EthereumVerifyMessage")
- proto.RegisterType((*EthereumMessageSignature)(nil), "EthereumMessageSignature")
- proto.RegisterType((*SignIdentity)(nil), "SignIdentity")
- proto.RegisterType((*SignedIdentity)(nil), "SignedIdentity")
- proto.RegisterType((*GetECDHSessionKey)(nil), "GetECDHSessionKey")
- proto.RegisterType((*ECDHSessionKey)(nil), "ECDHSessionKey")
- proto.RegisterType((*SetU2FCounter)(nil), "SetU2FCounter")
- proto.RegisterType((*FirmwareErase)(nil), "FirmwareErase")
- proto.RegisterType((*FirmwareRequest)(nil), "FirmwareRequest")
- proto.RegisterType((*FirmwareUpload)(nil), "FirmwareUpload")
- proto.RegisterType((*SelfTest)(nil), "SelfTest")
- proto.RegisterType((*DebugLinkDecision)(nil), "DebugLinkDecision")
- proto.RegisterType((*DebugLinkGetState)(nil), "DebugLinkGetState")
- proto.RegisterType((*DebugLinkState)(nil), "DebugLinkState")
- proto.RegisterType((*DebugLinkStop)(nil), "DebugLinkStop")
- proto.RegisterType((*DebugLinkLog)(nil), "DebugLinkLog")
- proto.RegisterType((*DebugLinkMemoryRead)(nil), "DebugLinkMemoryRead")
- proto.RegisterType((*DebugLinkMemory)(nil), "DebugLinkMemory")
- proto.RegisterType((*DebugLinkMemoryWrite)(nil), "DebugLinkMemoryWrite")
- proto.RegisterType((*DebugLinkFlashErase)(nil), "DebugLinkFlashErase")
- proto.RegisterEnum("MessageType", MessageType_name, MessageType_value)
-}
-
-func init() { proto.RegisterFile("messages.proto", fileDescriptor1) }
-
-var fileDescriptor1 = []byte{
- // 3424 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x5a, 0xcb, 0x6f, 0xdc, 0x46,
- 0x9a, 0x5f, 0x76, 0xb7, 0xfa, 0xf1, 0x35, 0xbb, 0x55, 0xa2, 0x2d, 0xbb, 0x2d, 0x5b, 0xb6, 0x4c,
- 0xc9, 0xb6, 0x64, 0x27, 0xed, 0x44, 0x79, 0x6c, 0xd6, 0xbb, 0x79, 0xc8, 0x7a, 0xd8, 0xde, 0xd8,
- 0x8e, 0xc0, 0x56, 0x9c, 0xdb, 0x12, 0x14, 0x59, 0xea, 0xae, 0x55, 0x37, 0xc9, 0xf0, 0xa1, 0xa8,
- 0x7d, 0xd8, 0xeb, 0xee, 0x65, 0x81, 0xec, 0x69, 0x73, 0x1a, 0xe4, 0x36, 0x19, 0x04, 0x18, 0x0c,
- 0x30, 0x18, 0x60, 0x72, 0x9a, 0x3f, 0x60, 0xfe, 0x8b, 0x39, 0xce, 0x1f, 0x30, 0xe7, 0x41, 0x3d,
- 0x48, 0x16, 0x29, 0xb6, 0x6c, 0x27, 0xc0, 0x5c, 0x04, 0xd6, 0x57, 0xbf, 0xfe, 0xea, 0x7b, 0xd5,
- 0x57, 0x5f, 0x7d, 0x25, 0xe8, 0x4e, 0x70, 0x18, 0x5a, 0x43, 0x1c, 0xf6, 0xfd, 0xc0, 0x8b, 0xbc,
- 0xa5, 0x76, 0x34, 0xf5, 0x93, 0x81, 0xae, 0x02, 0x3c, 0x71, 0x49, 0x44, 0xac, 0x31, 0x79, 0x89,
- 0xf5, 0x0e, 0xb4, 0x1f, 0xe1, 0x68, 0x0f, 0x5b, 0x51, 0x1c, 0xe0, 0x50, 0xff, 0x69, 0x0e, 0x9a,
- 0xc9, 0x40, 0xbb, 0x04, 0xf5, 0x13, 0xec, 0x3a, 0x5e, 0xd0, 0x53, 0x56, 0x94, 0xf5, 0x96, 0x21,
- 0x46, 0xda, 0x2a, 0x74, 0x26, 0xd6, 0x7f, 0x7a, 0x81, 0x79, 0x82, 0x83, 0x90, 0x78, 0x6e, 0xaf,
- 0xb2, 0xa2, 0xac, 0x77, 0x0c, 0x95, 0x11, 0x5f, 0x70, 0x1a, 0x03, 0x11, 0x57, 0x02, 0x55, 0x05,
- 0x88, 0x12, 0x25, 0x90, 0x6f, 0x45, 0xf6, 0x28, 0x05, 0xd5, 0x38, 0x88, 0x11, 0x13, 0xd0, 0x1d,
- 0x98, 0x3f, 0xf4, 0xbc, 0x68, 0xec, 0x59, 0x0e, 0x0e, 0xcc, 0x89, 0xe7, 0xe0, 0xde, 0xdc, 0x8a,
- 0xb2, 0xde, 0x34, 0xba, 0x19, 0xf9, 0x99, 0xe7, 0x60, 0xed, 0x2a, 0xb4, 0x1c, 0x7c, 0x42, 0x6c,
- 0x6c, 0x12, 0xa7, 0x57, 0x67, 0x22, 0x37, 0x39, 0xe1, 0x89, 0xa3, 0xdd, 0x82, 0xae, 0x4f, 0x5c,
- 0x93, 0xda, 0x00, 0xdb, 0x11, 0x5d, 0xab, 0xc1, 0x98, 0x74, 0x7c, 0xe2, 0xee, 0xa7, 0x44, 0xed,
- 0x3d, 0x58, 0xf4, 0xad, 0x30, 0xf4, 0x47, 0x81, 0x15, 0x62, 0x19, 0xdd, 0x64, 0xe8, 0x8b, 0xd9,
- 0xa4, 0xf4, 0xa3, 0x25, 0x68, 0x8e, 0x2d, 0x77, 0x18, 0x5b, 0x43, 0xdc, 0x6b, 0xf1, 0x75, 0x93,
- 0xb1, 0x76, 0x11, 0xe6, 0xc6, 0xd6, 0x21, 0x1e, 0xf7, 0x80, 0x4d, 0xf0, 0x81, 0x76, 0x03, 0xe6,
- 0x6c, 0x8f, 0xb8, 0x61, 0xaf, 0xbd, 0x52, 0x5d, 0x6f, 0x6f, 0xb6, 0xfa, 0xdb, 0x1e, 0x71, 0x0f,
- 0xa6, 0x3e, 0x36, 0x38, 0x5d, 0x5b, 0x81, 0x36, 0x49, 0xbd, 0xe4, 0xf4, 0x54, 0xb6, 0xba, 0x4c,
- 0xa2, 0x8b, 0x06, 0xf8, 0x84, 0x30, 0xb3, 0x75, 0x56, 0x94, 0x75, 0xd5, 0x48, 0xc7, 0x05, 0x93,
- 0x8d, 0xac, 0x70, 0xd4, 0xeb, 0x32, 0x88, 0x64, 0xb2, 0xc7, 0x56, 0x38, 0xa2, 0x4c, 0xc8, 0xc4,
- 0xf7, 0x82, 0x08, 0x3b, 0xbd, 0x79, 0xb6, 0x46, 0x3a, 0xd6, 0x96, 0x01, 0xa8, 0xc5, 0x6c, 0xcb,
- 0x1e, 0x61, 0xa7, 0x87, 0xd8, 0x6c, 0xcb, 0x27, 0xee, 0x36, 0x23, 0x68, 0xf7, 0x60, 0x41, 0xb2,
- 0x94, 0x40, 0x2d, 0x30, 0x14, 0xca, 0x26, 0x04, 0x78, 0x03, 0xd0, 0x11, 0x09, 0x26, 0xdf, 0x58,
- 0x01, 0x35, 0x2a, 0x0e, 0xb1, 0x1b, 0xf5, 0x34, 0x86, 0x9d, 0x4f, 0xe8, 0xfb, 0x9c, 0xac, 0xdd,
- 0x04, 0xd5, 0xc5, 0xd8, 0x09, 0xcd, 0x43, 0xcb, 0x3e, 0x8e, 0xfd, 0xde, 0x05, 0xae, 0x3a, 0xa3,
- 0x3d, 0x64, 0x24, 0x6a, 0xd3, 0xa3, 0xb1, 0x35, 0x0c, 0x7b, 0x17, 0x59, 0xb8, 0xf0, 0x81, 0xde,
- 0x05, 0x75, 0x7b, 0x8c, 0xad, 0x60, 0x80, 0x43, 0x6a, 0x04, 0xfd, 0x7f, 0x14, 0xe8, 0x6c, 0xf9,
- 0xfe, 0x78, 0x3a, 0xc0, 0x51, 0x44, 0xdc, 0x61, 0x98, 0xf3, 0x93, 0x32, 0xcb, 0x4f, 0x15, 0xd9,
- 0x4f, 0xb7, 0xa0, 0x1b, 0xd3, 0x38, 0x48, 0xf5, 0x61, 0x61, 0xdc, 0x34, 0x3a, 0x71, 0x88, 0xf7,
- 0x53, 0xa2, 0x76, 0x1d, 0x60, 0xe4, 0x4d, 0x70, 0x68, 0x07, 0x18, 0xf3, 0x20, 0x56, 0x0d, 0x89,
- 0xa2, 0xeb, 0x00, 0x4c, 0x92, 0x3d, 0x2a, 0x68, 0x26, 0xbe, 0x22, 0x8b, 0xbf, 0x0a, 0xad, 0xed,
- 0x91, 0xe5, 0x0e, 0xf1, 0x3e, 0x71, 0xe9, 0xd6, 0x0b, 0xf0, 0xc4, 0x3b, 0xe1, 0x72, 0x36, 0x0d,
- 0x31, 0xd2, 0x7f, 0xa3, 0x40, 0x6d, 0x9f, 0xb8, 0x43, 0xad, 0x07, 0x0d, 0xb1, 0xc9, 0x85, 0x26,
- 0xc9, 0x90, 0xfa, 0xe5, 0x30, 0x8e, 0x22, 0x2f, 0x17, 0xeb, 0x15, 0xee, 0x17, 0x3e, 0x21, 0x45,
- 0xee, 0xd9, 0x5d, 0x51, 0x7d, 0xa3, 0x5d, 0x51, 0x9b, 0xbd, 0x2b, 0xf4, 0x55, 0x68, 0x0c, 0x62,
- 0xdb, 0xc6, 0x61, 0x38, 0x5b, 0x5a, 0x7d, 0x17, 0x1a, 0x7b, 0x16, 0x19, 0xc7, 0x01, 0xd6, 0x56,
- 0xa0, 0x66, 0xd3, 0xcd, 0x4d, 0x11, 0xdd, 0x4d, 0xb5, 0x2f, 0xe8, 0x6c, 0x57, 0xb0, 0x19, 0x99,
- 0x4d, 0x25, 0xcf, 0xe6, 0x73, 0xe8, 0x3c, 0x64, 0xba, 0x19, 0xf8, 0xeb, 0x18, 0x87, 0x91, 0x76,
- 0x3b, 0xc7, 0x4c, 0xeb, 0xe7, 0x66, 0x25, 0x96, 0x1a, 0xd4, 0x1c, 0x2b, 0xb2, 0x04, 0x3f, 0xf6,
- 0xad, 0xb7, 0xa1, 0xc5, 0xe1, 0x5b, 0xf6, 0xb1, 0xfe, 0x31, 0xa0, 0x7d, 0xe2, 0x3e, 0xb3, 0xa2,
- 0x80, 0x9c, 0x26, 0xcc, 0x37, 0xa0, 0x46, 0x33, 0xaa, 0x60, 0xbe, 0xd8, 0x2f, 0x02, 0x38, 0x7f,
- 0x0a, 0xd1, 0x57, 0x40, 0x4d, 0x67, 0xb7, 0xec, 0x63, 0x0d, 0x41, 0xd5, 0x27, 0x6e, 0x4f, 0x59,
- 0xa9, 0xac, 0xb7, 0x0c, 0xfa, 0xa9, 0x37, 0xa1, 0xbe, 0x6d, 0xb9, 0x36, 0x1e, 0xeb, 0x17, 0x60,
- 0x21, 0x8b, 0x29, 0xc1, 0x4a, 0xbf, 0x0f, 0x9d, 0x8c, 0x48, 0x39, 0x5c, 0x07, 0x90, 0xc2, 0x91,
- 0x33, 0x92, 0x28, 0xfa, 0x0a, 0xc0, 0x23, 0x1c, 0xed, 0xba, 0x51, 0xe0, 0xf9, 0x53, 0xaa, 0x5f,
- 0x48, 0x5e, 0x72, 0x5c, 0xc7, 0x60, 0xdf, 0xd4, 0x31, 0xc9, 0x74, 0x0f, 0x1a, 0x98, 0x7f, 0x32,
- 0x84, 0x6a, 0x24, 0x43, 0xfd, 0x57, 0x0a, 0xa8, 0x8f, 0x70, 0xb4, 0x1f, 0x1f, 0x8e, 0x89, 0xfd,
- 0x39, 0x9e, 0xd2, 0xec, 0x6a, 0x39, 0x4e, 0x80, 0xc3, 0xd0, 0xa4, 0xf2, 0x57, 0xd7, 0x3b, 0x46,
- 0x53, 0x10, 0x9e, 0x6b, 0xeb, 0x80, 0xb0, 0xed, 0x84, 0x96, 0x69, 0xc7, 0xc1, 0x09, 0x36, 0x5d,
- 0x6b, 0x92, 0xb8, 0xa8, 0xcb, 0xe8, 0xdb, 0x94, 0xfc, 0xdc, 0x9a, 0x60, 0xba, 0xbd, 0xc3, 0x91,
- 0xf7, 0x8d, 0xe9, 0x90, 0xd0, 0x1f, 0x5b, 0x53, 0x11, 0x6f, 0x6d, 0x4a, 0xdb, 0xe1, 0x24, 0x6d,
- 0x0d, 0x5a, 0x34, 0x09, 0x72, 0x2e, 0x34, 0xc2, 0x5a, 0x0f, 0x1a, 0x0f, 0x49, 0x44, 0x69, 0x46,
- 0x93, 0xfe, 0xa5, 0x8c, 0xf4, 0xcf, 0xa0, 0x95, 0x09, 0x77, 0x03, 0x6a, 0x2e, 0x77, 0x77, 0x65,
- 0xbd, 0xbd, 0xd9, 0xee, 0x3f, 0xde, 0x79, 0xee, 0x39, 0x22, 0x74, 0x5c, 0xe1, 0xe7, 0x53, 0x3f,
- 0x3e, 0x4c, 0xfc, 0x4c, 0xbf, 0xf5, 0xbf, 0x2a, 0xcc, 0x54, 0x5b, 0x5c, 0x89, 0xf3, 0x15, 0xcc,
- 0xc9, 0x54, 0x99, 0x21, 0xd3, 0xeb, 0x28, 0xf7, 0x01, 0x34, 0x27, 0xf1, 0x38, 0x22, 0x21, 0x19,
- 0x32, 0xdd, 0xda, 0x9b, 0x57, 0xfa, 0xcf, 0x04, 0xc1, 0xc0, 0x0e, 0xc6, 0x93, 0x81, 0x1d, 0x10,
- 0x9f, 0xc7, 0x50, 0x0a, 0xd5, 0x3e, 0x85, 0x76, 0xc8, 0xe8, 0x26, 0x8b, 0xbc, 0x39, 0x16, 0x79,
- 0xa8, 0xff, 0xc4, 0xf5, 0xe3, 0x28, 0xfb, 0xc1, 0x03, 0x75, 0xb0, 0xbf, 0xfb, 0x7c, 0x67, 0x6b,
- 0x67, 0xc7, 0xd8, 0x1d, 0x0c, 0x0c, 0x08, 0xd3, 0x19, 0xfd, 0x00, 0xb4, 0xdd, 0x68, 0x84, 0x03,
- 0x1c, 0x4f, 0x5e, 0x57, 0xe7, 0xa2, 0x36, 0x95, 0x33, 0xda, 0xd0, 0x50, 0x4a, 0x58, 0xf5, 0xa0,
- 0x21, 0x7e, 0x29, 0x82, 0x32, 0x19, 0xea, 0xf7, 0x60, 0x3e, 0x59, 0x7a, 0x06, 0x58, 0xcd, 0xc0,
- 0x2a, 0xc0, 0x57, 0xc4, 0xc7, 0x3b, 0xec, 0xdc, 0xd6, 0xff, 0xaf, 0x02, 0xf0, 0xd4, 0xb3, 0x1c,
- 0x3e, 0xa4, 0x09, 0x7c, 0xe2, 0xe2, 0x89, 0xe7, 0x12, 0x3b, 0x49, 0xe0, 0xc9, 0x38, 0x0d, 0x81,
- 0x0a, 0x33, 0x6a, 0x49, 0x08, 0x88, 0xad, 0x57, 0x65, 0xbf, 0xa3, 0x9f, 0x3f, 0x2b, 0xad, 0x69,
- 0xab, 0xd2, 0x21, 0x32, 0xc7, 0x03, 0x01, 0xbb, 0xc3, 0x31, 0x09, 0x47, 0x65, 0xa7, 0x49, 0x5d,
- 0x3e, 0x4d, 0x56, 0xa1, 0x13, 0x1e, 0x13, 0xdf, 0xb4, 0x47, 0xd8, 0x3e, 0x0e, 0xe3, 0x89, 0x28,
- 0x41, 0x54, 0x4a, 0xdc, 0x16, 0x34, 0xed, 0x06, 0xb4, 0xe3, 0xcd, 0x23, 0xd3, 0xf6, 0x62, 0x37,
- 0xc2, 0x01, 0xab, 0x3b, 0x3a, 0x06, 0xc4, 0x9b, 0x47, 0xdb, 0x9c, 0xa2, 0xff, 0xb6, 0x02, 0x6d,
- 0x03, 0x87, 0x38, 0x12, 0x46, 0xb9, 0x05, 0x5d, 0xe1, 0x21, 0x33, 0xb0, 0x5c, 0xc7, 0x9b, 0x88,
- 0x33, 0xa3, 0x23, 0xa8, 0x06, 0x23, 0x6a, 0x37, 0xa0, 0x19, 0x46, 0x01, 0x76, 0x87, 0xd1, 0x88,
- 0x17, 0x6c, 0x0f, 0xaa, 0x9b, 0x1f, 0x7c, 0x68, 0xa4, 0xc4, 0xd9, 0xd6, 0xa8, 0x9e, 0x63, 0x8d,
- 0xb3, 0x07, 0x48, 0xad, 0xec, 0x00, 0xf9, 0x05, 0x46, 0x2b, 0xd8, 0xa3, 0x51, 0xb4, 0x07, 0x05,
- 0x30, 0xab, 0x8a, 0x7a, 0x81, 0x17, 0x6a, 0x40, 0x49, 0xbc, 0x5c, 0xa0, 0x85, 0x01, 0xff, 0x12,
- 0x41, 0x85, 0xa0, 0x2b, 0xf2, 0x5f, 0x92, 0x64, 0x6f, 0x03, 0x08, 0x0a, 0xcd, 0xb0, 0xb9, 0xa4,
- 0xa8, 0xc8, 0x49, 0xf1, 0x4f, 0x15, 0xe8, 0x1a, 0xd8, 0xf6, 0x4e, 0x70, 0x30, 0x15, 0xd6, 0x5f,
- 0x06, 0xf8, 0xc6, 0x0b, 0x1c, 0x2e, 0x9f, 0x38, 0xd1, 0x5b, 0x94, 0xc2, 0xc4, 0x9b, 0x6d, 0xd4,
- 0xca, 0x1b, 0x19, 0xb5, 0xfa, 0x2a, 0xa3, 0xd6, 0x5e, 0x69, 0xd4, 0x39, 0xd9, 0xa8, 0x1b, 0x80,
- 0xb0, 0x7b, 0xe4, 0x05, 0x36, 0x36, 0xa9, 0xac, 0x63, 0x12, 0x46, 0xcc, 0xea, 0x4d, 0x63, 0x5e,
- 0xd0, 0xbf, 0x12, 0x64, 0x9a, 0x39, 0x59, 0xca, 0xe1, 0x81, 0xc8, 0xbe, 0x8b, 0x3e, 0x69, 0x9d,
- 0xf1, 0xc9, 0x65, 0x68, 0x38, 0xc1, 0xd4, 0x0c, 0x62, 0x97, 0xd5, 0xbd, 0x4d, 0xa3, 0xee, 0x04,
- 0x53, 0x23, 0x76, 0xf5, 0xf7, 0xa0, 0x4d, 0x39, 0x27, 0x27, 0xe9, 0x5a, 0xee, 0x24, 0x45, 0x7d,
- 0x69, 0x4e, 0x3a, 0x44, 0x97, 0xa1, 0x41, 0x27, 0xa8, 0x6f, 0x34, 0xa8, 0x51, 0x81, 0x45, 0x8a,
- 0x61, 0xdf, 0xfa, 0x8f, 0x0a, 0xb4, 0x07, 0x64, 0xe8, 0x3e, 0x13, 0x15, 0xd0, 0xb9, 0x49, 0x2d,
- 0x57, 0x43, 0xb0, 0xcc, 0x93, 0x14, 0x4e, 0xb9, 0x14, 0x5f, 0x9d, 0x95, 0xe2, 0x0b, 0x89, 0xb8,
- 0xf6, 0xc6, 0x89, 0xf8, 0xbf, 0x15, 0xe8, 0xbc, 0xc0, 0x01, 0x39, 0x9a, 0x26, 0xf2, 0xe6, 0x92,
- 0xa1, 0x22, 0x65, 0x4e, 0xed, 0x1a, 0xb4, 0x42, 0x32, 0x74, 0xd9, 0x7d, 0x8c, 0x45, 0x8c, 0x6a,
- 0x64, 0x04, 0x59, 0x95, 0x2a, 0x8f, 0xd3, 0x52, 0x55, 0x66, 0x9e, 0xa0, 0xff, 0x0e, 0x48, 0x88,
- 0x30, 0x90, 0x79, 0xfe, 0x1c, 0x59, 0xf4, 0x1f, 0x14, 0xba, 0xa9, 0xec, 0x60, 0xea, 0x47, 0x89,
- 0x5a, 0x97, 0xa0, 0xee, 0xc7, 0x87, 0xc7, 0x38, 0xd9, 0x45, 0x62, 0x54, 0xac, 0xe2, 0x24, 0xb1,
- 0x6f, 0x82, 0x9a, 0x64, 0x32, 0xcf, 0x1d, 0xa7, 0xc7, 0xa7, 0xa0, 0x7d, 0xe1, 0x8e, 0x0b, 0x55,
- 0x48, 0xed, 0xbc, 0x43, 0x7a, 0x6e, 0x96, 0xda, 0x2f, 0x00, 0x09, 0x49, 0xb1, 0x93, 0xc8, 0x7a,
- 0x11, 0xe6, 0x5c, 0xcf, 0xb5, 0xb1, 0x10, 0x95, 0x0f, 0xce, 0x91, 0x54, 0x83, 0xda, 0x68, 0x62,
- 0xd9, 0xc2, 0xee, 0xec, 0x5b, 0xff, 0x1a, 0xba, 0x3b, 0x38, 0x67, 0x81, 0x73, 0x03, 0x31, 0x5d,
- 0xb2, 0x32, 0x63, 0xc9, 0x6a, 0xf9, 0x92, 0x35, 0x69, 0xc9, 0x3d, 0x40, 0x62, 0xc9, 0x4c, 0x95,
- 0x42, 0xad, 0x2d, 0x71, 0x90, 0x7c, 0x5b, 0xc9, 0xf9, 0x56, 0xff, 0xb3, 0x02, 0xdd, 0x6d, 0xe2,
- 0x8f, 0x70, 0xf0, 0x39, 0x9e, 0xbe, 0xb0, 0xc6, 0xf1, 0x2b, 0x64, 0x47, 0x50, 0xa5, 0x7e, 0xe5,
- 0x5c, 0xe8, 0x27, 0xd5, 0xe6, 0x84, 0xfe, 0x4e, 0x48, 0xcd, 0x07, 0x3c, 0x93, 0x32, 0xf9, 0xc4,
- 0xb1, 0x90, 0x0c, 0xb5, 0x35, 0xe8, 0x5a, 0xe1, 0xb1, 0xe9, 0xb9, 0x66, 0x02, 0xe0, 0x77, 0x7a,
- 0xd5, 0x0a, 0x8f, 0xbf, 0x70, 0x77, 0xcf, 0xa0, 0x1c, 0xae, 0xa6, 0x48, 0x52, 0x1c, 0x25, 0x54,
- 0xd7, 0xba, 0x50, 0x21, 0x27, 0xec, 0x60, 0x50, 0x8d, 0x0a, 0x39, 0xd1, 0xd7, 0x01, 0x71, 0x65,
- 0xb0, 0x93, 0xaa, 0x93, 0xca, 0xa7, 0x48, 0xf2, 0xe9, 0xff, 0x05, 0xdd, 0xdd, 0x30, 0x22, 0x13,
- 0x2b, 0xc2, 0x07, 0xa7, 0x03, 0xf2, 0x12, 0xd3, 0x23, 0xda, 0x8b, 0x23, 0x3f, 0x8e, 0xc2, 0x34,
- 0xa3, 0xd3, 0xc2, 0x59, 0x15, 0x44, 0x9e, 0xd4, 0x6f, 0x82, 0x4a, 0x5c, 0x09, 0x53, 0x61, 0x98,
- 0x36, 0xa7, 0x71, 0xc8, 0x6b, 0x25, 0x13, 0xfd, 0x26, 0xd4, 0xc5, 0xba, 0x97, 0xa1, 0x11, 0x9d,
- 0x9a, 0xa2, 0x54, 0xa7, 0xd9, 0xb4, 0x1e, 0xb1, 0x09, 0xfd, 0xf7, 0x0a, 0xd4, 0xe9, 0xf6, 0x3c,
- 0x38, 0xfd, 0xc7, 0xca, 0xa6, 0x5d, 0x85, 0x46, 0xae, 0x2b, 0xf3, 0x40, 0x79, 0xd7, 0x48, 0x28,
- 0xda, 0x75, 0x68, 0x8d, 0x3d, 0xfb, 0xd8, 0x8c, 0x88, 0xd8, 0x69, 0x9d, 0x07, 0xca, 0x3b, 0x46,
- 0x93, 0xd2, 0x0e, 0xc8, 0x04, 0xeb, 0x7f, 0x53, 0x40, 0x1d, 0x90, 0x89, 0x3f, 0xc6, 0x42, 0xf6,
- 0x35, 0xa8, 0x73, 0x11, 0x58, 0x2c, 0xb5, 0x37, 0xd5, 0xfe, 0xc1, 0x29, 0xcb, 0x99, 0x2c, 0xcd,
- 0x8b, 0x39, 0xed, 0x0e, 0x34, 0x84, 0x32, 0xbd, 0x0a, 0x83, 0x75, 0xfa, 0x07, 0xa7, 0x5f, 0x30,
- 0x0a, 0xc3, 0x25, 0xb3, 0xda, 0xfb, 0xa0, 0x46, 0x81, 0xe5, 0x86, 0x16, 0x3b, 0x09, 0xc3, 0x5e,
- 0x95, 0xa1, 0x51, 0xff, 0x20, 0x23, 0xb2, 0x1f, 0xe4, 0x50, 0xaf, 0x97, 0x16, 0x65, 0xc5, 0xe7,
- 0xce, 0x57, 0xbc, 0x7e, 0x56, 0xf1, 0x5f, 0x2b, 0xd0, 0x3a, 0x48, 0x2f, 0x8a, 0xf7, 0x41, 0x0d,
- 0xf8, 0xa7, 0x29, 0x1d, 0x73, 0x6a, 0x5f, 0x3e, 0xe2, 0xda, 0x41, 0x36, 0xd0, 0xee, 0x43, 0xc3,
- 0xc1, 0x91, 0x45, 0xc6, 0xa1, 0xa8, 0x63, 0x17, 0xfb, 0x29, 0xb7, 0x1d, 0x3e, 0xc1, 0x0d, 0x21,
- 0x50, 0xda, 0x47, 0x00, 0x21, 0x0e, 0x92, 0x36, 0x51, 0x95, 0xfd, 0xa6, 0x97, 0xfd, 0x66, 0x90,
- 0xce, 0xb1, 0x9f, 0x49, 0x58, 0x7d, 0x03, 0xe6, 0x0e, 0xd8, 0x95, 0x74, 0x05, 0x2a, 0xd1, 0x29,
- 0x13, 0xad, 0xcc, 0x82, 0x95, 0xe8, 0x54, 0xff, 0xdf, 0x0a, 0x74, 0x93, 0x0a, 0x5e, 0xf8, 0xf3,
- 0x67, 0xa4, 0xb6, 0xab, 0xd0, 0x1a, 0x5a, 0xa1, 0xe9, 0x07, 0xc4, 0x4e, 0xd2, 0x44, 0x73, 0x68,
- 0x85, 0xfb, 0x74, 0x9c, 0x4c, 0x8e, 0xc9, 0x84, 0x44, 0x22, 0xc5, 0xd1, 0xc9, 0xa7, 0x74, 0x4c,
- 0x37, 0x78, 0xe4, 0x31, 0x67, 0xa8, 0x46, 0x25, 0xf2, 0xb2, 0xcd, 0x5c, 0x97, 0x93, 0xcd, 0x5b,
- 0xa0, 0xd1, 0xeb, 0xbb, 0x29, 0x9a, 0x64, 0xa6, 0x3d, 0x8a, 0xdd, 0x63, 0x91, 0x16, 0x10, 0x9d,
- 0x11, 0x6d, 0xcf, 0x6d, 0x4a, 0xa7, 0x25, 0x0c, 0x43, 0x8f, 0x79, 0x45, 0x2c, 0xca, 0x6c, 0x4a,
- 0x7a, 0xca, 0xcb, 0xe1, 0x2b, 0xd0, 0xb4, 0x47, 0x16, 0x71, 0x4d, 0xe2, 0x88, 0x02, 0xa7, 0xc1,
- 0xc6, 0x4f, 0x1c, 0xfd, 0xff, 0x15, 0x58, 0x48, 0xec, 0x91, 0x39, 0xbb, 0xc0, 0x51, 0x39, 0xc3,
- 0x91, 0x16, 0xaa, 0xc9, 0x81, 0x69, 0x9e, 0x88, 0xae, 0x29, 0xa4, 0xa4, 0x17, 0x79, 0x40, 0x20,
- 0x6c, 0x94, 0x01, 0x8c, 0x3c, 0x20, 0x4c, 0x1a, 0x4d, 0x29, 0x69, 0xa0, 0xf7, 0xa1, 0x93, 0x09,
- 0x46, 0x9d, 0xbb, 0x0c, 0x4c, 0x02, 0x61, 0x0c, 0x9e, 0xfc, 0x5a, 0x94, 0xc2, 0xac, 0xa0, 0x3f,
- 0x85, 0x0b, 0xb2, 0x63, 0x7f, 0x59, 0x05, 0xa5, 0x13, 0x58, 0x4c, 0xb8, 0x9d, 0x5b, 0xe1, 0xa8,
- 0xbf, 0xb8, 0xc2, 0xd1, 0x0d, 0xe8, 0x25, 0x4b, 0xbd, 0xaa, 0x86, 0x79, 0xdd, 0xd5, 0xf4, 0x9f,
- 0x58, 0xd2, 0x1a, 0xba, 0x4f, 0x1c, 0xec, 0x46, 0x24, 0x9a, 0x6a, 0x1b, 0xd0, 0x24, 0xe2, 0x5b,
- 0xec, 0x8f, 0x4e, 0x3f, 0x99, 0xe4, 0xf7, 0x73, 0x92, 0x41, 0x91, 0x3d, 0xb2, 0xc6, 0xd4, 0xf7,
- 0xd8, 0x1c, 0x11, 0xc7, 0xc1, 0xae, 0x58, 0x60, 0x3e, 0xa5, 0x3f, 0x66, 0xe4, 0x3c, 0xf4, 0x84,
- 0x84, 0xb1, 0x35, 0x16, 0x97, 0xd2, 0x0c, 0xfa, 0x82, 0x91, 0x4b, 0xdb, 0x2a, 0xb5, 0xb2, 0xb6,
- 0x8a, 0x3e, 0x84, 0x2e, 0x15, 0x1d, 0x3b, 0xa9, 0xf0, 0xb3, 0x2b, 0xb9, 0x65, 0x00, 0x9f, 0x75,
- 0x4e, 0xcc, 0xe4, 0x10, 0x57, 0x8d, 0x96, 0x9f, 0xf6, 0x52, 0x72, 0x46, 0xaa, 0x16, 0x8d, 0xf4,
- 0xad, 0x02, 0x0b, 0x8f, 0x70, 0xb4, 0xbb, 0xbd, 0xf3, 0x58, 0x34, 0x5a, 0xe9, 0x6f, 0xde, 0xc0,
- 0x52, 0xb7, 0x61, 0xde, 0xc7, 0x38, 0x30, 0xcf, 0x88, 0xd0, 0xa1, 0xe4, 0xac, 0xa5, 0x53, 0xa6,
- 0x7b, 0xb5, 0x54, 0xf7, 0x77, 0xa1, 0x5b, 0x10, 0x87, 0xee, 0x13, 0x3e, 0x32, 0xb3, 0xfa, 0x13,
- 0xc2, 0x14, 0xa0, 0xbf, 0x03, 0x9d, 0x01, 0x8e, 0xbe, 0xdc, 0xdc, 0x93, 0x2e, 0x91, 0xf2, 0x8d,
- 0x46, 0x39, 0x73, 0xeb, 0xbe, 0x03, 0x9d, 0x3d, 0xd1, 0xa9, 0xde, 0x65, 0x3d, 0xdf, 0x4b, 0x50,
- 0xcf, 0xed, 0x74, 0x31, 0xd2, 0xb7, 0x60, 0x3e, 0x01, 0x26, 0x99, 0xe1, 0x12, 0xd4, 0xbd, 0xa3,
- 0xa3, 0x10, 0x27, 0xf7, 0x43, 0x31, 0x92, 0x58, 0x54, 0x72, 0x2c, 0x3e, 0x81, 0x6e, 0xc2, 0xe2,
- 0x4b, 0x7f, 0xec, 0x59, 0x0e, 0x75, 0xa6, 0x6f, 0x4d, 0xe9, 0x67, 0xd2, 0x2f, 0x11, 0x43, 0x56,
- 0x16, 0x5a, 0xe1, 0x48, 0xd8, 0x90, 0x7d, 0xeb, 0x6b, 0xd0, 0x1c, 0xe0, 0xf1, 0xd1, 0x01, 0x5d,
- 0x3b, 0xf7, 0x4b, 0x45, 0xfa, 0xa5, 0x7e, 0x17, 0x16, 0x76, 0xf0, 0x61, 0x3c, 0x7c, 0x4a, 0xdc,
- 0xe3, 0x1d, 0x6c, 0xf3, 0x97, 0x83, 0x45, 0xa8, 0x4f, 0x71, 0x68, 0xba, 0x1e, 0x5b, 0xa7, 0x69,
- 0xcc, 0x4d, 0x71, 0xf8, 0xdc, 0xd3, 0x2f, 0x48, 0xd8, 0x47, 0x38, 0x1a, 0x44, 0x56, 0x84, 0xf5,
- 0xbf, 0x54, 0x68, 0xc5, 0x2b, 0xa8, 0x8c, 0xc4, 0x34, 0xb2, 0xa6, 0x5e, 0x1c, 0x25, 0x35, 0x3f,
- 0x1f, 0x25, 0xbd, 0x97, 0x4a, 0xd6, 0x7b, 0xb9, 0x04, 0xf5, 0x09, 0xeb, 0x8a, 0x0a, 0xa7, 0x8a,
- 0x51, 0xae, 0xc5, 0x53, 0x9b, 0xd1, 0xe2, 0x99, 0x9b, 0xd5, 0xe2, 0x99, 0x79, 0xdb, 0xae, 0x9f,
- 0x73, 0xdb, 0x5e, 0x06, 0x08, 0x70, 0x88, 0x23, 0x76, 0x13, 0x66, 0xe7, 0x45, 0xcb, 0x68, 0x31,
- 0x0a, 0xbd, 0x74, 0xd2, 0xaa, 0x8b, 0x4f, 0x27, 0x3d, 0x81, 0x26, 0xd3, 0x4c, 0x65, 0xc4, 0xa4,
- 0x8f, 0xfa, 0x16, 0x68, 0x81, 0xe8, 0x0b, 0x98, 0x47, 0xd6, 0x31, 0xbf, 0x55, 0x8b, 0xb7, 0x20,
- 0x94, 0xcc, 0xec, 0x59, 0xc7, 0xec, 0x5a, 0xad, 0xdd, 0x85, 0x85, 0x14, 0xcd, 0x9a, 0x07, 0xbe,
- 0x17, 0xb2, 0x7b, 0x72, 0xc7, 0x98, 0x4f, 0x26, 0x28, 0x70, 0xdf, 0x0b, 0xf5, 0x79, 0xe8, 0x48,
- 0x36, 0xf6, 0x7c, 0x7d, 0x1f, 0xd4, 0x94, 0xf0, 0xd4, 0x1b, 0xb2, 0x0b, 0x3e, 0x3e, 0xc1, 0xe3,
- 0xe4, 0x35, 0x81, 0x0d, 0xa8, 0x79, 0x0f, 0x63, 0xfb, 0x18, 0x47, 0xc2, 0xe6, 0x62, 0xc4, 0x6e,
- 0xf3, 0xf8, 0x34, 0x12, 0x46, 0x67, 0xdf, 0xfa, 0x23, 0xb8, 0x90, 0x72, 0x7c, 0x86, 0x27, 0x5e,
- 0x30, 0x35, 0x30, 0x8f, 0x39, 0x39, 0x81, 0x74, 0xb2, 0x04, 0x32, 0x2b, 0x6e, 0x37, 0x60, 0xbe,
- 0xc0, 0x88, 0xb9, 0x99, 0x7d, 0x25, 0x01, 0xc1, 0x47, 0xfa, 0x7f, 0xc0, 0xc5, 0x02, 0xf4, 0xab,
- 0x80, 0x44, 0xf8, 0xfc, 0x45, 0x05, 0xa7, 0x8a, 0xcc, 0x49, 0xbc, 0xa6, 0x84, 0x23, 0x71, 0x5b,
- 0xe4, 0x03, 0xfd, 0x6d, 0x49, 0xa7, 0x3d, 0x4a, 0x49, 0x37, 0x6d, 0x88, 0xed, 0xc8, 0x4b, 0x76,
- 0xb8, 0x18, 0xdd, 0xfd, 0x71, 0x11, 0xda, 0xe2, 0x1c, 0x61, 0x75, 0xd8, 0x0a, 0x5c, 0x92, 0x86,
- 0x66, 0xf6, 0x60, 0x8a, 0xfe, 0x69, 0xa9, 0xf6, 0xed, 0x1f, 0x7a, 0x8a, 0xb6, 0x94, 0x5e, 0x9e,
- 0x19, 0x62, 0x9f, 0xb8, 0x43, 0xa4, 0x88, 0xb9, 0x65, 0xb8, 0x20, 0xcf, 0x89, 0x57, 0x10, 0x54,
- 0x59, 0xaa, 0x7d, 0x57, 0x32, 0x2d, 0xde, 0x39, 0x50, 0x55, 0x4c, 0xdf, 0x80, 0x45, 0x79, 0x3a,
- 0x7d, 0x14, 0x42, 0x35, 0xc1, 0xbe, 0x20, 0x5c, 0xd6, 0x2e, 0x45, 0x73, 0x02, 0x71, 0x07, 0xae,
- 0xe4, 0x56, 0x90, 0x13, 0x17, 0xaa, 0x2f, 0x35, 0x29, 0xe8, 0x8f, 0x14, 0xb8, 0x0e, 0x4b, 0x65,
- 0x40, 0x9e, 0x75, 0x50, 0x43, 0x42, 0x6e, 0xc0, 0xd5, 0x32, 0xa4, 0x48, 0x71, 0xa8, 0xb9, 0xd4,
- 0xfc, 0x2e, 0x81, 0x16, 0xe4, 0xcb, 0x5e, 0x23, 0x50, 0xab, 0xdc, 0x40, 0xc9, 0x34, 0x08, 0x0b,
- 0xe8, 0xd0, 0x2b, 0x30, 0x48, 0x8f, 0x05, 0xd4, 0x16, 0x2c, 0x0a, 0x56, 0xca, 0x00, 0xaa, 0x60,
- 0x52, 0x90, 0x22, 0xeb, 0x22, 0xa3, 0x8e, 0x60, 0x71, 0x13, 0x2e, 0xcb, 0x08, 0xa9, 0xa7, 0x8a,
- 0xba, 0x02, 0x72, 0x0d, 0xb4, 0x9c, 0x27, 0x59, 0xf1, 0x8b, 0xe6, 0xc5, 0xec, 0x5a, 0x5e, 0x4e,
- 0xf9, 0xc2, 0x83, 0xd0, 0x52, 0x9d, 0x62, 0x9a, 0x8a, 0x76, 0x1d, 0x2e, 0xe6, 0x2c, 0x27, 0x9e,
- 0xd7, 0xd1, 0x82, 0x10, 0xf4, 0x36, 0x5c, 0x2b, 0x44, 0x52, 0xee, 0x31, 0x09, 0x69, 0x29, 0xae,
- 0x57, 0x8a, 0xdb, 0xb2, 0x8f, 0xd1, 0x05, 0xee, 0xa9, 0xdf, 0x95, 0xc8, 0xcc, 0x1f, 0x97, 0xd0,
- 0xc5, 0x72, 0xbb, 0xa5, 0xe5, 0x2b, 0x5a, 0x14, 0xcb, 0x5c, 0x85, 0x85, 0x3c, 0x80, 0xf2, 0xbf,
- 0x94, 0x6a, 0x9c, 0x8b, 0x97, 0x7c, 0xcf, 0x00, 0x5d, 0x16, 0xa8, 0x82, 0xff, 0xe4, 0x57, 0x59,
- 0xd4, 0x13, 0x98, 0xd5, 0x7c, 0x88, 0xe6, 0x1e, 0x6a, 0xd1, 0x95, 0x72, 0x50, 0xee, 0x11, 0x0f,
- 0x2d, 0x09, 0x81, 0x57, 0xf3, 0x1a, 0xa5, 0x4f, 0x77, 0xe8, 0xaa, 0x64, 0x94, 0x42, 0x34, 0x64,
- 0xaf, 0xb1, 0xe8, 0x5a, 0xf9, 0xae, 0xca, 0x1e, 0x49, 0xd0, 0x72, 0x79, 0xd4, 0x26, 0xd3, 0xd7,
- 0xd3, 0xa8, 0xcd, 0xf9, 0x39, 0x39, 0x81, 0xd1, 0x8a, 0xb4, 0x8b, 0x0a, 0x96, 0x91, 0xdb, 0xd2,
- 0x48, 0x2f, 0xb7, 0x71, 0xbe, 0x55, 0x8d, 0x56, 0xcb, 0xc3, 0x3b, 0x6b, 0x5f, 0xa3, 0xb5, 0xf2,
- 0xf0, 0x96, 0xea, 0x7b, 0x74, 0xbb, 0xdc, 0xbe, 0xb9, 0xa2, 0x1d, 0xdd, 0x11, 0xa0, 0x42, 0x7c,
- 0x16, 0xcb, 0x6d, 0xb4, 0x2e, 0x24, 0xba, 0x03, 0xcb, 0xb9, 0xf8, 0x2c, 0x3e, 0x65, 0xa2, 0x8d,
- 0x14, 0x78, 0xa5, 0x1c, 0x48, 0xa5, 0xbf, 0x2b, 0x39, 0xed, 0x76, 0xc1, 0x12, 0xb9, 0x56, 0x0d,
- 0xba, 0x27, 0xed, 0x30, 0x2d, 0x1f, 0xb2, 0x6c, 0xfe, 0xad, 0xa5, 0xfa, 0x77, 0x7c, 0xbe, 0x60,
- 0xd1, 0x7c, 0x07, 0x1f, 0xbd, 0x5d, 0x6e, 0x2f, 0xa9, 0x15, 0x8d, 0xfa, 0xe5, 0x99, 0x5b, 0x34,
- 0xa5, 0xd1, 0xfd, 0x72, 0x4b, 0x15, 0x9b, 0x50, 0xe8, 0x9d, 0x74, 0x27, 0x17, 0x3c, 0x2c, 0x77,
- 0x0d, 0xd1, 0xbb, 0xa9, 0x5e, 0xeb, 0x79, 0x7e, 0xc5, 0xae, 0x25, 0xda, 0x4c, 0x35, 0x2c, 0x70,
- 0xcc, 0xf7, 0x21, 0xd1, 0x7b, 0xb3, 0x38, 0x16, 0x9b, 0x87, 0xe8, 0xfd, 0x94, 0xa3, 0x5e, 0xcc,
- 0x6d, 0xd9, 0xbd, 0x08, 0x7d, 0x50, 0x1e, 0xa9, 0xf9, 0x0b, 0x08, 0xfa, 0x50, 0x68, 0x5b, 0xb0,
- 0xab, 0xf4, 0xef, 0x46, 0xe8, 0x9f, 0x05, 0xa3, 0x75, 0xb8, 0x9e, 0x53, 0xf4, 0xcc, 0x43, 0x25,
- 0xfa, 0x48, 0x20, 0x6f, 0xe5, 0x8f, 0xa1, 0xc2, 0xbb, 0x22, 0xfa, 0x17, 0xb1, 0x66, 0x71, 0x0f,
- 0xe5, 0x9a, 0x17, 0xe8, 0x41, 0x7a, 0x4c, 0x2e, 0x97, 0xa1, 0xb2, 0x9c, 0xf8, 0xaf, 0x69, 0x8a,
- 0xb9, 0x52, 0x0e, 0xa4, 0xde, 0xff, 0xb7, 0x72, 0x6e, 0x67, 0x2e, 0x49, 0xe8, 0xe3, 0x19, 0x1b,
- 0x3c, 0x8f, 0xfa, 0xa4, 0x7c, 0xcd, 0xdc, 0x75, 0x05, 0x7d, 0x2a, 0x58, 0x6d, 0xc0, 0x8d, 0x59,
- 0x7a, 0x26, 0x2e, 0xfd, 0x4c, 0x40, 0xef, 0xc1, 0xcd, 0x32, 0x68, 0x7e, 0xcf, 0x6f, 0x09, 0x70,
- 0x1f, 0xd6, 0xca, 0xc0, 0x67, 0xf6, 0xfe, 0x43, 0x21, 0xec, 0xbd, 0xbc, 0xee, 0x67, 0xee, 0x15,
- 0xc8, 0x59, 0x6a, 0x7e, 0x9f, 0x6c, 0xeb, 0x3b, 0x33, 0xc0, 0xc9, 0xc5, 0x02, 0xe1, 0xa5, 0xda,
- 0xf7, 0x25, 0x86, 0xca, 0xdf, 0x35, 0xd0, 0xd1, 0x52, 0xed, 0x87, 0x12, 0x43, 0xe5, 0xaa, 0x65,
- 0x34, 0x14, 0xac, 0x0a, 0xe1, 0x2c, 0x57, 0xd0, 0x68, 0x24, 0x18, 0x15, 0x8c, 0x59, 0x52, 0x13,
- 0x23, 0x57, 0xb0, 0x2b, 0x84, 0x61, 0x01, 0x8a, 0x3c, 0xc1, 0xf1, 0x2e, 0xac, 0x9c, 0x03, 0x63,
- 0x15, 0x2f, 0xf2, 0x05, 0xcb, 0x59, 0xab, 0x67, 0xd5, 0x2b, 0xfa, 0x9a, 0x43, 0x1f, 0xbe, 0x0f,
- 0xab, 0xb6, 0x37, 0xe9, 0x87, 0x56, 0xe4, 0x85, 0x23, 0x32, 0xb6, 0x0e, 0xc3, 0x7e, 0x14, 0xe0,
- 0x97, 0x5e, 0xd0, 0x1f, 0x93, 0x43, 0xfe, 0x6f, 0x7e, 0x87, 0xf1, 0xd1, 0xc3, 0xce, 0x01, 0x23,
- 0x0a, 0xae, 0x7f, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x2a, 0xe4, 0xc0, 0x85, 0x16, 0x28, 0x00, 0x00,
-}
diff --git a/accounts/usbwallet/internal/trezor/messages.proto b/accounts/usbwallet/internal/trezor/messages.proto
deleted file mode 100644
index 8cb9c8cc2..000000000
--- a/accounts/usbwallet/internal/trezor/messages.proto
+++ /dev/null
@@ -1,905 +0,0 @@
-// This file originates from the SatoshiLabs Trezor `common` repository at:
-// https://github.com/trezor/trezor-common/blob/master/protob/messages.proto
-// dated 28.07.2017, commit dd8ec3231fb5f7992360aff9bdfe30bb58130f4b.
-
-syntax = "proto2";
-
-/**
- * Messages for TREZOR communication
- */
-
-// Sugar for easier handling in Java
-option java_package = "com.satoshilabs.trezor.lib.protobuf";
-option java_outer_classname = "TrezorMessage";
-
-import "types.proto";
-
-/**
- * Mapping between Trezor wire identifier (uint) and a protobuf message
- */
-enum MessageType {
- MessageType_Initialize = 0 [(wire_in) = true];
- MessageType_Ping = 1 [(wire_in) = true];
- MessageType_Success = 2 [(wire_out) = true];
- MessageType_Failure = 3 [(wire_out) = true];
- MessageType_ChangePin = 4 [(wire_in) = true];
- MessageType_WipeDevice = 5 [(wire_in) = true];
- MessageType_FirmwareErase = 6 [(wire_in) = true, (wire_bootloader) = true];
- MessageType_FirmwareUpload = 7 [(wire_in) = true, (wire_bootloader) = true];
- MessageType_FirmwareRequest = 8 [(wire_out) = true, (wire_bootloader) = true];
- MessageType_GetEntropy = 9 [(wire_in) = true];
- MessageType_Entropy = 10 [(wire_out) = true];
- MessageType_GetPublicKey = 11 [(wire_in) = true];
- MessageType_PublicKey = 12 [(wire_out) = true];
- MessageType_LoadDevice = 13 [(wire_in) = true];
- MessageType_ResetDevice = 14 [(wire_in) = true];
- MessageType_SignTx = 15 [(wire_in) = true];
- MessageType_SimpleSignTx = 16 [(wire_in) = true, deprecated = true];
- MessageType_Features = 17 [(wire_out) = true];
- MessageType_PinMatrixRequest = 18 [(wire_out) = true];
- MessageType_PinMatrixAck = 19 [(wire_in) = true, (wire_tiny) = true];
- MessageType_Cancel = 20 [(wire_in) = true];
- MessageType_TxRequest = 21 [(wire_out) = true];
- MessageType_TxAck = 22 [(wire_in) = true];
- MessageType_CipherKeyValue = 23 [(wire_in) = true];
- MessageType_ClearSession = 24 [(wire_in) = true];
- MessageType_ApplySettings = 25 [(wire_in) = true];
- MessageType_ButtonRequest = 26 [(wire_out) = true];
- MessageType_ButtonAck = 27 [(wire_in) = true, (wire_tiny) = true];
- MessageType_ApplyFlags = 28 [(wire_in) = true];
- MessageType_GetAddress = 29 [(wire_in) = true];
- MessageType_Address = 30 [(wire_out) = true];
- MessageType_SelfTest = 32 [(wire_in) = true, (wire_bootloader) = true];
- MessageType_BackupDevice = 34 [(wire_in) = true];
- MessageType_EntropyRequest = 35 [(wire_out) = true];
- MessageType_EntropyAck = 36 [(wire_in) = true];
- MessageType_SignMessage = 38 [(wire_in) = true];
- MessageType_VerifyMessage = 39 [(wire_in) = true];
- MessageType_MessageSignature = 40 [(wire_out) = true];
- MessageType_PassphraseRequest = 41 [(wire_out) = true];
- MessageType_PassphraseAck = 42 [(wire_in) = true, (wire_tiny) = true];
- MessageType_EstimateTxSize = 43 [(wire_in) = true, deprecated = true];
- MessageType_TxSize = 44 [(wire_out) = true, deprecated = true];
- MessageType_RecoveryDevice = 45 [(wire_in) = true];
- MessageType_WordRequest = 46 [(wire_out) = true];
- MessageType_WordAck = 47 [(wire_in) = true];
- MessageType_CipheredKeyValue = 48 [(wire_out) = true];
- MessageType_EncryptMessage = 49 [(wire_in) = true, deprecated = true];
- MessageType_EncryptedMessage = 50 [(wire_out) = true, deprecated = true];
- MessageType_DecryptMessage = 51 [(wire_in) = true, deprecated = true];
- MessageType_DecryptedMessage = 52 [(wire_out) = true, deprecated = true];
- MessageType_SignIdentity = 53 [(wire_in) = true];
- MessageType_SignedIdentity = 54 [(wire_out) = true];
- MessageType_GetFeatures = 55 [(wire_in) = true];
- MessageType_EthereumGetAddress = 56 [(wire_in) = true];
- MessageType_EthereumAddress = 57 [(wire_out) = true];
- MessageType_EthereumSignTx = 58 [(wire_in) = true];
- MessageType_EthereumTxRequest = 59 [(wire_out) = true];
- MessageType_EthereumTxAck = 60 [(wire_in) = true];
- MessageType_GetECDHSessionKey = 61 [(wire_in) = true];
- MessageType_ECDHSessionKey = 62 [(wire_out) = true];
- MessageType_SetU2FCounter = 63 [(wire_in) = true];
- MessageType_EthereumSignMessage = 64 [(wire_in) = true];
- MessageType_EthereumVerifyMessage = 65 [(wire_in) = true];
- MessageType_EthereumMessageSignature = 66 [(wire_out) = true];
- MessageType_DebugLinkDecision = 100 [(wire_debug_in) = true, (wire_tiny) = true];
- MessageType_DebugLinkGetState = 101 [(wire_debug_in) = true];
- MessageType_DebugLinkState = 102 [(wire_debug_out) = true];
- MessageType_DebugLinkStop = 103 [(wire_debug_in) = true];
- MessageType_DebugLinkLog = 104 [(wire_debug_out) = true];
- MessageType_DebugLinkMemoryRead = 110 [(wire_debug_in) = true];
- MessageType_DebugLinkMemory = 111 [(wire_debug_out) = true];
- MessageType_DebugLinkMemoryWrite = 112 [(wire_debug_in) = true];
- MessageType_DebugLinkFlashErase = 113 [(wire_debug_in) = true];
-}
-
-////////////////////
-// Basic messages //
-////////////////////
-
-/**
- * Request: Reset device to default state and ask for device details
- * @next Features
- */
-message Initialize {
-}
-
-/**
- * Request: Ask for device details (no device reset)
- * @next Features
- */
-message GetFeatures {
-}
-
-/**
- * Response: Reports various information about the device
- * @prev Initialize
- * @prev GetFeatures
- */
-message Features {
- optional string vendor = 1; // name of the manufacturer, e.g. "bitcointrezor.com"
- optional uint32 major_version = 2; // major version of the device, e.g. 1
- optional uint32 minor_version = 3; // minor version of the device, e.g. 0
- optional uint32 patch_version = 4; // patch version of the device, e.g. 0
- optional bool bootloader_mode = 5; // is device in bootloader mode?
- optional string device_id = 6; // device's unique identifier
- optional bool pin_protection = 7; // is device protected by PIN?
- optional bool passphrase_protection = 8; // is node/mnemonic encrypted using passphrase?
- optional string language = 9; // device language
- optional string label = 10; // device description label
- repeated CoinType coins = 11; // supported coins
- optional bool initialized = 12; // does device contain seed?
- optional bytes revision = 13; // SCM revision of firmware
- optional bytes bootloader_hash = 14; // hash of the bootloader
- optional bool imported = 15; // was storage imported from an external source?
- optional bool pin_cached = 16; // is PIN already cached in session?
- optional bool passphrase_cached = 17; // is passphrase already cached in session?
- optional bool firmware_present = 18; // is valid firmware loaded?
- optional bool needs_backup = 19; // does storage need backup? (equals to Storage.needs_backup)
- optional uint32 flags = 20; // device flags (equals to Storage.flags)
-}
-
-/**
- * Request: clear session (removes cached PIN, passphrase, etc).
- * @next Success
- */
-message ClearSession {
-}
-
-/**
- * Request: change language and/or label of the device
- * @next Success
- * @next Failure
- * @next ButtonRequest
- * @next PinMatrixRequest
- */
-message ApplySettings {
- optional string language = 1;
- optional string label = 2;
- optional bool use_passphrase = 3;
- optional bytes homescreen = 4;
-}
-
-/**
- * Request: set flags of the device
- * @next Success
- * @next Failure
- */
-message ApplyFlags {
- optional uint32 flags = 1; // bitmask, can only set bits, not unset
-}
-
-/**
- * Request: Starts workflow for setting/changing/removing the PIN
- * @next ButtonRequest
- * @next PinMatrixRequest
- */
-message ChangePin {
- optional bool remove = 1; // is PIN removal requested?
-}
-
-/**
- * Request: Test if the device is alive, device sends back the message in Success response
- * @next Success
- */
-message Ping {
- optional string message = 1; // message to send back in Success message
- optional bool button_protection = 2; // ask for button press
- optional bool pin_protection = 3; // ask for PIN if set in device
- optional bool passphrase_protection = 4; // ask for passphrase if set in device
-}
-
-/**
- * Response: Success of the previous request
- */
-message Success {
- optional string message = 1; // human readable description of action or request-specific payload
-}
-
-/**
- * Response: Failure of the previous request
- */
-message Failure {
- optional FailureType code = 1; // computer-readable definition of the error state
- optional string message = 2; // human-readable message of the error state
-}
-
-/**
- * Response: Device is waiting for HW button press.
- * @next ButtonAck
- * @next Cancel
- */
-message ButtonRequest {
- optional ButtonRequestType code = 1;
- optional string data = 2;
-}
-
-/**
- * Request: Computer agrees to wait for HW button press
- * @prev ButtonRequest
- */
-message ButtonAck {
-}
-
-/**
- * Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
- * @next PinMatrixAck
- * @next Cancel
- */
-message PinMatrixRequest {
- optional PinMatrixRequestType type = 1;
-}
-
-/**
- * Request: Computer responds with encoded PIN
- * @prev PinMatrixRequest
- */
-message PinMatrixAck {
- required string pin = 1; // matrix encoded PIN entered by user
-}
-
-/**
- * Request: Abort last operation that required user interaction
- * @prev ButtonRequest
- * @prev PinMatrixRequest
- * @prev PassphraseRequest
- */
-message Cancel {
-}
-
-/**
- * Response: Device awaits encryption passphrase
- * @next PassphraseAck
- * @next Cancel
- */
-message PassphraseRequest {
-}
-
-/**
- * Request: Send passphrase back
- * @prev PassphraseRequest
- */
-message PassphraseAck {
- required string passphrase = 1;
-}
-
-/**
- * Request: Request a sample of random data generated by hardware RNG. May be used for testing.
- * @next ButtonRequest
- * @next Entropy
- * @next Failure
- */
-message GetEntropy {
- required uint32 size = 1; // size of requested entropy
-}
-
-/**
- * Response: Reply with random data generated by internal RNG
- * @prev GetEntropy
- */
-message Entropy {
- required bytes entropy = 1; // stream of random generated bytes
-}
-
-/**
- * Request: Ask device for public key corresponding to address_n path
- * @next PassphraseRequest
- * @next PublicKey
- * @next Failure
- */
-message GetPublicKey {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- optional string ecdsa_curve_name = 2; // ECDSA curve name to use
- optional bool show_display = 3; // optionally show on display before sending the result
- optional string coin_name = 4 [default='Bitcoin'];
-}
-
-/**
- * Response: Contains public key derived from device private seed
- * @prev GetPublicKey
- */
-message PublicKey {
- required HDNodeType node = 1; // BIP32 public node
- optional string xpub = 2; // serialized form of public node
-}
-
-/**
- * Request: Ask device for address corresponding to address_n path
- * @next PassphraseRequest
- * @next Address
- * @next Failure
- */
-message GetAddress {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- optional string coin_name = 2 [default='Bitcoin'];
- optional bool show_display = 3 ; // optionally show on display before sending the result
- optional MultisigRedeemScriptType multisig = 4; // filled if we are showing a multisig address
- optional InputScriptType script_type = 5 [default=SPENDADDRESS]; // used to distinguish between various address formats (non-segwit, segwit, etc.)
-}
-
-/**
- * Request: Ask device for Ethereum address corresponding to address_n path
- * @next PassphraseRequest
- * @next EthereumAddress
- * @next Failure
- */
-message EthereumGetAddress {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- optional bool show_display = 2; // optionally show on display before sending the result
-}
-
-/**
- * Response: Contains address derived from device private seed
- * @prev GetAddress
- */
-message Address {
- required string address = 1; // Coin address in Base58 encoding
-}
-
-/**
- * Response: Contains an Ethereum address derived from device private seed
- * @prev EthereumGetAddress
- */
-message EthereumAddress {
- required bytes address = 1; // Coin address as an Ethereum 160 bit hash
-}
-
-/**
- * Request: Request device to wipe all sensitive data and settings
- * @next ButtonRequest
- */
-message WipeDevice {
-}
-
-/**
- * Request: Load seed and related internal settings from the computer
- * @next ButtonRequest
- * @next Success
- * @next Failure
- */
-message LoadDevice {
- optional string mnemonic = 1; // seed encoded as BIP-39 mnemonic (12, 18 or 24 words)
- optional HDNodeType node = 2; // BIP-32 node
- optional string pin = 3; // set PIN protection
- optional bool passphrase_protection = 4; // enable master node encryption using passphrase
- optional string language = 5 [default='english']; // device language
- optional string label = 6; // device label
- optional bool skip_checksum = 7; // do not test mnemonic for valid BIP-39 checksum
- optional uint32 u2f_counter = 8; // U2F counter
-}
-
-/**
- * Request: Ask device to do initialization involving user interaction
- * @next EntropyRequest
- * @next Failure
- */
-message ResetDevice {
- optional bool display_random = 1; // display entropy generated by the device before asking for additional entropy
- optional uint32 strength = 2 [default=256]; // strength of seed in bits
- optional bool passphrase_protection = 3; // enable master node encryption using passphrase
- optional bool pin_protection = 4; // enable PIN protection
- optional string language = 5 [default='english']; // device language
- optional string label = 6; // device label
- optional uint32 u2f_counter = 7; // U2F counter
- optional bool skip_backup = 8; // postpone seed backup to BackupDevice workflow
-}
-
-/**
- * Request: Perform backup of the device seed if not backed up using ResetDevice
- * @next ButtonRequest
- */
-message BackupDevice {
-}
-
-/**
- * Response: Ask for additional entropy from host computer
- * @prev ResetDevice
- * @next EntropyAck
- */
-message EntropyRequest {
-}
-
-/**
- * Request: Provide additional entropy for seed generation function
- * @prev EntropyRequest
- * @next ButtonRequest
- */
-message EntropyAck {
- optional bytes entropy = 1; // 256 bits (32 bytes) of random data
-}
-
-/**
- * Request: Start recovery workflow asking user for specific words of mnemonic
- * Used to recovery device safely even on untrusted computer.
- * @next WordRequest
- */
-message RecoveryDevice {
- optional uint32 word_count = 1; // number of words in BIP-39 mnemonic
- optional bool passphrase_protection = 2; // enable master node encryption using passphrase
- optional bool pin_protection = 3; // enable PIN protection
- optional string language = 4 [default='english']; // device language
- optional string label = 5; // device label
- optional bool enforce_wordlist = 6; // enforce BIP-39 wordlist during the process
- // 7 reserved for unused recovery method
- optional uint32 type = 8; // supported recovery type (see RecoveryType)
- optional uint32 u2f_counter = 9; // U2F counter
- optional bool dry_run = 10; // perform dry-run recovery workflow (for safe mnemonic validation)
-}
-
-/**
- * Response: Device is waiting for user to enter word of the mnemonic
- * Its position is shown only on device's internal display.
- * @prev RecoveryDevice
- * @prev WordAck
- */
-message WordRequest {
- optional WordRequestType type = 1;
-}
-
-/**
- * Request: Computer replies with word from the mnemonic
- * @prev WordRequest
- * @next WordRequest
- * @next Success
- * @next Failure
- */
-message WordAck {
- required string word = 1; // one word of mnemonic on asked position
-}
-
-//////////////////////////////
-// Message signing messages //
-//////////////////////////////
-
-/**
- * Request: Ask device to sign message
- * @next MessageSignature
- * @next Failure
- */
-message SignMessage {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- required bytes message = 2; // message to be signed
- optional string coin_name = 3 [default='Bitcoin']; // coin to use for signing
- optional InputScriptType script_type = 4 [default=SPENDADDRESS]; // used to distinguish between various address formats (non-segwit, segwit, etc.)
-}
-
-/**
- * Request: Ask device to verify message
- * @next Success
- * @next Failure
- */
-message VerifyMessage {
- optional string address = 1; // address to verify
- optional bytes signature = 2; // signature to verify
- optional bytes message = 3; // message to verify
- optional string coin_name = 4 [default='Bitcoin']; // coin to use for verifying
-}
-
-/**
- * Response: Signed message
- * @prev SignMessage
- */
-message MessageSignature {
- optional string address = 1; // address used to sign the message
- optional bytes signature = 2; // signature of the message
-}
-
-///////////////////////////
-// Encryption/decryption //
-///////////////////////////
-
-/**
- * Request: Ask device to encrypt message
- * @next EncryptedMessage
- * @next Failure
- */
-message EncryptMessage {
- optional bytes pubkey = 1; // public key
- optional bytes message = 2; // message to encrypt
- optional bool display_only = 3; // show just on display? (don't send back via wire)
- repeated uint32 address_n = 4; // BIP-32 path to derive the signing key from master node
- optional string coin_name = 5 [default='Bitcoin']; // coin to use for signing
-}
-
-/**
- * Response: Encrypted message
- * @prev EncryptMessage
- */
-message EncryptedMessage {
- optional bytes nonce = 1; // nonce used during encryption
- optional bytes message = 2; // encrypted message
- optional bytes hmac = 3; // message hmac
-}
-
-/**
- * Request: Ask device to decrypt message
- * @next Success
- * @next Failure
- */
-message DecryptMessage {
- repeated uint32 address_n = 1; // BIP-32 path to derive the decryption key from master node
- optional bytes nonce = 2; // nonce used during encryption
- optional bytes message = 3; // message to decrypt
- optional bytes hmac = 4; // message hmac
-}
-
-/**
- * Response: Decrypted message
- * @prev DecryptedMessage
- */
-message DecryptedMessage {
- optional bytes message = 1; // decrypted message
- optional string address = 2; // address used to sign the message (if used)
-}
-
-/**
- * Request: Ask device to encrypt or decrypt value of given key
- * @next CipheredKeyValue
- * @next Failure
- */
-message CipherKeyValue {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- optional string key = 2; // key component of key:value
- optional bytes value = 3; // value component of key:value
- optional bool encrypt = 4; // are we encrypting (True) or decrypting (False)?
- optional bool ask_on_encrypt = 5; // should we ask on encrypt operation?
- optional bool ask_on_decrypt = 6; // should we ask on decrypt operation?
- optional bytes iv = 7; // initialization vector (will be computed if not set)
-}
-
-/**
- * Response: Return ciphered/deciphered value
- * @prev CipherKeyValue
- */
-message CipheredKeyValue {
- optional bytes value = 1; // ciphered/deciphered value
-}
-
-//////////////////////////////////
-// Transaction signing messages //
-//////////////////////////////////
-
-/**
- * Request: Estimated size of the transaction
- * This behaves exactly like SignTx, which means that it can ask using TxRequest
- * This call is non-blocking (except possible PassphraseRequest to unlock the seed)
- * @next TxSize
- * @next Failure
- */
-message EstimateTxSize {
- required uint32 outputs_count = 1; // number of transaction outputs
- required uint32 inputs_count = 2; // number of transaction inputs
- optional string coin_name = 3 [default='Bitcoin']; // coin to use
-}
-
-/**
- * Response: Estimated size of the transaction
- * @prev EstimateTxSize
- */
-message TxSize {
- optional uint32 tx_size = 1; // estimated size of transaction in bytes
-}
-
-/**
- * Request: Ask device to sign transaction
- * @next PassphraseRequest
- * @next PinMatrixRequest
- * @next TxRequest
- * @next Failure
- */
-message SignTx {
- required uint32 outputs_count = 1; // number of transaction outputs
- required uint32 inputs_count = 2; // number of transaction inputs
- optional string coin_name = 3 [default='Bitcoin']; // coin to use
- optional uint32 version = 4 [default=1]; // transaction version
- optional uint32 lock_time = 5 [default=0]; // transaction lock_time
-}
-
-/**
- * Request: Simplified transaction signing
- * This method doesn't support streaming, so there are hardware limits in number of inputs and outputs.
- * In case of success, the result is returned using TxRequest message.
- * @next PassphraseRequest
- * @next PinMatrixRequest
- * @next TxRequest
- * @next Failure
- */
-message SimpleSignTx {
- repeated TxInputType inputs = 1; // transaction inputs
- repeated TxOutputType outputs = 2; // transaction outputs
- repeated TransactionType transactions = 3; // transactions whose outputs are used to build current inputs
- optional string coin_name = 4 [default='Bitcoin']; // coin to use
- optional uint32 version = 5 [default=1]; // transaction version
- optional uint32 lock_time = 6 [default=0]; // transaction lock_time
-}
-
-/**
- * Response: Device asks for information for signing transaction or returns the last result
- * If request_index is set, device awaits TxAck message (with fields filled in according to request_type)
- * If signature_index is set, 'signature' contains signed input of signature_index's input
- * @prev SignTx
- * @prev SimpleSignTx
- * @prev TxAck
- */
-message TxRequest {
- optional RequestType request_type = 1; // what should be filled in TxAck message?
- optional TxRequestDetailsType details = 2; // request for tx details
- optional TxRequestSerializedType serialized = 3; // serialized data and request for next
-}
-
-/**
- * Request: Reported transaction data
- * @prev TxRequest
- * @next TxRequest
- */
-message TxAck {
- optional TransactionType tx = 1;
-}
-
-/**
- * Request: Ask device to sign transaction
- * All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
- * Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
- * @next PassphraseRequest
- * @next PinMatrixRequest
- * @next EthereumTxRequest
- * @next Failure
- */
-message EthereumSignTx {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- optional bytes nonce = 2; // <=256 bit unsigned big endian
- optional bytes gas_price = 3; // <=256 bit unsigned big endian (in wei)
- optional bytes gas_limit = 4; // <=256 bit unsigned big endian
- optional bytes to = 5; // 160 bit address hash
- optional bytes value = 6; // <=256 bit unsigned big endian (in wei)
- optional bytes data_initial_chunk = 7; // The initial data chunk (<= 1024 bytes)
- optional uint32 data_length = 8; // Length of transaction payload
- optional uint32 chain_id = 9; // Chain Id for EIP 155
-}
-
-/**
- * Response: Device asks for more data from transaction payload, or returns the signature.
- * If data_length is set, device awaits that many more bytes of payload.
- * Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
- * @prev EthereumSignTx
- * @next EthereumTxAck
- */
-message EthereumTxRequest {
- optional uint32 data_length = 1; // Number of bytes being requested (<= 1024)
- optional uint32 signature_v = 2; // Computed signature (recovery parameter, limited to 27 or 28)
- optional bytes signature_r = 3; // Computed signature R component (256 bit)
- optional bytes signature_s = 4; // Computed signature S component (256 bit)
-}
-
-/**
- * Request: Transaction payload data.
- * @prev EthereumTxRequest
- * @next EthereumTxRequest
- */
-message EthereumTxAck {
- optional bytes data_chunk = 1; // Bytes from transaction payload (<= 1024 bytes)
-}
-
-////////////////////////////////////////
-// Ethereum: Message signing messages //
-////////////////////////////////////////
-
-/**
- * Request: Ask device to sign message
- * @next EthereumMessageSignature
- * @next Failure
- */
-message EthereumSignMessage {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- required bytes message = 2; // message to be signed
-}
-
-/**
- * Request: Ask device to verify message
- * @next Success
- * @next Failure
- */
-message EthereumVerifyMessage {
- optional bytes address = 1; // address to verify
- optional bytes signature = 2; // signature to verify
- optional bytes message = 3; // message to verify
-}
-
-/**
- * Response: Signed message
- * @prev EthereumSignMessage
- */
-message EthereumMessageSignature {
- optional bytes address = 1; // address used to sign the message
- optional bytes signature = 2; // signature of the message
-}
-
-///////////////////////
-// Identity messages //
-///////////////////////
-
-/**
- * Request: Ask device to sign identity
- * @next SignedIdentity
- * @next Failure
- */
-message SignIdentity {
- optional IdentityType identity = 1; // identity
- optional bytes challenge_hidden = 2; // non-visible challenge
- optional string challenge_visual = 3; // challenge shown on display (e.g. date+time)
- optional string ecdsa_curve_name = 4; // ECDSA curve name to use
-}
-
-/**
- * Response: Device provides signed identity
- * @prev SignIdentity
- */
-message SignedIdentity {
- optional string address = 1; // identity address
- optional bytes public_key = 2; // identity public key
- optional bytes signature = 3; // signature of the identity data
-}
-
-///////////////////
-// ECDH messages //
-///////////////////
-
-/**
- * Request: Ask device to generate ECDH session key
- * @next ECDHSessionKey
- * @next Failure
- */
-message GetECDHSessionKey {
- optional IdentityType identity = 1; // identity
- optional bytes peer_public_key = 2; // peer's public key
- optional string ecdsa_curve_name = 3; // ECDSA curve name to use
-}
-
-/**
- * Response: Device provides ECDH session key
- * @prev GetECDHSessionKey
- */
-message ECDHSessionKey {
- optional bytes session_key = 1; // ECDH session key
-}
-
-///////////////////
-// U2F messages //
-///////////////////
-
-/**
- * Request: Set U2F counter
- * @next Success
- */
-message SetU2FCounter {
- optional uint32 u2f_counter = 1; // counter
-}
-
-/////////////////////////
-// Bootloader messages //
-/////////////////////////
-
-/**
- * Request: Ask device to erase its firmware (so it can be replaced via FirmwareUpload)
- * @next Success
- * @next FirmwareRequest
- * @next Failure
- */
-message FirmwareErase {
- optional uint32 length = 1; // length of new firmware
-}
-
-/**
- * Response: Ask for firmware chunk
- * @next FirmwareUpload
- */
-message FirmwareRequest {
- optional uint32 offset = 1; // offset of requested firmware chunk
- optional uint32 length = 2; // length of requested firmware chunk
-}
-
-/**
- * Request: Send firmware in binary form to the device
- * @next Success
- * @next Failure
- */
-message FirmwareUpload {
- required bytes payload = 1; // firmware to be loaded into device
- optional bytes hash = 2; // hash of the payload
-}
-
-
-/**
- * Request: Perform a device self-test
- * @next Success
- * @next Failure
- */
-message SelfTest {
- optional bytes payload = 1; // payload to be used in self-test
-}
-
-/////////////////////////////////////////////////////////////
-// Debug messages (only available if DebugLink is enabled) //
-/////////////////////////////////////////////////////////////
-
-/**
- * Request: "Press" the button on the device
- * @next Success
- */
-message DebugLinkDecision {
- required bool yes_no = 1; // true for "Confirm", false for "Cancel"
-}
-
-/**
- * Request: Computer asks for device state
- * @next DebugLinkState
- */
-message DebugLinkGetState {
-}
-
-/**
- * Response: Device current state
- * @prev DebugLinkGetState
- */
-message DebugLinkState {
- optional bytes layout = 1; // raw buffer of display
- optional string pin = 2; // current PIN, blank if PIN is not set/enabled
- optional string matrix = 3; // current PIN matrix
- optional string mnemonic = 4; // current BIP-39 mnemonic
- optional HDNodeType node = 5; // current BIP-32 node
- optional bool passphrase_protection = 6; // is node/mnemonic encrypted using passphrase?
- optional string reset_word = 7; // word on device display during ResetDevice workflow
- optional bytes reset_entropy = 8; // current entropy during ResetDevice workflow
- optional string recovery_fake_word = 9; // (fake) word on display during RecoveryDevice workflow
- optional uint32 recovery_word_pos = 10; // index of mnemonic word the device is expecting during RecoveryDevice workflow
-}
-
-/**
- * Request: Ask device to restart
- */
-message DebugLinkStop {
-}
-
-/**
- * Response: Device wants host to log event
- */
-message DebugLinkLog {
- optional uint32 level = 1;
- optional string bucket = 2;
- optional string text = 3;
-}
-
-/**
- * Request: Read memory from device
- * @next DebugLinkMemory
- */
-message DebugLinkMemoryRead {
- optional uint32 address = 1;
- optional uint32 length = 2;
-}
-
-/**
- * Response: Device sends memory back
- * @prev DebugLinkMemoryRead
- */
-message DebugLinkMemory {
- optional bytes memory = 1;
-}
-
-/**
- * Request: Write memory to device.
- * WARNING: Writing to the wrong location can irreparably break the device.
- */
-message DebugLinkMemoryWrite {
- optional uint32 address = 1;
- optional bytes memory = 2;
- optional bool flash = 3;
-}
-
-/**
- * Request: Erase block of flash on device
- * WARNING: Writing to the wrong location can irreparably break the device.
- */
-message DebugLinkFlashErase {
- optional uint32 sector = 1;
-}
diff --git a/accounts/usbwallet/internal/trezor/trezor.go b/accounts/usbwallet/internal/trezor/trezor.go
deleted file mode 100644
index 80cc75efc..000000000
--- a/accounts/usbwallet/internal/trezor/trezor.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2017 The go-ethereum Authors
-// This file is part of the go-ethereum library.
-//
-// The go-ethereum library is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Lesser General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// The go-ethereum library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public License
-// along with the go-ethereum library. If not, see .
-
-// This file contains the implementation for interacting with the Trezor hardware
-// wallets. The wire protocol spec can be found on the SatoshiLabs website:
-// https://doc.satoshilabs.com/trezor-tech/api-protobuf.html
-
-//go:generate protoc --go_out=import_path=trezor:. types.proto messages.proto
-
-// Package trezor contains the wire protocol wrapper in Go.
-package trezor
-
-import (
- "reflect"
-
- "github.com/golang/protobuf/proto"
-)
-
-// Type returns the protocol buffer type number of a specific message. If the
-// message is nil, this method panics!
-func Type(msg proto.Message) uint16 {
- return uint16(MessageType_value["MessageType_"+reflect.TypeOf(msg).Elem().Name()])
-}
-
-// Name returns the friendly message type name of a specific protocol buffer
-// type number.
-func Name(kind uint16) string {
- name := MessageType_name[int32(kind)]
- if len(name) < 12 {
- return name
- }
- return name[12:]
-}
diff --git a/accounts/usbwallet/internal/trezor/types.pb.go b/accounts/usbwallet/internal/trezor/types.pb.go
deleted file mode 100644
index 25b7672d2..000000000
--- a/accounts/usbwallet/internal/trezor/types.pb.go
+++ /dev/null
@@ -1,1333 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: types.proto
-
-/*
-Package trezor is a generated protocol buffer package.
-
-It is generated from these files:
- types.proto
- messages.proto
-
-It has these top-level messages:
- HDNodeType
- HDNodePathType
- CoinType
- MultisigRedeemScriptType
- TxInputType
- TxOutputType
- TxOutputBinType
- TransactionType
- TxRequestDetailsType
- TxRequestSerializedType
- IdentityType
- Initialize
- GetFeatures
- Features
- ClearSession
- ApplySettings
- ApplyFlags
- ChangePin
- Ping
- Success
- Failure
- ButtonRequest
- ButtonAck
- PinMatrixRequest
- PinMatrixAck
- Cancel
- PassphraseRequest
- PassphraseAck
- GetEntropy
- Entropy
- GetPublicKey
- PublicKey
- GetAddress
- EthereumGetAddress
- Address
- EthereumAddress
- WipeDevice
- LoadDevice
- ResetDevice
- BackupDevice
- EntropyRequest
- EntropyAck
- RecoveryDevice
- WordRequest
- WordAck
- SignMessage
- VerifyMessage
- MessageSignature
- EncryptMessage
- EncryptedMessage
- DecryptMessage
- DecryptedMessage
- CipherKeyValue
- CipheredKeyValue
- EstimateTxSize
- TxSize
- SignTx
- SimpleSignTx
- TxRequest
- TxAck
- EthereumSignTx
- EthereumTxRequest
- EthereumTxAck
- EthereumSignMessage
- EthereumVerifyMessage
- EthereumMessageSignature
- SignIdentity
- SignedIdentity
- GetECDHSessionKey
- ECDHSessionKey
- SetU2FCounter
- FirmwareErase
- FirmwareRequest
- FirmwareUpload
- SelfTest
- DebugLinkDecision
- DebugLinkGetState
- DebugLinkState
- DebugLinkStop
- DebugLinkLog
- DebugLinkMemoryRead
- DebugLinkMemory
- DebugLinkMemoryWrite
- DebugLinkFlashErase
-*/
-package trezor
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// *
-// Type of failures returned by Failure message
-// @used_in Failure
-type FailureType int32
-
-const (
- FailureType_Failure_UnexpectedMessage FailureType = 1
- FailureType_Failure_ButtonExpected FailureType = 2
- FailureType_Failure_DataError FailureType = 3
- FailureType_Failure_ActionCancelled FailureType = 4
- FailureType_Failure_PinExpected FailureType = 5
- FailureType_Failure_PinCancelled FailureType = 6
- FailureType_Failure_PinInvalid FailureType = 7
- FailureType_Failure_InvalidSignature FailureType = 8
- FailureType_Failure_ProcessError FailureType = 9
- FailureType_Failure_NotEnoughFunds FailureType = 10
- FailureType_Failure_NotInitialized FailureType = 11
- FailureType_Failure_FirmwareError FailureType = 99
-)
-
-var FailureType_name = map[int32]string{
- 1: "Failure_UnexpectedMessage",
- 2: "Failure_ButtonExpected",
- 3: "Failure_DataError",
- 4: "Failure_ActionCancelled",
- 5: "Failure_PinExpected",
- 6: "Failure_PinCancelled",
- 7: "Failure_PinInvalid",
- 8: "Failure_InvalidSignature",
- 9: "Failure_ProcessError",
- 10: "Failure_NotEnoughFunds",
- 11: "Failure_NotInitialized",
- 99: "Failure_FirmwareError",
-}
-var FailureType_value = map[string]int32{
- "Failure_UnexpectedMessage": 1,
- "Failure_ButtonExpected": 2,
- "Failure_DataError": 3,
- "Failure_ActionCancelled": 4,
- "Failure_PinExpected": 5,
- "Failure_PinCancelled": 6,
- "Failure_PinInvalid": 7,
- "Failure_InvalidSignature": 8,
- "Failure_ProcessError": 9,
- "Failure_NotEnoughFunds": 10,
- "Failure_NotInitialized": 11,
- "Failure_FirmwareError": 99,
-}
-
-func (x FailureType) Enum() *FailureType {
- p := new(FailureType)
- *p = x
- return p
-}
-func (x FailureType) String() string {
- return proto.EnumName(FailureType_name, int32(x))
-}
-func (x *FailureType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FailureType_value, data, "FailureType")
- if err != nil {
- return err
- }
- *x = FailureType(value)
- return nil
-}
-func (FailureType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-
-// *
-// Type of script which will be used for transaction output
-// @used_in TxOutputType
-type OutputScriptType int32
-
-const (
- OutputScriptType_PAYTOADDRESS OutputScriptType = 0
- OutputScriptType_PAYTOSCRIPTHASH OutputScriptType = 1
- OutputScriptType_PAYTOMULTISIG OutputScriptType = 2
- OutputScriptType_PAYTOOPRETURN OutputScriptType = 3
- OutputScriptType_PAYTOWITNESS OutputScriptType = 4
- OutputScriptType_PAYTOP2SHWITNESS OutputScriptType = 5
-)
-
-var OutputScriptType_name = map[int32]string{
- 0: "PAYTOADDRESS",
- 1: "PAYTOSCRIPTHASH",
- 2: "PAYTOMULTISIG",
- 3: "PAYTOOPRETURN",
- 4: "PAYTOWITNESS",
- 5: "PAYTOP2SHWITNESS",
-}
-var OutputScriptType_value = map[string]int32{
- "PAYTOADDRESS": 0,
- "PAYTOSCRIPTHASH": 1,
- "PAYTOMULTISIG": 2,
- "PAYTOOPRETURN": 3,
- "PAYTOWITNESS": 4,
- "PAYTOP2SHWITNESS": 5,
-}
-
-func (x OutputScriptType) Enum() *OutputScriptType {
- p := new(OutputScriptType)
- *p = x
- return p
-}
-func (x OutputScriptType) String() string {
- return proto.EnumName(OutputScriptType_name, int32(x))
-}
-func (x *OutputScriptType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(OutputScriptType_value, data, "OutputScriptType")
- if err != nil {
- return err
- }
- *x = OutputScriptType(value)
- return nil
-}
-func (OutputScriptType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
-
-// *
-// Type of script which will be used for transaction output
-// @used_in TxInputType
-type InputScriptType int32
-
-const (
- InputScriptType_SPENDADDRESS InputScriptType = 0
- InputScriptType_SPENDMULTISIG InputScriptType = 1
- InputScriptType_EXTERNAL InputScriptType = 2
- InputScriptType_SPENDWITNESS InputScriptType = 3
- InputScriptType_SPENDP2SHWITNESS InputScriptType = 4
-)
-
-var InputScriptType_name = map[int32]string{
- 0: "SPENDADDRESS",
- 1: "SPENDMULTISIG",
- 2: "EXTERNAL",
- 3: "SPENDWITNESS",
- 4: "SPENDP2SHWITNESS",
-}
-var InputScriptType_value = map[string]int32{
- "SPENDADDRESS": 0,
- "SPENDMULTISIG": 1,
- "EXTERNAL": 2,
- "SPENDWITNESS": 3,
- "SPENDP2SHWITNESS": 4,
-}
-
-func (x InputScriptType) Enum() *InputScriptType {
- p := new(InputScriptType)
- *p = x
- return p
-}
-func (x InputScriptType) String() string {
- return proto.EnumName(InputScriptType_name, int32(x))
-}
-func (x *InputScriptType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(InputScriptType_value, data, "InputScriptType")
- if err != nil {
- return err
- }
- *x = InputScriptType(value)
- return nil
-}
-func (InputScriptType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
-
-// *
-// Type of information required by transaction signing process
-// @used_in TxRequest
-type RequestType int32
-
-const (
- RequestType_TXINPUT RequestType = 0
- RequestType_TXOUTPUT RequestType = 1
- RequestType_TXMETA RequestType = 2
- RequestType_TXFINISHED RequestType = 3
- RequestType_TXEXTRADATA RequestType = 4
-)
-
-var RequestType_name = map[int32]string{
- 0: "TXINPUT",
- 1: "TXOUTPUT",
- 2: "TXMETA",
- 3: "TXFINISHED",
- 4: "TXEXTRADATA",
-}
-var RequestType_value = map[string]int32{
- "TXINPUT": 0,
- "TXOUTPUT": 1,
- "TXMETA": 2,
- "TXFINISHED": 3,
- "TXEXTRADATA": 4,
-}
-
-func (x RequestType) Enum() *RequestType {
- p := new(RequestType)
- *p = x
- return p
-}
-func (x RequestType) String() string {
- return proto.EnumName(RequestType_name, int32(x))
-}
-func (x *RequestType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(RequestType_value, data, "RequestType")
- if err != nil {
- return err
- }
- *x = RequestType(value)
- return nil
-}
-func (RequestType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
-
-// *
-// Type of button request
-// @used_in ButtonRequest
-type ButtonRequestType int32
-
-const (
- ButtonRequestType_ButtonRequest_Other ButtonRequestType = 1
- ButtonRequestType_ButtonRequest_FeeOverThreshold ButtonRequestType = 2
- ButtonRequestType_ButtonRequest_ConfirmOutput ButtonRequestType = 3
- ButtonRequestType_ButtonRequest_ResetDevice ButtonRequestType = 4
- ButtonRequestType_ButtonRequest_ConfirmWord ButtonRequestType = 5
- ButtonRequestType_ButtonRequest_WipeDevice ButtonRequestType = 6
- ButtonRequestType_ButtonRequest_ProtectCall ButtonRequestType = 7
- ButtonRequestType_ButtonRequest_SignTx ButtonRequestType = 8
- ButtonRequestType_ButtonRequest_FirmwareCheck ButtonRequestType = 9
- ButtonRequestType_ButtonRequest_Address ButtonRequestType = 10
- ButtonRequestType_ButtonRequest_PublicKey ButtonRequestType = 11
-)
-
-var ButtonRequestType_name = map[int32]string{
- 1: "ButtonRequest_Other",
- 2: "ButtonRequest_FeeOverThreshold",
- 3: "ButtonRequest_ConfirmOutput",
- 4: "ButtonRequest_ResetDevice",
- 5: "ButtonRequest_ConfirmWord",
- 6: "ButtonRequest_WipeDevice",
- 7: "ButtonRequest_ProtectCall",
- 8: "ButtonRequest_SignTx",
- 9: "ButtonRequest_FirmwareCheck",
- 10: "ButtonRequest_Address",
- 11: "ButtonRequest_PublicKey",
-}
-var ButtonRequestType_value = map[string]int32{
- "ButtonRequest_Other": 1,
- "ButtonRequest_FeeOverThreshold": 2,
- "ButtonRequest_ConfirmOutput": 3,
- "ButtonRequest_ResetDevice": 4,
- "ButtonRequest_ConfirmWord": 5,
- "ButtonRequest_WipeDevice": 6,
- "ButtonRequest_ProtectCall": 7,
- "ButtonRequest_SignTx": 8,
- "ButtonRequest_FirmwareCheck": 9,
- "ButtonRequest_Address": 10,
- "ButtonRequest_PublicKey": 11,
-}
-
-func (x ButtonRequestType) Enum() *ButtonRequestType {
- p := new(ButtonRequestType)
- *p = x
- return p
-}
-func (x ButtonRequestType) String() string {
- return proto.EnumName(ButtonRequestType_name, int32(x))
-}
-func (x *ButtonRequestType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(ButtonRequestType_value, data, "ButtonRequestType")
- if err != nil {
- return err
- }
- *x = ButtonRequestType(value)
- return nil
-}
-func (ButtonRequestType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
-
-// *
-// Type of PIN request
-// @used_in PinMatrixRequest
-type PinMatrixRequestType int32
-
-const (
- PinMatrixRequestType_PinMatrixRequestType_Current PinMatrixRequestType = 1
- PinMatrixRequestType_PinMatrixRequestType_NewFirst PinMatrixRequestType = 2
- PinMatrixRequestType_PinMatrixRequestType_NewSecond PinMatrixRequestType = 3
-)
-
-var PinMatrixRequestType_name = map[int32]string{
- 1: "PinMatrixRequestType_Current",
- 2: "PinMatrixRequestType_NewFirst",
- 3: "PinMatrixRequestType_NewSecond",
-}
-var PinMatrixRequestType_value = map[string]int32{
- "PinMatrixRequestType_Current": 1,
- "PinMatrixRequestType_NewFirst": 2,
- "PinMatrixRequestType_NewSecond": 3,
-}
-
-func (x PinMatrixRequestType) Enum() *PinMatrixRequestType {
- p := new(PinMatrixRequestType)
- *p = x
- return p
-}
-func (x PinMatrixRequestType) String() string {
- return proto.EnumName(PinMatrixRequestType_name, int32(x))
-}
-func (x *PinMatrixRequestType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(PinMatrixRequestType_value, data, "PinMatrixRequestType")
- if err != nil {
- return err
- }
- *x = PinMatrixRequestType(value)
- return nil
-}
-func (PinMatrixRequestType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
-
-// *
-// Type of recovery procedure. These should be used as bitmask, e.g.,
-// `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix`
-// listing every method supported by the host computer.
-//
-// Note that ScrambledWords must be supported by every implementation
-// for backward compatibility; there is no way to not support it.
-//
-// @used_in RecoveryDevice
-type RecoveryDeviceType int32
-
-const (
- // use powers of two when extending this field
- RecoveryDeviceType_RecoveryDeviceType_ScrambledWords RecoveryDeviceType = 0
- RecoveryDeviceType_RecoveryDeviceType_Matrix RecoveryDeviceType = 1
-)
-
-var RecoveryDeviceType_name = map[int32]string{
- 0: "RecoveryDeviceType_ScrambledWords",
- 1: "RecoveryDeviceType_Matrix",
-}
-var RecoveryDeviceType_value = map[string]int32{
- "RecoveryDeviceType_ScrambledWords": 0,
- "RecoveryDeviceType_Matrix": 1,
-}
-
-func (x RecoveryDeviceType) Enum() *RecoveryDeviceType {
- p := new(RecoveryDeviceType)
- *p = x
- return p
-}
-func (x RecoveryDeviceType) String() string {
- return proto.EnumName(RecoveryDeviceType_name, int32(x))
-}
-func (x *RecoveryDeviceType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(RecoveryDeviceType_value, data, "RecoveryDeviceType")
- if err != nil {
- return err
- }
- *x = RecoveryDeviceType(value)
- return nil
-}
-func (RecoveryDeviceType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
-
-// *
-// Type of Recovery Word request
-// @used_in WordRequest
-type WordRequestType int32
-
-const (
- WordRequestType_WordRequestType_Plain WordRequestType = 0
- WordRequestType_WordRequestType_Matrix9 WordRequestType = 1
- WordRequestType_WordRequestType_Matrix6 WordRequestType = 2
-)
-
-var WordRequestType_name = map[int32]string{
- 0: "WordRequestType_Plain",
- 1: "WordRequestType_Matrix9",
- 2: "WordRequestType_Matrix6",
-}
-var WordRequestType_value = map[string]int32{
- "WordRequestType_Plain": 0,
- "WordRequestType_Matrix9": 1,
- "WordRequestType_Matrix6": 2,
-}
-
-func (x WordRequestType) Enum() *WordRequestType {
- p := new(WordRequestType)
- *p = x
- return p
-}
-func (x WordRequestType) String() string {
- return proto.EnumName(WordRequestType_name, int32(x))
-}
-func (x *WordRequestType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(WordRequestType_value, data, "WordRequestType")
- if err != nil {
- return err
- }
- *x = WordRequestType(value)
- return nil
-}
-func (WordRequestType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
-
-// *
-// Structure representing BIP32 (hierarchical deterministic) node
-// Used for imports of private key into the device and exporting public key out of device
-// @used_in PublicKey
-// @used_in LoadDevice
-// @used_in DebugLinkState
-// @used_in Storage
-type HDNodeType struct {
- Depth *uint32 `protobuf:"varint,1,req,name=depth" json:"depth,omitempty"`
- Fingerprint *uint32 `protobuf:"varint,2,req,name=fingerprint" json:"fingerprint,omitempty"`
- ChildNum *uint32 `protobuf:"varint,3,req,name=child_num,json=childNum" json:"child_num,omitempty"`
- ChainCode []byte `protobuf:"bytes,4,req,name=chain_code,json=chainCode" json:"chain_code,omitempty"`
- PrivateKey []byte `protobuf:"bytes,5,opt,name=private_key,json=privateKey" json:"private_key,omitempty"`
- PublicKey []byte `protobuf:"bytes,6,opt,name=public_key,json=publicKey" json:"public_key,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *HDNodeType) Reset() { *m = HDNodeType{} }
-func (m *HDNodeType) String() string { return proto.CompactTextString(m) }
-func (*HDNodeType) ProtoMessage() {}
-func (*HDNodeType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-
-func (m *HDNodeType) GetDepth() uint32 {
- if m != nil && m.Depth != nil {
- return *m.Depth
- }
- return 0
-}
-
-func (m *HDNodeType) GetFingerprint() uint32 {
- if m != nil && m.Fingerprint != nil {
- return *m.Fingerprint
- }
- return 0
-}
-
-func (m *HDNodeType) GetChildNum() uint32 {
- if m != nil && m.ChildNum != nil {
- return *m.ChildNum
- }
- return 0
-}
-
-func (m *HDNodeType) GetChainCode() []byte {
- if m != nil {
- return m.ChainCode
- }
- return nil
-}
-
-func (m *HDNodeType) GetPrivateKey() []byte {
- if m != nil {
- return m.PrivateKey
- }
- return nil
-}
-
-func (m *HDNodeType) GetPublicKey() []byte {
- if m != nil {
- return m.PublicKey
- }
- return nil
-}
-
-type HDNodePathType struct {
- Node *HDNodeType `protobuf:"bytes,1,req,name=node" json:"node,omitempty"`
- AddressN []uint32 `protobuf:"varint,2,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *HDNodePathType) Reset() { *m = HDNodePathType{} }
-func (m *HDNodePathType) String() string { return proto.CompactTextString(m) }
-func (*HDNodePathType) ProtoMessage() {}
-func (*HDNodePathType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
-
-func (m *HDNodePathType) GetNode() *HDNodeType {
- if m != nil {
- return m.Node
- }
- return nil
-}
-
-func (m *HDNodePathType) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-// *
-// Structure representing Coin
-// @used_in Features
-type CoinType struct {
- CoinName *string `protobuf:"bytes,1,opt,name=coin_name,json=coinName" json:"coin_name,omitempty"`
- CoinShortcut *string `protobuf:"bytes,2,opt,name=coin_shortcut,json=coinShortcut" json:"coin_shortcut,omitempty"`
- AddressType *uint32 `protobuf:"varint,3,opt,name=address_type,json=addressType,def=0" json:"address_type,omitempty"`
- MaxfeeKb *uint64 `protobuf:"varint,4,opt,name=maxfee_kb,json=maxfeeKb" json:"maxfee_kb,omitempty"`
- AddressTypeP2Sh *uint32 `protobuf:"varint,5,opt,name=address_type_p2sh,json=addressTypeP2sh,def=5" json:"address_type_p2sh,omitempty"`
- SignedMessageHeader *string `protobuf:"bytes,8,opt,name=signed_message_header,json=signedMessageHeader" json:"signed_message_header,omitempty"`
- XpubMagic *uint32 `protobuf:"varint,9,opt,name=xpub_magic,json=xpubMagic,def=76067358" json:"xpub_magic,omitempty"`
- XprvMagic *uint32 `protobuf:"varint,10,opt,name=xprv_magic,json=xprvMagic,def=76066276" json:"xprv_magic,omitempty"`
- Segwit *bool `protobuf:"varint,11,opt,name=segwit" json:"segwit,omitempty"`
- Forkid *uint32 `protobuf:"varint,12,opt,name=forkid" json:"forkid,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CoinType) Reset() { *m = CoinType{} }
-func (m *CoinType) String() string { return proto.CompactTextString(m) }
-func (*CoinType) ProtoMessage() {}
-func (*CoinType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
-
-const Default_CoinType_AddressType uint32 = 0
-const Default_CoinType_AddressTypeP2Sh uint32 = 5
-const Default_CoinType_XpubMagic uint32 = 76067358
-const Default_CoinType_XprvMagic uint32 = 76066276
-
-func (m *CoinType) GetCoinName() string {
- if m != nil && m.CoinName != nil {
- return *m.CoinName
- }
- return ""
-}
-
-func (m *CoinType) GetCoinShortcut() string {
- if m != nil && m.CoinShortcut != nil {
- return *m.CoinShortcut
- }
- return ""
-}
-
-func (m *CoinType) GetAddressType() uint32 {
- if m != nil && m.AddressType != nil {
- return *m.AddressType
- }
- return Default_CoinType_AddressType
-}
-
-func (m *CoinType) GetMaxfeeKb() uint64 {
- if m != nil && m.MaxfeeKb != nil {
- return *m.MaxfeeKb
- }
- return 0
-}
-
-func (m *CoinType) GetAddressTypeP2Sh() uint32 {
- if m != nil && m.AddressTypeP2Sh != nil {
- return *m.AddressTypeP2Sh
- }
- return Default_CoinType_AddressTypeP2Sh
-}
-
-func (m *CoinType) GetSignedMessageHeader() string {
- if m != nil && m.SignedMessageHeader != nil {
- return *m.SignedMessageHeader
- }
- return ""
-}
-
-func (m *CoinType) GetXpubMagic() uint32 {
- if m != nil && m.XpubMagic != nil {
- return *m.XpubMagic
- }
- return Default_CoinType_XpubMagic
-}
-
-func (m *CoinType) GetXprvMagic() uint32 {
- if m != nil && m.XprvMagic != nil {
- return *m.XprvMagic
- }
- return Default_CoinType_XprvMagic
-}
-
-func (m *CoinType) GetSegwit() bool {
- if m != nil && m.Segwit != nil {
- return *m.Segwit
- }
- return false
-}
-
-func (m *CoinType) GetForkid() uint32 {
- if m != nil && m.Forkid != nil {
- return *m.Forkid
- }
- return 0
-}
-
-// *
-// Type of redeem script used in input
-// @used_in TxInputType
-type MultisigRedeemScriptType struct {
- Pubkeys []*HDNodePathType `protobuf:"bytes,1,rep,name=pubkeys" json:"pubkeys,omitempty"`
- Signatures [][]byte `protobuf:"bytes,2,rep,name=signatures" json:"signatures,omitempty"`
- M *uint32 `protobuf:"varint,3,opt,name=m" json:"m,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MultisigRedeemScriptType) Reset() { *m = MultisigRedeemScriptType{} }
-func (m *MultisigRedeemScriptType) String() string { return proto.CompactTextString(m) }
-func (*MultisigRedeemScriptType) ProtoMessage() {}
-func (*MultisigRedeemScriptType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
-
-func (m *MultisigRedeemScriptType) GetPubkeys() []*HDNodePathType {
- if m != nil {
- return m.Pubkeys
- }
- return nil
-}
-
-func (m *MultisigRedeemScriptType) GetSignatures() [][]byte {
- if m != nil {
- return m.Signatures
- }
- return nil
-}
-
-func (m *MultisigRedeemScriptType) GetM() uint32 {
- if m != nil && m.M != nil {
- return *m.M
- }
- return 0
-}
-
-// *
-// Structure representing transaction input
-// @used_in SimpleSignTx
-// @used_in TransactionType
-type TxInputType struct {
- AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- PrevHash []byte `protobuf:"bytes,2,req,name=prev_hash,json=prevHash" json:"prev_hash,omitempty"`
- PrevIndex *uint32 `protobuf:"varint,3,req,name=prev_index,json=prevIndex" json:"prev_index,omitempty"`
- ScriptSig []byte `protobuf:"bytes,4,opt,name=script_sig,json=scriptSig" json:"script_sig,omitempty"`
- Sequence *uint32 `protobuf:"varint,5,opt,name=sequence,def=4294967295" json:"sequence,omitempty"`
- ScriptType *InputScriptType `protobuf:"varint,6,opt,name=script_type,json=scriptType,enum=InputScriptType,def=0" json:"script_type,omitempty"`
- Multisig *MultisigRedeemScriptType `protobuf:"bytes,7,opt,name=multisig" json:"multisig,omitempty"`
- Amount *uint64 `protobuf:"varint,8,opt,name=amount" json:"amount,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxInputType) Reset() { *m = TxInputType{} }
-func (m *TxInputType) String() string { return proto.CompactTextString(m) }
-func (*TxInputType) ProtoMessage() {}
-func (*TxInputType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
-
-const Default_TxInputType_Sequence uint32 = 4294967295
-const Default_TxInputType_ScriptType InputScriptType = InputScriptType_SPENDADDRESS
-
-func (m *TxInputType) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *TxInputType) GetPrevHash() []byte {
- if m != nil {
- return m.PrevHash
- }
- return nil
-}
-
-func (m *TxInputType) GetPrevIndex() uint32 {
- if m != nil && m.PrevIndex != nil {
- return *m.PrevIndex
- }
- return 0
-}
-
-func (m *TxInputType) GetScriptSig() []byte {
- if m != nil {
- return m.ScriptSig
- }
- return nil
-}
-
-func (m *TxInputType) GetSequence() uint32 {
- if m != nil && m.Sequence != nil {
- return *m.Sequence
- }
- return Default_TxInputType_Sequence
-}
-
-func (m *TxInputType) GetScriptType() InputScriptType {
- if m != nil && m.ScriptType != nil {
- return *m.ScriptType
- }
- return Default_TxInputType_ScriptType
-}
-
-func (m *TxInputType) GetMultisig() *MultisigRedeemScriptType {
- if m != nil {
- return m.Multisig
- }
- return nil
-}
-
-func (m *TxInputType) GetAmount() uint64 {
- if m != nil && m.Amount != nil {
- return *m.Amount
- }
- return 0
-}
-
-// *
-// Structure representing transaction output
-// @used_in SimpleSignTx
-// @used_in TransactionType
-type TxOutputType struct {
- Address *string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- AddressN []uint32 `protobuf:"varint,2,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
- Amount *uint64 `protobuf:"varint,3,req,name=amount" json:"amount,omitempty"`
- ScriptType *OutputScriptType `protobuf:"varint,4,req,name=script_type,json=scriptType,enum=OutputScriptType" json:"script_type,omitempty"`
- Multisig *MultisigRedeemScriptType `protobuf:"bytes,5,opt,name=multisig" json:"multisig,omitempty"`
- OpReturnData []byte `protobuf:"bytes,6,opt,name=op_return_data,json=opReturnData" json:"op_return_data,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxOutputType) Reset() { *m = TxOutputType{} }
-func (m *TxOutputType) String() string { return proto.CompactTextString(m) }
-func (*TxOutputType) ProtoMessage() {}
-func (*TxOutputType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
-
-func (m *TxOutputType) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-func (m *TxOutputType) GetAddressN() []uint32 {
- if m != nil {
- return m.AddressN
- }
- return nil
-}
-
-func (m *TxOutputType) GetAmount() uint64 {
- if m != nil && m.Amount != nil {
- return *m.Amount
- }
- return 0
-}
-
-func (m *TxOutputType) GetScriptType() OutputScriptType {
- if m != nil && m.ScriptType != nil {
- return *m.ScriptType
- }
- return OutputScriptType_PAYTOADDRESS
-}
-
-func (m *TxOutputType) GetMultisig() *MultisigRedeemScriptType {
- if m != nil {
- return m.Multisig
- }
- return nil
-}
-
-func (m *TxOutputType) GetOpReturnData() []byte {
- if m != nil {
- return m.OpReturnData
- }
- return nil
-}
-
-// *
-// Structure representing compiled transaction output
-// @used_in TransactionType
-type TxOutputBinType struct {
- Amount *uint64 `protobuf:"varint,1,req,name=amount" json:"amount,omitempty"`
- ScriptPubkey []byte `protobuf:"bytes,2,req,name=script_pubkey,json=scriptPubkey" json:"script_pubkey,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxOutputBinType) Reset() { *m = TxOutputBinType{} }
-func (m *TxOutputBinType) String() string { return proto.CompactTextString(m) }
-func (*TxOutputBinType) ProtoMessage() {}
-func (*TxOutputBinType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
-
-func (m *TxOutputBinType) GetAmount() uint64 {
- if m != nil && m.Amount != nil {
- return *m.Amount
- }
- return 0
-}
-
-func (m *TxOutputBinType) GetScriptPubkey() []byte {
- if m != nil {
- return m.ScriptPubkey
- }
- return nil
-}
-
-// *
-// Structure representing transaction
-// @used_in SimpleSignTx
-type TransactionType struct {
- Version *uint32 `protobuf:"varint,1,opt,name=version" json:"version,omitempty"`
- Inputs []*TxInputType `protobuf:"bytes,2,rep,name=inputs" json:"inputs,omitempty"`
- BinOutputs []*TxOutputBinType `protobuf:"bytes,3,rep,name=bin_outputs,json=binOutputs" json:"bin_outputs,omitempty"`
- Outputs []*TxOutputType `protobuf:"bytes,5,rep,name=outputs" json:"outputs,omitempty"`
- LockTime *uint32 `protobuf:"varint,4,opt,name=lock_time,json=lockTime" json:"lock_time,omitempty"`
- InputsCnt *uint32 `protobuf:"varint,6,opt,name=inputs_cnt,json=inputsCnt" json:"inputs_cnt,omitempty"`
- OutputsCnt *uint32 `protobuf:"varint,7,opt,name=outputs_cnt,json=outputsCnt" json:"outputs_cnt,omitempty"`
- ExtraData []byte `protobuf:"bytes,8,opt,name=extra_data,json=extraData" json:"extra_data,omitempty"`
- ExtraDataLen *uint32 `protobuf:"varint,9,opt,name=extra_data_len,json=extraDataLen" json:"extra_data_len,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TransactionType) Reset() { *m = TransactionType{} }
-func (m *TransactionType) String() string { return proto.CompactTextString(m) }
-func (*TransactionType) ProtoMessage() {}
-func (*TransactionType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
-
-func (m *TransactionType) GetVersion() uint32 {
- if m != nil && m.Version != nil {
- return *m.Version
- }
- return 0
-}
-
-func (m *TransactionType) GetInputs() []*TxInputType {
- if m != nil {
- return m.Inputs
- }
- return nil
-}
-
-func (m *TransactionType) GetBinOutputs() []*TxOutputBinType {
- if m != nil {
- return m.BinOutputs
- }
- return nil
-}
-
-func (m *TransactionType) GetOutputs() []*TxOutputType {
- if m != nil {
- return m.Outputs
- }
- return nil
-}
-
-func (m *TransactionType) GetLockTime() uint32 {
- if m != nil && m.LockTime != nil {
- return *m.LockTime
- }
- return 0
-}
-
-func (m *TransactionType) GetInputsCnt() uint32 {
- if m != nil && m.InputsCnt != nil {
- return *m.InputsCnt
- }
- return 0
-}
-
-func (m *TransactionType) GetOutputsCnt() uint32 {
- if m != nil && m.OutputsCnt != nil {
- return *m.OutputsCnt
- }
- return 0
-}
-
-func (m *TransactionType) GetExtraData() []byte {
- if m != nil {
- return m.ExtraData
- }
- return nil
-}
-
-func (m *TransactionType) GetExtraDataLen() uint32 {
- if m != nil && m.ExtraDataLen != nil {
- return *m.ExtraDataLen
- }
- return 0
-}
-
-// *
-// Structure representing request details
-// @used_in TxRequest
-type TxRequestDetailsType struct {
- RequestIndex *uint32 `protobuf:"varint,1,opt,name=request_index,json=requestIndex" json:"request_index,omitempty"`
- TxHash []byte `protobuf:"bytes,2,opt,name=tx_hash,json=txHash" json:"tx_hash,omitempty"`
- ExtraDataLen *uint32 `protobuf:"varint,3,opt,name=extra_data_len,json=extraDataLen" json:"extra_data_len,omitempty"`
- ExtraDataOffset *uint32 `protobuf:"varint,4,opt,name=extra_data_offset,json=extraDataOffset" json:"extra_data_offset,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxRequestDetailsType) Reset() { *m = TxRequestDetailsType{} }
-func (m *TxRequestDetailsType) String() string { return proto.CompactTextString(m) }
-func (*TxRequestDetailsType) ProtoMessage() {}
-func (*TxRequestDetailsType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
-
-func (m *TxRequestDetailsType) GetRequestIndex() uint32 {
- if m != nil && m.RequestIndex != nil {
- return *m.RequestIndex
- }
- return 0
-}
-
-func (m *TxRequestDetailsType) GetTxHash() []byte {
- if m != nil {
- return m.TxHash
- }
- return nil
-}
-
-func (m *TxRequestDetailsType) GetExtraDataLen() uint32 {
- if m != nil && m.ExtraDataLen != nil {
- return *m.ExtraDataLen
- }
- return 0
-}
-
-func (m *TxRequestDetailsType) GetExtraDataOffset() uint32 {
- if m != nil && m.ExtraDataOffset != nil {
- return *m.ExtraDataOffset
- }
- return 0
-}
-
-// *
-// Structure representing serialized data
-// @used_in TxRequest
-type TxRequestSerializedType struct {
- SignatureIndex *uint32 `protobuf:"varint,1,opt,name=signature_index,json=signatureIndex" json:"signature_index,omitempty"`
- Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
- SerializedTx []byte `protobuf:"bytes,3,opt,name=serialized_tx,json=serializedTx" json:"serialized_tx,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *TxRequestSerializedType) Reset() { *m = TxRequestSerializedType{} }
-func (m *TxRequestSerializedType) String() string { return proto.CompactTextString(m) }
-func (*TxRequestSerializedType) ProtoMessage() {}
-func (*TxRequestSerializedType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
-
-func (m *TxRequestSerializedType) GetSignatureIndex() uint32 {
- if m != nil && m.SignatureIndex != nil {
- return *m.SignatureIndex
- }
- return 0
-}
-
-func (m *TxRequestSerializedType) GetSignature() []byte {
- if m != nil {
- return m.Signature
- }
- return nil
-}
-
-func (m *TxRequestSerializedType) GetSerializedTx() []byte {
- if m != nil {
- return m.SerializedTx
- }
- return nil
-}
-
-// *
-// Structure representing identity data
-// @used_in IdentityType
-type IdentityType struct {
- Proto *string `protobuf:"bytes,1,opt,name=proto" json:"proto,omitempty"`
- User *string `protobuf:"bytes,2,opt,name=user" json:"user,omitempty"`
- Host *string `protobuf:"bytes,3,opt,name=host" json:"host,omitempty"`
- Port *string `protobuf:"bytes,4,opt,name=port" json:"port,omitempty"`
- Path *string `protobuf:"bytes,5,opt,name=path" json:"path,omitempty"`
- Index *uint32 `protobuf:"varint,6,opt,name=index,def=0" json:"index,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *IdentityType) Reset() { *m = IdentityType{} }
-func (m *IdentityType) String() string { return proto.CompactTextString(m) }
-func (*IdentityType) ProtoMessage() {}
-func (*IdentityType) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
-
-const Default_IdentityType_Index uint32 = 0
-
-func (m *IdentityType) GetProto() string {
- if m != nil && m.Proto != nil {
- return *m.Proto
- }
- return ""
-}
-
-func (m *IdentityType) GetUser() string {
- if m != nil && m.User != nil {
- return *m.User
- }
- return ""
-}
-
-func (m *IdentityType) GetHost() string {
- if m != nil && m.Host != nil {
- return *m.Host
- }
- return ""
-}
-
-func (m *IdentityType) GetPort() string {
- if m != nil && m.Port != nil {
- return *m.Port
- }
- return ""
-}
-
-func (m *IdentityType) GetPath() string {
- if m != nil && m.Path != nil {
- return *m.Path
- }
- return ""
-}
-
-func (m *IdentityType) GetIndex() uint32 {
- if m != nil && m.Index != nil {
- return *m.Index
- }
- return Default_IdentityType_Index
-}
-
-var E_WireIn = &proto.ExtensionDesc{
- ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
- ExtensionType: (*bool)(nil),
- Field: 50002,
- Name: "wire_in",
- Tag: "varint,50002,opt,name=wire_in,json=wireIn",
- Filename: "types.proto",
-}
-
-var E_WireOut = &proto.ExtensionDesc{
- ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
- ExtensionType: (*bool)(nil),
- Field: 50003,
- Name: "wire_out",
- Tag: "varint,50003,opt,name=wire_out,json=wireOut",
- Filename: "types.proto",
-}
-
-var E_WireDebugIn = &proto.ExtensionDesc{
- ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
- ExtensionType: (*bool)(nil),
- Field: 50004,
- Name: "wire_debug_in",
- Tag: "varint,50004,opt,name=wire_debug_in,json=wireDebugIn",
- Filename: "types.proto",
-}
-
-var E_WireDebugOut = &proto.ExtensionDesc{
- ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
- ExtensionType: (*bool)(nil),
- Field: 50005,
- Name: "wire_debug_out",
- Tag: "varint,50005,opt,name=wire_debug_out,json=wireDebugOut",
- Filename: "types.proto",
-}
-
-var E_WireTiny = &proto.ExtensionDesc{
- ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
- ExtensionType: (*bool)(nil),
- Field: 50006,
- Name: "wire_tiny",
- Tag: "varint,50006,opt,name=wire_tiny,json=wireTiny",
- Filename: "types.proto",
-}
-
-var E_WireBootloader = &proto.ExtensionDesc{
- ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
- ExtensionType: (*bool)(nil),
- Field: 50007,
- Name: "wire_bootloader",
- Tag: "varint,50007,opt,name=wire_bootloader,json=wireBootloader",
- Filename: "types.proto",
-}
-
-func init() {
- proto.RegisterType((*HDNodeType)(nil), "HDNodeType")
- proto.RegisterType((*HDNodePathType)(nil), "HDNodePathType")
- proto.RegisterType((*CoinType)(nil), "CoinType")
- proto.RegisterType((*MultisigRedeemScriptType)(nil), "MultisigRedeemScriptType")
- proto.RegisterType((*TxInputType)(nil), "TxInputType")
- proto.RegisterType((*TxOutputType)(nil), "TxOutputType")
- proto.RegisterType((*TxOutputBinType)(nil), "TxOutputBinType")
- proto.RegisterType((*TransactionType)(nil), "TransactionType")
- proto.RegisterType((*TxRequestDetailsType)(nil), "TxRequestDetailsType")
- proto.RegisterType((*TxRequestSerializedType)(nil), "TxRequestSerializedType")
- proto.RegisterType((*IdentityType)(nil), "IdentityType")
- proto.RegisterEnum("FailureType", FailureType_name, FailureType_value)
- proto.RegisterEnum("OutputScriptType", OutputScriptType_name, OutputScriptType_value)
- proto.RegisterEnum("InputScriptType", InputScriptType_name, InputScriptType_value)
- proto.RegisterEnum("RequestType", RequestType_name, RequestType_value)
- proto.RegisterEnum("ButtonRequestType", ButtonRequestType_name, ButtonRequestType_value)
- proto.RegisterEnum("PinMatrixRequestType", PinMatrixRequestType_name, PinMatrixRequestType_value)
- proto.RegisterEnum("RecoveryDeviceType", RecoveryDeviceType_name, RecoveryDeviceType_value)
- proto.RegisterEnum("WordRequestType", WordRequestType_name, WordRequestType_value)
- proto.RegisterExtension(E_WireIn)
- proto.RegisterExtension(E_WireOut)
- proto.RegisterExtension(E_WireDebugIn)
- proto.RegisterExtension(E_WireDebugOut)
- proto.RegisterExtension(E_WireTiny)
- proto.RegisterExtension(E_WireBootloader)
-}
-
-func init() { proto.RegisterFile("types.proto", fileDescriptor0) }
-
-var fileDescriptor0 = []byte{
- // 1899 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x57, 0xdb, 0x72, 0x1a, 0xc9,
- 0x19, 0xf6, 0x00, 0x92, 0xe0, 0x07, 0xc4, 0xa8, 0x7d, 0xd0, 0x78, 0x6d, 0xaf, 0x31, 0x76, 0x62,
- 0x45, 0x55, 0x61, 0x77, 0xc9, 0x5a, 0x8e, 0x55, 0xa9, 0x24, 0x3a, 0xa0, 0x15, 0x65, 0x0b, 0x51,
- 0xc3, 0x28, 0x56, 0x72, 0x33, 0x35, 0xcc, 0xb4, 0xa0, 0x4b, 0x43, 0x37, 0xe9, 0xe9, 0x91, 0xd1,
- 0xde, 0xe4, 0x2a, 0xc9, 0x55, 0x5e, 0x23, 0x6f, 0x91, 0xaa, 0xbc, 0x41, 0xaa, 0x36, 0xa7, 0xcb,
- 0xbc, 0x41, 0xae, 0xf2, 0x00, 0xa9, 0x3e, 0x0c, 0x02, 0xc9, 0xde, 0xd2, 0x1d, 0xfd, 0x7d, 0xff,
- 0xf9, 0xd0, 0x3d, 0x40, 0x59, 0x5c, 0x4e, 0x70, 0xd2, 0x9c, 0x70, 0x26, 0xd8, 0x67, 0xf5, 0x21,
- 0x63, 0xc3, 0x18, 0x7f, 0xa1, 0x4e, 0x83, 0xf4, 0xec, 0x8b, 0x08, 0x27, 0x21, 0x27, 0x13, 0xc1,
- 0xb8, 0x96, 0x68, 0xfc, 0xd5, 0x02, 0x38, 0xdc, 0xef, 0xb2, 0x08, 0x7b, 0x97, 0x13, 0x8c, 0xee,
- 0xc1, 0x52, 0x84, 0x27, 0x62, 0xe4, 0x58, 0xf5, 0xdc, 0x46, 0xd5, 0xd5, 0x07, 0x54, 0x87, 0xf2,
- 0x19, 0xa1, 0x43, 0xcc, 0x27, 0x9c, 0x50, 0xe1, 0xe4, 0x14, 0x37, 0x0f, 0xa1, 0x47, 0x50, 0x0a,
- 0x47, 0x24, 0x8e, 0x7c, 0x9a, 0x8e, 0x9d, 0xbc, 0xe2, 0x8b, 0x0a, 0xe8, 0xa6, 0x63, 0xf4, 0x04,
- 0x20, 0x1c, 0x05, 0x84, 0xfa, 0x21, 0x8b, 0xb0, 0x53, 0xa8, 0xe7, 0x36, 0x2a, 0x6e, 0x49, 0x21,
- 0x7b, 0x2c, 0xc2, 0xe8, 0x29, 0x94, 0x27, 0x9c, 0x5c, 0x04, 0x02, 0xfb, 0xe7, 0xf8, 0xd2, 0x59,
- 0xaa, 0x5b, 0x1b, 0x15, 0x17, 0x0c, 0xf4, 0x16, 0x5f, 0x4a, 0xfd, 0x49, 0x3a, 0x88, 0x49, 0xa8,
- 0xf8, 0x65, 0xc5, 0x97, 0x34, 0xf2, 0x16, 0x5f, 0x36, 0xba, 0xb0, 0xaa, 0x33, 0xe8, 0x05, 0x62,
- 0xa4, 0xb2, 0x78, 0x0a, 0x05, 0x2a, 0x5d, 0xc9, 0x24, 0xca, 0xad, 0x72, 0xf3, 0x2a, 0x41, 0x57,
- 0x11, 0x32, 0xdc, 0x20, 0x8a, 0x38, 0x4e, 0x12, 0x9f, 0x3a, 0xb9, 0x7a, 0x5e, 0x86, 0x6b, 0x80,
- 0x6e, 0xe3, 0x7f, 0x39, 0x28, 0xee, 0x31, 0x42, 0x95, 0x29, 0x99, 0x18, 0x23, 0xd4, 0xa7, 0xc1,
- 0x58, 0xda, 0xb3, 0x36, 0x4a, 0x6e, 0x51, 0x02, 0xdd, 0x60, 0x8c, 0xd1, 0x73, 0xa8, 0x2a, 0x32,
- 0x19, 0x31, 0x2e, 0xc2, 0x54, 0x56, 0x46, 0x0a, 0x54, 0x24, 0xd8, 0x37, 0x18, 0x7a, 0x01, 0x95,
- 0xcc, 0x97, 0x6c, 0x8d, 0x93, 0xaf, 0x5b, 0x1b, 0xd5, 0x6d, 0xeb, 0x4b, 0xb7, 0x6c, 0xe0, 0xcc,
- 0xcf, 0x38, 0x98, 0x9e, 0x61, 0xec, 0x9f, 0x0f, 0x9c, 0x42, 0xdd, 0xda, 0x28, 0xb8, 0x45, 0x0d,
- 0xbc, 0x1d, 0xa0, 0x1f, 0xc3, 0xda, 0xbc, 0x09, 0x7f, 0xd2, 0x4a, 0x46, 0xaa, 0x4e, 0xd5, 0x6d,
- 0xeb, 0x95, 0x5b, 0x9b, 0xb3, 0xd3, 0x6b, 0x25, 0x23, 0xd4, 0x82, 0xfb, 0x09, 0x19, 0x52, 0x1c,
- 0xf9, 0x63, 0x9c, 0x24, 0xc1, 0x10, 0xfb, 0x23, 0x1c, 0x44, 0x98, 0x3b, 0x45, 0x15, 0xde, 0x5d,
- 0x4d, 0x1e, 0x69, 0xee, 0x50, 0x51, 0xe8, 0x25, 0xc0, 0x74, 0x92, 0x0e, 0xfc, 0x71, 0x30, 0x24,
- 0xa1, 0x53, 0x52, 0xb6, 0x8b, 0xaf, 0xb7, 0xbe, 0xdc, 0x7a, 0xfd, 0x93, 0x57, 0x3f, 0x75, 0x4b,
- 0x92, 0x3b, 0x92, 0x94, 0x16, 0xe4, 0x17, 0x46, 0x10, 0xae, 0x04, 0xb7, 0x5a, 0xaf, 0xb7, 0xa4,
- 0x20, 0xbf, 0xd0, 0x82, 0x0f, 0x60, 0x39, 0xc1, 0xc3, 0x0f, 0x44, 0x38, 0xe5, 0xba, 0xb5, 0x51,
- 0x74, 0xcd, 0x49, 0xe2, 0x67, 0x8c, 0x9f, 0x93, 0xc8, 0xa9, 0x48, 0x65, 0xd7, 0x9c, 0x1a, 0x09,
- 0x38, 0x47, 0x69, 0x2c, 0x48, 0x42, 0x86, 0x2e, 0x8e, 0x30, 0x1e, 0xf7, 0xd5, 0xa4, 0xaa, 0xea,
- 0xfc, 0x08, 0x56, 0x26, 0xe9, 0xe0, 0x1c, 0x5f, 0x26, 0x8e, 0x55, 0xcf, 0x6f, 0x94, 0x5b, 0xb5,
- 0xe6, 0x62, 0xcb, 0xdd, 0x8c, 0x47, 0x9f, 0x03, 0xc8, 0xfc, 0x02, 0x91, 0x72, 0x9c, 0xa8, 0xde,
- 0x56, 0xdc, 0x39, 0x04, 0x55, 0xc0, 0x1a, 0xeb, 0x1e, 0xb8, 0xd6, 0xb8, 0xf1, 0x97, 0x1c, 0x94,
- 0xbd, 0x69, 0x87, 0x4e, 0x52, 0x91, 0xb5, 0xe1, 0x6a, 0x30, 0xac, 0xc5, 0xc1, 0x90, 0xe4, 0x84,
- 0xe3, 0x0b, 0x7f, 0x14, 0x24, 0x23, 0xb5, 0x04, 0x15, 0xb7, 0x28, 0x81, 0xc3, 0x20, 0x19, 0xa9,
- 0x21, 0x95, 0x24, 0xa1, 0x11, 0x9e, 0x9a, 0x15, 0x50, 0xe2, 0x1d, 0x09, 0x48, 0x5a, 0x6f, 0x9e,
- 0x9f, 0x90, 0xa1, 0x6a, 0x70, 0xc5, 0x2d, 0x69, 0xa4, 0x4f, 0x86, 0xe8, 0x87, 0x50, 0x4c, 0xf0,
- 0x6f, 0x53, 0x4c, 0x43, 0x6c, 0x1a, 0x0b, 0x5f, 0xb7, 0xde, 0x7c, 0xfd, 0x66, 0xeb, 0x75, 0xeb,
- 0xcd, 0x2b, 0x77, 0xc6, 0xa1, 0x5f, 0x40, 0xd9, 0x98, 0x51, 0xb3, 0x24, 0x77, 0x61, 0xb5, 0x65,
- 0x37, 0x55, 0x02, 0x57, 0xf5, 0xda, 0xae, 0xf4, 0x7b, 0xed, 0xee, 0xfe, 0xce, 0xfe, 0xbe, 0xdb,
- 0xee, 0xf7, 0x5d, 0xe3, 0x59, 0x25, 0xf8, 0x0a, 0x8a, 0x63, 0x53, 0x65, 0x67, 0xa5, 0x6e, 0x6d,
- 0x94, 0x5b, 0x0f, 0x9b, 0x9f, 0x2a, 0xbb, 0x3b, 0x13, 0x95, 0x4d, 0x0b, 0xc6, 0x2c, 0xa5, 0x42,
- 0xcd, 0x50, 0xc1, 0x35, 0xa7, 0xc6, 0x7f, 0x2d, 0xa8, 0x78, 0xd3, 0xe3, 0x54, 0x64, 0x05, 0x74,
- 0x60, 0xc5, 0xd4, 0xcb, 0x6c, 0x4b, 0x76, 0xfc, 0xde, 0x9d, 0x9b, 0xb3, 0x2f, 0x2b, 0x37, 0xb3,
- 0x8f, 0x5a, 0x8b, 0xf9, 0xca, 0xbb, 0x63, 0xb5, 0xb5, 0xd6, 0xd4, 0x0e, 0xe7, 0x22, 0xfd, 0x54,
- 0x8a, 0x4b, 0xb7, 0x4f, 0xf1, 0x05, 0xac, 0xb2, 0x89, 0xcf, 0xb1, 0x48, 0x39, 0xf5, 0xa3, 0x40,
- 0x04, 0xe6, 0xa6, 0xa9, 0xb0, 0x89, 0xab, 0xc0, 0xfd, 0x40, 0x04, 0x8d, 0x2e, 0xd4, 0xb2, 0x7c,
- 0x77, 0xcd, 0x15, 0x71, 0x15, 0xbb, 0xb5, 0x10, 0xfb, 0x73, 0xa8, 0x9a, 0xd8, 0xf5, 0x6c, 0x9a,
- 0x91, 0xa9, 0x68, 0xb0, 0xa7, 0xb0, 0xc6, 0xdf, 0x72, 0x50, 0xf3, 0x78, 0x40, 0x93, 0x20, 0x14,
- 0x84, 0xd1, 0xac, 0x86, 0x17, 0x98, 0x27, 0x84, 0x51, 0x55, 0xc3, 0xaa, 0x9b, 0x1d, 0xd1, 0x0b,
- 0x58, 0x26, 0xb2, 0xd5, 0x7a, 0xb0, 0xcb, 0xad, 0x4a, 0x73, 0x6e, 0x78, 0x5d, 0xc3, 0xa1, 0xaf,
- 0xa0, 0x3c, 0x20, 0xd4, 0x67, 0x2a, 0xca, 0xc4, 0xc9, 0x2b, 0x51, 0xbb, 0x79, 0x2d, 0x6e, 0x17,
- 0x06, 0x84, 0x6a, 0x24, 0x41, 0x2f, 0x61, 0x25, 0x13, 0x5f, 0x52, 0xe2, 0xd5, 0xe6, 0x7c, 0x5b,
- 0xdd, 0x8c, 0x95, 0x5d, 0x8c, 0x59, 0x78, 0xee, 0x0b, 0x32, 0xc6, 0x6a, 0x8c, 0xab, 0x6e, 0x51,
- 0x02, 0x1e, 0x19, 0x63, 0x39, 0xe4, 0x3a, 0x04, 0x3f, 0xa4, 0x42, 0x95, 0xaf, 0xea, 0x96, 0x34,
- 0xb2, 0x47, 0x85, 0xbc, 0xe8, 0x8d, 0x19, 0xc5, 0xaf, 0x28, 0x1e, 0x0c, 0x24, 0x05, 0x9e, 0x00,
- 0xe0, 0xa9, 0xe0, 0x81, 0x2e, 0x7f, 0x51, 0x2f, 0x89, 0x42, 0x64, 0xed, 0x65, 0x87, 0xae, 0x68,
- 0x3f, 0xc6, 0x54, 0xdf, 0x53, 0x6e, 0x65, 0x26, 0xf2, 0x0e, 0xd3, 0xc6, 0x9f, 0x2d, 0xb8, 0xe7,
- 0x4d, 0x5d, 0xb9, 0x31, 0x89, 0xd8, 0xc7, 0x22, 0x20, 0xb1, 0xbe, 0x62, 0x9f, 0x43, 0x95, 0x6b,
- 0xd4, 0x2c, 0xa9, 0x2e, 0x6e, 0xc5, 0x80, 0x7a, 0x4f, 0xd7, 0x61, 0x45, 0x4c, 0xb3, 0x0d, 0x97,
- 0xfe, 0x97, 0xc5, 0x54, 0xed, 0xf7, 0x4d, 0xe7, 0xf9, 0x9b, 0xce, 0xd1, 0x26, 0xac, 0xcd, 0x49,
- 0xb1, 0xb3, 0xb3, 0x04, 0x0b, 0x53, 0xa6, 0xda, 0x4c, 0xf0, 0x58, 0xc1, 0x8d, 0xdf, 0x5b, 0xb0,
- 0x3e, 0x0b, 0xb4, 0x8f, 0x39, 0x09, 0x62, 0xf2, 0x2d, 0x8e, 0x54, 0xac, 0x2f, 0xa1, 0x36, 0xbb,
- 0xb3, 0x16, 0xa2, 0x5d, 0x9d, 0xc1, 0x3a, 0xde, 0xc7, 0x50, 0x9a, 0x21, 0x26, 0xe2, 0x2b, 0x40,
- 0x8d, 0xe0, 0xcc, 0xb0, 0x2f, 0xa6, 0x2a, 0x66, 0x39, 0x82, 0x57, 0xde, 0xa6, 0x8d, 0x3f, 0x59,
- 0x50, 0xe9, 0x44, 0x98, 0x0a, 0x22, 0x2e, 0xb3, 0x8f, 0x00, 0xf5, 0x71, 0x60, 0x36, 0x58, 0x1f,
- 0x10, 0x82, 0x42, 0x9a, 0x60, 0x6e, 0xde, 0x38, 0xf5, 0x5b, 0x62, 0x23, 0x96, 0x08, 0x65, 0xb6,
- 0xe4, 0xaa, 0xdf, 0x12, 0x9b, 0x30, 0xae, 0xb3, 0x2e, 0xb9, 0xea, 0xb7, 0xc2, 0x02, 0xa1, 0xdf,
- 0x2c, 0x89, 0x05, 0x62, 0x84, 0xd6, 0x61, 0x49, 0x27, 0xb6, 0x9c, 0x3d, 0x88, 0xfa, 0xbc, 0xf9,
- 0x5d, 0x0e, 0xca, 0x07, 0x01, 0x89, 0x53, 0xae, 0xbf, 0x49, 0x9e, 0xc0, 0x43, 0x73, 0xf4, 0x4f,
- 0x28, 0x9e, 0x4e, 0x70, 0x28, 0x66, 0xaf, 0x97, 0x6d, 0xa1, 0xcf, 0xe0, 0x41, 0x46, 0xef, 0xa6,
- 0x42, 0x30, 0xda, 0x36, 0x22, 0x76, 0x0e, 0xdd, 0x87, 0xb5, 0x8c, 0x93, 0x85, 0x6f, 0x73, 0xce,
- 0xb8, 0x9d, 0x47, 0x8f, 0x60, 0x3d, 0x83, 0x77, 0xd4, 0xda, 0xed, 0x05, 0x34, 0xc4, 0x71, 0x8c,
- 0x23, 0xbb, 0x80, 0xd6, 0xe1, 0x6e, 0x46, 0xf6, 0xc8, 0x95, 0xb1, 0x25, 0xe4, 0xc0, 0xbd, 0x39,
- 0xe2, 0x4a, 0x65, 0x19, 0x3d, 0x00, 0x34, 0xc7, 0x74, 0xe8, 0x45, 0x10, 0x93, 0xc8, 0x5e, 0x41,
- 0x8f, 0xc1, 0xc9, 0x70, 0x03, 0xf6, 0xb3, 0xd6, 0xd8, 0xc5, 0x05, 0x7b, 0x9c, 0x85, 0x38, 0x49,
- 0x74, 0x7c, 0xa5, 0xf9, 0x94, 0xba, 0x4c, 0xb4, 0x29, 0x4b, 0x87, 0xa3, 0x83, 0x94, 0x46, 0x89,
- 0x0d, 0xd7, 0xb8, 0x0e, 0x25, 0xc2, 0x74, 0xd2, 0x2e, 0xa3, 0x87, 0x70, 0x3f, 0xe3, 0x0e, 0x08,
- 0x1f, 0x7f, 0x08, 0x38, 0xd6, 0x26, 0xc3, 0xcd, 0x3f, 0x5a, 0x60, 0x5f, 0xbf, 0x35, 0x91, 0x0d,
- 0x95, 0xde, 0xce, 0xaf, 0xbd, 0x63, 0xf3, 0x50, 0xd8, 0x77, 0xd0, 0x5d, 0xa8, 0x29, 0xa4, 0xbf,
- 0xe7, 0x76, 0x7a, 0xde, 0xe1, 0x4e, 0xff, 0xd0, 0xb6, 0xd0, 0x1a, 0x54, 0x15, 0x78, 0x74, 0xf2,
- 0xce, 0xeb, 0xf4, 0x3b, 0xdf, 0xd8, 0xb9, 0x19, 0x74, 0xdc, 0x73, 0xdb, 0xde, 0x89, 0xdb, 0xb5,
- 0xf3, 0x33, 0x63, 0xef, 0x3b, 0x5e, 0x57, 0x1a, 0x2b, 0xa0, 0x7b, 0x60, 0x2b, 0xa4, 0xd7, 0xea,
- 0x1f, 0x66, 0xe8, 0xd2, 0x66, 0x0c, 0xb5, 0x6b, 0xcf, 0x95, 0x54, 0x9d, 0x7f, 0xb0, 0xec, 0x3b,
- 0xd2, 0xbe, 0x42, 0x66, 0x2e, 0x2d, 0x54, 0x81, 0x62, 0xfb, 0xd4, 0x6b, 0xbb, 0xdd, 0x9d, 0x77,
- 0x76, 0x6e, 0xa6, 0x92, 0xd9, 0xcd, 0x4b, 0x6f, 0x0a, 0x99, 0xf7, 0x56, 0xd8, 0x3c, 0x81, 0xb2,
- 0xd9, 0x30, 0xe5, 0xa9, 0x0c, 0x2b, 0xde, 0x69, 0xa7, 0xdb, 0x3b, 0xf1, 0xec, 0x3b, 0xd2, 0xa2,
- 0x77, 0x7a, 0x7c, 0xe2, 0xc9, 0x93, 0x85, 0x00, 0x96, 0xbd, 0xd3, 0xa3, 0xb6, 0xb7, 0x63, 0xe7,
- 0xd0, 0x2a, 0x80, 0x77, 0x7a, 0xd0, 0xe9, 0x76, 0xfa, 0x87, 0xed, 0x7d, 0x3b, 0x8f, 0x6a, 0x50,
- 0xf6, 0x4e, 0xdb, 0xa7, 0x9e, 0xbb, 0xb3, 0xbf, 0xe3, 0xed, 0xd8, 0x85, 0xcd, 0xff, 0xe4, 0x60,
- 0x4d, 0x4f, 0xdb, 0xbc, 0xf5, 0x75, 0xb8, 0xbb, 0x00, 0xfa, 0xc7, 0x62, 0x84, 0xb9, 0x6d, 0xa1,
- 0x06, 0x7c, 0xbe, 0x48, 0x1c, 0x60, 0x7c, 0x7c, 0x81, 0xb9, 0x37, 0xe2, 0x38, 0x19, 0xb1, 0x58,
- 0xce, 0xea, 0x53, 0x78, 0xb4, 0x28, 0xb3, 0xc7, 0xe8, 0x19, 0xe1, 0x63, 0xdd, 0x35, 0x3b, 0x2f,
- 0xf7, 0x60, 0x51, 0xc0, 0xc5, 0x09, 0x16, 0xfb, 0xf8, 0x82, 0x84, 0xd8, 0x2e, 0xdc, 0xa4, 0x8d,
- 0xfe, 0x7b, 0xc6, 0xe5, 0xf4, 0x3e, 0x06, 0x67, 0x91, 0x7e, 0x4f, 0x26, 0xd8, 0x28, 0x2f, 0xdf,
- 0x54, 0xee, 0x71, 0x26, 0x70, 0x28, 0xf6, 0x82, 0x38, 0xb6, 0x57, 0xe4, 0xa8, 0x2e, 0xd2, 0x72,
- 0x8e, 0xbd, 0xa9, 0x5d, 0xbc, 0x19, 0x75, 0x36, 0x78, 0x7b, 0x23, 0x1c, 0x9e, 0xdb, 0x25, 0x39,
- 0x93, 0x8b, 0x02, 0x3b, 0xfa, 0xcd, 0xb7, 0x41, 0xae, 0xe1, 0x35, 0xa7, 0xd9, 0x37, 0xbd, 0x5d,
- 0xde, 0xfc, 0x1d, 0xdc, 0xeb, 0x11, 0x7a, 0x14, 0x08, 0x4e, 0xa6, 0xf3, 0x35, 0xae, 0xc3, 0xe3,
- 0x8f, 0xe1, 0xfe, 0x5e, 0xca, 0x39, 0xa6, 0xc2, 0xb6, 0xd0, 0x33, 0x78, 0xf2, 0x51, 0x89, 0x2e,
- 0xfe, 0x70, 0x40, 0x78, 0x22, 0xec, 0x9c, 0xec, 0xc7, 0xa7, 0x44, 0xfa, 0x38, 0x64, 0x34, 0xb2,
- 0xf3, 0x9b, 0xbf, 0x01, 0xe4, 0xe2, 0x90, 0x5d, 0x60, 0x7e, 0xa9, 0xcb, 0xa4, 0xdc, 0xff, 0x00,
- 0x9e, 0xdd, 0x44, 0xfd, 0x7e, 0xc8, 0x83, 0xf1, 0x20, 0xc6, 0x91, 0x2c, 0x76, 0x62, 0xdf, 0x91,
- 0xf5, 0xfc, 0x88, 0x98, 0x76, 0x68, 0x5b, 0x9b, 0x67, 0x50, 0x93, 0x92, 0xf3, 0x79, 0x3d, 0x84,
- 0xfb, 0xd7, 0x20, 0xbf, 0x17, 0x07, 0x84, 0xda, 0x77, 0x64, 0x9d, 0xae, 0x53, 0xda, 0xd2, 0x1b,
- 0xdb, 0xfa, 0x34, 0xb9, 0x65, 0xe7, 0xb6, 0x7f, 0x06, 0x2b, 0x1f, 0x88, 0x7a, 0x41, 0xd0, 0xb3,
- 0xa6, 0xfe, 0x2f, 0xd8, 0xcc, 0xfe, 0x0b, 0x36, 0xdb, 0x34, 0x1d, 0xff, 0x2a, 0x88, 0x53, 0x7c,
- 0x3c, 0x91, 0x77, 0x60, 0xe2, 0x7c, 0xf7, 0x87, 0xbc, 0xfe, 0x52, 0x97, 0x3a, 0x1d, 0xba, 0xfd,
- 0x73, 0x28, 0x2a, 0x6d, 0x96, 0x8a, 0xdb, 0xa8, 0xff, 0xdd, 0xa8, 0x2b, 0x97, 0xc7, 0xa9, 0xd8,
- 0xfe, 0x06, 0xaa, 0x4a, 0x3f, 0xc2, 0x83, 0x74, 0x78, 0xcb, 0x18, 0xfe, 0x61, 0x8c, 0x94, 0xa5,
- 0xe6, 0xbe, 0x54, 0xec, 0xd0, 0xed, 0x0e, 0xac, 0xce, 0x19, 0xba, 0x65, 0x38, 0xff, 0x34, 0x96,
- 0x2a, 0x33, 0x4b, 0x32, 0xa6, 0x5f, 0x42, 0x49, 0x99, 0x12, 0x84, 0x5e, 0xde, 0xc6, 0xca, 0xbf,
- 0x8c, 0x15, 0x55, 0x09, 0x8f, 0xd0, 0xcb, 0xed, 0x77, 0x50, 0x53, 0x16, 0x06, 0x8c, 0x89, 0x98,
- 0xa9, 0x3f, 0x4f, 0xb7, 0xb0, 0xf3, 0x6f, 0x63, 0x47, 0x25, 0xb2, 0x3b, 0x53, 0xdd, 0xfd, 0x0a,
- 0x9e, 0x87, 0x6c, 0xdc, 0x4c, 0x02, 0xc1, 0x92, 0x11, 0x89, 0x83, 0x41, 0xd2, 0x14, 0x1c, 0x7f,
- 0xcb, 0x78, 0x33, 0x26, 0x83, 0x99, 0xbd, 0x5d, 0xf0, 0x14, 0x28, 0xdb, 0xfb, 0xff, 0x00, 0x00,
- 0x00, 0xff, 0xff, 0x70, 0x88, 0xcd, 0x71, 0xe2, 0x0f, 0x00, 0x00,
-}
diff --git a/accounts/usbwallet/internal/trezor/types.proto b/accounts/usbwallet/internal/trezor/types.proto
deleted file mode 100644
index acbe79e3f..000000000
--- a/accounts/usbwallet/internal/trezor/types.proto
+++ /dev/null
@@ -1,278 +0,0 @@
-// This file originates from the SatoshiLabs Trezor `common` repository at:
-// https://github.com/trezor/trezor-common/blob/master/protob/types.proto
-// dated 28.07.2017, commit dd8ec3231fb5f7992360aff9bdfe30bb58130f4b.
-
-syntax = "proto2";
-
-/**
- * Types for TREZOR communication
- *
- * @author Marek Palatinus
- * @version 1.2
- */
-
-// Sugar for easier handling in Java
-option java_package = "com.satoshilabs.trezor.lib.protobuf";
-option java_outer_classname = "TrezorType";
-
-import "google/protobuf/descriptor.proto";
-
-/**
- * Options for specifying message direction and type of wire (normal/debug)
- */
-extend google.protobuf.EnumValueOptions {
- optional bool wire_in = 50002; // message can be transmitted via wire from PC to TREZOR
- optional bool wire_out = 50003; // message can be transmitted via wire from TREZOR to PC
- optional bool wire_debug_in = 50004; // message can be transmitted via debug wire from PC to TREZOR
- optional bool wire_debug_out = 50005; // message can be transmitted via debug wire from TREZOR to PC
- optional bool wire_tiny = 50006; // message is handled by TREZOR when the USB stack is in tiny mode
- optional bool wire_bootloader = 50007; // message is only handled by TREZOR Bootloader
-}
-
-/**
- * Type of failures returned by Failure message
- * @used_in Failure
- */
-enum FailureType {
- Failure_UnexpectedMessage = 1;
- Failure_ButtonExpected = 2;
- Failure_DataError = 3;
- Failure_ActionCancelled = 4;
- Failure_PinExpected = 5;
- Failure_PinCancelled = 6;
- Failure_PinInvalid = 7;
- Failure_InvalidSignature = 8;
- Failure_ProcessError = 9;
- Failure_NotEnoughFunds = 10;
- Failure_NotInitialized = 11;
- Failure_FirmwareError = 99;
-}
-
-/**
- * Type of script which will be used for transaction output
- * @used_in TxOutputType
- */
-enum OutputScriptType {
- PAYTOADDRESS = 0; // used for all addresses (bitcoin, p2sh, witness)
- PAYTOSCRIPTHASH = 1; // p2sh address (deprecated; use PAYTOADDRESS)
- PAYTOMULTISIG = 2; // only for change output
- PAYTOOPRETURN = 3; // op_return
- PAYTOWITNESS = 4; // only for change output
- PAYTOP2SHWITNESS = 5; // only for change output
-}
-
-/**
- * Type of script which will be used for transaction output
- * @used_in TxInputType
- */
-enum InputScriptType {
- SPENDADDRESS = 0; // standard p2pkh address
- SPENDMULTISIG = 1; // p2sh multisig address
- EXTERNAL = 2; // reserved for external inputs (coinjoin)
- SPENDWITNESS = 3; // native segwit
- SPENDP2SHWITNESS = 4; // segwit over p2sh (backward compatible)
-}
-
-/**
- * Type of information required by transaction signing process
- * @used_in TxRequest
- */
-enum RequestType {
- TXINPUT = 0;
- TXOUTPUT = 1;
- TXMETA = 2;
- TXFINISHED = 3;
- TXEXTRADATA = 4;
-}
-
-/**
- * Type of button request
- * @used_in ButtonRequest
- */
-enum ButtonRequestType {
- ButtonRequest_Other = 1;
- ButtonRequest_FeeOverThreshold = 2;
- ButtonRequest_ConfirmOutput = 3;
- ButtonRequest_ResetDevice = 4;
- ButtonRequest_ConfirmWord = 5;
- ButtonRequest_WipeDevice = 6;
- ButtonRequest_ProtectCall = 7;
- ButtonRequest_SignTx = 8;
- ButtonRequest_FirmwareCheck = 9;
- ButtonRequest_Address = 10;
- ButtonRequest_PublicKey = 11;
-}
-
-/**
- * Type of PIN request
- * @used_in PinMatrixRequest
- */
-enum PinMatrixRequestType {
- PinMatrixRequestType_Current = 1;
- PinMatrixRequestType_NewFirst = 2;
- PinMatrixRequestType_NewSecond = 3;
-}
-
-/**
- * Type of recovery procedure. These should be used as bitmask, e.g.,
- * `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix`
- * listing every method supported by the host computer.
- *
- * Note that ScrambledWords must be supported by every implementation
- * for backward compatibility; there is no way to not support it.
- *
- * @used_in RecoveryDevice
- */
-enum RecoveryDeviceType {
- // use powers of two when extending this field
- RecoveryDeviceType_ScrambledWords = 0; // words in scrambled order
- RecoveryDeviceType_Matrix = 1; // matrix recovery type
-}
-
-/**
- * Type of Recovery Word request
- * @used_in WordRequest
- */
-enum WordRequestType {
- WordRequestType_Plain = 0;
- WordRequestType_Matrix9 = 1;
- WordRequestType_Matrix6 = 2;
-}
-
-/**
- * Structure representing BIP32 (hierarchical deterministic) node
- * Used for imports of private key into the device and exporting public key out of device
- * @used_in PublicKey
- * @used_in LoadDevice
- * @used_in DebugLinkState
- * @used_in Storage
- */
-message HDNodeType {
- required uint32 depth = 1;
- required uint32 fingerprint = 2;
- required uint32 child_num = 3;
- required bytes chain_code = 4;
- optional bytes private_key = 5;
- optional bytes public_key = 6;
-}
-
-message HDNodePathType {
- required HDNodeType node = 1; // BIP-32 node in deserialized form
- repeated uint32 address_n = 2; // BIP-32 path to derive the key from node
-}
-
-/**
- * Structure representing Coin
- * @used_in Features
- */
-message CoinType {
- optional string coin_name = 1;
- optional string coin_shortcut = 2;
- optional uint32 address_type = 3 [default=0];
- optional uint64 maxfee_kb = 4;
- optional uint32 address_type_p2sh = 5 [default=5];
- optional string signed_message_header = 8;
- optional uint32 xpub_magic = 9 [default=76067358]; // default=0x0488b21e
- optional uint32 xprv_magic = 10 [default=76066276]; // default=0x0488ade4
- optional bool segwit = 11;
- optional uint32 forkid = 12;
-}
-
-/**
- * Type of redeem script used in input
- * @used_in TxInputType
- */
-message MultisigRedeemScriptType {
- repeated HDNodePathType pubkeys = 1; // pubkeys from multisig address (sorted lexicographically)
- repeated bytes signatures = 2; // existing signatures for partially signed input
- optional uint32 m = 3; // "m" from n, how many valid signatures is necessary for spending
-}
-
-/**
- * Structure representing transaction input
- * @used_in SimpleSignTx
- * @used_in TransactionType
- */
-message TxInputType {
- repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
- required bytes prev_hash = 2; // hash of previous transaction output to spend by this input
- required uint32 prev_index = 3; // index of previous output to spend
- optional bytes script_sig = 4; // script signature, unset for tx to sign
- optional uint32 sequence = 5 [default=4294967295]; // sequence (default=0xffffffff)
- optional InputScriptType script_type = 6 [default=SPENDADDRESS]; // defines template of input script
- optional MultisigRedeemScriptType multisig = 7; // Filled if input is going to spend multisig tx
- optional uint64 amount = 8; // amount of previous transaction output (for segwit only)
-}
-
-/**
- * Structure representing transaction output
- * @used_in SimpleSignTx
- * @used_in TransactionType
- */
-message TxOutputType {
- optional string address = 1; // target coin address in Base58 encoding
- repeated uint32 address_n = 2; // BIP-32 path to derive the key from master node; has higher priority than "address"
- required uint64 amount = 3; // amount to spend in satoshis
- required OutputScriptType script_type = 4; // output script type
- optional MultisigRedeemScriptType multisig = 5; // defines multisig address; script_type must be PAYTOMULTISIG
- optional bytes op_return_data = 6; // defines op_return data; script_type must be PAYTOOPRETURN, amount must be 0
-}
-
-/**
- * Structure representing compiled transaction output
- * @used_in TransactionType
- */
-message TxOutputBinType {
- required uint64 amount = 1;
- required bytes script_pubkey = 2;
-}
-
-/**
- * Structure representing transaction
- * @used_in SimpleSignTx
- */
-message TransactionType {
- optional uint32 version = 1;
- repeated TxInputType inputs = 2;
- repeated TxOutputBinType bin_outputs = 3;
- repeated TxOutputType outputs = 5;
- optional uint32 lock_time = 4;
- optional uint32 inputs_cnt = 6;
- optional uint32 outputs_cnt = 7;
- optional bytes extra_data = 8;
- optional uint32 extra_data_len = 9;
-}
-
-/**
- * Structure representing request details
- * @used_in TxRequest
- */
-message TxRequestDetailsType {
- optional uint32 request_index = 1; // device expects TxAck message from the computer
- optional bytes tx_hash = 2; // tx_hash of requested transaction
- optional uint32 extra_data_len = 3; // length of requested extra data
- optional uint32 extra_data_offset = 4; // offset of requested extra data
-}
-
-/**
- * Structure representing serialized data
- * @used_in TxRequest
- */
-message TxRequestSerializedType {
- optional uint32 signature_index = 1; // 'signature' field contains signed input of this index
- optional bytes signature = 2; // signature of the signature_index input
- optional bytes serialized_tx = 3; // part of serialized and signed transaction
-}
-
-/**
- * Structure representing identity data
- * @used_in IdentityType
- */
-message IdentityType {
- optional string proto = 1; // proto part of URI
- optional string user = 2; // user part of URI
- optional string host = 3; // host part of URI
- optional string port = 4; // port part of URI
- optional string path = 5; // path part of URI
- optional uint32 index = 6 [default=0]; // identity index
-}
diff --git a/accounts/usbwallet/ledger.go b/accounts/usbwallet/ledger.go
index 6b93b6e17..e896332bb 100644
--- a/accounts/usbwallet/ledger.go
+++ b/accounts/usbwallet/ledger.go
@@ -28,12 +28,13 @@ import (
"io"
"math/big"
+ "github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/common/hexutil"
+ "github.com/truechain/truechain-engineering-code/core/types"
+ "github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/log"
"github.com/truechain/truechain-engineering-code/rlp"
- "github.com/truechain/truechain-engineering-code/accounts"
- "github.com/truechain/truechain-engineering-code/core/types"
)
// ledgerOpcode is an enumeration encoding the supported Ledger opcodes.
@@ -51,8 +52,10 @@ const (
ledgerOpRetrieveAddress ledgerOpcode = 0x02 // Returns the public key and Ethereum address for a given BIP 32 path
ledgerOpSignTransaction ledgerOpcode = 0x04 // Signs an Ethereum transaction after having the user validate the parameters
ledgerOpGetConfiguration ledgerOpcode = 0x06 // Returns specific wallet application configuration
+ ledgerOpSignTypedMessage ledgerOpcode = 0x0c // Signs an Ethereum message following the EIP 712 specification
ledgerP1DirectlyFetchAddress ledgerParam1 = 0x00 // Return address directly from the wallet
+ ledgerP1InitTypedMessageData ledgerParam1 = 0x00 // First chunk of Typed Message data
ledgerP1InitTransactionData ledgerParam1 = 0x00 // First transaction data block for signing
ledgerP1ContTransactionData ledgerParam1 = 0x80 // Subsequent transaction data block for signing
ledgerP2DiscardAddressChainCode ledgerParam2 = 0x00 // Do not return the chain code along with the address
@@ -162,12 +165,31 @@ func (w *ledgerDriver) SignTx(path accounts.DerivationPath, tx *types.Transactio
}
// Ensure the wallet is capable of signing the given transaction
if chainID != nil && w.version[0] <= 1 && w.version[1] <= 0 && w.version[2] <= 2 {
+ //lint:ignore ST1005 brand name displayed on the console
return common.Address{}, nil, fmt.Errorf("Ledger v%d.%d.%d doesn't support signing this transaction, please update to v1.0.3 at least", w.version[0], w.version[1], w.version[2])
}
// All infos gathered and metadata checks out, request signing
return w.ledgerSign(path, tx, chainID)
}
+// SignTypedMessage implements usbwallet.driver, sending the message to the Ledger and
+// waiting for the user to sign or deny the transaction.
+//
+// Note: this was introduced in the ledger 1.5.0 firmware
+func (w *ledgerDriver) SignTypedMessage(path accounts.DerivationPath, domainHash []byte, messageHash []byte) ([]byte, error) {
+ // If the Ethereum app doesn't run, abort
+ if w.offline() {
+ return nil, accounts.ErrWalletClosed
+ }
+ // Ensure the wallet is capable of signing the given transaction
+ if w.version[0] < 1 && w.version[1] < 5 {
+ //lint:ignore ST1005 brand name displayed on the console
+ return nil, fmt.Errorf("Ledger version >= 1.5.0 required for EIP-712 signing (found version v%d.%d.%d)", w.version[0], w.version[1], w.version[2])
+ }
+ // All infos gathered and metadata checks out, request signing
+ return w.ledgerSignTypedMessage(path, domainHash, messageHash)
+}
+
// ledgerVersion retrieves the current version of the Ethereum wallet app running
// on the Ledger wallet.
//
@@ -257,7 +279,9 @@ func (w *ledgerDriver) ledgerDerive(derivationPath []uint32) (common.Address, er
// Decode the hex sting into an Ethereum address and return
var address common.Address
- hex.Decode(address[:], hexstr)
+ if _, err = hex.Decode(address[:], hexstr); err != nil {
+ return common.Address{}, err
+ }
return address, nil
}
@@ -339,15 +363,19 @@ func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction
op = ledgerP1ContTransactionData
}
// Extract the Ethereum signature and do a sanity validation
- if len(reply) != 65 {
+ if len(reply) != crypto.SignatureLength {
return common.Address{}, nil, errors.New("reply lacks signature")
}
signature := append(reply[1:], reply[0])
// Create the correct signer and signature transform based on the chain ID
- var signer types.Signer = types.NewTIP1Signer(chainID)
- signature[64] -= byte(chainID.Uint64()*2 + 35)
-
+ var signer types.Signer
+ if chainID == nil {
+ signer = new(types.TIP1Signer)
+ } else {
+ signer = types.NewTIP1Signer(chainID)
+ signature[64] -= byte(chainID.Uint64()*2 + 35)
+ }
signed, err := tx.WithSignature(signer, signature)
if err != nil {
return common.Address{}, nil, err
@@ -359,6 +387,68 @@ func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction
return sender, signed, nil
}
+// ledgerSignTypedMessage sends the transaction to the Ledger wallet, and waits for the user
+// to confirm or deny the transaction.
+//
+// The signing protocol is defined as follows:
+//
+// CLA | INS | P1 | P2 | Lc | Le
+// ----+-----+----+-----------------------------+-----+---
+// E0 | 0C | 00 | implementation version : 00 | variable | variable
+//
+// Where the input is:
+//
+// Description | Length
+// -------------------------------------------------+----------
+// Number of BIP 32 derivations to perform (max 10) | 1 byte
+// First derivation index (big endian) | 4 bytes
+// ... | 4 bytes
+// Last derivation index (big endian) | 4 bytes
+// domain hash | 32 bytes
+// message hash | 32 bytes
+//
+//
+//
+// And the output data is:
+//
+// Description | Length
+// ------------+---------
+// signature V | 1 byte
+// signature R | 32 bytes
+// signature S | 32 bytes
+func (w *ledgerDriver) ledgerSignTypedMessage(derivationPath []uint32, domainHash []byte, messageHash []byte) ([]byte, error) {
+ // Flatten the derivation path into the Ledger request
+ path := make([]byte, 1+4*len(derivationPath))
+ path[0] = byte(len(derivationPath))
+ for i, component := range derivationPath {
+ binary.BigEndian.PutUint32(path[1+4*i:], component)
+ }
+ // Create the 712 message
+ payload := append(path, domainHash...)
+ payload = append(payload, messageHash...)
+
+ // Send the request and wait for the response
+ var (
+ op = ledgerP1InitTypedMessageData
+ reply []byte
+ err error
+ )
+
+ // Send the message over, ensuring it's processed correctly
+ reply, err = w.ledgerExchange(ledgerOpSignTypedMessage, op, 0, payload)
+
+ if err != nil {
+ return nil, err
+ }
+
+ // Extract the Ethereum signature and do a sanity validation
+ if len(reply) != crypto.SignatureLength {
+ return nil, errors.New("reply lacks signature")
+ }
+ signature := append(reply[1:], reply[0])
+ return signature, nil
+}
+
// ledgerExchange performs a data exchange with the Ledger wallet, sending it a
// message and retrieving the response.
//
diff --git a/accounts/usbwallet/trezor.go b/accounts/usbwallet/trezor.go
index ede78b283..f961a2a27 100644
--- a/accounts/usbwallet/trezor.go
+++ b/accounts/usbwallet/trezor.go
@@ -27,13 +27,13 @@ import (
"io"
"math/big"
- "github.com/truechain/truechain-engineering-code/common"
- "github.com/truechain/truechain-engineering-code/common/hexutil"
- "github.com/truechain/truechain-engineering-code/log"
"github.com/golang/protobuf/proto"
"github.com/truechain/truechain-engineering-code/accounts"
- "github.com/truechain/truechain-engineering-code/accounts/usbwallet/internal/trezor"
+ "github.com/truechain/truechain-engineering-code/accounts/usbwallet/trezor"
+ "github.com/truechain/truechain-engineering-code/common"
+ "github.com/truechain/truechain-engineering-code/common/hexutil"
"github.com/truechain/truechain-engineering-code/core/types"
+ "github.com/truechain/truechain-engineering-code/log"
)
// ErrTrezorPINNeeded is returned if opening the trezor requires a PIN code. In
@@ -41,6 +41,9 @@ import (
// encoded passphrase.
var ErrTrezorPINNeeded = errors.New("trezor: pin needed")
+// ErrTrezorPassphraseNeeded is returned if opening the trezor requires a passphrase
+var ErrTrezorPassphraseNeeded = errors.New("trezor: passphrase needed")
+
// errTrezorReplyInvalidHeader is the error message returned by a Trezor data exchange
// if the device replies with a mismatching header. This usually means the device
// is in browser mode.
@@ -48,12 +51,13 @@ var errTrezorReplyInvalidHeader = errors.New("trezor: invalid reply header")
// trezorDriver implements the communication with a Trezor hardware wallet.
type trezorDriver struct {
- device io.ReadWriter // USB device connection to communicate through
- version [3]uint32 // Current version of the Trezor firmware
- label string // Current textual label of the Trezor device
- pinwait bool // Flags whether the device is waiting for PIN entry
- failure error // Any failure that would make the device unusable
- log log.Logger // Contextual logger to tag the trezor with its id
+ device io.ReadWriter // USB device connection to communicate through
+ version [3]uint32 // Current version of the Trezor firmware
+ label string // Current textual label of the Trezor device
+ pinwait bool // Flags whether the device is waiting for PIN entry
+ passphrasewait bool // Flags whether the device is waiting for passphrase entry
+ failure error // Any failure that would make the device unusable
+ log log.Logger // Contextual logger to tag the trezor with its id
}
// newTrezorDriver creates a new instance of a Trezor USB protocol driver.
@@ -79,19 +83,21 @@ func (w *trezorDriver) Status() (string, error) {
}
// Open implements usbwallet.driver, attempting to initialize the connection to
-// the Trezor hardware wallet. Initializing the Trezor is a two phase operation:
+// the Trezor hardware wallet. Initializing the Trezor is a two or three phase operation:
// * The first phase is to initialize the connection and read the wallet's
-// features. This phase is invoked is the provided passphrase is empty. The
+// features. This phase is invoked if the provided passphrase is empty. The
// device will display the pinpad as a result and will return an appropriate
// error to notify the user that a second open phase is needed.
// * The second phase is to unlock access to the Trezor, which is done by the
// user actually providing a passphrase mapping a keyboard keypad to the pin
// number of the user (shuffled according to the pinpad displayed).
+// * If needed the device will ask for passphrase which will require calling
+// open again with the actual passphrase (3rd phase)
func (w *trezorDriver) Open(device io.ReadWriter, passphrase string) error {
w.device, w.failure = device, nil
// If phase 1 is requested, init the connection and wait for user callback
- if passphrase == "" {
+ if passphrase == "" && !w.passphrasewait {
// If we're already waiting for a PIN entry, insta-return
if w.pinwait {
return ErrTrezorPINNeeded
@@ -104,26 +110,46 @@ func (w *trezorDriver) Open(device io.ReadWriter, passphrase string) error {
w.version = [3]uint32{features.GetMajorVersion(), features.GetMinorVersion(), features.GetPatchVersion()}
w.label = features.GetLabel()
- // Do a manual ping, forcing the device to ask for its PIN
+ // Do a manual ping, forcing the device to ask for its PIN and Passphrase
askPin := true
- res, err := w.trezorExchange(&trezor.Ping{PinProtection: &askPin}, new(trezor.PinMatrixRequest), new(trezor.Success))
+ askPassphrase := true
+ res, err := w.trezorExchange(&trezor.Ping{PinProtection: &askPin, PassphraseProtection: &askPassphrase}, new(trezor.PinMatrixRequest), new(trezor.PassphraseRequest), new(trezor.Success))
if err != nil {
return err
}
// Only return the PIN request if the device wasn't unlocked until now
- if res == 1 {
- return nil // Device responded with trezor.Success
+ switch res {
+ case 0:
+ w.pinwait = true
+ return ErrTrezorPINNeeded
+ case 1:
+ w.pinwait = false
+ w.passphrasewait = true
+ return ErrTrezorPassphraseNeeded
+ case 2:
+ return nil // responded with trezor.Success
}
- w.pinwait = true
- return ErrTrezorPINNeeded
}
// Phase 2 requested with actual PIN entry
- w.pinwait = false
-
- if _, err := w.trezorExchange(&trezor.PinMatrixAck{Pin: &passphrase}, new(trezor.Success)); err != nil {
- w.failure = err
- return err
+ if w.pinwait {
+ w.pinwait = false
+ res, err := w.trezorExchange(&trezor.PinMatrixAck{Pin: &passphrase}, new(trezor.Success), new(trezor.PassphraseRequest))
+ if err != nil {
+ w.failure = err
+ return err
+ }
+ if res == 1 {
+ w.passphrasewait = true
+ return ErrTrezorPassphraseNeeded
+ }
+ } else if w.passphrasewait {
+ w.passphrasewait = false
+ if _, err := w.trezorExchange(&trezor.PassphraseAck{Passphrase: &passphrase}, new(trezor.Success)); err != nil {
+ w.failure = err
+ return err
+ }
}
+
return nil
}
@@ -159,6 +185,10 @@ func (w *trezorDriver) SignTx(path accounts.DerivationPath, tx *types.Transactio
return w.trezorSign(path, tx, chainID)
}
+func (w *trezorDriver) SignTypedMessage(path accounts.DerivationPath, domainHash []byte, messageHash []byte) ([]byte, error) {
+ return nil, accounts.ErrNotSupported
+}
+
// trezorDerive sends a derivation request to the Trezor device and returns the
// Ethereum address located on that path.
func (w *trezorDriver) trezorDerive(derivationPath []uint32) (common.Address, error) {
@@ -166,7 +196,13 @@ func (w *trezorDriver) trezorDerive(derivationPath []uint32) (common.Address, er
if _, err := w.trezorExchange(&trezor.EthereumGetAddress{AddressN: derivationPath}, address); err != nil {
return common.Address{}, err
}
- return common.BytesToAddress(address.GetAddress()), nil
+ if addr := address.GetAddressBin(); len(addr) > 0 { // Older firmwares use binary fomats
+ return common.BytesToAddress(addr), nil
+ }
+ if addr := address.GetAddressHex(); len(addr) > 0 { // Newer firmwares use hexadecimal fomats
+ return common.HexToAddress(addr), nil
+ }
+ return common.Address{}, errors.New("missing derived address")
}
// trezorSign sends the transaction to the Trezor wallet, and waits for the user
@@ -185,7 +221,10 @@ func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction
DataLength: &length,
}
if to := tx.To(); to != nil {
- request.To = (*to)[:] // Non contract deploy, set recipient explicitly
+ // Non contract deploy, set recipient explicitly
+ hex := to.Hex()
+ request.ToHex = &hex // Newer firmwares (old will ignore)
+ request.ToBin = (*to)[:] // Older firmwares (new will ignore)
}
if length > 1024 { // Send the data chunked if that was requested
request.DataInitialChunk, data = data[:1024], data[1024:]
@@ -216,8 +255,14 @@ func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction
signature := append(append(response.GetSignatureR(), response.GetSignatureS()...), byte(response.GetSignatureV()))
// Create the correct signer and signature transform based on the chain ID
- var signer types.Signer = types.NewTIP1Signer(chainID)
- signature[64] -= byte(chainID.Uint64()*2 + 35)
+ var signer types.Signer
+ if chainID == nil {
+ signer = new(types.TIP1Signer)
+ } else {
+ // Trezor backend does not support typed transactions yet.
+ signer = types.NewTIP1Signer(chainID)
+ signature[64] -= byte(chainID.Uint64()*2 + 35)
+ }
// Inject the final signature into the transaction and sanity check the sender
signed, err := tx.WithSignature(signer, signature)
diff --git a/accounts/usbwallet/trezor/messages-common.pb.go b/accounts/usbwallet/trezor/messages-common.pb.go
new file mode 100644
index 000000000..304bec0e3
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages-common.pb.go
@@ -0,0 +1,811 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: messages-common.proto
+
+package trezor
+
+import (
+ fmt "fmt"
+ math "math"
+
+ proto "github.com/golang/protobuf/proto"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
+
+type Failure_FailureType int32
+
+const (
+ Failure_Failure_UnexpectedMessage Failure_FailureType = 1
+ Failure_Failure_ButtonExpected Failure_FailureType = 2
+ Failure_Failure_DataError Failure_FailureType = 3
+ Failure_Failure_ActionCancelled Failure_FailureType = 4
+ Failure_Failure_PinExpected Failure_FailureType = 5
+ Failure_Failure_PinCancelled Failure_FailureType = 6
+ Failure_Failure_PinInvalid Failure_FailureType = 7
+ Failure_Failure_InvalidSignature Failure_FailureType = 8
+ Failure_Failure_ProcessError Failure_FailureType = 9
+ Failure_Failure_NotEnoughFunds Failure_FailureType = 10
+ Failure_Failure_NotInitialized Failure_FailureType = 11
+ Failure_Failure_PinMismatch Failure_FailureType = 12
+ Failure_Failure_FirmwareError Failure_FailureType = 99
+)
+
+var Failure_FailureType_name = map[int32]string{
+ 1: "Failure_UnexpectedMessage",
+ 2: "Failure_ButtonExpected",
+ 3: "Failure_DataError",
+ 4: "Failure_ActionCancelled",
+ 5: "Failure_PinExpected",
+ 6: "Failure_PinCancelled",
+ 7: "Failure_PinInvalid",
+ 8: "Failure_InvalidSignature",
+ 9: "Failure_ProcessError",
+ 10: "Failure_NotEnoughFunds",
+ 11: "Failure_NotInitialized",
+ 12: "Failure_PinMismatch",
+ 99: "Failure_FirmwareError",
+}
+
+var Failure_FailureType_value = map[string]int32{
+ "Failure_UnexpectedMessage": 1,
+ "Failure_ButtonExpected": 2,
+ "Failure_DataError": 3,
+ "Failure_ActionCancelled": 4,
+ "Failure_PinExpected": 5,
+ "Failure_PinCancelled": 6,
+ "Failure_PinInvalid": 7,
+ "Failure_InvalidSignature": 8,
+ "Failure_ProcessError": 9,
+ "Failure_NotEnoughFunds": 10,
+ "Failure_NotInitialized": 11,
+ "Failure_PinMismatch": 12,
+ "Failure_FirmwareError": 99,
+}
+
+func (x Failure_FailureType) Enum() *Failure_FailureType {
+ p := new(Failure_FailureType)
+ *p = x
+ return p
+}
+
+func (x Failure_FailureType) String() string {
+ return proto.EnumName(Failure_FailureType_name, int32(x))
+}
+
+func (x *Failure_FailureType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Failure_FailureType_value, data, "Failure_FailureType")
+ if err != nil {
+ return err
+ }
+ *x = Failure_FailureType(value)
+ return nil
+}
+
+func (Failure_FailureType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{1, 0}
+}
+
+//*
+// Type of button request
+type ButtonRequest_ButtonRequestType int32
+
+const (
+ ButtonRequest_ButtonRequest_Other ButtonRequest_ButtonRequestType = 1
+ ButtonRequest_ButtonRequest_FeeOverThreshold ButtonRequest_ButtonRequestType = 2
+ ButtonRequest_ButtonRequest_ConfirmOutput ButtonRequest_ButtonRequestType = 3
+ ButtonRequest_ButtonRequest_ResetDevice ButtonRequest_ButtonRequestType = 4
+ ButtonRequest_ButtonRequest_ConfirmWord ButtonRequest_ButtonRequestType = 5
+ ButtonRequest_ButtonRequest_WipeDevice ButtonRequest_ButtonRequestType = 6
+ ButtonRequest_ButtonRequest_ProtectCall ButtonRequest_ButtonRequestType = 7
+ ButtonRequest_ButtonRequest_SignTx ButtonRequest_ButtonRequestType = 8
+ ButtonRequest_ButtonRequest_FirmwareCheck ButtonRequest_ButtonRequestType = 9
+ ButtonRequest_ButtonRequest_Address ButtonRequest_ButtonRequestType = 10
+ ButtonRequest_ButtonRequest_PublicKey ButtonRequest_ButtonRequestType = 11
+ ButtonRequest_ButtonRequest_MnemonicWordCount ButtonRequest_ButtonRequestType = 12
+ ButtonRequest_ButtonRequest_MnemonicInput ButtonRequest_ButtonRequestType = 13
+ ButtonRequest_ButtonRequest_PassphraseType ButtonRequest_ButtonRequestType = 14
+ ButtonRequest_ButtonRequest_UnknownDerivationPath ButtonRequest_ButtonRequestType = 15
+)
+
+var ButtonRequest_ButtonRequestType_name = map[int32]string{
+ 1: "ButtonRequest_Other",
+ 2: "ButtonRequest_FeeOverThreshold",
+ 3: "ButtonRequest_ConfirmOutput",
+ 4: "ButtonRequest_ResetDevice",
+ 5: "ButtonRequest_ConfirmWord",
+ 6: "ButtonRequest_WipeDevice",
+ 7: "ButtonRequest_ProtectCall",
+ 8: "ButtonRequest_SignTx",
+ 9: "ButtonRequest_FirmwareCheck",
+ 10: "ButtonRequest_Address",
+ 11: "ButtonRequest_PublicKey",
+ 12: "ButtonRequest_MnemonicWordCount",
+ 13: "ButtonRequest_MnemonicInput",
+ 14: "ButtonRequest_PassphraseType",
+ 15: "ButtonRequest_UnknownDerivationPath",
+}
+
+var ButtonRequest_ButtonRequestType_value = map[string]int32{
+ "ButtonRequest_Other": 1,
+ "ButtonRequest_FeeOverThreshold": 2,
+ "ButtonRequest_ConfirmOutput": 3,
+ "ButtonRequest_ResetDevice": 4,
+ "ButtonRequest_ConfirmWord": 5,
+ "ButtonRequest_WipeDevice": 6,
+ "ButtonRequest_ProtectCall": 7,
+ "ButtonRequest_SignTx": 8,
+ "ButtonRequest_FirmwareCheck": 9,
+ "ButtonRequest_Address": 10,
+ "ButtonRequest_PublicKey": 11,
+ "ButtonRequest_MnemonicWordCount": 12,
+ "ButtonRequest_MnemonicInput": 13,
+ "ButtonRequest_PassphraseType": 14,
+ "ButtonRequest_UnknownDerivationPath": 15,
+}
+
+func (x ButtonRequest_ButtonRequestType) Enum() *ButtonRequest_ButtonRequestType {
+ p := new(ButtonRequest_ButtonRequestType)
+ *p = x
+ return p
+}
+
+func (x ButtonRequest_ButtonRequestType) String() string {
+ return proto.EnumName(ButtonRequest_ButtonRequestType_name, int32(x))
+}
+
+func (x *ButtonRequest_ButtonRequestType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(ButtonRequest_ButtonRequestType_value, data, "ButtonRequest_ButtonRequestType")
+ if err != nil {
+ return err
+ }
+ *x = ButtonRequest_ButtonRequestType(value)
+ return nil
+}
+
+func (ButtonRequest_ButtonRequestType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{2, 0}
+}
+
+//*
+// Type of PIN request
+type PinMatrixRequest_PinMatrixRequestType int32
+
+const (
+ PinMatrixRequest_PinMatrixRequestType_Current PinMatrixRequest_PinMatrixRequestType = 1
+ PinMatrixRequest_PinMatrixRequestType_NewFirst PinMatrixRequest_PinMatrixRequestType = 2
+ PinMatrixRequest_PinMatrixRequestType_NewSecond PinMatrixRequest_PinMatrixRequestType = 3
+)
+
+var PinMatrixRequest_PinMatrixRequestType_name = map[int32]string{
+ 1: "PinMatrixRequestType_Current",
+ 2: "PinMatrixRequestType_NewFirst",
+ 3: "PinMatrixRequestType_NewSecond",
+}
+
+var PinMatrixRequest_PinMatrixRequestType_value = map[string]int32{
+ "PinMatrixRequestType_Current": 1,
+ "PinMatrixRequestType_NewFirst": 2,
+ "PinMatrixRequestType_NewSecond": 3,
+}
+
+func (x PinMatrixRequest_PinMatrixRequestType) Enum() *PinMatrixRequest_PinMatrixRequestType {
+ p := new(PinMatrixRequest_PinMatrixRequestType)
+ *p = x
+ return p
+}
+
+func (x PinMatrixRequest_PinMatrixRequestType) String() string {
+ return proto.EnumName(PinMatrixRequest_PinMatrixRequestType_name, int32(x))
+}
+
+func (x *PinMatrixRequest_PinMatrixRequestType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(PinMatrixRequest_PinMatrixRequestType_value, data, "PinMatrixRequest_PinMatrixRequestType")
+ if err != nil {
+ return err
+ }
+ *x = PinMatrixRequest_PinMatrixRequestType(value)
+ return nil
+}
+
+func (PinMatrixRequest_PinMatrixRequestType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{4, 0}
+}
+
+//*
+// Response: Success of the previous request
+// @end
+type Success struct {
+ Message *string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Success) Reset() { *m = Success{} }
+func (m *Success) String() string { return proto.CompactTextString(m) }
+func (*Success) ProtoMessage() {}
+func (*Success) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{0}
+}
+
+func (m *Success) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Success.Unmarshal(m, b)
+}
+func (m *Success) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Success.Marshal(b, m, deterministic)
+}
+func (m *Success) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Success.Merge(m, src)
+}
+func (m *Success) XXX_Size() int {
+ return xxx_messageInfo_Success.Size(m)
+}
+func (m *Success) XXX_DiscardUnknown() {
+ xxx_messageInfo_Success.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Success proto.InternalMessageInfo
+
+func (m *Success) GetMessage() string {
+ if m != nil && m.Message != nil {
+ return *m.Message
+ }
+ return ""
+}
+
+//*
+// Response: Failure of the previous request
+// @end
+type Failure struct {
+ Code *Failure_FailureType `protobuf:"varint,1,opt,name=code,enum=hw.trezor.messages.common.Failure_FailureType" json:"code,omitempty"`
+ Message *string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Failure) Reset() { *m = Failure{} }
+func (m *Failure) String() string { return proto.CompactTextString(m) }
+func (*Failure) ProtoMessage() {}
+func (*Failure) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{1}
+}
+
+func (m *Failure) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Failure.Unmarshal(m, b)
+}
+func (m *Failure) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Failure.Marshal(b, m, deterministic)
+}
+func (m *Failure) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Failure.Merge(m, src)
+}
+func (m *Failure) XXX_Size() int {
+ return xxx_messageInfo_Failure.Size(m)
+}
+func (m *Failure) XXX_DiscardUnknown() {
+ xxx_messageInfo_Failure.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Failure proto.InternalMessageInfo
+
+func (m *Failure) GetCode() Failure_FailureType {
+ if m != nil && m.Code != nil {
+ return *m.Code
+ }
+ return Failure_Failure_UnexpectedMessage
+}
+
+func (m *Failure) GetMessage() string {
+ if m != nil && m.Message != nil {
+ return *m.Message
+ }
+ return ""
+}
+
+//*
+// Response: Device is waiting for HW button press.
+// @auxstart
+// @next ButtonAck
+type ButtonRequest struct {
+ Code *ButtonRequest_ButtonRequestType `protobuf:"varint,1,opt,name=code,enum=hw.trezor.messages.common.ButtonRequest_ButtonRequestType" json:"code,omitempty"`
+ Data *string `protobuf:"bytes,2,opt,name=data" json:"data,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ButtonRequest) Reset() { *m = ButtonRequest{} }
+func (m *ButtonRequest) String() string { return proto.CompactTextString(m) }
+func (*ButtonRequest) ProtoMessage() {}
+func (*ButtonRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{2}
+}
+
+func (m *ButtonRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ButtonRequest.Unmarshal(m, b)
+}
+func (m *ButtonRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ButtonRequest.Marshal(b, m, deterministic)
+}
+func (m *ButtonRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ButtonRequest.Merge(m, src)
+}
+func (m *ButtonRequest) XXX_Size() int {
+ return xxx_messageInfo_ButtonRequest.Size(m)
+}
+func (m *ButtonRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_ButtonRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ButtonRequest proto.InternalMessageInfo
+
+func (m *ButtonRequest) GetCode() ButtonRequest_ButtonRequestType {
+ if m != nil && m.Code != nil {
+ return *m.Code
+ }
+ return ButtonRequest_ButtonRequest_Other
+}
+
+func (m *ButtonRequest) GetData() string {
+ if m != nil && m.Data != nil {
+ return *m.Data
+ }
+ return ""
+}
+
+//*
+// Request: Computer agrees to wait for HW button press
+// @auxend
+type ButtonAck struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ButtonAck) Reset() { *m = ButtonAck{} }
+func (m *ButtonAck) String() string { return proto.CompactTextString(m) }
+func (*ButtonAck) ProtoMessage() {}
+func (*ButtonAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{3}
+}
+
+func (m *ButtonAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ButtonAck.Unmarshal(m, b)
+}
+func (m *ButtonAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ButtonAck.Marshal(b, m, deterministic)
+}
+func (m *ButtonAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ButtonAck.Merge(m, src)
+}
+func (m *ButtonAck) XXX_Size() int {
+ return xxx_messageInfo_ButtonAck.Size(m)
+}
+func (m *ButtonAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_ButtonAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ButtonAck proto.InternalMessageInfo
+
+//*
+// Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
+// @auxstart
+// @next PinMatrixAck
+type PinMatrixRequest struct {
+ Type *PinMatrixRequest_PinMatrixRequestType `protobuf:"varint,1,opt,name=type,enum=hw.trezor.messages.common.PinMatrixRequest_PinMatrixRequestType" json:"type,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PinMatrixRequest) Reset() { *m = PinMatrixRequest{} }
+func (m *PinMatrixRequest) String() string { return proto.CompactTextString(m) }
+func (*PinMatrixRequest) ProtoMessage() {}
+func (*PinMatrixRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{4}
+}
+
+func (m *PinMatrixRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_PinMatrixRequest.Unmarshal(m, b)
+}
+func (m *PinMatrixRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_PinMatrixRequest.Marshal(b, m, deterministic)
+}
+func (m *PinMatrixRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PinMatrixRequest.Merge(m, src)
+}
+func (m *PinMatrixRequest) XXX_Size() int {
+ return xxx_messageInfo_PinMatrixRequest.Size(m)
+}
+func (m *PinMatrixRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_PinMatrixRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PinMatrixRequest proto.InternalMessageInfo
+
+func (m *PinMatrixRequest) GetType() PinMatrixRequest_PinMatrixRequestType {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return PinMatrixRequest_PinMatrixRequestType_Current
+}
+
+//*
+// Request: Computer responds with encoded PIN
+// @auxend
+type PinMatrixAck struct {
+ Pin *string `protobuf:"bytes,1,req,name=pin" json:"pin,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PinMatrixAck) Reset() { *m = PinMatrixAck{} }
+func (m *PinMatrixAck) String() string { return proto.CompactTextString(m) }
+func (*PinMatrixAck) ProtoMessage() {}
+func (*PinMatrixAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{5}
+}
+
+func (m *PinMatrixAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_PinMatrixAck.Unmarshal(m, b)
+}
+func (m *PinMatrixAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_PinMatrixAck.Marshal(b, m, deterministic)
+}
+func (m *PinMatrixAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PinMatrixAck.Merge(m, src)
+}
+func (m *PinMatrixAck) XXX_Size() int {
+ return xxx_messageInfo_PinMatrixAck.Size(m)
+}
+func (m *PinMatrixAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_PinMatrixAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PinMatrixAck proto.InternalMessageInfo
+
+func (m *PinMatrixAck) GetPin() string {
+ if m != nil && m.Pin != nil {
+ return *m.Pin
+ }
+ return ""
+}
+
+//*
+// Response: Device awaits encryption passphrase
+// @auxstart
+// @next PassphraseAck
+type PassphraseRequest struct {
+ OnDevice *bool `protobuf:"varint,1,opt,name=on_device,json=onDevice" json:"on_device,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PassphraseRequest) Reset() { *m = PassphraseRequest{} }
+func (m *PassphraseRequest) String() string { return proto.CompactTextString(m) }
+func (*PassphraseRequest) ProtoMessage() {}
+func (*PassphraseRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{6}
+}
+
+func (m *PassphraseRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_PassphraseRequest.Unmarshal(m, b)
+}
+func (m *PassphraseRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_PassphraseRequest.Marshal(b, m, deterministic)
+}
+func (m *PassphraseRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PassphraseRequest.Merge(m, src)
+}
+func (m *PassphraseRequest) XXX_Size() int {
+ return xxx_messageInfo_PassphraseRequest.Size(m)
+}
+func (m *PassphraseRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_PassphraseRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PassphraseRequest proto.InternalMessageInfo
+
+func (m *PassphraseRequest) GetOnDevice() bool {
+ if m != nil && m.OnDevice != nil {
+ return *m.OnDevice
+ }
+ return false
+}
+
+//*
+// Request: Send passphrase back
+// @next PassphraseStateRequest
+type PassphraseAck struct {
+ Passphrase *string `protobuf:"bytes,1,opt,name=passphrase" json:"passphrase,omitempty"`
+ State []byte `protobuf:"bytes,2,opt,name=state" json:"state,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PassphraseAck) Reset() { *m = PassphraseAck{} }
+func (m *PassphraseAck) String() string { return proto.CompactTextString(m) }
+func (*PassphraseAck) ProtoMessage() {}
+func (*PassphraseAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{7}
+}
+
+func (m *PassphraseAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_PassphraseAck.Unmarshal(m, b)
+}
+func (m *PassphraseAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_PassphraseAck.Marshal(b, m, deterministic)
+}
+func (m *PassphraseAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PassphraseAck.Merge(m, src)
+}
+func (m *PassphraseAck) XXX_Size() int {
+ return xxx_messageInfo_PassphraseAck.Size(m)
+}
+func (m *PassphraseAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_PassphraseAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PassphraseAck proto.InternalMessageInfo
+
+func (m *PassphraseAck) GetPassphrase() string {
+ if m != nil && m.Passphrase != nil {
+ return *m.Passphrase
+ }
+ return ""
+}
+
+func (m *PassphraseAck) GetState() []byte {
+ if m != nil {
+ return m.State
+ }
+ return nil
+}
+
+//*
+// Response: Device awaits passphrase state
+// @next PassphraseStateAck
+type PassphraseStateRequest struct {
+ State []byte `protobuf:"bytes,1,opt,name=state" json:"state,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PassphraseStateRequest) Reset() { *m = PassphraseStateRequest{} }
+func (m *PassphraseStateRequest) String() string { return proto.CompactTextString(m) }
+func (*PassphraseStateRequest) ProtoMessage() {}
+func (*PassphraseStateRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{8}
+}
+
+func (m *PassphraseStateRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_PassphraseStateRequest.Unmarshal(m, b)
+}
+func (m *PassphraseStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_PassphraseStateRequest.Marshal(b, m, deterministic)
+}
+func (m *PassphraseStateRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PassphraseStateRequest.Merge(m, src)
+}
+func (m *PassphraseStateRequest) XXX_Size() int {
+ return xxx_messageInfo_PassphraseStateRequest.Size(m)
+}
+func (m *PassphraseStateRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_PassphraseStateRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PassphraseStateRequest proto.InternalMessageInfo
+
+func (m *PassphraseStateRequest) GetState() []byte {
+ if m != nil {
+ return m.State
+ }
+ return nil
+}
+
+//*
+// Request: Send passphrase state back
+// @auxend
+type PassphraseStateAck struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PassphraseStateAck) Reset() { *m = PassphraseStateAck{} }
+func (m *PassphraseStateAck) String() string { return proto.CompactTextString(m) }
+func (*PassphraseStateAck) ProtoMessage() {}
+func (*PassphraseStateAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{9}
+}
+
+func (m *PassphraseStateAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_PassphraseStateAck.Unmarshal(m, b)
+}
+func (m *PassphraseStateAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_PassphraseStateAck.Marshal(b, m, deterministic)
+}
+func (m *PassphraseStateAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PassphraseStateAck.Merge(m, src)
+}
+func (m *PassphraseStateAck) XXX_Size() int {
+ return xxx_messageInfo_PassphraseStateAck.Size(m)
+}
+func (m *PassphraseStateAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_PassphraseStateAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PassphraseStateAck proto.InternalMessageInfo
+
+//*
+// Structure representing BIP32 (hierarchical deterministic) node
+// Used for imports of private key into the device and exporting public key out of device
+// @embed
+type HDNodeType struct {
+ Depth *uint32 `protobuf:"varint,1,req,name=depth" json:"depth,omitempty"`
+ Fingerprint *uint32 `protobuf:"varint,2,req,name=fingerprint" json:"fingerprint,omitempty"`
+ ChildNum *uint32 `protobuf:"varint,3,req,name=child_num,json=childNum" json:"child_num,omitempty"`
+ ChainCode []byte `protobuf:"bytes,4,req,name=chain_code,json=chainCode" json:"chain_code,omitempty"`
+ PrivateKey []byte `protobuf:"bytes,5,opt,name=private_key,json=privateKey" json:"private_key,omitempty"`
+ PublicKey []byte `protobuf:"bytes,6,opt,name=public_key,json=publicKey" json:"public_key,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *HDNodeType) Reset() { *m = HDNodeType{} }
+func (m *HDNodeType) String() string { return proto.CompactTextString(m) }
+func (*HDNodeType) ProtoMessage() {}
+func (*HDNodeType) Descriptor() ([]byte, []int) {
+ return fileDescriptor_aaf30d059fdbc38d, []int{10}
+}
+
+func (m *HDNodeType) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_HDNodeType.Unmarshal(m, b)
+}
+func (m *HDNodeType) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_HDNodeType.Marshal(b, m, deterministic)
+}
+func (m *HDNodeType) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_HDNodeType.Merge(m, src)
+}
+func (m *HDNodeType) XXX_Size() int {
+ return xxx_messageInfo_HDNodeType.Size(m)
+}
+func (m *HDNodeType) XXX_DiscardUnknown() {
+ xxx_messageInfo_HDNodeType.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_HDNodeType proto.InternalMessageInfo
+
+func (m *HDNodeType) GetDepth() uint32 {
+ if m != nil && m.Depth != nil {
+ return *m.Depth
+ }
+ return 0
+}
+
+func (m *HDNodeType) GetFingerprint() uint32 {
+ if m != nil && m.Fingerprint != nil {
+ return *m.Fingerprint
+ }
+ return 0
+}
+
+func (m *HDNodeType) GetChildNum() uint32 {
+ if m != nil && m.ChildNum != nil {
+ return *m.ChildNum
+ }
+ return 0
+}
+
+func (m *HDNodeType) GetChainCode() []byte {
+ if m != nil {
+ return m.ChainCode
+ }
+ return nil
+}
+
+func (m *HDNodeType) GetPrivateKey() []byte {
+ if m != nil {
+ return m.PrivateKey
+ }
+ return nil
+}
+
+func (m *HDNodeType) GetPublicKey() []byte {
+ if m != nil {
+ return m.PublicKey
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterEnum("hw.trezor.messages.common.Failure_FailureType", Failure_FailureType_name, Failure_FailureType_value)
+ proto.RegisterEnum("hw.trezor.messages.common.ButtonRequest_ButtonRequestType", ButtonRequest_ButtonRequestType_name, ButtonRequest_ButtonRequestType_value)
+ proto.RegisterEnum("hw.trezor.messages.common.PinMatrixRequest_PinMatrixRequestType", PinMatrixRequest_PinMatrixRequestType_name, PinMatrixRequest_PinMatrixRequestType_value)
+ proto.RegisterType((*Success)(nil), "hw.trezor.messages.common.Success")
+ proto.RegisterType((*Failure)(nil), "hw.trezor.messages.common.Failure")
+ proto.RegisterType((*ButtonRequest)(nil), "hw.trezor.messages.common.ButtonRequest")
+ proto.RegisterType((*ButtonAck)(nil), "hw.trezor.messages.common.ButtonAck")
+ proto.RegisterType((*PinMatrixRequest)(nil), "hw.trezor.messages.common.PinMatrixRequest")
+ proto.RegisterType((*PinMatrixAck)(nil), "hw.trezor.messages.common.PinMatrixAck")
+ proto.RegisterType((*PassphraseRequest)(nil), "hw.trezor.messages.common.PassphraseRequest")
+ proto.RegisterType((*PassphraseAck)(nil), "hw.trezor.messages.common.PassphraseAck")
+ proto.RegisterType((*PassphraseStateRequest)(nil), "hw.trezor.messages.common.PassphraseStateRequest")
+ proto.RegisterType((*PassphraseStateAck)(nil), "hw.trezor.messages.common.PassphraseStateAck")
+ proto.RegisterType((*HDNodeType)(nil), "hw.trezor.messages.common.HDNodeType")
+}
+
+func init() { proto.RegisterFile("messages-common.proto", fileDescriptor_aaf30d059fdbc38d) }
+
+var fileDescriptor_aaf30d059fdbc38d = []byte{
+ // 846 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x54, 0xcd, 0x52, 0x23, 0x37,
+ 0x10, 0x2e, 0xff, 0x80, 0xed, 0xb6, 0xd9, 0x08, 0xc5, 0x80, 0x09, 0xb0, 0x38, 0xc3, 0x21, 0x5c,
+ 0xe2, 0x4a, 0xe5, 0x98, 0x53, 0x58, 0x83, 0x2b, 0xd4, 0x16, 0x86, 0x1a, 0xd8, 0xda, 0xa3, 0x4b,
+ 0xd1, 0xf4, 0x32, 0x2a, 0xcf, 0x48, 0x13, 0x8d, 0x06, 0xf0, 0x5e, 0xf2, 0x6a, 0x79, 0x89, 0xbc,
+ 0x42, 0xaa, 0x52, 0xb9, 0xe4, 0x11, 0xb6, 0x34, 0x3f, 0x78, 0xc6, 0x66, 0x39, 0xcd, 0xe8, 0xfb,
+ 0xbe, 0xee, 0x96, 0xba, 0x3f, 0x09, 0x76, 0x42, 0x8c, 0x63, 0x76, 0x8f, 0xf1, 0x8f, 0x5c, 0x85,
+ 0xa1, 0x92, 0xa3, 0x48, 0x2b, 0xa3, 0xe8, 0xbe, 0xff, 0x38, 0x32, 0x1a, 0x3f, 0x2b, 0x3d, 0x2a,
+ 0x04, 0xa3, 0x4c, 0xe0, 0x9c, 0x40, 0xeb, 0x36, 0xe1, 0x1c, 0xe3, 0x98, 0x0e, 0xa0, 0x95, 0xb3,
+ 0x83, 0xda, 0xb0, 0x76, 0xda, 0x71, 0x8b, 0xa5, 0xf3, 0x77, 0x03, 0x5a, 0x13, 0x26, 0x82, 0x44,
+ 0x23, 0x7d, 0x07, 0x4d, 0xae, 0xbc, 0x4c, 0xf2, 0xe6, 0xe7, 0xd1, 0xe8, 0xab, 0xa9, 0x47, 0x79,
+ 0x44, 0xf1, 0xbd, 0x5b, 0x44, 0xe8, 0xa6, 0xb1, 0xe5, 0x4a, 0xf5, 0x6a, 0xa5, 0xff, 0xea, 0xd0,
+ 0x2d, 0xe9, 0xe9, 0x11, 0xec, 0xe7, 0xcb, 0xd9, 0x07, 0x89, 0x4f, 0x11, 0x72, 0x83, 0xde, 0x55,
+ 0x26, 0x26, 0x35, 0xfa, 0x1d, 0xec, 0x16, 0xf4, 0xbb, 0xc4, 0x18, 0x25, 0x2f, 0x72, 0x09, 0xa9,
+ 0xd3, 0x1d, 0xd8, 0x2e, 0xb8, 0x73, 0x66, 0xd8, 0x85, 0xd6, 0x4a, 0x93, 0x06, 0x3d, 0x80, 0xbd,
+ 0x02, 0x3e, 0xe3, 0x46, 0x28, 0x39, 0x66, 0x92, 0x63, 0x10, 0xa0, 0x47, 0x9a, 0x74, 0x0f, 0xbe,
+ 0x2d, 0xc8, 0x1b, 0xb1, 0x4c, 0xb6, 0x41, 0x07, 0xd0, 0x2f, 0x11, 0xcb, 0x90, 0x4d, 0xba, 0x0b,
+ 0xb4, 0xc4, 0x5c, 0xca, 0x07, 0x16, 0x08, 0x8f, 0xb4, 0xe8, 0x21, 0x0c, 0x0a, 0x3c, 0x07, 0x6f,
+ 0xc5, 0xbd, 0x64, 0x26, 0xd1, 0x48, 0xda, 0x95, 0x7c, 0x5a, 0xd9, 0xf6, 0x67, 0xfb, 0xeb, 0x94,
+ 0x8f, 0x34, 0x55, 0xe6, 0x42, 0xaa, 0xe4, 0xde, 0x9f, 0x24, 0xd2, 0x8b, 0x09, 0xac, 0x70, 0x97,
+ 0x52, 0x18, 0xc1, 0x02, 0xf1, 0x19, 0x3d, 0xd2, 0x5d, 0xd9, 0xfa, 0x95, 0x88, 0x43, 0x66, 0xb8,
+ 0x4f, 0x7a, 0x74, 0x1f, 0x76, 0x0a, 0x62, 0x22, 0x74, 0xf8, 0xc8, 0x34, 0x66, 0xb5, 0xb8, 0xf3,
+ 0x4f, 0x13, 0xb6, 0xb2, 0xbe, 0xb9, 0xf8, 0x47, 0x82, 0xb1, 0xa1, 0xd3, 0xca, 0x74, 0x7f, 0x79,
+ 0x65, 0xba, 0x95, 0xb8, 0xea, 0xaa, 0x34, 0x69, 0x0a, 0x4d, 0x8f, 0x19, 0x96, 0x8f, 0x39, 0xfd,
+ 0x77, 0xfe, 0x6f, 0xc0, 0xf6, 0x9a, 0xde, 0xee, 0xbf, 0x02, 0xce, 0xae, 0x8d, 0x8f, 0x9a, 0xd4,
+ 0xa8, 0x03, 0x6f, 0xab, 0xc4, 0x04, 0xf1, 0xfa, 0x01, 0xf5, 0x9d, 0xaf, 0x31, 0xf6, 0x55, 0x60,
+ 0x67, 0x7d, 0x0c, 0x07, 0x55, 0xcd, 0x58, 0xc9, 0x4f, 0x42, 0x87, 0xd7, 0x89, 0x89, 0x12, 0x43,
+ 0x1a, 0xd6, 0x47, 0x55, 0x81, 0x8b, 0x31, 0x9a, 0x73, 0x7c, 0x10, 0x1c, 0x49, 0x73, 0x9d, 0xce,
+ 0xe3, 0x3f, 0x2a, 0x6d, 0xa7, 0x7f, 0x08, 0x83, 0x2a, 0xfd, 0x51, 0x44, 0x98, 0x07, 0x6f, 0xae,
+ 0x07, 0xdf, 0x68, 0x65, 0x90, 0x9b, 0x31, 0x0b, 0x02, 0xd2, 0xb2, 0xa3, 0xae, 0xd2, 0xd6, 0x07,
+ 0x77, 0x4f, 0xa4, 0xbd, 0xbe, 0xeb, 0x62, 0x3e, 0x63, 0x1f, 0xf9, 0x9c, 0x74, 0xec, 0xe8, 0xaa,
+ 0x82, 0x33, 0xcf, 0xd3, 0x18, 0x5b, 0x2b, 0x1c, 0xc0, 0xde, 0x4a, 0xd1, 0xe4, 0xf7, 0x40, 0xf0,
+ 0xf7, 0xb8, 0x20, 0x5d, 0x7a, 0x02, 0xc7, 0x55, 0xf2, 0x4a, 0x62, 0xa8, 0xa4, 0xe0, 0xf6, 0x3c,
+ 0x63, 0x95, 0x48, 0x43, 0x7a, 0xeb, 0xd5, 0x0b, 0xd1, 0xa5, 0xb4, 0x3d, 0xdb, 0xa2, 0x43, 0x38,
+ 0x5c, 0x29, 0xc1, 0xe2, 0x38, 0xf2, 0x35, 0x8b, 0xd3, 0xbb, 0x49, 0xde, 0xd0, 0x1f, 0xe0, 0xa4,
+ 0xaa, 0xf8, 0x20, 0xe7, 0x52, 0x3d, 0xca, 0x73, 0xd4, 0xe2, 0x81, 0xd9, 0xcb, 0x75, 0xc3, 0x8c,
+ 0x4f, 0xbe, 0x71, 0xba, 0xd0, 0xc9, 0x84, 0x67, 0x7c, 0xee, 0xfc, 0x5b, 0x03, 0x62, 0x2d, 0xca,
+ 0x8c, 0x16, 0x4f, 0x85, 0xf1, 0xee, 0xa0, 0x69, 0x16, 0x51, 0x61, 0xbc, 0x5f, 0x5f, 0x31, 0xde,
+ 0x6a, 0xe8, 0x1a, 0x90, 0xd9, 0xcf, 0x66, 0x73, 0xfe, 0x84, 0xfe, 0x4b, 0xac, 0x3d, 0xda, 0x4b,
+ 0xf8, 0x6c, 0x9c, 0x68, 0x8d, 0xd2, 0x90, 0x1a, 0xfd, 0x1e, 0x8e, 0x5e, 0x54, 0x4c, 0xf1, 0x71,
+ 0x22, 0x74, 0x6c, 0x48, 0xdd, 0x1a, 0xf3, 0x6b, 0x92, 0x5b, 0xe4, 0x4a, 0x7a, 0xa4, 0xe1, 0x0c,
+ 0xa1, 0xf7, 0xac, 0x39, 0xe3, 0x73, 0x4a, 0xa0, 0x11, 0x09, 0x39, 0xa8, 0x0d, 0xeb, 0xa7, 0x1d,
+ 0xd7, 0xfe, 0x3a, 0x3f, 0xc1, 0xf6, 0xb2, 0xaf, 0x45, 0x37, 0x0e, 0xa0, 0xa3, 0xe4, 0xcc, 0x4b,
+ 0x1d, 0x96, 0xb6, 0xa4, 0xed, 0xb6, 0x95, 0xcc, 0x1c, 0xe7, 0x5c, 0xc0, 0xd6, 0x32, 0xc2, 0x26,
+ 0x7d, 0x0b, 0x10, 0x3d, 0x03, 0xf9, 0xdb, 0x5d, 0x42, 0x68, 0x1f, 0x36, 0x62, 0xc3, 0x4c, 0xf6,
+ 0xd8, 0xf6, 0xdc, 0x6c, 0xe1, 0x8c, 0x60, 0x77, 0x99, 0xe6, 0xd6, 0x42, 0x45, 0xf5, 0x67, 0x7d,
+ 0xad, 0xac, 0xef, 0x03, 0x5d, 0xd1, 0xdb, 0x61, 0xfe, 0x55, 0x03, 0xf8, 0xed, 0x7c, 0xaa, 0xbc,
+ 0xec, 0xbd, 0xee, 0xc3, 0x86, 0x87, 0x91, 0xf1, 0xd3, 0x13, 0x6e, 0xb9, 0xd9, 0x82, 0x0e, 0xa1,
+ 0xfb, 0x49, 0xc8, 0x7b, 0xd4, 0x91, 0x16, 0xd2, 0x0c, 0xea, 0x29, 0x57, 0x86, 0xec, 0x81, 0xb9,
+ 0x2f, 0x02, 0x6f, 0x26, 0x93, 0x70, 0xd0, 0x48, 0xf9, 0x76, 0x0a, 0x4c, 0x93, 0x90, 0x1e, 0x01,
+ 0x70, 0x9f, 0x09, 0x39, 0x4b, 0x9f, 0xa6, 0xe6, 0xb0, 0x7e, 0xda, 0x73, 0x3b, 0x29, 0x32, 0xb6,
+ 0x6f, 0xcc, 0x31, 0x74, 0xa3, 0xd4, 0x6f, 0x38, 0x9b, 0xe3, 0x62, 0xb0, 0x91, 0x6e, 0x1a, 0x72,
+ 0xe8, 0x3d, 0x2e, 0x6c, 0x7c, 0x94, 0xde, 0x8e, 0x94, 0xdf, 0x4c, 0xf9, 0x4e, 0x54, 0xdc, 0x97,
+ 0x2f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xb2, 0x7d, 0x20, 0xa6, 0x35, 0x07, 0x00, 0x00,
+}
diff --git a/accounts/usbwallet/trezor/messages-common.proto b/accounts/usbwallet/trezor/messages-common.proto
new file mode 100644
index 000000000..75a983b0a
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages-common.proto
@@ -0,0 +1,147 @@
+// This file originates from the SatoshiLabs Trezor `common` repository at:
+// https://github.com/trezor/trezor-common/blob/master/protob/messages-common.proto
+// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
+
+syntax = "proto2";
+package hw.trezor.messages.common;
+
+/**
+ * Response: Success of the previous request
+ * @end
+ */
+message Success {
+ optional string message = 1; // human readable description of action or request-specific payload
+}
+
+/**
+ * Response: Failure of the previous request
+ * @end
+ */
+message Failure {
+ optional FailureType code = 1; // computer-readable definition of the error state
+ optional string message = 2; // human-readable message of the error state
+ enum FailureType {
+ Failure_UnexpectedMessage = 1;
+ Failure_ButtonExpected = 2;
+ Failure_DataError = 3;
+ Failure_ActionCancelled = 4;
+ Failure_PinExpected = 5;
+ Failure_PinCancelled = 6;
+ Failure_PinInvalid = 7;
+ Failure_InvalidSignature = 8;
+ Failure_ProcessError = 9;
+ Failure_NotEnoughFunds = 10;
+ Failure_NotInitialized = 11;
+ Failure_PinMismatch = 12;
+ Failure_FirmwareError = 99;
+ }
+}
+
+/**
+ * Response: Device is waiting for HW button press.
+ * @auxstart
+ * @next ButtonAck
+ */
+message ButtonRequest {
+ optional ButtonRequestType code = 1;
+ optional string data = 2;
+ /**
+ * Type of button request
+ */
+ enum ButtonRequestType {
+ ButtonRequest_Other = 1;
+ ButtonRequest_FeeOverThreshold = 2;
+ ButtonRequest_ConfirmOutput = 3;
+ ButtonRequest_ResetDevice = 4;
+ ButtonRequest_ConfirmWord = 5;
+ ButtonRequest_WipeDevice = 6;
+ ButtonRequest_ProtectCall = 7;
+ ButtonRequest_SignTx = 8;
+ ButtonRequest_FirmwareCheck = 9;
+ ButtonRequest_Address = 10;
+ ButtonRequest_PublicKey = 11;
+ ButtonRequest_MnemonicWordCount = 12;
+ ButtonRequest_MnemonicInput = 13;
+ ButtonRequest_PassphraseType = 14;
+ ButtonRequest_UnknownDerivationPath = 15;
+ }
+}
+
+/**
+ * Request: Computer agrees to wait for HW button press
+ * @auxend
+ */
+message ButtonAck {
+}
+
+/**
+ * Response: Device is asking computer to show PIN matrix and awaits PIN encoded using this matrix scheme
+ * @auxstart
+ * @next PinMatrixAck
+ */
+message PinMatrixRequest {
+ optional PinMatrixRequestType type = 1;
+ /**
+ * Type of PIN request
+ */
+ enum PinMatrixRequestType {
+ PinMatrixRequestType_Current = 1;
+ PinMatrixRequestType_NewFirst = 2;
+ PinMatrixRequestType_NewSecond = 3;
+ }
+}
+
+/**
+ * Request: Computer responds with encoded PIN
+ * @auxend
+ */
+message PinMatrixAck {
+ required string pin = 1; // matrix encoded PIN entered by user
+}
+
+/**
+ * Response: Device awaits encryption passphrase
+ * @auxstart
+ * @next PassphraseAck
+ */
+message PassphraseRequest {
+ optional bool on_device = 1; // passphrase is being entered on the device
+}
+
+/**
+ * Request: Send passphrase back
+ * @next PassphraseStateRequest
+ */
+message PassphraseAck {
+ optional string passphrase = 1;
+ optional bytes state = 2; // expected device state
+}
+
+/**
+ * Response: Device awaits passphrase state
+ * @next PassphraseStateAck
+ */
+message PassphraseStateRequest {
+ optional bytes state = 1; // actual device state
+}
+
+/**
+ * Request: Send passphrase state back
+ * @auxend
+ */
+message PassphraseStateAck {
+}
+
+/**
+ * Structure representing BIP32 (hierarchical deterministic) node
+ * Used for imports of private key into the device and exporting public key out of device
+ * @embed
+ */
+message HDNodeType {
+ required uint32 depth = 1;
+ required uint32 fingerprint = 2;
+ required uint32 child_num = 3;
+ required bytes chain_code = 4;
+ optional bytes private_key = 5;
+ optional bytes public_key = 6;
+}
diff --git a/accounts/usbwallet/trezor/messages-ethereum.pb.go b/accounts/usbwallet/trezor/messages-ethereum.pb.go
new file mode 100644
index 000000000..5d664f5ba
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages-ethereum.pb.go
@@ -0,0 +1,698 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: messages-ethereum.proto
+
+package trezor
+
+import (
+ fmt "fmt"
+ math "math"
+
+ proto "github.com/golang/protobuf/proto"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
+
+//*
+// Request: Ask device for public key corresponding to address_n path
+// @start
+// @next EthereumPublicKey
+// @next Failure
+type EthereumGetPublicKey struct {
+ AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
+ ShowDisplay *bool `protobuf:"varint,2,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumGetPublicKey) Reset() { *m = EthereumGetPublicKey{} }
+func (m *EthereumGetPublicKey) String() string { return proto.CompactTextString(m) }
+func (*EthereumGetPublicKey) ProtoMessage() {}
+func (*EthereumGetPublicKey) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{0}
+}
+
+func (m *EthereumGetPublicKey) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumGetPublicKey.Unmarshal(m, b)
+}
+func (m *EthereumGetPublicKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumGetPublicKey.Marshal(b, m, deterministic)
+}
+func (m *EthereumGetPublicKey) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumGetPublicKey.Merge(m, src)
+}
+func (m *EthereumGetPublicKey) XXX_Size() int {
+ return xxx_messageInfo_EthereumGetPublicKey.Size(m)
+}
+func (m *EthereumGetPublicKey) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumGetPublicKey.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumGetPublicKey proto.InternalMessageInfo
+
+func (m *EthereumGetPublicKey) GetAddressN() []uint32 {
+ if m != nil {
+ return m.AddressN
+ }
+ return nil
+}
+
+func (m *EthereumGetPublicKey) GetShowDisplay() bool {
+ if m != nil && m.ShowDisplay != nil {
+ return *m.ShowDisplay
+ }
+ return false
+}
+
+//*
+// Response: Contains public key derived from device private seed
+// @end
+type EthereumPublicKey struct {
+ Node *HDNodeType `protobuf:"bytes,1,opt,name=node" json:"node,omitempty"`
+ Xpub *string `protobuf:"bytes,2,opt,name=xpub" json:"xpub,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumPublicKey) Reset() { *m = EthereumPublicKey{} }
+func (m *EthereumPublicKey) String() string { return proto.CompactTextString(m) }
+func (*EthereumPublicKey) ProtoMessage() {}
+func (*EthereumPublicKey) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{1}
+}
+
+func (m *EthereumPublicKey) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumPublicKey.Unmarshal(m, b)
+}
+func (m *EthereumPublicKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumPublicKey.Marshal(b, m, deterministic)
+}
+func (m *EthereumPublicKey) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumPublicKey.Merge(m, src)
+}
+func (m *EthereumPublicKey) XXX_Size() int {
+ return xxx_messageInfo_EthereumPublicKey.Size(m)
+}
+func (m *EthereumPublicKey) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumPublicKey.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumPublicKey proto.InternalMessageInfo
+
+func (m *EthereumPublicKey) GetNode() *HDNodeType {
+ if m != nil {
+ return m.Node
+ }
+ return nil
+}
+
+func (m *EthereumPublicKey) GetXpub() string {
+ if m != nil && m.Xpub != nil {
+ return *m.Xpub
+ }
+ return ""
+}
+
+//*
+// Request: Ask device for Ethereum address corresponding to address_n path
+// @start
+// @next EthereumAddress
+// @next Failure
+type EthereumGetAddress struct {
+ AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
+ ShowDisplay *bool `protobuf:"varint,2,opt,name=show_display,json=showDisplay" json:"show_display,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumGetAddress) Reset() { *m = EthereumGetAddress{} }
+func (m *EthereumGetAddress) String() string { return proto.CompactTextString(m) }
+func (*EthereumGetAddress) ProtoMessage() {}
+func (*EthereumGetAddress) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{2}
+}
+
+func (m *EthereumGetAddress) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumGetAddress.Unmarshal(m, b)
+}
+func (m *EthereumGetAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumGetAddress.Marshal(b, m, deterministic)
+}
+func (m *EthereumGetAddress) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumGetAddress.Merge(m, src)
+}
+func (m *EthereumGetAddress) XXX_Size() int {
+ return xxx_messageInfo_EthereumGetAddress.Size(m)
+}
+func (m *EthereumGetAddress) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumGetAddress.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumGetAddress proto.InternalMessageInfo
+
+func (m *EthereumGetAddress) GetAddressN() []uint32 {
+ if m != nil {
+ return m.AddressN
+ }
+ return nil
+}
+
+func (m *EthereumGetAddress) GetShowDisplay() bool {
+ if m != nil && m.ShowDisplay != nil {
+ return *m.ShowDisplay
+ }
+ return false
+}
+
+//*
+// Response: Contains an Ethereum address derived from device private seed
+// @end
+type EthereumAddress struct {
+ AddressBin []byte `protobuf:"bytes,1,opt,name=addressBin" json:"addressBin,omitempty"`
+ AddressHex *string `protobuf:"bytes,2,opt,name=addressHex" json:"addressHex,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumAddress) Reset() { *m = EthereumAddress{} }
+func (m *EthereumAddress) String() string { return proto.CompactTextString(m) }
+func (*EthereumAddress) ProtoMessage() {}
+func (*EthereumAddress) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{3}
+}
+
+func (m *EthereumAddress) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumAddress.Unmarshal(m, b)
+}
+func (m *EthereumAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumAddress.Marshal(b, m, deterministic)
+}
+func (m *EthereumAddress) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumAddress.Merge(m, src)
+}
+func (m *EthereumAddress) XXX_Size() int {
+ return xxx_messageInfo_EthereumAddress.Size(m)
+}
+func (m *EthereumAddress) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumAddress.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumAddress proto.InternalMessageInfo
+
+func (m *EthereumAddress) GetAddressBin() []byte {
+ if m != nil {
+ return m.AddressBin
+ }
+ return nil
+}
+
+func (m *EthereumAddress) GetAddressHex() string {
+ if m != nil && m.AddressHex != nil {
+ return *m.AddressHex
+ }
+ return ""
+}
+
+//*
+// Request: Ask device to sign transaction
+// All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
+// Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
+// @start
+// @next EthereumTxRequest
+// @next Failure
+type EthereumSignTx struct {
+ AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
+ Nonce []byte `protobuf:"bytes,2,opt,name=nonce" json:"nonce,omitempty"`
+ GasPrice []byte `protobuf:"bytes,3,opt,name=gas_price,json=gasPrice" json:"gas_price,omitempty"`
+ GasLimit []byte `protobuf:"bytes,4,opt,name=gas_limit,json=gasLimit" json:"gas_limit,omitempty"`
+ ToBin []byte `protobuf:"bytes,5,opt,name=toBin" json:"toBin,omitempty"`
+ ToHex *string `protobuf:"bytes,11,opt,name=toHex" json:"toHex,omitempty"`
+ Value []byte `protobuf:"bytes,6,opt,name=value" json:"value,omitempty"`
+ DataInitialChunk []byte `protobuf:"bytes,7,opt,name=data_initial_chunk,json=dataInitialChunk" json:"data_initial_chunk,omitempty"`
+ DataLength *uint32 `protobuf:"varint,8,opt,name=data_length,json=dataLength" json:"data_length,omitempty"`
+ ChainId *uint32 `protobuf:"varint,9,opt,name=chain_id,json=chainId" json:"chain_id,omitempty"`
+ TxType *uint32 `protobuf:"varint,10,opt,name=tx_type,json=txType" json:"tx_type,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumSignTx) Reset() { *m = EthereumSignTx{} }
+func (m *EthereumSignTx) String() string { return proto.CompactTextString(m) }
+func (*EthereumSignTx) ProtoMessage() {}
+func (*EthereumSignTx) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{4}
+}
+
+func (m *EthereumSignTx) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumSignTx.Unmarshal(m, b)
+}
+func (m *EthereumSignTx) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumSignTx.Marshal(b, m, deterministic)
+}
+func (m *EthereumSignTx) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumSignTx.Merge(m, src)
+}
+func (m *EthereumSignTx) XXX_Size() int {
+ return xxx_messageInfo_EthereumSignTx.Size(m)
+}
+func (m *EthereumSignTx) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumSignTx.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumSignTx proto.InternalMessageInfo
+
+func (m *EthereumSignTx) GetAddressN() []uint32 {
+ if m != nil {
+ return m.AddressN
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetNonce() []byte {
+ if m != nil {
+ return m.Nonce
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetGasPrice() []byte {
+ if m != nil {
+ return m.GasPrice
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetGasLimit() []byte {
+ if m != nil {
+ return m.GasLimit
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetToBin() []byte {
+ if m != nil {
+ return m.ToBin
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetToHex() string {
+ if m != nil && m.ToHex != nil {
+ return *m.ToHex
+ }
+ return ""
+}
+
+func (m *EthereumSignTx) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetDataInitialChunk() []byte {
+ if m != nil {
+ return m.DataInitialChunk
+ }
+ return nil
+}
+
+func (m *EthereumSignTx) GetDataLength() uint32 {
+ if m != nil && m.DataLength != nil {
+ return *m.DataLength
+ }
+ return 0
+}
+
+func (m *EthereumSignTx) GetChainId() uint32 {
+ if m != nil && m.ChainId != nil {
+ return *m.ChainId
+ }
+ return 0
+}
+
+func (m *EthereumSignTx) GetTxType() uint32 {
+ if m != nil && m.TxType != nil {
+ return *m.TxType
+ }
+ return 0
+}
+
+//*
+// Response: Device asks for more data from transaction payload, or returns the signature.
+// If data_length is set, device awaits that many more bytes of payload.
+// Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
+// @end
+// @next EthereumTxAck
+type EthereumTxRequest struct {
+ DataLength *uint32 `protobuf:"varint,1,opt,name=data_length,json=dataLength" json:"data_length,omitempty"`
+ SignatureV *uint32 `protobuf:"varint,2,opt,name=signature_v,json=signatureV" json:"signature_v,omitempty"`
+ SignatureR []byte `protobuf:"bytes,3,opt,name=signature_r,json=signatureR" json:"signature_r,omitempty"`
+ SignatureS []byte `protobuf:"bytes,4,opt,name=signature_s,json=signatureS" json:"signature_s,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumTxRequest) Reset() { *m = EthereumTxRequest{} }
+func (m *EthereumTxRequest) String() string { return proto.CompactTextString(m) }
+func (*EthereumTxRequest) ProtoMessage() {}
+func (*EthereumTxRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{5}
+}
+
+func (m *EthereumTxRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumTxRequest.Unmarshal(m, b)
+}
+func (m *EthereumTxRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumTxRequest.Marshal(b, m, deterministic)
+}
+func (m *EthereumTxRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumTxRequest.Merge(m, src)
+}
+func (m *EthereumTxRequest) XXX_Size() int {
+ return xxx_messageInfo_EthereumTxRequest.Size(m)
+}
+func (m *EthereumTxRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumTxRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumTxRequest proto.InternalMessageInfo
+
+func (m *EthereumTxRequest) GetDataLength() uint32 {
+ if m != nil && m.DataLength != nil {
+ return *m.DataLength
+ }
+ return 0
+}
+
+func (m *EthereumTxRequest) GetSignatureV() uint32 {
+ if m != nil && m.SignatureV != nil {
+ return *m.SignatureV
+ }
+ return 0
+}
+
+func (m *EthereumTxRequest) GetSignatureR() []byte {
+ if m != nil {
+ return m.SignatureR
+ }
+ return nil
+}
+
+func (m *EthereumTxRequest) GetSignatureS() []byte {
+ if m != nil {
+ return m.SignatureS
+ }
+ return nil
+}
+
+//*
+// Request: Transaction payload data.
+// @next EthereumTxRequest
+type EthereumTxAck struct {
+ DataChunk []byte `protobuf:"bytes,1,opt,name=data_chunk,json=dataChunk" json:"data_chunk,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumTxAck) Reset() { *m = EthereumTxAck{} }
+func (m *EthereumTxAck) String() string { return proto.CompactTextString(m) }
+func (*EthereumTxAck) ProtoMessage() {}
+func (*EthereumTxAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{6}
+}
+
+func (m *EthereumTxAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumTxAck.Unmarshal(m, b)
+}
+func (m *EthereumTxAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumTxAck.Marshal(b, m, deterministic)
+}
+func (m *EthereumTxAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumTxAck.Merge(m, src)
+}
+func (m *EthereumTxAck) XXX_Size() int {
+ return xxx_messageInfo_EthereumTxAck.Size(m)
+}
+func (m *EthereumTxAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumTxAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumTxAck proto.InternalMessageInfo
+
+func (m *EthereumTxAck) GetDataChunk() []byte {
+ if m != nil {
+ return m.DataChunk
+ }
+ return nil
+}
+
+//*
+// Request: Ask device to sign message
+// @start
+// @next EthereumMessageSignature
+// @next Failure
+type EthereumSignMessage struct {
+ AddressN []uint32 `protobuf:"varint,1,rep,name=address_n,json=addressN" json:"address_n,omitempty"`
+ Message []byte `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumSignMessage) Reset() { *m = EthereumSignMessage{} }
+func (m *EthereumSignMessage) String() string { return proto.CompactTextString(m) }
+func (*EthereumSignMessage) ProtoMessage() {}
+func (*EthereumSignMessage) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{7}
+}
+
+func (m *EthereumSignMessage) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumSignMessage.Unmarshal(m, b)
+}
+func (m *EthereumSignMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumSignMessage.Marshal(b, m, deterministic)
+}
+func (m *EthereumSignMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumSignMessage.Merge(m, src)
+}
+func (m *EthereumSignMessage) XXX_Size() int {
+ return xxx_messageInfo_EthereumSignMessage.Size(m)
+}
+func (m *EthereumSignMessage) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumSignMessage.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumSignMessage proto.InternalMessageInfo
+
+func (m *EthereumSignMessage) GetAddressN() []uint32 {
+ if m != nil {
+ return m.AddressN
+ }
+ return nil
+}
+
+func (m *EthereumSignMessage) GetMessage() []byte {
+ if m != nil {
+ return m.Message
+ }
+ return nil
+}
+
+//*
+// Response: Signed message
+// @end
+type EthereumMessageSignature struct {
+ AddressBin []byte `protobuf:"bytes,1,opt,name=addressBin" json:"addressBin,omitempty"`
+ Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
+ AddressHex *string `protobuf:"bytes,3,opt,name=addressHex" json:"addressHex,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumMessageSignature) Reset() { *m = EthereumMessageSignature{} }
+func (m *EthereumMessageSignature) String() string { return proto.CompactTextString(m) }
+func (*EthereumMessageSignature) ProtoMessage() {}
+func (*EthereumMessageSignature) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{8}
+}
+
+func (m *EthereumMessageSignature) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumMessageSignature.Unmarshal(m, b)
+}
+func (m *EthereumMessageSignature) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumMessageSignature.Marshal(b, m, deterministic)
+}
+func (m *EthereumMessageSignature) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumMessageSignature.Merge(m, src)
+}
+func (m *EthereumMessageSignature) XXX_Size() int {
+ return xxx_messageInfo_EthereumMessageSignature.Size(m)
+}
+func (m *EthereumMessageSignature) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumMessageSignature.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumMessageSignature proto.InternalMessageInfo
+
+func (m *EthereumMessageSignature) GetAddressBin() []byte {
+ if m != nil {
+ return m.AddressBin
+ }
+ return nil
+}
+
+func (m *EthereumMessageSignature) GetSignature() []byte {
+ if m != nil {
+ return m.Signature
+ }
+ return nil
+}
+
+func (m *EthereumMessageSignature) GetAddressHex() string {
+ if m != nil && m.AddressHex != nil {
+ return *m.AddressHex
+ }
+ return ""
+}
+
+//*
+// Request: Ask device to verify message
+// @start
+// @next Success
+// @next Failure
+type EthereumVerifyMessage struct {
+ AddressBin []byte `protobuf:"bytes,1,opt,name=addressBin" json:"addressBin,omitempty"`
+ Signature []byte `protobuf:"bytes,2,opt,name=signature" json:"signature,omitempty"`
+ Message []byte `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"`
+ AddressHex *string `protobuf:"bytes,4,opt,name=addressHex" json:"addressHex,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EthereumVerifyMessage) Reset() { *m = EthereumVerifyMessage{} }
+func (m *EthereumVerifyMessage) String() string { return proto.CompactTextString(m) }
+func (*EthereumVerifyMessage) ProtoMessage() {}
+func (*EthereumVerifyMessage) Descriptor() ([]byte, []int) {
+ return fileDescriptor_cb33f46ba915f15c, []int{9}
+}
+
+func (m *EthereumVerifyMessage) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EthereumVerifyMessage.Unmarshal(m, b)
+}
+func (m *EthereumVerifyMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EthereumVerifyMessage.Marshal(b, m, deterministic)
+}
+func (m *EthereumVerifyMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EthereumVerifyMessage.Merge(m, src)
+}
+func (m *EthereumVerifyMessage) XXX_Size() int {
+ return xxx_messageInfo_EthereumVerifyMessage.Size(m)
+}
+func (m *EthereumVerifyMessage) XXX_DiscardUnknown() {
+ xxx_messageInfo_EthereumVerifyMessage.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EthereumVerifyMessage proto.InternalMessageInfo
+
+func (m *EthereumVerifyMessage) GetAddressBin() []byte {
+ if m != nil {
+ return m.AddressBin
+ }
+ return nil
+}
+
+func (m *EthereumVerifyMessage) GetSignature() []byte {
+ if m != nil {
+ return m.Signature
+ }
+ return nil
+}
+
+func (m *EthereumVerifyMessage) GetMessage() []byte {
+ if m != nil {
+ return m.Message
+ }
+ return nil
+}
+
+func (m *EthereumVerifyMessage) GetAddressHex() string {
+ if m != nil && m.AddressHex != nil {
+ return *m.AddressHex
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*EthereumGetPublicKey)(nil), "hw.trezor.messages.ethereum.EthereumGetPublicKey")
+ proto.RegisterType((*EthereumPublicKey)(nil), "hw.trezor.messages.ethereum.EthereumPublicKey")
+ proto.RegisterType((*EthereumGetAddress)(nil), "hw.trezor.messages.ethereum.EthereumGetAddress")
+ proto.RegisterType((*EthereumAddress)(nil), "hw.trezor.messages.ethereum.EthereumAddress")
+ proto.RegisterType((*EthereumSignTx)(nil), "hw.trezor.messages.ethereum.EthereumSignTx")
+ proto.RegisterType((*EthereumTxRequest)(nil), "hw.trezor.messages.ethereum.EthereumTxRequest")
+ proto.RegisterType((*EthereumTxAck)(nil), "hw.trezor.messages.ethereum.EthereumTxAck")
+ proto.RegisterType((*EthereumSignMessage)(nil), "hw.trezor.messages.ethereum.EthereumSignMessage")
+ proto.RegisterType((*EthereumMessageSignature)(nil), "hw.trezor.messages.ethereum.EthereumMessageSignature")
+ proto.RegisterType((*EthereumVerifyMessage)(nil), "hw.trezor.messages.ethereum.EthereumVerifyMessage")
+}
+
+func init() { proto.RegisterFile("messages-ethereum.proto", fileDescriptor_cb33f46ba915f15c) }
+
+var fileDescriptor_cb33f46ba915f15c = []byte{
+ // 593 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x4d, 0x6f, 0xd3, 0x40,
+ 0x10, 0x95, 0x9b, 0xb4, 0x49, 0x26, 0x0d, 0x1f, 0xa6, 0x55, 0x17, 0x0a, 0x34, 0x18, 0x21, 0xe5,
+ 0x00, 0x3e, 0x70, 0x43, 0xe2, 0xd2, 0x52, 0x44, 0x2b, 0x4a, 0x55, 0xdc, 0xa8, 0x57, 0x6b, 0x63,
+ 0x6f, 0xe3, 0x55, 0x9d, 0xdd, 0xe0, 0x5d, 0xb7, 0x0e, 0x7f, 0x82, 0x23, 0xff, 0x87, 0x5f, 0x86,
+ 0xf6, 0x2b, 0x71, 0x52, 0x54, 0x0e, 0xbd, 0x65, 0xde, 0xbc, 0x7d, 0xf3, 0x66, 0xf4, 0x62, 0xd8,
+ 0x99, 0x10, 0x21, 0xf0, 0x98, 0x88, 0x77, 0x44, 0x66, 0xa4, 0x20, 0xe5, 0x24, 0x9c, 0x16, 0x5c,
+ 0x72, 0x7f, 0x37, 0xbb, 0x09, 0x65, 0x41, 0x7e, 0xf2, 0x22, 0x74, 0x94, 0xd0, 0x51, 0x9e, 0x6d,
+ 0xcf, 0x5f, 0x25, 0x7c, 0x32, 0xe1, 0xcc, 0xbc, 0x09, 0x2e, 0x60, 0xeb, 0xb3, 0xa5, 0x7c, 0x21,
+ 0xf2, 0xac, 0x1c, 0xe5, 0x34, 0xf9, 0x4a, 0x66, 0xfe, 0x2e, 0x74, 0x70, 0x9a, 0x16, 0x44, 0x88,
+ 0x98, 0x21, 0xaf, 0xdf, 0x18, 0xf4, 0xa2, 0xb6, 0x05, 0x4e, 0xfd, 0x57, 0xb0, 0x29, 0x32, 0x7e,
+ 0x13, 0xa7, 0x54, 0x4c, 0x73, 0x3c, 0x43, 0x6b, 0x7d, 0x6f, 0xd0, 0x8e, 0xba, 0x0a, 0x3b, 0x34,
+ 0x50, 0x30, 0x82, 0xc7, 0x4e, 0x77, 0x21, 0xfa, 0x01, 0x9a, 0x8c, 0xa7, 0x04, 0x79, 0x7d, 0x6f,
+ 0xd0, 0x7d, 0xff, 0x26, 0xfc, 0x87, 0x5f, 0x6b, 0xee, 0xe8, 0xf0, 0x94, 0xa7, 0x64, 0x38, 0x9b,
+ 0x92, 0x48, 0x3f, 0xf1, 0x7d, 0x68, 0x56, 0xd3, 0x72, 0xa4, 0x47, 0x75, 0x22, 0xfd, 0x3b, 0x18,
+ 0x82, 0x5f, 0xf3, 0xbe, 0x6f, 0xdc, 0xdd, 0xdb, 0xf9, 0x77, 0x78, 0xe8, 0x54, 0x9d, 0xe4, 0x4b,
+ 0x00, 0xab, 0x70, 0x40, 0x99, 0x76, 0xbf, 0x19, 0xd5, 0x90, 0x5a, 0xff, 0x88, 0x54, 0xd6, 0x62,
+ 0x0d, 0x09, 0xfe, 0xac, 0xc1, 0x03, 0xa7, 0x79, 0x4e, 0xc7, 0x6c, 0x58, 0xdd, 0xed, 0x72, 0x0b,
+ 0xd6, 0x19, 0x67, 0x09, 0xd1, 0x52, 0x9b, 0x91, 0x29, 0xd4, 0x93, 0x31, 0x16, 0xf1, 0xb4, 0xa0,
+ 0x09, 0x41, 0x0d, 0xdd, 0x69, 0x8f, 0xb1, 0x38, 0x53, 0xb5, 0x6b, 0xe6, 0x74, 0x42, 0x25, 0x6a,
+ 0xce, 0x9b, 0x27, 0xaa, 0x56, 0x7a, 0x92, 0x2b, 0xeb, 0xeb, 0x46, 0x4f, 0x17, 0x06, 0x55, 0x86,
+ 0xbb, 0xda, 0xb0, 0x29, 0x14, 0x7a, 0x8d, 0xf3, 0x92, 0xa0, 0x0d, 0xc3, 0xd5, 0x85, 0xff, 0x16,
+ 0xfc, 0x14, 0x4b, 0x1c, 0x53, 0x46, 0x25, 0xc5, 0x79, 0x9c, 0x64, 0x25, 0xbb, 0x42, 0x2d, 0x4d,
+ 0x79, 0xa4, 0x3a, 0xc7, 0xa6, 0xf1, 0x49, 0xe1, 0xfe, 0x1e, 0x74, 0x35, 0x3b, 0x27, 0x6c, 0x2c,
+ 0x33, 0xd4, 0xee, 0x7b, 0x83, 0x5e, 0x04, 0x0a, 0x3a, 0xd1, 0x88, 0xff, 0x14, 0xda, 0x49, 0x86,
+ 0x29, 0x8b, 0x69, 0x8a, 0x3a, 0xba, 0xdb, 0xd2, 0xf5, 0x71, 0xea, 0xef, 0x40, 0x4b, 0x56, 0xb1,
+ 0x9c, 0x4d, 0x09, 0x02, 0xdd, 0xd9, 0x90, 0x95, 0xca, 0x41, 0xf0, 0xdb, 0x5b, 0x44, 0x6a, 0x58,
+ 0x45, 0xe4, 0x47, 0x49, 0x84, 0x5c, 0x1d, 0xe5, 0xdd, 0x1a, 0xb5, 0x07, 0x5d, 0x41, 0xc7, 0x0c,
+ 0xcb, 0xb2, 0x20, 0xf1, 0xb5, 0xbe, 0x68, 0x2f, 0x82, 0x39, 0x74, 0xb1, 0x4c, 0x28, 0xec, 0x61,
+ 0x17, 0x84, 0x68, 0x99, 0x20, 0xec, 0x71, 0x17, 0x84, 0xf3, 0x20, 0x84, 0xde, 0xc2, 0xd8, 0x7e,
+ 0x72, 0xe5, 0xbf, 0x00, 0xed, 0xc0, 0x5e, 0xc9, 0xe4, 0xa5, 0xa3, 0x10, 0x7d, 0x9e, 0xe0, 0x04,
+ 0x9e, 0xd4, 0xd3, 0xf0, 0xcd, 0x64, 0xff, 0xee, 0x48, 0x20, 0x68, 0xd9, 0xff, 0x88, 0x0d, 0x85,
+ 0x2b, 0x83, 0x0a, 0x90, 0x53, 0xb3, 0x4a, 0xe7, 0xce, 0xda, 0x7f, 0x83, 0xfb, 0x1c, 0x3a, 0xf3,
+ 0x3d, 0xac, 0xee, 0x02, 0x58, 0x89, 0x75, 0xe3, 0x56, 0xac, 0x7f, 0x79, 0xb0, 0xed, 0x46, 0x5f,
+ 0x90, 0x82, 0x5e, 0xce, 0xdc, 0x2a, 0xf7, 0x9b, 0x5b, 0xdb, 0xb5, 0xb1, 0xb4, 0xeb, 0x8a, 0xa3,
+ 0xe6, 0xaa, 0xa3, 0x83, 0x8f, 0xf0, 0x3a, 0xe1, 0x93, 0x50, 0x60, 0xc9, 0x45, 0x46, 0x73, 0x3c,
+ 0x12, 0xee, 0x03, 0x93, 0xd3, 0x91, 0xf9, 0xe2, 0x8d, 0xca, 0xcb, 0x83, 0xed, 0xa1, 0x06, 0xad,
+ 0x5b, 0xb7, 0xc2, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8a, 0xce, 0x81, 0xc8, 0x59, 0x05, 0x00,
+ 0x00,
+}
diff --git a/accounts/usbwallet/trezor/messages-ethereum.proto b/accounts/usbwallet/trezor/messages-ethereum.proto
new file mode 100644
index 000000000..096bed2e4
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages-ethereum.proto
@@ -0,0 +1,131 @@
+// This file originates from the SatoshiLabs Trezor `common` repository at:
+// https://github.com/trezor/trezor-common/blob/master/protob/messages-ethereum.proto
+// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
+
+syntax = "proto2";
+package hw.trezor.messages.ethereum;
+
+// Sugar for easier handling in Java
+option java_package = "com.satoshilabs.trezor.lib.protobuf";
+option java_outer_classname = "TrezorMessageEthereum";
+
+import "messages-common.proto";
+
+
+/**
+ * Request: Ask device for public key corresponding to address_n path
+ * @start
+ * @next EthereumPublicKey
+ * @next Failure
+ */
+message EthereumGetPublicKey {
+ repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
+ optional bool show_display = 2; // optionally show on display before sending the result
+}
+
+/**
+ * Response: Contains public key derived from device private seed
+ * @end
+ */
+message EthereumPublicKey {
+ optional hw.trezor.messages.common.HDNodeType node = 1; // BIP32 public node
+ optional string xpub = 2; // serialized form of public node
+}
+
+/**
+ * Request: Ask device for Ethereum address corresponding to address_n path
+ * @start
+ * @next EthereumAddress
+ * @next Failure
+ */
+message EthereumGetAddress {
+ repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
+ optional bool show_display = 2; // optionally show on display before sending the result
+}
+
+/**
+ * Response: Contains an Ethereum address derived from device private seed
+ * @end
+ */
+message EthereumAddress {
+ optional bytes addressBin = 1; // Ethereum address as 20 bytes (legacy firmwares)
+ optional string addressHex = 2; // Ethereum address as hex string (newer firmwares)
+}
+
+/**
+ * Request: Ask device to sign transaction
+ * All fields are optional from the protocol's point of view. Each field defaults to value `0` if missing.
+ * Note: the first at most 1024 bytes of data MUST be transmitted as part of this message.
+ * @start
+ * @next EthereumTxRequest
+ * @next Failure
+ */
+message EthereumSignTx {
+ repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
+ optional bytes nonce = 2; // <=256 bit unsigned big endian
+ optional bytes gas_price = 3; // <=256 bit unsigned big endian (in wei)
+ optional bytes gas_limit = 4; // <=256 bit unsigned big endian
+ optional bytes toBin = 5; // recipient address (20 bytes, legacy firmware)
+ optional string toHex = 11; // recipient address (hex string, newer firmware)
+ optional bytes value = 6; // <=256 bit unsigned big endian (in wei)
+ optional bytes data_initial_chunk = 7; // The initial data chunk (<= 1024 bytes)
+ optional uint32 data_length = 8; // Length of transaction payload
+ optional uint32 chain_id = 9; // Chain Id for EIP 155
+ optional uint32 tx_type = 10; // (only for Wanchain)
+}
+
+/**
+ * Response: Device asks for more data from transaction payload, or returns the signature.
+ * If data_length is set, device awaits that many more bytes of payload.
+ * Otherwise, the signature_* fields contain the computed transaction signature. All three fields will be present.
+ * @end
+ * @next EthereumTxAck
+ */
+message EthereumTxRequest {
+ optional uint32 data_length = 1; // Number of bytes being requested (<= 1024)
+ optional uint32 signature_v = 2; // Computed signature (recovery parameter, limited to 27 or 28)
+ optional bytes signature_r = 3; // Computed signature R component (256 bit)
+ optional bytes signature_s = 4; // Computed signature S component (256 bit)
+}
+
+/**
+ * Request: Transaction payload data.
+ * @next EthereumTxRequest
+ */
+message EthereumTxAck {
+ optional bytes data_chunk = 1; // Bytes from transaction payload (<= 1024 bytes)
+}
+
+/**
+ * Request: Ask device to sign message
+ * @start
+ * @next EthereumMessageSignature
+ * @next Failure
+ */
+message EthereumSignMessage {
+ repeated uint32 address_n = 1; // BIP-32 path to derive the key from master node
+ optional bytes message = 2; // message to be signed
+}
+
+/**
+ * Response: Signed message
+ * @end
+ */
+message EthereumMessageSignature {
+ optional bytes addressBin = 1; // address used to sign the message (20 bytes, legacy firmware)
+ optional bytes signature = 2; // signature of the message
+ optional string addressHex = 3; // address used to sign the message (hex string, newer firmware)
+}
+
+/**
+ * Request: Ask device to verify message
+ * @start
+ * @next Success
+ * @next Failure
+ */
+message EthereumVerifyMessage {
+ optional bytes addressBin = 1; // address to verify (20 bytes, legacy firmware)
+ optional bytes signature = 2; // signature to verify
+ optional bytes message = 3; // message to verify
+ optional string addressHex = 4; // address to verify (hex string, newer firmware)
+}
diff --git a/accounts/usbwallet/trezor/messages-management.pb.go b/accounts/usbwallet/trezor/messages-management.pb.go
new file mode 100644
index 000000000..f5c872f1f
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages-management.pb.go
@@ -0,0 +1,1621 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: messages-management.proto
+
+package trezor
+
+import (
+ fmt "fmt"
+ math "math"
+
+ proto "github.com/golang/protobuf/proto"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
+
+//*
+// Structure representing passphrase source
+type ApplySettings_PassphraseSourceType int32
+
+const (
+ ApplySettings_ASK ApplySettings_PassphraseSourceType = 0
+ ApplySettings_DEVICE ApplySettings_PassphraseSourceType = 1
+ ApplySettings_HOST ApplySettings_PassphraseSourceType = 2
+)
+
+var ApplySettings_PassphraseSourceType_name = map[int32]string{
+ 0: "ASK",
+ 1: "DEVICE",
+ 2: "HOST",
+}
+
+var ApplySettings_PassphraseSourceType_value = map[string]int32{
+ "ASK": 0,
+ "DEVICE": 1,
+ "HOST": 2,
+}
+
+func (x ApplySettings_PassphraseSourceType) Enum() *ApplySettings_PassphraseSourceType {
+ p := new(ApplySettings_PassphraseSourceType)
+ *p = x
+ return p
+}
+
+func (x ApplySettings_PassphraseSourceType) String() string {
+ return proto.EnumName(ApplySettings_PassphraseSourceType_name, int32(x))
+}
+
+func (x *ApplySettings_PassphraseSourceType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(ApplySettings_PassphraseSourceType_value, data, "ApplySettings_PassphraseSourceType")
+ if err != nil {
+ return err
+ }
+ *x = ApplySettings_PassphraseSourceType(value)
+ return nil
+}
+
+func (ApplySettings_PassphraseSourceType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{4, 0}
+}
+
+//*
+// Type of recovery procedure. These should be used as bitmask, e.g.,
+// `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix`
+// listing every method supported by the host computer.
+//
+// Note that ScrambledWords must be supported by every implementation
+// for backward compatibility; there is no way to not support it.
+type RecoveryDevice_RecoveryDeviceType int32
+
+const (
+ // use powers of two when extending this field
+ RecoveryDevice_RecoveryDeviceType_ScrambledWords RecoveryDevice_RecoveryDeviceType = 0
+ RecoveryDevice_RecoveryDeviceType_Matrix RecoveryDevice_RecoveryDeviceType = 1
+)
+
+var RecoveryDevice_RecoveryDeviceType_name = map[int32]string{
+ 0: "RecoveryDeviceType_ScrambledWords",
+ 1: "RecoveryDeviceType_Matrix",
+}
+
+var RecoveryDevice_RecoveryDeviceType_value = map[string]int32{
+ "RecoveryDeviceType_ScrambledWords": 0,
+ "RecoveryDeviceType_Matrix": 1,
+}
+
+func (x RecoveryDevice_RecoveryDeviceType) Enum() *RecoveryDevice_RecoveryDeviceType {
+ p := new(RecoveryDevice_RecoveryDeviceType)
+ *p = x
+ return p
+}
+
+func (x RecoveryDevice_RecoveryDeviceType) String() string {
+ return proto.EnumName(RecoveryDevice_RecoveryDeviceType_name, int32(x))
+}
+
+func (x *RecoveryDevice_RecoveryDeviceType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(RecoveryDevice_RecoveryDeviceType_value, data, "RecoveryDevice_RecoveryDeviceType")
+ if err != nil {
+ return err
+ }
+ *x = RecoveryDevice_RecoveryDeviceType(value)
+ return nil
+}
+
+func (RecoveryDevice_RecoveryDeviceType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{17, 0}
+}
+
+//*
+// Type of Recovery Word request
+type WordRequest_WordRequestType int32
+
+const (
+ WordRequest_WordRequestType_Plain WordRequest_WordRequestType = 0
+ WordRequest_WordRequestType_Matrix9 WordRequest_WordRequestType = 1
+ WordRequest_WordRequestType_Matrix6 WordRequest_WordRequestType = 2
+)
+
+var WordRequest_WordRequestType_name = map[int32]string{
+ 0: "WordRequestType_Plain",
+ 1: "WordRequestType_Matrix9",
+ 2: "WordRequestType_Matrix6",
+}
+
+var WordRequest_WordRequestType_value = map[string]int32{
+ "WordRequestType_Plain": 0,
+ "WordRequestType_Matrix9": 1,
+ "WordRequestType_Matrix6": 2,
+}
+
+func (x WordRequest_WordRequestType) Enum() *WordRequest_WordRequestType {
+ p := new(WordRequest_WordRequestType)
+ *p = x
+ return p
+}
+
+func (x WordRequest_WordRequestType) String() string {
+ return proto.EnumName(WordRequest_WordRequestType_name, int32(x))
+}
+
+func (x *WordRequest_WordRequestType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(WordRequest_WordRequestType_value, data, "WordRequest_WordRequestType")
+ if err != nil {
+ return err
+ }
+ *x = WordRequest_WordRequestType(value)
+ return nil
+}
+
+func (WordRequest_WordRequestType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{18, 0}
+}
+
+//*
+// Request: Reset device to default state and ask for device details
+// @start
+// @next Features
+type Initialize struct {
+ State []byte `protobuf:"bytes,1,opt,name=state" json:"state,omitempty"`
+ SkipPassphrase *bool `protobuf:"varint,2,opt,name=skip_passphrase,json=skipPassphrase" json:"skip_passphrase,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Initialize) Reset() { *m = Initialize{} }
+func (m *Initialize) String() string { return proto.CompactTextString(m) }
+func (*Initialize) ProtoMessage() {}
+func (*Initialize) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{0}
+}
+
+func (m *Initialize) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Initialize.Unmarshal(m, b)
+}
+func (m *Initialize) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Initialize.Marshal(b, m, deterministic)
+}
+func (m *Initialize) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Initialize.Merge(m, src)
+}
+func (m *Initialize) XXX_Size() int {
+ return xxx_messageInfo_Initialize.Size(m)
+}
+func (m *Initialize) XXX_DiscardUnknown() {
+ xxx_messageInfo_Initialize.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Initialize proto.InternalMessageInfo
+
+func (m *Initialize) GetState() []byte {
+ if m != nil {
+ return m.State
+ }
+ return nil
+}
+
+func (m *Initialize) GetSkipPassphrase() bool {
+ if m != nil && m.SkipPassphrase != nil {
+ return *m.SkipPassphrase
+ }
+ return false
+}
+
+//*
+// Request: Ask for device details (no device reset)
+// @start
+// @next Features
+type GetFeatures struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *GetFeatures) Reset() { *m = GetFeatures{} }
+func (m *GetFeatures) String() string { return proto.CompactTextString(m) }
+func (*GetFeatures) ProtoMessage() {}
+func (*GetFeatures) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{1}
+}
+
+func (m *GetFeatures) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_GetFeatures.Unmarshal(m, b)
+}
+func (m *GetFeatures) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_GetFeatures.Marshal(b, m, deterministic)
+}
+func (m *GetFeatures) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GetFeatures.Merge(m, src)
+}
+func (m *GetFeatures) XXX_Size() int {
+ return xxx_messageInfo_GetFeatures.Size(m)
+}
+func (m *GetFeatures) XXX_DiscardUnknown() {
+ xxx_messageInfo_GetFeatures.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_GetFeatures proto.InternalMessageInfo
+
+//*
+// Response: Reports various information about the device
+// @end
+type Features struct {
+ Vendor *string `protobuf:"bytes,1,opt,name=vendor" json:"vendor,omitempty"`
+ MajorVersion *uint32 `protobuf:"varint,2,opt,name=major_version,json=majorVersion" json:"major_version,omitempty"`
+ MinorVersion *uint32 `protobuf:"varint,3,opt,name=minor_version,json=minorVersion" json:"minor_version,omitempty"`
+ PatchVersion *uint32 `protobuf:"varint,4,opt,name=patch_version,json=patchVersion" json:"patch_version,omitempty"`
+ BootloaderMode *bool `protobuf:"varint,5,opt,name=bootloader_mode,json=bootloaderMode" json:"bootloader_mode,omitempty"`
+ DeviceId *string `protobuf:"bytes,6,opt,name=device_id,json=deviceId" json:"device_id,omitempty"`
+ PinProtection *bool `protobuf:"varint,7,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
+ PassphraseProtection *bool `protobuf:"varint,8,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
+ Language *string `protobuf:"bytes,9,opt,name=language" json:"language,omitempty"`
+ Label *string `protobuf:"bytes,10,opt,name=label" json:"label,omitempty"`
+ Initialized *bool `protobuf:"varint,12,opt,name=initialized" json:"initialized,omitempty"`
+ Revision []byte `protobuf:"bytes,13,opt,name=revision" json:"revision,omitempty"`
+ BootloaderHash []byte `protobuf:"bytes,14,opt,name=bootloader_hash,json=bootloaderHash" json:"bootloader_hash,omitempty"`
+ Imported *bool `protobuf:"varint,15,opt,name=imported" json:"imported,omitempty"`
+ PinCached *bool `protobuf:"varint,16,opt,name=pin_cached,json=pinCached" json:"pin_cached,omitempty"`
+ PassphraseCached *bool `protobuf:"varint,17,opt,name=passphrase_cached,json=passphraseCached" json:"passphrase_cached,omitempty"`
+ FirmwarePresent *bool `protobuf:"varint,18,opt,name=firmware_present,json=firmwarePresent" json:"firmware_present,omitempty"`
+ NeedsBackup *bool `protobuf:"varint,19,opt,name=needs_backup,json=needsBackup" json:"needs_backup,omitempty"`
+ Flags *uint32 `protobuf:"varint,20,opt,name=flags" json:"flags,omitempty"`
+ Model *string `protobuf:"bytes,21,opt,name=model" json:"model,omitempty"`
+ FwMajor *uint32 `protobuf:"varint,22,opt,name=fw_major,json=fwMajor" json:"fw_major,omitempty"`
+ FwMinor *uint32 `protobuf:"varint,23,opt,name=fw_minor,json=fwMinor" json:"fw_minor,omitempty"`
+ FwPatch *uint32 `protobuf:"varint,24,opt,name=fw_patch,json=fwPatch" json:"fw_patch,omitempty"`
+ FwVendor *string `protobuf:"bytes,25,opt,name=fw_vendor,json=fwVendor" json:"fw_vendor,omitempty"`
+ FwVendorKeys []byte `protobuf:"bytes,26,opt,name=fw_vendor_keys,json=fwVendorKeys" json:"fw_vendor_keys,omitempty"`
+ UnfinishedBackup *bool `protobuf:"varint,27,opt,name=unfinished_backup,json=unfinishedBackup" json:"unfinished_backup,omitempty"`
+ NoBackup *bool `protobuf:"varint,28,opt,name=no_backup,json=noBackup" json:"no_backup,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Features) Reset() { *m = Features{} }
+func (m *Features) String() string { return proto.CompactTextString(m) }
+func (*Features) ProtoMessage() {}
+func (*Features) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{2}
+}
+
+func (m *Features) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Features.Unmarshal(m, b)
+}
+func (m *Features) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Features.Marshal(b, m, deterministic)
+}
+func (m *Features) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Features.Merge(m, src)
+}
+func (m *Features) XXX_Size() int {
+ return xxx_messageInfo_Features.Size(m)
+}
+func (m *Features) XXX_DiscardUnknown() {
+ xxx_messageInfo_Features.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Features proto.InternalMessageInfo
+
+func (m *Features) GetVendor() string {
+ if m != nil && m.Vendor != nil {
+ return *m.Vendor
+ }
+ return ""
+}
+
+func (m *Features) GetMajorVersion() uint32 {
+ if m != nil && m.MajorVersion != nil {
+ return *m.MajorVersion
+ }
+ return 0
+}
+
+func (m *Features) GetMinorVersion() uint32 {
+ if m != nil && m.MinorVersion != nil {
+ return *m.MinorVersion
+ }
+ return 0
+}
+
+func (m *Features) GetPatchVersion() uint32 {
+ if m != nil && m.PatchVersion != nil {
+ return *m.PatchVersion
+ }
+ return 0
+}
+
+func (m *Features) GetBootloaderMode() bool {
+ if m != nil && m.BootloaderMode != nil {
+ return *m.BootloaderMode
+ }
+ return false
+}
+
+func (m *Features) GetDeviceId() string {
+ if m != nil && m.DeviceId != nil {
+ return *m.DeviceId
+ }
+ return ""
+}
+
+func (m *Features) GetPinProtection() bool {
+ if m != nil && m.PinProtection != nil {
+ return *m.PinProtection
+ }
+ return false
+}
+
+func (m *Features) GetPassphraseProtection() bool {
+ if m != nil && m.PassphraseProtection != nil {
+ return *m.PassphraseProtection
+ }
+ return false
+}
+
+func (m *Features) GetLanguage() string {
+ if m != nil && m.Language != nil {
+ return *m.Language
+ }
+ return ""
+}
+
+func (m *Features) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+}
+
+func (m *Features) GetInitialized() bool {
+ if m != nil && m.Initialized != nil {
+ return *m.Initialized
+ }
+ return false
+}
+
+func (m *Features) GetRevision() []byte {
+ if m != nil {
+ return m.Revision
+ }
+ return nil
+}
+
+func (m *Features) GetBootloaderHash() []byte {
+ if m != nil {
+ return m.BootloaderHash
+ }
+ return nil
+}
+
+func (m *Features) GetImported() bool {
+ if m != nil && m.Imported != nil {
+ return *m.Imported
+ }
+ return false
+}
+
+func (m *Features) GetPinCached() bool {
+ if m != nil && m.PinCached != nil {
+ return *m.PinCached
+ }
+ return false
+}
+
+func (m *Features) GetPassphraseCached() bool {
+ if m != nil && m.PassphraseCached != nil {
+ return *m.PassphraseCached
+ }
+ return false
+}
+
+func (m *Features) GetFirmwarePresent() bool {
+ if m != nil && m.FirmwarePresent != nil {
+ return *m.FirmwarePresent
+ }
+ return false
+}
+
+func (m *Features) GetNeedsBackup() bool {
+ if m != nil && m.NeedsBackup != nil {
+ return *m.NeedsBackup
+ }
+ return false
+}
+
+func (m *Features) GetFlags() uint32 {
+ if m != nil && m.Flags != nil {
+ return *m.Flags
+ }
+ return 0
+}
+
+func (m *Features) GetModel() string {
+ if m != nil && m.Model != nil {
+ return *m.Model
+ }
+ return ""
+}
+
+func (m *Features) GetFwMajor() uint32 {
+ if m != nil && m.FwMajor != nil {
+ return *m.FwMajor
+ }
+ return 0
+}
+
+func (m *Features) GetFwMinor() uint32 {
+ if m != nil && m.FwMinor != nil {
+ return *m.FwMinor
+ }
+ return 0
+}
+
+func (m *Features) GetFwPatch() uint32 {
+ if m != nil && m.FwPatch != nil {
+ return *m.FwPatch
+ }
+ return 0
+}
+
+func (m *Features) GetFwVendor() string {
+ if m != nil && m.FwVendor != nil {
+ return *m.FwVendor
+ }
+ return ""
+}
+
+func (m *Features) GetFwVendorKeys() []byte {
+ if m != nil {
+ return m.FwVendorKeys
+ }
+ return nil
+}
+
+func (m *Features) GetUnfinishedBackup() bool {
+ if m != nil && m.UnfinishedBackup != nil {
+ return *m.UnfinishedBackup
+ }
+ return false
+}
+
+func (m *Features) GetNoBackup() bool {
+ if m != nil && m.NoBackup != nil {
+ return *m.NoBackup
+ }
+ return false
+}
+
+//*
+// Request: clear session (removes cached PIN, passphrase, etc).
+// @start
+// @next Success
+type ClearSession struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ClearSession) Reset() { *m = ClearSession{} }
+func (m *ClearSession) String() string { return proto.CompactTextString(m) }
+func (*ClearSession) ProtoMessage() {}
+func (*ClearSession) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{3}
+}
+
+func (m *ClearSession) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ClearSession.Unmarshal(m, b)
+}
+func (m *ClearSession) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ClearSession.Marshal(b, m, deterministic)
+}
+func (m *ClearSession) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ClearSession.Merge(m, src)
+}
+func (m *ClearSession) XXX_Size() int {
+ return xxx_messageInfo_ClearSession.Size(m)
+}
+func (m *ClearSession) XXX_DiscardUnknown() {
+ xxx_messageInfo_ClearSession.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ClearSession proto.InternalMessageInfo
+
+//*
+// Request: change language and/or label of the device
+// @start
+// @next Success
+// @next Failure
+type ApplySettings struct {
+ Language *string `protobuf:"bytes,1,opt,name=language" json:"language,omitempty"`
+ Label *string `protobuf:"bytes,2,opt,name=label" json:"label,omitempty"`
+ UsePassphrase *bool `protobuf:"varint,3,opt,name=use_passphrase,json=usePassphrase" json:"use_passphrase,omitempty"`
+ Homescreen []byte `protobuf:"bytes,4,opt,name=homescreen" json:"homescreen,omitempty"`
+ PassphraseSource *ApplySettings_PassphraseSourceType `protobuf:"varint,5,opt,name=passphrase_source,json=passphraseSource,enum=hw.trezor.messages.management.ApplySettings_PassphraseSourceType" json:"passphrase_source,omitempty"`
+ AutoLockDelayMs *uint32 `protobuf:"varint,6,opt,name=auto_lock_delay_ms,json=autoLockDelayMs" json:"auto_lock_delay_ms,omitempty"`
+ DisplayRotation *uint32 `protobuf:"varint,7,opt,name=display_rotation,json=displayRotation" json:"display_rotation,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ApplySettings) Reset() { *m = ApplySettings{} }
+func (m *ApplySettings) String() string { return proto.CompactTextString(m) }
+func (*ApplySettings) ProtoMessage() {}
+func (*ApplySettings) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{4}
+}
+
+func (m *ApplySettings) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ApplySettings.Unmarshal(m, b)
+}
+func (m *ApplySettings) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ApplySettings.Marshal(b, m, deterministic)
+}
+func (m *ApplySettings) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ApplySettings.Merge(m, src)
+}
+func (m *ApplySettings) XXX_Size() int {
+ return xxx_messageInfo_ApplySettings.Size(m)
+}
+func (m *ApplySettings) XXX_DiscardUnknown() {
+ xxx_messageInfo_ApplySettings.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ApplySettings proto.InternalMessageInfo
+
+func (m *ApplySettings) GetLanguage() string {
+ if m != nil && m.Language != nil {
+ return *m.Language
+ }
+ return ""
+}
+
+func (m *ApplySettings) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+}
+
+func (m *ApplySettings) GetUsePassphrase() bool {
+ if m != nil && m.UsePassphrase != nil {
+ return *m.UsePassphrase
+ }
+ return false
+}
+
+func (m *ApplySettings) GetHomescreen() []byte {
+ if m != nil {
+ return m.Homescreen
+ }
+ return nil
+}
+
+func (m *ApplySettings) GetPassphraseSource() ApplySettings_PassphraseSourceType {
+ if m != nil && m.PassphraseSource != nil {
+ return *m.PassphraseSource
+ }
+ return ApplySettings_ASK
+}
+
+func (m *ApplySettings) GetAutoLockDelayMs() uint32 {
+ if m != nil && m.AutoLockDelayMs != nil {
+ return *m.AutoLockDelayMs
+ }
+ return 0
+}
+
+func (m *ApplySettings) GetDisplayRotation() uint32 {
+ if m != nil && m.DisplayRotation != nil {
+ return *m.DisplayRotation
+ }
+ return 0
+}
+
+//*
+// Request: set flags of the device
+// @start
+// @next Success
+// @next Failure
+type ApplyFlags struct {
+ Flags *uint32 `protobuf:"varint,1,opt,name=flags" json:"flags,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ApplyFlags) Reset() { *m = ApplyFlags{} }
+func (m *ApplyFlags) String() string { return proto.CompactTextString(m) }
+func (*ApplyFlags) ProtoMessage() {}
+func (*ApplyFlags) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{5}
+}
+
+func (m *ApplyFlags) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ApplyFlags.Unmarshal(m, b)
+}
+func (m *ApplyFlags) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ApplyFlags.Marshal(b, m, deterministic)
+}
+func (m *ApplyFlags) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ApplyFlags.Merge(m, src)
+}
+func (m *ApplyFlags) XXX_Size() int {
+ return xxx_messageInfo_ApplyFlags.Size(m)
+}
+func (m *ApplyFlags) XXX_DiscardUnknown() {
+ xxx_messageInfo_ApplyFlags.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ApplyFlags proto.InternalMessageInfo
+
+func (m *ApplyFlags) GetFlags() uint32 {
+ if m != nil && m.Flags != nil {
+ return *m.Flags
+ }
+ return 0
+}
+
+//*
+// Request: Starts workflow for setting/changing/removing the PIN
+// @start
+// @next Success
+// @next Failure
+type ChangePin struct {
+ Remove *bool `protobuf:"varint,1,opt,name=remove" json:"remove,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ChangePin) Reset() { *m = ChangePin{} }
+func (m *ChangePin) String() string { return proto.CompactTextString(m) }
+func (*ChangePin) ProtoMessage() {}
+func (*ChangePin) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{6}
+}
+
+func (m *ChangePin) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ChangePin.Unmarshal(m, b)
+}
+func (m *ChangePin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ChangePin.Marshal(b, m, deterministic)
+}
+func (m *ChangePin) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ChangePin.Merge(m, src)
+}
+func (m *ChangePin) XXX_Size() int {
+ return xxx_messageInfo_ChangePin.Size(m)
+}
+func (m *ChangePin) XXX_DiscardUnknown() {
+ xxx_messageInfo_ChangePin.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ChangePin proto.InternalMessageInfo
+
+func (m *ChangePin) GetRemove() bool {
+ if m != nil && m.Remove != nil {
+ return *m.Remove
+ }
+ return false
+}
+
+//*
+// Request: Test if the device is alive, device sends back the message in Success response
+// @start
+// @next Success
+type Ping struct {
+ Message *string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
+ ButtonProtection *bool `protobuf:"varint,2,opt,name=button_protection,json=buttonProtection" json:"button_protection,omitempty"`
+ PinProtection *bool `protobuf:"varint,3,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
+ PassphraseProtection *bool `protobuf:"varint,4,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Ping) Reset() { *m = Ping{} }
+func (m *Ping) String() string { return proto.CompactTextString(m) }
+func (*Ping) ProtoMessage() {}
+func (*Ping) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{7}
+}
+
+func (m *Ping) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Ping.Unmarshal(m, b)
+}
+func (m *Ping) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Ping.Marshal(b, m, deterministic)
+}
+func (m *Ping) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Ping.Merge(m, src)
+}
+func (m *Ping) XXX_Size() int {
+ return xxx_messageInfo_Ping.Size(m)
+}
+func (m *Ping) XXX_DiscardUnknown() {
+ xxx_messageInfo_Ping.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Ping proto.InternalMessageInfo
+
+func (m *Ping) GetMessage() string {
+ if m != nil && m.Message != nil {
+ return *m.Message
+ }
+ return ""
+}
+
+func (m *Ping) GetButtonProtection() bool {
+ if m != nil && m.ButtonProtection != nil {
+ return *m.ButtonProtection
+ }
+ return false
+}
+
+func (m *Ping) GetPinProtection() bool {
+ if m != nil && m.PinProtection != nil {
+ return *m.PinProtection
+ }
+ return false
+}
+
+func (m *Ping) GetPassphraseProtection() bool {
+ if m != nil && m.PassphraseProtection != nil {
+ return *m.PassphraseProtection
+ }
+ return false
+}
+
+//*
+// Request: Abort last operation that required user interaction
+// @start
+// @next Failure
+type Cancel struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Cancel) Reset() { *m = Cancel{} }
+func (m *Cancel) String() string { return proto.CompactTextString(m) }
+func (*Cancel) ProtoMessage() {}
+func (*Cancel) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{8}
+}
+
+func (m *Cancel) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Cancel.Unmarshal(m, b)
+}
+func (m *Cancel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Cancel.Marshal(b, m, deterministic)
+}
+func (m *Cancel) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Cancel.Merge(m, src)
+}
+func (m *Cancel) XXX_Size() int {
+ return xxx_messageInfo_Cancel.Size(m)
+}
+func (m *Cancel) XXX_DiscardUnknown() {
+ xxx_messageInfo_Cancel.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Cancel proto.InternalMessageInfo
+
+//*
+// Request: Request a sample of random data generated by hardware RNG. May be used for testing.
+// @start
+// @next Entropy
+// @next Failure
+type GetEntropy struct {
+ Size *uint32 `protobuf:"varint,1,req,name=size" json:"size,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *GetEntropy) Reset() { *m = GetEntropy{} }
+func (m *GetEntropy) String() string { return proto.CompactTextString(m) }
+func (*GetEntropy) ProtoMessage() {}
+func (*GetEntropy) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{9}
+}
+
+func (m *GetEntropy) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_GetEntropy.Unmarshal(m, b)
+}
+func (m *GetEntropy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_GetEntropy.Marshal(b, m, deterministic)
+}
+func (m *GetEntropy) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GetEntropy.Merge(m, src)
+}
+func (m *GetEntropy) XXX_Size() int {
+ return xxx_messageInfo_GetEntropy.Size(m)
+}
+func (m *GetEntropy) XXX_DiscardUnknown() {
+ xxx_messageInfo_GetEntropy.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_GetEntropy proto.InternalMessageInfo
+
+func (m *GetEntropy) GetSize() uint32 {
+ if m != nil && m.Size != nil {
+ return *m.Size
+ }
+ return 0
+}
+
+//*
+// Response: Reply with random data generated by internal RNG
+// @end
+type Entropy struct {
+ Entropy []byte `protobuf:"bytes,1,req,name=entropy" json:"entropy,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Entropy) Reset() { *m = Entropy{} }
+func (m *Entropy) String() string { return proto.CompactTextString(m) }
+func (*Entropy) ProtoMessage() {}
+func (*Entropy) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{10}
+}
+
+func (m *Entropy) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Entropy.Unmarshal(m, b)
+}
+func (m *Entropy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Entropy.Marshal(b, m, deterministic)
+}
+func (m *Entropy) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Entropy.Merge(m, src)
+}
+func (m *Entropy) XXX_Size() int {
+ return xxx_messageInfo_Entropy.Size(m)
+}
+func (m *Entropy) XXX_DiscardUnknown() {
+ xxx_messageInfo_Entropy.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Entropy proto.InternalMessageInfo
+
+func (m *Entropy) GetEntropy() []byte {
+ if m != nil {
+ return m.Entropy
+ }
+ return nil
+}
+
+//*
+// Request: Request device to wipe all sensitive data and settings
+// @start
+// @next Success
+// @next Failure
+type WipeDevice struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *WipeDevice) Reset() { *m = WipeDevice{} }
+func (m *WipeDevice) String() string { return proto.CompactTextString(m) }
+func (*WipeDevice) ProtoMessage() {}
+func (*WipeDevice) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{11}
+}
+
+func (m *WipeDevice) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_WipeDevice.Unmarshal(m, b)
+}
+func (m *WipeDevice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_WipeDevice.Marshal(b, m, deterministic)
+}
+func (m *WipeDevice) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_WipeDevice.Merge(m, src)
+}
+func (m *WipeDevice) XXX_Size() int {
+ return xxx_messageInfo_WipeDevice.Size(m)
+}
+func (m *WipeDevice) XXX_DiscardUnknown() {
+ xxx_messageInfo_WipeDevice.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_WipeDevice proto.InternalMessageInfo
+
+//*
+// Request: Load seed and related internal settings from the computer
+// @start
+// @next Success
+// @next Failure
+type LoadDevice struct {
+ Mnemonic *string `protobuf:"bytes,1,opt,name=mnemonic" json:"mnemonic,omitempty"`
+ Node *HDNodeType `protobuf:"bytes,2,opt,name=node" json:"node,omitempty"`
+ Pin *string `protobuf:"bytes,3,opt,name=pin" json:"pin,omitempty"`
+ PassphraseProtection *bool `protobuf:"varint,4,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
+ Language *string `protobuf:"bytes,5,opt,name=language,def=english" json:"language,omitempty"`
+ Label *string `protobuf:"bytes,6,opt,name=label" json:"label,omitempty"`
+ SkipChecksum *bool `protobuf:"varint,7,opt,name=skip_checksum,json=skipChecksum" json:"skip_checksum,omitempty"`
+ U2FCounter *uint32 `protobuf:"varint,8,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *LoadDevice) Reset() { *m = LoadDevice{} }
+func (m *LoadDevice) String() string { return proto.CompactTextString(m) }
+func (*LoadDevice) ProtoMessage() {}
+func (*LoadDevice) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{12}
+}
+
+func (m *LoadDevice) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_LoadDevice.Unmarshal(m, b)
+}
+func (m *LoadDevice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_LoadDevice.Marshal(b, m, deterministic)
+}
+func (m *LoadDevice) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_LoadDevice.Merge(m, src)
+}
+func (m *LoadDevice) XXX_Size() int {
+ return xxx_messageInfo_LoadDevice.Size(m)
+}
+func (m *LoadDevice) XXX_DiscardUnknown() {
+ xxx_messageInfo_LoadDevice.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_LoadDevice proto.InternalMessageInfo
+
+const Default_LoadDevice_Language string = "english"
+
+func (m *LoadDevice) GetMnemonic() string {
+ if m != nil && m.Mnemonic != nil {
+ return *m.Mnemonic
+ }
+ return ""
+}
+
+func (m *LoadDevice) GetNode() *HDNodeType {
+ if m != nil {
+ return m.Node
+ }
+ return nil
+}
+
+func (m *LoadDevice) GetPin() string {
+ if m != nil && m.Pin != nil {
+ return *m.Pin
+ }
+ return ""
+}
+
+func (m *LoadDevice) GetPassphraseProtection() bool {
+ if m != nil && m.PassphraseProtection != nil {
+ return *m.PassphraseProtection
+ }
+ return false
+}
+
+func (m *LoadDevice) GetLanguage() string {
+ if m != nil && m.Language != nil {
+ return *m.Language
+ }
+ return Default_LoadDevice_Language
+}
+
+func (m *LoadDevice) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+}
+
+func (m *LoadDevice) GetSkipChecksum() bool {
+ if m != nil && m.SkipChecksum != nil {
+ return *m.SkipChecksum
+ }
+ return false
+}
+
+func (m *LoadDevice) GetU2FCounter() uint32 {
+ if m != nil && m.U2FCounter != nil {
+ return *m.U2FCounter
+ }
+ return 0
+}
+
+//*
+// Request: Ask device to do initialization involving user interaction
+// @start
+// @next EntropyRequest
+// @next Failure
+type ResetDevice struct {
+ DisplayRandom *bool `protobuf:"varint,1,opt,name=display_random,json=displayRandom" json:"display_random,omitempty"`
+ Strength *uint32 `protobuf:"varint,2,opt,name=strength,def=256" json:"strength,omitempty"`
+ PassphraseProtection *bool `protobuf:"varint,3,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
+ PinProtection *bool `protobuf:"varint,4,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
+ Language *string `protobuf:"bytes,5,opt,name=language,def=english" json:"language,omitempty"`
+ Label *string `protobuf:"bytes,6,opt,name=label" json:"label,omitempty"`
+ U2FCounter *uint32 `protobuf:"varint,7,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
+ SkipBackup *bool `protobuf:"varint,8,opt,name=skip_backup,json=skipBackup" json:"skip_backup,omitempty"`
+ NoBackup *bool `protobuf:"varint,9,opt,name=no_backup,json=noBackup" json:"no_backup,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ResetDevice) Reset() { *m = ResetDevice{} }
+func (m *ResetDevice) String() string { return proto.CompactTextString(m) }
+func (*ResetDevice) ProtoMessage() {}
+func (*ResetDevice) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{13}
+}
+
+func (m *ResetDevice) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ResetDevice.Unmarshal(m, b)
+}
+func (m *ResetDevice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ResetDevice.Marshal(b, m, deterministic)
+}
+func (m *ResetDevice) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ResetDevice.Merge(m, src)
+}
+func (m *ResetDevice) XXX_Size() int {
+ return xxx_messageInfo_ResetDevice.Size(m)
+}
+func (m *ResetDevice) XXX_DiscardUnknown() {
+ xxx_messageInfo_ResetDevice.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ResetDevice proto.InternalMessageInfo
+
+const Default_ResetDevice_Strength uint32 = 256
+const Default_ResetDevice_Language string = "english"
+
+func (m *ResetDevice) GetDisplayRandom() bool {
+ if m != nil && m.DisplayRandom != nil {
+ return *m.DisplayRandom
+ }
+ return false
+}
+
+func (m *ResetDevice) GetStrength() uint32 {
+ if m != nil && m.Strength != nil {
+ return *m.Strength
+ }
+ return Default_ResetDevice_Strength
+}
+
+func (m *ResetDevice) GetPassphraseProtection() bool {
+ if m != nil && m.PassphraseProtection != nil {
+ return *m.PassphraseProtection
+ }
+ return false
+}
+
+func (m *ResetDevice) GetPinProtection() bool {
+ if m != nil && m.PinProtection != nil {
+ return *m.PinProtection
+ }
+ return false
+}
+
+func (m *ResetDevice) GetLanguage() string {
+ if m != nil && m.Language != nil {
+ return *m.Language
+ }
+ return Default_ResetDevice_Language
+}
+
+func (m *ResetDevice) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+}
+
+func (m *ResetDevice) GetU2FCounter() uint32 {
+ if m != nil && m.U2FCounter != nil {
+ return *m.U2FCounter
+ }
+ return 0
+}
+
+func (m *ResetDevice) GetSkipBackup() bool {
+ if m != nil && m.SkipBackup != nil {
+ return *m.SkipBackup
+ }
+ return false
+}
+
+func (m *ResetDevice) GetNoBackup() bool {
+ if m != nil && m.NoBackup != nil {
+ return *m.NoBackup
+ }
+ return false
+}
+
+//*
+// Request: Perform backup of the device seed if not backed up using ResetDevice
+// @start
+// @next Success
+type BackupDevice struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *BackupDevice) Reset() { *m = BackupDevice{} }
+func (m *BackupDevice) String() string { return proto.CompactTextString(m) }
+func (*BackupDevice) ProtoMessage() {}
+func (*BackupDevice) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{14}
+}
+
+func (m *BackupDevice) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_BackupDevice.Unmarshal(m, b)
+}
+func (m *BackupDevice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_BackupDevice.Marshal(b, m, deterministic)
+}
+func (m *BackupDevice) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_BackupDevice.Merge(m, src)
+}
+func (m *BackupDevice) XXX_Size() int {
+ return xxx_messageInfo_BackupDevice.Size(m)
+}
+func (m *BackupDevice) XXX_DiscardUnknown() {
+ xxx_messageInfo_BackupDevice.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_BackupDevice proto.InternalMessageInfo
+
+//*
+// Response: Ask for additional entropy from host computer
+// @next EntropyAck
+type EntropyRequest struct {
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EntropyRequest) Reset() { *m = EntropyRequest{} }
+func (m *EntropyRequest) String() string { return proto.CompactTextString(m) }
+func (*EntropyRequest) ProtoMessage() {}
+func (*EntropyRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{15}
+}
+
+func (m *EntropyRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EntropyRequest.Unmarshal(m, b)
+}
+func (m *EntropyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EntropyRequest.Marshal(b, m, deterministic)
+}
+func (m *EntropyRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EntropyRequest.Merge(m, src)
+}
+func (m *EntropyRequest) XXX_Size() int {
+ return xxx_messageInfo_EntropyRequest.Size(m)
+}
+func (m *EntropyRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_EntropyRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EntropyRequest proto.InternalMessageInfo
+
+//*
+// Request: Provide additional entropy for seed generation function
+// @next Success
+type EntropyAck struct {
+ Entropy []byte `protobuf:"bytes,1,opt,name=entropy" json:"entropy,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EntropyAck) Reset() { *m = EntropyAck{} }
+func (m *EntropyAck) String() string { return proto.CompactTextString(m) }
+func (*EntropyAck) ProtoMessage() {}
+func (*EntropyAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{16}
+}
+
+func (m *EntropyAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EntropyAck.Unmarshal(m, b)
+}
+func (m *EntropyAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EntropyAck.Marshal(b, m, deterministic)
+}
+func (m *EntropyAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EntropyAck.Merge(m, src)
+}
+func (m *EntropyAck) XXX_Size() int {
+ return xxx_messageInfo_EntropyAck.Size(m)
+}
+func (m *EntropyAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_EntropyAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EntropyAck proto.InternalMessageInfo
+
+func (m *EntropyAck) GetEntropy() []byte {
+ if m != nil {
+ return m.Entropy
+ }
+ return nil
+}
+
+//*
+// Request: Start recovery workflow asking user for specific words of mnemonic
+// Used to recovery device safely even on untrusted computer.
+// @start
+// @next WordRequest
+type RecoveryDevice struct {
+ WordCount *uint32 `protobuf:"varint,1,opt,name=word_count,json=wordCount" json:"word_count,omitempty"`
+ PassphraseProtection *bool `protobuf:"varint,2,opt,name=passphrase_protection,json=passphraseProtection" json:"passphrase_protection,omitempty"`
+ PinProtection *bool `protobuf:"varint,3,opt,name=pin_protection,json=pinProtection" json:"pin_protection,omitempty"`
+ Language *string `protobuf:"bytes,4,opt,name=language,def=english" json:"language,omitempty"`
+ Label *string `protobuf:"bytes,5,opt,name=label" json:"label,omitempty"`
+ EnforceWordlist *bool `protobuf:"varint,6,opt,name=enforce_wordlist,json=enforceWordlist" json:"enforce_wordlist,omitempty"`
+ // 7 reserved for unused recovery method
+ Type *RecoveryDevice_RecoveryDeviceType `protobuf:"varint,8,opt,name=type,enum=hw.trezor.messages.management.RecoveryDevice_RecoveryDeviceType" json:"type,omitempty"`
+ U2FCounter *uint32 `protobuf:"varint,9,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
+ DryRun *bool `protobuf:"varint,10,opt,name=dry_run,json=dryRun" json:"dry_run,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *RecoveryDevice) Reset() { *m = RecoveryDevice{} }
+func (m *RecoveryDevice) String() string { return proto.CompactTextString(m) }
+func (*RecoveryDevice) ProtoMessage() {}
+func (*RecoveryDevice) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{17}
+}
+
+func (m *RecoveryDevice) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_RecoveryDevice.Unmarshal(m, b)
+}
+func (m *RecoveryDevice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_RecoveryDevice.Marshal(b, m, deterministic)
+}
+func (m *RecoveryDevice) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RecoveryDevice.Merge(m, src)
+}
+func (m *RecoveryDevice) XXX_Size() int {
+ return xxx_messageInfo_RecoveryDevice.Size(m)
+}
+func (m *RecoveryDevice) XXX_DiscardUnknown() {
+ xxx_messageInfo_RecoveryDevice.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_RecoveryDevice proto.InternalMessageInfo
+
+const Default_RecoveryDevice_Language string = "english"
+
+func (m *RecoveryDevice) GetWordCount() uint32 {
+ if m != nil && m.WordCount != nil {
+ return *m.WordCount
+ }
+ return 0
+}
+
+func (m *RecoveryDevice) GetPassphraseProtection() bool {
+ if m != nil && m.PassphraseProtection != nil {
+ return *m.PassphraseProtection
+ }
+ return false
+}
+
+func (m *RecoveryDevice) GetPinProtection() bool {
+ if m != nil && m.PinProtection != nil {
+ return *m.PinProtection
+ }
+ return false
+}
+
+func (m *RecoveryDevice) GetLanguage() string {
+ if m != nil && m.Language != nil {
+ return *m.Language
+ }
+ return Default_RecoveryDevice_Language
+}
+
+func (m *RecoveryDevice) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+}
+
+func (m *RecoveryDevice) GetEnforceWordlist() bool {
+ if m != nil && m.EnforceWordlist != nil {
+ return *m.EnforceWordlist
+ }
+ return false
+}
+
+func (m *RecoveryDevice) GetType() RecoveryDevice_RecoveryDeviceType {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return RecoveryDevice_RecoveryDeviceType_ScrambledWords
+}
+
+func (m *RecoveryDevice) GetU2FCounter() uint32 {
+ if m != nil && m.U2FCounter != nil {
+ return *m.U2FCounter
+ }
+ return 0
+}
+
+func (m *RecoveryDevice) GetDryRun() bool {
+ if m != nil && m.DryRun != nil {
+ return *m.DryRun
+ }
+ return false
+}
+
+//*
+// Response: Device is waiting for user to enter word of the mnemonic
+// Its position is shown only on device's internal display.
+// @next WordAck
+type WordRequest struct {
+ Type *WordRequest_WordRequestType `protobuf:"varint,1,opt,name=type,enum=hw.trezor.messages.management.WordRequest_WordRequestType" json:"type,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *WordRequest) Reset() { *m = WordRequest{} }
+func (m *WordRequest) String() string { return proto.CompactTextString(m) }
+func (*WordRequest) ProtoMessage() {}
+func (*WordRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{18}
+}
+
+func (m *WordRequest) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_WordRequest.Unmarshal(m, b)
+}
+func (m *WordRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_WordRequest.Marshal(b, m, deterministic)
+}
+func (m *WordRequest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_WordRequest.Merge(m, src)
+}
+func (m *WordRequest) XXX_Size() int {
+ return xxx_messageInfo_WordRequest.Size(m)
+}
+func (m *WordRequest) XXX_DiscardUnknown() {
+ xxx_messageInfo_WordRequest.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_WordRequest proto.InternalMessageInfo
+
+func (m *WordRequest) GetType() WordRequest_WordRequestType {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return WordRequest_WordRequestType_Plain
+}
+
+//*
+// Request: Computer replies with word from the mnemonic
+// @next WordRequest
+// @next Success
+// @next Failure
+type WordAck struct {
+ Word *string `protobuf:"bytes,1,req,name=word" json:"word,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *WordAck) Reset() { *m = WordAck{} }
+func (m *WordAck) String() string { return proto.CompactTextString(m) }
+func (*WordAck) ProtoMessage() {}
+func (*WordAck) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{19}
+}
+
+func (m *WordAck) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_WordAck.Unmarshal(m, b)
+}
+func (m *WordAck) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_WordAck.Marshal(b, m, deterministic)
+}
+func (m *WordAck) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_WordAck.Merge(m, src)
+}
+func (m *WordAck) XXX_Size() int {
+ return xxx_messageInfo_WordAck.Size(m)
+}
+func (m *WordAck) XXX_DiscardUnknown() {
+ xxx_messageInfo_WordAck.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_WordAck proto.InternalMessageInfo
+
+func (m *WordAck) GetWord() string {
+ if m != nil && m.Word != nil {
+ return *m.Word
+ }
+ return ""
+}
+
+//*
+// Request: Set U2F counter
+// @start
+// @next Success
+type SetU2FCounter struct {
+ U2FCounter *uint32 `protobuf:"varint,1,opt,name=u2f_counter,json=u2fCounter" json:"u2f_counter,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *SetU2FCounter) Reset() { *m = SetU2FCounter{} }
+func (m *SetU2FCounter) String() string { return proto.CompactTextString(m) }
+func (*SetU2FCounter) ProtoMessage() {}
+func (*SetU2FCounter) Descriptor() ([]byte, []int) {
+ return fileDescriptor_0c720c20d27aa029, []int{20}
+}
+
+func (m *SetU2FCounter) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_SetU2FCounter.Unmarshal(m, b)
+}
+func (m *SetU2FCounter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_SetU2FCounter.Marshal(b, m, deterministic)
+}
+func (m *SetU2FCounter) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SetU2FCounter.Merge(m, src)
+}
+func (m *SetU2FCounter) XXX_Size() int {
+ return xxx_messageInfo_SetU2FCounter.Size(m)
+}
+func (m *SetU2FCounter) XXX_DiscardUnknown() {
+ xxx_messageInfo_SetU2FCounter.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_SetU2FCounter proto.InternalMessageInfo
+
+func (m *SetU2FCounter) GetU2FCounter() uint32 {
+ if m != nil && m.U2FCounter != nil {
+ return *m.U2FCounter
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterEnum("hw.trezor.messages.management.ApplySettings_PassphraseSourceType", ApplySettings_PassphraseSourceType_name, ApplySettings_PassphraseSourceType_value)
+ proto.RegisterEnum("hw.trezor.messages.management.RecoveryDevice_RecoveryDeviceType", RecoveryDevice_RecoveryDeviceType_name, RecoveryDevice_RecoveryDeviceType_value)
+ proto.RegisterEnum("hw.trezor.messages.management.WordRequest_WordRequestType", WordRequest_WordRequestType_name, WordRequest_WordRequestType_value)
+ proto.RegisterType((*Initialize)(nil), "hw.trezor.messages.management.Initialize")
+ proto.RegisterType((*GetFeatures)(nil), "hw.trezor.messages.management.GetFeatures")
+ proto.RegisterType((*Features)(nil), "hw.trezor.messages.management.Features")
+ proto.RegisterType((*ClearSession)(nil), "hw.trezor.messages.management.ClearSession")
+ proto.RegisterType((*ApplySettings)(nil), "hw.trezor.messages.management.ApplySettings")
+ proto.RegisterType((*ApplyFlags)(nil), "hw.trezor.messages.management.ApplyFlags")
+ proto.RegisterType((*ChangePin)(nil), "hw.trezor.messages.management.ChangePin")
+ proto.RegisterType((*Ping)(nil), "hw.trezor.messages.management.Ping")
+ proto.RegisterType((*Cancel)(nil), "hw.trezor.messages.management.Cancel")
+ proto.RegisterType((*GetEntropy)(nil), "hw.trezor.messages.management.GetEntropy")
+ proto.RegisterType((*Entropy)(nil), "hw.trezor.messages.management.Entropy")
+ proto.RegisterType((*WipeDevice)(nil), "hw.trezor.messages.management.WipeDevice")
+ proto.RegisterType((*LoadDevice)(nil), "hw.trezor.messages.management.LoadDevice")
+ proto.RegisterType((*ResetDevice)(nil), "hw.trezor.messages.management.ResetDevice")
+ proto.RegisterType((*BackupDevice)(nil), "hw.trezor.messages.management.BackupDevice")
+ proto.RegisterType((*EntropyRequest)(nil), "hw.trezor.messages.management.EntropyRequest")
+ proto.RegisterType((*EntropyAck)(nil), "hw.trezor.messages.management.EntropyAck")
+ proto.RegisterType((*RecoveryDevice)(nil), "hw.trezor.messages.management.RecoveryDevice")
+ proto.RegisterType((*WordRequest)(nil), "hw.trezor.messages.management.WordRequest")
+ proto.RegisterType((*WordAck)(nil), "hw.trezor.messages.management.WordAck")
+ proto.RegisterType((*SetU2FCounter)(nil), "hw.trezor.messages.management.SetU2FCounter")
+}
+
+func init() { proto.RegisterFile("messages-management.proto", fileDescriptor_0c720c20d27aa029) }
+
+var fileDescriptor_0c720c20d27aa029 = []byte{
+ // 1393 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x57, 0xdd, 0x6e, 0xdb, 0xc8,
+ 0x15, 0x8e, 0x7e, 0x62, 0x49, 0xc7, 0xfa, 0xcb, 0xd4, 0x8e, 0xe9, 0xb8, 0x6e, 0x1c, 0xba, 0x6e,
+ 0x12, 0x04, 0x15, 0x0a, 0x17, 0x09, 0x90, 0x5c, 0x14, 0x75, 0xec, 0xfc, 0x21, 0x71, 0x6a, 0xd0,
+ 0x6e, 0x02, 0xf4, 0x86, 0x18, 0x91, 0x47, 0xd2, 0xd4, 0xe4, 0x0c, 0xcb, 0x19, 0xda, 0x55, 0x5e,
+ 0x60, 0x6f, 0xf6, 0x45, 0x16, 0xfb, 0x1c, 0x7b, 0xb5, 0xcf, 0xb0, 0xef, 0xb2, 0x98, 0x19, 0x52,
+ 0xa2, 0x65, 0x3b, 0x46, 0x76, 0xef, 0xe6, 0x7c, 0xe7, 0xe3, 0x68, 0xce, 0x77, 0xbe, 0x39, 0x63,
+ 0xc3, 0x7a, 0x8c, 0x52, 0xd2, 0x31, 0xca, 0xbf, 0xc6, 0x94, 0xd3, 0x31, 0xc6, 0xc8, 0xd5, 0x20,
+ 0x49, 0x85, 0x12, 0x64, 0x73, 0x72, 0x3e, 0x50, 0x29, 0x7e, 0x11, 0xe9, 0xa0, 0x20, 0x0d, 0xe6,
+ 0xa4, 0x7b, 0xab, 0xb3, 0x2f, 0x03, 0x11, 0xc7, 0x82, 0xdb, 0xaf, 0xdc, 0xf7, 0x00, 0xef, 0x38,
+ 0x53, 0x8c, 0x46, 0xec, 0x0b, 0x92, 0x15, 0xb8, 0x2d, 0x15, 0x55, 0xe8, 0x54, 0xb6, 0x2a, 0x8f,
+ 0xda, 0x9e, 0x0d, 0xc8, 0x43, 0xe8, 0xc9, 0x53, 0x96, 0xf8, 0x09, 0x95, 0x32, 0x99, 0xa4, 0x54,
+ 0xa2, 0x53, 0xdd, 0xaa, 0x3c, 0x6a, 0x7a, 0x5d, 0x0d, 0x1f, 0xcd, 0x50, 0xb7, 0x03, 0xcb, 0x6f,
+ 0x50, 0xbd, 0x46, 0xaa, 0xb2, 0x14, 0xa5, 0xfb, 0x7d, 0x03, 0x9a, 0x45, 0x40, 0xee, 0xc2, 0xd2,
+ 0x19, 0xf2, 0x50, 0xa4, 0x66, 0xef, 0x96, 0x97, 0x47, 0x64, 0x1b, 0x3a, 0x31, 0xfd, 0xaf, 0x48,
+ 0xfd, 0x33, 0x4c, 0x25, 0x13, 0xdc, 0x6c, 0xdd, 0xf1, 0xda, 0x06, 0xfc, 0x64, 0x31, 0x43, 0x62,
+ 0xbc, 0x44, 0xaa, 0xe5, 0x24, 0x0d, 0x96, 0x48, 0x09, 0x55, 0xc1, 0x64, 0x46, 0xaa, 0x5b, 0x92,
+ 0x01, 0x0b, 0xd2, 0x43, 0xe8, 0x0d, 0x85, 0x50, 0x91, 0xa0, 0x21, 0xa6, 0x7e, 0x2c, 0x42, 0x74,
+ 0x6e, 0xdb, 0x5a, 0xe6, 0xf0, 0xa1, 0x08, 0x91, 0x6c, 0x40, 0x2b, 0xc4, 0x33, 0x16, 0xa0, 0xcf,
+ 0x42, 0x67, 0xc9, 0x1c, 0xb9, 0x69, 0x81, 0x77, 0x21, 0xd9, 0x81, 0x6e, 0xc2, 0xb8, 0xaf, 0x25,
+ 0xc4, 0x40, 0xe9, 0xdf, 0x6a, 0x98, 0x4d, 0x3a, 0x09, 0xe3, 0x47, 0x33, 0x90, 0xfc, 0x1d, 0x56,
+ 0xe7, 0x9a, 0x95, 0xd9, 0x4d, 0xc3, 0x5e, 0x99, 0x27, 0x4b, 0x1f, 0xdd, 0x83, 0x66, 0x44, 0xf9,
+ 0x38, 0xa3, 0x63, 0x74, 0x5a, 0xf6, 0x77, 0x8b, 0x58, 0xf7, 0x27, 0xa2, 0x43, 0x8c, 0x1c, 0x30,
+ 0x09, 0x1b, 0x90, 0x2d, 0x58, 0x66, 0xb3, 0x1e, 0x86, 0x4e, 0xdb, 0x6c, 0x5e, 0x86, 0xf4, 0x9e,
+ 0x29, 0x9e, 0x31, 0xa3, 0x4a, 0xc7, 0xb4, 0x76, 0x16, 0x2f, 0x28, 0x32, 0xa1, 0x72, 0xe2, 0x74,
+ 0x0d, 0xa5, 0xa4, 0xc8, 0x5b, 0x2a, 0x27, 0x7a, 0x13, 0x16, 0x27, 0x22, 0x55, 0x18, 0x3a, 0x3d,
+ 0xf3, 0x1b, 0xb3, 0x98, 0x6c, 0x02, 0x68, 0x41, 0x02, 0x1a, 0x4c, 0x30, 0x74, 0xfa, 0x26, 0xdb,
+ 0x4a, 0x18, 0xdf, 0x37, 0x00, 0x79, 0x02, 0x77, 0x4a, 0x42, 0xe4, 0xac, 0x3b, 0x86, 0xd5, 0x9f,
+ 0x27, 0x72, 0xf2, 0x63, 0xe8, 0x8f, 0x58, 0x1a, 0x9f, 0xd3, 0x54, 0x6b, 0x86, 0x12, 0xb9, 0x72,
+ 0x88, 0xe1, 0xf6, 0x0a, 0xfc, 0xc8, 0xc2, 0xe4, 0x01, 0xb4, 0x39, 0x62, 0x28, 0xfd, 0x21, 0x0d,
+ 0x4e, 0xb3, 0xc4, 0xf9, 0x83, 0x2d, 0xdd, 0x60, 0x2f, 0x0d, 0xa4, 0x25, 0x1b, 0x45, 0x74, 0x2c,
+ 0x9d, 0x15, 0xe3, 0x06, 0x1b, 0x68, 0x54, 0xf7, 0x3e, 0x72, 0x56, 0xad, 0x90, 0x26, 0x20, 0xeb,
+ 0xd0, 0x1c, 0x9d, 0xfb, 0xc6, 0x79, 0xce, 0x5d, 0x43, 0x6f, 0x8c, 0xce, 0x0f, 0x75, 0x58, 0xa4,
+ 0xb4, 0xdf, 0x9c, 0xb5, 0x59, 0x4a, 0x87, 0x79, 0xca, 0xb8, 0xcc, 0x71, 0x8a, 0xd4, 0x91, 0x0e,
+ 0xb5, 0x89, 0x46, 0xe7, 0x7e, 0xee, 0xfb, 0x75, 0xdb, 0xcc, 0xd1, 0xf9, 0x27, 0xeb, 0xfc, 0x3f,
+ 0x43, 0x77, 0x96, 0xf4, 0x4f, 0x71, 0x2a, 0x9d, 0x7b, 0x46, 0xf7, 0x76, 0xc1, 0x78, 0x8f, 0x53,
+ 0xa9, 0xa5, 0xcb, 0xf8, 0x88, 0x71, 0x26, 0x27, 0x18, 0x16, 0x75, 0x6e, 0x58, 0xe9, 0xe6, 0x89,
+ 0xbc, 0xd8, 0x0d, 0x68, 0x71, 0x51, 0x90, 0xfe, 0x68, 0x7b, 0xc4, 0x85, 0x4d, 0xba, 0x5d, 0x68,
+ 0xef, 0x47, 0x48, 0xd3, 0x63, 0x94, 0xba, 0xf1, 0xee, 0x77, 0x35, 0xe8, 0xec, 0x25, 0x49, 0x34,
+ 0x3d, 0x46, 0xa5, 0x18, 0x1f, 0xcb, 0x0b, 0xd6, 0xab, 0x5c, 0x67, 0xbd, 0x6a, 0xd9, 0x7a, 0x3b,
+ 0xd0, 0xcd, 0xb4, 0xb5, 0xe7, 0x93, 0xa1, 0x66, 0x2f, 0x42, 0x26, 0x71, 0x3e, 0x18, 0xc8, 0x9f,
+ 0x00, 0x26, 0x22, 0x46, 0x19, 0xa4, 0x88, 0xf6, 0x5e, 0xb6, 0xbd, 0x12, 0x42, 0xf8, 0x05, 0x7f,
+ 0x48, 0x91, 0xa5, 0x81, 0xbd, 0x97, 0xdd, 0xdd, 0xbd, 0xc1, 0x57, 0xe7, 0xda, 0xe0, 0x42, 0x05,
+ 0x83, 0xf9, 0x6f, 0x1e, 0x9b, 0x4d, 0x4e, 0xa6, 0x09, 0x96, 0x2d, 0x66, 0x51, 0xf2, 0x04, 0x08,
+ 0xcd, 0x94, 0xf0, 0x23, 0x11, 0x9c, 0xfa, 0x21, 0x46, 0x74, 0xea, 0xc7, 0xd2, 0xdc, 0xf2, 0x8e,
+ 0xd7, 0xd3, 0x99, 0x0f, 0x22, 0x38, 0x3d, 0xd0, 0xf8, 0xa1, 0xd4, 0x7e, 0x0c, 0x99, 0x4c, 0x34,
+ 0x29, 0x15, 0x8a, 0xce, 0xae, 0x7b, 0xc7, 0xeb, 0xe5, 0xb8, 0x97, 0xc3, 0xee, 0x53, 0x58, 0xb9,
+ 0xea, 0x04, 0xa4, 0x01, 0xb5, 0xbd, 0xe3, 0xf7, 0xfd, 0x5b, 0x04, 0x60, 0xe9, 0xe0, 0xd5, 0xa7,
+ 0x77, 0xfb, 0xaf, 0xfa, 0x15, 0xd2, 0x84, 0xfa, 0xdb, 0x7f, 0x1d, 0x9f, 0xf4, 0xab, 0xae, 0x0b,
+ 0x60, 0xca, 0x78, 0x5d, 0x78, 0xd3, 0x3a, 0xb6, 0x52, 0x72, 0xac, 0xbb, 0x0d, 0xad, 0xfd, 0x09,
+ 0xe5, 0x63, 0x3c, 0x62, 0x5c, 0x0f, 0xd3, 0x14, 0x63, 0x71, 0x66, 0xdb, 0xd4, 0xf4, 0xf2, 0xc8,
+ 0xfd, 0xa1, 0x02, 0xf5, 0x23, 0xc6, 0xc7, 0xc4, 0x81, 0x46, 0x2e, 0x56, 0xde, 0xc8, 0x22, 0xd4,
+ 0x7e, 0x1a, 0x66, 0x4a, 0x89, 0x0b, 0xd3, 0xcb, 0x8e, 0xf3, 0xbe, 0x4d, 0x94, 0x66, 0xd1, 0xe5,
+ 0x39, 0x57, 0xfb, 0xa6, 0x39, 0x57, 0xbf, 0x7e, 0xce, 0xb9, 0x4d, 0x58, 0xda, 0xa7, 0x3c, 0xc0,
+ 0xc8, 0xdd, 0x02, 0x78, 0x83, 0xea, 0x15, 0x57, 0xa9, 0x48, 0xa6, 0x84, 0x40, 0x5d, 0xb2, 0x2f,
+ 0xfa, 0xdc, 0xd5, 0x47, 0x1d, 0xcf, 0xac, 0xdd, 0x6d, 0x68, 0x14, 0x69, 0x07, 0x1a, 0x68, 0x97,
+ 0x86, 0xd1, 0xf6, 0x8a, 0xd0, 0x6d, 0x03, 0x7c, 0x66, 0x09, 0x1e, 0x98, 0x21, 0xed, 0xfe, 0x58,
+ 0x05, 0xf8, 0x20, 0x68, 0x68, 0x43, 0x6d, 0xed, 0x98, 0x63, 0x2c, 0x38, 0x0b, 0x0a, 0x6b, 0x17,
+ 0x31, 0x79, 0x0e, 0x75, 0xae, 0x1f, 0x02, 0xad, 0xc2, 0xf2, 0xee, 0xce, 0x55, 0x86, 0xcb, 0xdf,
+ 0xcc, 0xb7, 0x07, 0x1f, 0x45, 0x68, 0x4d, 0x65, 0x3e, 0x21, 0x7d, 0xa8, 0x25, 0xcc, 0xaa, 0xd2,
+ 0xf2, 0xf4, 0xf2, 0x37, 0x69, 0x41, 0xb6, 0x4b, 0x17, 0x4f, 0xdb, 0xbe, 0xf5, 0xa2, 0x81, 0x7c,
+ 0x1c, 0x31, 0x39, 0xb9, 0xea, 0x06, 0x2e, 0x95, 0x6f, 0xe0, 0x36, 0x74, 0xcc, 0xe3, 0x1c, 0x4c,
+ 0x30, 0x38, 0x95, 0x59, 0x9c, 0xbf, 0x44, 0x6d, 0x0d, 0xee, 0xe7, 0x18, 0xb9, 0x0f, 0xcb, 0xd9,
+ 0xee, 0xc8, 0x0f, 0x44, 0xc6, 0x15, 0xa6, 0xe6, 0xf9, 0xe9, 0x78, 0x90, 0xed, 0x8e, 0xf6, 0x2d,
+ 0xe2, 0xfe, 0x5c, 0x85, 0x65, 0x0f, 0x25, 0xaa, 0x5c, 0xae, 0x1d, 0xe8, 0xce, 0x3c, 0x4f, 0x79,
+ 0x28, 0xe2, 0xdc, 0x68, 0x9d, 0xc2, 0xf1, 0x06, 0x24, 0xf7, 0xa1, 0x29, 0x55, 0x8a, 0x7c, 0xac,
+ 0x26, 0xf6, 0xdd, 0x7e, 0x51, 0xdb, 0x7d, 0xfa, 0xcc, 0x9b, 0x81, 0xd7, 0xab, 0x51, 0xfb, 0x8a,
+ 0x1a, 0x97, 0x5d, 0x57, 0xbf, 0xca, 0x75, 0xbf, 0x43, 0xb4, 0x05, 0x3d, 0x1a, 0x8b, 0x7a, 0x68,
+ 0x82, 0x51, 0x35, 0x1f, 0xa5, 0xf6, 0xbd, 0x06, 0x0d, 0x5d, 0x35, 0x69, 0x5b, 0x97, 0x27, 0xad,
+ 0x5d, 0xe5, 0x5e, 0xec, 0x43, 0x37, 0xb7, 0xaf, 0x87, 0xff, 0xcb, 0x50, 0x2a, 0xf7, 0x2f, 0x00,
+ 0x39, 0xb2, 0x17, 0x9c, 0x5e, 0xf4, 0x74, 0xa5, 0xec, 0xe9, 0x5f, 0x6a, 0xd0, 0xf5, 0x30, 0x10,
+ 0x67, 0x98, 0x4e, 0xf3, 0xd6, 0x6c, 0x02, 0x9c, 0x8b, 0x34, 0xb4, 0x87, 0xcf, 0x67, 0x44, 0x4b,
+ 0x23, 0xe6, 0xec, 0xd7, 0x2b, 0x5e, 0xfd, 0x26, 0xc5, 0x6b, 0x37, 0x29, 0x5e, 0xbf, 0x51, 0xf1,
+ 0xdb, 0x65, 0xc5, 0x1f, 0x43, 0x1f, 0xf9, 0x48, 0xa4, 0x01, 0xfa, 0xfa, 0xac, 0x11, 0x93, 0xca,
+ 0xb4, 0xa4, 0xe9, 0xf5, 0x72, 0xfc, 0x73, 0x0e, 0x93, 0x13, 0xa8, 0xab, 0x69, 0x82, 0x46, 0xf4,
+ 0xee, 0xee, 0x3f, 0x6f, 0x98, 0xff, 0x17, 0xd5, 0x59, 0x08, 0xed, 0x4d, 0xd5, 0xbb, 0x2d, 0xb6,
+ 0xbc, 0x75, 0xa9, 0xe5, 0x6b, 0xd0, 0x08, 0xd3, 0xa9, 0x9f, 0x66, 0xdc, 0xfc, 0x75, 0xd5, 0xf4,
+ 0x96, 0xc2, 0x74, 0xea, 0x65, 0xdc, 0xfd, 0x0f, 0x90, 0xcb, 0xbb, 0x92, 0x1d, 0x78, 0x70, 0x19,
+ 0xf5, 0x8f, 0x83, 0x94, 0xc6, 0xc3, 0x08, 0x43, 0x5d, 0x8d, 0xec, 0xdf, 0x22, 0x9b, 0xb0, 0x7e,
+ 0x05, 0xed, 0x90, 0xaa, 0x94, 0xfd, 0xbf, 0x5f, 0x71, 0x7f, 0xaa, 0xc0, 0xb2, 0xa6, 0xe6, 0xbe,
+ 0x20, 0x1f, 0xf3, 0xda, 0x2b, 0xa6, 0xf6, 0x17, 0x37, 0xd4, 0x5e, 0xfa, 0xb2, 0xbc, 0x9e, 0x57,
+ 0xed, 0x8e, 0xa0, 0xb7, 0x90, 0x20, 0xeb, 0xb0, 0xba, 0x00, 0xf9, 0x47, 0x11, 0x65, 0xbc, 0x7f,
+ 0x8b, 0x6c, 0xc0, 0xda, 0x62, 0xca, 0x9e, 0xf4, 0x79, 0xbf, 0x72, 0x7d, 0xf2, 0x59, 0xbf, 0xea,
+ 0x6e, 0x42, 0x43, 0x27, 0xb5, 0x99, 0x09, 0xd4, 0x75, 0x87, 0xcd, 0x74, 0x6e, 0x79, 0x66, 0xed,
+ 0xfe, 0x0d, 0x3a, 0xc7, 0xa8, 0xfe, 0xbd, 0xfb, 0xba, 0x74, 0xbf, 0xca, 0xdd, 0xa8, 0x2c, 0x76,
+ 0xe3, 0xe5, 0x3f, 0x60, 0x3b, 0x10, 0xf1, 0x40, 0x52, 0x25, 0xe4, 0x84, 0x45, 0x74, 0x28, 0x0b,
+ 0x21, 0x22, 0x36, 0xb4, 0xff, 0xbb, 0x0c, 0xb3, 0xd1, 0xcb, 0xb5, 0x13, 0x03, 0x1e, 0x5a, 0x71,
+ 0x0e, 0x67, 0xd2, 0xfc, 0x1a, 0x00, 0x00, 0xff, 0xff, 0xd7, 0x6e, 0xfc, 0x59, 0x29, 0x0d, 0x00,
+ 0x00,
+}
diff --git a/accounts/usbwallet/trezor/messages-management.proto b/accounts/usbwallet/trezor/messages-management.proto
new file mode 100644
index 000000000..0ab825a1b
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages-management.proto
@@ -0,0 +1,289 @@
+// This file originates from the SatoshiLabs Trezor `common` repository at:
+// https://github.com/trezor/trezor-common/blob/master/protob/messages-management.proto
+// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
+
+syntax = "proto2";
+package hw.trezor.messages.management;
+
+// Sugar for easier handling in Java
+option java_package = "com.satoshilabs.trezor.lib.protobuf";
+option java_outer_classname = "TrezorMessageManagement";
+
+import "messages-common.proto";
+
+/**
+ * Request: Reset device to default state and ask for device details
+ * @start
+ * @next Features
+ */
+message Initialize {
+ optional bytes state = 1; // assumed device state, clear session if set and different
+ optional bool skip_passphrase = 2; // this session should always assume empty passphrase
+}
+
+/**
+ * Request: Ask for device details (no device reset)
+ * @start
+ * @next Features
+ */
+message GetFeatures {
+}
+
+/**
+ * Response: Reports various information about the device
+ * @end
+ */
+message Features {
+ optional string vendor = 1; // name of the manufacturer, e.g. "trezor.io"
+ optional uint32 major_version = 2; // major version of the firmware/bootloader, e.g. 1
+ optional uint32 minor_version = 3; // minor version of the firmware/bootloader, e.g. 0
+ optional uint32 patch_version = 4; // patch version of the firmware/bootloader, e.g. 0
+ optional bool bootloader_mode = 5; // is device in bootloader mode?
+ optional string device_id = 6; // device's unique identifier
+ optional bool pin_protection = 7; // is device protected by PIN?
+ optional bool passphrase_protection = 8; // is node/mnemonic encrypted using passphrase?
+ optional string language = 9; // device language
+ optional string label = 10; // device description label
+ optional bool initialized = 12; // does device contain seed?
+ optional bytes revision = 13; // SCM revision of firmware
+ optional bytes bootloader_hash = 14; // hash of the bootloader
+ optional bool imported = 15; // was storage imported from an external source?
+ optional bool pin_cached = 16; // is PIN already cached in session?
+ optional bool passphrase_cached = 17; // is passphrase already cached in session?
+ optional bool firmware_present = 18; // is valid firmware loaded?
+ optional bool needs_backup = 19; // does storage need backup? (equals to Storage.needs_backup)
+ optional uint32 flags = 20; // device flags (equals to Storage.flags)
+ optional string model = 21; // device hardware model
+ optional uint32 fw_major = 22; // reported firmware version if in bootloader mode
+ optional uint32 fw_minor = 23; // reported firmware version if in bootloader mode
+ optional uint32 fw_patch = 24; // reported firmware version if in bootloader mode
+ optional string fw_vendor = 25; // reported firmware vendor if in bootloader mode
+ optional bytes fw_vendor_keys = 26; // reported firmware vendor keys (their hash)
+ optional bool unfinished_backup = 27; // report unfinished backup (equals to Storage.unfinished_backup)
+ optional bool no_backup = 28; // report no backup (equals to Storage.no_backup)
+}
+
+/**
+ * Request: clear session (removes cached PIN, passphrase, etc).
+ * @start
+ * @next Success
+ */
+message ClearSession {
+}
+
+/**
+ * Request: change language and/or label of the device
+ * @start
+ * @next Success
+ * @next Failure
+ */
+message ApplySettings {
+ optional string language = 1;
+ optional string label = 2;
+ optional bool use_passphrase = 3;
+ optional bytes homescreen = 4;
+ optional PassphraseSourceType passphrase_source = 5;
+ optional uint32 auto_lock_delay_ms = 6;
+ optional uint32 display_rotation = 7; // in degrees from North
+ /**
+ * Structure representing passphrase source
+ */
+ enum PassphraseSourceType {
+ ASK = 0;
+ DEVICE = 1;
+ HOST = 2;
+ }
+}
+
+/**
+ * Request: set flags of the device
+ * @start
+ * @next Success
+ * @next Failure
+ */
+message ApplyFlags {
+ optional uint32 flags = 1; // bitmask, can only set bits, not unset
+}
+
+/**
+ * Request: Starts workflow for setting/changing/removing the PIN
+ * @start
+ * @next Success
+ * @next Failure
+ */
+message ChangePin {
+ optional bool remove = 1; // is PIN removal requested?
+}
+
+/**
+ * Request: Test if the device is alive, device sends back the message in Success response
+ * @start
+ * @next Success
+ */
+message Ping {
+ optional string message = 1; // message to send back in Success message
+ optional bool button_protection = 2; // ask for button press
+ optional bool pin_protection = 3; // ask for PIN if set in device
+ optional bool passphrase_protection = 4; // ask for passphrase if set in device
+}
+
+/**
+ * Request: Abort last operation that required user interaction
+ * @start
+ * @next Failure
+ */
+message Cancel {
+}
+
+/**
+ * Request: Request a sample of random data generated by hardware RNG. May be used for testing.
+ * @start
+ * @next Entropy
+ * @next Failure
+ */
+message GetEntropy {
+ required uint32 size = 1; // size of requested entropy
+}
+
+/**
+ * Response: Reply with random data generated by internal RNG
+ * @end
+ */
+message Entropy {
+ required bytes entropy = 1; // chunk of random generated bytes
+}
+
+/**
+ * Request: Request device to wipe all sensitive data and settings
+ * @start
+ * @next Success
+ * @next Failure
+ */
+message WipeDevice {
+}
+
+/**
+ * Request: Load seed and related internal settings from the computer
+ * @start
+ * @next Success
+ * @next Failure
+ */
+message LoadDevice {
+ optional string mnemonic = 1; // seed encoded as BIP-39 mnemonic (12, 18 or 24 words)
+ optional hw.trezor.messages.common.HDNodeType node = 2; // BIP-32 node
+ optional string pin = 3; // set PIN protection
+ optional bool passphrase_protection = 4; // enable master node encryption using passphrase
+ optional string language = 5 [default='english']; // device language
+ optional string label = 6; // device label
+ optional bool skip_checksum = 7; // do not test mnemonic for valid BIP-39 checksum
+ optional uint32 u2f_counter = 8; // U2F counter
+}
+
+/**
+ * Request: Ask device to do initialization involving user interaction
+ * @start
+ * @next EntropyRequest
+ * @next Failure
+ */
+message ResetDevice {
+ optional bool display_random = 1; // display entropy generated by the device before asking for additional entropy
+ optional uint32 strength = 2 [default=256]; // strength of seed in bits
+ optional bool passphrase_protection = 3; // enable master node encryption using passphrase
+ optional bool pin_protection = 4; // enable PIN protection
+ optional string language = 5 [default='english']; // device language
+ optional string label = 6; // device label
+ optional uint32 u2f_counter = 7; // U2F counter
+ optional bool skip_backup = 8; // postpone seed backup to BackupDevice workflow
+ optional bool no_backup = 9; // indicate that no backup is going to be made
+}
+
+/**
+ * Request: Perform backup of the device seed if not backed up using ResetDevice
+ * @start
+ * @next Success
+ */
+message BackupDevice {
+}
+
+/**
+ * Response: Ask for additional entropy from host computer
+ * @next EntropyAck
+ */
+message EntropyRequest {
+}
+
+/**
+ * Request: Provide additional entropy for seed generation function
+ * @next Success
+ */
+message EntropyAck {
+ optional bytes entropy = 1; // 256 bits (32 bytes) of random data
+}
+
+/**
+ * Request: Start recovery workflow asking user for specific words of mnemonic
+ * Used to recovery device safely even on untrusted computer.
+ * @start
+ * @next WordRequest
+ */
+message RecoveryDevice {
+ optional uint32 word_count = 1; // number of words in BIP-39 mnemonic
+ optional bool passphrase_protection = 2; // enable master node encryption using passphrase
+ optional bool pin_protection = 3; // enable PIN protection
+ optional string language = 4 [default='english']; // device language
+ optional string label = 5; // device label
+ optional bool enforce_wordlist = 6; // enforce BIP-39 wordlist during the process
+ // 7 reserved for unused recovery method
+ optional RecoveryDeviceType type = 8; // supported recovery type
+ optional uint32 u2f_counter = 9; // U2F counter
+ optional bool dry_run = 10; // perform dry-run recovery workflow (for safe mnemonic validation)
+ /**
+ * Type of recovery procedure. These should be used as bitmask, e.g.,
+ * `RecoveryDeviceType_ScrambledWords | RecoveryDeviceType_Matrix`
+ * listing every method supported by the host computer.
+ *
+ * Note that ScrambledWords must be supported by every implementation
+ * for backward compatibility; there is no way to not support it.
+ */
+ enum RecoveryDeviceType {
+ // use powers of two when extending this field
+ RecoveryDeviceType_ScrambledWords = 0; // words in scrambled order
+ RecoveryDeviceType_Matrix = 1; // matrix recovery type
+ }
+}
+
+/**
+ * Response: Device is waiting for user to enter word of the mnemonic
+ * Its position is shown only on device's internal display.
+ * @next WordAck
+ */
+message WordRequest {
+ optional WordRequestType type = 1;
+ /**
+ * Type of Recovery Word request
+ */
+ enum WordRequestType {
+ WordRequestType_Plain = 0;
+ WordRequestType_Matrix9 = 1;
+ WordRequestType_Matrix6 = 2;
+ }
+}
+
+/**
+ * Request: Computer replies with word from the mnemonic
+ * @next WordRequest
+ * @next Success
+ * @next Failure
+ */
+message WordAck {
+ required string word = 1; // one word of mnemonic on asked position
+}
+
+/**
+ * Request: Set U2F counter
+ * @start
+ * @next Success
+ */
+message SetU2FCounter {
+ optional uint32 u2f_counter = 1; // counter
+}
diff --git a/accounts/usbwallet/trezor/messages.pb.go b/accounts/usbwallet/trezor/messages.pb.go
new file mode 100644
index 000000000..6278bd8ee
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages.pb.go
@@ -0,0 +1,889 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: messages.proto
+
+package trezor
+
+import (
+ fmt "fmt"
+ math "math"
+
+ proto "github.com/golang/protobuf/proto"
+ descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
+
+//*
+// Mapping between TREZOR wire identifier (uint) and a protobuf message
+type MessageType int32
+
+const (
+ // Management
+ MessageType_MessageType_Initialize MessageType = 0
+ MessageType_MessageType_Ping MessageType = 1
+ MessageType_MessageType_Success MessageType = 2
+ MessageType_MessageType_Failure MessageType = 3
+ MessageType_MessageType_ChangePin MessageType = 4
+ MessageType_MessageType_WipeDevice MessageType = 5
+ MessageType_MessageType_GetEntropy MessageType = 9
+ MessageType_MessageType_Entropy MessageType = 10
+ MessageType_MessageType_LoadDevice MessageType = 13
+ MessageType_MessageType_ResetDevice MessageType = 14
+ MessageType_MessageType_Features MessageType = 17
+ MessageType_MessageType_PinMatrixRequest MessageType = 18
+ MessageType_MessageType_PinMatrixAck MessageType = 19
+ MessageType_MessageType_Cancel MessageType = 20
+ MessageType_MessageType_ClearSession MessageType = 24
+ MessageType_MessageType_ApplySettings MessageType = 25
+ MessageType_MessageType_ButtonRequest MessageType = 26
+ MessageType_MessageType_ButtonAck MessageType = 27
+ MessageType_MessageType_ApplyFlags MessageType = 28
+ MessageType_MessageType_BackupDevice MessageType = 34
+ MessageType_MessageType_EntropyRequest MessageType = 35
+ MessageType_MessageType_EntropyAck MessageType = 36
+ MessageType_MessageType_PassphraseRequest MessageType = 41
+ MessageType_MessageType_PassphraseAck MessageType = 42
+ MessageType_MessageType_PassphraseStateRequest MessageType = 77
+ MessageType_MessageType_PassphraseStateAck MessageType = 78
+ MessageType_MessageType_RecoveryDevice MessageType = 45
+ MessageType_MessageType_WordRequest MessageType = 46
+ MessageType_MessageType_WordAck MessageType = 47
+ MessageType_MessageType_GetFeatures MessageType = 55
+ MessageType_MessageType_SetU2FCounter MessageType = 63
+ // Bootloader
+ MessageType_MessageType_FirmwareErase MessageType = 6
+ MessageType_MessageType_FirmwareUpload MessageType = 7
+ MessageType_MessageType_FirmwareRequest MessageType = 8
+ MessageType_MessageType_SelfTest MessageType = 32
+ // Bitcoin
+ MessageType_MessageType_GetPublicKey MessageType = 11
+ MessageType_MessageType_PublicKey MessageType = 12
+ MessageType_MessageType_SignTx MessageType = 15
+ MessageType_MessageType_TxRequest MessageType = 21
+ MessageType_MessageType_TxAck MessageType = 22
+ MessageType_MessageType_GetAddress MessageType = 29
+ MessageType_MessageType_Address MessageType = 30
+ MessageType_MessageType_SignMessage MessageType = 38
+ MessageType_MessageType_VerifyMessage MessageType = 39
+ MessageType_MessageType_MessageSignature MessageType = 40
+ // Crypto
+ MessageType_MessageType_CipherKeyValue MessageType = 23
+ MessageType_MessageType_CipheredKeyValue MessageType = 48
+ MessageType_MessageType_SignIdentity MessageType = 53
+ MessageType_MessageType_SignedIdentity MessageType = 54
+ MessageType_MessageType_GetECDHSessionKey MessageType = 61
+ MessageType_MessageType_ECDHSessionKey MessageType = 62
+ MessageType_MessageType_CosiCommit MessageType = 71
+ MessageType_MessageType_CosiCommitment MessageType = 72
+ MessageType_MessageType_CosiSign MessageType = 73
+ MessageType_MessageType_CosiSignature MessageType = 74
+ // Debug
+ MessageType_MessageType_DebugLinkDecision MessageType = 100
+ MessageType_MessageType_DebugLinkGetState MessageType = 101
+ MessageType_MessageType_DebugLinkState MessageType = 102
+ MessageType_MessageType_DebugLinkStop MessageType = 103
+ MessageType_MessageType_DebugLinkLog MessageType = 104
+ MessageType_MessageType_DebugLinkMemoryRead MessageType = 110
+ MessageType_MessageType_DebugLinkMemory MessageType = 111
+ MessageType_MessageType_DebugLinkMemoryWrite MessageType = 112
+ MessageType_MessageType_DebugLinkFlashErase MessageType = 113
+ // Ethereum
+ MessageType_MessageType_EthereumGetPublicKey MessageType = 450
+ MessageType_MessageType_EthereumPublicKey MessageType = 451
+ MessageType_MessageType_EthereumGetAddress MessageType = 56
+ MessageType_MessageType_EthereumAddress MessageType = 57
+ MessageType_MessageType_EthereumSignTx MessageType = 58
+ MessageType_MessageType_EthereumTxRequest MessageType = 59
+ MessageType_MessageType_EthereumTxAck MessageType = 60
+ MessageType_MessageType_EthereumSignMessage MessageType = 64
+ MessageType_MessageType_EthereumVerifyMessage MessageType = 65
+ MessageType_MessageType_EthereumMessageSignature MessageType = 66
+ // NEM
+ MessageType_MessageType_NEMGetAddress MessageType = 67
+ MessageType_MessageType_NEMAddress MessageType = 68
+ MessageType_MessageType_NEMSignTx MessageType = 69
+ MessageType_MessageType_NEMSignedTx MessageType = 70
+ MessageType_MessageType_NEMDecryptMessage MessageType = 75
+ MessageType_MessageType_NEMDecryptedMessage MessageType = 76
+ // Lisk
+ MessageType_MessageType_LiskGetAddress MessageType = 114
+ MessageType_MessageType_LiskAddress MessageType = 115
+ MessageType_MessageType_LiskSignTx MessageType = 116
+ MessageType_MessageType_LiskSignedTx MessageType = 117
+ MessageType_MessageType_LiskSignMessage MessageType = 118
+ MessageType_MessageType_LiskMessageSignature MessageType = 119
+ MessageType_MessageType_LiskVerifyMessage MessageType = 120
+ MessageType_MessageType_LiskGetPublicKey MessageType = 121
+ MessageType_MessageType_LiskPublicKey MessageType = 122
+ // Tezos
+ MessageType_MessageType_TezosGetAddress MessageType = 150
+ MessageType_MessageType_TezosAddress MessageType = 151
+ MessageType_MessageType_TezosSignTx MessageType = 152
+ MessageType_MessageType_TezosSignedTx MessageType = 153
+ MessageType_MessageType_TezosGetPublicKey MessageType = 154
+ MessageType_MessageType_TezosPublicKey MessageType = 155
+ // Stellar
+ MessageType_MessageType_StellarSignTx MessageType = 202
+ MessageType_MessageType_StellarTxOpRequest MessageType = 203
+ MessageType_MessageType_StellarGetAddress MessageType = 207
+ MessageType_MessageType_StellarAddress MessageType = 208
+ MessageType_MessageType_StellarCreateAccountOp MessageType = 210
+ MessageType_MessageType_StellarPaymentOp MessageType = 211
+ MessageType_MessageType_StellarPathPaymentOp MessageType = 212
+ MessageType_MessageType_StellarManageOfferOp MessageType = 213
+ MessageType_MessageType_StellarCreatePassiveOfferOp MessageType = 214
+ MessageType_MessageType_StellarSetOptionsOp MessageType = 215
+ MessageType_MessageType_StellarChangeTrustOp MessageType = 216
+ MessageType_MessageType_StellarAllowTrustOp MessageType = 217
+ MessageType_MessageType_StellarAccountMergeOp MessageType = 218
+ // omitted: StellarInflationOp is not a supported operation, would be 219
+ MessageType_MessageType_StellarManageDataOp MessageType = 220
+ MessageType_MessageType_StellarBumpSequenceOp MessageType = 221
+ MessageType_MessageType_StellarSignedTx MessageType = 230
+ // TRON
+ MessageType_MessageType_TronGetAddress MessageType = 250
+ MessageType_MessageType_TronAddress MessageType = 251
+ MessageType_MessageType_TronSignTx MessageType = 252
+ MessageType_MessageType_TronSignedTx MessageType = 253
+ // Cardano
+ // dropped Sign/VerifyMessage ids 300-302
+ MessageType_MessageType_CardanoSignTx MessageType = 303
+ MessageType_MessageType_CardanoTxRequest MessageType = 304
+ MessageType_MessageType_CardanoGetPublicKey MessageType = 305
+ MessageType_MessageType_CardanoPublicKey MessageType = 306
+ MessageType_MessageType_CardanoGetAddress MessageType = 307
+ MessageType_MessageType_CardanoAddress MessageType = 308
+ MessageType_MessageType_CardanoTxAck MessageType = 309
+ MessageType_MessageType_CardanoSignedTx MessageType = 310
+ // Ontology
+ MessageType_MessageType_OntologyGetAddress MessageType = 350
+ MessageType_MessageType_OntologyAddress MessageType = 351
+ MessageType_MessageType_OntologyGetPublicKey MessageType = 352
+ MessageType_MessageType_OntologyPublicKey MessageType = 353
+ MessageType_MessageType_OntologySignTransfer MessageType = 354
+ MessageType_MessageType_OntologySignedTransfer MessageType = 355
+ MessageType_MessageType_OntologySignWithdrawOng MessageType = 356
+ MessageType_MessageType_OntologySignedWithdrawOng MessageType = 357
+ MessageType_MessageType_OntologySignOntIdRegister MessageType = 358
+ MessageType_MessageType_OntologySignedOntIdRegister MessageType = 359
+ MessageType_MessageType_OntologySignOntIdAddAttributes MessageType = 360
+ MessageType_MessageType_OntologySignedOntIdAddAttributes MessageType = 361
+ // Ripple
+ MessageType_MessageType_RippleGetAddress MessageType = 400
+ MessageType_MessageType_RippleAddress MessageType = 401
+ MessageType_MessageType_RippleSignTx MessageType = 402
+ MessageType_MessageType_RippleSignedTx MessageType = 403
+ // Monero
+ MessageType_MessageType_MoneroTransactionInitRequest MessageType = 501
+ MessageType_MessageType_MoneroTransactionInitAck MessageType = 502
+ MessageType_MessageType_MoneroTransactionSetInputRequest MessageType = 503
+ MessageType_MessageType_MoneroTransactionSetInputAck MessageType = 504
+ MessageType_MessageType_MoneroTransactionInputsPermutationRequest MessageType = 505
+ MessageType_MessageType_MoneroTransactionInputsPermutationAck MessageType = 506
+ MessageType_MessageType_MoneroTransactionInputViniRequest MessageType = 507
+ MessageType_MessageType_MoneroTransactionInputViniAck MessageType = 508
+ MessageType_MessageType_MoneroTransactionAllInputsSetRequest MessageType = 509
+ MessageType_MessageType_MoneroTransactionAllInputsSetAck MessageType = 510
+ MessageType_MessageType_MoneroTransactionSetOutputRequest MessageType = 511
+ MessageType_MessageType_MoneroTransactionSetOutputAck MessageType = 512
+ MessageType_MessageType_MoneroTransactionAllOutSetRequest MessageType = 513
+ MessageType_MessageType_MoneroTransactionAllOutSetAck MessageType = 514
+ MessageType_MessageType_MoneroTransactionSignInputRequest MessageType = 515
+ MessageType_MessageType_MoneroTransactionSignInputAck MessageType = 516
+ MessageType_MessageType_MoneroTransactionFinalRequest MessageType = 517
+ MessageType_MessageType_MoneroTransactionFinalAck MessageType = 518
+ MessageType_MessageType_MoneroKeyImageExportInitRequest MessageType = 530
+ MessageType_MessageType_MoneroKeyImageExportInitAck MessageType = 531
+ MessageType_MessageType_MoneroKeyImageSyncStepRequest MessageType = 532
+ MessageType_MessageType_MoneroKeyImageSyncStepAck MessageType = 533
+ MessageType_MessageType_MoneroKeyImageSyncFinalRequest MessageType = 534
+ MessageType_MessageType_MoneroKeyImageSyncFinalAck MessageType = 535
+ MessageType_MessageType_MoneroGetAddress MessageType = 540
+ MessageType_MessageType_MoneroAddress MessageType = 541
+ MessageType_MessageType_MoneroGetWatchKey MessageType = 542
+ MessageType_MessageType_MoneroWatchKey MessageType = 543
+ MessageType_MessageType_DebugMoneroDiagRequest MessageType = 546
+ MessageType_MessageType_DebugMoneroDiagAck MessageType = 547
+ MessageType_MessageType_MoneroGetTxKeyRequest MessageType = 550
+ MessageType_MessageType_MoneroGetTxKeyAck MessageType = 551
+ MessageType_MessageType_MoneroLiveRefreshStartRequest MessageType = 552
+ MessageType_MessageType_MoneroLiveRefreshStartAck MessageType = 553
+ MessageType_MessageType_MoneroLiveRefreshStepRequest MessageType = 554
+ MessageType_MessageType_MoneroLiveRefreshStepAck MessageType = 555
+ MessageType_MessageType_MoneroLiveRefreshFinalRequest MessageType = 556
+ MessageType_MessageType_MoneroLiveRefreshFinalAck MessageType = 557
+ // EOS
+ MessageType_MessageType_EosGetPublicKey MessageType = 600
+ MessageType_MessageType_EosPublicKey MessageType = 601
+ MessageType_MessageType_EosSignTx MessageType = 602
+ MessageType_MessageType_EosTxActionRequest MessageType = 603
+ MessageType_MessageType_EosTxActionAck MessageType = 604
+ MessageType_MessageType_EosSignedTx MessageType = 605
+ // Binance
+ MessageType_MessageType_BinanceGetAddress MessageType = 700
+ MessageType_MessageType_BinanceAddress MessageType = 701
+ MessageType_MessageType_BinanceGetPublicKey MessageType = 702
+ MessageType_MessageType_BinancePublicKey MessageType = 703
+ MessageType_MessageType_BinanceSignTx MessageType = 704
+ MessageType_MessageType_BinanceTxRequest MessageType = 705
+ MessageType_MessageType_BinanceTransferMsg MessageType = 706
+ MessageType_MessageType_BinanceOrderMsg MessageType = 707
+ MessageType_MessageType_BinanceCancelMsg MessageType = 708
+ MessageType_MessageType_BinanceSignedTx MessageType = 709
+)
+
+var MessageType_name = map[int32]string{
+ 0: "MessageType_Initialize",
+ 1: "MessageType_Ping",
+ 2: "MessageType_Success",
+ 3: "MessageType_Failure",
+ 4: "MessageType_ChangePin",
+ 5: "MessageType_WipeDevice",
+ 9: "MessageType_GetEntropy",
+ 10: "MessageType_Entropy",
+ 13: "MessageType_LoadDevice",
+ 14: "MessageType_ResetDevice",
+ 17: "MessageType_Features",
+ 18: "MessageType_PinMatrixRequest",
+ 19: "MessageType_PinMatrixAck",
+ 20: "MessageType_Cancel",
+ 24: "MessageType_ClearSession",
+ 25: "MessageType_ApplySettings",
+ 26: "MessageType_ButtonRequest",
+ 27: "MessageType_ButtonAck",
+ 28: "MessageType_ApplyFlags",
+ 34: "MessageType_BackupDevice",
+ 35: "MessageType_EntropyRequest",
+ 36: "MessageType_EntropyAck",
+ 41: "MessageType_PassphraseRequest",
+ 42: "MessageType_PassphraseAck",
+ 77: "MessageType_PassphraseStateRequest",
+ 78: "MessageType_PassphraseStateAck",
+ 45: "MessageType_RecoveryDevice",
+ 46: "MessageType_WordRequest",
+ 47: "MessageType_WordAck",
+ 55: "MessageType_GetFeatures",
+ 63: "MessageType_SetU2FCounter",
+ 6: "MessageType_FirmwareErase",
+ 7: "MessageType_FirmwareUpload",
+ 8: "MessageType_FirmwareRequest",
+ 32: "MessageType_SelfTest",
+ 11: "MessageType_GetPublicKey",
+ 12: "MessageType_PublicKey",
+ 15: "MessageType_SignTx",
+ 21: "MessageType_TxRequest",
+ 22: "MessageType_TxAck",
+ 29: "MessageType_GetAddress",
+ 30: "MessageType_Address",
+ 38: "MessageType_SignMessage",
+ 39: "MessageType_VerifyMessage",
+ 40: "MessageType_MessageSignature",
+ 23: "MessageType_CipherKeyValue",
+ 48: "MessageType_CipheredKeyValue",
+ 53: "MessageType_SignIdentity",
+ 54: "MessageType_SignedIdentity",
+ 61: "MessageType_GetECDHSessionKey",
+ 62: "MessageType_ECDHSessionKey",
+ 71: "MessageType_CosiCommit",
+ 72: "MessageType_CosiCommitment",
+ 73: "MessageType_CosiSign",
+ 74: "MessageType_CosiSignature",
+ 100: "MessageType_DebugLinkDecision",
+ 101: "MessageType_DebugLinkGetState",
+ 102: "MessageType_DebugLinkState",
+ 103: "MessageType_DebugLinkStop",
+ 104: "MessageType_DebugLinkLog",
+ 110: "MessageType_DebugLinkMemoryRead",
+ 111: "MessageType_DebugLinkMemory",
+ 112: "MessageType_DebugLinkMemoryWrite",
+ 113: "MessageType_DebugLinkFlashErase",
+ 450: "MessageType_EthereumGetPublicKey",
+ 451: "MessageType_EthereumPublicKey",
+ 56: "MessageType_EthereumGetAddress",
+ 57: "MessageType_EthereumAddress",
+ 58: "MessageType_EthereumSignTx",
+ 59: "MessageType_EthereumTxRequest",
+ 60: "MessageType_EthereumTxAck",
+ 64: "MessageType_EthereumSignMessage",
+ 65: "MessageType_EthereumVerifyMessage",
+ 66: "MessageType_EthereumMessageSignature",
+ 67: "MessageType_NEMGetAddress",
+ 68: "MessageType_NEMAddress",
+ 69: "MessageType_NEMSignTx",
+ 70: "MessageType_NEMSignedTx",
+ 75: "MessageType_NEMDecryptMessage",
+ 76: "MessageType_NEMDecryptedMessage",
+ 114: "MessageType_LiskGetAddress",
+ 115: "MessageType_LiskAddress",
+ 116: "MessageType_LiskSignTx",
+ 117: "MessageType_LiskSignedTx",
+ 118: "MessageType_LiskSignMessage",
+ 119: "MessageType_LiskMessageSignature",
+ 120: "MessageType_LiskVerifyMessage",
+ 121: "MessageType_LiskGetPublicKey",
+ 122: "MessageType_LiskPublicKey",
+ 150: "MessageType_TezosGetAddress",
+ 151: "MessageType_TezosAddress",
+ 152: "MessageType_TezosSignTx",
+ 153: "MessageType_TezosSignedTx",
+ 154: "MessageType_TezosGetPublicKey",
+ 155: "MessageType_TezosPublicKey",
+ 202: "MessageType_StellarSignTx",
+ 203: "MessageType_StellarTxOpRequest",
+ 207: "MessageType_StellarGetAddress",
+ 208: "MessageType_StellarAddress",
+ 210: "MessageType_StellarCreateAccountOp",
+ 211: "MessageType_StellarPaymentOp",
+ 212: "MessageType_StellarPathPaymentOp",
+ 213: "MessageType_StellarManageOfferOp",
+ 214: "MessageType_StellarCreatePassiveOfferOp",
+ 215: "MessageType_StellarSetOptionsOp",
+ 216: "MessageType_StellarChangeTrustOp",
+ 217: "MessageType_StellarAllowTrustOp",
+ 218: "MessageType_StellarAccountMergeOp",
+ 220: "MessageType_StellarManageDataOp",
+ 221: "MessageType_StellarBumpSequenceOp",
+ 230: "MessageType_StellarSignedTx",
+ 250: "MessageType_TronGetAddress",
+ 251: "MessageType_TronAddress",
+ 252: "MessageType_TronSignTx",
+ 253: "MessageType_TronSignedTx",
+ 303: "MessageType_CardanoSignTx",
+ 304: "MessageType_CardanoTxRequest",
+ 305: "MessageType_CardanoGetPublicKey",
+ 306: "MessageType_CardanoPublicKey",
+ 307: "MessageType_CardanoGetAddress",
+ 308: "MessageType_CardanoAddress",
+ 309: "MessageType_CardanoTxAck",
+ 310: "MessageType_CardanoSignedTx",
+ 350: "MessageType_OntologyGetAddress",
+ 351: "MessageType_OntologyAddress",
+ 352: "MessageType_OntologyGetPublicKey",
+ 353: "MessageType_OntologyPublicKey",
+ 354: "MessageType_OntologySignTransfer",
+ 355: "MessageType_OntologySignedTransfer",
+ 356: "MessageType_OntologySignWithdrawOng",
+ 357: "MessageType_OntologySignedWithdrawOng",
+ 358: "MessageType_OntologySignOntIdRegister",
+ 359: "MessageType_OntologySignedOntIdRegister",
+ 360: "MessageType_OntologySignOntIdAddAttributes",
+ 361: "MessageType_OntologySignedOntIdAddAttributes",
+ 400: "MessageType_RippleGetAddress",
+ 401: "MessageType_RippleAddress",
+ 402: "MessageType_RippleSignTx",
+ 403: "MessageType_RippleSignedTx",
+ 501: "MessageType_MoneroTransactionInitRequest",
+ 502: "MessageType_MoneroTransactionInitAck",
+ 503: "MessageType_MoneroTransactionSetInputRequest",
+ 504: "MessageType_MoneroTransactionSetInputAck",
+ 505: "MessageType_MoneroTransactionInputsPermutationRequest",
+ 506: "MessageType_MoneroTransactionInputsPermutationAck",
+ 507: "MessageType_MoneroTransactionInputViniRequest",
+ 508: "MessageType_MoneroTransactionInputViniAck",
+ 509: "MessageType_MoneroTransactionAllInputsSetRequest",
+ 510: "MessageType_MoneroTransactionAllInputsSetAck",
+ 511: "MessageType_MoneroTransactionSetOutputRequest",
+ 512: "MessageType_MoneroTransactionSetOutputAck",
+ 513: "MessageType_MoneroTransactionAllOutSetRequest",
+ 514: "MessageType_MoneroTransactionAllOutSetAck",
+ 515: "MessageType_MoneroTransactionSignInputRequest",
+ 516: "MessageType_MoneroTransactionSignInputAck",
+ 517: "MessageType_MoneroTransactionFinalRequest",
+ 518: "MessageType_MoneroTransactionFinalAck",
+ 530: "MessageType_MoneroKeyImageExportInitRequest",
+ 531: "MessageType_MoneroKeyImageExportInitAck",
+ 532: "MessageType_MoneroKeyImageSyncStepRequest",
+ 533: "MessageType_MoneroKeyImageSyncStepAck",
+ 534: "MessageType_MoneroKeyImageSyncFinalRequest",
+ 535: "MessageType_MoneroKeyImageSyncFinalAck",
+ 540: "MessageType_MoneroGetAddress",
+ 541: "MessageType_MoneroAddress",
+ 542: "MessageType_MoneroGetWatchKey",
+ 543: "MessageType_MoneroWatchKey",
+ 546: "MessageType_DebugMoneroDiagRequest",
+ 547: "MessageType_DebugMoneroDiagAck",
+ 550: "MessageType_MoneroGetTxKeyRequest",
+ 551: "MessageType_MoneroGetTxKeyAck",
+ 552: "MessageType_MoneroLiveRefreshStartRequest",
+ 553: "MessageType_MoneroLiveRefreshStartAck",
+ 554: "MessageType_MoneroLiveRefreshStepRequest",
+ 555: "MessageType_MoneroLiveRefreshStepAck",
+ 556: "MessageType_MoneroLiveRefreshFinalRequest",
+ 557: "MessageType_MoneroLiveRefreshFinalAck",
+ 600: "MessageType_EosGetPublicKey",
+ 601: "MessageType_EosPublicKey",
+ 602: "MessageType_EosSignTx",
+ 603: "MessageType_EosTxActionRequest",
+ 604: "MessageType_EosTxActionAck",
+ 605: "MessageType_EosSignedTx",
+ 700: "MessageType_BinanceGetAddress",
+ 701: "MessageType_BinanceAddress",
+ 702: "MessageType_BinanceGetPublicKey",
+ 703: "MessageType_BinancePublicKey",
+ 704: "MessageType_BinanceSignTx",
+ 705: "MessageType_BinanceTxRequest",
+ 706: "MessageType_BinanceTransferMsg",
+ 707: "MessageType_BinanceOrderMsg",
+ 708: "MessageType_BinanceCancelMsg",
+ 709: "MessageType_BinanceSignedTx",
+}
+
+var MessageType_value = map[string]int32{
+ "MessageType_Initialize": 0,
+ "MessageType_Ping": 1,
+ "MessageType_Success": 2,
+ "MessageType_Failure": 3,
+ "MessageType_ChangePin": 4,
+ "MessageType_WipeDevice": 5,
+ "MessageType_GetEntropy": 9,
+ "MessageType_Entropy": 10,
+ "MessageType_LoadDevice": 13,
+ "MessageType_ResetDevice": 14,
+ "MessageType_Features": 17,
+ "MessageType_PinMatrixRequest": 18,
+ "MessageType_PinMatrixAck": 19,
+ "MessageType_Cancel": 20,
+ "MessageType_ClearSession": 24,
+ "MessageType_ApplySettings": 25,
+ "MessageType_ButtonRequest": 26,
+ "MessageType_ButtonAck": 27,
+ "MessageType_ApplyFlags": 28,
+ "MessageType_BackupDevice": 34,
+ "MessageType_EntropyRequest": 35,
+ "MessageType_EntropyAck": 36,
+ "MessageType_PassphraseRequest": 41,
+ "MessageType_PassphraseAck": 42,
+ "MessageType_PassphraseStateRequest": 77,
+ "MessageType_PassphraseStateAck": 78,
+ "MessageType_RecoveryDevice": 45,
+ "MessageType_WordRequest": 46,
+ "MessageType_WordAck": 47,
+ "MessageType_GetFeatures": 55,
+ "MessageType_SetU2FCounter": 63,
+ "MessageType_FirmwareErase": 6,
+ "MessageType_FirmwareUpload": 7,
+ "MessageType_FirmwareRequest": 8,
+ "MessageType_SelfTest": 32,
+ "MessageType_GetPublicKey": 11,
+ "MessageType_PublicKey": 12,
+ "MessageType_SignTx": 15,
+ "MessageType_TxRequest": 21,
+ "MessageType_TxAck": 22,
+ "MessageType_GetAddress": 29,
+ "MessageType_Address": 30,
+ "MessageType_SignMessage": 38,
+ "MessageType_VerifyMessage": 39,
+ "MessageType_MessageSignature": 40,
+ "MessageType_CipherKeyValue": 23,
+ "MessageType_CipheredKeyValue": 48,
+ "MessageType_SignIdentity": 53,
+ "MessageType_SignedIdentity": 54,
+ "MessageType_GetECDHSessionKey": 61,
+ "MessageType_ECDHSessionKey": 62,
+ "MessageType_CosiCommit": 71,
+ "MessageType_CosiCommitment": 72,
+ "MessageType_CosiSign": 73,
+ "MessageType_CosiSignature": 74,
+ "MessageType_DebugLinkDecision": 100,
+ "MessageType_DebugLinkGetState": 101,
+ "MessageType_DebugLinkState": 102,
+ "MessageType_DebugLinkStop": 103,
+ "MessageType_DebugLinkLog": 104,
+ "MessageType_DebugLinkMemoryRead": 110,
+ "MessageType_DebugLinkMemory": 111,
+ "MessageType_DebugLinkMemoryWrite": 112,
+ "MessageType_DebugLinkFlashErase": 113,
+ "MessageType_EthereumGetPublicKey": 450,
+ "MessageType_EthereumPublicKey": 451,
+ "MessageType_EthereumGetAddress": 56,
+ "MessageType_EthereumAddress": 57,
+ "MessageType_EthereumSignTx": 58,
+ "MessageType_EthereumTxRequest": 59,
+ "MessageType_EthereumTxAck": 60,
+ "MessageType_EthereumSignMessage": 64,
+ "MessageType_EthereumVerifyMessage": 65,
+ "MessageType_EthereumMessageSignature": 66,
+ "MessageType_NEMGetAddress": 67,
+ "MessageType_NEMAddress": 68,
+ "MessageType_NEMSignTx": 69,
+ "MessageType_NEMSignedTx": 70,
+ "MessageType_NEMDecryptMessage": 75,
+ "MessageType_NEMDecryptedMessage": 76,
+ "MessageType_LiskGetAddress": 114,
+ "MessageType_LiskAddress": 115,
+ "MessageType_LiskSignTx": 116,
+ "MessageType_LiskSignedTx": 117,
+ "MessageType_LiskSignMessage": 118,
+ "MessageType_LiskMessageSignature": 119,
+ "MessageType_LiskVerifyMessage": 120,
+ "MessageType_LiskGetPublicKey": 121,
+ "MessageType_LiskPublicKey": 122,
+ "MessageType_TezosGetAddress": 150,
+ "MessageType_TezosAddress": 151,
+ "MessageType_TezosSignTx": 152,
+ "MessageType_TezosSignedTx": 153,
+ "MessageType_TezosGetPublicKey": 154,
+ "MessageType_TezosPublicKey": 155,
+ "MessageType_StellarSignTx": 202,
+ "MessageType_StellarTxOpRequest": 203,
+ "MessageType_StellarGetAddress": 207,
+ "MessageType_StellarAddress": 208,
+ "MessageType_StellarCreateAccountOp": 210,
+ "MessageType_StellarPaymentOp": 211,
+ "MessageType_StellarPathPaymentOp": 212,
+ "MessageType_StellarManageOfferOp": 213,
+ "MessageType_StellarCreatePassiveOfferOp": 214,
+ "MessageType_StellarSetOptionsOp": 215,
+ "MessageType_StellarChangeTrustOp": 216,
+ "MessageType_StellarAllowTrustOp": 217,
+ "MessageType_StellarAccountMergeOp": 218,
+ "MessageType_StellarManageDataOp": 220,
+ "MessageType_StellarBumpSequenceOp": 221,
+ "MessageType_StellarSignedTx": 230,
+ "MessageType_TronGetAddress": 250,
+ "MessageType_TronAddress": 251,
+ "MessageType_TronSignTx": 252,
+ "MessageType_TronSignedTx": 253,
+ "MessageType_CardanoSignTx": 303,
+ "MessageType_CardanoTxRequest": 304,
+ "MessageType_CardanoGetPublicKey": 305,
+ "MessageType_CardanoPublicKey": 306,
+ "MessageType_CardanoGetAddress": 307,
+ "MessageType_CardanoAddress": 308,
+ "MessageType_CardanoTxAck": 309,
+ "MessageType_CardanoSignedTx": 310,
+ "MessageType_OntologyGetAddress": 350,
+ "MessageType_OntologyAddress": 351,
+ "MessageType_OntologyGetPublicKey": 352,
+ "MessageType_OntologyPublicKey": 353,
+ "MessageType_OntologySignTransfer": 354,
+ "MessageType_OntologySignedTransfer": 355,
+ "MessageType_OntologySignWithdrawOng": 356,
+ "MessageType_OntologySignedWithdrawOng": 357,
+ "MessageType_OntologySignOntIdRegister": 358,
+ "MessageType_OntologySignedOntIdRegister": 359,
+ "MessageType_OntologySignOntIdAddAttributes": 360,
+ "MessageType_OntologySignedOntIdAddAttributes": 361,
+ "MessageType_RippleGetAddress": 400,
+ "MessageType_RippleAddress": 401,
+ "MessageType_RippleSignTx": 402,
+ "MessageType_RippleSignedTx": 403,
+ "MessageType_MoneroTransactionInitRequest": 501,
+ "MessageType_MoneroTransactionInitAck": 502,
+ "MessageType_MoneroTransactionSetInputRequest": 503,
+ "MessageType_MoneroTransactionSetInputAck": 504,
+ "MessageType_MoneroTransactionInputsPermutationRequest": 505,
+ "MessageType_MoneroTransactionInputsPermutationAck": 506,
+ "MessageType_MoneroTransactionInputViniRequest": 507,
+ "MessageType_MoneroTransactionInputViniAck": 508,
+ "MessageType_MoneroTransactionAllInputsSetRequest": 509,
+ "MessageType_MoneroTransactionAllInputsSetAck": 510,
+ "MessageType_MoneroTransactionSetOutputRequest": 511,
+ "MessageType_MoneroTransactionSetOutputAck": 512,
+ "MessageType_MoneroTransactionAllOutSetRequest": 513,
+ "MessageType_MoneroTransactionAllOutSetAck": 514,
+ "MessageType_MoneroTransactionSignInputRequest": 515,
+ "MessageType_MoneroTransactionSignInputAck": 516,
+ "MessageType_MoneroTransactionFinalRequest": 517,
+ "MessageType_MoneroTransactionFinalAck": 518,
+ "MessageType_MoneroKeyImageExportInitRequest": 530,
+ "MessageType_MoneroKeyImageExportInitAck": 531,
+ "MessageType_MoneroKeyImageSyncStepRequest": 532,
+ "MessageType_MoneroKeyImageSyncStepAck": 533,
+ "MessageType_MoneroKeyImageSyncFinalRequest": 534,
+ "MessageType_MoneroKeyImageSyncFinalAck": 535,
+ "MessageType_MoneroGetAddress": 540,
+ "MessageType_MoneroAddress": 541,
+ "MessageType_MoneroGetWatchKey": 542,
+ "MessageType_MoneroWatchKey": 543,
+ "MessageType_DebugMoneroDiagRequest": 546,
+ "MessageType_DebugMoneroDiagAck": 547,
+ "MessageType_MoneroGetTxKeyRequest": 550,
+ "MessageType_MoneroGetTxKeyAck": 551,
+ "MessageType_MoneroLiveRefreshStartRequest": 552,
+ "MessageType_MoneroLiveRefreshStartAck": 553,
+ "MessageType_MoneroLiveRefreshStepRequest": 554,
+ "MessageType_MoneroLiveRefreshStepAck": 555,
+ "MessageType_MoneroLiveRefreshFinalRequest": 556,
+ "MessageType_MoneroLiveRefreshFinalAck": 557,
+ "MessageType_EosGetPublicKey": 600,
+ "MessageType_EosPublicKey": 601,
+ "MessageType_EosSignTx": 602,
+ "MessageType_EosTxActionRequest": 603,
+ "MessageType_EosTxActionAck": 604,
+ "MessageType_EosSignedTx": 605,
+ "MessageType_BinanceGetAddress": 700,
+ "MessageType_BinanceAddress": 701,
+ "MessageType_BinanceGetPublicKey": 702,
+ "MessageType_BinancePublicKey": 703,
+ "MessageType_BinanceSignTx": 704,
+ "MessageType_BinanceTxRequest": 705,
+ "MessageType_BinanceTransferMsg": 706,
+ "MessageType_BinanceOrderMsg": 707,
+ "MessageType_BinanceCancelMsg": 708,
+ "MessageType_BinanceSignedTx": 709,
+}
+
+func (x MessageType) Enum() *MessageType {
+ p := new(MessageType)
+ *p = x
+ return p
+}
+
+func (x MessageType) String() string {
+ return proto.EnumName(MessageType_name, int32(x))
+}
+
+func (x *MessageType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MessageType_value, data, "MessageType")
+ if err != nil {
+ return err
+ }
+ *x = MessageType(value)
+ return nil
+}
+
+func (MessageType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_4dc296cbfe5ffcd5, []int{0}
+}
+
+var E_WireIn = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50002,
+ Name: "hw.trezor.messages.wire_in",
+ Tag: "varint,50002,opt,name=wire_in",
+ Filename: "messages.proto",
+}
+
+var E_WireOut = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50003,
+ Name: "hw.trezor.messages.wire_out",
+ Tag: "varint,50003,opt,name=wire_out",
+ Filename: "messages.proto",
+}
+
+var E_WireDebugIn = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50004,
+ Name: "hw.trezor.messages.wire_debug_in",
+ Tag: "varint,50004,opt,name=wire_debug_in",
+ Filename: "messages.proto",
+}
+
+var E_WireDebugOut = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50005,
+ Name: "hw.trezor.messages.wire_debug_out",
+ Tag: "varint,50005,opt,name=wire_debug_out",
+ Filename: "messages.proto",
+}
+
+var E_WireTiny = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50006,
+ Name: "hw.trezor.messages.wire_tiny",
+ Tag: "varint,50006,opt,name=wire_tiny",
+ Filename: "messages.proto",
+}
+
+var E_WireBootloader = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50007,
+ Name: "hw.trezor.messages.wire_bootloader",
+ Tag: "varint,50007,opt,name=wire_bootloader",
+ Filename: "messages.proto",
+}
+
+var E_WireNoFsm = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 50008,
+ Name: "hw.trezor.messages.wire_no_fsm",
+ Tag: "varint,50008,opt,name=wire_no_fsm",
+ Filename: "messages.proto",
+}
+
+func init() {
+ proto.RegisterEnum("hw.trezor.messages.MessageType", MessageType_name, MessageType_value)
+ proto.RegisterExtension(E_WireIn)
+ proto.RegisterExtension(E_WireOut)
+ proto.RegisterExtension(E_WireDebugIn)
+ proto.RegisterExtension(E_WireDebugOut)
+ proto.RegisterExtension(E_WireTiny)
+ proto.RegisterExtension(E_WireBootloader)
+ proto.RegisterExtension(E_WireNoFsm)
+}
+
+func init() { proto.RegisterFile("messages.proto", fileDescriptor_4dc296cbfe5ffcd5) }
+
+var fileDescriptor_4dc296cbfe5ffcd5 = []byte{
+ // 2430 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x9a, 0xd9, 0x73, 0x1c, 0xc5,
+ 0x1d, 0xc7, 0xb3, 0xab, 0x11, 0x88, 0xf6, 0x41, 0x23, 0xb0, 0x2d, 0xaf, 0x2f, 0xf9, 0xc0, 0x96,
+ 0x2f, 0xd9, 0x10, 0x0c, 0x44, 0x38, 0x60, 0x69, 0xb5, 0x12, 0x8a, 0xb5, 0x5a, 0x97, 0x76, 0xb1,
+ 0x1f, 0x5d, 0xa3, 0x9d, 0xd6, 0x6e, 0x97, 0x67, 0x67, 0x86, 0x9e, 0x1e, 0x49, 0xeb, 0xa7, 0x9c,
+ 0x3c, 0x13, 0x48, 0xc0, 0xb9, 0xa9, 0xa4, 0x2a, 0x21, 0x57, 0x85, 0x1c, 0x4e, 0x25, 0x55, 0x39,
+ 0x08, 0x24, 0x2f, 0xc9, 0x43, 0x52, 0x9c, 0x86, 0x40, 0xee, 0x90, 0xe4, 0x0f, 0xc8, 0xc5, 0x91,
+ 0xa4, 0x7a, 0xa6, 0xbb, 0xe7, 0xd8, 0xdf, 0xae, 0x36, 0x6f, 0x58, 0xf3, 0xf9, 0x7d, 0x7f, 0x47,
+ 0xff, 0xfa, 0x37, 0xdd, 0xb3, 0xa0, 0xcd, 0x2d, 0xe2, 0xfb, 0x66, 0x83, 0xf8, 0xe3, 0x1e, 0x73,
+ 0xb9, 0x3b, 0x3c, 0xdc, 0x5c, 0x1d, 0xe7, 0x8c, 0x5c, 0x76, 0xd9, 0xb8, 0x7a, 0x52, 0x18, 0x6d,
+ 0xb8, 0x6e, 0xc3, 0x26, 0x27, 0x42, 0x62, 0x29, 0x58, 0x3e, 0x61, 0x11, 0xbf, 0xce, 0xa8, 0xc7,
+ 0x5d, 0x16, 0x59, 0x1d, 0xf9, 0xfe, 0x7d, 0x68, 0x43, 0x39, 0xc2, 0x6b, 0x6d, 0x8f, 0x0c, 0x1f,
+ 0x40, 0x5b, 0x13, 0xff, 0xbc, 0x38, 0xe7, 0x50, 0x4e, 0x4d, 0x9b, 0x5e, 0x26, 0xf8, 0x5d, 0x85,
+ 0xa1, 0x87, 0xaf, 0x8e, 0xe4, 0x9e, 0xba, 0x3a, 0x92, 0x1b, 0x2e, 0x20, 0x9c, 0xa4, 0xce, 0x51,
+ 0xa7, 0x81, 0x73, 0x05, 0x43, 0x3c, 0x1f, 0xde, 0x85, 0x6e, 0x4e, 0x3e, 0xab, 0x06, 0xf5, 0x3a,
+ 0xf1, 0x7d, 0x9c, 0x2f, 0x18, 0x57, 0x80, 0xc7, 0x33, 0x26, 0xb5, 0x03, 0x46, 0xf0, 0x80, 0x7c,
+ 0xbc, 0x07, 0x6d, 0x49, 0x3e, 0x2e, 0x36, 0x4d, 0xa7, 0x41, 0xce, 0x51, 0x07, 0x1b, 0x52, 0x7e,
+ 0x34, 0x1d, 0xe0, 0x05, 0xea, 0x91, 0x69, 0xb2, 0x42, 0xeb, 0x04, 0x0f, 0xc2, 0xc4, 0x2c, 0xe1,
+ 0x25, 0x87, 0x33, 0xd7, 0x6b, 0xe3, 0x1b, 0xe0, 0x10, 0xd5, 0x63, 0x24, 0x63, 0xc8, 0x08, 0xcc,
+ 0xbb, 0xa6, 0x25, 0x5d, 0x6c, 0x92, 0x02, 0x7b, 0xd1, 0xb6, 0x24, 0xb1, 0x48, 0x7c, 0xc2, 0x25,
+ 0xb2, 0x59, 0x22, 0xbb, 0xd1, 0x2d, 0xa9, 0x3c, 0x89, 0xc9, 0x03, 0x46, 0x7c, 0x7c, 0x93, 0x74,
+ 0x72, 0x10, 0xed, 0xcc, 0x94, 0xb0, 0x6c, 0x72, 0x46, 0xd7, 0x16, 0xc9, 0x83, 0x01, 0xf1, 0x39,
+ 0x1e, 0x96, 0xdc, 0x11, 0x34, 0x02, 0x72, 0x93, 0xf5, 0x4b, 0xf8, 0xe6, 0xc2, 0x46, 0xb5, 0x24,
+ 0x4f, 0x47, 0x81, 0x0f, 0xa7, 0x8a, 0x67, 0x3a, 0x75, 0x62, 0xe3, 0x5b, 0x12, 0x0b, 0xb7, 0x2f,
+ 0xad, 0x56, 0xb4, 0x89, 0xc9, 0xaa, 0xc4, 0xf7, 0xa9, 0xeb, 0xe0, 0x11, 0x19, 0xf9, 0x7e, 0xb4,
+ 0x3d, 0xc9, 0x4c, 0x7a, 0x9e, 0xdd, 0xae, 0x12, 0xce, 0xa9, 0xd3, 0xf0, 0xf1, 0x76, 0x18, 0x9a,
+ 0x0a, 0x38, 0x77, 0x1d, 0x15, 0x7b, 0x41, 0xc6, 0x7e, 0x28, 0xbd, 0x98, 0x11, 0x24, 0x02, 0xdf,
+ 0xd1, 0x11, 0xf8, 0xd6, 0x0e, 0x97, 0x33, 0xb6, 0xd9, 0xf0, 0xf1, 0x4e, 0xe9, 0x2f, 0x13, 0xf8,
+ 0x94, 0x59, 0xbf, 0x14, 0x78, 0xb2, 0xe4, 0xfb, 0x24, 0x73, 0x00, 0x15, 0x80, 0x65, 0x55, 0x41,
+ 0xed, 0x87, 0x57, 0x57, 0x52, 0x22, 0xaa, 0x03, 0x52, 0xe7, 0x10, 0xda, 0x95, 0x2a, 0xb9, 0xe9,
+ 0xfb, 0x5e, 0x93, 0x99, 0x3e, 0x51, 0x52, 0x87, 0xa5, 0xd4, 0xd1, 0x74, 0x11, 0x62, 0x50, 0xa8,
+ 0x1d, 0xc9, 0xe4, 0x78, 0x0c, 0xed, 0x83, 0xe1, 0x2a, 0x37, 0xb9, 0x96, 0x2e, 0x4b, 0xe9, 0x93,
+ 0x68, 0x77, 0x0f, 0x5a, 0xe8, 0x2f, 0x64, 0xf4, 0x33, 0xd9, 0x2f, 0x92, 0xba, 0xbb, 0x42, 0x58,
+ 0x5b, 0xd6, 0xe8, 0x38, 0xdc, 0xb9, 0x17, 0x5c, 0x66, 0x29, 0xd7, 0xe3, 0xf0, 0x0e, 0x15, 0x88,
+ 0xf0, 0x77, 0x02, 0x56, 0x98, 0x25, 0x5c, 0xf7, 0xf6, 0x5d, 0x70, 0x73, 0x54, 0x09, 0x7f, 0xe0,
+ 0xf6, 0x99, 0xa2, 0x1b, 0x38, 0x9c, 0x30, 0x7c, 0x9f, 0xae, 0x72, 0x0a, 0x9a, 0xa1, 0xac, 0xb5,
+ 0x6a, 0x32, 0x52, 0x12, 0x49, 0xe2, 0xeb, 0xa2, 0x9e, 0xfd, 0x9e, 0x00, 0xc7, 0xd2, 0x89, 0x29,
+ 0xf0, 0x01, 0xcf, 0x76, 0x4d, 0x0b, 0x5f, 0x9f, 0x20, 0x0f, 0xa3, 0x1d, 0x10, 0xa9, 0x12, 0x1c,
+ 0x2a, 0x0c, 0x5d, 0x51, 0xe8, 0xbe, 0xf4, 0xf6, 0xac, 0x12, 0x7b, 0xb9, 0x26, 0x98, 0xd1, 0x84,
+ 0x5c, 0xa6, 0xe7, 0x66, 0x09, 0x3f, 0x17, 0x2c, 0xd9, 0xb4, 0x7e, 0x96, 0xb4, 0xf1, 0x06, 0x99,
+ 0x45, 0x66, 0x5e, 0xc5, 0xc0, 0x46, 0x59, 0xcd, 0x9d, 0xe9, 0x3d, 0x59, 0xa5, 0x0d, 0xa7, 0xb6,
+ 0x86, 0x6f, 0x84, 0xcd, 0x6b, 0x7a, 0xfb, 0x6f, 0x91, 0xe6, 0x3b, 0xd0, 0x4d, 0x69, 0x40, 0x2c,
+ 0xc5, 0xd6, 0xae, 0x93, 0x6e, 0xd2, 0xb2, 0x98, 0x98, 0xb6, 0xbb, 0xe0, 0x49, 0xa7, 0x1e, 0xef,
+ 0x96, 0xea, 0x99, 0xb5, 0x14, 0xc1, 0xc9, 0x7f, 0xe3, 0x83, 0xf0, 0x5a, 0x9e, 0x27, 0x8c, 0x2e,
+ 0xb7, 0x15, 0x74, 0x48, 0x42, 0x99, 0x61, 0x26, 0xff, 0x5b, 0xc8, 0x85, 0x9d, 0x81, 0xc7, 0xa4,
+ 0xbf, 0x4c, 0x8f, 0x16, 0xa9, 0xd7, 0x24, 0xec, 0x2c, 0x69, 0x9f, 0x37, 0xed, 0x80, 0xe0, 0x6d,
+ 0xb0, 0x5a, 0x44, 0x11, 0x4b, 0x73, 0x27, 0xa5, 0x5a, 0x66, 0x7d, 0x84, 0xbb, 0x39, 0x8b, 0x38,
+ 0x9c, 0xf2, 0x36, 0x3e, 0x05, 0xcf, 0x04, 0xc1, 0x10, 0x4b, 0x53, 0x77, 0xea, 0x41, 0xb5, 0x2b,
+ 0xfb, 0xca, 0x28, 0x4e, 0xdf, 0x2f, 0x07, 0xa3, 0x58, 0xcd, 0xf7, 0x76, 0x19, 0x31, 0x69, 0xea,
+ 0x5e, 0x78, 0xc4, 0x14, 0x5d, 0x9f, 0x16, 0xdd, 0x56, 0x8b, 0x72, 0x3c, 0x0b, 0xeb, 0xc4, 0x44,
+ 0x8b, 0x38, 0x1c, 0xdf, 0x2f, 0x75, 0x32, 0xef, 0x10, 0x41, 0x89, 0x04, 0xf0, 0x1c, 0xbc, 0x36,
+ 0xea, 0x79, 0x54, 0xf3, 0xf7, 0x49, 0x91, 0x13, 0xe9, 0xdc, 0xa6, 0xc9, 0x52, 0xd0, 0x98, 0xa7,
+ 0xce, 0xa5, 0x69, 0x52, 0xa7, 0xe1, 0xdc, 0xb7, 0x0a, 0x1b, 0x9f, 0x48, 0x0e, 0x92, 0xa3, 0x5d,
+ 0x0c, 0x66, 0x09, 0x0f, 0x87, 0x0f, 0x26, 0x85, 0x21, 0x65, 0x90, 0x4d, 0x44, 0xc3, 0x11, 0xb9,
+ 0x5c, 0x30, 0x9e, 0x04, 0x02, 0x4d, 0x50, 0xae, 0x87, 0x1b, 0x05, 0xe3, 0x09, 0x60, 0x39, 0x35,
+ 0x34, 0xef, 0x36, 0x70, 0x53, 0x0a, 0x1d, 0x46, 0x7b, 0x40, 0xa6, 0x4c, 0x5a, 0x2e, 0x6b, 0x2f,
+ 0x12, 0xd3, 0xc2, 0x8e, 0x94, 0xbb, 0x35, 0x3d, 0x0c, 0x32, 0x28, 0x76, 0xa5, 0xe2, 0x11, 0x34,
+ 0xda, 0x03, 0xbb, 0xc0, 0x28, 0x27, 0xd8, 0x93, 0x92, 0xdd, 0xbc, 0xcf, 0xd8, 0xa6, 0xdf, 0x8c,
+ 0x06, 0xd7, 0x83, 0x12, 0x3d, 0x9a, 0x96, 0x2d, 0x71, 0xd1, 0xc2, 0x41, 0x2b, 0x35, 0x43, 0x9e,
+ 0x19, 0x90, 0xeb, 0x38, 0x96, 0xae, 0xb8, 0x82, 0x63, 0xf2, 0x59, 0x75, 0x3c, 0x1a, 0x4b, 0xbf,
+ 0x16, 0x12, 0xb2, 0x6a, 0x6b, 0xdf, 0x2d, 0x35, 0x33, 0xe9, 0x2b, 0x52, 0x61, 0xef, 0x81, 0x77,
+ 0xa4, 0xc2, 0xe4, 0x98, 0x9a, 0x80, 0xdf, 0x88, 0x8a, 0x8a, 0xc7, 0xd5, 0x3d, 0x52, 0x2e, 0xb3,
+ 0xd0, 0x31, 0x28, 0xc6, 0xd6, 0x69, 0xa9, 0x96, 0x29, 0x63, 0xd2, 0xa7, 0x1a, 0x2c, 0x67, 0x24,
+ 0x7a, 0x14, 0xed, 0x85, 0xd0, 0xf4, 0x14, 0x9a, 0x94, 0xf0, 0x38, 0x3a, 0x00, 0xc1, 0x1d, 0xd3,
+ 0x68, 0x0a, 0x0e, 0x76, 0xa1, 0x54, 0x4e, 0xd4, 0xb1, 0x08, 0xcf, 0xd8, 0x85, 0x52, 0x59, 0x11,
+ 0xd3, 0xf0, 0x91, 0x75, 0xa1, 0x54, 0x96, 0xd5, 0x2b, 0xc1, 0x6f, 0x4c, 0x09, 0x10, 0xab, 0xb6,
+ 0x86, 0x67, 0xe0, 0x01, 0xb4, 0x50, 0x2a, 0x4f, 0x93, 0x3a, 0x6b, 0x7b, 0x5c, 0xe5, 0x78, 0x16,
+ 0xae, 0x5d, 0x0c, 0x12, 0x4b, 0xa1, 0xf3, 0xf0, 0xd2, 0xce, 0x53, 0xff, 0x52, 0x22, 0x3f, 0x06,
+ 0x07, 0x27, 0x28, 0x85, 0xf8, 0x5d, 0xce, 0xc3, 0xd4, 0xbf, 0x24, 0x33, 0xe4, 0xf0, 0xe9, 0x4c,
+ 0x11, 0x61, 0x8a, 0x81, 0x54, 0xc9, 0x34, 0xa4, 0x62, 0x54, 0xd4, 0x2b, 0x52, 0x2a, 0xb3, 0x1f,
+ 0x05, 0xd6, 0xb1, 0x80, 0xab, 0x70, 0xd5, 0x04, 0x9b, 0xee, 0x8c, 0x35, 0xf8, 0x8d, 0x22, 0x4b,
+ 0x11, 0xef, 0xaf, 0x36, 0x3c, 0x50, 0x05, 0x17, 0x43, 0x97, 0xf5, 0xc9, 0x3d, 0x95, 0x48, 0x8d,
+ 0x5c, 0x76, 0xfd, 0x44, 0x61, 0x1f, 0xcb, 0x69, 0xb1, 0x91, 0x0e, 0x4e, 0x41, 0x8f, 0xe7, 0xf4,
+ 0x3b, 0x6c, 0x5b, 0x07, 0x24, 0x8b, 0x7b, 0x25, 0xa7, 0x5f, 0x16, 0xdb, 0x41, 0x26, 0x2c, 0xef,
+ 0x27, 0x72, 0x7a, 0x34, 0xec, 0x82, 0xc2, 0x8a, 0xe3, 0xff, 0x64, 0x4e, 0x8f, 0x86, 0x42, 0x07,
+ 0x19, 0x63, 0x9f, 0xca, 0xe9, 0xfe, 0x49, 0x9f, 0xe2, 0x38, 0xb1, 0x6d, 0x93, 0xc9, 0xe0, 0x7e,
+ 0x9e, 0xd3, 0x0d, 0xb9, 0x1b, 0xa0, 0x6a, 0x6b, 0x15, 0x4f, 0xcd, 0x86, 0x5f, 0x74, 0x89, 0x50,
+ 0xa2, 0x89, 0xd2, 0xfd, 0xb2, 0x4b, 0x84, 0x92, 0x54, 0xd8, 0xaf, 0x94, 0xe0, 0xf1, 0xf4, 0x91,
+ 0x5a, 0x62, 0x45, 0x46, 0xc2, 0x23, 0x72, 0x5d, 0x1c, 0x38, 0x2b, 0x1e, 0x7e, 0x2e, 0xa7, 0xa7,
+ 0xd8, 0x4e, 0x00, 0x3f, 0x67, 0xb6, 0xc5, 0x4b, 0xb7, 0xe2, 0xe1, 0xe7, 0x73, 0x7a, 0xea, 0x8c,
+ 0x82, 0x20, 0x6f, 0xc6, 0xf0, 0x0b, 0xbd, 0xe1, 0xb2, 0xe9, 0x98, 0x0d, 0x52, 0x59, 0x5e, 0x26,
+ 0xac, 0xe2, 0xe1, 0x17, 0x15, 0x7c, 0x3b, 0x3a, 0xd4, 0x35, 0x62, 0x71, 0xc6, 0xa7, 0x2b, 0xda,
+ 0xe6, 0xa5, 0x9c, 0xde, 0x11, 0x7b, 0xa0, 0x75, 0x20, 0xbc, 0xe2, 0x71, 0xea, 0x3a, 0x7e, 0xc5,
+ 0xc3, 0x2f, 0xf7, 0x0e, 0x26, 0xba, 0x45, 0xd7, 0x58, 0xe0, 0x8b, 0xc8, 0xaf, 0xf5, 0x16, 0x9e,
+ 0xb4, 0x6d, 0x77, 0x55, 0xb1, 0xaf, 0x28, 0xf6, 0x58, 0x7a, 0x10, 0x2b, 0x36, 0x2a, 0x72, 0x99,
+ 0xb0, 0x06, 0xa9, 0x78, 0xf8, 0xd5, 0xde, 0xca, 0x51, 0x4d, 0xa6, 0x4d, 0x6e, 0x56, 0x3c, 0xfc,
+ 0x5a, 0x6f, 0xe5, 0xa9, 0xa0, 0xe5, 0x55, 0x45, 0x03, 0x39, 0x75, 0xa1, 0xfc, 0x7a, 0x4e, 0xef,
+ 0xe4, 0x1d, 0x5d, 0x9a, 0x32, 0xdc, 0x0d, 0x6f, 0xe4, 0xf4, 0xb4, 0x49, 0xf7, 0x38, 0x73, 0x9d,
+ 0x44, 0xa3, 0xbd, 0x99, 0xd3, 0x83, 0x6b, 0x5b, 0x16, 0x53, 0xcc, 0x5b, 0x39, 0x7d, 0x48, 0xde,
+ 0x9a, 0x65, 0xe4, 0x26, 0x78, 0xbb, 0xdb, 0x56, 0x97, 0x48, 0x18, 0xd2, 0x3b, 0x5d, 0xf6, 0x53,
+ 0xd1, 0x64, 0x96, 0xe9, 0xb8, 0x52, 0xea, 0x1b, 0x79, 0xb8, 0x49, 0x25, 0x15, 0xbf, 0x69, 0x9f,
+ 0xca, 0xeb, 0x0f, 0x03, 0x7b, 0x00, 0x30, 0xb5, 0xe3, 0xbf, 0xd9, 0x5b, 0x34, 0x06, 0xbf, 0x95,
+ 0x87, 0xb7, 0x68, 0x2c, 0xaa, 0xaa, 0xf2, 0xed, 0x3c, 0xbc, 0x45, 0x25, 0xa9, 0xb0, 0xef, 0xe4,
+ 0xf5, 0x3b, 0x76, 0x04, 0x4c, 0x47, 0x9c, 0x07, 0xae, 0xe6, 0xe1, 0x45, 0x4d, 0x54, 0x26, 0xac,
+ 0xe0, 0x77, 0x95, 0x58, 0x66, 0xd6, 0x54, 0x1c, 0xee, 0xda, 0x6e, 0xa3, 0x9d, 0x08, 0xef, 0x37,
+ 0x5d, 0x24, 0x15, 0xaa, 0xb8, 0xdf, 0xe6, 0xf5, 0x15, 0x7e, 0xb4, 0x8b, 0x64, 0x5c, 0x9d, 0xdf,
+ 0xe5, 0xe1, 0x73, 0x9a, 0x82, 0x63, 0xf2, 0xf7, 0xeb, 0xc8, 0x86, 0x8b, 0xcd, 0x4c, 0xc7, 0x5f,
+ 0x26, 0x0c, 0xff, 0x41, 0xc9, 0x66, 0xc6, 0x58, 0x12, 0x26, 0x96, 0xc6, 0xff, 0xa8, 0xb4, 0xc7,
+ 0xd1, 0xfe, 0x6e, 0xf8, 0x05, 0xca, 0x9b, 0x16, 0x33, 0x57, 0x2b, 0x4e, 0x03, 0xff, 0x49, 0xc9,
+ 0x9f, 0x44, 0xb7, 0x76, 0x97, 0x4f, 0x5a, 0xfc, 0x39, 0xaf, 0x3f, 0x3e, 0x74, 0xb5, 0xa8, 0x38,
+ 0x7c, 0xce, 0x5a, 0x24, 0x0d, 0xea, 0x8b, 0xbb, 0xfc, 0x1b, 0x79, 0x78, 0xae, 0xa5, 0x7d, 0xa4,
+ 0x6d, 0xfe, 0xa2, 0xbc, 0x9c, 0x42, 0x47, 0x7a, 0x7a, 0x99, 0xb4, 0xac, 0x49, 0xce, 0x19, 0x5d,
+ 0x0a, 0x38, 0xf1, 0xf1, 0x5f, 0x95, 0xab, 0xbb, 0xd0, 0xb1, 0x75, 0x5c, 0xa5, 0x0d, 0xff, 0x96,
+ 0xd7, 0xa7, 0x85, 0xd4, 0x26, 0x58, 0xa4, 0x9e, 0x67, 0x93, 0x44, 0xef, 0x3c, 0x3c, 0x00, 0xbf,
+ 0x6f, 0x23, 0x50, 0x51, 0x1f, 0x1d, 0x80, 0x3b, 0x3b, 0xa2, 0xe4, 0x6e, 0x7e, 0x64, 0x00, 0xde,
+ 0x25, 0x31, 0x14, 0x36, 0xf6, 0xa3, 0x0a, 0x7b, 0x37, 0x1a, 0x4b, 0xdd, 0x9f, 0x5d, 0x87, 0x30,
+ 0x37, 0x5c, 0x79, 0xb3, 0x2e, 0x66, 0xfc, 0x9c, 0x43, 0xb9, 0x1a, 0x00, 0x7f, 0x1f, 0xd0, 0x17,
+ 0xbb, 0x03, 0xeb, 0x1a, 0x89, 0x6d, 0xf6, 0x0f, 0x65, 0x90, 0xa9, 0x5c, 0x87, 0x41, 0x95, 0xf0,
+ 0x39, 0xc7, 0x0b, 0xb4, 0xa7, 0x7f, 0x2a, 0xc3, 0xf5, 0xc2, 0x53, 0x86, 0xc2, 0xdb, 0xbf, 0x94,
+ 0xd1, 0x19, 0x74, 0x6a, 0x9d, 0xf0, 0xbc, 0x80, 0xfb, 0xe7, 0x08, 0x6b, 0x05, 0xdc, 0x14, 0x7f,
+ 0x50, 0x6e, 0xff, 0xad, 0x14, 0x4e, 0xa3, 0xdb, 0xfe, 0x3f, 0x05, 0xe1, 0xff, 0x4d, 0x65, 0x7d,
+ 0x37, 0x3a, 0xbe, 0xbe, 0xf5, 0x79, 0xea, 0x50, 0xe5, 0xf7, 0x2d, 0x65, 0x79, 0x07, 0x3a, 0xdc,
+ 0x9f, 0xa5, 0xf0, 0xf7, 0xb6, 0xb2, 0xba, 0x07, 0x9d, 0xec, 0x69, 0x35, 0x69, 0xdb, 0x51, 0xc0,
+ 0x55, 0xa2, 0x2b, 0xfc, 0x4e, 0xbf, 0x4b, 0x93, 0x34, 0x16, 0x5e, 0xff, 0xd3, 0x6f, 0x96, 0xe2,
+ 0x98, 0x10, 0xf0, 0xc4, 0xa2, 0xfe, 0xb7, 0xdf, 0x2c, 0xb5, 0xa5, 0xf0, 0xf7, 0x7e, 0xa3, 0x4f,
+ 0x7f, 0x93, 0xb6, 0x5d, 0x09, 0x78, 0x22, 0xc5, 0x0f, 0x18, 0x7d, 0xfa, 0xd3, 0x96, 0xc2, 0xdf,
+ 0x07, 0xfb, 0xf5, 0x17, 0x7e, 0xf4, 0x49, 0x36, 0xed, 0x87, 0xfa, 0xf5, 0xa7, 0x2d, 0x85, 0xbf,
+ 0x0f, 0xf7, 0x6b, 0x35, 0x43, 0x1d, 0xd3, 0x56, 0xbe, 0x3e, 0x62, 0xc0, 0x03, 0x13, 0xb6, 0x12,
+ 0x7e, 0x1e, 0x52, 0x16, 0x77, 0xa2, 0xa3, 0x9d, 0x16, 0x67, 0x49, 0x7b, 0xae, 0x65, 0x36, 0x48,
+ 0x69, 0xcd, 0x73, 0x19, 0x4f, 0x6e, 0xfa, 0x47, 0x94, 0x5d, 0x66, 0xd0, 0x76, 0xb3, 0x13, 0xbe,
+ 0x1e, 0xed, 0x99, 0x93, 0xb2, 0xa9, 0xb6, 0x9d, 0x7a, 0x95, 0x13, 0x7d, 0x5a, 0xff, 0x58, 0xcf,
+ 0x9c, 0xb2, 0x56, 0xc2, 0xcf, 0xc7, 0x0d, 0x78, 0xa0, 0x77, 0x5a, 0xa4, 0x8a, 0xf7, 0x98, 0x32,
+ 0xbb, 0x0d, 0x1d, 0xec, 0xc3, 0x4c, 0x78, 0x7a, 0xdc, 0x80, 0x47, 0x79, 0x64, 0x92, 0x18, 0xe5,
+ 0x9f, 0x36, 0xe0, 0x51, 0x1e, 0x81, 0x8a, 0xfa, 0x8c, 0x01, 0x9f, 0x7a, 0xb4, 0xdc, 0x05, 0x93,
+ 0xd7, 0x9b, 0xe2, 0xbd, 0xfe, 0x59, 0x03, 0x9e, 0xe7, 0x11, 0xa9, 0xb1, 0xcf, 0x19, 0xf0, 0xc5,
+ 0x24, 0xfc, 0x50, 0x14, 0xb1, 0xd3, 0xd4, 0x6c, 0xa8, 0x0a, 0x7c, 0xde, 0x80, 0xef, 0x50, 0x19,
+ 0x5c, 0x64, 0xfe, 0x05, 0xa5, 0x9c, 0x39, 0x2d, 0xeb, 0x50, 0x6b, 0x6b, 0x67, 0x89, 0xfe, 0xa9,
+ 0xe3, 0x8b, 0x06, 0x7c, 0x60, 0x49, 0xd3, 0x42, 0xf7, 0x4b, 0x3d, 0x7b, 0x64, 0x9e, 0xae, 0x90,
+ 0x45, 0xb2, 0xcc, 0x88, 0xdf, 0xac, 0x72, 0x93, 0xe9, 0x6e, 0x7c, 0xd2, 0x80, 0x8f, 0x16, 0xb0,
+ 0x95, 0xf0, 0xf3, 0x65, 0xa3, 0xd7, 0xab, 0x24, 0x65, 0x11, 0xb7, 0xe2, 0x57, 0x94, 0x1b, 0xf0,
+ 0x4d, 0x97, 0x31, 0x12, 0x5e, 0xbe, 0xda, 0x6f, 0x36, 0xa9, 0x46, 0xfc, 0x5a, 0xbf, 0xd9, 0xe8,
+ 0x3e, 0xfc, 0xba, 0x01, 0x7f, 0x0a, 0x28, 0x65, 0x6e, 0xdc, 0xd7, 0x0c, 0xf8, 0x7e, 0x50, 0x4a,
+ 0xde, 0xb7, 0x5f, 0x31, 0xf4, 0x67, 0x96, 0x2d, 0x19, 0x48, 0x9e, 0x26, 0x5e, 0xed, 0xd2, 0x27,
+ 0x25, 0xd7, 0x17, 0x07, 0xe9, 0xe4, 0xbb, 0xf3, 0xd7, 0x06, 0x7c, 0xff, 0x49, 0xa0, 0x22, 0x81,
+ 0xd7, 0x0c, 0xf8, 0xfe, 0x53, 0x4a, 0x7c, 0x58, 0x78, 0xbd, 0xcb, 0xee, 0x98, 0xa2, 0x8e, 0xe9,
+ 0xd4, 0x93, 0x07, 0xa7, 0x1f, 0x0c, 0xc2, 0xbb, 0x43, 0x92, 0x0a, 0xfb, 0xe1, 0x20, 0x7c, 0x73,
+ 0x89, 0x05, 0xe3, 0xa2, 0xfc, 0x68, 0x10, 0xbe, 0xb9, 0x48, 0x36, 0x06, 0x7f, 0x3c, 0x08, 0xdf,
+ 0xae, 0x24, 0x28, 0x2b, 0xf8, 0x74, 0x6f, 0xb9, 0xf8, 0x76, 0xf5, 0x93, 0x41, 0xf8, 0xaa, 0xa1,
+ 0x40, 0x79, 0x18, 0x2f, 0xfb, 0x0d, 0xfc, 0xcc, 0x20, 0x7c, 0xd5, 0x90, 0x68, 0x85, 0x59, 0x11,
+ 0xf7, 0x6c, 0x6f, 0xdf, 0xd1, 0x8f, 0xb4, 0x02, 0xfc, 0x69, 0x6f, 0x41, 0xbd, 0x30, 0x3f, 0x93,
+ 0x31, 0x4e, 0x9c, 0x46, 0xd7, 0xaf, 0x52, 0x46, 0x2e, 0x52, 0x67, 0x78, 0xef, 0x78, 0xf4, 0x4b,
+ 0xff, 0xb8, 0xfa, 0xa5, 0x7f, 0xbc, 0xe4, 0x04, 0xad, 0xf0, 0xe7, 0x12, 0xf9, 0x95, 0x60, 0xe4,
+ 0xb9, 0x87, 0x06, 0x46, 0x73, 0x63, 0x43, 0x8b, 0xd7, 0x09, 0x9b, 0x39, 0x67, 0xe2, 0x5e, 0x34,
+ 0x14, 0x5a, 0xbb, 0x01, 0xef, 0xc7, 0xfc, 0x79, 0x69, 0x1e, 0xba, 0xac, 0x04, 0x7c, 0x62, 0x16,
+ 0x6d, 0x0a, 0xed, 0x2d, 0x31, 0xad, 0xfa, 0x8c, 0xe1, 0x05, 0x29, 0xb2, 0x41, 0x58, 0x86, 0x63,
+ 0x6e, 0xce, 0x99, 0x98, 0x43, 0x9b, 0x13, 0x42, 0x7d, 0x86, 0xf3, 0xa2, 0x54, 0xda, 0xa8, 0x95,
+ 0x44, 0x4c, 0x67, 0xd0, 0x0d, 0xa1, 0x14, 0xa7, 0x4e, 0xbb, 0x1f, 0x95, 0x97, 0xa4, 0x4a, 0x58,
+ 0x89, 0x1a, 0x75, 0xda, 0x13, 0xf3, 0xe8, 0xc6, 0x50, 0x61, 0xc9, 0x75, 0xb9, 0xed, 0x9a, 0x16,
+ 0x61, 0xfd, 0xe8, 0xbc, 0x2c, 0x75, 0xc2, 0x44, 0xa6, 0xb4, 0xe9, 0x44, 0x11, 0x85, 0x99, 0x5e,
+ 0x74, 0xdc, 0x8b, 0xcb, 0x7e, 0xab, 0x1f, 0xa5, 0x6b, 0x52, 0x29, 0xcc, 0x63, 0xc1, 0x9d, 0xf1,
+ 0x5b, 0x53, 0x77, 0xa0, 0xfd, 0x75, 0xb7, 0x35, 0xee, 0x9b, 0xdc, 0xf5, 0x9b, 0xd4, 0x36, 0x97,
+ 0x7c, 0xf5, 0xff, 0x79, 0xd8, 0x74, 0x49, 0x4b, 0x4d, 0x6d, 0xaa, 0x85, 0x7f, 0x94, 0x9d, 0xf3,
+ 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa3, 0x69, 0x67, 0x5d, 0x1f, 0x22, 0x00, 0x00,
+}
diff --git a/accounts/usbwallet/trezor/messages.proto b/accounts/usbwallet/trezor/messages.proto
new file mode 100644
index 000000000..3e0482e34
--- /dev/null
+++ b/accounts/usbwallet/trezor/messages.proto
@@ -0,0 +1,264 @@
+// This file originates from the SatoshiLabs Trezor `common` repository at:
+// https://github.com/trezor/trezor-common/blob/master/protob/messages.proto
+// dated 28.05.2019, commit 893fd219d4a01bcffa0cd9cfa631856371ec5aa9.
+
+syntax = "proto2";
+package hw.trezor.messages;
+
+/**
+ * Messages for TREZOR communication
+ */
+
+// Sugar for easier handling in Java
+option java_package = "com.satoshilabs.trezor.lib.protobuf";
+option java_outer_classname = "TrezorMessage";
+
+import "google/protobuf/descriptor.proto";
+
+/**
+ * Options for specifying message direction and type of wire (normal/debug)
+ */
+extend google.protobuf.EnumValueOptions {
+ optional bool wire_in = 50002; // message can be transmitted via wire from PC to TREZOR
+ optional bool wire_out = 50003; // message can be transmitted via wire from TREZOR to PC
+ optional bool wire_debug_in = 50004; // message can be transmitted via debug wire from PC to TREZOR
+ optional bool wire_debug_out = 50005; // message can be transmitted via debug wire from TREZOR to PC
+ optional bool wire_tiny = 50006; // message is handled by TREZOR when the USB stack is in tiny mode
+ optional bool wire_bootloader = 50007; // message is only handled by TREZOR Bootloader
+ optional bool wire_no_fsm = 50008; // message is not handled by TREZOR unless the USB stack is in tiny mode
+}
+
+/**
+ * Mapping between TREZOR wire identifier (uint) and a protobuf message
+ */
+enum MessageType {
+
+ // Management
+ MessageType_Initialize = 0 [(wire_in) = true, (wire_tiny) = true];
+ MessageType_Ping = 1 [(wire_in) = true];
+ MessageType_Success = 2 [(wire_out) = true];
+ MessageType_Failure = 3 [(wire_out) = true];
+ MessageType_ChangePin = 4 [(wire_in) = true];
+ MessageType_WipeDevice = 5 [(wire_in) = true];
+ MessageType_GetEntropy = 9 [(wire_in) = true];
+ MessageType_Entropy = 10 [(wire_out) = true];
+ MessageType_LoadDevice = 13 [(wire_in) = true];
+ MessageType_ResetDevice = 14 [(wire_in) = true];
+ MessageType_Features = 17 [(wire_out) = true];
+ MessageType_PinMatrixRequest = 18 [(wire_out) = true];
+ MessageType_PinMatrixAck = 19 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
+ MessageType_Cancel = 20 [(wire_in) = true, (wire_tiny) = true];
+ MessageType_ClearSession = 24 [(wire_in) = true];
+ MessageType_ApplySettings = 25 [(wire_in) = true];
+ MessageType_ButtonRequest = 26 [(wire_out) = true];
+ MessageType_ButtonAck = 27 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
+ MessageType_ApplyFlags = 28 [(wire_in) = true];
+ MessageType_BackupDevice = 34 [(wire_in) = true];
+ MessageType_EntropyRequest = 35 [(wire_out) = true];
+ MessageType_EntropyAck = 36 [(wire_in) = true];
+ MessageType_PassphraseRequest = 41 [(wire_out) = true];
+ MessageType_PassphraseAck = 42 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
+ MessageType_PassphraseStateRequest = 77 [(wire_out) = true];
+ MessageType_PassphraseStateAck = 78 [(wire_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
+ MessageType_RecoveryDevice = 45 [(wire_in) = true];
+ MessageType_WordRequest = 46 [(wire_out) = true];
+ MessageType_WordAck = 47 [(wire_in) = true];
+ MessageType_GetFeatures = 55 [(wire_in) = true];
+ MessageType_SetU2FCounter = 63 [(wire_in) = true];
+
+ // Bootloader
+ MessageType_FirmwareErase = 6 [(wire_in) = true, (wire_bootloader) = true];
+ MessageType_FirmwareUpload = 7 [(wire_in) = true, (wire_bootloader) = true];
+ MessageType_FirmwareRequest = 8 [(wire_out) = true, (wire_bootloader) = true];
+ MessageType_SelfTest = 32 [(wire_in) = true, (wire_bootloader) = true];
+
+ // Bitcoin
+ MessageType_GetPublicKey = 11 [(wire_in) = true];
+ MessageType_PublicKey = 12 [(wire_out) = true];
+ MessageType_SignTx = 15 [(wire_in) = true];
+ MessageType_TxRequest = 21 [(wire_out) = true];
+ MessageType_TxAck = 22 [(wire_in) = true];
+ MessageType_GetAddress = 29 [(wire_in) = true];
+ MessageType_Address = 30 [(wire_out) = true];
+ MessageType_SignMessage = 38 [(wire_in) = true];
+ MessageType_VerifyMessage = 39 [(wire_in) = true];
+ MessageType_MessageSignature = 40 [(wire_out) = true];
+
+ // Crypto
+ MessageType_CipherKeyValue = 23 [(wire_in) = true];
+ MessageType_CipheredKeyValue = 48 [(wire_out) = true];
+ MessageType_SignIdentity = 53 [(wire_in) = true];
+ MessageType_SignedIdentity = 54 [(wire_out) = true];
+ MessageType_GetECDHSessionKey = 61 [(wire_in) = true];
+ MessageType_ECDHSessionKey = 62 [(wire_out) = true];
+ MessageType_CosiCommit = 71 [(wire_in) = true];
+ MessageType_CosiCommitment = 72 [(wire_out) = true];
+ MessageType_CosiSign = 73 [(wire_in) = true];
+ MessageType_CosiSignature = 74 [(wire_out) = true];
+
+ // Debug
+ MessageType_DebugLinkDecision = 100 [(wire_debug_in) = true, (wire_tiny) = true, (wire_no_fsm) = true];
+ MessageType_DebugLinkGetState = 101 [(wire_debug_in) = true, (wire_tiny) = true];
+ MessageType_DebugLinkState = 102 [(wire_debug_out) = true];
+ MessageType_DebugLinkStop = 103 [(wire_debug_in) = true];
+ MessageType_DebugLinkLog = 104 [(wire_debug_out) = true];
+ MessageType_DebugLinkMemoryRead = 110 [(wire_debug_in) = true];
+ MessageType_DebugLinkMemory = 111 [(wire_debug_out) = true];
+ MessageType_DebugLinkMemoryWrite = 112 [(wire_debug_in) = true];
+ MessageType_DebugLinkFlashErase = 113 [(wire_debug_in) = true];
+
+ // Ethereum
+ MessageType_EthereumGetPublicKey = 450 [(wire_in) = true];
+ MessageType_EthereumPublicKey = 451 [(wire_out) = true];
+ MessageType_EthereumGetAddress = 56 [(wire_in) = true];
+ MessageType_EthereumAddress = 57 [(wire_out) = true];
+ MessageType_EthereumSignTx = 58 [(wire_in) = true];
+ MessageType_EthereumTxRequest = 59 [(wire_out) = true];
+ MessageType_EthereumTxAck = 60 [(wire_in) = true];
+ MessageType_EthereumSignMessage = 64 [(wire_in) = true];
+ MessageType_EthereumVerifyMessage = 65 [(wire_in) = true];
+ MessageType_EthereumMessageSignature = 66 [(wire_out) = true];
+
+ // NEM
+ MessageType_NEMGetAddress = 67 [(wire_in) = true];
+ MessageType_NEMAddress = 68 [(wire_out) = true];
+ MessageType_NEMSignTx = 69 [(wire_in) = true];
+ MessageType_NEMSignedTx = 70 [(wire_out) = true];
+ MessageType_NEMDecryptMessage = 75 [(wire_in) = true];
+ MessageType_NEMDecryptedMessage = 76 [(wire_out) = true];
+
+ // Lisk
+ MessageType_LiskGetAddress = 114 [(wire_in) = true];
+ MessageType_LiskAddress = 115 [(wire_out) = true];
+ MessageType_LiskSignTx = 116 [(wire_in) = true];
+ MessageType_LiskSignedTx = 117 [(wire_out) = true];
+ MessageType_LiskSignMessage = 118 [(wire_in) = true];
+ MessageType_LiskMessageSignature = 119 [(wire_out) = true];
+ MessageType_LiskVerifyMessage = 120 [(wire_in) = true];
+ MessageType_LiskGetPublicKey = 121 [(wire_in) = true];
+ MessageType_LiskPublicKey = 122 [(wire_out) = true];
+
+ // Tezos
+ MessageType_TezosGetAddress = 150 [(wire_in) = true];
+ MessageType_TezosAddress = 151 [(wire_out) = true];
+ MessageType_TezosSignTx = 152 [(wire_in) = true];
+ MessageType_TezosSignedTx = 153 [(wire_out) = true];
+ MessageType_TezosGetPublicKey = 154 [(wire_in) = true];
+ MessageType_TezosPublicKey = 155 [(wire_out) = true];
+
+ // Stellar
+ MessageType_StellarSignTx = 202 [(wire_in) = true];
+ MessageType_StellarTxOpRequest = 203 [(wire_out) = true];
+ MessageType_StellarGetAddress = 207 [(wire_in) = true];
+ MessageType_StellarAddress = 208 [(wire_out) = true];
+ MessageType_StellarCreateAccountOp = 210 [(wire_in) = true];
+ MessageType_StellarPaymentOp = 211 [(wire_in) = true];
+ MessageType_StellarPathPaymentOp = 212 [(wire_in) = true];
+ MessageType_StellarManageOfferOp = 213 [(wire_in) = true];
+ MessageType_StellarCreatePassiveOfferOp = 214 [(wire_in) = true];
+ MessageType_StellarSetOptionsOp = 215 [(wire_in) = true];
+ MessageType_StellarChangeTrustOp = 216 [(wire_in) = true];
+ MessageType_StellarAllowTrustOp = 217 [(wire_in) = true];
+ MessageType_StellarAccountMergeOp = 218 [(wire_in) = true];
+ // omitted: StellarInflationOp is not a supported operation, would be 219
+ MessageType_StellarManageDataOp = 220 [(wire_in) = true];
+ MessageType_StellarBumpSequenceOp = 221 [(wire_in) = true];
+ MessageType_StellarSignedTx = 230 [(wire_out) = true];
+
+ // TRON
+ MessageType_TronGetAddress = 250 [(wire_in) = true];
+ MessageType_TronAddress = 251 [(wire_out) = true];
+ MessageType_TronSignTx = 252 [(wire_in) = true];
+ MessageType_TronSignedTx = 253 [(wire_out) = true];
+
+ // Cardano
+ // dropped Sign/VerifyMessage ids 300-302
+ MessageType_CardanoSignTx = 303 [(wire_in) = true];
+ MessageType_CardanoTxRequest = 304 [(wire_out) = true];
+ MessageType_CardanoGetPublicKey = 305 [(wire_in) = true];
+ MessageType_CardanoPublicKey = 306 [(wire_out) = true];
+ MessageType_CardanoGetAddress = 307 [(wire_in) = true];
+ MessageType_CardanoAddress = 308 [(wire_out) = true];
+ MessageType_CardanoTxAck = 309 [(wire_in) = true];
+ MessageType_CardanoSignedTx = 310 [(wire_out) = true];
+
+ // Ontology
+ MessageType_OntologyGetAddress = 350 [(wire_in) = true];
+ MessageType_OntologyAddress = 351 [(wire_out) = true];
+ MessageType_OntologyGetPublicKey = 352 [(wire_in) = true];
+ MessageType_OntologyPublicKey = 353 [(wire_out) = true];
+ MessageType_OntologySignTransfer = 354 [(wire_in) = true];
+ MessageType_OntologySignedTransfer = 355 [(wire_out) = true];
+ MessageType_OntologySignWithdrawOng = 356 [(wire_in) = true];
+ MessageType_OntologySignedWithdrawOng = 357 [(wire_out) = true];
+ MessageType_OntologySignOntIdRegister = 358 [(wire_in) = true];
+ MessageType_OntologySignedOntIdRegister = 359 [(wire_out) = true];
+ MessageType_OntologySignOntIdAddAttributes = 360 [(wire_in) = true];
+ MessageType_OntologySignedOntIdAddAttributes = 361 [(wire_out) = true];
+
+ // Ripple
+ MessageType_RippleGetAddress = 400 [(wire_in) = true];
+ MessageType_RippleAddress = 401 [(wire_out) = true];
+ MessageType_RippleSignTx = 402 [(wire_in) = true];
+ MessageType_RippleSignedTx = 403 [(wire_in) = true];
+
+ // Monero
+ MessageType_MoneroTransactionInitRequest = 501 [(wire_out) = true];
+ MessageType_MoneroTransactionInitAck = 502 [(wire_out) = true];
+ MessageType_MoneroTransactionSetInputRequest = 503 [(wire_out) = true];
+ MessageType_MoneroTransactionSetInputAck = 504 [(wire_out) = true];
+ MessageType_MoneroTransactionInputsPermutationRequest = 505 [(wire_out) = true];
+ MessageType_MoneroTransactionInputsPermutationAck = 506 [(wire_out) = true];
+ MessageType_MoneroTransactionInputViniRequest = 507 [(wire_out) = true];
+ MessageType_MoneroTransactionInputViniAck = 508 [(wire_out) = true];
+ MessageType_MoneroTransactionAllInputsSetRequest = 509 [(wire_out) = true];
+ MessageType_MoneroTransactionAllInputsSetAck = 510 [(wire_out) = true];
+ MessageType_MoneroTransactionSetOutputRequest = 511 [(wire_out) = true];
+ MessageType_MoneroTransactionSetOutputAck = 512 [(wire_out) = true];
+ MessageType_MoneroTransactionAllOutSetRequest = 513 [(wire_out) = true];
+ MessageType_MoneroTransactionAllOutSetAck = 514 [(wire_out) = true];
+ MessageType_MoneroTransactionSignInputRequest = 515 [(wire_out) = true];
+ MessageType_MoneroTransactionSignInputAck = 516 [(wire_out) = true];
+ MessageType_MoneroTransactionFinalRequest = 517 [(wire_out) = true];
+ MessageType_MoneroTransactionFinalAck = 518 [(wire_out) = true];
+ MessageType_MoneroKeyImageExportInitRequest = 530 [(wire_out) = true];
+ MessageType_MoneroKeyImageExportInitAck = 531 [(wire_out) = true];
+ MessageType_MoneroKeyImageSyncStepRequest = 532 [(wire_out) = true];
+ MessageType_MoneroKeyImageSyncStepAck = 533 [(wire_out) = true];
+ MessageType_MoneroKeyImageSyncFinalRequest = 534 [(wire_out) = true];
+ MessageType_MoneroKeyImageSyncFinalAck = 535 [(wire_out) = true];
+ MessageType_MoneroGetAddress = 540 [(wire_in) = true];
+ MessageType_MoneroAddress = 541 [(wire_out) = true];
+ MessageType_MoneroGetWatchKey = 542 [(wire_in) = true];
+ MessageType_MoneroWatchKey = 543 [(wire_out) = true];
+ MessageType_DebugMoneroDiagRequest = 546 [(wire_in) = true];
+ MessageType_DebugMoneroDiagAck = 547 [(wire_out) = true];
+ MessageType_MoneroGetTxKeyRequest = 550 [(wire_in) = true];
+ MessageType_MoneroGetTxKeyAck = 551 [(wire_out) = true];
+ MessageType_MoneroLiveRefreshStartRequest = 552 [(wire_in) = true];
+ MessageType_MoneroLiveRefreshStartAck = 553 [(wire_out) = true];
+ MessageType_MoneroLiveRefreshStepRequest = 554 [(wire_in) = true];
+ MessageType_MoneroLiveRefreshStepAck = 555 [(wire_out) = true];
+ MessageType_MoneroLiveRefreshFinalRequest = 556 [(wire_in) = true];
+ MessageType_MoneroLiveRefreshFinalAck = 557 [(wire_out) = true];
+
+ // EOS
+ MessageType_EosGetPublicKey = 600 [(wire_in) = true];
+ MessageType_EosPublicKey = 601 [(wire_out) = true];
+ MessageType_EosSignTx = 602 [(wire_in) = true];
+ MessageType_EosTxActionRequest = 603 [(wire_out) = true];
+ MessageType_EosTxActionAck = 604 [(wire_in) = true];
+ MessageType_EosSignedTx = 605 [(wire_out) = true];
+
+ // Binance
+ MessageType_BinanceGetAddress = 700 [(wire_in) = true];
+ MessageType_BinanceAddress = 701 [(wire_out) = true];
+ MessageType_BinanceGetPublicKey = 702 [(wire_in) = true];
+ MessageType_BinancePublicKey = 703 [(wire_out) = true];
+ MessageType_BinanceSignTx = 704 [(wire_in) = true];
+ MessageType_BinanceTxRequest = 705 [(wire_out) = true];
+ MessageType_BinanceTransferMsg = 706 [(wire_in) = true];
+ MessageType_BinanceOrderMsg = 707 [(wire_in) = true];
+ MessageType_BinanceCancelMsg = 708 [(wire_in) = true];
+ MessageType_BinanceSignedTx = 709 [(wire_out) = true];
+}
diff --git a/accounts/usbwallet/trezor/trezor.go b/accounts/usbwallet/trezor/trezor.go
new file mode 100644
index 000000000..7e756e609
--- /dev/null
+++ b/accounts/usbwallet/trezor/trezor.go
@@ -0,0 +1,70 @@
+// Copyright 2017 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+// This file contains the implementation for interacting with the Trezor hardware
+// wallets. The wire protocol spec can be found on the SatoshiLabs website:
+// https://wiki.trezor.io/Developers_guide-Message_Workflows
+
+// !!! STAHP !!!
+//
+// Before you touch the protocol files, you need to be aware of a breaking change
+// that occurred between firmware versions 1.7.3->1.8.0 (Model One) and 2.0.10->
+// 2.1.0 (Model T). The Ethereum address representation was changed from the 20
+// byte binary blob to a 42 byte hex string. The upstream protocol buffer files
+// only support the new format, so blindly pulling in a new spec will break old
+// devices!
+//
+// The Trezor devs had the foresight to add the string version as a new message
+// code instead of replacing the binary one. This means that the proto file can
+// actually define both the old and the new versions as optional. Please ensure
+// that you add back the old addresses everywhere (to avoid name clash. use the
+// addressBin and addressHex names).
+//
+// If in doubt, reach out to @karalabe.
+
+// To regenerate the protocol files in this package:
+// - Download the latest protoc https://github.com/protocolbuffers/protobuf/releases
+// - Build with the usual `./configure && make` and ensure it's on your $PATH
+// - Delete all the .proto and .pb.go files, pull in fresh ones from Trezor
+// - Grab the latest Go plugin `go get -u github.com/golang/protobuf/protoc-gen-go`
+// - Vendor in the latest Go plugin `govendor fetch github.com/golang/protobuf/...`
+
+//go:generate protoc -I/usr/local/include:. --go_out=import_path=trezor:. messages.proto messages-common.proto messages-management.proto messages-ethereum.proto
+
+// Package trezor contains the wire protocol.
+package trezor
+
+import (
+ "reflect"
+
+ "github.com/golang/protobuf/proto"
+)
+
+// Type returns the protocol buffer type number of a specific message. If the
+// message is nil, this method panics!
+func Type(msg proto.Message) uint16 {
+ return uint16(MessageType_value["MessageType_"+reflect.TypeOf(msg).Elem().Name()])
+}
+
+// Name returns the friendly message type name of a specific protocol buffer
+// type number.
+func Name(kind uint16) string {
+ name := MessageType_name[int32(kind)]
+ if len(name) < 12 {
+ return name
+ }
+ return name[12:]
+}
diff --git a/accounts/usbwallet/wallet.go b/accounts/usbwallet/wallet.go
index 943a7b3f9..ca7e54427 100644
--- a/accounts/usbwallet/wallet.go
+++ b/accounts/usbwallet/wallet.go
@@ -20,17 +20,17 @@ package usbwallet
import (
"context"
"fmt"
- "io"
- "math/big"
- "sync"
- "time"
-
- "github.com/karalabe/hid"
+ "github.com/karalabe/usb"
ethereum "github.com/truechain/truechain-engineering-code"
"github.com/truechain/truechain-engineering-code/accounts"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/core/types"
+ "github.com/truechain/truechain-engineering-code/crypto"
"github.com/truechain/truechain-engineering-code/log"
+ "io"
+ "math/big"
+ "sync"
+ "time"
)
// Maximum time between wallet health checks to detect USB unplugs.
@@ -66,6 +66,8 @@ type driver interface {
// SignTx sends the transaction to the USB device and waits for the user to confirm
// or deny the transaction.
SignTx(path accounts.DerivationPath, tx *types.Transaction, chainID *big.Int) (common.Address, *types.Transaction, error)
+
+ SignTypedMessage(path accounts.DerivationPath, messageHash []byte, domainHash []byte) ([]byte, error)
}
// wallet represents the common functionality shared by all USB hardware
@@ -76,17 +78,17 @@ type wallet struct {
driver driver // Hardware implementation of the low level device operations
url *accounts.URL // Textual URL uniquely identifying this wallet
- info hid.DeviceInfo // Known USB device infos about the wallet
- device *hid.Device // USB device advertising itself as a hardware wallet
+ info usb.DeviceInfo // Known USB device infos about the wallet
+ device usb.Device // USB device advertising itself as a hardware wallet
accounts []accounts.Account // List of derive accounts pinned on the hardware wallet
paths map[common.Address]accounts.DerivationPath // Known derivation paths for signing operations
- deriveNextPath accounts.DerivationPath // Next derivation path for account auto-discovery
- deriveNextAddr common.Address // Next derived account address for auto-discovery
- deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
- deriveReq chan chan struct{} // Channel to request a self-derivation on
- deriveQuit chan chan error // Channel to terminate the self-deriver with
+ deriveNextPaths []accounts.DerivationPath // Next derivation paths for account auto-discovery (multiple bases supported)
+ deriveNextAddrs []common.Address // Next derived account addresses for auto-discovery (multiple bases supported)
+ deriveChain ethereum.ChainStateReader // Blockchain state reader to discover used account with
+ deriveReq chan chan struct{} // Channel to request a self-derivation on
+ deriveQuit chan chan error // Channel to terminate the self-deriver with
healthQuit chan chan error
@@ -273,9 +275,7 @@ func (w *wallet) close() error {
w.device = nil
w.accounts, w.paths = nil, nil
- w.driver.Close()
-
- return nil
+ return w.driver.Close()
}
// Accounts implements accounts.Wallet, returning the list of accounts pinned to
@@ -340,57 +340,66 @@ func (w *wallet) selfDerive() {
accs []accounts.Account
paths []accounts.DerivationPath
- nextAddr = w.deriveNextAddr
- nextPath = w.deriveNextPath
+ nextPaths = append([]accounts.DerivationPath{}, w.deriveNextPaths...)
+ nextAddrs = append([]common.Address{}, w.deriveNextAddrs...)
context = context.Background()
)
- for empty := false; !empty; {
- // Retrieve the next derived Ethereum account
- if nextAddr == (common.Address{}) {
- if nextAddr, err = w.driver.Derive(nextPath); err != nil {
- w.log.Warn("USB wallet account derivation failed", "err", err)
+ for i := 0; i < len(nextAddrs); i++ {
+ for empty := false; !empty; {
+ // Retrieve the next derived Ethereum account
+ if nextAddrs[i] == (common.Address{}) {
+ if nextAddrs[i], err = w.driver.Derive(nextPaths[i]); err != nil {
+ w.log.Warn("USB wallet account derivation failed", "err", err)
+ break
+ }
+ }
+ // Check the account's status against the current chain state
+ var (
+ balance *big.Int
+ nonce uint64
+ )
+ balance, err = w.deriveChain.BalanceAt(context, nextAddrs[i], nil)
+ if err != nil {
+ w.log.Warn("USB wallet balance retrieval failed", "err", err)
break
}
- }
- // Check the account's status against the current chain state
- var (
- balance *big.Int
- nonce uint64
- )
- balance, err = w.deriveChain.BalanceAt(context, nextAddr, nil)
- if err != nil {
- w.log.Warn("USB wallet balance retrieval failed", "err", err)
- break
- }
- nonce, err = w.deriveChain.NonceAt(context, nextAddr, nil)
- if err != nil {
- w.log.Warn("USB wallet nonce retrieval failed", "err", err)
- break
- }
- // If the next account is empty, stop self-derivation, but add it nonetheless
- if balance.Sign() == 0 && nonce == 0 {
- empty = true
- }
- // We've just self-derived a new account, start tracking it locally
- path := make(accounts.DerivationPath, len(nextPath))
- copy(path[:], nextPath[:])
- paths = append(paths, path)
-
- account := accounts.Account{
- Address: nextAddr,
- URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)},
- }
- accs = append(accs, account)
+ nonce, err = w.deriveChain.NonceAt(context, nextAddrs[i], nil)
+ if err != nil {
+ w.log.Warn("USB wallet nonce retrieval failed", "err", err)
+ break
+ }
+ // We've just self-derived a new account, start tracking it locally
+ // unless the account was empty.
+ path := make(accounts.DerivationPath, len(nextPaths[i]))
+ copy(path[:], nextPaths[i][:])
+ if balance.Sign() == 0 && nonce == 0 {
+ empty = true
+ // If it indeed was empty, make a log output for it anyway. In the case
+ // of legacy-ledger, the first account on the legacy-path will
+ // be shown to the user, even if we don't actively track it
+ if i < len(nextAddrs)-1 {
+ w.log.Info("Skipping trakcking first account on legacy path, use personal.deriveAccount(,, false) to track",
+ "path", path, "address", nextAddrs[i])
+ break
+ }
+ }
+ paths = append(paths, path)
+ account := accounts.Account{
+ Address: nextAddrs[i],
+ URL: accounts.URL{Scheme: w.url.Scheme, Path: fmt.Sprintf("%s/%s", w.url.Path, path)},
+ }
+ accs = append(accs, account)
- // Display a log message to the user for new (or previously empty accounts)
- if _, known := w.paths[nextAddr]; !known || (!empty && nextAddr == w.deriveNextAddr) {
- w.log.Info("USB wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce)
- }
- // Fetch the next potential account
- if !empty {
- nextAddr = common.Address{}
- nextPath[len(nextPath)-1]++
+ // Display a log message to the user for new (or previously empty accounts)
+ if _, known := w.paths[nextAddrs[i]]; !known || (!empty && nextAddrs[i] == w.deriveNextAddrs[i]) {
+ w.log.Info("USB wallet discovered new account", "address", nextAddrs[i], "path", path, "balance", balance, "nonce", nonce)
+ }
+ // Fetch the next potential account
+ if !empty {
+ nextAddrs[i] = common.Address{}
+ nextPaths[i][len(nextPaths[i])-1]++
+ }
}
}
// Self derivation complete, release device lock
@@ -407,8 +416,8 @@ func (w *wallet) selfDerive() {
}
// Shift the self-derivation forward
// TODO(karalabe): don't overwrite changes from wallet.SelfDerive
- w.deriveNextAddr = nextAddr
- w.deriveNextPath = nextPath
+ w.deriveNextAddrs = nextAddrs
+ w.deriveNextPaths = nextPaths
w.stateLock.Unlock()
// Notify the user of termination and loop after a bit of time (to avoid trashing)
@@ -475,32 +484,100 @@ func (w *wallet) Derive(path accounts.DerivationPath, pin bool) (accounts.Accoun
if _, ok := w.paths[address]; !ok {
w.accounts = append(w.accounts, account)
- w.paths[address] = path
+ w.paths[address] = make(accounts.DerivationPath, len(path))
+ copy(w.paths[address], path)
}
return account, nil
}
-// SelfDerive implements accounts.Wallet, trying to discover accounts that the
-// user used previously (based on the chain state), but ones that he/she did not
-// explicitly pin to the wallet manually. To avoid chain head monitoring, self
-// derivation only runs during account listing (and even then throttled).
-func (w *wallet) SelfDerive(base accounts.DerivationPath, chain ethereum.ChainStateReader) {
+// SelfDerive sets a base account derivation path from which the wallet attempts
+// to discover non zero accounts and automatically add them to list of tracked
+// accounts.
+//
+// Note, self derivation will increment the last component of the specified path
+// opposed to decending into a child path to allow discovering accounts starting
+// from non zero components.
+//
+// Some hardware wallets switched derivation paths through their evolution, so
+// this method supports providing multiple bases to discover old user accounts
+// too. Only the last base will be used to derive the next empty account.
+//
+// You can disable automatic account discovery by calling SelfDerive with a nil
+// chain state reader.
+func (w *wallet) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) {
w.stateLock.Lock()
defer w.stateLock.Unlock()
- w.deriveNextPath = make(accounts.DerivationPath, len(base))
- copy(w.deriveNextPath[:], base[:])
-
- w.deriveNextAddr = common.Address{}
+ w.deriveNextPaths = make([]accounts.DerivationPath, len(bases))
+ for i, base := range bases {
+ w.deriveNextPaths[i] = make(accounts.DerivationPath, len(base))
+ copy(w.deriveNextPaths[i][:], base[:])
+ }
+ w.deriveNextAddrs = make([]common.Address, len(bases))
w.deriveChain = chain
}
-// SignHash implements accounts.Wallet, however signing arbitrary data is not
+// signHash implements accounts.Wallet, however signing arbitrary data is not
// supported for hardware wallets, so this method will always return an error.
-func (w *wallet) SignHash(account accounts.Account, hash []byte) ([]byte, error) {
+func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
return nil, accounts.ErrNotSupported
}
+// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed
+func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) {
+
+ // Unless we are doing 712 signing, simply dispatch to signHash
+ if !(mimeType == accounts.MimetypeTypedData && len(data) == 66 && data[0] == 0x19 && data[1] == 0x01) {
+ return w.signHash(account, crypto.Keccak256(data))
+ }
+
+ // dispatch to 712 signing if the mimetype is TypedData and the format matches
+ w.stateLock.RLock() // Comms have own mutex, this is for the state fields
+ defer w.stateLock.RUnlock()
+
+ // If the wallet is closed, abort
+ if w.device == nil {
+ return nil, accounts.ErrWalletClosed
+ }
+ // Make sure the requested account is contained within
+ path, ok := w.paths[account.Address]
+ if !ok {
+ return nil, accounts.ErrUnknownAccount
+ }
+ // All infos gathered and metadata checks out, request signing
+ <-w.commsLock
+ defer func() { w.commsLock <- struct{}{} }()
+
+ // Ensure the device isn't screwed with while user confirmation is pending
+ // TODO(karalabe): remove if hotplug lands on Windows
+ w.hub.commsLock.Lock()
+ w.hub.commsPend++
+ w.hub.commsLock.Unlock()
+
+ defer func() {
+ w.hub.commsLock.Lock()
+ w.hub.commsPend--
+ w.hub.commsLock.Unlock()
+ }()
+ // Sign the transaction
+ signature, err := w.driver.SignTypedMessage(path, data[2:34], data[34:66])
+ if err != nil {
+ return nil, err
+ }
+ return signature, nil
+}
+
+// SignDataWithPassphrase implements accounts.Wallet, attempting to sign the given
+// data with the given account using passphrase as extra authentication.
+// Since USB wallets don't rely on passphrases, these are silently ignored.
+func (w *wallet) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) {
+ return w.SignData(account, mimeType, data)
+}
+
+func (w *wallet) SignText(account accounts.Account, text []byte) ([]byte, error) {
+ return w.signHash(account, accounts.TextHash(text))
+}
+
// SignTx implements accounts.Wallet. It sends the transaction over to the Ledger
// wallet to request a confirmation from the user. It returns either the signed
// transaction or a failure if the user denied the transaction.
@@ -547,15 +624,11 @@ func (w *wallet) SignTx(account accounts.Account, tx *types.Transaction, chainID
return signed, nil
}
-func (w *wallet) SignTx_Payment(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
- return nil, nil
-}
-
// SignHashWithPassphrase implements accounts.Wallet, however signing arbitrary
// data is not supported for Ledger wallets, so this method will always return
// an error.
-func (w *wallet) SignHashWithPassphrase(account accounts.Account, passphrase string, hash []byte) ([]byte, error) {
- return w.SignHash(account, hash)
+func (w *wallet) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) {
+ return w.SignText(account, accounts.TextHash(text))
}
// SignTxWithPassphrase implements accounts.Wallet, attempting to sign the given
diff --git a/cmd/getrue/main.go b/cmd/getrue/main.go
index ae5f7ff54..9a94d777c 100644
--- a/cmd/getrue/main.go
+++ b/cmd/getrue/main.go
@@ -292,9 +292,9 @@ func startNode(ctx *cli.Context, stack *node.Node) {
log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
if event.Wallet.URL().Scheme == "ledger" {
- event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader)
+ event.Wallet.SelfDerive([]accounts.DerivationPath{accounts.LegacyLedgerBaseDerivationPath}, stateReader)
} else {
- event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
+ event.Wallet.SelfDerive([]accounts.DerivationPath{accounts.DefaultBaseDerivationPath}, stateReader)
}
case accounts.WalletDropped:
diff --git a/core/types/block.go b/core/types/block.go
index fa2ebf210..06ae671a4 100644
--- a/core/types/block.go
+++ b/core/types/block.go
@@ -163,6 +163,9 @@ type Header struct {
GasUsed uint64 `json:"gasUsed" gencodec:"required"`
Time *big.Int `json:"timestamp" gencodec:"required"`
Extra []byte `json:"extraData" gencodec:"required"`
+
+ // BaseFee was added by EIP-1559 and is ignored in legacy headers.
+ BaseFee *big.Int `json:"baseFeePerGas" rlp:"optional"`
}
// field type overrides for gencodec
diff --git a/core/types/transaction_signing.go b/core/types/transaction_signing.go
index 958b4cc43..aee57f2fa 100644
--- a/core/types/transaction_signing.go
+++ b/core/types/transaction_signing.go
@@ -50,7 +50,21 @@ func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer {
return signer
}
-// SignTx signs the transaction using the given signer and private key
+// LatestSignerForChainID returns the 'most permissive' Signer available. Specifically,
+// this enables support for EIP-155 replay protection and all implemented EIP-2718
+// transaction types if chainID is non-nil.
+//
+// Use this in transaction-handling code where the current block number and fork
+// configuration are unknown. If you have a ChainConfig, use LatestSigner instead.
+// If you have a ChainConfig and know the current block number, use MakeSigner instead.
+func LatestSignerForChainID(chainID *big.Int) Signer {
+ if chainID == nil {
+ return TIP1Signer{}
+ }
+ return NewTIP1Signer(chainID)
+}
+
+// SignTx signs the transaction using the given signer and private key.
func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) {
h := s.Hash(tx)
sig, err := crypto.Sign(h[:], prv)
diff --git a/core/vm/access_list_tracer.go b/core/vm/access_list_tracer.go
index 9fd1388ff..b6619b661 100644
--- a/core/vm/access_list_tracer.go
+++ b/core/vm/access_list_tracer.go
@@ -96,7 +96,7 @@ func (al accessList) equal(other accessList) bool {
func (al accessList) accessList() types.AccessList {
acl := make(types.AccessList, 0, len(al))
for addr, slots := range al {
- tuple := types.AccessTuple{Address: addr}
+ tuple := types.AccessTuple{Address: addr, StorageKeys: []common.Hash{}}
for slot := range slots {
tuple.StorageKeys = append(tuple.StorageKeys, slot)
}
diff --git a/core/vm/analysis.go b/core/vm/analysis.go
index 0ccf47b97..449cded2a 100644
--- a/core/vm/analysis.go
+++ b/core/vm/analysis.go
@@ -16,17 +16,49 @@
package vm
+const (
+ set2BitsMask = uint16(0b1100_0000_0000_0000)
+ set3BitsMask = uint16(0b1110_0000_0000_0000)
+ set4BitsMask = uint16(0b1111_0000_0000_0000)
+ set5BitsMask = uint16(0b1111_1000_0000_0000)
+ set6BitsMask = uint16(0b1111_1100_0000_0000)
+ set7BitsMask = uint16(0b1111_1110_0000_0000)
+)
+
// bitvec is a bit vector which maps bytes in a program.
// An unset bit means the byte is an opcode, a set bit means
// it's data (i.e. argument of PUSHxx).
type bitvec []byte
-func (bits *bitvec) set(pos uint64) {
- (*bits)[pos/8] |= 0x80 >> (pos % 8)
+var lookup = [8]byte{
+ 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1,
+}
+
+func (bits bitvec) set1(pos uint64) {
+ bits[pos/8] |= lookup[pos%8]
+}
+
+func (bits bitvec) setN(flag uint16, pos uint64) {
+ a := flag >> (pos % 8)
+ bits[pos/8] |= byte(a >> 8)
+ if b := byte(a); b != 0 {
+ // If the bit-setting affects the neighbouring byte, we can assign - no need to OR it,
+ // since it's the first write to that byte
+ bits[pos/8+1] = b
+ }
+}
+
+func (bits bitvec) set8(pos uint64) {
+ a := byte(0xFF >> (pos % 8))
+ bits[pos/8] |= a
+ bits[pos/8+1] = ^a
}
-func (bits *bitvec) set8(pos uint64) {
- (*bits)[pos/8] |= 0xFF >> (pos % 8)
- (*bits)[pos/8+1] |= ^(0xFF >> (pos % 8))
+
+func (bits bitvec) set16(pos uint64) {
+ a := byte(0xFF >> (pos % 8))
+ bits[pos/8] |= a
+ bits[pos/8+1] = 0xFF
+ bits[pos/8+2] = ^a
}
// codeSegment checks if the position is in a code segment.
@@ -40,22 +72,52 @@ func codeBitmap(code []byte) bitvec {
// ends with a PUSH32, the algorithm will push zeroes onto the
// bitvector outside the bounds of the actual code.
bits := make(bitvec, len(code)/8+1+4)
+ return codeBitmapInternal(code, bits)
+}
+
+// codeBitmapInternal is the internal implementation of codeBitmap.
+// It exists for the purpose of being able to run benchmark tests
+// without dynamic allocations affecting the results.
+func codeBitmapInternal(code, bits bitvec) bitvec {
for pc := uint64(0); pc < uint64(len(code)); {
op := OpCode(code[pc])
-
- if op >= PUSH1 && op <= PUSH32 {
- numbits := op - PUSH1 + 1
- pc++
+ pc++
+ if op < PUSH1 || op > PUSH32 {
+ continue
+ }
+ numbits := op - PUSH1 + 1
+ if numbits >= 8 {
+ for ; numbits >= 16; numbits -= 16 {
+ bits.set16(pc)
+ pc += 16
+ }
for ; numbits >= 8; numbits -= 8 {
- bits.set8(pc) // 8
+ bits.set8(pc)
pc += 8
}
- for ; numbits > 0; numbits-- {
- bits.set(pc)
- pc++
- }
- } else {
- pc++
+ }
+ switch numbits {
+ case 1:
+ bits.set1(pc)
+ pc += 1
+ case 2:
+ bits.setN(set2BitsMask, pc)
+ pc += 2
+ case 3:
+ bits.setN(set3BitsMask, pc)
+ pc += 3
+ case 4:
+ bits.setN(set4BitsMask, pc)
+ pc += 4
+ case 5:
+ bits.setN(set5BitsMask, pc)
+ pc += 5
+ case 6:
+ bits.setN(set6BitsMask, pc)
+ pc += 6
+ case 7:
+ bits.setN(set7BitsMask, pc)
+ pc += 7
}
}
return bits
diff --git a/core/vm/analysis_test.go b/core/vm/analysis_test.go
index d20b501ce..53d6c307b 100644
--- a/core/vm/analysis_test.go
+++ b/core/vm/analysis_test.go
@@ -47,17 +47,20 @@ func TestJumpDestAnalysis(t *testing.T) {
{[]byte{byte(PUSH32)}, 0xFF, 1},
{[]byte{byte(PUSH32)}, 0xFF, 2},
}
- for _, test := range tests {
+ for i, test := range tests {
ret := codeBitmap(test.code)
if ret[test.which] != test.exp {
- t.Fatalf("expected %x, got %02x", test.exp, ret[test.which])
+ t.Fatalf("test %d: expected %x, got %02x", i, test.exp, ret[test.which])
}
}
}
+const analysisCodeSize = 1200 * 1024
+
func BenchmarkJumpdestAnalysis_1200k(bench *testing.B) {
// 1.4 ms
- code := make([]byte, 1200000)
+ code := make([]byte, analysisCodeSize)
+ bench.SetBytes(analysisCodeSize)
bench.ResetTimer()
for i := 0; i < bench.N; i++ {
codeBitmap(code)
@@ -66,10 +69,37 @@ func BenchmarkJumpdestAnalysis_1200k(bench *testing.B) {
}
func BenchmarkJumpdestHashing_1200k(bench *testing.B) {
// 4 ms
- code := make([]byte, 1200000)
+ code := make([]byte, analysisCodeSize)
+ bench.SetBytes(analysisCodeSize)
bench.ResetTimer()
for i := 0; i < bench.N; i++ {
crypto.Keccak256Hash(code)
}
bench.StopTimer()
}
+
+func BenchmarkJumpdestOpAnalysis(bench *testing.B) {
+ var op OpCode
+ bencher := func(b *testing.B) {
+ code := make([]byte, analysisCodeSize)
+ b.SetBytes(analysisCodeSize)
+ for i := range code {
+ code[i] = byte(op)
+ }
+ bits := make(bitvec, len(code)/8+1+4)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ for j := range bits {
+ bits[j] = 0
+ }
+ codeBitmapInternal(code, bits)
+ }
+ }
+ for op = PUSH1; op <= PUSH32; op++ {
+ bench.Run(op.String(), bencher)
+ }
+ op = JUMPDEST
+ bench.Run(op.String(), bencher)
+ op = STOP
+ bench.Run(op.String(), bencher)
+}
diff --git a/core/vm/errors.go b/core/vm/errors.go
index e64e38ed4..8fb880a3e 100644
--- a/core/vm/errors.go
+++ b/core/vm/errors.go
@@ -42,6 +42,7 @@ var (
ErrReturnStackExceeded = errors.New("return stack limit reached")
ErrStakingInvalidInput = errors.New("invalid input for staking")
ErrStakingInsufficientBalance = errors.New("insufficient balance for staking transfer")
+ ErrInvalidCode = errors.New("invalid code: must not begin with 0xef")
)
// ErrStackUnderflow wraps an evm error when the items on the stack less
diff --git a/core/vm/gas_table.go b/core/vm/gas_table.go
index dcc1a32e7..d6a5960cd 100644
--- a/core/vm/gas_table.go
+++ b/core/vm/gas_table.go
@@ -59,7 +59,7 @@ func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) {
// as argument:
// CALLDATACOPY (stack position 2)
// CODECOPY (stack position 2)
-// EXTCODECOPY (stack poition 3)
+// EXTCODECOPY (stack position 3)
// RETURNDATACOPY (stack position 2)
func memoryCopierGas(stackpos int) gasFunc {
return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
@@ -161,18 +161,18 @@ func gasSStore(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySi
}
// 0. If *gasleft* is less than or equal to 2300, fail the current call.
-// 1. If current value equals new value (this is a no-op), SSTORE_NOOP_GAS gas is deducted.
+// 1. If current value equals new value (this is a no-op), SLOAD_GAS is deducted.
// 2. If current value does not equal new value:
// 2.1. If original value equals current value (this storage slot has not been changed by the current execution context):
-// 2.1.1. If original value is 0, SSTORE_INIT_GAS gas is deducted.
-// 2.1.2. Otherwise, SSTORE_CLEAN_GAS gas is deducted. If new value is 0, add SSTORE_CLEAR_REFUND to refund counter.
-// 2.2. If original value does not equal current value (this storage slot is dirty), SSTORE_DIRTY_GAS gas is deducted. Apply both of the following clauses:
+// 2.1.1. If original value is 0, SSTORE_SET_GAS (20K) gas is deducted.
+// 2.1.2. Otherwise, SSTORE_RESET_GAS gas is deducted. If new value is 0, add SSTORE_CLEARS_SCHEDULE to refund counter.
+// 2.2. If original value does not equal current value (this storage slot is dirty), SLOAD_GAS gas is deducted. Apply both of the following clauses:
// 2.2.1. If original value is not 0:
-// 2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEAR_REFUND gas from refund counter. We can prove that refund counter will never go below 0.
-// 2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEAR_REFUND gas to refund counter.
+// 2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEARS_SCHEDULE gas from refund counter.
+// 2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEARS_SCHEDULE gas to refund counter.
// 2.2.2. If original value equals new value (this storage slot is reset):
-// 2.2.2.1. If original value is 0, add SSTORE_INIT_REFUND to refund counter.
-// 2.2.2.2. Otherwise, add SSTORE_CLEAN_REFUND gas to refund counter.
+// 2.2.2.1. If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter.
+// 2.2.2.2. Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter.
func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
// If we fail the minimum gas availability invariant, fail (0)
if contract.Gas <= params.SstoreSentryGasEIP2200 {
@@ -186,7 +186,7 @@ func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, m
value := common.Hash(y.Bytes32())
if current == value { // noop (1)
- return params.SstoreNoopGasEIP2200, nil
+ return params.SloadGasEIP2200, nil
}
original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
if original == current {
@@ -195,7 +195,6 @@ func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, m
}
if value == (common.Hash{}) { // delete slot (2.1.2b)
evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
-
}
return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
}
@@ -208,12 +207,12 @@ func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *Stack, mem *Memory, m
}
if original == value {
if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
- evm.StateDB.AddRefund(params.SstoreInitRefundEIP2200)
+ evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
} else { // reset to original existing slot (2.2.2.2)
- evm.StateDB.AddRefund(params.SstoreCleanRefundEIP2200)
+ evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)
}
}
- return params.SstoreDirtyGasEIP2200, nil // dirty update (2.2)
+ return params.SloadGasEIP2200, nil // dirty update (2.2)
}
func makeGasLog(n uint64) gasFunc {
@@ -298,7 +297,20 @@ func gasCreate2(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memoryS
return gas, nil
}
-func gasExp(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
+func gasExpFrontier(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
+ expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
+
+ var (
+ gas = expByteLen * params.ExpByteFrontier // no overflow check required. Max is 256 * ExpByte gas
+ overflow bool
+ )
+ if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow {
+ return 0, ErrGasUintOverflow
+ }
+ return gas, nil
+}
+
+func gasExpEIP158(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
expByteLen := uint64((stack.data[stack.len()-2].BitLen() + 7) / 8)
var (
diff --git a/core/vm/gas_table_test.go b/core/vm/gas_table_test.go
index 3a86d7872..4fa305c0e 100644
--- a/core/vm/gas_table_test.go
+++ b/core/vm/gas_table_test.go
@@ -20,6 +20,7 @@ import (
"github.com/truechain/truechain-engineering-code/etruedb"
"math"
"math/big"
+
"testing"
"github.com/truechain/truechain-engineering-code/common"
@@ -87,13 +88,13 @@ func TestEIP2200(t *testing.T) {
statedb.SetState(address, common.Hash{}, common.BytesToHash([]byte{tt.original}))
statedb.Finalise(true) // Push the state into the "original" slot
- vmctx := Context{
+ vmctx := BlockContext{
CanTransfer: func(StateDB, common.Address, *big.Int) bool { return true },
Transfer: func(StateDB, common.Address, common.Address, *big.Int) {},
}
- vmenv := NewEVM(vmctx, statedb, params.TestChainConfig, Config{ExtraEips: []int{2200}})
+ vmenv := NewEVM(vmctx, TxContext{}, statedb, params.TestChainConfig, Config{ExtraEips: []int{2200}})
- _, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, tt.gaspool, new(big.Int), new(big.Int))
+ _, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, tt.gaspool, new(big.Int), nil)
if err != tt.failure {
t.Errorf("test %d: failure mismatch: have %v, want %v", i, err, tt.failure)
}
diff --git a/core/vm/gen_structlog.go b/core/vm/gen_structlog.go
index cd92f16ec..a873e459d 100644
--- a/core/vm/gen_structlog.go
+++ b/core/vm/gen_structlog.go
@@ -4,8 +4,8 @@ package vm
import (
"encoding/json"
- "math/big"
+ "github.com/holiman/uint256"
"github.com/truechain/truechain-engineering-code/common"
"github.com/truechain/truechain-engineering-code/common/hexutil"
"github.com/truechain/truechain-engineering-code/common/math"
@@ -22,7 +22,7 @@ func (s StructLog) MarshalJSON() ([]byte, error) {
GasCost math.HexOrDecimal64 `json:"gasCost"`
Memory hexutil.Bytes `json:"memory"`
MemorySize int `json:"memSize"`
- Stack []*math.HexOrDecimal256 `json:"stack"`
+ Stack []uint256.Int `json:"stack"`
ReturnData hexutil.Bytes `json:"returnData"`
Storage map[common.Hash]common.Hash `json:"-"`
Depth int `json:"depth"`
@@ -38,12 +38,7 @@ func (s StructLog) MarshalJSON() ([]byte, error) {
enc.GasCost = math.HexOrDecimal64(s.GasCost)
enc.Memory = s.Memory
enc.MemorySize = s.MemorySize
- if s.Stack != nil {
- enc.Stack = make([]*math.HexOrDecimal256, len(s.Stack))
- for k, v := range s.Stack {
- enc.Stack[k] = (*math.HexOrDecimal256)(v)
- }
- }
+ enc.Stack = s.Stack
enc.ReturnData = s.ReturnData
enc.Storage = s.Storage
enc.Depth = s.Depth
@@ -63,7 +58,7 @@ func (s *StructLog) UnmarshalJSON(input []byte) error {
GasCost *math.HexOrDecimal64 `json:"gasCost"`
Memory *hexutil.Bytes `json:"memory"`
MemorySize *int `json:"memSize"`
- Stack []*math.HexOrDecimal256 `json:"stack"`
+ Stack []uint256.Int `json:"stack"`
ReturnData *hexutil.Bytes `json:"returnData"`
Storage map[common.Hash]common.Hash `json:"-"`
Depth *int `json:"depth"`
@@ -93,10 +88,7 @@ func (s *StructLog) UnmarshalJSON(input []byte) error {
s.MemorySize = *dec.MemorySize
}
if dec.Stack != nil {
- s.Stack = make([]*big.Int, len(dec.Stack))
- for k, v := range dec.Stack {
- s.Stack[k] = (*big.Int)(v)
- }
+ s.Stack = dec.Stack
}
if dec.ReturnData != nil {
s.ReturnData = *dec.ReturnData
diff --git a/core/vm/instructions.go b/core/vm/instructions.go
index 13ae91bb8..f4ff9402e 100644
--- a/core/vm/instructions.go
+++ b/core/vm/instructions.go
@@ -667,6 +667,7 @@ func opCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byt
}
stack.push(&temp)
if err == nil || err == ErrExecutionReverted {
+ ret = common.CopyBytes(ret)
scope.Memory.Set(retOffset.Uint64(), retSize.Uint64(), ret)
}
scope.Contract.Gas += returnGas
@@ -701,6 +702,7 @@ func opCallCode(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([
}
stack.push(&temp)
if err == nil || err == ErrExecutionReverted {
+ ret = common.CopyBytes(ret)
scope.Memory.Set(retOffset.Uint64(), retSize.Uint64(), ret)
}
scope.Contract.Gas += returnGas
@@ -728,6 +730,7 @@ func opDelegateCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext
}
stack.push(&temp)
if err == nil || err == ErrExecutionReverted {
+ ret = common.CopyBytes(ret)
scope.Memory.Set(retOffset.Uint64(), retSize.Uint64(), ret)
}
scope.Contract.Gas += returnGas
@@ -755,6 +758,7 @@ func opStaticCall(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext)
}
stack.push(&temp)
if err == nil || err == ErrExecutionReverted {
+ ret = common.CopyBytes(ret)
scope.Memory.Set(retOffset.Uint64(), retSize.Uint64(), ret)
}
scope.Contract.Gas += returnGas
@@ -783,11 +787,8 @@ func opStop(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byt
func opSuicide(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) {
beneficiary := scope.Stack.pop()
balance := interpreter.evm.StateDB.GetBalance(scope.Contract.Address())
- addr := beneficiary.Bytes20()
- if interpreter.evm.StateDB.GetPOSLocked(scope.Contract.Address()).Cmp(common.Big0) == 0 {
- interpreter.evm.StateDB.AddBalance(addr, balance)
- interpreter.evm.StateDB.Suicide(scope.Contract.Address())
- }
+ interpreter.evm.StateDB.AddBalance(beneficiary.Bytes20(), balance)
+ interpreter.evm.StateDB.Suicide(scope.Contract.Address())
return nil, nil
}
diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go
index b683716bd..28fea23be 100644
--- a/core/vm/interpreter.go
+++ b/core/vm/interpreter.go
@@ -34,9 +34,6 @@ type Config struct {
JumpTable [256]*operation // EVM instruction table, automatically populated if unset
- EWASMInterpreter string // External EWASM interpreter options
- EVMInterpreter string // External EVM interpreter options
-
ExtraEips []int // Additional EIPS that are to be enabled
}
@@ -272,7 +269,7 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (
// if the operation clears the return data (e.g. it has returning data)
// set the last return to the result of the operation.
if operation.returns {
- in.returnData = common.CopyBytes(res)
+ in.returnData = res
}
switch {
diff --git a/core/vm/jump_table.go b/core/vm/jump_table.go
index 8d16545c2..27a4411f1 100644
--- a/core/vm/jump_table.go
+++ b/core/vm/jump_table.go
@@ -49,8 +49,14 @@ type operation struct {
}
var (
- constantinopleInstructionSet = newConstantinopleInstructionSet()
- berlinInstructionSet = newBerlinInstructionSet()
+ constantinopleInstructionSet = newConstantinopleInstructionSet()
+ berlinInstructionSet = newBerlinInstructionSet()
+ frontierInstructionSet = newFrontierInstructionSet()
+ homesteadInstructionSet = newHomesteadInstructionSet()
+ tangerineWhistleInstructionSet = newTangerineWhistleInstructionSet()
+ spuriousDragonInstructionSet = newSpuriousDragonInstructionSet()
+ byzantiumInstructionSet = newByzantiumInstructionSet()
+ istanbulInstructionSet = newIstanbulInstructionSet()
)
// JumpTable contains the EVM opcodes supported at a given fork.
@@ -64,8 +70,8 @@ func newBerlinInstructionSet() JumpTable {
return instructionSet
}
-// newIstanbulInstructionSet returns the frontier, homestead
-// byzantium, contantinople and petersburg instructions.
+// newIstanbulInstructionSet returns the frontier, homestead, byzantium,
+// contantinople, istanbul and petersburg instructions.
func newIstanbulInstructionSet() JumpTable {
instructionSet := newConstantinopleInstructionSet()
@@ -76,7 +82,7 @@ func newIstanbulInstructionSet() JumpTable {
return instructionSet
}
-// newConstantinopleInstructionSet returns the frontier, homestead
+// newConstantinopleInstructionSet returns the frontier, homestead,
// byzantium and contantinople instructions.
func newConstantinopleInstructionSet() JumpTable {
instructionSet := newByzantiumInstructionSet()
@@ -100,7 +106,7 @@ func newConstantinopleInstructionSet() JumpTable {
}
instructionSet[EXTCODEHASH] = &operation{
execute: opExtCodeHash,
- constantGas: params.ExtcodeHashGas,
+ constantGas: params.ExtcodeHashGasConstantinople,
minStack: minStack(1, 1),
maxStack: maxStack(1, 1),
}
@@ -159,7 +165,7 @@ func newByzantiumInstructionSet() JumpTable {
// EIP 158 a.k.a Spurious Dragon
func newSpuriousDragonInstructionSet() JumpTable {
instructionSet := newTangerineWhistleInstructionSet()
- instructionSet[EXP].dynamicGas = gasExp
+ instructionSet[EXP].dynamicGas = gasExpEIP158
return instructionSet
}
@@ -184,7 +190,7 @@ func newHomesteadInstructionSet() JumpTable {
instructionSet[DELEGATECALL] = &operation{
execute: opDelegateCall,
dynamicGas: gasDelegateCall,
- constantGas: params.CallGas,
+ constantGas: params.CallGasFrontier,
minStack: minStack(6, 1),
maxStack: maxStack(6, 1),
memorySize: memoryDelegateCall,
@@ -260,7 +266,7 @@ func newFrontierInstructionSet() JumpTable {
},
EXP: {
execute: opExp,
- dynamicGas: gasExp,
+ dynamicGas: gasExpFrontier,
minStack: minStack(2, 1),
maxStack: maxStack(2, 1),
},
@@ -352,7 +358,7 @@ func newFrontierInstructionSet() JumpTable {
},
BALANCE: {
execute: opBalance,
- constantGas: params.BalanceGas,
+ constantGas: params.BalanceGasFrontier,
minStack: minStack(1, 1),
maxStack: maxStack(1, 1),
},
@@ -416,13 +422,13 @@ func newFrontierInstructionSet() JumpTable {
},
EXTCODESIZE: {
execute: opExtCodeSize,
- constantGas: params.ExtcodeSizeGas,
+ constantGas: params.ExtcodeSizeGasFrontier,
minStack: minStack(1, 1),
maxStack: maxStack(1, 1),
},
EXTCODECOPY: {
execute: opExtCodeCopy,
- constantGas: params.ExtcodeCopyBase,
+ constantGas: params.ExtcodeCopyBaseFrontier,
dynamicGas: gasExtCodeCopy,
minStack: minStack(4, 0),
maxStack: maxStack(4, 0),
@@ -496,7 +502,7 @@ func newFrontierInstructionSet() JumpTable {
},
SLOAD: {
execute: opSload,
- constantGas: params.SloadGas,
+ constantGas: params.SloadGasFrontier,
minStack: minStack(1, 1),
maxStack: maxStack(1, 1),
},
@@ -981,7 +987,7 @@ func newFrontierInstructionSet() JumpTable {
},
CALL: {
execute: opCall,
- constantGas: params.CallGas,
+ constantGas: params.CallGasFrontier,
dynamicGas: gasCall,
minStack: minStack(7, 1),
maxStack: maxStack(7, 1),
@@ -990,7 +996,7 @@ func newFrontierInstructionSet() JumpTable {
},
CALLCODE: {
execute: opCallCode,
- constantGas: params.CallGas,
+ constantGas: params.CallGasFrontier,
dynamicGas: gasCallCode,
minStack: minStack(7, 1),
maxStack: maxStack(7, 1),
diff --git a/core/vm/logger.go b/core/vm/logger.go
index 1aac48ce2..a3261e892 100644
--- a/core/vm/logger.go
+++ b/core/vm/logger.go
@@ -19,6 +19,7 @@ package vm
import (
"encoding/hex"
"fmt"
+ "github.com/holiman/uint256"
"io"
"math/big"
"strings"
@@ -65,7 +66,7 @@ type StructLog struct {
GasCost uint64 `json:"gasCost"`
Memory []byte `json:"memory"`
MemorySize int `json:"memSize"`
- Stack []*big.Int `json:"stack"`
+ Stack []uint256.Int `json:"stack"`
ReturnData []byte `json:"returnData"`
Storage map[common.Hash]common.Hash `json:"-"`
Depth int `json:"depth"`
@@ -75,7 +76,6 @@ type StructLog struct {
// overrides for gencodec
type structLogMarshaling struct {
- Stack []*math.HexOrDecimal256
Gas math.HexOrDecimal64
GasCost math.HexOrDecimal64
Memory hexutil.Bytes
@@ -134,6 +134,14 @@ func NewStructLogger(cfg *LogConfig) *StructLogger {
return logger
}
+// Reset clears the data held by the logger.
+func (l *StructLogger) Reset() {
+ l.storage = make(map[common.Address]Storage)
+ l.output = make([]byte, 0)
+ l.logs = l.logs[:0]
+ l.err = nil
+}
+
// CaptureStart implements the Tracer interface to initialize the tracing operation.
func (l *StructLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
}
@@ -156,16 +164,16 @@ func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost ui
copy(mem, memory.Data())
}
// Copy a snapshot of the current stack state to a new buffer
- var stck []*big.Int
+ var stck []uint256.Int
if !l.cfg.DisableStack {
- stck = make([]*big.Int, len(stack.Data()))
+ stck = make([]uint256.Int, len(stack.Data()))
for i, item := range stack.Data() {
- stck[i] = new(big.Int).Set(item.ToBig())
+ stck[i] = item
}
}
// Copy a snapshot of the current storage to a new container
var storage Storage
- if !l.cfg.DisableStorage {
+ if !l.cfg.DisableStorage && (op == SLOAD || op == SSTORE) {
// initialise new changed values storage container for this contract
// if not present.
if l.storage[contract.Address()] == nil {
@@ -178,16 +186,16 @@ func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost ui
value = env.StateDB.GetState(contract.Address(), address)
)
l.storage[contract.Address()][address] = value
- }
- // capture SSTORE opcodes and record the written entry in the local storage.
- if op == SSTORE && stack.len() >= 2 {
+ storage = l.storage[contract.Address()].Copy()
+ } else if op == SSTORE && stack.len() >= 2 {
+ // capture SSTORE opcodes and record the written entry in the local storage.
var (
value = common.Hash(stack.data[stack.len()-2].Bytes32())
address = common.Hash(stack.data[stack.len()-1].Bytes32())
)
l.storage[contract.Address()][address] = value
+ storage = l.storage[contract.Address()].Copy()
}
- storage = l.storage[contract.Address()].Copy()
}
var rdata []byte
if !l.cfg.DisableReturnData {
@@ -196,7 +204,6 @@ func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost ui
}
// create a new snapshot of the EVM.
log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, env.StateDB.GetRefund(), err}
-
l.logs = append(l.logs, log)
}
@@ -226,6 +233,39 @@ func (l *StructLogger) Error() error { return l.err }
// Output returns the VM return value captured by the trace.
func (l *StructLogger) Output() []byte { return l.output }
+// WriteTrace writes a formatted trace to the given writer
+func WriteTrace(writer io.Writer, logs []StructLog) {
+ for _, log := range logs {
+ fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
+ if log.Err != nil {
+ fmt.Fprintf(writer, " ERROR: %v", log.Err)
+ }
+ fmt.Fprintln(writer)
+
+ if len(log.Stack) > 0 {
+ fmt.Fprintln(writer, "Stack:")
+ for i := len(log.Stack) - 1; i >= 0; i-- {
+ fmt.Fprintf(writer, "%08d %s\n", len(log.Stack)-i-1, log.Stack[i].Hex())
+ }
+ }
+ if len(log.Memory) > 0 {
+ fmt.Fprintln(writer, "Memory:")
+ fmt.Fprint(writer, hex.Dump(log.Memory))
+ }
+ if len(log.Storage) > 0 {
+ fmt.Fprintln(writer, "Storage:")
+ for h, item := range log.Storage {
+ fmt.Fprintf(writer, "%x: %x\n", h, item)
+ }
+ }
+ if len(log.ReturnData) > 0 {
+ fmt.Fprintln(writer, "ReturnData:")
+ fmt.Fprint(writer, hex.Dump(log.ReturnData))
+ }
+ fmt.Fprintln(writer)
+ }
+}
+
// WriteLogs writes vm logs in a readable format to the given writer
func WriteLogs(writer io.Writer, logs []*types.Log) {
for _, log := range logs {
@@ -281,7 +321,7 @@ func (t *mdLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64
// format stack
var a []string
for _, elem := range stack.data {
- a = append(a, fmt.Sprintf("%v", elem.String()))
+ a = append(a, elem.Hex())
}
b := fmt.Sprintf("[%v]", strings.Join(a, ","))
fmt.Fprintf(t.out, "%10v |", b)
diff --git a/core/vm/logger_json.go b/core/vm/logger_json.go
index aeb007f1c..60a546de3 100644
--- a/core/vm/logger_json.go
+++ b/core/vm/logger_json.go
@@ -66,12 +66,7 @@ func (l *JSONLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint
log.Memory = memory.Data()
}
if !l.cfg.DisableStack {
- //TODO(@holiman) improve this
- logstack := make([]*big.Int, len(stack.Data()))
- for i, item := range stack.Data() {
- logstack[i] = item.ToBig()
- }
- log.Stack = logstack
+ log.Stack = stack.data
}
if !l.cfg.DisableReturnData {
log.ReturnData = rData
@@ -87,8 +82,9 @@ func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration,
Time time.Duration `json:"time"`
Err string `json:"error,omitempty"`
}
+ var errMsg string
if err != nil {
- l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, err.Error()})
+ errMsg = err.Error()
}
- l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, ""})
+ l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), t, errMsg})
}
diff --git a/core/vm/logger_test.go b/core/vm/logger_test.go
index 02766199d..ab243a4c9 100644
--- a/core/vm/logger_test.go
+++ b/core/vm/logger_test.go
@@ -51,19 +51,22 @@ func (*dummyStatedb) GetRefund() uint64 { return 1337 }
func TestStoreCapture(t *testing.T) {
var (
- env = NewEVM(Context{}, &dummyStatedb{}, params.TestChainConfig, Config{})
+ env = NewEVM(BlockContext{}, TxContext{}, &dummyStatedb{}, params.TestChainConfig, Config{})
logger = NewStructLogger(nil)
- mem = NewMemory()
- stack = newstack()
- rstack = newReturnStack()
contract = NewContract(&dummyContractRef{}, &dummyContractRef{}, new(big.Int), 0)
+ scope = &ScopeContext{
+ Memory: NewMemory(),
+ Stack: newstack(),
+ Contract: contract,
+ }
)
- stack.push(uint256.NewInt().SetUint64(1))
- stack.push(uint256.NewInt())
+ scope.Stack.push(uint256.NewInt(1))
+ scope.Stack.push(new(uint256.Int))
var index common.Hash
- logger.CaptureState(env, 0, SSTORE, 0, 0, mem, stack, rstack, nil, contract, 0, nil)
+ logger.CaptureState(env, 0, SSTORE, 0, 0, scope, nil, 0, nil)
if len(logger.storage[contract.Address()]) == 0 {
- t.Fatalf("expected exactly 1 changed value on address %x, got %d", contract.Address(), len(logger.storage[contract.Address()]))
+ t.Fatalf("expected exactly 1 changed value on address %x, got %d", contract.Address(),
+ len(logger.storage[contract.Address()]))
}
exp := common.BigToHash(big.NewInt(1))
if logger.storage[contract.Address()][index] != exp {
diff --git a/core/vm/opcodes.go b/core/vm/opcodes.go
index b0adf37d0..286307ae9 100644
--- a/core/vm/opcodes.go
+++ b/core/vm/opcodes.go
@@ -103,6 +103,7 @@ const (
GASLIMIT
CHAINID OpCode = 0x46
SELFBALANCE OpCode = 0x47
+ BASEFEE OpCode = 0x48
)
// 0x50 range - 'storage' and execution.
@@ -280,6 +281,7 @@ var opCodeToString = map[OpCode]string{
GASLIMIT: "GASLIMIT",
CHAINID: "CHAINID",
SELFBALANCE: "SELFBALANCE",
+ BASEFEE: "BASEFEE",
// 0x50 range - 'storage' and execution.
POP: "POP",
@@ -432,6 +434,7 @@ var stringToOp = map[string]OpCode{
"CALLDATASIZE": CALLDATASIZE,
"CALLDATACOPY": CALLDATACOPY,
"CHAINID": CHAINID,
+ "BASEFEE": BASEFEE,
"DELEGATECALL": DELEGATECALL,
"STATICCALL": STATICCALL,
"CODESIZE": CODESIZE,
diff --git a/core/vm/operations_acl.go b/core/vm/operations_acl.go
index 886ba81ce..9e290def7 100644
--- a/core/vm/operations_acl.go
+++ b/core/vm/operations_acl.go
@@ -24,91 +24,75 @@ import (
"github.com/truechain/truechain-engineering-code/params"
)
-const (
- ColdAccountAccessCostEIP2929 = uint64(2600) // COLD_ACCOUNT_ACCESS_COST
- ColdSloadCostEIP2929 = uint64(2100) // COLD_SLOAD_COST
- WarmStorageReadCostEIP2929 = uint64(100) // WARM_STORAGE_READ_COST
-)
-
-// gasSStoreEIP2929 implements gas cost for SSTORE according to EIP-2929
-//
-// When calling SSTORE, check if the (address, storage_key) pair is in accessed_storage_keys.
-// If it is not, charge an additional COLD_SLOAD_COST gas, and add the pair to accessed_storage_keys.
-// Additionally, modify the parameters defined in EIP 2200 as follows:
-//
-// Parameter Old value New value
-// SLOAD_GAS 800 = WARM_STORAGE_READ_COST
-// SSTORE_RESET_GAS 5000 5000 - COLD_SLOAD_COST
-//
-//The other parameters defined in EIP 2200 are unchanged.
-// see gasSStoreEIP2200(...) in core/vm/gas_table.go for more info about how EIP 2200 is specified
-func gasSStoreEIP2929(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
- // If we fail the minimum gas availability invariant, fail (0)
- if contract.Gas <= params.SstoreSentryGasEIP2200 {
- return 0, errors.New("not enough gas for reentrancy sentry")
- }
- // Gas sentry honoured, do the actual gas calculation based on the stored value
- var (
- y, x = stack.Back(1), stack.peek()
- slot = common.Hash(x.Bytes32())
- current = evm.StateDB.GetState(contract.Address(), slot)
- cost = uint64(0)
- )
- // Check slot presence in the access list
- if addrPresent, slotPresent := evm.StateDB.SlotInAccessList(contract.Address(), slot); !slotPresent {
- cost = ColdSloadCostEIP2929
- // If the caller cannot afford the cost, this change will be rolled back
- evm.StateDB.AddSlotToAccessList(contract.Address(), slot)
- if !addrPresent {
- // Once we're done with YOLOv2 and schedule this for mainnet, might
- // be good to remove this panic here, which is just really a
- // canary to have during testing
- panic("impossible case: address was not present in access list during sstore op")
+func makeGasSStoreFunc(clearingRefund uint64) gasFunc {
+ return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
+ // If we fail the minimum gas availability invariant, fail (0)
+ if contract.Gas <= params.SstoreSentryGasEIP2200 {
+ return 0, errors.New("not enough gas for reentrancy sentry")
}
- }
- value := common.Hash(y.Bytes32())
+ // Gas sentry honoured, do the actual gas calculation based on the stored value
+ var (
+ y, x = stack.Back(1), stack.peek()
+ slot = common.Hash(x.Bytes32())
+ current = evm.StateDB.GetState(contract.Address(), slot)
+ cost = uint64(0)
+ )
+ // Check slot presence in the access list
+ if addrPresent, slotPresent := evm.StateDB.SlotInAccessList(contract.Address(), slot); !slotPresent {
+ cost = params.ColdSloadCostEIP2929
+ // If the caller cannot afford the cost, this change will be rolled back
+ evm.StateDB.AddSlotToAccessList(contract.Address(), slot)
+ if !addrPresent {
+ // Once we're done with YOLOv2 and schedule this for mainnet, might
+ // be good to remove this panic here, which is just really a
+ // canary to have during testing
+ panic("impossible case: address was not present in access list during sstore op")
+ }
+ }
+ value := common.Hash(y.Bytes32())
- if current == value { // noop (1)
- // EIP 2200 original clause:
- // return params.SloadGasEIP2200, nil
- return cost + WarmStorageReadCostEIP2929, nil // SLOAD_GAS
- }
- original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
- if original == current {
- if original == (common.Hash{}) { // create slot (2.1.1)
- return cost + params.SstoreSetGasEIP2200, nil
+ if current == value { // noop (1)
+ // EIP 2200 original clause:
+ // return params.SloadGasEIP2200, nil
+ return cost + params.WarmStorageReadCostEIP2929, nil // SLOAD_GAS
}
- if value == (common.Hash{}) { // delete slot (2.1.2b)
- evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
+ original := evm.StateDB.GetCommittedState(contract.Address(), x.Bytes32())
+ if original == current {
+ if original == (common.Hash{}) { // create slot (2.1.1)
+ return cost + params.SstoreSetGasEIP2200, nil
+ }
+ if value == (common.Hash{}) { // delete slot (2.1.2b)
+ evm.StateDB.AddRefund(clearingRefund)
+ }
+ // EIP-2200 original clause:
+ // return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
+ return cost + (params.SstoreResetGasEIP2200 - params.ColdSloadCostEIP2929), nil // write existing slot (2.1.2)
}
- // EIP-2200 original clause:
- // return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2)
- return cost + (params.SstoreResetGasEIP2200 - ColdSloadCostEIP2929), nil // write existing slot (2.1.2)
- }
- if original != (common.Hash{}) {
- if current == (common.Hash{}) { // recreate slot (2.2.1.1)
- evm.StateDB.SubRefund(params.SstoreClearsScheduleRefundEIP2200)
- } else if value == (common.Hash{}) { // delete slot (2.2.1.2)
- evm.StateDB.AddRefund(params.SstoreClearsScheduleRefundEIP2200)
+ if original != (common.Hash{}) {
+ if current == (common.Hash{}) { // recreate slot (2.2.1.1)
+ evm.StateDB.SubRefund(clearingRefund)
+ } else if value == (common.Hash{}) { // delete slot (2.2.1.2)
+ evm.StateDB.AddRefund(clearingRefund)
+ }
}
- }
- if original == value {
- if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
- // EIP 2200 Original clause:
- //evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
- evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - WarmStorageReadCostEIP2929)
- } else { // reset to original existing slot (2.2.2.2)
- // EIP 2200 Original clause:
- // evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)
- // - SSTORE_RESET_GAS redefined as (5000 - COLD_SLOAD_COST)
- // - SLOAD_GAS redefined as WARM_STORAGE_READ_COST
- // Final: (5000 - COLD_SLOAD_COST) - WARM_STORAGE_READ_COST
- evm.StateDB.AddRefund((params.SstoreResetGasEIP2200 - ColdSloadCostEIP2929) - WarmStorageReadCostEIP2929)
+ if original == value {
+ if original == (common.Hash{}) { // reset to original inexistent slot (2.2.2.1)
+ // EIP 2200 Original clause:
+ //evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200)
+ evm.StateDB.AddRefund(params.SstoreSetGasEIP2200 - params.WarmStorageReadCostEIP2929)
+ } else { // reset to original existing slot (2.2.2.2)
+ // EIP 2200 Original clause:
+ // evm.StateDB.AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200)
+ // - SSTORE_RESET_GAS redefined as (5000 - COLD_SLOAD_COST)
+ // - SLOAD_GAS redefined as WARM_STORAGE_READ_COST
+ // Final: (5000 - COLD_SLOAD_COST) - WARM_STORAGE_READ_COST
+ evm.StateDB.AddRefund((params.SstoreResetGasEIP2200 - params.ColdSloadCostEIP2929) - params.WarmStorageReadCostEIP2929)
+ }
}
+ // EIP-2200 original clause:
+ //return params.SloadGasEIP2200, nil // dirty update (2.2)
+ return cost + params.WarmStorageReadCostEIP2929, nil // dirty update (2.2)
}
- // EIP-2200 original clause:
- //return params.SloadGasEIP2200, nil // dirty update (2.2)
- return cost + WarmStorageReadCostEIP2929, nil // dirty update (2.2)
}
// gasSLoadEIP2929 calculates dynamic gas for SLOAD according to EIP-2929
@@ -124,9 +108,9 @@ func gasSLoadEIP2929(evm *EVM, contract *Contract, stack *Stack, mem *Memory, me
// If the caller cannot afford the cost, this change will be rolled back
// If he does afford it, we can skip checking the same thing later on, during execution
evm.StateDB.AddSlotToAccessList(contract.Address(), slot)
- return ColdSloadCostEIP2929, nil
+ return params.ColdSloadCostEIP2929, nil
}
- return WarmStorageReadCostEIP2929, nil
+ return params.WarmStorageReadCostEIP2929, nil
}
// gasExtCodeCopyEIP2929 implements extcodecopy according to EIP-2929
@@ -146,7 +130,7 @@ func gasExtCodeCopyEIP2929(evm *EVM, contract *Contract, stack *Stack, mem *Memo
evm.StateDB.AddAddressToAccessList(addr)
var overflow bool
// We charge (cold-warm), since 'warm' is already charged as constantGas
- if gas, overflow = math.SafeAdd(gas, ColdAccountAccessCostEIP2929-WarmStorageReadCostEIP2929); overflow {
+ if gas, overflow = math.SafeAdd(gas, params.ColdAccountAccessCostEIP2929-params.WarmStorageReadCostEIP2929); overflow {
return 0, ErrGasUintOverflow
}
return gas, nil
@@ -168,7 +152,7 @@ func gasEip2929AccountCheck(evm *EVM, contract *Contract, stack *Stack, mem *Mem
// If the caller cannot afford the cost, this change will be rolled back
evm.StateDB.AddAddressToAccessList(addr)
// The warm storage read cost is already charged as constantGas
- return ColdAccountAccessCostEIP2929 - WarmStorageReadCostEIP2929, nil
+ return params.ColdAccountAccessCostEIP2929 - params.WarmStorageReadCostEIP2929, nil
}
return 0, nil
}
@@ -180,7 +164,7 @@ func makeCallVariantGasCallEIP2929(oldCalculator gasFunc) gasFunc {
warmAccess := evm.StateDB.AddressInAccessList(addr)
// The WarmStorageReadCostEIP2929 (100) is already deducted in the form of a constant cost, so
// the cost to charge for cold access, if any, is Cold - Warm
- coldCost := ColdAccountAccessCostEIP2929 - WarmStorageReadCostEIP2929
+ coldCost := params.ColdAccountAccessCostEIP2929 - params.WarmStorageReadCostEIP2929
if !warmAccess {
evm.StateDB.AddAddressToAccessList(addr)
// Charge the remaining difference here already, to correctly calculate available
@@ -212,25 +196,49 @@ var (
gasDelegateCallEIP2929 = makeCallVariantGasCallEIP2929(gasDelegateCall)
gasStaticCallEIP2929 = makeCallVariantGasCallEIP2929(gasStaticCall)
gasCallCodeEIP2929 = makeCallVariantGasCallEIP2929(gasCallCode)
+ gasSelfdestructEIP2929 = makeSelfdestructGasFn(true)
+ // gasSelfdestructEIP3529 implements the changes in EIP-2539 (no refunds)
+ gasSelfdestructEIP3529 = makeSelfdestructGasFn(false)
+
+ // gasSStoreEIP2929 implements gas cost for SSTORE according to EIP-2929
+ //
+ // When calling SSTORE, check if the (address, storage_key) pair is in accessed_storage_keys.
+ // If it is not, charge an additional COLD_SLOAD_COST gas, and add the pair to accessed_storage_keys.
+ // Additionally, modify the parameters defined in EIP 2200 as follows:
+ //
+ // Parameter Old value New value
+ // SLOAD_GAS 800 = WARM_STORAGE_READ_COST
+ // SSTORE_RESET_GAS 5000 5000 - COLD_SLOAD_COST
+ //
+ //The other parameters defined in EIP 2200 are unchanged.
+ // see gasSStoreEIP2200(...) in core/vm/gas_table.go for more info about how EIP 2200 is specified
+ gasSStoreEIP2929 = makeGasSStoreFunc(params.SstoreClearsScheduleRefundEIP2200)
+
+ // gasSStoreEIP2539 implements gas cost for SSTORE according to EPI-2539
+ // Replace `SSTORE_CLEARS_SCHEDULE` with `SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST` (4,800)
+ gasSStoreEIP3529 = makeGasSStoreFunc(params.SstoreClearsScheduleRefundEIP3529)
)
-func gasSelfdestructEIP2929(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
- var (
- gas uint64
- address = common.Address(stack.peek().Bytes20())
- )
- if !evm.StateDB.AddressInAccessList(address) {
- // If the caller cannot afford the cost, this change will be rolled back
- evm.StateDB.AddAddressToAccessList(address)
- gas = ColdAccountAccessCostEIP2929
- }
- // if empty and transfers value
- if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
- gas += params.CreateBySelfdestructGas
- }
- if !evm.StateDB.HasSuicided(contract.Address()) {
- evm.StateDB.AddRefund(params.SelfdestructRefundGas)
+// makeSelfdestructGasFn can create the selfdestruct dynamic gas function for EIP-2929 and EIP-2539
+func makeSelfdestructGasFn(refundsEnabled bool) gasFunc {
+ gasFunc := func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
+ var (
+ gas uint64
+ address = common.Address(stack.peek().Bytes20())
+ )
+ if !evm.StateDB.AddressInAccessList(address) {
+ // If the caller cannot afford the cost, this change will be rolled back
+ evm.StateDB.AddAddressToAccessList(address)
+ gas = params.ColdAccountAccessCostEIP2929
+ }
+ // if empty and transfers value
+ if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
+ gas += params.CreateBySelfdestructGas
+ }
+ if refundsEnabled && !evm.StateDB.HasSuicided(contract.Address()) {
+ evm.StateDB.AddRefund(params.SelfdestructRefundGas)
+ }
+ return gas, nil
}
- return gas, nil
-
+ return gasFunc
}
diff --git a/core/vm/staking.go b/core/vm/staking.go
index d4ffb4b16..69847b3d8 100644
--- a/core/vm/staking.go
+++ b/core/vm/staking.go
@@ -107,7 +107,7 @@ func RunStaking(evm *EVM, contract *Contract, input []byte) (ret []byte, err err
}
if err != nil {
- log.Warn("Staking error code", "code", err)
+ log.Warn("Staking error code", "code", err, "method.Name", method.Name)
err = ErrExecutionReverted
}
@@ -145,12 +145,15 @@ func deposit(evm *EVM, contract *Contract, input []byte) (ret []byte, err error)
}{}
method, _ := abiStaking.Methods["deposit"]
- err = method.Inputs.Unpack(&args, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack deposit pubkey error", "err", err)
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&args, unpacked)
+ if err != nil {
+ return nil, err
+ }
from := contract.caller.Address()
if evm.StateDB.GetUnlockedBalance(from).Cmp(args.Value) < 0 {
log.Error("Staking balance insufficient", "address", contract.caller.Address(), "value", args.Value)
@@ -207,11 +210,15 @@ func depositAppend(evm *EVM, contract *Contract, input []byte) (ret []byte, err
amount := big.NewInt(0)
method, _ := abiStaking.Methods["append"]
- err = method.Inputs.Unpack(&amount, input)
+ unpack, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack append value error", "err", err)
return nil, ErrStakingInvalidInput
}
+ err = method.Inputs.Copy(&amount, unpack)
+ if err != nil {
+ return nil, err
+ }
if evm.StateDB.GetUnlockedBalance(from).Cmp(amount) < 0 {
log.Error("Staking balance insufficient", "address", contract.caller.Address(), "value", amount)
return nil, ErrStakingInsufficientBalance
@@ -256,12 +263,15 @@ func setFeeRate(evm *EVM, contract *Contract, input []byte) (ret []byte, err err
fee := big.NewInt(0)
method, _ := abiStaking.Methods["setFee"]
- err = method.Inputs.Unpack(&fee, input)
+ unpack, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack deposit pubkey error", "err", err)
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&fee, unpack)
+ if err != nil {
+ return nil, err
+ }
from := contract.caller.Address()
log.Info("Staking set fee", "number", evm.Context.BlockNumber.Uint64(), "address", contract.caller.Address(), "fee", fee)
@@ -302,12 +312,16 @@ func setPubkey(evm *EVM, contract *Contract, input []byte) (ret []byte, err erro
var pubkey []byte
method, _ := abiStaking.Methods["setPubkey"]
- err = method.Inputs.Unpack(&pubkey, input)
+
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack update pubkey error", "err", err)
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&pubkey, unpacked)
+ if err != nil {
+ return nil, err
+ }
from := contract.caller.Address()
log.Info("Staking set pubkey", "number", evm.Context.BlockNumber.Uint64(), "address", contract.caller.Address(), "pk", pubkey)
@@ -353,11 +367,15 @@ func delegate(evm *EVM, contract *Contract, input []byte) (ret []byte, err error
t0 := time.Now()
method, _ := abiStaking.Methods["delegate"]
- err = method.Inputs.Unpack(&args, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack deposit pubkey error", "err", err)
return nil, ErrStakingInvalidInput
}
+ err = method.Inputs.Copy(&args, unpacked)
+ if err != nil {
+ return nil, err
+ }
from := contract.caller.Address()
if evm.StateDB.GetUnlockedBalance(from).Cmp(args.Value) < 0 {
log.Error("Staking balance insufficient", "address", contract.caller.Address(), "value", args.Value)
@@ -417,11 +435,15 @@ func undelegate(evm *EVM, contract *Contract, input []byte) (ret []byte, err err
}{}
method, _ := abiStaking.Methods["undelegate"]
- err = method.Inputs.Unpack(&args, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack undelegate error", "err", err)
return nil, ErrStakingInvalidInput
}
+ err = method.Inputs.Copy(&args, unpacked)
+ if err != nil {
+ return nil, err
+ }
from := contract.caller.Address()
log.Info("Staking undelegate", "number", evm.Context.BlockNumber.Uint64(), "address", contract.caller.Address(), "holder", args.Holder, "value", args.Value)
@@ -464,12 +486,15 @@ func cancel(evm *EVM, contract *Contract, input []byte) (ret []byte, err error)
amount := new(big.Int)
method, _ := abiStaking.Methods["cancel"]
- err = method.Inputs.Unpack(&amount, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack cancel input error")
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&amount, unpacked)
+ if err != nil {
+ return nil, err
+ }
log.Info("Staking cancel", "number", evm.Context.BlockNumber.Uint64(), "address", contract.caller.Address(), "value", amount)
impawn := NewImpawnImpl()
err = impawn.Load(evm.StateDB, types.StakingAddress)
@@ -510,11 +535,15 @@ func withdraw(evm *EVM, contract *Contract, input []byte) (ret []byte, err error
amount := new(big.Int)
method, _ := abiStaking.Methods["withdraw"]
- err = method.Inputs.Unpack(&amount, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack withdraw input error")
return nil, ErrStakingInvalidInput
}
+ err = method.Inputs.Copy(&amount, unpacked)
+ if err != nil {
+ return nil, err
+ }
if evm.StateDB.GetPOSLocked(from).Cmp(amount) < 0 {
log.Error("Staking balance insufficient", "address", contract.caller.Address(), "value", amount)
return nil, ErrStakingInsufficientBalance
@@ -563,11 +592,15 @@ func withdrawDelegate(evm *EVM, contract *Contract, input []byte) (ret []byte, e
from := contract.caller.Address()
method, _ := abiStaking.Methods["withdrawDelegate"]
- err = method.Inputs.Unpack(&args, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack withdraw delegate input error")
return nil, ErrStakingInvalidInput
}
+ err = method.Inputs.Copy(&args, unpacked)
+ if err != nil {
+ return nil, err
+ }
if evm.StateDB.GetPOSLocked(from).Cmp(args.Value) < 0 {
log.Error("Staking balance insufficient", "address", contract.caller.Address(), "value", args.Value)
return nil, ErrStakingInsufficientBalance
@@ -614,12 +647,15 @@ func getLocked(evm *EVM, contract *Contract, input []byte) (ret []byte, err erro
var depositAddr common.Address
method, _ := abiStaking.Methods["lockedBalance"]
- err = method.Inputs.Unpack(&depositAddr, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack get_deposit input error")
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&depositAddr, unpacked)
+ if err != nil {
+ return nil, err
+ }
locked := evm.StateDB.GetPOSLocked(depositAddr)
ret, err = method.Outputs.Pack(locked)
@@ -636,12 +672,15 @@ func getDeposit(evm *EVM, contract *Contract, input []byte) (ret []byte, err err
unlocked = big.NewInt(0)
)
- err = method.Inputs.Unpack(&depositAddr, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack get_deposit input error")
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&depositAddr, unpacked)
+ if err != nil {
+ return nil, err
+ }
impawn := NewImpawnImpl()
err = impawn.Load(evm.StateDB, types.StakingAddress)
if err != nil {
@@ -683,12 +722,15 @@ func getDelegate(evm *EVM, contract *Contract, input []byte) (ret []byte, err er
unlocked = big.NewInt(0)
)
- err = method.Inputs.Unpack(&args, input)
+ unpacked, err := method.Inputs.Unpack(input)
if err != nil {
log.Error("Unpack get_deposit input error")
return nil, ErrStakingInvalidInput
}
-
+ err = method.Inputs.Copy(&args, unpacked)
+ if err != nil {
+ return nil, err
+ }
impawn := NewImpawnImpl()
err = impawn.Load(evm.StateDB, types.StakingAddress)
if err != nil {
diff --git a/internal/trueapi/api.go b/internal/trueapi/api.go
index 987abc62c..441710f5c 100644
--- a/internal/trueapi/api.go
+++ b/internal/trueapi/api.go
@@ -534,7 +534,7 @@ func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr c
return nil, err
}
// Assemble sign the data with the wallet
- signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data))
+ signature, err := wallet.SignTextWithPassphrase(account, passwd, signHash(data))
if err != nil {
return nil, err
}
@@ -607,10 +607,10 @@ func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
}
// GetBalance returns the amount of wei for the given address in the state of the
-// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
+// given block number or hash. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
// block numbers are also allowed.
-func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {
- state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
+func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
+ state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
@@ -618,10 +618,10 @@ func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Add
}
// GetLockBalance returns the amount of wei for the given address in pos state of the
-// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
+// given block number or hash. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
// block numbers are also allowed.
-func (s *PublicBlockChainAPI) GetLockBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {
- state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
+func (s *PublicBlockChainAPI) GetLockBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
+ state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
@@ -764,9 +764,9 @@ func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, bloc
return nil
}
-// GetCode returns the code stored at the given address in the state for the given block number.
-func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
- state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
+// GetCode returns the code stored at the given address in the state for the given block number or hash.
+func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
+ state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
@@ -775,10 +775,10 @@ func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Addres
}
// GetStorageAt returns the storage from the state at the given address, key and
-// block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
+// block number or hash. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
// numbers are also allowed.
-func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
- state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
+func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
+ state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
@@ -1026,7 +1026,7 @@ func FormatLogs(logs []vm.StructLog) []StructLogRes {
if trace.Stack != nil {
stack := make([]string, len(trace.Stack))
for i, stackValue := range trace.Stack {
- stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
+ stack[i] = stackValue.Hex()
}
formatted[index].Stack = &stack
}
@@ -1526,9 +1526,9 @@ func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx cont
return nil
}
-// GetTransactionCount returns the number of transactions the given address has sent for the given block number
-func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
- state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
+// GetTransactionCount returns the number of transactions the given address has sent for the given block number or hash
+func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
+ state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
@@ -1634,7 +1634,7 @@ func (s *PublicTransactionPoolAPI) sign_payment(addr common.Address, tx *types.T
return nil, err
}
// Request the wallet to sign the transaction
- return wallet.SignTx_Payment(account, tx, s.b.ChainConfig().ChainID)
+ return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
}
// SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
@@ -1850,7 +1850,7 @@ func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes)
return nil, err
}
// Sign the requested hash with the wallet
- signature, err := wallet.SignHash(account, signHash(data))
+ signature, err := wallet.SignText(account, signHash(data))
if err == nil {
signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
}
diff --git a/node/config.go b/node/config.go
index f9eecec7e..b8cd9d7f9 100644
--- a/node/config.go
+++ b/node/config.go
@@ -83,6 +83,9 @@ type Config struct {
// scrypt KDF at the expense of security.
UseLightweightKDF bool `toml:",omitempty"`
+ // InsecureUnlockAllowed allows user to unlock accounts in unsafe http environment.
+ InsecureUnlockAllowed bool `toml:",omitempty"`
+
// NoUSB disables hardware wallet monitoring and connectivity.
NoUSB bool `toml:",omitempty"`
@@ -428,13 +431,13 @@ func makeAccountManager(conf *Config) (*accounts.Manager, string, error) {
backends = append(backends, ledgerhub)
}
// Start a USB hub for Trezor hardware wallets
- if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
+ if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
} else {
backends = append(backends, trezorhub)
}
}
- return accounts.NewManager(backends...), ephemeral, nil
+ return accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: conf.InsecureUnlockAllowed}, backends...), ephemeral, nil
}
func (c *Config) BftCommitteeKey() *ecdsa.PrivateKey {
diff --git a/params/config.go b/params/config.go
index ae5676646..1b8a8a1da 100644
--- a/params/config.go
+++ b/params/config.go
@@ -246,13 +246,34 @@ type ChainConfig struct {
TIP3 *BlockConfig `json:"tip3"`
- TIP5 *BlockConfig `json:"tip5"`
- TIP7 *BlockConfig `json:"tip7"`
- TIP8 *BlockConfig `json:"tip8"`
- TIP9 *BlockConfig `json:"tip9"`
- TIP10 *BlockConfig `json:"tip10"`
- TIP11 *BlockConfig `json:"tip11"`
- TIP12 *BlockConfig `json:"tip12"`
+ TIP5 *BlockConfig `json:"tip5"`
+ TIP7 *BlockConfig `json:"tip7"`
+ TIP8 *BlockConfig `json:"tip8"`
+ TIP9 *BlockConfig `json:"tip9"`
+ TIP10 *BlockConfig `json:"tip10"`
+ TIP11 *BlockConfig `json:"tip11"`
+ TIP12 *BlockConfig `json:"tip12"`
+ HomesteadBlock *big.Int `json:"homesteadBlock,omitempty"` // Homestead switch block (nil = no fork, 0 = already homestead)
+
+ DAOForkBlock *big.Int `json:"daoForkBlock,omitempty"` // TheDAO hard-fork switch block (nil = no fork)
+ DAOForkSupport bool `json:"daoForkSupport,omitempty"` // Whether the nodes supports or opposes the DAO hard-fork
+
+ // EIP150 implements the Gas price changes (https://github.com/ethereum/EIPs/issues/150)
+ EIP150Block *big.Int `json:"eip150Block,omitempty"` // EIP150 HF block (nil = no fork)
+ EIP150Hash common.Hash `json:"eip150Hash,omitempty"` // EIP150 HF hash (needed for header only clients as only gas pricing changed)
+
+ EIP155Block *big.Int `json:"eip155Block,omitempty"` // EIP155 HF block
+ EIP158Block *big.Int `json:"eip158Block,omitempty"` // EIP158 HF block
+
+ ByzantiumBlock *big.Int `json:"byzantiumBlock,omitempty"` // Byzantium switch block (nil = no fork, 0 = already on byzantium)
+ ConstantinopleBlock *big.Int `json:"constantinopleBlock,omitempty"` // Constantinople switch block (nil = no fork, 0 = already activated)
+ PetersburgBlock *big.Int `json:"petersburgBlock,omitempty"` // Petersburg switch block (nil = same as Constantinople)
+ IstanbulBlock *big.Int `json:"istanbulBlock,omitempty"` // Istanbul switch block (nil = no fork, 0 = already on istanbul)
+ MuirGlacierBlock *big.Int `json:"muirGlacierBlock,omitempty"` // Eip-2384 (bomb delay) switch block (nil = no fork, 0 = already activated)
+ BerlinBlock *big.Int `json:"berlinBlock,omitempty"` // Berlin switch block (nil = no fork, 0 = already on berlin)
+ LondonBlock *big.Int `json:"londonBlock,omitempty"` // London switch block (nil = no fork, 0 = already on london)
+
+ CatalystBlock *big.Int `json:"catalystBlock,omitempty"` // Catalyst switch block (nil = no fork, 0 = already on catalyst)
TIPStake *BlockConfig `json:"tipstake"`
}
diff --git a/params/protocol_params.go b/params/protocol_params.go
index 210ae8fcc..20adbe867 100644
--- a/params/protocol_params.go
+++ b/params/protocol_params.go
@@ -32,7 +32,7 @@ const (
MaximumExtraDataSize uint64 = 32 // Maximum size extra data may be after Genesis.
ExpByteGas uint64 = 10 // Times ceil(log256(exponent)) for the EXP instruction.
- SloadGas uint64 = 50 // Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added.
+ SloadGasFrontier uint64 = 50 // Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added.
CallValueTransferGas uint64 = 9000 // Paid for CALL when the value transfer is non-zero.
CallNewAccountGas uint64 = 25000 // Paid for CALL when the destination address didn't exist prior.
TxGas uint64 = 21000 // Per transaction not creating a contract. NOTE: Not payable on data of calls between transactions.
@@ -68,6 +68,16 @@ const (
SstoreCleanRefundEIP2200 uint64 = 4200 // Once per SSTORE operation for resetting to the original non-zero value
SstoreClearsScheduleRefundEIP2200 uint64 = 15000 // Once per SSTORE operation for clearing an originally existing storage slot
+ ColdAccountAccessCostEIP2929 = uint64(2600) // COLD_ACCOUNT_ACCESS_COST
+ ColdSloadCostEIP2929 = uint64(2100) // COLD_SLOAD_COST
+ WarmStorageReadCostEIP2929 = uint64(100) // WARM_STORAGE_READ_COST
+
+ // In EIP-2200: SstoreResetGas was 5000.
+ // In EIP-2929: SstoreResetGas was changed to '5000 - COLD_SLOAD_COST'.
+ // In EIP-3529: SSTORE_CLEARS_SCHEDULE is defined as SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST
+ // Which becomes: 5000 - 2100 + 1900 = 4800
+ SstoreClearsScheduleRefundEIP3529 uint64 = SstoreResetGasEIP2200 - ColdSloadCostEIP2929 + TxAccessListStorageKeyGas
+
JumpdestGas uint64 = 1 // Once per JUMPDEST operation.
EpochDuration uint64 = 30000 // Duration between proof-of-work epochs. EpochDuration uint64 = 30000 // Duration between proof-of-work epochs.
@@ -83,30 +93,36 @@ const (
Create2Gas uint64 = 32000 // Once per CREATE2 operation Create2Gas uint64 = 32000 // Once per CREATE2 operation
SelfdestructRefundGas uint64 = 24000 // Refunded following a suicide operation. SelfdestructRefundGas uint64 = 24000 // Refunded following a selfdestruct operation.
MemoryGas uint64 = 3 // Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL. MemoryGas uint64 = 3 // Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL.
- TxDataNonZeroGas uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions. TxDataNonZeroGas uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions.
+
+ TxDataNonZeroGas uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions. TxDataNonZeroGas uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions.
+ TxDataNonZeroGasFrontier uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions.
+ TxDataNonZeroGasEIP2028 uint64 = 16 // Per byte of non zero data attached to a transaction after EIP 2028 (part in Istanbul)
+ TxAccessListAddressGas uint64 = 2400 // Per address specified in EIP 2930 access list
+ TxAccessListStorageKeyGas uint64 = 1900 // Per storage key specified in EIP 2930 access list
// These have been changed during the course of the chain
- CallGas uint64 = 40 // Once per CALL operation & message call transaction.
- CallGasEIP150 uint64 = 700 // Static portion of gas for CALL-derivates after EIP 150 (Tangerine)
- BalanceGas uint64 = 20 // The cost of a BALANCE operation
- BalanceGasEIP150 uint64 = 400 // The cost of a BALANCE operation after Tangerine
- BalanceGasEIP1884 uint64 = 700
- ExtcodeSizeGas uint64 = 20 // Cost of EXTCODESIZE before EIP 150 (Tangerine)
- ExtcodeSizeGasEIP150 uint64 = 700 // Cost of EXTCODESIZE after EIP 150 (Tangerine)
- SloadGasEIP150 uint64 = 200
- SloadGasEIP1884 uint64 = 800 // Cost of SLOAD after EIP 1884 (part of Istanbul)
- SloadGasEIP2200 uint64 = 800 // Cost of SLOAD after EIP 2200 (part of Istanbul)
- ExtcodeHashGas uint64 = 400 // Cost of EXTCODEHASH (introduced in Constantinople)
- ExtcodeHashGasEIP1884 uint64 = 700 // Cost of EXTCODEHASH (introduced in Constantinople)
- SelfdestructGasEIP150 uint64 = 5000 // Cost of SELFDESTRUCT post EIP 150 (Tangerine)
+ CallGasFrontier uint64 = 40 // Once per CALL operation & message call transaction.
+ CallGasEIP150 uint64 = 700 // Static portion of gas for CALL-derivates after EIP 150 (Tangerine)
+ BalanceGasFrontier uint64 = 20 // The cost of a BALANCE operation
+ BalanceGasEIP150 uint64 = 400 // The cost of a BALANCE operation after Tangerine
+ BalanceGasEIP1884 uint64 = 700
+ ExtcodeSizeGasFrontier uint64 = 20 // Cost of EXTCODESIZE before EIP 150 (Tangerine)
+ ExtcodeSizeGasEIP150 uint64 = 700 // Cost of EXTCODESIZE after EIP 150 (Tangerine)
+ SloadGasEIP150 uint64 = 200
+ SloadGasEIP1884 uint64 = 800 // Cost of SLOAD after EIP 1884 (part of Istanbul)
+ SloadGasEIP2200 uint64 = 800 // Cost of SLOAD after EIP 2200 (part of Istanbul)
+ ExtcodeHashGasConstantinople uint64 = 400 // Cost of EXTCODEHASH (introduced in Constantinople)
+ ExtcodeHashGasEIP1884 uint64 = 700 // Cost of EXTCODEHASH (introduced in Constantinople)
+ SelfdestructGasEIP150 uint64 = 5000 // Cost of SELFDESTRUCT post EIP 150 (Tangerine)
// EXP has a dynamic portion depending on the size of the exponent
- ExpByteEIP158 uint64 = 50 // was raised to 50 during Eip158 (Spurious Dragon)
+ ExpByteFrontier uint64 = 10 // was set to 10 in Frontier
+ ExpByteEIP158 uint64 = 50 // was raised to 50 during Eip158 (Spurious Dragon)
// Extcodecopy has a dynamic AND a static cost. This represents only the
// static portion of the gas. It was changed during EIP 150 (Tangerine)
- ExtcodeCopyBase uint64 = 20
- ExtcodeCopyBaseEIP150 uint64 = 700
+ ExtcodeCopyBaseFrontier uint64 = 20
+ ExtcodeCopyBaseEIP150 uint64 = 700
// CreateBySelfdestructGas is used when the refunded account is one that does
// not exist. This logic is similar to call.
diff --git a/rlp/decode.go b/rlp/decode.go
index dbbe59959..ac04d5d56 100644
--- a/rlp/decode.go
+++ b/rlp/decode.go
@@ -26,14 +26,16 @@ import (
"math/big"
"reflect"
"strings"
+ "sync"
)
-var (
- // EOL is returned when the end of the current list
- // has been reached during streaming.
- EOL = errors.New("rlp: end of list")
+//lint:ignore ST1012 EOL is not an error.
+
+// EOL is returned when the end of the current list
+// has been reached during streaming.
+var EOL = errors.New("rlp: end of list")
- // Actual Errors
+var (
ErrExpectedString = errors.New("rlp: expected String or Byte")
ErrExpectedList = errors.New("rlp: expected List")
ErrCanonInt = errors.New("rlp: non-canonical integer format")
@@ -48,95 +50,49 @@ var (
errUintOverflow = errors.New("rlp: uint overflow")
errNoPointer = errors.New("rlp: interface given to Decode must be a pointer")
errDecodeIntoNil = errors.New("rlp: pointer given to Decode must not be nil")
+
+ streamPool = sync.Pool{
+ New: func() interface{} { return new(Stream) },
+ }
)
-// Decoder is implemented by types that require custom RLP
-// decoding rules or need to decode into private fields.
+// Decoder is implemented by types that require custom RLP decoding rules or need to decode
+// into private fields.
//
-// The DecodeRLP method should read one value from the given
-// Stream. It is not forbidden to read less or more, but it might
-// be confusing.
+// The DecodeRLP method should read one value from the given Stream. It is not forbidden to
+// read less or more, but it might be confusing.
type Decoder interface {
DecodeRLP(*Stream) error
}
-// Decode parses RLP-encoded data from r and stores the result in the
-// value pointed to by val. Val must be a non-nil pointer. If r does
-// not implement ByteReader, Decode will do its own buffering.
-//
-// Decode uses the following type-dependent decoding rules:
-//
-// If the type implements the Decoder interface, decode calls
-// DecodeRLP.
-//
-// To decode into a pointer, Decode will decode into the value pointed
-// to. If the pointer is nil, a new value of the pointer's element
-// type is allocated. If the pointer is non-nil, the existing value
-// will be reused.
-//
-// To decode into a struct, Decode expects the input to be an RLP
-// list. The decoded elements of the list are assigned to each public
-// field in the order given by the struct's definition. The input list
-// must contain an element for each decoded field. Decode returns an
-// error if there are too few or too many elements.
-//
-// The decoding of struct fields honours certain struct tags, "tail",
-// "nil" and "-".
-//
-// The "-" tag ignores fields.
-//
-// For an explanation of "tail", see the example.
-//
-// The "nil" tag applies to pointer-typed fields and changes the decoding
-// rules for the field such that input values of size zero decode as a nil
-// pointer. This tag can be useful when decoding recursive types.
+// Decode parses RLP-encoded data from r and stores the result in the value pointed to by
+// val. Please see package-level documentation for the decoding rules. Val must be a
+// non-nil pointer.
//
-// type StructWithEmptyOK struct {
-// Foo *[20]byte `rlp:"nil"`
-// }
+// If r does not implement ByteReader, Decode will do its own buffering.
//
-// To decode into a slice, the input must be a list and the resulting
-// slice will contain the input elements in order. For byte slices,
-// the input must be an RLP string. Array types decode similarly, with
-// the additional restriction that the number of input elements (or
-// bytes) must match the array's length.
-//
-// To decode into a Go string, the input must be an RLP string. The
-// input bytes are taken as-is and will not necessarily be valid UTF-8.
-//
-// To decode into an unsigned integer type, the input must also be an RLP
-// string. The bytes are interpreted as a big endian representation of
-// the integer. If the RLP string is larger than the bit size of the
-// type, Decode will return an error. Decode also supports *big.Int.
-// There is no size limit for big integers.
-//
-// To decode into an interface value, Decode stores one of these
-// in the value:
-//
-// []interface{}, for RLP lists
-// []byte, for RLP strings
-//
-// Non-empty interface types are not supported, nor are booleans,
-// signed integers, floating point numbers, maps, channels and
-// functions.
-//
-// Note that Decode does not set an input limit for all readers
-// and may be vulnerable to panics cause by huge value sizes. If
-// you need an input limit, use
+// Note that Decode does not set an input limit for all readers and may be vulnerable to
+// panics cause by huge value sizes. If you need an input limit, use
//
// NewStream(r, limit).Decode(val)
func Decode(r io.Reader, val interface{}) error {
- // TODO: this could use a Stream from a pool.
- return NewStream(r, 0).Decode(val)
+ stream := streamPool.Get().(*Stream)
+ defer streamPool.Put(stream)
+
+ stream.Reset(r, 0)
+ return stream.Decode(val)
}
-// DecodeBytes parses RLP data from b into val.
-// Please see the documentation of Decode for the decoding rules.
-// The input must contain exactly one value and no trailing data.
+// DecodeBytes parses RLP data from b into val. Please see package-level documentation for
+// the decoding rules. The input must contain exactly one value and no trailing data.
func DecodeBytes(b []byte, val interface{}) error {
- // TODO: this could use a Stream from a pool.
r := bytes.NewReader(b)
- if err := NewStream(r, uint64(len(b))).Decode(val); err != nil {
+
+ stream := streamPool.Get().(*Stream)
+ defer streamPool.Put(stream)
+
+ stream.Reset(r, uint64(len(b)))
+ if err := stream.Decode(val); err != nil {
return err
}
if r.Len() > 0 {
@@ -197,14 +153,14 @@ func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
switch {
case typ == rawValueType:
return decodeRawValue, nil
- case typ.Implements(decoderInterface):
- return decodeDecoder, nil
- case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(decoderInterface):
- return decodeDecoderNoPtr, nil
case typ.AssignableTo(reflect.PtrTo(bigInt)):
return decodeBigInt, nil
case typ.AssignableTo(bigInt):
return decodeBigIntNoPtr, nil
+ case kind == reflect.Ptr:
+ return makePtrDecoder(typ, tags)
+ case reflect.PtrTo(typ).Implements(decoderInterface):
+ return decodeDecoder, nil
case isUint(kind):
return decodeUint, nil
case kind == reflect.Bool:
@@ -215,11 +171,6 @@ func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
return makeListDecoder(typ, tags)
case kind == reflect.Struct:
return makeStructDecoder(typ)
- case kind == reflect.Ptr:
- if tags.nilOK {
- return makeOptionalPtrDecoder(typ)
- }
- return makePtrDecoder(typ)
case kind == reflect.Interface:
return decodeInterface, nil
default:
@@ -269,20 +220,51 @@ func decodeBigIntNoPtr(s *Stream, val reflect.Value) error {
}
func decodeBigInt(s *Stream, val reflect.Value) error {
- b, err := s.Bytes()
- if err != nil {
+ var buffer []byte
+ kind, size, err := s.Kind()
+ switch {
+ case err != nil:
return wrapStreamError(err, val.Type())
+ case kind == List:
+ return wrapStreamError(ErrExpectedString, val.Type())
+ case kind == Byte:
+ buffer = s.uintbuf[:1]
+ buffer[0] = s.byteval
+ s.kind = -1 // re-arm Kind
+ case size == 0:
+ // Avoid zero-length read.
+ s.kind = -1
+ case size <= uint64(len(s.uintbuf)):
+ // For integers smaller than s.uintbuf, allocating a buffer
+ // can be avoided.
+ buffer = s.uintbuf[:size]
+ if err := s.readFull(buffer); err != nil {
+ return wrapStreamError(err, val.Type())
+ }
+ // Reject inputs where single byte encoding should have been used.
+ if size == 1 && buffer[0] < 128 {
+ return wrapStreamError(ErrCanonSize, val.Type())
+ }
+ default:
+ // For large integers, a temporary buffer is needed.
+ buffer = make([]byte, size)
+ if err := s.readFull(buffer); err != nil {
+ return wrapStreamError(err, val.Type())
+ }
+ }
+
+ // Reject leading zero bytes.
+ if len(buffer) > 0 && buffer[0] == 0 {
+ return wrapStreamError(ErrCanonInt, val.Type())
}
+
+ // Set the integer bytes.
i := val.Interface().(*big.Int)
if i == nil {
i = new(big.Int)
val.Set(reflect.ValueOf(i))
}
- // Reject leading zero bytes
- if len(b) > 0 && b[0] == 0 {
- return wrapStreamError(ErrCanonInt, val.Type())
- }
- i.SetBytes(b)
+ i.SetBytes(buffer)
return nil
}
@@ -294,9 +276,9 @@ func makeListDecoder(typ reflect.Type, tag tags) (decoder, error) {
}
return decodeByteSlice, nil
}
- etypeinfo, err := cachedTypeInfo1(etype, tags{})
- if err != nil {
- return nil, err
+ etypeinfo := theTC.infoWhileGenerating(etype, tags{})
+ if etypeinfo.decoderErr != nil {
+ return nil, etypeinfo.decoderErr
}
var dec decoder
switch {
@@ -397,25 +379,23 @@ func decodeByteArray(s *Stream, val reflect.Value) error {
if err != nil {
return err
}
- vlen := val.Len()
+ slice := byteArrayBytes(val)
switch kind {
case Byte:
- if vlen == 0 {
+ if len(slice) == 0 {
return &decodeError{msg: "input string too long", typ: val.Type()}
- }
- if vlen > 1 {
+ } else if len(slice) > 1 {
return &decodeError{msg: "input string too short", typ: val.Type()}
}
- bv, _ := s.Uint()
- val.Index(0).SetUint(bv)
+ slice[0] = s.byteval
+ s.kind = -1
case String:
- if uint64(vlen) < size {
+ if uint64(len(slice)) < size {
return &decodeError{msg: "input string too long", typ: val.Type()}
}
- if uint64(vlen) > size {
+ if uint64(len(slice)) > size {
return &decodeError{msg: "input string too short", typ: val.Type()}
}
- slice := val.Slice(0, vlen).Interface().([]byte)
if err := s.readFull(slice); err != nil {
return err
}
@@ -434,13 +414,25 @@ func makeStructDecoder(typ reflect.Type) (decoder, error) {
if err != nil {
return nil, err
}
+ for _, f := range fields {
+ if f.info.decoderErr != nil {
+ return nil, structFieldError{typ, f.index, f.info.decoderErr}
+ }
+ }
dec := func(s *Stream, val reflect.Value) (err error) {
if _, err := s.List(); err != nil {
return wrapStreamError(err, typ)
}
- for _, f := range fields {
+ for i, f := range fields {
err := f.info.decoder(s, val.Field(f.index))
if err == EOL {
+ if f.optional {
+ // The field is optional, so reaching the end of the list before
+ // reaching the last field is acceptable. All remaining undecoded
+ // fields are zeroed.
+ zeroFields(val, fields[i:])
+ break
+ }
return &decodeError{msg: "too few elements", typ: typ}
} else if err != nil {
return addErrorContext(err, "."+typ.Field(f.index).Name)
@@ -451,15 +443,29 @@ func makeStructDecoder(typ reflect.Type) (decoder, error) {
return dec, nil
}
-// makePtrDecoder creates a decoder that decodes into
-// the pointer's element type.
-func makePtrDecoder(typ reflect.Type) (decoder, error) {
+func zeroFields(structval reflect.Value, fields []field) {
+ for _, f := range fields {
+ fv := structval.Field(f.index)
+ fv.Set(reflect.Zero(fv.Type()))
+ }
+}
+
+// makePtrDecoder creates a decoder that decodes into the pointer's element type.
+func makePtrDecoder(typ reflect.Type, tag tags) (decoder, error) {
etype := typ.Elem()
- etypeinfo, err := cachedTypeInfo1(etype, tags{})
- if err != nil {
- return nil, err
+ etypeinfo := theTC.infoWhileGenerating(etype, tags{})
+ switch {
+ case etypeinfo.decoderErr != nil:
+ return nil, etypeinfo.decoderErr
+ case !tag.nilOK:
+ return makeSimplePtrDecoder(etype, etypeinfo), nil
+ default:
+ return makeNilPtrDecoder(etype, etypeinfo, tag.nilKind), nil
}
- dec := func(s *Stream, val reflect.Value) (err error) {
+}
+
+func makeSimplePtrDecoder(etype reflect.Type, etypeinfo *typeinfo) decoder {
+ return func(s *Stream, val reflect.Value) (err error) {
newval := val
if val.IsNil() {
newval = reflect.New(etype)
@@ -469,30 +475,35 @@ func makePtrDecoder(typ reflect.Type) (decoder, error) {
}
return err
}
- return dec, nil
}
-// makeOptionalPtrDecoder creates a decoder that decodes empty values
-// as nil. Non-empty values are decoded into a value of the element type,
-// just like makePtrDecoder does.
+// makeNilPtrDecoder creates a decoder that decodes empty values as nil. Non-empty
+// values are decoded into a value of the element type, just like makePtrDecoder does.
//
// This decoder is used for pointer-typed struct fields with struct tag "nil".
-func makeOptionalPtrDecoder(typ reflect.Type) (decoder, error) {
- etype := typ.Elem()
- etypeinfo, err := cachedTypeInfo1(etype, tags{})
- if err != nil {
- return nil, err
- }
- dec := func(s *Stream, val reflect.Value) (err error) {
+func makeNilPtrDecoder(etype reflect.Type, etypeinfo *typeinfo, nilKind Kind) decoder {
+ typ := reflect.PtrTo(etype)
+ nilPtr := reflect.Zero(typ)
+ return func(s *Stream, val reflect.Value) (err error) {
kind, size, err := s.Kind()
- if err != nil || size == 0 && kind != Byte {
+ if err != nil {
+ val.Set(nilPtr)
+ return wrapStreamError(err, typ)
+ }
+ // Handle empty values as a nil pointer.
+ if kind != Byte && size == 0 {
+ if kind != nilKind {
+ return &decodeError{
+ msg: fmt.Sprintf("wrong kind of empty value (got %v, want %v)", kind, nilKind),
+ typ: typ,
+ }
+ }
// rearm s.Kind. This is important because the input
// position must advance to the next value even though
// we don't read anything.
s.kind = -1
- // set the pointer to nil.
- val.Set(reflect.Zero(typ))
- return err
+ val.Set(nilPtr)
+ return nil
}
newval := val
if val.IsNil() {
@@ -503,7 +514,6 @@ func makeOptionalPtrDecoder(typ reflect.Type) (decoder, error) {
}
return err
}
- return dec, nil
}
var ifsliceType = reflect.TypeOf([]interface{}{})
@@ -532,25 +542,12 @@ func decodeInterface(s *Stream, val reflect.Value) error {
return nil
}
-// This decoder is used for non-pointer values of types
-// that implement the Decoder interface using a pointer receiver.
-func decodeDecoderNoPtr(s *Stream, val reflect.Value) error {
- return val.Addr().Interface().(Decoder).DecodeRLP(s)
-}
-
func decodeDecoder(s *Stream, val reflect.Value) error {
- // Decoder instances are not handled using the pointer rule if the type
- // implements Decoder with pointer receiver (i.e. always)
- // because it might handle empty values specially.
- // We need to allocate one here in this case, like makePtrDecoder does.
- if val.Kind() == reflect.Ptr && val.IsNil() {
- val.Set(reflect.New(val.Type().Elem()))
- }
- return val.Interface().(Decoder).DecodeRLP(s)
+ return val.Addr().Interface().(Decoder).DecodeRLP(s)
}
// Kind represents the kind of value contained in an RLP stream.
-type Kind int
+type Kind int8
const (
Byte Kind = iota
@@ -593,22 +590,16 @@ type ByteReader interface {
type Stream struct {
r ByteReader
- // number of bytes remaining to be read from r.
- remaining uint64
- limited bool
-
- // auxiliary buffer for integer decoding
- uintbuf []byte
-
- kind Kind // kind of value ahead
- size uint64 // size of value ahead
- byteval byte // value of single byte in type tag
- kinderr error // error from last readKind
- stack []listpos
+ remaining uint64 // number of bytes remaining to be read from r
+ size uint64 // size of value ahead
+ kinderr error // error from last readKind
+ stack []uint64 // list sizes
+ uintbuf [32]byte // auxiliary buffer for integer decoding
+ kind Kind // kind of value ahead
+ byteval byte // value of single byte in type tag
+ limited bool // true if input limit is in effect
}
-type listpos struct{ pos, size uint64 }
-
// NewStream creates a new decoding stream reading from r.
//
// If r implements the ByteReader interface, Stream will
@@ -678,8 +669,8 @@ func (s *Stream) Raw() ([]byte, error) {
s.kind = -1 // rearm Kind
return []byte{s.byteval}, nil
}
- // the original header has already been read and is no longer
- // available. read content and put a new header in front of it.
+ // The original header has already been read and is no longer
+ // available. Read content and put a new header in front of it.
start := headsize(size)
buf := make([]byte, uint64(start)+size)
if err := s.readFull(buf[start:]); err != nil {
@@ -762,7 +753,14 @@ func (s *Stream) List() (size uint64, err error) {
if kind != List {
return 0, ErrExpectedList
}
- s.stack = append(s.stack, listpos{0, size})
+
+ // Remove size of inner list from outer list before pushing the new size
+ // onto the stack. This ensures that the remaining outer list size will
+ // be correct after the matching call to ListEnd.
+ if inList, limit := s.listLimit(); inList {
+ s.stack[len(s.stack)-1] = limit - size
+ }
+ s.stack = append(s.stack, size)
s.kind = -1
s.size = 0
return size, nil
@@ -771,17 +769,13 @@ func (s *Stream) List() (size uint64, err error) {
// ListEnd returns to the enclosing list.
// The input reader must be positioned at the end of a list.
func (s *Stream) ListEnd() error {
- if len(s.stack) == 0 {
+ // Ensure that no more data is remaining in the current list.
+ if inList, listLimit := s.listLimit(); !inList {
return errNotInList
- }
- tos := s.stack[len(s.stack)-1]
- if tos.pos != tos.size {
+ } else if listLimit > 0 {
return errNotAtEOL
}
s.stack = s.stack[:len(s.stack)-1] // pop
- if len(s.stack) > 0 {
- s.stack[len(s.stack)-1].pos += tos.size
- }
s.kind = -1
s.size = 0
return nil
@@ -802,14 +796,14 @@ func (s *Stream) Decode(val interface{}) error {
if rval.IsNil() {
return errDecodeIntoNil
}
- info, err := cachedTypeInfo(rtyp.Elem(), tags{})
+ decoder, err := cachedDecoder(rtyp.Elem())
if err != nil {
return err
}
- err = info.decoder(s, rval.Elem())
+ err = decoder(s, rval.Elem())
if decErr, ok := err.(*decodeError); ok && len(decErr.ctx) > 0 {
- // add decode target type to error so context has more meaning
+ // Add decode target type to error so context has more meaning.
decErr.ctx = append(decErr.ctx, fmt.Sprint("(", rtyp.Elem(), ")"))
}
return err
@@ -832,6 +826,9 @@ func (s *Stream) Reset(r io.Reader, inputLimit uint64) {
case *bytes.Reader:
s.remaining = uint64(br.Len())
s.limited = true
+ case *bytes.Buffer:
+ s.remaining = uint64(br.Len())
+ s.limited = true
case *strings.Reader:
s.remaining = uint64(br.Len())
s.limited = true
@@ -850,9 +847,8 @@ func (s *Stream) Reset(r io.Reader, inputLimit uint64) {
s.size = 0
s.kind = -1
s.kinderr = nil
- if s.uintbuf == nil {
- s.uintbuf = make([]byte, 8)
- }
+ s.byteval = 0
+ s.uintbuf = [32]byte{}
}
// Kind returns the kind and size of the next value in the
@@ -867,35 +863,29 @@ func (s *Stream) Reset(r io.Reader, inputLimit uint64) {
// the value. Subsequent calls to Kind (until the value is decoded)
// will not advance the input reader and return cached information.
func (s *Stream) Kind() (kind Kind, size uint64, err error) {
- var tos *listpos
- if len(s.stack) > 0 {
- tos = &s.stack[len(s.stack)-1]
- }
- if s.kind < 0 {
- s.kinderr = nil
- // Don't read further if we're at the end of the
- // innermost list.
- if tos != nil && tos.pos == tos.size {
- return 0, 0, EOL
- }
- s.kind, s.size, s.kinderr = s.readKind()
- if s.kinderr == nil {
- if tos == nil {
- // At toplevel, check that the value is smaller
- // than the remaining input length.
- if s.limited && s.size > s.remaining {
- s.kinderr = ErrValueTooLarge
- }
- } else {
- // Inside a list, check that the value doesn't overflow the list.
- if s.size > tos.size-tos.pos {
- s.kinderr = ErrElemTooLarge
- }
- }
+ if s.kind >= 0 {
+ return s.kind, s.size, s.kinderr
+ }
+
+ // Check for end of list. This needs to be done here because readKind
+ // checks against the list size, and would return the wrong error.
+ inList, listLimit := s.listLimit()
+ if inList && listLimit == 0 {
+ return 0, 0, EOL
+ }
+ // Read the actual size tag.
+ s.kind, s.size, s.kinderr = s.readKind()
+ if s.kinderr == nil {
+ // Check the data size of the value ahead against input limits. This
+ // is done here because many decoders require allocating an input
+ // buffer matching the value size. Checking it here protects those
+ // decoders from inputs declaring very large value size.
+ if inList && s.size > listLimit {
+ s.kinderr = ErrElemTooLarge
+ } else if s.limited && s.size > s.remaining {
+ s.kinderr = ErrValueTooLarge
}
}
- // Note: this might return a sticky error generated
- // by an earlier call to readKind.
return s.kind, s.size, s.kinderr
}
@@ -922,37 +912,35 @@ func (s *Stream) readKind() (kind Kind, size uint64, err error) {
s.byteval = b
return Byte, 0, nil
case b < 0xB8:
- // Otherwise, if a string is 0-55 bytes long,
- // the RLP encoding consists of a single byte with value 0x80 plus the
- // length of the string followed by the string. The range of the first
- // byte is thus [0x80, 0xB7].
+ // Otherwise, if a string is 0-55 bytes long, the RLP encoding consists
+ // of a single byte with value 0x80 plus the length of the string
+ // followed by the string. The range of the first byte is thus [0x80, 0xB7].
return String, uint64(b - 0x80), nil
case b < 0xC0:
- // If a string is more than 55 bytes long, the
- // RLP encoding consists of a single byte with value 0xB7 plus the length
- // of the length of the string in binary form, followed by the length of
- // the string, followed by the string. For example, a length-1024 string
- // would be encoded as 0xB90400 followed by the string. The range of
- // the first byte is thus [0xB8, 0xBF].
+ // If a string is more than 55 bytes long, the RLP encoding consists of a
+ // single byte with value 0xB7 plus the length of the length of the
+ // string in binary form, followed by the length of the string, followed
+ // by the string. For example, a length-1024 string would be encoded as
+ // 0xB90400 followed by the string. The range of the first byte is thus
+ // [0xB8, 0xBF].
size, err = s.readUint(b - 0xB7)
if err == nil && size < 56 {
err = ErrCanonSize
}
return String, size, err
case b < 0xF8:
- // If the total payload of a list
- // (i.e. the combined length of all its items) is 0-55 bytes long, the
- // RLP encoding consists of a single byte with value 0xC0 plus the length
- // of the list followed by the concatenation of the RLP encodings of the
- // items. The range of the first byte is thus [0xC0, 0xF7].
+ // If the total payload of a list (i.e. the combined length of all its
+ // items) is 0-55 bytes long, the RLP encoding consists of a single byte
+ // with value 0xC0 plus the length of the list followed by the
+ // concatenation of the RLP encodings of the items. The range of the
+ // first byte is thus [0xC0, 0xF7].
return List, uint64(b - 0xC0), nil
default:
- // If the total payload of a list is more than 55 bytes long,
- // the RLP encoding consists of a single byte with value 0xF7
- // plus the length of the length of the payload in binary
- // form, followed by the length of the payload, followed by
- // the concatenation of the RLP encodings of the items. The
- // range of the first byte is thus [0xF8, 0xFF].
+ // If the total payload of a list is more than 55 bytes long, the RLP
+ // encoding consists of a single byte with value 0xF7 plus the length of
+ // the length of the payload in binary form, followed by the length of
+ // the payload, followed by the concatenation of the RLP encodings of
+ // the items. The range of the first byte is thus [0xF8, 0xFF].
size, err = s.readUint(b - 0xF7)
if err == nil && size < 56 {
err = ErrCanonSize
@@ -970,23 +958,24 @@ func (s *Stream) readUint(size byte) (uint64, error) {
b, err := s.readByte()
return uint64(b), err
default:
- start := int(8 - size)
- for i := 0; i < start; i++ {
- s.uintbuf[i] = 0
+ buffer := s.uintbuf[:8]
+ for i := range buffer {
+ buffer[i] = 0
}
- if err := s.readFull(s.uintbuf[start:]); err != nil {
+ start := int(8 - size)
+ if err := s.readFull(buffer[start:]); err != nil {
return 0, err
}
- if s.uintbuf[start] == 0 {
- // Note: readUint is also used to decode integer
- // values. The error needs to be adjusted to become
- // ErrCanonInt in this case.
+ if buffer[start] == 0 {
+ // Note: readUint is also used to decode integer values.
+ // The error needs to be adjusted to become ErrCanonInt in this case.
return 0, ErrCanonSize
}
- return binary.BigEndian.Uint64(s.uintbuf), nil
+ return binary.BigEndian.Uint64(buffer[:]), nil
}
}
+// readFull reads into buf from the underlying stream.
func (s *Stream) readFull(buf []byte) (err error) {
if err := s.willRead(uint64(len(buf))); err != nil {
return err
@@ -997,11 +986,18 @@ func (s *Stream) readFull(buf []byte) (err error) {
n += nn
}
if err == io.EOF {
- err = io.ErrUnexpectedEOF
+ if n < len(buf) {
+ err = io.ErrUnexpectedEOF
+ } else {
+ // Readers are allowed to give EOF even though the read succeeded.
+ // In such cases, we discard the EOF, like io.ReadFull() does.
+ err = nil
+ }
}
return err
}
+// readByte reads a single byte from the underlying stream.
func (s *Stream) readByte() (byte, error) {
if err := s.willRead(1); err != nil {
return 0, err
@@ -1013,16 +1009,16 @@ func (s *Stream) readByte() (byte, error) {
return b, err
}
+// willRead is called before any read from the underlying stream. It checks
+// n against size limits, and updates the limits if n doesn't overflow them.
func (s *Stream) willRead(n uint64) error {
s.kind = -1 // rearm Kind
- if len(s.stack) > 0 {
- // check list overflow
- tos := s.stack[len(s.stack)-1]
- if n > tos.size-tos.pos {
+ if inList, limit := s.listLimit(); inList {
+ if n > limit {
return ErrElemTooLarge
}
- s.stack[len(s.stack)-1].pos += n
+ s.stack[len(s.stack)-1] = limit - n
}
if s.limited {
if n > s.remaining {
@@ -1032,3 +1028,11 @@ func (s *Stream) willRead(n uint64) error {
}
return nil
}
+
+// listLimit returns the amount of data remaining in the innermost list.
+func (s *Stream) listLimit() (inList bool, limit uint64) {
+ if len(s.stack) == 0 {
+ return false, 0
+ }
+ return true, s.stack[len(s.stack)-1]
+}
diff --git a/rlp/encode.go b/rlp/encode.go
index 445b4b5b2..334864434 100644
--- a/rlp/encode.go
+++ b/rlp/encode.go
@@ -49,34 +49,7 @@ type Encoder interface {
// perform many small writes in some cases. Consider making w
// buffered.
//
-// Encode uses the following type-dependent encoding rules:
-//
-// If the type implements the Encoder interface, Encode calls
-// EncodeRLP. This is true even for nil pointers, please see the
-// documentation for Encoder.
-//
-// To encode a pointer, the value being pointed to is encoded. For nil
-// pointers, Encode will encode the zero value of the type. A nil
-// pointer to a struct type always encodes as an empty RLP list.
-// A nil pointer to an array encodes as an empty list (or empty string
-// if the array has element type byte).
-//
-// Struct values are encoded as an RLP list of all their encoded
-// public fields. Recursive struct types are supported.
-//
-// To encode slices and arrays, the elements are encoded as an RLP
-// list of the value's elements. Note that arrays and slices with
-// element type uint8 or byte are always encoded as an RLP string.
-//
-// A Go string is encoded as an RLP string.
-//
-// An unsigned integer value is encoded as an RLP string. Zero always
-// encodes as an empty RLP string. Encode also supports *big.Int.
-//
-// An interface value encodes as the value contained in the interface.
-//
-// Boolean values are not supported, nor are signed integers, floating
-// point numbers, maps, channels and functions.
+// Please see package-level documentation of encoding rules.
func Encode(w io.Writer, val interface{}) error {
if outer, ok := w.(*encbuf); ok {
// Encode was called by some type's EncodeRLP.
@@ -93,7 +66,7 @@ func Encode(w io.Writer, val interface{}) error {
}
// EncodeToBytes returns the RLP encoding of val.
-// Please see the documentation of Encode for the encoding rules.
+// Please see package-level documentation for the encoding rules.
func EncodeToBytes(val interface{}) ([]byte, error) {
eb := encbufPool.Get().(*encbuf)
defer encbufPool.Put(eb)
@@ -118,13 +91,6 @@ func EncodeToReader(val interface{}) (size int, r io.Reader, err error) {
return eb.size(), &encReader{buf: eb}, nil
}
-type encbuf struct {
- str []byte // string data, contains everything except list headers
- lheads []*listhead // all list headers
- lhsize int // sum of sizes of all encoded list headers
- sizebuf []byte // 9-byte auxiliary buffer for uint encoding
-}
-
type listhead struct {
offset int // index of this header in string data
size int // total size of encoded data (including list headers)
@@ -157,19 +123,22 @@ func puthead(buf []byte, smalltag, largetag byte, size uint64) int {
return sizesize + 1
}
+type encbuf struct {
+ str []byte // string data, contains everything except list headers
+ lheads []listhead // all list headers
+ lhsize int // sum of sizes of all encoded list headers
+ sizebuf [9]byte // auxiliary buffer for uint encoding
+}
+
// encbufs are pooled.
var encbufPool = sync.Pool{
- New: func() interface{} { return &encbuf{sizebuf: make([]byte, 9)} },
+ New: func() interface{} { return new(encbuf) },
}
func (w *encbuf) reset() {
w.lhsize = 0
- if w.str != nil {
- w.str = w.str[:0]
- }
- if w.lheads != nil {
- w.lheads = w.lheads[:0]
- }
+ w.str = w.str[:0]
+ w.lheads = w.lheads[:0]
}
// encbuf implements io.Writer so it can be passed it into EncodeRLP.
@@ -180,18 +149,17 @@ func (w *encbuf) Write(b []byte) (int, error) {
func (w *encbuf) encode(val interface{}) error {
rval := reflect.ValueOf(val)
- ti, err := cachedTypeInfo(rval.Type(), tags{})
+ writer, err := cachedWriter(rval.Type())
if err != nil {
return err
}
- return ti.writer(rval, w)
+ return writer(rval, w)
}
func (w *encbuf) encodeStringHeader(size int) {
if size < 56 {
w.str = append(w.str, 0x80+byte(size))
} else {
- // TODO: encode to w.str directly
sizesize := putint(w.sizebuf[1:], uint64(size))
w.sizebuf[0] = 0xB7 + byte(sizesize)
w.str = append(w.str, w.sizebuf[:sizesize+1]...)
@@ -208,13 +176,29 @@ func (w *encbuf) encodeString(b []byte) {
}
}
-func (w *encbuf) list() *listhead {
- lh := &listhead{offset: len(w.str), size: w.lhsize}
- w.lheads = append(w.lheads, lh)
- return lh
+func (w *encbuf) encodeUint(i uint64) {
+ if i == 0 {
+ w.str = append(w.str, 0x80)
+ } else if i < 128 {
+ // fits single byte
+ w.str = append(w.str, byte(i))
+ } else {
+ s := putint(w.sizebuf[1:], i)
+ w.sizebuf[0] = 0x80 + byte(s)
+ w.str = append(w.str, w.sizebuf[:s+1]...)
+ }
}
-func (w *encbuf) listEnd(lh *listhead) {
+// list adds a new list header to the header stack. It returns the index
+// of the header. The caller must call listEnd with this index after encoding
+// the content of the list.
+func (w *encbuf) list() int {
+ w.lheads = append(w.lheads, listhead{offset: len(w.str), size: w.lhsize})
+ return len(w.lheads) - 1
+}
+
+func (w *encbuf) listEnd(index int) {
+ lh := &w.lheads[index]
lh.size = w.size() - lh.offset - lh.size
if lh.size < 56 {
w.lhsize++ // length encoded into kind tag
@@ -257,7 +241,7 @@ func (w *encbuf) toWriter(out io.Writer) (err error) {
}
}
// write the header
- enc := head.encode(w.sizebuf)
+ enc := head.encode(w.sizebuf[:])
if _, err = out.Write(enc); err != nil {
return err
}
@@ -323,7 +307,7 @@ func (r *encReader) next() []byte {
return p
}
r.lhpos++
- return head.encode(r.buf.sizebuf)
+ return head.encode(r.buf.sizebuf[:])
case r.strpos < len(r.buf.str):
// String data at the end, after all list headers.
@@ -336,10 +320,7 @@ func (r *encReader) next() []byte {
}
}
-var (
- encoderInterface = reflect.TypeOf(new(Encoder)).Elem()
- big0 = big.NewInt(0)
-)
+var encoderInterface = reflect.TypeOf(new(Encoder)).Elem()
// makeWriter creates a writer function for the given type.
func makeWriter(typ reflect.Type, ts tags) (writer, error) {
@@ -347,16 +328,14 @@ func makeWriter(typ reflect.Type, ts tags) (writer, error) {
switch {
case typ == rawValueType:
return writeRawValue, nil
- case typ.Implements(encoderInterface):
- return writeEncoder, nil
- case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(encoderInterface):
- return writeEncoderNoPtr, nil
- case kind == reflect.Interface:
- return writeInterface, nil
case typ.AssignableTo(reflect.PtrTo(bigInt)):
return writeBigIntPtr, nil
case typ.AssignableTo(bigInt):
return writeBigIntNoPtr, nil
+ case kind == reflect.Ptr:
+ return makePtrWriter(typ, ts)
+ case reflect.PtrTo(typ).Implements(encoderInterface):
+ return makeEncoderWriter(typ), nil
case isUint(kind):
return writeUint, nil
case kind == reflect.Bool:
@@ -366,40 +345,25 @@ func makeWriter(typ reflect.Type, ts tags) (writer, error) {
case kind == reflect.Slice && isByte(typ.Elem()):
return writeBytes, nil
case kind == reflect.Array && isByte(typ.Elem()):
- return writeByteArray, nil
+ return makeByteArrayWriter(typ), nil
case kind == reflect.Slice || kind == reflect.Array:
return makeSliceWriter(typ, ts)
case kind == reflect.Struct:
return makeStructWriter(typ)
- case kind == reflect.Ptr:
- return makePtrWriter(typ)
+ case kind == reflect.Interface:
+ return writeInterface, nil
default:
return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
}
}
-func isByte(typ reflect.Type) bool {
- return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
-}
-
func writeRawValue(val reflect.Value, w *encbuf) error {
w.str = append(w.str, val.Bytes()...)
return nil
}
func writeUint(val reflect.Value, w *encbuf) error {
- i := val.Uint()
- if i == 0 {
- w.str = append(w.str, 0x80)
- } else if i < 128 {
- // fits single byte
- w.str = append(w.str, byte(i))
- } else {
- // TODO: encode int to w.str directly
- s := putint(w.sizebuf[1:], i)
- w.sizebuf[0] = 0x80 + byte(s)
- w.str = append(w.str, w.sizebuf[:s+1]...)
- }
+ w.encodeUint(val.Uint())
return nil
}
@@ -426,13 +390,32 @@ func writeBigIntNoPtr(val reflect.Value, w *encbuf) error {
return writeBigInt(&i, w)
}
+// wordBytes is the number of bytes in a big.Word
+const wordBytes = (32 << (uint64(^big.Word(0)) >> 63)) / 8
+
func writeBigInt(i *big.Int, w *encbuf) error {
- if cmp := i.Cmp(big0); cmp == -1 {
+ if i.Sign() == -1 {
return fmt.Errorf("rlp: cannot encode negative *big.Int")
- } else if cmp == 0 {
- w.str = append(w.str, 0x80)
- } else {
- w.encodeString(i.Bytes())
+ }
+ bitlen := i.BitLen()
+ if bitlen <= 64 {
+ w.encodeUint(i.Uint64())
+ return nil
+ }
+ // Integer is larger than 64 bits, encode from i.Bits().
+ // The minimal byte length is bitlen rounded up to the next
+ // multiple of 8, divided by 8.
+ length := ((bitlen + 7) & -8) >> 3
+ w.encodeStringHeader(length)
+ w.str = append(w.str, make([]byte, length)...)
+ index := length
+ buf := w.str[len(w.str)-length:]
+ for _, d := range i.Bits() {
+ for j := 0; j < wordBytes && index > 0; j++ {
+ index--
+ buf[index] = byte(d)
+ d >>= 8
+ }
}
return nil
}
@@ -442,17 +425,44 @@ func writeBytes(val reflect.Value, w *encbuf) error {
return nil
}
+func makeByteArrayWriter(typ reflect.Type) writer {
+ switch typ.Len() {
+ case 0:
+ return writeLengthZeroByteArray
+ case 1:
+ return writeLengthOneByteArray
+ default:
+ return writeByteArray
+ }
+}
+
+func writeLengthZeroByteArray(val reflect.Value, w *encbuf) error {
+ w.str = append(w.str, 0x80)
+ return nil
+}
+
+func writeLengthOneByteArray(val reflect.Value, w *encbuf) error {
+ b := byte(val.Index(0).Uint())
+ if b <= 0x7f {
+ w.str = append(w.str, b)
+ } else {
+ w.str = append(w.str, 0x81, b)
+ }
+ return nil
+}
+
func writeByteArray(val reflect.Value, w *encbuf) error {
if !val.CanAddr() {
- // Slice requires the value to be addressable.
- // Make it addressable by copying.
+ // Getting the byte slice of val requires it to be addressable. Make it
+ // addressable by copying.
copy := reflect.New(val.Type()).Elem()
copy.Set(val)
val = copy
}
- size := val.Len()
- slice := val.Slice(0, size).Bytes()
- w.encodeString(slice)
+
+ slice := byteArrayBytes(val)
+ w.encodeStringHeader(len(slice))
+ w.str = append(w.str, slice...)
return nil
}
@@ -468,26 +478,6 @@ func writeString(val reflect.Value, w *encbuf) error {
return nil
}
-func writeEncoder(val reflect.Value, w *encbuf) error {
- return val.Interface().(Encoder).EncodeRLP(w)
-}
-
-// writeEncoderNoPtr handles non-pointer values that implement Encoder
-// with a pointer receiver.
-func writeEncoderNoPtr(val reflect.Value, w *encbuf) error {
- if !val.CanAddr() {
- // We can't get the address. It would be possible to make the
- // value addressable by creating a shallow copy, but this
- // creates other problems so we're not doing it (yet).
- //
- // package json simply doesn't call MarshalJSON for cases like
- // this, but encodes the value as if it didn't implement the
- // interface. We don't want to handle it that way.
- return fmt.Errorf("rlp: game over: unadressable value of type %v, EncodeRLP is pointer method", val.Type())
- }
- return val.Addr().Interface().(Encoder).EncodeRLP(w)
-}
-
func writeInterface(val reflect.Value, w *encbuf) error {
if val.IsNil() {
// Write empty list. This is consistent with the previous RLP
@@ -497,17 +487,17 @@ func writeInterface(val reflect.Value, w *encbuf) error {
return nil
}
eval := val.Elem()
- ti, err := cachedTypeInfo(eval.Type(), tags{})
+ writer, err := cachedWriter(eval.Type())
if err != nil {
return err
}
- return ti.writer(eval, w)
+ return writer(eval, w)
}
func makeSliceWriter(typ reflect.Type, ts tags) (writer, error) {
- etypeinfo, err := cachedTypeInfo1(typ.Elem(), tags{})
- if err != nil {
- return nil, err
+ etypeinfo := theTC.infoWhileGenerating(typ.Elem(), tags{})
+ if etypeinfo.writerErr != nil {
+ return nil, etypeinfo.writerErr
}
writer := func(val reflect.Value, w *encbuf) error {
if !ts.tail {
@@ -529,55 +519,92 @@ func makeStructWriter(typ reflect.Type) (writer, error) {
if err != nil {
return nil, err
}
- writer := func(val reflect.Value, w *encbuf) error {
- lh := w.list()
- for _, f := range fields {
- if err := f.info.writer(val.Field(f.index), w); err != nil {
- return err
- }
+ for _, f := range fields {
+ if f.info.writerErr != nil {
+ return nil, structFieldError{typ, f.index, f.info.writerErr}
}
- w.listEnd(lh)
- return nil
- }
- return writer, nil
-}
-
-func makePtrWriter(typ reflect.Type) (writer, error) {
- etypeinfo, err := cachedTypeInfo1(typ.Elem(), tags{})
- if err != nil {
- return nil, err
}
- // determine nil pointer handler
- var nilfunc func(*encbuf) error
- kind := typ.Elem().Kind()
- switch {
- case kind == reflect.Array && isByte(typ.Elem().Elem()):
- nilfunc = func(w *encbuf) error {
- w.str = append(w.str, 0x80)
+ var writer writer
+ firstOptionalField := firstOptionalField(fields)
+ if firstOptionalField == len(fields) {
+ // This is the writer function for structs without any optional fields.
+ writer = func(val reflect.Value, w *encbuf) error {
+ lh := w.list()
+ for _, f := range fields {
+ if err := f.info.writer(val.Field(f.index), w); err != nil {
+ return err
+ }
+ }
+ w.listEnd(lh)
return nil
}
- case kind == reflect.Struct || kind == reflect.Array:
- nilfunc = func(w *encbuf) error {
- // encoding the zero value of a struct/array could trigger
- // infinite recursion, avoid that.
- w.listEnd(w.list())
+ } else {
+ // If there are any "optional" fields, the writer needs to perform additional
+ // checks to determine the output list length.
+ writer = func(val reflect.Value, w *encbuf) error {
+ lastField := len(fields) - 1
+ for ; lastField >= firstOptionalField; lastField-- {
+ if !val.Field(fields[lastField].index).IsZero() {
+ break
+ }
+ }
+ lh := w.list()
+ for i := 0; i <= lastField; i++ {
+ if err := fields[i].info.writer(val.Field(fields[i].index), w); err != nil {
+ return err
+ }
+ }
+ w.listEnd(lh)
return nil
}
- default:
- zero := reflect.Zero(typ.Elem())
- nilfunc = func(w *encbuf) error {
- return etypeinfo.writer(zero, w)
- }
+ }
+ return writer, nil
+}
+
+func makePtrWriter(typ reflect.Type, ts tags) (writer, error) {
+ etypeinfo := theTC.infoWhileGenerating(typ.Elem(), tags{})
+ if etypeinfo.writerErr != nil {
+ return nil, etypeinfo.writerErr
+ }
+ // Determine how to encode nil pointers.
+ var nilKind Kind
+ if ts.nilOK {
+ nilKind = ts.nilKind // use struct tag if provided
+ } else {
+ nilKind = defaultNilKind(typ.Elem())
}
writer := func(val reflect.Value, w *encbuf) error {
if val.IsNil() {
- return nilfunc(w)
+ if nilKind == String {
+ w.str = append(w.str, 0x80)
+ } else {
+ w.listEnd(w.list())
+ }
+ return nil
}
return etypeinfo.writer(val.Elem(), w)
}
- return writer, err
+ return writer, nil
+}
+
+func makeEncoderWriter(typ reflect.Type) writer {
+ if typ.Implements(encoderInterface) {
+ return func(val reflect.Value, w *encbuf) error {
+ return val.Interface().(Encoder).EncodeRLP(w)
+ }
+ }
+ w := func(val reflect.Value, w *encbuf) error {
+ if !val.CanAddr() {
+ // package json simply doesn't call MarshalJSON for this case, but encodes the
+ // value as if it didn't implement the interface. We don't want to handle it that
+ // way.
+ return fmt.Errorf("rlp: unadressable value of type %v, EncodeRLP is pointer method", val.Type())
+ }
+ return val.Addr().Interface().(Encoder).EncodeRLP(w)
+ }
+ return w
}
// putint writes i to the beginning of b in big endian byte
diff --git a/rlp/iterator.go b/rlp/iterator.go
new file mode 100644
index 000000000..559e03a86
--- /dev/null
+++ b/rlp/iterator.go
@@ -0,0 +1,61 @@
+// Copyright 2019 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package rlp
+
+type listIterator struct {
+ data []byte
+ next []byte
+ err error
+}
+
+// NewListIterator creates an iterator for the (list) represented by data
+// TODO: Consider removing this implementation, as it is no longer used.
+func NewListIterator(data RawValue) (*listIterator, error) {
+ k, t, c, err := readKind(data)
+ if err != nil {
+ return nil, err
+ }
+ if k != List {
+ return nil, ErrExpectedList
+ }
+ it := &listIterator{
+ data: data[t : t+c],
+ }
+ return it, nil
+
+}
+
+// Next forwards the iterator one step, returns true if it was not at end yet
+func (it *listIterator) Next() bool {
+ if len(it.data) == 0 {
+ return false
+ }
+ _, t, c, err := readKind(it.data)
+ it.next = it.data[:t+c]
+ it.data = it.data[t+c:]
+ it.err = err
+ return true
+}
+
+// Value returns the current value
+func (it *listIterator) Value() []byte {
+ return it.next
+}
+
+func (it *listIterator) Err() error {
+ return it.err
+}
diff --git a/rlp/typecache.go b/rlp/typecache.go
index 8c2dd518e..62553d3b5 100644
--- a/rlp/typecache.go
+++ b/rlp/typecache.go
@@ -21,34 +21,40 @@ import (
"reflect"
"strings"
"sync"
+ "sync/atomic"
)
-var (
- typeCacheMutex sync.RWMutex
- typeCache = make(map[typekey]*typeinfo)
-)
-
+// typeinfo is an entry in the type cache.
type typeinfo struct {
- decoder
- writer
+ decoder decoder
+ decoderErr error // error from makeDecoder
+ writer writer
+ writerErr error // error from makeWriter
}
-// represents struct tags
+// tags represents struct tags.
type tags struct {
// rlp:"nil" controls whether empty input results in a nil pointer.
- nilOK bool
- // rlp:"tail" controls whether this field swallows additional list
- // elements. It can only be set for the last field, which must be
- // of slice type.
+ // nilKind is the kind of empty value allowed for the field.
+ nilKind Kind
+ nilOK bool
+
+ // rlp:"optional" allows for a field to be missing in the input list.
+ // If this is set, all subsequent fields must also be optional.
+ optional bool
+
+ // rlp:"tail" controls whether this field swallows additional list elements. It can
+ // only be set for the last field, which must be of slice type.
tail bool
+
// rlp:"-" ignores fields.
ignored bool
}
+// typekey is the key of a type in typeCache. It includes the struct tags because
+// they might generate a different decoder.
type typekey struct {
reflect.Type
- // the key must include the struct tags because they
- // might generate a different decoder.
tags
}
@@ -56,66 +62,146 @@ type decoder func(*Stream, reflect.Value) error
type writer func(reflect.Value, *encbuf) error
-func cachedTypeInfo(typ reflect.Type, tags tags) (*typeinfo, error) {
- typeCacheMutex.RLock()
- info := typeCache[typekey{typ, tags}]
- typeCacheMutex.RUnlock()
- if info != nil {
- return info, nil
+var theTC = newTypeCache()
+
+type typeCache struct {
+ cur atomic.Value
+
+ // This lock synchronizes writers.
+ mu sync.Mutex
+ next map[typekey]*typeinfo
+}
+
+func newTypeCache() *typeCache {
+ c := new(typeCache)
+ c.cur.Store(make(map[typekey]*typeinfo))
+ return c
+}
+
+func cachedDecoder(typ reflect.Type) (decoder, error) {
+ info := theTC.info(typ)
+ return info.decoder, info.decoderErr
+}
+
+func cachedWriter(typ reflect.Type) (writer, error) {
+ info := theTC.info(typ)
+ return info.writer, info.writerErr
+}
+
+func (c *typeCache) info(typ reflect.Type) *typeinfo {
+ key := typekey{Type: typ}
+ if info := c.cur.Load().(map[typekey]*typeinfo)[key]; info != nil {
+ return info
}
- // not in the cache, need to generate info for this type.
- typeCacheMutex.Lock()
- defer typeCacheMutex.Unlock()
- return cachedTypeInfo1(typ, tags)
+
+ // Not in the cache, need to generate info for this type.
+ return c.generate(typ, tags{})
}
-func cachedTypeInfo1(typ reflect.Type, tags tags) (*typeinfo, error) {
+func (c *typeCache) generate(typ reflect.Type, tags tags) *typeinfo {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ cur := c.cur.Load().(map[typekey]*typeinfo)
+ if info := cur[typekey{typ, tags}]; info != nil {
+ return info
+ }
+
+ // Copy cur to next.
+ c.next = make(map[typekey]*typeinfo, len(cur)+1)
+ for k, v := range cur {
+ c.next[k] = v
+ }
+
+ // Generate.
+ info := c.infoWhileGenerating(typ, tags)
+
+ // next -> cur
+ c.cur.Store(c.next)
+ c.next = nil
+ return info
+}
+
+func (c *typeCache) infoWhileGenerating(typ reflect.Type, tags tags) *typeinfo {
key := typekey{typ, tags}
- info := typeCache[key]
- if info != nil {
- // another goroutine got the write lock first
- return info, nil
+ if info := c.next[key]; info != nil {
+ return info
}
- // put a dummy value into the cache before generating.
- // if the generator tries to lookup itself, it will get
+ // Put a dummy value into the cache before generating.
+ // If the generator tries to lookup itself, it will get
// the dummy value and won't call itself recursively.
- typeCache[key] = new(typeinfo)
- info, err := genTypeInfo(typ, tags)
- if err != nil {
- // remove the dummy value if the generator fails
- delete(typeCache, key)
- return nil, err
- }
- *typeCache[key] = *info
- return typeCache[key], err
+ info := new(typeinfo)
+ c.next[key] = info
+ info.generate(typ, tags)
+ return info
}
type field struct {
- index int
- info *typeinfo
+ index int
+ info *typeinfo
+ optional bool
}
+// structFields resolves the typeinfo of all public fields in a struct type.
func structFields(typ reflect.Type) (fields []field, err error) {
+ var (
+ lastPublic = lastPublicField(typ)
+ anyOptional = false
+ )
for i := 0; i < typ.NumField(); i++ {
if f := typ.Field(i); f.PkgPath == "" { // exported
- tags, err := parseStructTag(typ, i)
+ tags, err := parseStructTag(typ, i, lastPublic)
if err != nil {
return nil, err
}
+
+ // Skip rlp:"-" fields.
if tags.ignored {
continue
}
- info, err := cachedTypeInfo1(f.Type, tags)
- if err != nil {
- return nil, err
+ // If any field has the "optional" tag, subsequent fields must also have it.
+ if tags.optional || tags.tail {
+ anyOptional = true
+ } else if anyOptional {
+ return nil, fmt.Errorf(`rlp: struct field %v.%s needs "optional" tag`, typ, f.Name)
}
- fields = append(fields, field{i, info})
+ info := theTC.infoWhileGenerating(f.Type, tags)
+ fields = append(fields, field{i, info, tags.optional})
}
}
return fields, nil
}
-func parseStructTag(typ reflect.Type, fi int) (tags, error) {
+// anyOptionalFields returns the index of the first field with "optional" tag.
+func firstOptionalField(fields []field) int {
+ for i, f := range fields {
+ if f.optional {
+ return i
+ }
+ }
+ return len(fields)
+}
+
+type structFieldError struct {
+ typ reflect.Type
+ field int
+ err error
+}
+
+func (e structFieldError) Error() string {
+ return fmt.Sprintf("%v (struct field %v.%s)", e.err, e.typ, e.typ.Field(e.field).Name)
+}
+
+type structTagError struct {
+ typ reflect.Type
+ field, tag, err string
+}
+
+func (e structTagError) Error() string {
+ return fmt.Sprintf("rlp: invalid struct tag %q for %v.%s (%s)", e.tag, e.typ, e.field, e.err)
+}
+
+func parseStructTag(typ reflect.Type, fi, lastPublic int) (tags, error) {
f := typ.Field(fi)
var ts tags
for _, t := range strings.Split(f.Tag.Get("rlp"), ",") {
@@ -123,15 +209,34 @@ func parseStructTag(typ reflect.Type, fi int) (tags, error) {
case "":
case "-":
ts.ignored = true
- case "nil":
+ case "nil", "nilString", "nilList":
ts.nilOK = true
+ if f.Type.Kind() != reflect.Ptr {
+ return ts, structTagError{typ, f.Name, t, "field is not a pointer"}
+ }
+ switch t {
+ case "nil":
+ ts.nilKind = defaultNilKind(f.Type.Elem())
+ case "nilString":
+ ts.nilKind = String
+ case "nilList":
+ ts.nilKind = List
+ }
+ case "optional":
+ ts.optional = true
+ if ts.tail {
+ return ts, structTagError{typ, f.Name, t, `also has "tail" tag`}
+ }
case "tail":
ts.tail = true
- if fi != typ.NumField()-1 {
- return ts, fmt.Errorf(`rlp: invalid struct tag "tail" for %v.%s (must be on last field)`, typ, f.Name)
+ if fi != lastPublic {
+ return ts, structTagError{typ, f.Name, t, "must be on last field"}
+ }
+ if ts.optional {
+ return ts, structTagError{typ, f.Name, t, `also has "optional" tag`}
}
if f.Type.Kind() != reflect.Slice {
- return ts, fmt.Errorf(`rlp: invalid struct tag "tail" for %v.%s (field type is not slice)`, typ, f.Name)
+ return ts, structTagError{typ, f.Name, t, "field type is not slice"}
}
default:
return ts, fmt.Errorf("rlp: unknown struct tag %q on %v.%s", t, typ, f.Name)
@@ -140,17 +245,39 @@ func parseStructTag(typ reflect.Type, fi int) (tags, error) {
return ts, nil
}
-func genTypeInfo(typ reflect.Type, tags tags) (info *typeinfo, err error) {
- info = new(typeinfo)
- if info.decoder, err = makeDecoder(typ, tags); err != nil {
- return nil, err
+func lastPublicField(typ reflect.Type) int {
+ last := 0
+ for i := 0; i < typ.NumField(); i++ {
+ if typ.Field(i).PkgPath == "" {
+ last = i
+ }
}
- if info.writer, err = makeWriter(typ, tags); err != nil {
- return nil, err
+ return last
+}
+
+func (i *typeinfo) generate(typ reflect.Type, tags tags) {
+ i.decoder, i.decoderErr = makeDecoder(typ, tags)
+ i.writer, i.writerErr = makeWriter(typ, tags)
+}
+
+// defaultNilKind determines whether a nil pointer to typ encodes/decodes
+// as an empty string or empty list.
+func defaultNilKind(typ reflect.Type) Kind {
+ k := typ.Kind()
+ if isUint(k) || k == reflect.String || k == reflect.Bool || isByteArray(typ) {
+ return String
}
- return info, nil
+ return List
}
func isUint(k reflect.Kind) bool {
return k >= reflect.Uint && k <= reflect.Uintptr
}
+
+func isByte(typ reflect.Type) bool {
+ return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
+}
+
+func isByteArray(typ reflect.Type) bool {
+ return (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array) && isByte(typ.Elem())
+}
diff --git a/rlp/unsafe.go b/rlp/unsafe.go
new file mode 100644
index 000000000..94ed5405a
--- /dev/null
+++ b/rlp/unsafe.go
@@ -0,0 +1,35 @@
+// Copyright 2021 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+// +build !nacl,!js,cgo
+
+package rlp
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+// byteArrayBytes returns a slice of the byte array v.
+func byteArrayBytes(v reflect.Value) []byte {
+ len := v.Len()
+ var s []byte
+ hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
+ hdr.Data = v.UnsafeAddr()
+ hdr.Cap = len
+ hdr.Len = len
+ return s
+}
diff --git a/signer/core/abihelper.go b/signer/core/abihelper.go
index 9bcd6d25a..b111fa872 100644
--- a/signer/core/abihelper.go
+++ b/signer/core/abihelper.go
@@ -89,11 +89,11 @@ func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) {
return nil, err
}
- decoded := decodedCallData{signature: method.Sig(), name: method.Name}
+ decoded := decodedCallData{signature: method.Sig, name: method.Name}
for n, argument := range method.Inputs {
if err != nil {
- return nil, fmt.Errorf("Failed to decode argument %d (signature %v): %v", n, method.Sig(), err)
+ return nil, fmt.Errorf("Failed to decode argument %d (signature %v): %v", n, method.Sig, err)
}
decodedArg := decodedArgument{
soltype: argument,
@@ -118,7 +118,7 @@ func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) {
if !bytes.Equal(encoded, argdata) {
was := common.Bytes2Hex(encoded)
exp := common.Bytes2Hex(argdata)
- return nil, fmt.Errorf("WARNING: Supplied data is stuffed with extra data. \nWant %s\nHave %s\nfor method %v", exp, was, method.Sig())
+ return nil, fmt.Errorf("WARNING: Supplied data is stuffed with extra data. \nWant %s\nHave %s\nfor method %v", exp, was, method.Sig)
}
return &decoded, nil
}
diff --git a/signer/core/api.go b/signer/core/api.go
index 030c2204c..5d8c79b28 100644
--- a/signer/core/api.go
+++ b/signer/core/api.go
@@ -215,14 +215,14 @@ func NewSignerAPI(chainID int64, ksLocation string, noUSB bool, ui SignerUI, abi
log.Debug("Ledger support enabled")
}
// Start a USB hub for Trezor hardware wallets
- if trezorhub, err := usbwallet.NewTrezorHub(); err != nil {
+ if trezorhub, err := usbwallet.NewTrezorHubWithHID(); err != nil {
log.Warn(fmt.Sprintf("Failed to start Trezor hub, disabling: %v", err))
} else {
backends = append(backends, trezorhub)
log.Debug("Trezor support enabled")
}
}
- return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb)}
+ return &SignerAPI{big.NewInt(chainID), accounts.NewManager(&accounts.Config{}, backends...), ui, NewValidator(abidb)}
}
// List returns the set of wallet this signer manages. Each wallet can contain
@@ -395,7 +395,7 @@ func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, da
return nil, err
}
// Assemble sign the data with the wallet
- signature, err := wallet.SignHashWithPassphrase(account, res.Password, sighash)
+ signature, err := wallet.SignTextWithPassphrase(account, res.Password, sighash)
if err != nil {
api.UI.ShowError(err.Error())
return nil, err
diff --git a/vendor/bazil.org/fuse/fuse.iml b/vendor/bazil.org/fuse/fuse.iml
deleted file mode 100644
index 792ad4c30..000000000
--- a/vendor/bazil.org/fuse/fuse.iml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/bug_report.md b/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 000000000..cb9fc37c8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,20 @@
+---
+name: Bug report
+about: Create a report to help us improve
+
+---
+
+**What version of protobuf and what language are you using?**
+Version: (e.g., `v1.1.0`, `89a0c16f`, etc)
+
+**What did you do?**
+If possible, provide a recipe for reproducing the error.
+A complete runnable program is good with `.proto` and `.go` source code.
+
+**What did you expect to see?**
+
+**What did you see instead?**
+
+Make sure you include information that can help us debug (full error message, exception listing, stack trace, logs).
+
+**Anything else we should know about your project / environment?**
diff --git a/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/feature_request.md b/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 000000000..b904f1f84
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,17 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+
+---
+
+**Is your feature request related to a problem? Please describe.**
+A clear and concise description of what the problem is.
+
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.
+
+**Additional context**
+Add any other context or screenshots about the feature request here.
diff --git a/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/question.md b/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/question.md
new file mode 100644
index 000000000..bfa6ddea8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.github/ISSUE_TEMPLATE/question.md
@@ -0,0 +1,7 @@
+---
+name: Question
+about: Questions and troubleshooting
+
+---
+
+
diff --git a/vendor/github.com/golang/protobuf/.gitignore b/vendor/github.com/golang/protobuf/.gitignore
new file mode 100644
index 000000000..5c986d1c5
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.gitignore
@@ -0,0 +1,3 @@
+.cache
+vendor
+cmd/protoc-gen-go/protoc-gen-go
diff --git a/vendor/github.com/golang/protobuf/.travis.yml b/vendor/github.com/golang/protobuf/.travis.yml
new file mode 100644
index 000000000..0b5166678
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.travis.yml
@@ -0,0 +1,22 @@
+language: go
+before_install:
+ - mkdir /tmp/go1.12
+ - curl -L -s https://dl.google.com/go/go1.12.linux-amd64.tar.gz | tar -zxf - -C /tmp/go1.12 --strip-components 1
+ - unset GOROOT
+ - (GO111MODULE=on /tmp/go1.12/bin/go mod vendor)
+matrix:
+ include:
+ - go: 1.9.x
+ script: go test -tags protolegacy -v ./...
+ - go: 1.10.x
+ script: go test -tags protolegacy -v ./...
+ - go: 1.11.x
+ script: go test -tags protolegacy -v ./...
+ - go: 1.12.x
+ script: go test -tags protolegacy -v ./...
+ - go: 1.13.x
+ script: go test -tags protolegacy -v ./...
+ - go: 1.14.x
+ script: go test -tags protolegacy -v ./...
+ - go: 1.15.x
+ script: ./test.bash
diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTING.md b/vendor/github.com/golang/protobuf/CONTRIBUTING.md
new file mode 100644
index 000000000..83971cbbf
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/CONTRIBUTING.md
@@ -0,0 +1,30 @@
+# Contributing to Go Protocol Buffers
+
+Go protocol buffers is an open source project and accepts contributions.
+
+This project is the first major version of Go protobufs,
+while the next major revision of this project is located at
+[protocolbuffers/protobuf-go](https://github.com/protocolbuffers/protobuf-go).
+Most new development effort is focused on the latter project,
+and changes to this project is primarily reserved for bug fixes.
+
+
+## Contributor License Agreement
+
+Contributions to this project must be accompanied by a Contributor License
+Agreement. You (or your employer) retain the copyright to your contribution,
+this simply gives us permission to use and redistribute your contributions as
+part of the project. Head over to to see
+your current agreements on file or to sign a new one.
+
+You generally only need to submit a CLA once, so if you've already submitted one
+(even if it was for a different project), you probably don't need to do it
+again.
+
+
+## Code reviews
+
+All submissions, including submissions by project members, require review. We
+use GitHub pull requests for this purpose. Consult
+[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
+information on using pull requests.
diff --git a/vendor/github.com/golang/protobuf/Makefile b/vendor/github.com/golang/protobuf/Makefile
deleted file mode 100644
index 2bc2621aa..000000000
--- a/vendor/github.com/golang/protobuf/Makefile
+++ /dev/null
@@ -1,48 +0,0 @@
-# Go support for Protocol Buffers - Google's data interchange format
-#
-# Copyright 2010 The Go Authors. All rights reserved.
-# https://github.com/golang/protobuf
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-all: install
-
-install:
- go install ./proto ./jsonpb ./ptypes ./protoc-gen-go
-
-test:
- go test ./... ./protoc-gen-go/testdata
- make -C conformance test
-
-clean:
- go clean ./...
-
-nuke:
- go clean -i ./...
-
-regenerate:
- ./regenerate.sh
diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md
index 2a5670b1c..2e4233f20 100644
--- a/vendor/github.com/golang/protobuf/README.md
+++ b/vendor/github.com/golang/protobuf/README.md
@@ -1,285 +1,122 @@
-# Go support for Protocol Buffers - Google's data interchange format
+# Go support for Protocol Buffers
+[](https://pkg.go.dev/mod/github.com/golang/protobuf)
[](https://travis-ci.org/golang/protobuf)
-[](https://godoc.org/github.com/golang/protobuf)
-Google's data interchange format.
-Copyright 2010 The Go Authors.
-https://github.com/golang/protobuf
-
-truechain use protobuf version is libprotoc 3.5.1
-
-This package and the code it generates requires at least Go 1.6.
-
-This software implements Go bindings for protocol buffers. For
-information about protocol buffers themselves, see
- https://developers.google.com/protocol-buffers/
-
-## Installation ##
-
-To use this software, you must:
-- Install the standard C++ implementation of protocol buffers from
- https://developers.google.com/protocol-buffers/
-- Of course, install the Go compiler and tools from
- https://golang.org/
- See
- https://golang.org/doc/install
- for details or, if you are using gccgo, follow the instructions at
- https://golang.org/doc/install/gccgo
-- Grab the code from the repository and install the proto package.
- The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`.
- The compiler plugin, protoc-gen-go, will be installed in $GOBIN,
- defaulting to $GOPATH/bin. It must be in your $PATH for the protocol
- compiler, protoc, to find it.
-
-This software has two parts: a 'protocol compiler plugin' that
-generates Go source files that, once compiled, can access and manage
-protocol buffers; and a library that implements run-time support for
-encoding (marshaling), decoding (unmarshaling), and accessing protocol
-buffers.
-
-There is support for gRPC in Go using protocol buffers.
-See the note at the bottom of this file for details.
-
-There are no insertion points in the plugin.
-
-
-## Using protocol buffers with Go ##
-
-Once the software is installed, there are two steps to using it.
-First you must compile the protocol buffer definitions and then import
-them, with the support library, into your program.
-
-To compile the protocol buffer definition, run protoc with the --go_out
-parameter set to the directory you want to output the Go code to.
-
- protoc --go_out=. *.proto
-
-The generated files will be suffixed .pb.go. See the Test code below
-for an example using such a file.
-
-## Packages and input paths ##
-
-The protocol buffer language has a concept of "packages" which does not
-correspond well to the Go notion of packages. In generated Go code,
-each source `.proto` file is associated with a single Go package. The
-name and import path for this package is specified with the `go_package`
-proto option:
-
- option go_package = "github.com/golang/protobuf/ptypes/any";
-
-The protocol buffer compiler will attempt to derive a package name and
-import path if a `go_package` option is not present, but it is
-best to always specify one explicitly.
-
-There is a one-to-one relationship between source `.proto` files and
-generated `.pb.go` files, but any number of `.pb.go` files may be
-contained in the same Go package.
-
-The output name of a generated file is produced by replacing the
-`.proto` suffix with `.pb.go` (e.g., `foo.proto` produces `foo.pb.go`).
-However, the output directory is selected in one of two ways. Let
-us say we have `inputs/x.proto` with a `go_package` option of
-`github.com/golang/protobuf/p`. The corresponding output file may
-be:
-
-- Relative to the import path:
-
- protoc --go_out=. inputs/x.proto
- # writes ./github.com/golang/protobuf/p/x.pb.go
-
- (This can work well with `--go_out=$GOPATH`.)
-
-- Relative to the input file:
-
- protoc --go_out=paths=source_relative:. inputs/x.proto
- # generate ./inputs/x.pb.go
-
-## Generated code ##
-
-The package comment for the proto library contains text describing
-the interface provided in Go for protocol buffers. Here is an edited
-version.
-
-The proto package converts data structures to and from the
-wire format of protocol buffers. It works in concert with the
-Go source code generated for .proto files by the protocol compiler.
-
-A summary of the properties of the protocol buffer interface
-for a protocol buffer variable v:
-
- - Names are turned from camel_case to CamelCase for export.
- - There are no methods on v to set fields; just treat
- them as structure fields.
- - There are getters that return a field's value if set,
- and return the field's default value if unset.
- The getters work even if the receiver is a nil message.
- - The zero value for a struct is its correct initialization state.
- All desired fields must be set before marshaling.
- - A Reset() method will restore a protobuf struct to its zero state.
- - Non-repeated fields are pointers to the values; nil means unset.
- That is, optional or required field int32 f becomes F *int32.
- - Repeated fields are slices.
- - Helper functions are available to aid the setting of fields.
- Helpers for getting values are superseded by the
- GetFoo methods and their use is deprecated.
- msg.Foo = proto.String("hello") // set field
- - Constants are defined to hold the default values of all fields that
- have them. They have the form Default_StructName_FieldName.
- Because the getter methods handle defaulted values,
- direct use of these constants should be rare.
- - Enums are given type names and maps from names to values.
- Enum values are prefixed with the enum's type name. Enum types have
- a String method, and a Enum method to assist in message construction.
- - Nested groups and enums have type names prefixed with the name of
- the surrounding message type.
- - Extensions are given descriptor names that start with E_,
- followed by an underscore-delimited list of the nested messages
- that contain it (if any) followed by the CamelCased name of the
- extension field itself. HasExtension, ClearExtension, GetExtension
- and SetExtension are functions for manipulating extensions.
- - Oneof field sets are given a single field in their message,
- with distinguished wrapper types for each possible field value.
- - Marshal and Unmarshal are functions to encode and decode the wire format.
-
-When the .proto file specifies `syntax="proto3"`, there are some differences:
-
- - Non-repeated fields of non-message type are values instead of pointers.
- - Enum types do not get an Enum method.
-
-Consider file test.proto, containing
-
-```proto
- syntax = "proto2";
- package example;
-
- enum FOO { X = 17; };
-
- message Test {
- required string label = 1;
- optional int32 type = 2 [default=77];
- repeated int64 reps = 3;
- optional group OptionalGroup = 4 {
- required string RequiredField = 5;
- }
- }
-```
-
-To create and play with a Test object from the example package,
-
-```go
- package main
-
- import (
- "log"
-
- "github.com/golang/protobuf/proto"
- "path/to/example"
- )
-
- func main() {
- test := &example.Test {
- Label: proto.String("hello"),
- Type: proto.Int32(17),
- Reps: []int64{1, 2, 3},
- Optionalgroup: &example.Test_OptionalGroup {
- RequiredField: proto.String("good bye"),
- },
- }
- data, err := proto.Marshal(test)
- if err != nil {
- log.Fatal("marshaling error: ", err)
- }
- newTest := &example.Test{}
- err = proto.Unmarshal(data, newTest)
- if err != nil {
- log.Fatal("unmarshaling error: ", err)
- }
- // Now test and newTest contain the same data.
- if test.GetLabel() != newTest.GetLabel() {
- log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
- }
- // etc.
- }
-```
-
-## Parameters ##
-
-To pass extra parameters to the plugin, use a comma-separated
-parameter list separated from the output directory by a colon:
-
- protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto
-
-- `paths=(import | source_relative)` - specifies how the paths of
- generated files are structured. See the "Packages and imports paths"
- section above. The default is `import`.
-- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to
- load. The only plugin in this repo is `grpc`.
-- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is
- associated with Go package quux/shme. This is subject to the
- import_prefix parameter.
-
-The following parameters are deprecated and should not be used:
-
-- `import_prefix=xxx` - a prefix that is added onto the beginning of
- all imports.
-- `import_path=foo/bar` - used as the package if no input files
- declare `go_package`. If it contains slashes, everything up to the
- rightmost slash is ignored.
-
-## gRPC Support ##
-
-If a proto file specifies RPC services, protoc-gen-go can be instructed to
-generate code compatible with gRPC (http://www.grpc.io/). To do this, pass
-the `plugins` parameter to protoc-gen-go; the usual way is to insert it into
-the --go_out argument to protoc:
-
- protoc --go_out=plugins=grpc:. *.proto
-
-## Compatibility ##
-
-The library and the generated code are expected to be stable over time.
-However, we reserve the right to make breaking changes without notice for the
-following reasons:
-
-- Security. A security issue in the specification or implementation may come to
- light whose resolution requires breaking compatibility. We reserve the right
- to address such security issues.
-- Unspecified behavior. There are some aspects of the Protocol Buffers
- specification that are undefined. Programs that depend on such unspecified
- behavior may break in future releases.
-- Specification errors or changes. If it becomes necessary to address an
- inconsistency, incompleteness, or change in the Protocol Buffers
- specification, resolving the issue could affect the meaning or legality of
- existing programs. We reserve the right to address such issues, including
- updating the implementations.
-- Bugs. If the library has a bug that violates the specification, a program
- that depends on the buggy behavior may break if the bug is fixed. We reserve
- the right to fix such bugs.
-- Adding methods or fields to generated structs. These may conflict with field
- names that already exist in a schema, causing applications to break. When the
- code generator encounters a field in the schema that would collide with a
- generated field or method name, the code generator will append an underscore
- to the generated field or method name.
-- Adding, removing, or changing methods or fields in generated structs that
- start with `XXX`. These parts of the generated code are exported out of
- necessity, but should not be considered part of the public API.
-- Adding, removing, or changing unexported symbols in generated code.
+This module
+([`github.com/golang/protobuf`](https://pkg.go.dev/mod/github.com/golang/protobuf))
+contains Go bindings for protocol buffers.
+
+It has been superseded by the
+[`google.golang.org/protobuf`](https://pkg.go.dev/mod/google.golang.org/protobuf)
+module, which contains an updated and simplified API,
+support for protobuf reflection, and many other improvements.
+We recommend that new code use the `google.golang.org/protobuf` module.
+
+Versions v1.4 and later of `github.com/golang/protobuf` are implemented
+in terms of `google.golang.org/protobuf`.
+Programs which use both modules must use at least version v1.4 of this one.
+
+See the
+[developer guide for protocol buffers in Go](https://developers.google.com/protocol-buffers/docs/gotutorial)
+for a general guide for how to get started using protobufs in Go.
+
+See
+[release note documentation](https://github.com/golang/protobuf/releases)
+for more information about individual releases of this project.
+
+See
+[documentation for the next major revision](https://pkg.go.dev/mod/google.golang.org/protobuf)
+for more information about the purpose, usage, and history of this project.
+
+## Package index
+
+Summary of the packages provided by this module:
+
+* [`proto`](https://pkg.go.dev/github.com/golang/protobuf/proto): Package
+ `proto` provides functions operating on protobuf messages such as cloning,
+ merging, and checking equality, as well as binary serialization and text
+ serialization.
+* [`jsonpb`](https://pkg.go.dev/github.com/golang/protobuf/jsonpb): Package
+ `jsonpb` serializes protobuf messages as JSON.
+* [`ptypes`](https://pkg.go.dev/github.com/golang/protobuf/ptypes): Package
+ `ptypes` provides helper functionality for protobuf well-known types.
+* [`ptypes/any`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/any):
+ Package `any` is the generated package for `google/protobuf/any.proto`.
+* [`ptypes/empty`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/empty):
+ Package `empty` is the generated package for `google/protobuf/empty.proto`.
+* [`ptypes/timestamp`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/timestamp):
+ Package `timestamp` is the generated package for
+ `google/protobuf/timestamp.proto`.
+* [`ptypes/duration`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/duration):
+ Package `duration` is the generated package for
+ `google/protobuf/duration.proto`.
+* [`ptypes/wrappers`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/wrappers):
+ Package `wrappers` is the generated package for
+ `google/protobuf/wrappers.proto`.
+* [`ptypes/struct`](https://pkg.go.dev/github.com/golang/protobuf/ptypes/struct):
+ Package `structpb` is the generated package for
+ `google/protobuf/struct.proto`.
+* [`protoc-gen-go/descriptor`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go/descriptor):
+ Package `descriptor` is the generated package for
+ `google/protobuf/descriptor.proto`.
+* [`protoc-gen-go/plugin`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go/plugin):
+ Package `plugin` is the generated package for
+ `google/protobuf/compiler/plugin.proto`.
+* [`protoc-gen-go`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go):
+ The `protoc-gen-go` binary is a protoc plugin to generate a Go protocol
+ buffer package.
+
+## Reporting issues
+
+The issue tracker for this project
+[is located here](https://github.com/golang/protobuf/issues).
+
+Please report any issues with a sufficient description of the bug or feature
+request. Bug reports should ideally be accompanied by a minimal reproduction of
+the issue. Irreproducible bugs are difficult to diagnose and fix (and likely to
+be closed after some period of time). Bug reports must specify the version of
+the
+[Go protocol buffer module](https://github.com/protocolbuffers/protobuf-go/releases)
+and also the version of the
+[protocol buffer toolchain](https://github.com/protocolbuffers/protobuf/releases)
+being used.
+
+## Contributing
+
+This project is open-source and accepts contributions. See the
+[contribution guide](https://github.com/golang/protobuf/blob/master/CONTRIBUTING.md)
+for more information.
+
+## Compatibility
+
+This module and the generated code are expected to be stable over time. However,
+we reserve the right to make breaking changes without notice for the following
+reasons:
+
+* **Security:** A security issue in the specification or implementation may
+ come to light whose resolution requires breaking compatibility. We reserve
+ the right to address such issues.
+* **Unspecified behavior:** There are some aspects of the protocol buffer
+ specification that are undefined. Programs that depend on unspecified
+ behavior may break in future releases.
+* **Specification changes:** It may become necessary to address an
+ inconsistency, incompleteness, or change in the protocol buffer
+ specification, which may affect the behavior of existing programs. We
+ reserve the right to address such changes.
+* **Bugs:** If a package has a bug that violates correctness, a program
+ depending on the buggy behavior may break if the bug is fixed. We reserve
+ the right to fix such bugs.
+* **Generated additions**: We reserve the right to add new declarations to
+ generated Go packages of `.proto` files. This includes declared constants,
+ variables, functions, types, fields in structs, and methods on types. This
+ may break attempts at injecting additional code on top of what is generated
+ by `protoc-gen-go`. Such practice is not supported by this project.
+* **Internal changes**: We reserve the right to add, modify, and remove
+ internal code, which includes all unexported declarations, the
+ [`generator`](https://pkg.go.dev/github.com/golang/protobuf/protoc-gen-go/generator)
+ package, and all packages under
+ [`internal`](https://pkg.go.dev/github.com/golang/protobuf/internal).
Any breaking changes outside of these will be announced 6 months in advance to
-protobuf@googlegroups.com.
-
-You should, whenever possible, use generated code created by the `protoc-gen-go`
-tool built at the same commit as the `proto` package. The `proto` package
-declares package-level constants in the form `ProtoPackageIsVersionX`.
-Application code and generated code may depend on one of these constants to
-ensure that compilation will fail if the available version of the proto library
-is too old. Whenever we make a change to the generated code that requires newer
-library support, in the same commit we will increment the version number of the
-generated code and declare a new package-level constant whose name incorporates
-the latest version number. Removing a compatibility constant is considered a
-breaking change and would be subject to the announcement policy stated above.
-
-The `protoc-gen-go/generator` package exposes a plugin interface,
-which is used by the gRPC code generation. This interface is not
-supported and is subject to incompatible changes without notice.
+[protobuf@googlegroups.com](https://groups.google.com/forum/#!forum/protobuf).
diff --git a/vendor/github.com/golang/protobuf/conformance/Makefile b/vendor/github.com/golang/protobuf/conformance/Makefile
deleted file mode 100644
index b99e4ed6d..000000000
--- a/vendor/github.com/golang/protobuf/conformance/Makefile
+++ /dev/null
@@ -1,49 +0,0 @@
-# Go support for Protocol Buffers - Google's data interchange format
-#
-# Copyright 2016 The Go Authors. All rights reserved.
-# https://github.com/golang/protobuf
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-PROTOBUF_ROOT=$(HOME)/src/protobuf
-
-all:
- @echo To run the tests in this directory, acquire the main protobuf
- @echo distribution from:
- @echo
- @echo ' https://github.com/google/protobuf'
- @echo
- @echo Build the test runner with:
- @echo
- @echo ' cd conformance && make conformance-test-runner'
- @echo
- @echo And run the tests in this directory with:
- @echo
- @echo ' make test PROTOBUF_ROOT='
-
-test:
- ./test.sh $(PROTOBUF_ROOT)
diff --git a/vendor/github.com/golang/protobuf/conformance/conformance.go b/vendor/github.com/golang/protobuf/conformance/conformance.go
deleted file mode 100644
index 3029312a1..000000000
--- a/vendor/github.com/golang/protobuf/conformance/conformance.go
+++ /dev/null
@@ -1,154 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// conformance implements the conformance test subprocess protocol as
-// documented in conformance.proto.
-package main
-
-import (
- "encoding/binary"
- "fmt"
- "io"
- "os"
-
- pb "github.com/golang/protobuf/conformance/internal/conformance_proto"
- "github.com/golang/protobuf/jsonpb"
- "github.com/golang/protobuf/proto"
-)
-
-func main() {
- var sizeBuf [4]byte
- inbuf := make([]byte, 0, 4096)
- outbuf := proto.NewBuffer(nil)
- for {
- if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF {
- break
- } else if err != nil {
- fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
- os.Exit(1)
- }
- size := binary.LittleEndian.Uint32(sizeBuf[:])
- if int(size) > cap(inbuf) {
- inbuf = make([]byte, size)
- }
- inbuf = inbuf[:size]
- if _, err := io.ReadFull(os.Stdin, inbuf); err != nil {
- fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
- os.Exit(1)
- }
-
- req := new(pb.ConformanceRequest)
- if err := proto.Unmarshal(inbuf, req); err != nil {
- fmt.Fprintln(os.Stderr, "go conformance: parse request:", err)
- os.Exit(1)
- }
- res := handle(req)
-
- if err := outbuf.Marshal(res); err != nil {
- fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err)
- os.Exit(1)
- }
- binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes())))
- if _, err := os.Stdout.Write(sizeBuf[:]); err != nil {
- fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
- os.Exit(1)
- }
- if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil {
- fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
- os.Exit(1)
- }
- outbuf.Reset()
- }
-}
-
-var jsonMarshaler = jsonpb.Marshaler{
- OrigName: true,
-}
-
-func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse {
- var err error
- var msg pb.TestAllTypes
- switch p := req.Payload.(type) {
- case *pb.ConformanceRequest_ProtobufPayload:
- err = proto.Unmarshal(p.ProtobufPayload, &msg)
- case *pb.ConformanceRequest_JsonPayload:
- err = jsonpb.UnmarshalString(p.JsonPayload, &msg)
- default:
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_RuntimeError{
- RuntimeError: "unknown request payload type",
- },
- }
- }
- if err != nil {
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_ParseError{
- ParseError: err.Error(),
- },
- }
- }
- switch req.RequestedOutputFormat {
- case pb.WireFormat_PROTOBUF:
- p, err := proto.Marshal(&msg)
- if err != nil {
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_SerializeError{
- SerializeError: err.Error(),
- },
- }
- }
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_ProtobufPayload{
- ProtobufPayload: p,
- },
- }
- case pb.WireFormat_JSON:
- p, err := jsonMarshaler.MarshalToString(&msg)
- if err != nil {
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_SerializeError{
- SerializeError: err.Error(),
- },
- }
- }
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_JsonPayload{
- JsonPayload: p,
- },
- }
- default:
- return &pb.ConformanceResponse{
- Result: &pb.ConformanceResponse_RuntimeError{
- RuntimeError: "unknown output format",
- },
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/conformance/conformance.sh b/vendor/github.com/golang/protobuf/conformance/conformance.sh
deleted file mode 100644
index 8532f5711..000000000
--- a/vendor/github.com/golang/protobuf/conformance/conformance.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-cd $(dirname $0)
-exec go run conformance.go $*
diff --git a/vendor/github.com/golang/protobuf/conformance/failure_list_go.txt b/vendor/github.com/golang/protobuf/conformance/failure_list_go.txt
deleted file mode 100644
index d37280896..000000000
--- a/vendor/github.com/golang/protobuf/conformance/failure_list_go.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-# This is the list of conformance tests that are known ot fail right now.
-# TODO: These should be fixed.
-
-DurationProtoInputTooLarge.JsonOutput
-DurationProtoInputTooSmall.JsonOutput
-FieldMaskNumbersDontRoundTrip.JsonOutput
-FieldMaskPathsDontRoundTrip.JsonOutput
-FieldMaskTooManyUnderscore.JsonOutput
-JsonInput.AnyWithFieldMask.JsonOutput
-JsonInput.AnyWithFieldMask.ProtobufOutput
-JsonInput.DoubleFieldQuotedValue.JsonOutput
-JsonInput.DoubleFieldQuotedValue.ProtobufOutput
-JsonInput.DurationHas3FractionalDigits.Validator
-JsonInput.DurationHas6FractionalDigits.Validator
-JsonInput.DurationHas9FractionalDigits.Validator
-JsonInput.DurationHasZeroFractionalDigit.Validator
-JsonInput.DurationMaxValue.JsonOutput
-JsonInput.DurationMaxValue.ProtobufOutput
-JsonInput.DurationMinValue.JsonOutput
-JsonInput.DurationMinValue.ProtobufOutput
-JsonInput.EnumFieldUnknownValue.Validator
-JsonInput.FieldMask.JsonOutput
-JsonInput.FieldMask.ProtobufOutput
-JsonInput.FieldNameInLowerCamelCase.Validator
-JsonInput.FieldNameWithMixedCases.JsonOutput
-JsonInput.FieldNameWithMixedCases.ProtobufOutput
-JsonInput.FieldNameWithMixedCases.Validator
-JsonInput.FieldNameWithNumbers.Validator
-JsonInput.FloatFieldQuotedValue.JsonOutput
-JsonInput.FloatFieldQuotedValue.ProtobufOutput
-JsonInput.Int32FieldExponentialFormat.JsonOutput
-JsonInput.Int32FieldExponentialFormat.ProtobufOutput
-JsonInput.Int32FieldFloatTrailingZero.JsonOutput
-JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
-JsonInput.Int32FieldMaxFloatValue.JsonOutput
-JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
-JsonInput.Int32FieldMinFloatValue.JsonOutput
-JsonInput.Int32FieldMinFloatValue.ProtobufOutput
-JsonInput.Int32FieldStringValue.JsonOutput
-JsonInput.Int32FieldStringValue.ProtobufOutput
-JsonInput.Int32FieldStringValueEscaped.JsonOutput
-JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
-JsonInput.Int64FieldBeString.Validator
-JsonInput.MapFieldValueIsNull
-JsonInput.OneofFieldDuplicate
-JsonInput.RepeatedFieldMessageElementIsNull
-JsonInput.RepeatedFieldPrimitiveElementIsNull
-JsonInput.StringFieldSurrogateInWrongOrder
-JsonInput.StringFieldUnpairedHighSurrogate
-JsonInput.StringFieldUnpairedLowSurrogate
-JsonInput.TimestampHas3FractionalDigits.Validator
-JsonInput.TimestampHas6FractionalDigits.Validator
-JsonInput.TimestampHas9FractionalDigits.Validator
-JsonInput.TimestampHasZeroFractionalDigit.Validator
-JsonInput.TimestampJsonInputTooSmall
-JsonInput.TimestampZeroNormalized.Validator
-JsonInput.Uint32FieldMaxFloatValue.JsonOutput
-JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
-JsonInput.Uint64FieldBeString.Validator
-TimestampProtoInputTooLarge.JsonOutput
-TimestampProtoInputTooSmall.JsonOutput
diff --git a/vendor/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go b/vendor/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go
deleted file mode 100644
index 82d454120..000000000
--- a/vendor/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go
+++ /dev/null
@@ -1,1816 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: conformance.proto
-
-package conformance
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import any "github.com/golang/protobuf/ptypes/any"
-import duration "github.com/golang/protobuf/ptypes/duration"
-import _struct "github.com/golang/protobuf/ptypes/struct"
-import timestamp "github.com/golang/protobuf/ptypes/timestamp"
-import wrappers "github.com/golang/protobuf/ptypes/wrappers"
-import field_mask "google.golang.org/genproto/protobuf/field_mask"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type WireFormat int32
-
-const (
- WireFormat_UNSPECIFIED WireFormat = 0
- WireFormat_PROTOBUF WireFormat = 1
- WireFormat_JSON WireFormat = 2
-)
-
-var WireFormat_name = map[int32]string{
- 0: "UNSPECIFIED",
- 1: "PROTOBUF",
- 2: "JSON",
-}
-var WireFormat_value = map[string]int32{
- "UNSPECIFIED": 0,
- "PROTOBUF": 1,
- "JSON": 2,
-}
-
-func (x WireFormat) String() string {
- return proto.EnumName(WireFormat_name, int32(x))
-}
-func (WireFormat) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{0}
-}
-
-type ForeignEnum int32
-
-const (
- ForeignEnum_FOREIGN_FOO ForeignEnum = 0
- ForeignEnum_FOREIGN_BAR ForeignEnum = 1
- ForeignEnum_FOREIGN_BAZ ForeignEnum = 2
-)
-
-var ForeignEnum_name = map[int32]string{
- 0: "FOREIGN_FOO",
- 1: "FOREIGN_BAR",
- 2: "FOREIGN_BAZ",
-}
-var ForeignEnum_value = map[string]int32{
- "FOREIGN_FOO": 0,
- "FOREIGN_BAR": 1,
- "FOREIGN_BAZ": 2,
-}
-
-func (x ForeignEnum) String() string {
- return proto.EnumName(ForeignEnum_name, int32(x))
-}
-func (ForeignEnum) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{1}
-}
-
-type TestAllTypes_NestedEnum int32
-
-const (
- TestAllTypes_FOO TestAllTypes_NestedEnum = 0
- TestAllTypes_BAR TestAllTypes_NestedEnum = 1
- TestAllTypes_BAZ TestAllTypes_NestedEnum = 2
- TestAllTypes_NEG TestAllTypes_NestedEnum = -1
-)
-
-var TestAllTypes_NestedEnum_name = map[int32]string{
- 0: "FOO",
- 1: "BAR",
- 2: "BAZ",
- -1: "NEG",
-}
-var TestAllTypes_NestedEnum_value = map[string]int32{
- "FOO": 0,
- "BAR": 1,
- "BAZ": 2,
- "NEG": -1,
-}
-
-func (x TestAllTypes_NestedEnum) String() string {
- return proto.EnumName(TestAllTypes_NestedEnum_name, int32(x))
-}
-func (TestAllTypes_NestedEnum) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{2, 0}
-}
-
-// Represents a single test case's input. The testee should:
-//
-// 1. parse this proto (which should always succeed)
-// 2. parse the protobuf or JSON payload in "payload" (which may fail)
-// 3. if the parse succeeded, serialize the message in the requested format.
-type ConformanceRequest struct {
- // The payload (whether protobuf of JSON) is always for a TestAllTypes proto
- // (see below).
- //
- // Types that are valid to be assigned to Payload:
- // *ConformanceRequest_ProtobufPayload
- // *ConformanceRequest_JsonPayload
- Payload isConformanceRequest_Payload `protobuf_oneof:"payload"`
- // Which format should the testee serialize its message to?
- RequestedOutputFormat WireFormat `protobuf:"varint,3,opt,name=requested_output_format,json=requestedOutputFormat,enum=conformance.WireFormat" json:"requested_output_format,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ConformanceRequest) Reset() { *m = ConformanceRequest{} }
-func (m *ConformanceRequest) String() string { return proto.CompactTextString(m) }
-func (*ConformanceRequest) ProtoMessage() {}
-func (*ConformanceRequest) Descriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{0}
-}
-func (m *ConformanceRequest) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ConformanceRequest.Unmarshal(m, b)
-}
-func (m *ConformanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ConformanceRequest.Marshal(b, m, deterministic)
-}
-func (dst *ConformanceRequest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ConformanceRequest.Merge(dst, src)
-}
-func (m *ConformanceRequest) XXX_Size() int {
- return xxx_messageInfo_ConformanceRequest.Size(m)
-}
-func (m *ConformanceRequest) XXX_DiscardUnknown() {
- xxx_messageInfo_ConformanceRequest.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ConformanceRequest proto.InternalMessageInfo
-
-type isConformanceRequest_Payload interface {
- isConformanceRequest_Payload()
-}
-
-type ConformanceRequest_ProtobufPayload struct {
- ProtobufPayload []byte `protobuf:"bytes,1,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"`
-}
-type ConformanceRequest_JsonPayload struct {
- JsonPayload string `protobuf:"bytes,2,opt,name=json_payload,json=jsonPayload,oneof"`
-}
-
-func (*ConformanceRequest_ProtobufPayload) isConformanceRequest_Payload() {}
-func (*ConformanceRequest_JsonPayload) isConformanceRequest_Payload() {}
-
-func (m *ConformanceRequest) GetPayload() isConformanceRequest_Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func (m *ConformanceRequest) GetProtobufPayload() []byte {
- if x, ok := m.GetPayload().(*ConformanceRequest_ProtobufPayload); ok {
- return x.ProtobufPayload
- }
- return nil
-}
-
-func (m *ConformanceRequest) GetJsonPayload() string {
- if x, ok := m.GetPayload().(*ConformanceRequest_JsonPayload); ok {
- return x.JsonPayload
- }
- return ""
-}
-
-func (m *ConformanceRequest) GetRequestedOutputFormat() WireFormat {
- if m != nil {
- return m.RequestedOutputFormat
- }
- return WireFormat_UNSPECIFIED
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*ConformanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _ConformanceRequest_OneofMarshaler, _ConformanceRequest_OneofUnmarshaler, _ConformanceRequest_OneofSizer, []interface{}{
- (*ConformanceRequest_ProtobufPayload)(nil),
- (*ConformanceRequest_JsonPayload)(nil),
- }
-}
-
-func _ConformanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*ConformanceRequest)
- // payload
- switch x := m.Payload.(type) {
- case *ConformanceRequest_ProtobufPayload:
- b.EncodeVarint(1<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.ProtobufPayload)
- case *ConformanceRequest_JsonPayload:
- b.EncodeVarint(2<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.JsonPayload)
- case nil:
- default:
- return fmt.Errorf("ConformanceRequest.Payload has unexpected type %T", x)
- }
- return nil
-}
-
-func _ConformanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*ConformanceRequest)
- switch tag {
- case 1: // payload.protobuf_payload
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Payload = &ConformanceRequest_ProtobufPayload{x}
- return true, err
- case 2: // payload.json_payload
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Payload = &ConformanceRequest_JsonPayload{x}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _ConformanceRequest_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*ConformanceRequest)
- // payload
- switch x := m.Payload.(type) {
- case *ConformanceRequest_ProtobufPayload:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.ProtobufPayload)))
- n += len(x.ProtobufPayload)
- case *ConformanceRequest_JsonPayload:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.JsonPayload)))
- n += len(x.JsonPayload)
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-// Represents a single test case's output.
-type ConformanceResponse struct {
- // Types that are valid to be assigned to Result:
- // *ConformanceResponse_ParseError
- // *ConformanceResponse_SerializeError
- // *ConformanceResponse_RuntimeError
- // *ConformanceResponse_ProtobufPayload
- // *ConformanceResponse_JsonPayload
- // *ConformanceResponse_Skipped
- Result isConformanceResponse_Result `protobuf_oneof:"result"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ConformanceResponse) Reset() { *m = ConformanceResponse{} }
-func (m *ConformanceResponse) String() string { return proto.CompactTextString(m) }
-func (*ConformanceResponse) ProtoMessage() {}
-func (*ConformanceResponse) Descriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{1}
-}
-func (m *ConformanceResponse) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ConformanceResponse.Unmarshal(m, b)
-}
-func (m *ConformanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ConformanceResponse.Marshal(b, m, deterministic)
-}
-func (dst *ConformanceResponse) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ConformanceResponse.Merge(dst, src)
-}
-func (m *ConformanceResponse) XXX_Size() int {
- return xxx_messageInfo_ConformanceResponse.Size(m)
-}
-func (m *ConformanceResponse) XXX_DiscardUnknown() {
- xxx_messageInfo_ConformanceResponse.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ConformanceResponse proto.InternalMessageInfo
-
-type isConformanceResponse_Result interface {
- isConformanceResponse_Result()
-}
-
-type ConformanceResponse_ParseError struct {
- ParseError string `protobuf:"bytes,1,opt,name=parse_error,json=parseError,oneof"`
-}
-type ConformanceResponse_SerializeError struct {
- SerializeError string `protobuf:"bytes,6,opt,name=serialize_error,json=serializeError,oneof"`
-}
-type ConformanceResponse_RuntimeError struct {
- RuntimeError string `protobuf:"bytes,2,opt,name=runtime_error,json=runtimeError,oneof"`
-}
-type ConformanceResponse_ProtobufPayload struct {
- ProtobufPayload []byte `protobuf:"bytes,3,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"`
-}
-type ConformanceResponse_JsonPayload struct {
- JsonPayload string `protobuf:"bytes,4,opt,name=json_payload,json=jsonPayload,oneof"`
-}
-type ConformanceResponse_Skipped struct {
- Skipped string `protobuf:"bytes,5,opt,name=skipped,oneof"`
-}
-
-func (*ConformanceResponse_ParseError) isConformanceResponse_Result() {}
-func (*ConformanceResponse_SerializeError) isConformanceResponse_Result() {}
-func (*ConformanceResponse_RuntimeError) isConformanceResponse_Result() {}
-func (*ConformanceResponse_ProtobufPayload) isConformanceResponse_Result() {}
-func (*ConformanceResponse_JsonPayload) isConformanceResponse_Result() {}
-func (*ConformanceResponse_Skipped) isConformanceResponse_Result() {}
-
-func (m *ConformanceResponse) GetResult() isConformanceResponse_Result {
- if m != nil {
- return m.Result
- }
- return nil
-}
-
-func (m *ConformanceResponse) GetParseError() string {
- if x, ok := m.GetResult().(*ConformanceResponse_ParseError); ok {
- return x.ParseError
- }
- return ""
-}
-
-func (m *ConformanceResponse) GetSerializeError() string {
- if x, ok := m.GetResult().(*ConformanceResponse_SerializeError); ok {
- return x.SerializeError
- }
- return ""
-}
-
-func (m *ConformanceResponse) GetRuntimeError() string {
- if x, ok := m.GetResult().(*ConformanceResponse_RuntimeError); ok {
- return x.RuntimeError
- }
- return ""
-}
-
-func (m *ConformanceResponse) GetProtobufPayload() []byte {
- if x, ok := m.GetResult().(*ConformanceResponse_ProtobufPayload); ok {
- return x.ProtobufPayload
- }
- return nil
-}
-
-func (m *ConformanceResponse) GetJsonPayload() string {
- if x, ok := m.GetResult().(*ConformanceResponse_JsonPayload); ok {
- return x.JsonPayload
- }
- return ""
-}
-
-func (m *ConformanceResponse) GetSkipped() string {
- if x, ok := m.GetResult().(*ConformanceResponse_Skipped); ok {
- return x.Skipped
- }
- return ""
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*ConformanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _ConformanceResponse_OneofMarshaler, _ConformanceResponse_OneofUnmarshaler, _ConformanceResponse_OneofSizer, []interface{}{
- (*ConformanceResponse_ParseError)(nil),
- (*ConformanceResponse_SerializeError)(nil),
- (*ConformanceResponse_RuntimeError)(nil),
- (*ConformanceResponse_ProtobufPayload)(nil),
- (*ConformanceResponse_JsonPayload)(nil),
- (*ConformanceResponse_Skipped)(nil),
- }
-}
-
-func _ConformanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*ConformanceResponse)
- // result
- switch x := m.Result.(type) {
- case *ConformanceResponse_ParseError:
- b.EncodeVarint(1<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.ParseError)
- case *ConformanceResponse_SerializeError:
- b.EncodeVarint(6<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.SerializeError)
- case *ConformanceResponse_RuntimeError:
- b.EncodeVarint(2<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.RuntimeError)
- case *ConformanceResponse_ProtobufPayload:
- b.EncodeVarint(3<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.ProtobufPayload)
- case *ConformanceResponse_JsonPayload:
- b.EncodeVarint(4<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.JsonPayload)
- case *ConformanceResponse_Skipped:
- b.EncodeVarint(5<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.Skipped)
- case nil:
- default:
- return fmt.Errorf("ConformanceResponse.Result has unexpected type %T", x)
- }
- return nil
-}
-
-func _ConformanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*ConformanceResponse)
- switch tag {
- case 1: // result.parse_error
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Result = &ConformanceResponse_ParseError{x}
- return true, err
- case 6: // result.serialize_error
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Result = &ConformanceResponse_SerializeError{x}
- return true, err
- case 2: // result.runtime_error
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Result = &ConformanceResponse_RuntimeError{x}
- return true, err
- case 3: // result.protobuf_payload
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Result = &ConformanceResponse_ProtobufPayload{x}
- return true, err
- case 4: // result.json_payload
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Result = &ConformanceResponse_JsonPayload{x}
- return true, err
- case 5: // result.skipped
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Result = &ConformanceResponse_Skipped{x}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _ConformanceResponse_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*ConformanceResponse)
- // result
- switch x := m.Result.(type) {
- case *ConformanceResponse_ParseError:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.ParseError)))
- n += len(x.ParseError)
- case *ConformanceResponse_SerializeError:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.SerializeError)))
- n += len(x.SerializeError)
- case *ConformanceResponse_RuntimeError:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.RuntimeError)))
- n += len(x.RuntimeError)
- case *ConformanceResponse_ProtobufPayload:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.ProtobufPayload)))
- n += len(x.ProtobufPayload)
- case *ConformanceResponse_JsonPayload:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.JsonPayload)))
- n += len(x.JsonPayload)
- case *ConformanceResponse_Skipped:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Skipped)))
- n += len(x.Skipped)
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-// This proto includes every type of field in both singular and repeated
-// forms.
-type TestAllTypes struct {
- // Singular
- OptionalInt32 int32 `protobuf:"varint,1,opt,name=optional_int32,json=optionalInt32" json:"optional_int32,omitempty"`
- OptionalInt64 int64 `protobuf:"varint,2,opt,name=optional_int64,json=optionalInt64" json:"optional_int64,omitempty"`
- OptionalUint32 uint32 `protobuf:"varint,3,opt,name=optional_uint32,json=optionalUint32" json:"optional_uint32,omitempty"`
- OptionalUint64 uint64 `protobuf:"varint,4,opt,name=optional_uint64,json=optionalUint64" json:"optional_uint64,omitempty"`
- OptionalSint32 int32 `protobuf:"zigzag32,5,opt,name=optional_sint32,json=optionalSint32" json:"optional_sint32,omitempty"`
- OptionalSint64 int64 `protobuf:"zigzag64,6,opt,name=optional_sint64,json=optionalSint64" json:"optional_sint64,omitempty"`
- OptionalFixed32 uint32 `protobuf:"fixed32,7,opt,name=optional_fixed32,json=optionalFixed32" json:"optional_fixed32,omitempty"`
- OptionalFixed64 uint64 `protobuf:"fixed64,8,opt,name=optional_fixed64,json=optionalFixed64" json:"optional_fixed64,omitempty"`
- OptionalSfixed32 int32 `protobuf:"fixed32,9,opt,name=optional_sfixed32,json=optionalSfixed32" json:"optional_sfixed32,omitempty"`
- OptionalSfixed64 int64 `protobuf:"fixed64,10,opt,name=optional_sfixed64,json=optionalSfixed64" json:"optional_sfixed64,omitempty"`
- OptionalFloat float32 `protobuf:"fixed32,11,opt,name=optional_float,json=optionalFloat" json:"optional_float,omitempty"`
- OptionalDouble float64 `protobuf:"fixed64,12,opt,name=optional_double,json=optionalDouble" json:"optional_double,omitempty"`
- OptionalBool bool `protobuf:"varint,13,opt,name=optional_bool,json=optionalBool" json:"optional_bool,omitempty"`
- OptionalString string `protobuf:"bytes,14,opt,name=optional_string,json=optionalString" json:"optional_string,omitempty"`
- OptionalBytes []byte `protobuf:"bytes,15,opt,name=optional_bytes,json=optionalBytes,proto3" json:"optional_bytes,omitempty"`
- OptionalNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,18,opt,name=optional_nested_message,json=optionalNestedMessage" json:"optional_nested_message,omitempty"`
- OptionalForeignMessage *ForeignMessage `protobuf:"bytes,19,opt,name=optional_foreign_message,json=optionalForeignMessage" json:"optional_foreign_message,omitempty"`
- OptionalNestedEnum TestAllTypes_NestedEnum `protobuf:"varint,21,opt,name=optional_nested_enum,json=optionalNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"optional_nested_enum,omitempty"`
- OptionalForeignEnum ForeignEnum `protobuf:"varint,22,opt,name=optional_foreign_enum,json=optionalForeignEnum,enum=conformance.ForeignEnum" json:"optional_foreign_enum,omitempty"`
- OptionalStringPiece string `protobuf:"bytes,24,opt,name=optional_string_piece,json=optionalStringPiece" json:"optional_string_piece,omitempty"`
- OptionalCord string `protobuf:"bytes,25,opt,name=optional_cord,json=optionalCord" json:"optional_cord,omitempty"`
- RecursiveMessage *TestAllTypes `protobuf:"bytes,27,opt,name=recursive_message,json=recursiveMessage" json:"recursive_message,omitempty"`
- // Repeated
- RepeatedInt32 []int32 `protobuf:"varint,31,rep,packed,name=repeated_int32,json=repeatedInt32" json:"repeated_int32,omitempty"`
- RepeatedInt64 []int64 `protobuf:"varint,32,rep,packed,name=repeated_int64,json=repeatedInt64" json:"repeated_int64,omitempty"`
- RepeatedUint32 []uint32 `protobuf:"varint,33,rep,packed,name=repeated_uint32,json=repeatedUint32" json:"repeated_uint32,omitempty"`
- RepeatedUint64 []uint64 `protobuf:"varint,34,rep,packed,name=repeated_uint64,json=repeatedUint64" json:"repeated_uint64,omitempty"`
- RepeatedSint32 []int32 `protobuf:"zigzag32,35,rep,packed,name=repeated_sint32,json=repeatedSint32" json:"repeated_sint32,omitempty"`
- RepeatedSint64 []int64 `protobuf:"zigzag64,36,rep,packed,name=repeated_sint64,json=repeatedSint64" json:"repeated_sint64,omitempty"`
- RepeatedFixed32 []uint32 `protobuf:"fixed32,37,rep,packed,name=repeated_fixed32,json=repeatedFixed32" json:"repeated_fixed32,omitempty"`
- RepeatedFixed64 []uint64 `protobuf:"fixed64,38,rep,packed,name=repeated_fixed64,json=repeatedFixed64" json:"repeated_fixed64,omitempty"`
- RepeatedSfixed32 []int32 `protobuf:"fixed32,39,rep,packed,name=repeated_sfixed32,json=repeatedSfixed32" json:"repeated_sfixed32,omitempty"`
- RepeatedSfixed64 []int64 `protobuf:"fixed64,40,rep,packed,name=repeated_sfixed64,json=repeatedSfixed64" json:"repeated_sfixed64,omitempty"`
- RepeatedFloat []float32 `protobuf:"fixed32,41,rep,packed,name=repeated_float,json=repeatedFloat" json:"repeated_float,omitempty"`
- RepeatedDouble []float64 `protobuf:"fixed64,42,rep,packed,name=repeated_double,json=repeatedDouble" json:"repeated_double,omitempty"`
- RepeatedBool []bool `protobuf:"varint,43,rep,packed,name=repeated_bool,json=repeatedBool" json:"repeated_bool,omitempty"`
- RepeatedString []string `protobuf:"bytes,44,rep,name=repeated_string,json=repeatedString" json:"repeated_string,omitempty"`
- RepeatedBytes [][]byte `protobuf:"bytes,45,rep,name=repeated_bytes,json=repeatedBytes,proto3" json:"repeated_bytes,omitempty"`
- RepeatedNestedMessage []*TestAllTypes_NestedMessage `protobuf:"bytes,48,rep,name=repeated_nested_message,json=repeatedNestedMessage" json:"repeated_nested_message,omitempty"`
- RepeatedForeignMessage []*ForeignMessage `protobuf:"bytes,49,rep,name=repeated_foreign_message,json=repeatedForeignMessage" json:"repeated_foreign_message,omitempty"`
- RepeatedNestedEnum []TestAllTypes_NestedEnum `protobuf:"varint,51,rep,packed,name=repeated_nested_enum,json=repeatedNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"repeated_nested_enum,omitempty"`
- RepeatedForeignEnum []ForeignEnum `protobuf:"varint,52,rep,packed,name=repeated_foreign_enum,json=repeatedForeignEnum,enum=conformance.ForeignEnum" json:"repeated_foreign_enum,omitempty"`
- RepeatedStringPiece []string `protobuf:"bytes,54,rep,name=repeated_string_piece,json=repeatedStringPiece" json:"repeated_string_piece,omitempty"`
- RepeatedCord []string `protobuf:"bytes,55,rep,name=repeated_cord,json=repeatedCord" json:"repeated_cord,omitempty"`
- // Map
- MapInt32Int32 map[int32]int32 `protobuf:"bytes,56,rep,name=map_int32_int32,json=mapInt32Int32" json:"map_int32_int32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- MapInt64Int64 map[int64]int64 `protobuf:"bytes,57,rep,name=map_int64_int64,json=mapInt64Int64" json:"map_int64_int64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- MapUint32Uint32 map[uint32]uint32 `protobuf:"bytes,58,rep,name=map_uint32_uint32,json=mapUint32Uint32" json:"map_uint32_uint32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- MapUint64Uint64 map[uint64]uint64 `protobuf:"bytes,59,rep,name=map_uint64_uint64,json=mapUint64Uint64" json:"map_uint64_uint64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- MapSint32Sint32 map[int32]int32 `protobuf:"bytes,60,rep,name=map_sint32_sint32,json=mapSint32Sint32" json:"map_sint32_sint32,omitempty" protobuf_key:"zigzag32,1,opt,name=key" protobuf_val:"zigzag32,2,opt,name=value"`
- MapSint64Sint64 map[int64]int64 `protobuf:"bytes,61,rep,name=map_sint64_sint64,json=mapSint64Sint64" json:"map_sint64_sint64,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"zigzag64,2,opt,name=value"`
- MapFixed32Fixed32 map[uint32]uint32 `protobuf:"bytes,62,rep,name=map_fixed32_fixed32,json=mapFixed32Fixed32" json:"map_fixed32_fixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
- MapFixed64Fixed64 map[uint64]uint64 `protobuf:"bytes,63,rep,name=map_fixed64_fixed64,json=mapFixed64Fixed64" json:"map_fixed64_fixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
- MapSfixed32Sfixed32 map[int32]int32 `protobuf:"bytes,64,rep,name=map_sfixed32_sfixed32,json=mapSfixed32Sfixed32" json:"map_sfixed32_sfixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
- MapSfixed64Sfixed64 map[int64]int64 `protobuf:"bytes,65,rep,name=map_sfixed64_sfixed64,json=mapSfixed64Sfixed64" json:"map_sfixed64_sfixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
- MapInt32Float map[int32]float32 `protobuf:"bytes,66,rep,name=map_int32_float,json=mapInt32Float" json:"map_int32_float,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
- MapInt32Double map[int32]float64 `protobuf:"bytes,67,rep,name=map_int32_double,json=mapInt32Double" json:"map_int32_double,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
- MapBoolBool map[bool]bool `protobuf:"bytes,68,rep,name=map_bool_bool,json=mapBoolBool" json:"map_bool_bool,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- MapStringString map[string]string `protobuf:"bytes,69,rep,name=map_string_string,json=mapStringString" json:"map_string_string,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- MapStringBytes map[string][]byte `protobuf:"bytes,70,rep,name=map_string_bytes,json=mapStringBytes" json:"map_string_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
- MapStringNestedMessage map[string]*TestAllTypes_NestedMessage `protobuf:"bytes,71,rep,name=map_string_nested_message,json=mapStringNestedMessage" json:"map_string_nested_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- MapStringForeignMessage map[string]*ForeignMessage `protobuf:"bytes,72,rep,name=map_string_foreign_message,json=mapStringForeignMessage" json:"map_string_foreign_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- MapStringNestedEnum map[string]TestAllTypes_NestedEnum `protobuf:"bytes,73,rep,name=map_string_nested_enum,json=mapStringNestedEnum" json:"map_string_nested_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.TestAllTypes_NestedEnum"`
- MapStringForeignEnum map[string]ForeignEnum `protobuf:"bytes,74,rep,name=map_string_foreign_enum,json=mapStringForeignEnum" json:"map_string_foreign_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.ForeignEnum"`
- // Types that are valid to be assigned to OneofField:
- // *TestAllTypes_OneofUint32
- // *TestAllTypes_OneofNestedMessage
- // *TestAllTypes_OneofString
- // *TestAllTypes_OneofBytes
- OneofField isTestAllTypes_OneofField `protobuf_oneof:"oneof_field"`
- // Well-known types
- OptionalBoolWrapper *wrappers.BoolValue `protobuf:"bytes,201,opt,name=optional_bool_wrapper,json=optionalBoolWrapper" json:"optional_bool_wrapper,omitempty"`
- OptionalInt32Wrapper *wrappers.Int32Value `protobuf:"bytes,202,opt,name=optional_int32_wrapper,json=optionalInt32Wrapper" json:"optional_int32_wrapper,omitempty"`
- OptionalInt64Wrapper *wrappers.Int64Value `protobuf:"bytes,203,opt,name=optional_int64_wrapper,json=optionalInt64Wrapper" json:"optional_int64_wrapper,omitempty"`
- OptionalUint32Wrapper *wrappers.UInt32Value `protobuf:"bytes,204,opt,name=optional_uint32_wrapper,json=optionalUint32Wrapper" json:"optional_uint32_wrapper,omitempty"`
- OptionalUint64Wrapper *wrappers.UInt64Value `protobuf:"bytes,205,opt,name=optional_uint64_wrapper,json=optionalUint64Wrapper" json:"optional_uint64_wrapper,omitempty"`
- OptionalFloatWrapper *wrappers.FloatValue `protobuf:"bytes,206,opt,name=optional_float_wrapper,json=optionalFloatWrapper" json:"optional_float_wrapper,omitempty"`
- OptionalDoubleWrapper *wrappers.DoubleValue `protobuf:"bytes,207,opt,name=optional_double_wrapper,json=optionalDoubleWrapper" json:"optional_double_wrapper,omitempty"`
- OptionalStringWrapper *wrappers.StringValue `protobuf:"bytes,208,opt,name=optional_string_wrapper,json=optionalStringWrapper" json:"optional_string_wrapper,omitempty"`
- OptionalBytesWrapper *wrappers.BytesValue `protobuf:"bytes,209,opt,name=optional_bytes_wrapper,json=optionalBytesWrapper" json:"optional_bytes_wrapper,omitempty"`
- RepeatedBoolWrapper []*wrappers.BoolValue `protobuf:"bytes,211,rep,name=repeated_bool_wrapper,json=repeatedBoolWrapper" json:"repeated_bool_wrapper,omitempty"`
- RepeatedInt32Wrapper []*wrappers.Int32Value `protobuf:"bytes,212,rep,name=repeated_int32_wrapper,json=repeatedInt32Wrapper" json:"repeated_int32_wrapper,omitempty"`
- RepeatedInt64Wrapper []*wrappers.Int64Value `protobuf:"bytes,213,rep,name=repeated_int64_wrapper,json=repeatedInt64Wrapper" json:"repeated_int64_wrapper,omitempty"`
- RepeatedUint32Wrapper []*wrappers.UInt32Value `protobuf:"bytes,214,rep,name=repeated_uint32_wrapper,json=repeatedUint32Wrapper" json:"repeated_uint32_wrapper,omitempty"`
- RepeatedUint64Wrapper []*wrappers.UInt64Value `protobuf:"bytes,215,rep,name=repeated_uint64_wrapper,json=repeatedUint64Wrapper" json:"repeated_uint64_wrapper,omitempty"`
- RepeatedFloatWrapper []*wrappers.FloatValue `protobuf:"bytes,216,rep,name=repeated_float_wrapper,json=repeatedFloatWrapper" json:"repeated_float_wrapper,omitempty"`
- RepeatedDoubleWrapper []*wrappers.DoubleValue `protobuf:"bytes,217,rep,name=repeated_double_wrapper,json=repeatedDoubleWrapper" json:"repeated_double_wrapper,omitempty"`
- RepeatedStringWrapper []*wrappers.StringValue `protobuf:"bytes,218,rep,name=repeated_string_wrapper,json=repeatedStringWrapper" json:"repeated_string_wrapper,omitempty"`
- RepeatedBytesWrapper []*wrappers.BytesValue `protobuf:"bytes,219,rep,name=repeated_bytes_wrapper,json=repeatedBytesWrapper" json:"repeated_bytes_wrapper,omitempty"`
- OptionalDuration *duration.Duration `protobuf:"bytes,301,opt,name=optional_duration,json=optionalDuration" json:"optional_duration,omitempty"`
- OptionalTimestamp *timestamp.Timestamp `protobuf:"bytes,302,opt,name=optional_timestamp,json=optionalTimestamp" json:"optional_timestamp,omitempty"`
- OptionalFieldMask *field_mask.FieldMask `protobuf:"bytes,303,opt,name=optional_field_mask,json=optionalFieldMask" json:"optional_field_mask,omitempty"`
- OptionalStruct *_struct.Struct `protobuf:"bytes,304,opt,name=optional_struct,json=optionalStruct" json:"optional_struct,omitempty"`
- OptionalAny *any.Any `protobuf:"bytes,305,opt,name=optional_any,json=optionalAny" json:"optional_any,omitempty"`
- OptionalValue *_struct.Value `protobuf:"bytes,306,opt,name=optional_value,json=optionalValue" json:"optional_value,omitempty"`
- RepeatedDuration []*duration.Duration `protobuf:"bytes,311,rep,name=repeated_duration,json=repeatedDuration" json:"repeated_duration,omitempty"`
- RepeatedTimestamp []*timestamp.Timestamp `protobuf:"bytes,312,rep,name=repeated_timestamp,json=repeatedTimestamp" json:"repeated_timestamp,omitempty"`
- RepeatedFieldmask []*field_mask.FieldMask `protobuf:"bytes,313,rep,name=repeated_fieldmask,json=repeatedFieldmask" json:"repeated_fieldmask,omitempty"`
- RepeatedStruct []*_struct.Struct `protobuf:"bytes,324,rep,name=repeated_struct,json=repeatedStruct" json:"repeated_struct,omitempty"`
- RepeatedAny []*any.Any `protobuf:"bytes,315,rep,name=repeated_any,json=repeatedAny" json:"repeated_any,omitempty"`
- RepeatedValue []*_struct.Value `protobuf:"bytes,316,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"`
- // Test field-name-to-JSON-name convention.
- Fieldname1 int32 `protobuf:"varint,401,opt,name=fieldname1" json:"fieldname1,omitempty"`
- FieldName2 int32 `protobuf:"varint,402,opt,name=field_name2,json=fieldName2" json:"field_name2,omitempty"`
- XFieldName3 int32 `protobuf:"varint,403,opt,name=_field_name3,json=FieldName3" json:"_field_name3,omitempty"`
- Field_Name4_ int32 `protobuf:"varint,404,opt,name=field__name4_,json=fieldName4" json:"field__name4_,omitempty"`
- Field0Name5 int32 `protobuf:"varint,405,opt,name=field0name5" json:"field0name5,omitempty"`
- Field_0Name6 int32 `protobuf:"varint,406,opt,name=field_0_name6,json=field0Name6" json:"field_0_name6,omitempty"`
- FieldName7 int32 `protobuf:"varint,407,opt,name=fieldName7" json:"fieldName7,omitempty"`
- FieldName8 int32 `protobuf:"varint,408,opt,name=FieldName8" json:"FieldName8,omitempty"`
- Field_Name9 int32 `protobuf:"varint,409,opt,name=field_Name9,json=fieldName9" json:"field_Name9,omitempty"`
- Field_Name10 int32 `protobuf:"varint,410,opt,name=Field_Name10,json=FieldName10" json:"Field_Name10,omitempty"`
- FIELD_NAME11 int32 `protobuf:"varint,411,opt,name=FIELD_NAME11,json=FIELDNAME11" json:"FIELD_NAME11,omitempty"`
- FIELDName12 int32 `protobuf:"varint,412,opt,name=FIELD_name12,json=FIELDName12" json:"FIELD_name12,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *TestAllTypes) Reset() { *m = TestAllTypes{} }
-func (m *TestAllTypes) String() string { return proto.CompactTextString(m) }
-func (*TestAllTypes) ProtoMessage() {}
-func (*TestAllTypes) Descriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{2}
-}
-func (m *TestAllTypes) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_TestAllTypes.Unmarshal(m, b)
-}
-func (m *TestAllTypes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_TestAllTypes.Marshal(b, m, deterministic)
-}
-func (dst *TestAllTypes) XXX_Merge(src proto.Message) {
- xxx_messageInfo_TestAllTypes.Merge(dst, src)
-}
-func (m *TestAllTypes) XXX_Size() int {
- return xxx_messageInfo_TestAllTypes.Size(m)
-}
-func (m *TestAllTypes) XXX_DiscardUnknown() {
- xxx_messageInfo_TestAllTypes.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_TestAllTypes proto.InternalMessageInfo
-
-type isTestAllTypes_OneofField interface {
- isTestAllTypes_OneofField()
-}
-
-type TestAllTypes_OneofUint32 struct {
- OneofUint32 uint32 `protobuf:"varint,111,opt,name=oneof_uint32,json=oneofUint32,oneof"`
-}
-type TestAllTypes_OneofNestedMessage struct {
- OneofNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,112,opt,name=oneof_nested_message,json=oneofNestedMessage,oneof"`
-}
-type TestAllTypes_OneofString struct {
- OneofString string `protobuf:"bytes,113,opt,name=oneof_string,json=oneofString,oneof"`
-}
-type TestAllTypes_OneofBytes struct {
- OneofBytes []byte `protobuf:"bytes,114,opt,name=oneof_bytes,json=oneofBytes,proto3,oneof"`
-}
-
-func (*TestAllTypes_OneofUint32) isTestAllTypes_OneofField() {}
-func (*TestAllTypes_OneofNestedMessage) isTestAllTypes_OneofField() {}
-func (*TestAllTypes_OneofString) isTestAllTypes_OneofField() {}
-func (*TestAllTypes_OneofBytes) isTestAllTypes_OneofField() {}
-
-func (m *TestAllTypes) GetOneofField() isTestAllTypes_OneofField {
- if m != nil {
- return m.OneofField
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalInt32() int32 {
- if m != nil {
- return m.OptionalInt32
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalInt64() int64 {
- if m != nil {
- return m.OptionalInt64
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalUint32() uint32 {
- if m != nil {
- return m.OptionalUint32
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalUint64() uint64 {
- if m != nil {
- return m.OptionalUint64
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalSint32() int32 {
- if m != nil {
- return m.OptionalSint32
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalSint64() int64 {
- if m != nil {
- return m.OptionalSint64
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalFixed32() uint32 {
- if m != nil {
- return m.OptionalFixed32
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalFixed64() uint64 {
- if m != nil {
- return m.OptionalFixed64
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalSfixed32() int32 {
- if m != nil {
- return m.OptionalSfixed32
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalSfixed64() int64 {
- if m != nil {
- return m.OptionalSfixed64
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalFloat() float32 {
- if m != nil {
- return m.OptionalFloat
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalDouble() float64 {
- if m != nil {
- return m.OptionalDouble
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOptionalBool() bool {
- if m != nil {
- return m.OptionalBool
- }
- return false
-}
-
-func (m *TestAllTypes) GetOptionalString() string {
- if m != nil {
- return m.OptionalString
- }
- return ""
-}
-
-func (m *TestAllTypes) GetOptionalBytes() []byte {
- if m != nil {
- return m.OptionalBytes
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalNestedMessage() *TestAllTypes_NestedMessage {
- if m != nil {
- return m.OptionalNestedMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalForeignMessage() *ForeignMessage {
- if m != nil {
- return m.OptionalForeignMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalNestedEnum() TestAllTypes_NestedEnum {
- if m != nil {
- return m.OptionalNestedEnum
- }
- return TestAllTypes_FOO
-}
-
-func (m *TestAllTypes) GetOptionalForeignEnum() ForeignEnum {
- if m != nil {
- return m.OptionalForeignEnum
- }
- return ForeignEnum_FOREIGN_FOO
-}
-
-func (m *TestAllTypes) GetOptionalStringPiece() string {
- if m != nil {
- return m.OptionalStringPiece
- }
- return ""
-}
-
-func (m *TestAllTypes) GetOptionalCord() string {
- if m != nil {
- return m.OptionalCord
- }
- return ""
-}
-
-func (m *TestAllTypes) GetRecursiveMessage() *TestAllTypes {
- if m != nil {
- return m.RecursiveMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedInt32() []int32 {
- if m != nil {
- return m.RepeatedInt32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedInt64() []int64 {
- if m != nil {
- return m.RepeatedInt64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedUint32() []uint32 {
- if m != nil {
- return m.RepeatedUint32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedUint64() []uint64 {
- if m != nil {
- return m.RepeatedUint64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedSint32() []int32 {
- if m != nil {
- return m.RepeatedSint32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedSint64() []int64 {
- if m != nil {
- return m.RepeatedSint64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedFixed32() []uint32 {
- if m != nil {
- return m.RepeatedFixed32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedFixed64() []uint64 {
- if m != nil {
- return m.RepeatedFixed64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedSfixed32() []int32 {
- if m != nil {
- return m.RepeatedSfixed32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedSfixed64() []int64 {
- if m != nil {
- return m.RepeatedSfixed64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedFloat() []float32 {
- if m != nil {
- return m.RepeatedFloat
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedDouble() []float64 {
- if m != nil {
- return m.RepeatedDouble
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedBool() []bool {
- if m != nil {
- return m.RepeatedBool
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedString() []string {
- if m != nil {
- return m.RepeatedString
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedBytes() [][]byte {
- if m != nil {
- return m.RepeatedBytes
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedNestedMessage() []*TestAllTypes_NestedMessage {
- if m != nil {
- return m.RepeatedNestedMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedForeignMessage() []*ForeignMessage {
- if m != nil {
- return m.RepeatedForeignMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedNestedEnum() []TestAllTypes_NestedEnum {
- if m != nil {
- return m.RepeatedNestedEnum
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedForeignEnum() []ForeignEnum {
- if m != nil {
- return m.RepeatedForeignEnum
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedStringPiece() []string {
- if m != nil {
- return m.RepeatedStringPiece
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedCord() []string {
- if m != nil {
- return m.RepeatedCord
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapInt32Int32() map[int32]int32 {
- if m != nil {
- return m.MapInt32Int32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapInt64Int64() map[int64]int64 {
- if m != nil {
- return m.MapInt64Int64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapUint32Uint32() map[uint32]uint32 {
- if m != nil {
- return m.MapUint32Uint32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapUint64Uint64() map[uint64]uint64 {
- if m != nil {
- return m.MapUint64Uint64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapSint32Sint32() map[int32]int32 {
- if m != nil {
- return m.MapSint32Sint32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapSint64Sint64() map[int64]int64 {
- if m != nil {
- return m.MapSint64Sint64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapFixed32Fixed32() map[uint32]uint32 {
- if m != nil {
- return m.MapFixed32Fixed32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapFixed64Fixed64() map[uint64]uint64 {
- if m != nil {
- return m.MapFixed64Fixed64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapSfixed32Sfixed32() map[int32]int32 {
- if m != nil {
- return m.MapSfixed32Sfixed32
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapSfixed64Sfixed64() map[int64]int64 {
- if m != nil {
- return m.MapSfixed64Sfixed64
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapInt32Float() map[int32]float32 {
- if m != nil {
- return m.MapInt32Float
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapInt32Double() map[int32]float64 {
- if m != nil {
- return m.MapInt32Double
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapBoolBool() map[bool]bool {
- if m != nil {
- return m.MapBoolBool
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapStringString() map[string]string {
- if m != nil {
- return m.MapStringString
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapStringBytes() map[string][]byte {
- if m != nil {
- return m.MapStringBytes
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapStringNestedMessage() map[string]*TestAllTypes_NestedMessage {
- if m != nil {
- return m.MapStringNestedMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapStringForeignMessage() map[string]*ForeignMessage {
- if m != nil {
- return m.MapStringForeignMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapStringNestedEnum() map[string]TestAllTypes_NestedEnum {
- if m != nil {
- return m.MapStringNestedEnum
- }
- return nil
-}
-
-func (m *TestAllTypes) GetMapStringForeignEnum() map[string]ForeignEnum {
- if m != nil {
- return m.MapStringForeignEnum
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOneofUint32() uint32 {
- if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint32); ok {
- return x.OneofUint32
- }
- return 0
-}
-
-func (m *TestAllTypes) GetOneofNestedMessage() *TestAllTypes_NestedMessage {
- if x, ok := m.GetOneofField().(*TestAllTypes_OneofNestedMessage); ok {
- return x.OneofNestedMessage
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOneofString() string {
- if x, ok := m.GetOneofField().(*TestAllTypes_OneofString); ok {
- return x.OneofString
- }
- return ""
-}
-
-func (m *TestAllTypes) GetOneofBytes() []byte {
- if x, ok := m.GetOneofField().(*TestAllTypes_OneofBytes); ok {
- return x.OneofBytes
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalBoolWrapper() *wrappers.BoolValue {
- if m != nil {
- return m.OptionalBoolWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalInt32Wrapper() *wrappers.Int32Value {
- if m != nil {
- return m.OptionalInt32Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalInt64Wrapper() *wrappers.Int64Value {
- if m != nil {
- return m.OptionalInt64Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalUint32Wrapper() *wrappers.UInt32Value {
- if m != nil {
- return m.OptionalUint32Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalUint64Wrapper() *wrappers.UInt64Value {
- if m != nil {
- return m.OptionalUint64Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalFloatWrapper() *wrappers.FloatValue {
- if m != nil {
- return m.OptionalFloatWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalDoubleWrapper() *wrappers.DoubleValue {
- if m != nil {
- return m.OptionalDoubleWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalStringWrapper() *wrappers.StringValue {
- if m != nil {
- return m.OptionalStringWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalBytesWrapper() *wrappers.BytesValue {
- if m != nil {
- return m.OptionalBytesWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedBoolWrapper() []*wrappers.BoolValue {
- if m != nil {
- return m.RepeatedBoolWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedInt32Wrapper() []*wrappers.Int32Value {
- if m != nil {
- return m.RepeatedInt32Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedInt64Wrapper() []*wrappers.Int64Value {
- if m != nil {
- return m.RepeatedInt64Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedUint32Wrapper() []*wrappers.UInt32Value {
- if m != nil {
- return m.RepeatedUint32Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedUint64Wrapper() []*wrappers.UInt64Value {
- if m != nil {
- return m.RepeatedUint64Wrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedFloatWrapper() []*wrappers.FloatValue {
- if m != nil {
- return m.RepeatedFloatWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedDoubleWrapper() []*wrappers.DoubleValue {
- if m != nil {
- return m.RepeatedDoubleWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedStringWrapper() []*wrappers.StringValue {
- if m != nil {
- return m.RepeatedStringWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedBytesWrapper() []*wrappers.BytesValue {
- if m != nil {
- return m.RepeatedBytesWrapper
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalDuration() *duration.Duration {
- if m != nil {
- return m.OptionalDuration
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalTimestamp() *timestamp.Timestamp {
- if m != nil {
- return m.OptionalTimestamp
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalFieldMask() *field_mask.FieldMask {
- if m != nil {
- return m.OptionalFieldMask
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalStruct() *_struct.Struct {
- if m != nil {
- return m.OptionalStruct
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalAny() *any.Any {
- if m != nil {
- return m.OptionalAny
- }
- return nil
-}
-
-func (m *TestAllTypes) GetOptionalValue() *_struct.Value {
- if m != nil {
- return m.OptionalValue
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedDuration() []*duration.Duration {
- if m != nil {
- return m.RepeatedDuration
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedTimestamp() []*timestamp.Timestamp {
- if m != nil {
- return m.RepeatedTimestamp
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedFieldmask() []*field_mask.FieldMask {
- if m != nil {
- return m.RepeatedFieldmask
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedStruct() []*_struct.Struct {
- if m != nil {
- return m.RepeatedStruct
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedAny() []*any.Any {
- if m != nil {
- return m.RepeatedAny
- }
- return nil
-}
-
-func (m *TestAllTypes) GetRepeatedValue() []*_struct.Value {
- if m != nil {
- return m.RepeatedValue
- }
- return nil
-}
-
-func (m *TestAllTypes) GetFieldname1() int32 {
- if m != nil {
- return m.Fieldname1
- }
- return 0
-}
-
-func (m *TestAllTypes) GetFieldName2() int32 {
- if m != nil {
- return m.FieldName2
- }
- return 0
-}
-
-func (m *TestAllTypes) GetXFieldName3() int32 {
- if m != nil {
- return m.XFieldName3
- }
- return 0
-}
-
-func (m *TestAllTypes) GetField_Name4_() int32 {
- if m != nil {
- return m.Field_Name4_
- }
- return 0
-}
-
-func (m *TestAllTypes) GetField0Name5() int32 {
- if m != nil {
- return m.Field0Name5
- }
- return 0
-}
-
-func (m *TestAllTypes) GetField_0Name6() int32 {
- if m != nil {
- return m.Field_0Name6
- }
- return 0
-}
-
-func (m *TestAllTypes) GetFieldName7() int32 {
- if m != nil {
- return m.FieldName7
- }
- return 0
-}
-
-func (m *TestAllTypes) GetFieldName8() int32 {
- if m != nil {
- return m.FieldName8
- }
- return 0
-}
-
-func (m *TestAllTypes) GetField_Name9() int32 {
- if m != nil {
- return m.Field_Name9
- }
- return 0
-}
-
-func (m *TestAllTypes) GetField_Name10() int32 {
- if m != nil {
- return m.Field_Name10
- }
- return 0
-}
-
-func (m *TestAllTypes) GetFIELD_NAME11() int32 {
- if m != nil {
- return m.FIELD_NAME11
- }
- return 0
-}
-
-func (m *TestAllTypes) GetFIELDName12() int32 {
- if m != nil {
- return m.FIELDName12
- }
- return 0
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*TestAllTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _TestAllTypes_OneofMarshaler, _TestAllTypes_OneofUnmarshaler, _TestAllTypes_OneofSizer, []interface{}{
- (*TestAllTypes_OneofUint32)(nil),
- (*TestAllTypes_OneofNestedMessage)(nil),
- (*TestAllTypes_OneofString)(nil),
- (*TestAllTypes_OneofBytes)(nil),
- }
-}
-
-func _TestAllTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*TestAllTypes)
- // oneof_field
- switch x := m.OneofField.(type) {
- case *TestAllTypes_OneofUint32:
- b.EncodeVarint(111<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.OneofUint32))
- case *TestAllTypes_OneofNestedMessage:
- b.EncodeVarint(112<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.OneofNestedMessage); err != nil {
- return err
- }
- case *TestAllTypes_OneofString:
- b.EncodeVarint(113<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.OneofString)
- case *TestAllTypes_OneofBytes:
- b.EncodeVarint(114<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.OneofBytes)
- case nil:
- default:
- return fmt.Errorf("TestAllTypes.OneofField has unexpected type %T", x)
- }
- return nil
-}
-
-func _TestAllTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*TestAllTypes)
- switch tag {
- case 111: // oneof_field.oneof_uint32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.OneofField = &TestAllTypes_OneofUint32{uint32(x)}
- return true, err
- case 112: // oneof_field.oneof_nested_message
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(TestAllTypes_NestedMessage)
- err := b.DecodeMessage(msg)
- m.OneofField = &TestAllTypes_OneofNestedMessage{msg}
- return true, err
- case 113: // oneof_field.oneof_string
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.OneofField = &TestAllTypes_OneofString{x}
- return true, err
- case 114: // oneof_field.oneof_bytes
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.OneofField = &TestAllTypes_OneofBytes{x}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _TestAllTypes_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*TestAllTypes)
- // oneof_field
- switch x := m.OneofField.(type) {
- case *TestAllTypes_OneofUint32:
- n += 2 // tag and wire
- n += proto.SizeVarint(uint64(x.OneofUint32))
- case *TestAllTypes_OneofNestedMessage:
- s := proto.Size(x.OneofNestedMessage)
- n += 2 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case *TestAllTypes_OneofString:
- n += 2 // tag and wire
- n += proto.SizeVarint(uint64(len(x.OneofString)))
- n += len(x.OneofString)
- case *TestAllTypes_OneofBytes:
- n += 2 // tag and wire
- n += proto.SizeVarint(uint64(len(x.OneofBytes)))
- n += len(x.OneofBytes)
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-type TestAllTypes_NestedMessage struct {
- A int32 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"`
- Corecursive *TestAllTypes `protobuf:"bytes,2,opt,name=corecursive" json:"corecursive,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *TestAllTypes_NestedMessage) Reset() { *m = TestAllTypes_NestedMessage{} }
-func (m *TestAllTypes_NestedMessage) String() string { return proto.CompactTextString(m) }
-func (*TestAllTypes_NestedMessage) ProtoMessage() {}
-func (*TestAllTypes_NestedMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{2, 0}
-}
-func (m *TestAllTypes_NestedMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_TestAllTypes_NestedMessage.Unmarshal(m, b)
-}
-func (m *TestAllTypes_NestedMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_TestAllTypes_NestedMessage.Marshal(b, m, deterministic)
-}
-func (dst *TestAllTypes_NestedMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_TestAllTypes_NestedMessage.Merge(dst, src)
-}
-func (m *TestAllTypes_NestedMessage) XXX_Size() int {
- return xxx_messageInfo_TestAllTypes_NestedMessage.Size(m)
-}
-func (m *TestAllTypes_NestedMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_TestAllTypes_NestedMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_TestAllTypes_NestedMessage proto.InternalMessageInfo
-
-func (m *TestAllTypes_NestedMessage) GetA() int32 {
- if m != nil {
- return m.A
- }
- return 0
-}
-
-func (m *TestAllTypes_NestedMessage) GetCorecursive() *TestAllTypes {
- if m != nil {
- return m.Corecursive
- }
- return nil
-}
-
-type ForeignMessage struct {
- C int32 `protobuf:"varint,1,opt,name=c" json:"c,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ForeignMessage) Reset() { *m = ForeignMessage{} }
-func (m *ForeignMessage) String() string { return proto.CompactTextString(m) }
-func (*ForeignMessage) ProtoMessage() {}
-func (*ForeignMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_conformance_48ac832451f5d6c3, []int{3}
-}
-func (m *ForeignMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ForeignMessage.Unmarshal(m, b)
-}
-func (m *ForeignMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ForeignMessage.Marshal(b, m, deterministic)
-}
-func (dst *ForeignMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ForeignMessage.Merge(dst, src)
-}
-func (m *ForeignMessage) XXX_Size() int {
- return xxx_messageInfo_ForeignMessage.Size(m)
-}
-func (m *ForeignMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_ForeignMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ForeignMessage proto.InternalMessageInfo
-
-func (m *ForeignMessage) GetC() int32 {
- if m != nil {
- return m.C
- }
- return 0
-}
-
-func init() {
- proto.RegisterType((*ConformanceRequest)(nil), "conformance.ConformanceRequest")
- proto.RegisterType((*ConformanceResponse)(nil), "conformance.ConformanceResponse")
- proto.RegisterType((*TestAllTypes)(nil), "conformance.TestAllTypes")
- proto.RegisterMapType((map[bool]bool)(nil), "conformance.TestAllTypes.MapBoolBoolEntry")
- proto.RegisterMapType((map[uint32]uint32)(nil), "conformance.TestAllTypes.MapFixed32Fixed32Entry")
- proto.RegisterMapType((map[uint64]uint64)(nil), "conformance.TestAllTypes.MapFixed64Fixed64Entry")
- proto.RegisterMapType((map[int32]float64)(nil), "conformance.TestAllTypes.MapInt32DoubleEntry")
- proto.RegisterMapType((map[int32]float32)(nil), "conformance.TestAllTypes.MapInt32FloatEntry")
- proto.RegisterMapType((map[int32]int32)(nil), "conformance.TestAllTypes.MapInt32Int32Entry")
- proto.RegisterMapType((map[int64]int64)(nil), "conformance.TestAllTypes.MapInt64Int64Entry")
- proto.RegisterMapType((map[int32]int32)(nil), "conformance.TestAllTypes.MapSfixed32Sfixed32Entry")
- proto.RegisterMapType((map[int64]int64)(nil), "conformance.TestAllTypes.MapSfixed64Sfixed64Entry")
- proto.RegisterMapType((map[int32]int32)(nil), "conformance.TestAllTypes.MapSint32Sint32Entry")
- proto.RegisterMapType((map[int64]int64)(nil), "conformance.TestAllTypes.MapSint64Sint64Entry")
- proto.RegisterMapType((map[string][]byte)(nil), "conformance.TestAllTypes.MapStringBytesEntry")
- proto.RegisterMapType((map[string]ForeignEnum)(nil), "conformance.TestAllTypes.MapStringForeignEnumEntry")
- proto.RegisterMapType((map[string]*ForeignMessage)(nil), "conformance.TestAllTypes.MapStringForeignMessageEntry")
- proto.RegisterMapType((map[string]TestAllTypes_NestedEnum)(nil), "conformance.TestAllTypes.MapStringNestedEnumEntry")
- proto.RegisterMapType((map[string]*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.MapStringNestedMessageEntry")
- proto.RegisterMapType((map[string]string)(nil), "conformance.TestAllTypes.MapStringStringEntry")
- proto.RegisterMapType((map[uint32]uint32)(nil), "conformance.TestAllTypes.MapUint32Uint32Entry")
- proto.RegisterMapType((map[uint64]uint64)(nil), "conformance.TestAllTypes.MapUint64Uint64Entry")
- proto.RegisterType((*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.NestedMessage")
- proto.RegisterType((*ForeignMessage)(nil), "conformance.ForeignMessage")
- proto.RegisterEnum("conformance.WireFormat", WireFormat_name, WireFormat_value)
- proto.RegisterEnum("conformance.ForeignEnum", ForeignEnum_name, ForeignEnum_value)
- proto.RegisterEnum("conformance.TestAllTypes_NestedEnum", TestAllTypes_NestedEnum_name, TestAllTypes_NestedEnum_value)
-}
-
-func init() { proto.RegisterFile("conformance.proto", fileDescriptor_conformance_48ac832451f5d6c3) }
-
-var fileDescriptor_conformance_48ac832451f5d6c3 = []byte{
- // 2600 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0x5b, 0x73, 0x13, 0xc9,
- 0x15, 0xf6, 0x68, 0xc0, 0x36, 0x2d, 0xd9, 0x96, 0xdb, 0xb7, 0xc6, 0x50, 0xcb, 0x60, 0x96, 0x20,
- 0x60, 0xd7, 0xeb, 0xcb, 0x30, 0x5c, 0x36, 0x4b, 0xb0, 0xc0, 0x02, 0x93, 0xc5, 0xa2, 0xc6, 0x78,
- 0xa9, 0x22, 0x0f, 0xca, 0x20, 0x8f, 0x5d, 0x5a, 0x24, 0x8d, 0x76, 0x66, 0xb4, 0x89, 0xf3, 0x98,
- 0x7f, 0x90, 0xfb, 0xf5, 0x2f, 0xe4, 0x5a, 0x95, 0x4a, 0x52, 0xc9, 0x53, 0x2a, 0x2f, 0xb9, 0x27,
- 0x95, 0x7b, 0xf2, 0x63, 0x92, 0xea, 0xeb, 0x74, 0xb7, 0x7a, 0x64, 0xb1, 0x55, 0x2b, 0x5b, 0xa7,
- 0xbf, 0xfe, 0xce, 0xe9, 0xd3, 0x67, 0xbe, 0x76, 0x9f, 0x01, 0xcc, 0x36, 0xa3, 0xee, 0x61, 0x14,
- 0x77, 0x82, 0x6e, 0x33, 0x5c, 0xed, 0xc5, 0x51, 0x1a, 0xc1, 0xa2, 0x64, 0x5a, 0x3e, 0x7b, 0x14,
- 0x45, 0x47, 0xed, 0xf0, 0x1d, 0x32, 0xf4, 0xb2, 0x7f, 0xf8, 0x4e, 0xd0, 0x3d, 0xa6, 0xb8, 0xe5,
- 0x37, 0xf4, 0xa1, 0x83, 0x7e, 0x1c, 0xa4, 0xad, 0xa8, 0xcb, 0xc6, 0x1d, 0x7d, 0xfc, 0xb0, 0x15,
- 0xb6, 0x0f, 0x1a, 0x9d, 0x20, 0x79, 0xc5, 0x10, 0xe7, 0x75, 0x44, 0x92, 0xc6, 0xfd, 0x66, 0xca,
- 0x46, 0x2f, 0xe8, 0xa3, 0x69, 0xab, 0x13, 0x26, 0x69, 0xd0, 0xe9, 0xe5, 0x05, 0xf0, 0xb9, 0x38,
- 0xe8, 0xf5, 0xc2, 0x38, 0xa1, 0xe3, 0x2b, 0xbf, 0xb2, 0x00, 0xbc, 0x9f, 0xad, 0xc5, 0x0f, 0x3f,
- 0xea, 0x87, 0x49, 0x0a, 0xaf, 0x83, 0x32, 0x9f, 0xd1, 0xe8, 0x05, 0xc7, 0xed, 0x28, 0x38, 0x40,
- 0x96, 0x63, 0x55, 0x4a, 0x8f, 0xc6, 0xfc, 0x19, 0x3e, 0xf2, 0x94, 0x0e, 0xc0, 0x4b, 0xa0, 0xf4,
- 0x61, 0x12, 0x75, 0x05, 0xb0, 0xe0, 0x58, 0x95, 0x33, 0x8f, 0xc6, 0xfc, 0x22, 0xb6, 0x72, 0x50,
- 0x1d, 0x2c, 0xc5, 0x94, 0x3c, 0x3c, 0x68, 0x44, 0xfd, 0xb4, 0xd7, 0x4f, 0x1b, 0xc4, 0x6b, 0x8a,
- 0x6c, 0xc7, 0xaa, 0x4c, 0x6f, 0x2c, 0xad, 0xca, 0x69, 0x7e, 0xde, 0x8a, 0xc3, 0x1a, 0x19, 0xf6,
- 0x17, 0xc4, 0xbc, 0x3a, 0x99, 0x46, 0xcd, 0xd5, 0x33, 0x60, 0x82, 0x39, 0x5c, 0xf9, 0x62, 0x01,
- 0xcc, 0x29, 0x8b, 0x48, 0x7a, 0x51, 0x37, 0x09, 0xe1, 0x45, 0x50, 0xec, 0x05, 0x71, 0x12, 0x36,
- 0xc2, 0x38, 0x8e, 0x62, 0xb2, 0x00, 0x1c, 0x17, 0x20, 0xc6, 0x6d, 0x6c, 0x83, 0x57, 0xc1, 0x4c,
- 0x12, 0xc6, 0xad, 0xa0, 0xdd, 0xfa, 0x02, 0x87, 0x8d, 0x33, 0xd8, 0xb4, 0x18, 0xa0, 0xd0, 0xcb,
- 0x60, 0x2a, 0xee, 0x77, 0x71, 0x82, 0x19, 0x90, 0xaf, 0xb3, 0xc4, 0xcc, 0x14, 0x66, 0x4a, 0x9d,
- 0x3d, 0x6a, 0xea, 0x4e, 0x99, 0x52, 0xb7, 0x0c, 0x26, 0x92, 0x57, 0xad, 0x5e, 0x2f, 0x3c, 0x40,
- 0xa7, 0xd9, 0x38, 0x37, 0x54, 0x27, 0xc1, 0x78, 0x1c, 0x26, 0xfd, 0x76, 0xba, 0xf2, 0x93, 0xfb,
- 0xa0, 0xf4, 0x2c, 0x4c, 0xd2, 0xad, 0x76, 0xfb, 0xd9, 0x71, 0x2f, 0x4c, 0xe0, 0x65, 0x30, 0x1d,
- 0xf5, 0x70, 0xad, 0x05, 0xed, 0x46, 0xab, 0x9b, 0x6e, 0x6e, 0x90, 0x04, 0x9c, 0xf6, 0xa7, 0xb8,
- 0x75, 0x07, 0x1b, 0x75, 0x98, 0xe7, 0x92, 0x75, 0xd9, 0x0a, 0xcc, 0x73, 0xe1, 0x15, 0x30, 0x23,
- 0x60, 0x7d, 0x4a, 0x87, 0x57, 0x35, 0xe5, 0x8b, 0xd9, 0xfb, 0xc4, 0x3a, 0x00, 0xf4, 0x5c, 0xb2,
- 0xaa, 0x53, 0x2a, 0x50, 0x63, 0x4c, 0x28, 0x23, 0x5e, 0xde, 0x6c, 0x06, 0xdc, 0x1b, 0x64, 0x4c,
- 0x28, 0x23, 0xde, 0x23, 0xa8, 0x02, 0x3d, 0x17, 0x5e, 0x05, 0x65, 0x01, 0x3c, 0x6c, 0x7d, 0x3e,
- 0x3c, 0xd8, 0xdc, 0x40, 0x13, 0x8e, 0x55, 0x99, 0xf0, 0x05, 0x41, 0x8d, 0x9a, 0x07, 0xa1, 0x9e,
- 0x8b, 0x26, 0x1d, 0xab, 0x32, 0xae, 0x41, 0x3d, 0x17, 0x5e, 0x07, 0xb3, 0x99, 0x7b, 0x4e, 0x7b,
- 0xc6, 0xb1, 0x2a, 0x33, 0xbe, 0xe0, 0xd8, 0x63, 0x76, 0x03, 0xd8, 0x73, 0x11, 0x70, 0xac, 0x4a,
- 0x59, 0x07, 0x7b, 0xae, 0x92, 0xfa, 0xc3, 0x76, 0x14, 0xa4, 0xa8, 0xe8, 0x58, 0x95, 0x42, 0x96,
- 0xfa, 0x1a, 0x36, 0x2a, 0xeb, 0x3f, 0x88, 0xfa, 0x2f, 0xdb, 0x21, 0x2a, 0x39, 0x56, 0xc5, 0xca,
- 0xd6, 0xff, 0x80, 0x58, 0xe1, 0x25, 0x20, 0x66, 0x36, 0x5e, 0x46, 0x51, 0x1b, 0x4d, 0x39, 0x56,
- 0x65, 0xd2, 0x2f, 0x71, 0x63, 0x35, 0x8a, 0xda, 0x6a, 0x36, 0xd3, 0xb8, 0xd5, 0x3d, 0x42, 0xd3,
- 0xb8, 0xaa, 0xa4, 0x6c, 0x12, 0xab, 0x12, 0xdd, 0xcb, 0xe3, 0x34, 0x4c, 0xd0, 0x0c, 0x2e, 0xe3,
- 0x2c, 0xba, 0x2a, 0x36, 0xc2, 0x06, 0x58, 0x12, 0xb0, 0x2e, 0x7d, 0xbc, 0x3b, 0x61, 0x92, 0x04,
- 0x47, 0x21, 0x82, 0x8e, 0x55, 0x29, 0x6e, 0x5c, 0x51, 0x1e, 0x6c, 0xb9, 0x44, 0x57, 0x77, 0x09,
- 0xfe, 0x09, 0x85, 0xfb, 0x0b, 0x9c, 0x47, 0x31, 0xc3, 0x7d, 0x80, 0xb2, 0x2c, 0x45, 0x71, 0xd8,
- 0x3a, 0xea, 0x0a, 0x0f, 0x73, 0xc4, 0xc3, 0x39, 0xc5, 0x43, 0x8d, 0x62, 0x38, 0xeb, 0xa2, 0x48,
- 0xa6, 0x62, 0x87, 0x1f, 0x80, 0x79, 0x3d, 0xee, 0xb0, 0xdb, 0xef, 0xa0, 0x05, 0xa2, 0x46, 0x6f,
- 0x9e, 0x14, 0xf4, 0x76, 0xb7, 0xdf, 0xf1, 0xa1, 0x1a, 0x31, 0xb6, 0xc1, 0xf7, 0xc1, 0xc2, 0x40,
- 0xb8, 0x84, 0x78, 0x91, 0x10, 0x23, 0x53, 0xac, 0x84, 0x6c, 0x4e, 0x0b, 0x94, 0xb0, 0x79, 0x12,
- 0x1b, 0xdd, 0xad, 0x46, 0xaf, 0x15, 0x36, 0x43, 0x84, 0xf0, 0x9e, 0x55, 0x0b, 0x93, 0x85, 0x6c,
- 0x1e, 0xdd, 0xb7, 0xa7, 0x78, 0x18, 0x5e, 0x91, 0x4a, 0xa1, 0x19, 0xc5, 0x07, 0xe8, 0x2c, 0xc3,
- 0x5b, 0x59, 0x39, 0xdc, 0x8f, 0xe2, 0x03, 0x58, 0x03, 0xb3, 0x71, 0xd8, 0xec, 0xc7, 0x49, 0xeb,
- 0xe3, 0x50, 0xa4, 0xf5, 0x1c, 0x49, 0xeb, 0xd9, 0xdc, 0x1c, 0xf8, 0x65, 0x31, 0x87, 0xa7, 0xf3,
- 0x32, 0x98, 0x8e, 0xc3, 0x5e, 0x18, 0xe0, 0x3c, 0xd2, 0x87, 0xf9, 0x82, 0x63, 0x63, 0xb5, 0xe1,
- 0x56, 0xa1, 0x36, 0x32, 0xcc, 0x73, 0x91, 0xe3, 0xd8, 0x58, 0x6d, 0x24, 0x18, 0xd5, 0x06, 0x01,
- 0x63, 0x6a, 0x73, 0xd1, 0xb1, 0xb1, 0xda, 0x70, 0x73, 0xa6, 0x36, 0x0a, 0xd0, 0x73, 0xd1, 0x8a,
- 0x63, 0x63, 0xb5, 0x91, 0x81, 0x1a, 0x23, 0x53, 0x9b, 0x4b, 0x8e, 0x8d, 0xd5, 0x86, 0x9b, 0xf7,
- 0x06, 0x19, 0x99, 0xda, 0xbc, 0xe9, 0xd8, 0x58, 0x6d, 0x64, 0x20, 0x55, 0x1b, 0x01, 0xe4, 0xb2,
- 0x70, 0xd9, 0xb1, 0xb1, 0xda, 0x70, 0xbb, 0xa4, 0x36, 0x2a, 0xd4, 0x73, 0xd1, 0x27, 0x1c, 0x1b,
- 0xab, 0x8d, 0x02, 0xa5, 0x6a, 0x93, 0xb9, 0xe7, 0xb4, 0x57, 0x1c, 0x1b, 0xab, 0x8d, 0x08, 0x40,
- 0x52, 0x1b, 0x0d, 0xec, 0xb9, 0xa8, 0xe2, 0xd8, 0x58, 0x6d, 0x54, 0x30, 0x55, 0x9b, 0x2c, 0x08,
- 0xa2, 0x36, 0x57, 0x1d, 0x1b, 0xab, 0x8d, 0x08, 0x81, 0xab, 0x8d, 0x80, 0x31, 0xb5, 0xb9, 0xe6,
- 0xd8, 0x58, 0x6d, 0xb8, 0x39, 0x53, 0x1b, 0x01, 0x24, 0x6a, 0x73, 0xdd, 0xb1, 0xb1, 0xda, 0x70,
- 0x23, 0x57, 0x9b, 0x2c, 0x42, 0xaa, 0x36, 0x6f, 0x39, 0x36, 0x56, 0x1b, 0x11, 0x9f, 0x50, 0x9b,
- 0x8c, 0x8d, 0xa8, 0xcd, 0xdb, 0x8e, 0x8d, 0xd5, 0x46, 0xd0, 0x71, 0xb5, 0x11, 0x30, 0x4d, 0x6d,
- 0xd6, 0x1c, 0xfb, 0xb5, 0xd4, 0x86, 0xf3, 0x0c, 0xa8, 0x4d, 0x96, 0x25, 0x4d, 0x6d, 0xd6, 0x89,
- 0x87, 0xe1, 0x6a, 0x23, 0x92, 0x39, 0xa0, 0x36, 0x7a, 0xdc, 0x44, 0x14, 0x36, 0x1d, 0x7b, 0x74,
- 0xb5, 0x51, 0x23, 0xe6, 0x6a, 0x33, 0x10, 0x2e, 0x21, 0x76, 0x09, 0xf1, 0x10, 0xb5, 0xd1, 0x02,
- 0xe5, 0x6a, 0xa3, 0xed, 0x16, 0x53, 0x1b, 0x0f, 0xef, 0x19, 0x55, 0x1b, 0x75, 0xdf, 0x84, 0xda,
- 0x88, 0x79, 0x44, 0x6d, 0x6e, 0x32, 0xbc, 0x95, 0x95, 0x03, 0x51, 0x9b, 0x67, 0x60, 0xa6, 0x13,
- 0xf4, 0xa8, 0x40, 0x30, 0x99, 0xb8, 0x45, 0x92, 0xfa, 0x56, 0x7e, 0x06, 0x9e, 0x04, 0x3d, 0xa2,
- 0x1d, 0xe4, 0x63, 0xbb, 0x9b, 0xc6, 0xc7, 0xfe, 0x54, 0x47, 0xb6, 0x49, 0xac, 0x9e, 0xcb, 0x54,
- 0xe5, 0xf6, 0x68, 0xac, 0x9e, 0x4b, 0x3e, 0x14, 0x56, 0x66, 0x83, 0x2f, 0xc0, 0x2c, 0x66, 0xa5,
- 0xf2, 0xc3, 0x55, 0xe8, 0x0e, 0xe1, 0x5d, 0x1d, 0xca, 0x4b, 0xa5, 0x89, 0x7e, 0x52, 0x66, 0x1c,
- 0x9e, 0x6c, 0x95, 0xb9, 0x3d, 0x97, 0x0b, 0xd7, 0xbb, 0x23, 0x72, 0x7b, 0x2e, 0xfd, 0x54, 0xb9,
- 0xb9, 0x95, 0x73, 0x53, 0x91, 0xe3, 0x5a, 0xf7, 0xc9, 0x11, 0xb8, 0xa9, 0x00, 0xee, 0x69, 0x71,
- 0xcb, 0x56, 0x99, 0xdb, 0x73, 0xb9, 0x3c, 0xbe, 0x37, 0x22, 0xb7, 0xe7, 0xee, 0x69, 0x71, 0xcb,
- 0x56, 0xf8, 0x59, 0x30, 0x87, 0xb9, 0x99, 0xb6, 0x09, 0x49, 0xbd, 0x4b, 0xd8, 0xd7, 0x86, 0xb2,
- 0x33, 0x9d, 0x65, 0x3f, 0x28, 0x3f, 0x0e, 0x54, 0xb5, 0x2b, 0x1e, 0x3c, 0x57, 0x28, 0xf1, 0xa7,
- 0x46, 0xf5, 0xe0, 0xb9, 0xec, 0x87, 0xe6, 0x41, 0xd8, 0xe1, 0x21, 0x58, 0x20, 0xf9, 0xe1, 0x8b,
- 0x10, 0x0a, 0x7e, 0x8f, 0xf8, 0xd8, 0x18, 0x9e, 0x23, 0x06, 0xe6, 0x3f, 0xa9, 0x17, 0x1c, 0xb2,
- 0x3e, 0xa2, 0xfa, 0xc1, 0x3b, 0xc1, 0xd7, 0xb2, 0x35, 0xb2, 0x1f, 0xcf, 0xe5, 0x3f, 0x75, 0x3f,
- 0xd9, 0x88, 0xfa, 0xbc, 0xd2, 0x43, 0xa3, 0x3a, 0xea, 0xf3, 0x4a, 0x8e, 0x13, 0xed, 0x79, 0xa5,
- 0x47, 0xcc, 0x73, 0x50, 0xce, 0x58, 0xd9, 0x19, 0x73, 0x9f, 0xd0, 0xbe, 0x7d, 0x32, 0x2d, 0x3d,
- 0x7d, 0x28, 0xef, 0x74, 0x47, 0x31, 0xc2, 0x5d, 0x80, 0x3d, 0x91, 0xd3, 0x88, 0x1e, 0x49, 0x0f,
- 0x08, 0xeb, 0xb5, 0xa1, 0xac, 0xf8, 0x9c, 0xc2, 0xff, 0x53, 0xca, 0x62, 0x27, 0xb3, 0x88, 0x72,
- 0xa7, 0x52, 0xc8, 0xce, 0xaf, 0xed, 0x51, 0xca, 0x9d, 0x40, 0xe9, 0xa7, 0x54, 0xee, 0x92, 0x95,
- 0x27, 0x81, 0x71, 0xd3, 0x23, 0xaf, 0x36, 0x42, 0x12, 0xe8, 0x74, 0x72, 0x1a, 0x66, 0x49, 0x90,
- 0x8c, 0xb0, 0x07, 0xce, 0x4a, 0xc4, 0xda, 0x21, 0xf9, 0x90, 0x78, 0xb8, 0x31, 0x82, 0x07, 0xe5,
- 0x58, 0xa4, 0x9e, 0x16, 0x3b, 0xc6, 0x41, 0x98, 0x80, 0x65, 0xc9, 0xa3, 0x7e, 0x6a, 0x3e, 0x22,
- 0x2e, 0xbd, 0x11, 0x5c, 0xaa, 0x67, 0x26, 0xf5, 0xb9, 0xd4, 0x31, 0x8f, 0xc2, 0x23, 0xb0, 0x38,
- 0xb8, 0x4c, 0x72, 0xf4, 0xed, 0x8c, 0xf2, 0x0c, 0x48, 0xcb, 0xc0, 0x47, 0x9f, 0xf4, 0x0c, 0x68,
- 0x23, 0xf0, 0x43, 0xb0, 0x64, 0x58, 0x1d, 0xf1, 0xf4, 0x98, 0x78, 0xda, 0x1c, 0x7d, 0x69, 0x99,
- 0xab, 0xf9, 0x8e, 0x61, 0x08, 0x5e, 0x02, 0xa5, 0xa8, 0x1b, 0x46, 0x87, 0xfc, 0xb8, 0x89, 0xf0,
- 0x15, 0xfb, 0xd1, 0x98, 0x5f, 0x24, 0x56, 0x76, 0x78, 0x7c, 0x06, 0xcc, 0x53, 0x90, 0xb6, 0xb7,
- 0xbd, 0xd7, 0xba, 0x6e, 0x3d, 0x1a, 0xf3, 0x21, 0xa1, 0x51, 0xf7, 0x52, 0x44, 0xc0, 0xaa, 0xfd,
- 0x23, 0xde, 0x91, 0x20, 0x56, 0x56, 0xbb, 0x17, 0x01, 0xfd, 0xca, 0xca, 0x36, 0x66, 0xed, 0x0d,
- 0x40, 0x8c, 0xb4, 0x0a, 0xeb, 0xd2, 0xc5, 0x85, 0x3c, 0x8f, 0xac, 0xf1, 0x84, 0x7e, 0x63, 0x91,
- 0x30, 0x97, 0x57, 0x69, 0x67, 0x6a, 0x95, 0xb7, 0x44, 0x56, 0xf1, 0x13, 0xf7, 0x41, 0xd0, 0xee,
- 0x87, 0xd9, 0x8d, 0x06, 0x9b, 0x9e, 0xd3, 0x79, 0xd0, 0x07, 0x8b, 0x6a, 0x3b, 0x43, 0x30, 0xfe,
- 0xd6, 0x62, 0xb7, 0x40, 0x9d, 0x91, 0x48, 0x03, 0xa5, 0x9c, 0x57, 0x9a, 0x1e, 0x39, 0x9c, 0x9e,
- 0x2b, 0x38, 0x7f, 0x37, 0x84, 0xd3, 0x73, 0x07, 0x39, 0x3d, 0x97, 0x73, 0xee, 0x4b, 0xf7, 0xe1,
- 0xbe, 0x1a, 0xe8, 0xef, 0x29, 0xe9, 0xf9, 0x01, 0xd2, 0x7d, 0x29, 0xd2, 0x05, 0xb5, 0x9f, 0x92,
- 0x47, 0x2b, 0xc5, 0xfa, 0x87, 0x61, 0xb4, 0x3c, 0xd8, 0x05, 0xb5, 0xfb, 0x62, 0xca, 0x00, 0xd1,
- 0x77, 0xc1, 0xfa, 0xc7, 0xbc, 0x0c, 0x10, 0x0d, 0xd7, 0x32, 0x40, 0x6c, 0xa6, 0x50, 0xa9, 0xba,
- 0x0b, 0xd2, 0x3f, 0xe5, 0x85, 0x4a, 0x05, 0x5c, 0x0b, 0x95, 0x1a, 0x4d, 0xb4, 0xec, 0x61, 0xe4,
- 0xb4, 0x7f, 0xce, 0xa3, 0xa5, 0xf5, 0xaa, 0xd1, 0x52, 0xa3, 0x29, 0x03, 0xa4, 0x9c, 0x05, 0xeb,
- 0x5f, 0xf2, 0x32, 0x40, 0x2a, 0x5c, 0xcb, 0x00, 0xb1, 0x71, 0xce, 0xba, 0xf4, 0x77, 0xb4, 0x52,
- 0xfc, 0x7f, 0xb5, 0x88, 0x62, 0x0c, 0x2d, 0x7e, 0xf9, 0xfe, 0x24, 0x05, 0xa9, 0xde, 0xae, 0x05,
- 0xe3, 0xdf, 0x2c, 0x76, 0x29, 0x19, 0x56, 0xfc, 0xca, 0x1d, 0x3c, 0x87, 0x53, 0x2a, 0xa8, 0xbf,
- 0x0f, 0xe1, 0x14, 0xc5, 0xaf, 0x5c, 0xd8, 0xa5, 0x3d, 0xd2, 0xee, 0xed, 0x82, 0xf4, 0x1f, 0x94,
- 0xf4, 0x84, 0xe2, 0x57, 0xaf, 0xf7, 0x79, 0xb4, 0x52, 0xac, 0xff, 0x1c, 0x46, 0x2b, 0x8a, 0x5f,
- 0x6d, 0x06, 0x98, 0x32, 0xa0, 0x16, 0xff, 0xbf, 0xf2, 0x32, 0x20, 0x17, 0xbf, 0x72, 0x6f, 0x36,
- 0x85, 0xaa, 0x15, 0xff, 0xbf, 0xf3, 0x42, 0x55, 0x8a, 0x5f, 0xbd, 0x65, 0x9b, 0x68, 0xb5, 0xe2,
- 0xff, 0x4f, 0x1e, 0xad, 0x52, 0xfc, 0xea, 0xb5, 0xcd, 0x94, 0x01, 0xb5, 0xf8, 0xff, 0x9b, 0x97,
- 0x01, 0xb9, 0xf8, 0x95, 0xbb, 0x39, 0xe7, 0x7c, 0x28, 0xb5, 0x40, 0xf9, 0xeb, 0x0e, 0xf4, 0xbd,
- 0x02, 0x6b, 0x29, 0x0d, 0xac, 0x9d, 0x21, 0xb2, 0xf6, 0x28, 0xb7, 0xc0, 0xc7, 0x40, 0xf4, 0xd7,
- 0x1a, 0xe2, 0xbd, 0x06, 0xfa, 0x7e, 0x21, 0xe7, 0xfc, 0x78, 0xc6, 0x21, 0xbe, 0xf0, 0x2f, 0x4c,
- 0xf0, 0xd3, 0x60, 0x4e, 0xea, 0xf7, 0xf2, 0x77, 0x2c, 0xe8, 0x07, 0x79, 0x64, 0x35, 0x8c, 0x79,
- 0x12, 0x24, 0xaf, 0x32, 0x32, 0x61, 0x82, 0x5b, 0x6a, 0x0b, 0xb5, 0xdf, 0x4c, 0xd1, 0x0f, 0x29,
- 0xd1, 0x92, 0x69, 0x13, 0xfa, 0xcd, 0x54, 0x69, 0xae, 0xf6, 0x9b, 0x29, 0xbc, 0x05, 0x44, 0x1b,
- 0xae, 0x11, 0x74, 0x8f, 0xd1, 0x8f, 0xe8, 0xfc, 0xf9, 0x81, 0xf9, 0x5b, 0xdd, 0x63, 0xbf, 0xc8,
- 0xa1, 0x5b, 0xdd, 0x63, 0x78, 0x57, 0x6a, 0xcb, 0x7e, 0x8c, 0xb7, 0x01, 0xfd, 0x98, 0xce, 0x5d,
- 0x1c, 0x98, 0x4b, 0x77, 0x49, 0x34, 0x02, 0xc9, 0x57, 0xbc, 0x3d, 0x59, 0x81, 0xf2, 0xed, 0xf9,
- 0x69, 0x81, 0xec, 0xf6, 0xb0, 0xed, 0x11, 0x75, 0x29, 0x6d, 0x8f, 0x20, 0xca, 0xb6, 0xe7, 0x67,
- 0x85, 0x1c, 0x85, 0x93, 0xb6, 0x87, 0x4f, 0xcb, 0xb6, 0x47, 0xe6, 0x22, 0xdb, 0x43, 0x76, 0xe7,
- 0xe7, 0x79, 0x5c, 0xd2, 0xee, 0x64, 0xfd, 0x33, 0x36, 0x0b, 0xef, 0x8e, 0xfc, 0xa8, 0xe0, 0xdd,
- 0xf9, 0x35, 0x25, 0xca, 0xdf, 0x1d, 0xe9, 0xe9, 0x60, 0xbb, 0x23, 0x28, 0xf0, 0xee, 0xfc, 0x82,
- 0xce, 0xcf, 0xd9, 0x1d, 0x0e, 0x65, 0xbb, 0x23, 0x66, 0xd2, 0xdd, 0xf9, 0x25, 0x9d, 0x9b, 0xbb,
- 0x3b, 0x1c, 0x4e, 0x77, 0xe7, 0x02, 0x00, 0x64, 0xfd, 0xdd, 0xa0, 0x13, 0xae, 0xa3, 0x2f, 0xd9,
- 0xe4, 0x8d, 0x8d, 0x64, 0x82, 0x0e, 0x28, 0xd2, 0xfa, 0xc5, 0x5f, 0x37, 0xd0, 0x97, 0x65, 0xc4,
- 0x2e, 0x36, 0xc1, 0x8b, 0xa0, 0xd4, 0xc8, 0x20, 0x9b, 0xe8, 0x2b, 0x0c, 0x52, 0xe3, 0x90, 0x4d,
- 0xb8, 0x02, 0xa6, 0x28, 0x82, 0x40, 0xdc, 0x06, 0xfa, 0xaa, 0x4e, 0xe3, 0xe2, 0xbf, 0xf1, 0xc8,
- 0xb7, 0x35, 0x0c, 0xb9, 0x81, 0xbe, 0x46, 0x11, 0xb2, 0x0d, 0x5e, 0xe2, 0x34, 0x6b, 0x84, 0xc7,
- 0x43, 0x5f, 0x57, 0x40, 0x98, 0xc7, 0x13, 0x2b, 0xc2, 0xdf, 0x6e, 0xa2, 0x6f, 0xe8, 0x8e, 0x6e,
- 0x62, 0x80, 0x08, 0xed, 0x16, 0xfa, 0xa6, 0x1e, 0xed, 0xad, 0x6c, 0xc9, 0xf8, 0xeb, 0x6d, 0xf4,
- 0x2d, 0x9d, 0xe2, 0x36, 0x5c, 0x01, 0xa5, 0x9a, 0x40, 0xac, 0xaf, 0xa1, 0x6f, 0xb3, 0x38, 0x04,
- 0xc9, 0xfa, 0x1a, 0xc1, 0xec, 0x6c, 0xbf, 0xff, 0xa0, 0xb1, 0xbb, 0xf5, 0x64, 0x7b, 0x7d, 0x1d,
- 0x7d, 0x87, 0x63, 0xb0, 0x91, 0xda, 0x32, 0x0c, 0xc9, 0xf5, 0x06, 0xfa, 0xae, 0x82, 0x21, 0xb6,
- 0xe5, 0x17, 0x60, 0x4a, 0xfd, 0x8b, 0xb9, 0x04, 0xac, 0x80, 0xbd, 0x5a, 0xb3, 0x02, 0xf8, 0x2e,
- 0x28, 0x36, 0x23, 0xd1, 0x1d, 0x47, 0x85, 0x93, 0x3a, 0xe9, 0x32, 0x7a, 0xf9, 0x1e, 0x80, 0x83,
- 0xdd, 0x2e, 0x58, 0x06, 0xf6, 0xab, 0xf0, 0x98, 0xb9, 0xc0, 0xbf, 0xc2, 0x79, 0x70, 0x9a, 0x16,
- 0x57, 0x81, 0xd8, 0xe8, 0x97, 0x3b, 0x85, 0x5b, 0x56, 0xc6, 0x20, 0x77, 0xb6, 0x64, 0x06, 0xdb,
- 0xc0, 0x60, 0xcb, 0x0c, 0x55, 0x30, 0x6f, 0xea, 0x61, 0xc9, 0x1c, 0x53, 0x06, 0x8e, 0x29, 0x33,
- 0x87, 0xd2, 0xab, 0x92, 0x39, 0x4e, 0x19, 0x38, 0x4e, 0x0d, 0x72, 0x0c, 0xf4, 0xa4, 0x64, 0x8e,
- 0x59, 0x03, 0xc7, 0xac, 0x99, 0x43, 0xe9, 0x3d, 0xc9, 0x1c, 0xd0, 0xc0, 0x01, 0x65, 0x8e, 0x07,
- 0x60, 0xd1, 0xdc, 0x61, 0x92, 0x59, 0x26, 0x0c, 0x2c, 0x13, 0x39, 0x2c, 0x6a, 0x17, 0x49, 0x66,
- 0x19, 0x37, 0xb0, 0x8c, 0xcb, 0x2c, 0x35, 0x80, 0xf2, 0xfa, 0x44, 0x32, 0xcf, 0x8c, 0x81, 0x67,
- 0x26, 0x8f, 0x47, 0xeb, 0x03, 0xc9, 0x3c, 0x65, 0x03, 0x4f, 0xd9, 0x58, 0x6d, 0x72, 0xb7, 0xe7,
- 0xa4, 0x7a, 0x2d, 0xc8, 0x0c, 0x5b, 0x60, 0xce, 0xd0, 0xd8, 0x39, 0x89, 0xc2, 0x92, 0x29, 0xee,
- 0x82, 0xb2, 0xde, 0xc5, 0x91, 0xe7, 0x4f, 0x1a, 0xe6, 0x4f, 0x1a, 0x8a, 0x44, 0xef, 0xd8, 0xc8,
- 0x1c, 0x67, 0x0c, 0x1c, 0x67, 0x06, 0x97, 0xa1, 0xb7, 0x66, 0x4e, 0xa2, 0x28, 0xc9, 0x14, 0x31,
- 0x38, 0x37, 0xa4, 0xf7, 0x62, 0xa0, 0x7a, 0x4f, 0xa6, 0x7a, 0x8d, 0x17, 0x1f, 0x92, 0xcf, 0x23,
- 0x70, 0x7e, 0x58, 0xf3, 0xc5, 0xe0, 0x74, 0x5d, 0x75, 0x3a, 0xf4, 0x5d, 0x88, 0xe4, 0xa8, 0x4d,
- 0x0b, 0xce, 0xd4, 0x74, 0x31, 0x38, 0xb9, 0x23, 0x3b, 0x19, 0xf5, 0xed, 0x88, 0xe4, 0x2d, 0x00,
- 0x67, 0x73, 0x1b, 0x2f, 0x06, 0x77, 0xab, 0xaa, 0xbb, 0xfc, 0x77, 0x26, 0x99, 0x8b, 0x95, 0xdb,
- 0x00, 0x48, 0x2d, 0xa2, 0x09, 0x60, 0xd7, 0xea, 0xf5, 0xf2, 0x18, 0xfe, 0xa5, 0xba, 0xe5, 0x97,
- 0x2d, 0xfa, 0xcb, 0x8b, 0x72, 0x01, 0xbb, 0xdb, 0xdd, 0x7e, 0x58, 0xfe, 0x1f, 0xff, 0xcf, 0xaa,
- 0x4e, 0xf1, 0xe6, 0x09, 0x39, 0xc0, 0x56, 0xde, 0x00, 0xd3, 0x5a, 0x67, 0xab, 0x04, 0xac, 0x26,
- 0x3f, 0x50, 0x9a, 0xd7, 0x6e, 0x00, 0x90, 0xfd, 0x63, 0x18, 0x38, 0x03, 0x8a, 0xfb, 0xbb, 0x7b,
- 0x4f, 0xb7, 0xef, 0xef, 0xd4, 0x76, 0xb6, 0x1f, 0x94, 0xc7, 0x60, 0x09, 0x4c, 0x3e, 0xf5, 0xeb,
- 0xcf, 0xea, 0xd5, 0xfd, 0x5a, 0xd9, 0x82, 0x93, 0xe0, 0xd4, 0xe3, 0xbd, 0xfa, 0x6e, 0xb9, 0x70,
- 0xed, 0x1e, 0x28, 0xca, 0x8d, 0xa5, 0x19, 0x50, 0xac, 0xd5, 0xfd, 0xed, 0x9d, 0x87, 0xbb, 0x0d,
- 0x1a, 0xa9, 0x64, 0xa0, 0x11, 0x2b, 0x86, 0x17, 0xe5, 0x42, 0xf5, 0x22, 0xb8, 0xd0, 0x8c, 0x3a,
- 0x03, 0x7f, 0xb6, 0x48, 0xc9, 0x79, 0x39, 0x4e, 0xac, 0x9b, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff,
- 0x29, 0x30, 0x51, 0x54, 0x22, 0x25, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto b/vendor/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto
deleted file mode 100644
index fc96074ac..000000000
--- a/vendor/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto
+++ /dev/null
@@ -1,273 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package conformance;
-option java_package = "com.google.protobuf.conformance";
-
-import "google/protobuf/any.proto";
-import "google/protobuf/duration.proto";
-import "google/protobuf/field_mask.proto";
-import "google/protobuf/struct.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-
-// This defines the conformance testing protocol. This protocol exists between
-// the conformance test suite itself and the code being tested. For each test,
-// the suite will send a ConformanceRequest message and expect a
-// ConformanceResponse message.
-//
-// You can either run the tests in two different ways:
-//
-// 1. in-process (using the interface in conformance_test.h).
-//
-// 2. as a sub-process communicating over a pipe. Information about how to
-// do this is in conformance_test_runner.cc.
-//
-// Pros/cons of the two approaches:
-//
-// - running as a sub-process is much simpler for languages other than C/C++.
-//
-// - running as a sub-process may be more tricky in unusual environments like
-// iOS apps, where fork/stdin/stdout are not available.
-
-enum WireFormat {
- UNSPECIFIED = 0;
- PROTOBUF = 1;
- JSON = 2;
-}
-
-// Represents a single test case's input. The testee should:
-//
-// 1. parse this proto (which should always succeed)
-// 2. parse the protobuf or JSON payload in "payload" (which may fail)
-// 3. if the parse succeeded, serialize the message in the requested format.
-message ConformanceRequest {
- // The payload (whether protobuf of JSON) is always for a TestAllTypes proto
- // (see below).
- oneof payload {
- bytes protobuf_payload = 1;
- string json_payload = 2;
- }
-
- // Which format should the testee serialize its message to?
- WireFormat requested_output_format = 3;
-}
-
-// Represents a single test case's output.
-message ConformanceResponse {
- oneof result {
- // This string should be set to indicate parsing failed. The string can
- // provide more information about the parse error if it is available.
- //
- // Setting this string does not necessarily mean the testee failed the
- // test. Some of the test cases are intentionally invalid input.
- string parse_error = 1;
-
- // If the input was successfully parsed but errors occurred when
- // serializing it to the requested output format, set the error message in
- // this field.
- string serialize_error = 6;
-
- // This should be set if some other error occurred. This will always
- // indicate that the test failed. The string can provide more information
- // about the failure.
- string runtime_error = 2;
-
- // If the input was successfully parsed and the requested output was
- // protobuf, serialize it to protobuf and set it in this field.
- bytes protobuf_payload = 3;
-
- // If the input was successfully parsed and the requested output was JSON,
- // serialize to JSON and set it in this field.
- string json_payload = 4;
-
- // For when the testee skipped the test, likely because a certain feature
- // wasn't supported, like JSON input/output.
- string skipped = 5;
- }
-}
-
-// This proto includes every type of field in both singular and repeated
-// forms.
-message TestAllTypes {
- message NestedMessage {
- int32 a = 1;
- TestAllTypes corecursive = 2;
- }
-
- enum NestedEnum {
- FOO = 0;
- BAR = 1;
- BAZ = 2;
- NEG = -1; // Intentionally negative.
- }
-
- // Singular
- int32 optional_int32 = 1;
- int64 optional_int64 = 2;
- uint32 optional_uint32 = 3;
- uint64 optional_uint64 = 4;
- sint32 optional_sint32 = 5;
- sint64 optional_sint64 = 6;
- fixed32 optional_fixed32 = 7;
- fixed64 optional_fixed64 = 8;
- sfixed32 optional_sfixed32 = 9;
- sfixed64 optional_sfixed64 = 10;
- float optional_float = 11;
- double optional_double = 12;
- bool optional_bool = 13;
- string optional_string = 14;
- bytes optional_bytes = 15;
-
- NestedMessage optional_nested_message = 18;
- ForeignMessage optional_foreign_message = 19;
-
- NestedEnum optional_nested_enum = 21;
- ForeignEnum optional_foreign_enum = 22;
-
- string optional_string_piece = 24 [ctype=STRING_PIECE];
- string optional_cord = 25 [ctype=CORD];
-
- TestAllTypes recursive_message = 27;
-
- // Repeated
- repeated int32 repeated_int32 = 31;
- repeated int64 repeated_int64 = 32;
- repeated uint32 repeated_uint32 = 33;
- repeated uint64 repeated_uint64 = 34;
- repeated sint32 repeated_sint32 = 35;
- repeated sint64 repeated_sint64 = 36;
- repeated fixed32 repeated_fixed32 = 37;
- repeated fixed64 repeated_fixed64 = 38;
- repeated sfixed32 repeated_sfixed32 = 39;
- repeated sfixed64 repeated_sfixed64 = 40;
- repeated float repeated_float = 41;
- repeated double repeated_double = 42;
- repeated bool repeated_bool = 43;
- repeated string repeated_string = 44;
- repeated bytes repeated_bytes = 45;
-
- repeated NestedMessage repeated_nested_message = 48;
- repeated ForeignMessage repeated_foreign_message = 49;
-
- repeated NestedEnum repeated_nested_enum = 51;
- repeated ForeignEnum repeated_foreign_enum = 52;
-
- repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
- repeated string repeated_cord = 55 [ctype=CORD];
-
- // Map
- map < int32, int32> map_int32_int32 = 56;
- map < int64, int64> map_int64_int64 = 57;
- map < uint32, uint32> map_uint32_uint32 = 58;
- map < uint64, uint64> map_uint64_uint64 = 59;
- map < sint32, sint32> map_sint32_sint32 = 60;
- map < sint64, sint64> map_sint64_sint64 = 61;
- map < fixed32, fixed32> map_fixed32_fixed32 = 62;
- map < fixed64, fixed64> map_fixed64_fixed64 = 63;
- map map_sfixed32_sfixed32 = 64;
- map map_sfixed64_sfixed64 = 65;
- map < int32, float> map_int32_float = 66;
- map < int32, double> map_int32_double = 67;
- map < bool, bool> map_bool_bool = 68;
- map < string, string> map_string_string = 69;
- map < string, bytes> map_string_bytes = 70;
- map < string, NestedMessage> map_string_nested_message = 71;
- map < string, ForeignMessage> map_string_foreign_message = 72;
- map < string, NestedEnum> map_string_nested_enum = 73;
- map < string, ForeignEnum> map_string_foreign_enum = 74;
-
- oneof oneof_field {
- uint32 oneof_uint32 = 111;
- NestedMessage oneof_nested_message = 112;
- string oneof_string = 113;
- bytes oneof_bytes = 114;
- }
-
- // Well-known types
- google.protobuf.BoolValue optional_bool_wrapper = 201;
- google.protobuf.Int32Value optional_int32_wrapper = 202;
- google.protobuf.Int64Value optional_int64_wrapper = 203;
- google.protobuf.UInt32Value optional_uint32_wrapper = 204;
- google.protobuf.UInt64Value optional_uint64_wrapper = 205;
- google.protobuf.FloatValue optional_float_wrapper = 206;
- google.protobuf.DoubleValue optional_double_wrapper = 207;
- google.protobuf.StringValue optional_string_wrapper = 208;
- google.protobuf.BytesValue optional_bytes_wrapper = 209;
-
- repeated google.protobuf.BoolValue repeated_bool_wrapper = 211;
- repeated google.protobuf.Int32Value repeated_int32_wrapper = 212;
- repeated google.protobuf.Int64Value repeated_int64_wrapper = 213;
- repeated google.protobuf.UInt32Value repeated_uint32_wrapper = 214;
- repeated google.protobuf.UInt64Value repeated_uint64_wrapper = 215;
- repeated google.protobuf.FloatValue repeated_float_wrapper = 216;
- repeated google.protobuf.DoubleValue repeated_double_wrapper = 217;
- repeated google.protobuf.StringValue repeated_string_wrapper = 218;
- repeated google.protobuf.BytesValue repeated_bytes_wrapper = 219;
-
- google.protobuf.Duration optional_duration = 301;
- google.protobuf.Timestamp optional_timestamp = 302;
- google.protobuf.FieldMask optional_field_mask = 303;
- google.protobuf.Struct optional_struct = 304;
- google.protobuf.Any optional_any = 305;
- google.protobuf.Value optional_value = 306;
-
- repeated google.protobuf.Duration repeated_duration = 311;
- repeated google.protobuf.Timestamp repeated_timestamp = 312;
- repeated google.protobuf.FieldMask repeated_fieldmask = 313;
- repeated google.protobuf.Struct repeated_struct = 324;
- repeated google.protobuf.Any repeated_any = 315;
- repeated google.protobuf.Value repeated_value = 316;
-
- // Test field-name-to-JSON-name convention.
- int32 fieldname1 = 401;
- int32 field_name2 = 402;
- int32 _field_name3 = 403;
- int32 field__name4_ = 404;
- int32 field0name5 = 405;
- int32 field_0_name6 = 406;
- int32 fieldName7 = 407;
- int32 FieldName8 = 408;
- int32 field_Name9 = 409;
- int32 Field_Name10 = 410;
- int32 FIELD_NAME11 = 411;
- int32 FIELD_name12 = 412;
-}
-
-message ForeignMessage {
- int32 c = 1;
-}
-
-enum ForeignEnum {
- FOREIGN_FOO = 0;
- FOREIGN_BAR = 1;
- FOREIGN_BAZ = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/conformance/test.sh b/vendor/github.com/golang/protobuf/conformance/test.sh
deleted file mode 100644
index e6de29b9a..000000000
--- a/vendor/github.com/golang/protobuf/conformance/test.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/bin/bash
-
-PROTOBUF_ROOT=$1
-CONFORMANCE_ROOT=$1/conformance
-CONFORMANCE_TEST_RUNNER=$CONFORMANCE_ROOT/conformance-test-runner
-
-cd $(dirname $0)
-
-if [[ $PROTOBUF_ROOT == "" ]]; then
- echo "usage: test.sh " >/dev/stderr
- exit 1
-fi
-
-if [[ ! -x $CONFORMANCE_TEST_RUNNER ]]; then
- echo "SKIP: conformance test runner not installed" >/dev/stderr
- exit 0
-fi
-
-a=$CONFORMANCE_ROOT/conformance.proto
-b=internal/conformance_proto/conformance.proto
-if [[ $(diff $a $b) != "" ]]; then
- cp $a $b
- echo "WARNING: conformance.proto is out of date" >/dev/stderr
-fi
-
-$CONFORMANCE_TEST_RUNNER --failure_list failure_list_go.txt ./conformance.sh
diff --git a/vendor/github.com/golang/protobuf/descriptor/descriptor.go b/vendor/github.com/golang/protobuf/descriptor/descriptor.go
index ac7e51bfb..c3c4a2b87 100644
--- a/vendor/github.com/golang/protobuf/descriptor/descriptor.go
+++ b/vendor/github.com/golang/protobuf/descriptor/descriptor.go
@@ -1,92 +1,184 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Package descriptor provides functions for obtaining protocol buffer
-// descriptors for generated Go types.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package descriptor provides functions for obtaining the protocol buffer
+// descriptors of generated Go types.
//
-// These functions cannot go in package proto because they depend on the
-// generated protobuf descriptor messages, which themselves depend on proto.
+// Deprecated: See the "google.golang.org/protobuf/reflect/protoreflect" package
+// for how to obtain an EnumDescriptor or MessageDescriptor in order to
+// programatically interact with the protobuf type system.
package descriptor
import (
"bytes"
"compress/gzip"
- "fmt"
"io/ioutil"
+ "sync"
"github.com/golang/protobuf/proto"
- protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
+ "google.golang.org/protobuf/reflect/protodesc"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/runtime/protoimpl"
+
+ descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
)
-// extractFile extracts a FileDescriptorProto from a gzip'd buffer.
-func extractFile(gz []byte) (*protobuf.FileDescriptorProto, error) {
- r, err := gzip.NewReader(bytes.NewReader(gz))
- if err != nil {
- return nil, fmt.Errorf("failed to open gzip reader: %v", err)
+// Message is proto.Message with a method to return its descriptor.
+//
+// Deprecated: The Descriptor method may not be generated by future
+// versions of protoc-gen-go, meaning that this interface may not
+// be implemented by many concrete message types.
+type Message interface {
+ proto.Message
+ Descriptor() ([]byte, []int)
+}
+
+// ForMessage returns the file descriptor proto containing
+// the message and the message descriptor proto for the message itself.
+// The returned proto messages must not be mutated.
+//
+// Deprecated: Not all concrete message types satisfy the Message interface.
+// Use MessageDescriptorProto instead. If possible, the calling code should
+// be rewritten to use protobuf reflection instead.
+// See package "google.golang.org/protobuf/reflect/protoreflect" for details.
+func ForMessage(m Message) (*descriptorpb.FileDescriptorProto, *descriptorpb.DescriptorProto) {
+ return MessageDescriptorProto(m)
+}
+
+type rawDesc struct {
+ fileDesc []byte
+ indexes []int
+}
+
+var rawDescCache sync.Map // map[protoreflect.Descriptor]*rawDesc
+
+func deriveRawDescriptor(d protoreflect.Descriptor) ([]byte, []int) {
+ // Fast-path: check whether raw descriptors are already cached.
+ origDesc := d
+ if v, ok := rawDescCache.Load(origDesc); ok {
+ return v.(*rawDesc).fileDesc, v.(*rawDesc).indexes
}
- defer r.Close()
- b, err := ioutil.ReadAll(r)
- if err != nil {
- return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
+ // Slow-path: derive the raw descriptor from the v2 descriptor.
+
+ // Start with the leaf (a given enum or message declaration) and
+ // ascend upwards until we hit the parent file descriptor.
+ var idxs []int
+ for {
+ idxs = append(idxs, d.Index())
+ d = d.Parent()
+ if d == nil {
+ // TODO: We could construct a FileDescriptor stub for standalone
+ // descriptors to satisfy the API.
+ return nil, nil
+ }
+ if _, ok := d.(protoreflect.FileDescriptor); ok {
+ break
+ }
}
- fd := new(protobuf.FileDescriptorProto)
- if err := proto.Unmarshal(b, fd); err != nil {
- return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
+ // Obtain the raw file descriptor.
+ var raw []byte
+ switch fd := d.(type) {
+ case interface{ ProtoLegacyRawDesc() []byte }:
+ raw = fd.ProtoLegacyRawDesc()
+ case protoreflect.FileDescriptor:
+ raw, _ = proto.Marshal(protodesc.ToFileDescriptorProto(fd))
}
+ file := protoimpl.X.CompressGZIP(raw)
- return fd, nil
+ // Reverse the indexes, since we populated it in reverse.
+ for i, j := 0, len(idxs)-1; i < j; i, j = i+1, j-1 {
+ idxs[i], idxs[j] = idxs[j], idxs[i]
+ }
+
+ if v, ok := rawDescCache.LoadOrStore(origDesc, &rawDesc{file, idxs}); ok {
+ return v.(*rawDesc).fileDesc, v.(*rawDesc).indexes
+ }
+ return file, idxs
}
-// Message is a proto.Message with a method to return its descriptor.
-//
-// Message types generated by the protocol compiler always satisfy
-// the Message interface.
-type Message interface {
- proto.Message
- Descriptor() ([]byte, []int)
+// EnumRawDescriptor returns the GZIP'd raw file descriptor representing
+// the enum and the index path to reach the enum declaration.
+// The returned slices must not be mutated.
+func EnumRawDescriptor(e proto.GeneratedEnum) ([]byte, []int) {
+ if ev, ok := e.(interface{ EnumDescriptor() ([]byte, []int) }); ok {
+ return ev.EnumDescriptor()
+ }
+ ed := protoimpl.X.EnumTypeOf(e)
+ return deriveRawDescriptor(ed.Descriptor())
+}
+
+// MessageRawDescriptor returns the GZIP'd raw file descriptor representing
+// the message and the index path to reach the message declaration.
+// The returned slices must not be mutated.
+func MessageRawDescriptor(m proto.GeneratedMessage) ([]byte, []int) {
+ if mv, ok := m.(interface{ Descriptor() ([]byte, []int) }); ok {
+ return mv.Descriptor()
+ }
+ md := protoimpl.X.MessageTypeOf(m)
+ return deriveRawDescriptor(md.Descriptor())
}
-// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
-// describing the given message.
-func ForMessage(msg Message) (fd *protobuf.FileDescriptorProto, md *protobuf.DescriptorProto) {
- gz, path := msg.Descriptor()
- fd, err := extractFile(gz)
+var fileDescCache sync.Map // map[*byte]*descriptorpb.FileDescriptorProto
+
+func deriveFileDescriptor(rawDesc []byte) *descriptorpb.FileDescriptorProto {
+ // Fast-path: check whether descriptor protos are already cached.
+ if v, ok := fileDescCache.Load(&rawDesc[0]); ok {
+ return v.(*descriptorpb.FileDescriptorProto)
+ }
+
+ // Slow-path: derive the descriptor proto from the GZIP'd message.
+ zr, err := gzip.NewReader(bytes.NewReader(rawDesc))
+ if err != nil {
+ panic(err)
+ }
+ b, err := ioutil.ReadAll(zr)
if err != nil {
- panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
+ panic(err)
+ }
+ fd := new(descriptorpb.FileDescriptorProto)
+ if err := proto.Unmarshal(b, fd); err != nil {
+ panic(err)
+ }
+ if v, ok := fileDescCache.LoadOrStore(&rawDesc[0], fd); ok {
+ return v.(*descriptorpb.FileDescriptorProto)
+ }
+ return fd
+}
+
+// EnumDescriptorProto returns the file descriptor proto representing
+// the enum and the enum descriptor proto for the enum itself.
+// The returned proto messages must not be mutated.
+func EnumDescriptorProto(e proto.GeneratedEnum) (*descriptorpb.FileDescriptorProto, *descriptorpb.EnumDescriptorProto) {
+ rawDesc, idxs := EnumRawDescriptor(e)
+ if rawDesc == nil || idxs == nil {
+ return nil, nil
+ }
+ fd := deriveFileDescriptor(rawDesc)
+ if len(idxs) == 1 {
+ return fd, fd.EnumType[idxs[0]]
+ }
+ md := fd.MessageType[idxs[0]]
+ for _, i := range idxs[1 : len(idxs)-1] {
+ md = md.NestedType[i]
}
+ ed := md.EnumType[idxs[len(idxs)-1]]
+ return fd, ed
+}
- md = fd.MessageType[path[0]]
- for _, i := range path[1:] {
+// MessageDescriptorProto returns the file descriptor proto representing
+// the message and the message descriptor proto for the message itself.
+// The returned proto messages must not be mutated.
+func MessageDescriptorProto(m proto.GeneratedMessage) (*descriptorpb.FileDescriptorProto, *descriptorpb.DescriptorProto) {
+ rawDesc, idxs := MessageRawDescriptor(m)
+ if rawDesc == nil || idxs == nil {
+ return nil, nil
+ }
+ fd := deriveFileDescriptor(rawDesc)
+ md := fd.MessageType[idxs[0]]
+ for _, i := range idxs[1:] {
md = md.NestedType[i]
}
return fd, md
diff --git a/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go b/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go
index bf5174d3b..28083979c 100644
--- a/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go
+++ b/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go
@@ -1,32 +1,85 @@
-package descriptor_test
+// Copyright 2020 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package descriptor
import (
- "fmt"
"testing"
- "github.com/golang/protobuf/descriptor"
- tpb "github.com/golang/protobuf/proto/test_proto"
- protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
+ "github.com/google/go-cmp/cmp"
+ "google.golang.org/protobuf/reflect/protoreflect"
+
+ descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
)
-func TestMessage(t *testing.T) {
- var msg *protobuf.DescriptorProto
- fd, md := descriptor.ForMessage(msg)
- if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want {
- t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want)
- }
- if name, want := md.GetName(), "DescriptorProto"; name != want {
- t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want)
+func TestEnumDescriptor(t *testing.T) {
+ tests := []struct {
+ enum protoreflect.Enum
+ idxs []int
+ name string
+ }{{
+ enum: descpb.FieldDescriptorProto_Type(0),
+ idxs: []int{
+ new(descpb.FieldDescriptorProto).ProtoReflect().Descriptor().Index(),
+ new(descpb.FieldDescriptorProto_Type).Descriptor().Index(),
+ },
+ name: "Type",
+ }, {
+ enum: descpb.FieldOptions_CType(0),
+ idxs: []int{
+ new(descpb.FieldOptions).ProtoReflect().Descriptor().Index(),
+ new(descpb.FieldOptions_CType).Descriptor().Index(),
+ },
+ name: "CType",
+ }}
+
+ for _, tt := range tests {
+ e := struct{ protoreflect.Enum }{tt.enum} // v2-only enum
+
+ _, idxs := EnumRawDescriptor(e)
+ if diff := cmp.Diff(tt.idxs, idxs); diff != "" {
+ t.Errorf("path index mismatch (-want +got):\n%v", diff)
+ }
+
+ _, ed := EnumDescriptorProto(e)
+ if ed.GetName() != tt.name {
+ t.Errorf("mismatching enum name: got %v, want %v", ed.GetName(), tt.name)
+ }
}
}
-func Example_options() {
- var msg *tpb.MyMessageSet
- _, md := descriptor.ForMessage(msg)
- if md.GetOptions().GetMessageSetWireFormat() {
- fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName())
- }
+func TestMessageDescriptor(t *testing.T) {
+ tests := []struct {
+ message protoreflect.ProtoMessage
+ idxs []int
+ name string
+ }{{
+ message: (*descpb.SourceCodeInfo_Location)(nil),
+ idxs: []int{
+ new(descpb.SourceCodeInfo).ProtoReflect().Descriptor().Index(),
+ new(descpb.SourceCodeInfo_Location).ProtoReflect().Descriptor().Index(),
+ },
+ name: "Location",
+ }, {
+ message: (*descpb.FileDescriptorProto)(nil),
+ idxs: []int{
+ new(descpb.FileDescriptorProto).ProtoReflect().Descriptor().Index(),
+ },
+ name: "FileDescriptorProto",
+ }}
+
+ for _, tt := range tests {
+ m := struct{ protoreflect.ProtoMessage }{tt.message} // v2-only message
- // Output:
- // MyMessageSet uses option message_set_wire_format.
+ _, idxs := MessageRawDescriptor(m)
+ if diff := cmp.Diff(tt.idxs, idxs); diff != "" {
+ t.Errorf("path index mismatch (-want +got):\n%v", diff)
+ }
+
+ _, md := MessageDescriptorProto(m)
+ if md.GetName() != tt.name {
+ t.Errorf("mismatching message name: got %v, want %v", md.GetName(), tt.name)
+ }
+ }
}
diff --git a/vendor/github.com/golang/protobuf/go.mod b/vendor/github.com/golang/protobuf/go.mod
new file mode 100644
index 000000000..67adeed86
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/go.mod
@@ -0,0 +1,8 @@
+module github.com/golang/protobuf
+
+go 1.9
+
+require (
+ github.com/google/go-cmp v0.4.0
+ google.golang.org/protobuf v1.23.0
+)
diff --git a/vendor/github.com/golang/protobuf/go.sum b/vendor/github.com/golang/protobuf/go.sum
new file mode 100644
index 000000000..92baf2631
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/go.sum
@@ -0,0 +1,18 @@
+github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
+github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
+github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
+github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
+github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
+github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
+github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
+google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
+google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
+google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
diff --git a/vendor/github.com/golang/protobuf/internal/cmd/generate-alias/main.go b/vendor/github.com/golang/protobuf/internal/cmd/generate-alias/main.go
new file mode 100644
index 000000000..6c16e6dc6
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/internal/cmd/generate-alias/main.go
@@ -0,0 +1,132 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:generate go run . -execute
+
+package main
+
+import (
+ "flag"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "strings"
+
+ "github.com/golang/protobuf/proto"
+ gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
+ "google.golang.org/protobuf/compiler/protogen"
+ "google.golang.org/protobuf/reflect/protodesc"
+ "google.golang.org/protobuf/reflect/protoreflect"
+
+ "google.golang.org/protobuf/types/descriptorpb"
+ "google.golang.org/protobuf/types/known/anypb"
+ "google.golang.org/protobuf/types/known/durationpb"
+ "google.golang.org/protobuf/types/known/emptypb"
+ "google.golang.org/protobuf/types/known/structpb"
+ "google.golang.org/protobuf/types/known/timestamppb"
+ "google.golang.org/protobuf/types/known/wrapperspb"
+ "google.golang.org/protobuf/types/pluginpb"
+)
+
+func main() {
+ run := flag.Bool("execute", false, "Write generated files to destination.")
+ flag.Parse()
+
+ // Set of generated proto packages to forward to v2.
+ files := []struct {
+ oldGoPkg string
+ newGoPkg string
+ pbDesc protoreflect.FileDescriptor
+ }{{
+ oldGoPkg: "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor",
+ newGoPkg: "google.golang.org/protobuf/types/descriptorpb",
+ pbDesc: descriptorpb.File_google_protobuf_descriptor_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go",
+ newGoPkg: "google.golang.org/protobuf/types/pluginpb",
+ pbDesc: pluginpb.File_google_protobuf_compiler_plugin_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/ptypes/any;any",
+ newGoPkg: "google.golang.org/protobuf/types/known/anypb",
+ pbDesc: anypb.File_google_protobuf_any_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/ptypes/duration;duration",
+ newGoPkg: "google.golang.org/protobuf/types/known/durationpb",
+ pbDesc: durationpb.File_google_protobuf_duration_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/ptypes/timestamp;timestamp",
+ newGoPkg: "google.golang.org/protobuf/types/known/timestamppb",
+ pbDesc: timestamppb.File_google_protobuf_timestamp_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/ptypes/wrappers;wrappers",
+ newGoPkg: "google.golang.org/protobuf/types/known/wrapperspb",
+ pbDesc: wrapperspb.File_google_protobuf_wrappers_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/ptypes/struct;structpb",
+ newGoPkg: "google.golang.org/protobuf/types/known/structpb",
+ pbDesc: structpb.File_google_protobuf_struct_proto,
+ }, {
+ oldGoPkg: "github.com/golang/protobuf/ptypes/empty;empty",
+ newGoPkg: "google.golang.org/protobuf/types/known/emptypb",
+ pbDesc: emptypb.File_google_protobuf_empty_proto,
+ }}
+
+ // For each package, construct a proto file that public imports the package.
+ var req pluginpb.CodeGeneratorRequest
+ var flags []string
+ for _, file := range files {
+ pkgPath := file.oldGoPkg[:strings.IndexByte(file.oldGoPkg, ';')]
+ fd := &descriptorpb.FileDescriptorProto{
+ Name: proto.String(pkgPath + "/" + path.Base(pkgPath) + ".proto"),
+ Syntax: proto.String(file.pbDesc.Syntax().String()),
+ Dependency: []string{file.pbDesc.Path()},
+ PublicDependency: []int32{0},
+ Options: &descriptorpb.FileOptions{GoPackage: proto.String(file.oldGoPkg)},
+ }
+ req.ProtoFile = append(req.ProtoFile, protodesc.ToFileDescriptorProto(file.pbDesc), fd)
+ req.FileToGenerate = append(req.FileToGenerate, fd.GetName())
+ flags = append(flags, "M"+file.pbDesc.Path()+"="+file.newGoPkg)
+ }
+ req.Parameter = proto.String(strings.Join(flags, ","))
+
+ // Use the internal logic of protoc-gen-go to generate the files.
+ gen, err := protogen.Options{}.New(&req)
+ check(err)
+ for _, file := range gen.Files {
+ if file.Generate {
+ gengo.GenerateVersionMarkers = false
+ gengo.GenerateFile(gen, file)
+ }
+ }
+
+ // Write the generated files.
+ resp := gen.Response()
+ if resp.Error != nil {
+ panic("gengo error: " + resp.GetError())
+ }
+ for _, file := range resp.File {
+ relPath, err := filepath.Rel(filepath.FromSlash("github.com/golang/protobuf"), file.GetName())
+ check(err)
+
+ check(ioutil.WriteFile(relPath+".bak", []byte(file.GetContent()), 0664))
+ if *run {
+ fmt.Println("#", relPath)
+ check(os.Rename(relPath+".bak", relPath))
+ } else {
+ cmd := exec.Command("diff", relPath, relPath+".bak", "-N", "-u")
+ cmd.Stdout = os.Stdout
+ cmd.Run()
+ os.Remove(relPath + ".bak") // best-effort delete
+ }
+ }
+}
+
+func check(err error) {
+ if err != nil {
+ panic(err)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go b/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go
new file mode 100644
index 000000000..fd2f51d89
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go
@@ -0,0 +1,398 @@
+// Copyright 2018 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package gengogrpc contains the gRPC code generator.
+package gengogrpc
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "google.golang.org/protobuf/compiler/protogen"
+
+ "google.golang.org/protobuf/types/descriptorpb"
+)
+
+const (
+ contextPackage = protogen.GoImportPath("context")
+ grpcPackage = protogen.GoImportPath("google.golang.org/grpc")
+ codesPackage = protogen.GoImportPath("google.golang.org/grpc/codes")
+ statusPackage = protogen.GoImportPath("google.golang.org/grpc/status")
+)
+
+// GenerateFile generates a _grpc.pb.go file containing gRPC service definitions.
+func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
+ if len(file.Services) == 0 {
+ return nil
+ }
+ filename := file.GeneratedFilenamePrefix + "_grpc.pb.go"
+ g := gen.NewGeneratedFile(filename, file.GoImportPath)
+ g.P("// Code generated by protoc-gen-go-grpc. DO NOT EDIT.")
+ g.P()
+ g.P("package ", file.GoPackageName)
+ g.P()
+ GenerateFileContent(gen, file, g)
+ return g
+}
+
+// GenerateFileContent generates the gRPC service definitions, excluding the package statement.
+func GenerateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
+ if len(file.Services) == 0 {
+ return
+ }
+
+ // TODO: Remove this. We don't need to include these references any more.
+ g.P("// Reference imports to suppress errors if they are not otherwise used.")
+ g.P("var _ ", contextPackage.Ident("Context"))
+ g.P("var _ ", grpcPackage.Ident("ClientConnInterface"))
+ g.P()
+
+ g.P("// This is a compile-time assertion to ensure that this generated file")
+ g.P("// is compatible with the grpc package it is being compiled against.")
+ g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion6"))
+ g.P()
+ for _, service := range file.Services {
+ genService(gen, file, g, service)
+ }
+}
+
+func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
+ clientName := service.GoName + "Client"
+
+ g.P("// ", clientName, " is the client API for ", service.GoName, " service.")
+ g.P("//")
+ g.P("// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.")
+
+ // Client interface.
+ if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
+ g.P("//")
+ g.P(deprecationComment)
+ }
+ g.Annotate(clientName, service.Location)
+ g.P("type ", clientName, " interface {")
+ for _, method := range service.Methods {
+ g.Annotate(clientName+"."+method.GoName, method.Location)
+ if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
+ g.P(deprecationComment)
+ }
+ g.P(method.Comments.Leading,
+ clientSignature(g, method))
+ }
+ g.P("}")
+ g.P()
+
+ // Client structure.
+ g.P("type ", unexport(clientName), " struct {")
+ g.P("cc ", grpcPackage.Ident("ClientConnInterface"))
+ g.P("}")
+ g.P()
+
+ // NewClient factory.
+ if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
+ g.P(deprecationComment)
+ }
+ g.P("func New", clientName, " (cc ", grpcPackage.Ident("ClientConnInterface"), ") ", clientName, " {")
+ g.P("return &", unexport(clientName), "{cc}")
+ g.P("}")
+ g.P()
+
+ var methodIndex, streamIndex int
+ // Client method implementations.
+ for _, method := range service.Methods {
+ if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
+ // Unary RPC method
+ genClientMethod(gen, file, g, method, methodIndex)
+ methodIndex++
+ } else {
+ // Streaming RPC method
+ genClientMethod(gen, file, g, method, streamIndex)
+ streamIndex++
+ }
+ }
+
+ // Server interface.
+ serverType := service.GoName + "Server"
+ g.P("// ", serverType, " is the server API for ", service.GoName, " service.")
+ if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
+ g.P("//")
+ g.P(deprecationComment)
+ }
+ g.Annotate(serverType, service.Location)
+ g.P("type ", serverType, " interface {")
+ for _, method := range service.Methods {
+ g.Annotate(serverType+"."+method.GoName, method.Location)
+ if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
+ g.P(deprecationComment)
+ }
+ g.P(method.Comments.Leading,
+ serverSignature(g, method))
+ }
+ g.P("}")
+ g.P()
+
+ // Server Unimplemented struct for forward compatibility.
+ g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.")
+ g.P("type Unimplemented", serverType, " struct {")
+ g.P("}")
+ g.P()
+ for _, method := range service.Methods {
+ nilArg := ""
+ if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
+ nilArg = "nil,"
+ }
+ g.P("func (*Unimplemented", serverType, ") ", serverSignature(g, method), "{")
+ g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`)
+ g.P("}")
+ }
+ g.P()
+
+ // Server registration.
+ if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
+ g.P(deprecationComment)
+ }
+ serviceDescVar := "_" + service.GoName + "_serviceDesc"
+ g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {")
+ g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
+ g.P("}")
+ g.P()
+
+ // Server handler implementations.
+ var handlerNames []string
+ for _, method := range service.Methods {
+ hname := genServerMethod(gen, file, g, method)
+ handlerNames = append(handlerNames, hname)
+ }
+
+ // Service descriptor.
+ g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {")
+ g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",")
+ g.P("HandlerType: (*", serverType, ")(nil),")
+ g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{")
+ for i, method := range service.Methods {
+ if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
+ continue
+ }
+ g.P("{")
+ g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",")
+ g.P("Handler: ", handlerNames[i], ",")
+ g.P("},")
+ }
+ g.P("},")
+ g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{")
+ for i, method := range service.Methods {
+ if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
+ continue
+ }
+ g.P("{")
+ g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
+ g.P("Handler: ", handlerNames[i], ",")
+ if method.Desc.IsStreamingServer() {
+ g.P("ServerStreams: true,")
+ }
+ if method.Desc.IsStreamingClient() {
+ g.P("ClientStreams: true,")
+ }
+ g.P("},")
+ }
+ g.P("},")
+ g.P("Metadata: \"", file.Desc.Path(), "\",")
+ g.P("}")
+ g.P()
+}
+
+func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
+ s := method.GoName + "(ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context"))
+ if !method.Desc.IsStreamingClient() {
+ s += ", in *" + g.QualifiedGoIdent(method.Input.GoIdent)
+ }
+ s += ", opts ..." + g.QualifiedGoIdent(grpcPackage.Ident("CallOption")) + ") ("
+ if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
+ s += "*" + g.QualifiedGoIdent(method.Output.GoIdent)
+ } else {
+ s += method.Parent.GoName + "_" + method.GoName + "Client"
+ }
+ s += ", error)"
+ return s
+}
+
+func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) {
+ service := method.Parent
+ sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name())
+
+ if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
+ g.P(deprecationComment)
+ }
+ g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{")
+ if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
+ g.P("out := new(", method.Output.GoIdent, ")")
+ g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
+ g.P("if err != nil { return nil, err }")
+ g.P("return out, nil")
+ g.P("}")
+ g.P()
+ return
+ }
+ streamType := unexport(service.GoName) + method.GoName + "Client"
+ serviceDescVar := "_" + service.GoName + "_serviceDesc"
+ g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`)
+ g.P("if err != nil { return nil, err }")
+ g.P("x := &", streamType, "{stream}")
+ if !method.Desc.IsStreamingClient() {
+ g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
+ g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
+ }
+ g.P("return x, nil")
+ g.P("}")
+ g.P()
+
+ genSend := method.Desc.IsStreamingClient()
+ genRecv := method.Desc.IsStreamingServer()
+ genCloseAndRecv := !method.Desc.IsStreamingServer()
+
+ // Stream auxiliary types and methods.
+ g.P("type ", service.GoName, "_", method.GoName, "Client interface {")
+ if genSend {
+ g.P("Send(*", method.Input.GoIdent, ") error")
+ }
+ if genRecv {
+ g.P("Recv() (*", method.Output.GoIdent, ", error)")
+ }
+ if genCloseAndRecv {
+ g.P("CloseAndRecv() (*", method.Output.GoIdent, ", error)")
+ }
+ g.P(grpcPackage.Ident("ClientStream"))
+ g.P("}")
+ g.P()
+
+ g.P("type ", streamType, " struct {")
+ g.P(grpcPackage.Ident("ClientStream"))
+ g.P("}")
+ g.P()
+
+ if genSend {
+ g.P("func (x *", streamType, ") Send(m *", method.Input.GoIdent, ") error {")
+ g.P("return x.ClientStream.SendMsg(m)")
+ g.P("}")
+ g.P()
+ }
+ if genRecv {
+ g.P("func (x *", streamType, ") Recv() (*", method.Output.GoIdent, ", error) {")
+ g.P("m := new(", method.Output.GoIdent, ")")
+ g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
+ g.P("return m, nil")
+ g.P("}")
+ g.P()
+ }
+ if genCloseAndRecv {
+ g.P("func (x *", streamType, ") CloseAndRecv() (*", method.Output.GoIdent, ", error) {")
+ g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
+ g.P("m := new(", method.Output.GoIdent, ")")
+ g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
+ g.P("return m, nil")
+ g.P("}")
+ g.P()
+ }
+}
+
+func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
+ var reqArgs []string
+ ret := "error"
+ if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
+ reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context")))
+ ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)"
+ }
+ if !method.Desc.IsStreamingClient() {
+ reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent))
+ }
+ if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
+ reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server")
+ }
+ return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
+}
+
+func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string {
+ service := method.Parent
+ hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName)
+
+ if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
+ g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {")
+ g.P("in := new(", method.Input.GoIdent, ")")
+ g.P("if err := dec(in); err != nil { return nil, err }")
+ g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }")
+ g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{")
+ g.P("Server: srv,")
+ g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",")
+ g.P("}")
+ g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {")
+ g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))")
+ g.P("}")
+ g.P("return interceptor(ctx, in, info, handler)")
+ g.P("}")
+ g.P()
+ return hname
+ }
+ streamType := unexport(service.GoName) + method.GoName + "Server"
+ g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {")
+ if !method.Desc.IsStreamingClient() {
+ g.P("m := new(", method.Input.GoIdent, ")")
+ g.P("if err := stream.RecvMsg(m); err != nil { return err }")
+ g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})")
+ } else {
+ g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})")
+ }
+ g.P("}")
+ g.P()
+
+ genSend := method.Desc.IsStreamingServer()
+ genSendAndClose := !method.Desc.IsStreamingServer()
+ genRecv := method.Desc.IsStreamingClient()
+
+ // Stream auxiliary types and methods.
+ g.P("type ", service.GoName, "_", method.GoName, "Server interface {")
+ if genSend {
+ g.P("Send(*", method.Output.GoIdent, ") error")
+ }
+ if genSendAndClose {
+ g.P("SendAndClose(*", method.Output.GoIdent, ") error")
+ }
+ if genRecv {
+ g.P("Recv() (*", method.Input.GoIdent, ", error)")
+ }
+ g.P(grpcPackage.Ident("ServerStream"))
+ g.P("}")
+ g.P()
+
+ g.P("type ", streamType, " struct {")
+ g.P(grpcPackage.Ident("ServerStream"))
+ g.P("}")
+ g.P()
+
+ if genSend {
+ g.P("func (x *", streamType, ") Send(m *", method.Output.GoIdent, ") error {")
+ g.P("return x.ServerStream.SendMsg(m)")
+ g.P("}")
+ g.P()
+ }
+ if genSendAndClose {
+ g.P("func (x *", streamType, ") SendAndClose(m *", method.Output.GoIdent, ") error {")
+ g.P("return x.ServerStream.SendMsg(m)")
+ g.P("}")
+ g.P()
+ }
+ if genRecv {
+ g.P("func (x *", streamType, ") Recv() (*", method.Input.GoIdent, ", error) {")
+ g.P("m := new(", method.Input.GoIdent, ")")
+ g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
+ g.P("return m, nil")
+ g.P("}")
+ g.P()
+ }
+
+ return hname
+}
+
+const deprecationComment = "// Deprecated: Do not use."
+
+func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test2.pb.go
similarity index 56%
rename from vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
rename to vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test2.pb.go
index d9e24db2c..a27dc0c25 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test2.pb.go
@@ -1,16 +1,18 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: test_objects.proto
-
-package jsonpb
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import any "github.com/golang/protobuf/ptypes/any"
-import duration "github.com/golang/protobuf/ptypes/duration"
-import _struct "github.com/golang/protobuf/ptypes/struct"
-import timestamp "github.com/golang/protobuf/ptypes/timestamp"
-import wrappers "github.com/golang/protobuf/ptypes/wrappers"
+// source: jsonpb_proto/test2.proto
+
+package jsonpb_proto
+
+import (
+ fmt "fmt"
+ proto "github.com/golang/protobuf/proto"
+ anypb "google.golang.org/protobuf/types/known/anypb"
+ durationpb "google.golang.org/protobuf/types/known/durationpb"
+ structpb "google.golang.org/protobuf/types/known/structpb"
+ timestamppb "google.golang.org/protobuf/types/known/timestamppb"
+ wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
+ math "math"
+)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
@@ -21,7 +23,7 @@ var _ = math.Inf
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type Widget_Color int32
@@ -36,6 +38,7 @@ var Widget_Color_name = map[int32]string{
1: "GREEN",
2: "BLUE",
}
+
var Widget_Color_value = map[string]int32{
"RED": 0,
"GREEN": 1,
@@ -47,9 +50,11 @@ func (x Widget_Color) Enum() *Widget_Color {
*p = x
return p
}
+
func (x Widget_Color) String() string {
return proto.EnumName(Widget_Color_name, int32(x))
}
+
func (x *Widget_Color) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(Widget_Color_value, data, "Widget_Color")
if err != nil {
@@ -58,23 +63,32 @@ func (x *Widget_Color) UnmarshalJSON(data []byte) error {
*x = Widget_Color(value)
return nil
}
+
func (Widget_Color) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{3, 0}
+ return fileDescriptor_50cab1d8463dea41, []int{3, 0}
}
// Test message for holding primitive types.
type Simple struct {
OBool *bool `protobuf:"varint,1,opt,name=o_bool,json=oBool" json:"o_bool,omitempty"`
OInt32 *int32 `protobuf:"varint,2,opt,name=o_int32,json=oInt32" json:"o_int32,omitempty"`
- OInt64 *int64 `protobuf:"varint,3,opt,name=o_int64,json=oInt64" json:"o_int64,omitempty"`
- OUint32 *uint32 `protobuf:"varint,4,opt,name=o_uint32,json=oUint32" json:"o_uint32,omitempty"`
- OUint64 *uint64 `protobuf:"varint,5,opt,name=o_uint64,json=oUint64" json:"o_uint64,omitempty"`
- OSint32 *int32 `protobuf:"zigzag32,6,opt,name=o_sint32,json=oSint32" json:"o_sint32,omitempty"`
- OSint64 *int64 `protobuf:"zigzag64,7,opt,name=o_sint64,json=oSint64" json:"o_sint64,omitempty"`
- OFloat *float32 `protobuf:"fixed32,8,opt,name=o_float,json=oFloat" json:"o_float,omitempty"`
- ODouble *float64 `protobuf:"fixed64,9,opt,name=o_double,json=oDouble" json:"o_double,omitempty"`
- OString *string `protobuf:"bytes,10,opt,name=o_string,json=oString" json:"o_string,omitempty"`
- OBytes []byte `protobuf:"bytes,11,opt,name=o_bytes,json=oBytes" json:"o_bytes,omitempty"`
+ OInt32Str *int32 `protobuf:"varint,3,opt,name=o_int32_str,json=oInt32Str" json:"o_int32_str,omitempty"`
+ OInt64 *int64 `protobuf:"varint,4,opt,name=o_int64,json=oInt64" json:"o_int64,omitempty"`
+ OInt64Str *int64 `protobuf:"varint,5,opt,name=o_int64_str,json=oInt64Str" json:"o_int64_str,omitempty"`
+ OUint32 *uint32 `protobuf:"varint,6,opt,name=o_uint32,json=oUint32" json:"o_uint32,omitempty"`
+ OUint32Str *uint32 `protobuf:"varint,7,opt,name=o_uint32_str,json=oUint32Str" json:"o_uint32_str,omitempty"`
+ OUint64 *uint64 `protobuf:"varint,8,opt,name=o_uint64,json=oUint64" json:"o_uint64,omitempty"`
+ OUint64Str *uint64 `protobuf:"varint,9,opt,name=o_uint64_str,json=oUint64Str" json:"o_uint64_str,omitempty"`
+ OSint32 *int32 `protobuf:"zigzag32,10,opt,name=o_sint32,json=oSint32" json:"o_sint32,omitempty"`
+ OSint32Str *int32 `protobuf:"zigzag32,11,opt,name=o_sint32_str,json=oSint32Str" json:"o_sint32_str,omitempty"`
+ OSint64 *int64 `protobuf:"zigzag64,12,opt,name=o_sint64,json=oSint64" json:"o_sint64,omitempty"`
+ OSint64Str *int64 `protobuf:"zigzag64,13,opt,name=o_sint64_str,json=oSint64Str" json:"o_sint64_str,omitempty"`
+ OFloat *float32 `protobuf:"fixed32,14,opt,name=o_float,json=oFloat" json:"o_float,omitempty"`
+ OFloatStr *float32 `protobuf:"fixed32,15,opt,name=o_float_str,json=oFloatStr" json:"o_float_str,omitempty"`
+ ODouble *float64 `protobuf:"fixed64,16,opt,name=o_double,json=oDouble" json:"o_double,omitempty"`
+ ODoubleStr *float64 `protobuf:"fixed64,17,opt,name=o_double_str,json=oDoubleStr" json:"o_double_str,omitempty"`
+ OString *string `protobuf:"bytes,18,opt,name=o_string,json=oString" json:"o_string,omitempty"`
+ OBytes []byte `protobuf:"bytes,19,opt,name=o_bytes,json=oBytes" json:"o_bytes,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -84,16 +98,17 @@ func (m *Simple) Reset() { *m = Simple{} }
func (m *Simple) String() string { return proto.CompactTextString(m) }
func (*Simple) ProtoMessage() {}
func (*Simple) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{0}
+ return fileDescriptor_50cab1d8463dea41, []int{0}
}
+
func (m *Simple) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Simple.Unmarshal(m, b)
}
func (m *Simple) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Simple.Marshal(b, m, deterministic)
}
-func (dst *Simple) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Simple.Merge(dst, src)
+func (m *Simple) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Simple.Merge(m, src)
}
func (m *Simple) XXX_Size() int {
return xxx_messageInfo_Simple.Size(m)
@@ -118,6 +133,13 @@ func (m *Simple) GetOInt32() int32 {
return 0
}
+func (m *Simple) GetOInt32Str() int32 {
+ if m != nil && m.OInt32Str != nil {
+ return *m.OInt32Str
+ }
+ return 0
+}
+
func (m *Simple) GetOInt64() int64 {
if m != nil && m.OInt64 != nil {
return *m.OInt64
@@ -125,6 +147,13 @@ func (m *Simple) GetOInt64() int64 {
return 0
}
+func (m *Simple) GetOInt64Str() int64 {
+ if m != nil && m.OInt64Str != nil {
+ return *m.OInt64Str
+ }
+ return 0
+}
+
func (m *Simple) GetOUint32() uint32 {
if m != nil && m.OUint32 != nil {
return *m.OUint32
@@ -132,6 +161,13 @@ func (m *Simple) GetOUint32() uint32 {
return 0
}
+func (m *Simple) GetOUint32Str() uint32 {
+ if m != nil && m.OUint32Str != nil {
+ return *m.OUint32Str
+ }
+ return 0
+}
+
func (m *Simple) GetOUint64() uint64 {
if m != nil && m.OUint64 != nil {
return *m.OUint64
@@ -139,6 +175,13 @@ func (m *Simple) GetOUint64() uint64 {
return 0
}
+func (m *Simple) GetOUint64Str() uint64 {
+ if m != nil && m.OUint64Str != nil {
+ return *m.OUint64Str
+ }
+ return 0
+}
+
func (m *Simple) GetOSint32() int32 {
if m != nil && m.OSint32 != nil {
return *m.OSint32
@@ -146,6 +189,13 @@ func (m *Simple) GetOSint32() int32 {
return 0
}
+func (m *Simple) GetOSint32Str() int32 {
+ if m != nil && m.OSint32Str != nil {
+ return *m.OSint32Str
+ }
+ return 0
+}
+
func (m *Simple) GetOSint64() int64 {
if m != nil && m.OSint64 != nil {
return *m.OSint64
@@ -153,6 +203,13 @@ func (m *Simple) GetOSint64() int64 {
return 0
}
+func (m *Simple) GetOSint64Str() int64 {
+ if m != nil && m.OSint64Str != nil {
+ return *m.OSint64Str
+ }
+ return 0
+}
+
func (m *Simple) GetOFloat() float32 {
if m != nil && m.OFloat != nil {
return *m.OFloat
@@ -160,6 +217,13 @@ func (m *Simple) GetOFloat() float32 {
return 0
}
+func (m *Simple) GetOFloatStr() float32 {
+ if m != nil && m.OFloatStr != nil {
+ return *m.OFloatStr
+ }
+ return 0
+}
+
func (m *Simple) GetODouble() float64 {
if m != nil && m.ODouble != nil {
return *m.ODouble
@@ -167,6 +231,13 @@ func (m *Simple) GetODouble() float64 {
return 0
}
+func (m *Simple) GetODoubleStr() float64 {
+ if m != nil && m.ODoubleStr != nil {
+ return *m.ODoubleStr
+ }
+ return 0
+}
+
func (m *Simple) GetOString() string {
if m != nil && m.OString != nil {
return *m.OString
@@ -198,16 +269,17 @@ func (m *NonFinites) Reset() { *m = NonFinites{} }
func (m *NonFinites) String() string { return proto.CompactTextString(m) }
func (*NonFinites) ProtoMessage() {}
func (*NonFinites) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{1}
+ return fileDescriptor_50cab1d8463dea41, []int{1}
}
+
func (m *NonFinites) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_NonFinites.Unmarshal(m, b)
}
func (m *NonFinites) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_NonFinites.Marshal(b, m, deterministic)
}
-func (dst *NonFinites) XXX_Merge(src proto.Message) {
- xxx_messageInfo_NonFinites.Merge(dst, src)
+func (m *NonFinites) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_NonFinites.Merge(m, src)
}
func (m *NonFinites) XXX_Size() int {
return xxx_messageInfo_NonFinites.Size(m)
@@ -282,16 +354,17 @@ func (m *Repeats) Reset() { *m = Repeats{} }
func (m *Repeats) String() string { return proto.CompactTextString(m) }
func (*Repeats) ProtoMessage() {}
func (*Repeats) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{2}
+ return fileDescriptor_50cab1d8463dea41, []int{2}
}
+
func (m *Repeats) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Repeats.Unmarshal(m, b)
}
func (m *Repeats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Repeats.Marshal(b, m, deterministic)
}
-func (dst *Repeats) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Repeats.Merge(dst, src)
+func (m *Repeats) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Repeats.Merge(m, src)
}
func (m *Repeats) XXX_Size() int {
return xxx_messageInfo_Repeats.Size(m)
@@ -381,8 +454,8 @@ func (m *Repeats) GetRBytes() [][]byte {
// Test message for holding enums and nested messages.
type Widget struct {
- Color *Widget_Color `protobuf:"varint,1,opt,name=color,enum=jsonpb.Widget_Color" json:"color,omitempty"`
- RColor []Widget_Color `protobuf:"varint,2,rep,name=r_color,json=rColor,enum=jsonpb.Widget_Color" json:"r_color,omitempty"`
+ Color *Widget_Color `protobuf:"varint,1,opt,name=color,enum=jsonpb_test.Widget_Color" json:"color,omitempty"`
+ RColor []Widget_Color `protobuf:"varint,2,rep,name=r_color,json=rColor,enum=jsonpb_test.Widget_Color" json:"r_color,omitempty"`
Simple *Simple `protobuf:"bytes,10,opt,name=simple" json:"simple,omitempty"`
RSimple []*Simple `protobuf:"bytes,11,rep,name=r_simple,json=rSimple" json:"r_simple,omitempty"`
Repeats *Repeats `protobuf:"bytes,20,opt,name=repeats" json:"repeats,omitempty"`
@@ -396,16 +469,17 @@ func (m *Widget) Reset() { *m = Widget{} }
func (m *Widget) String() string { return proto.CompactTextString(m) }
func (*Widget) ProtoMessage() {}
func (*Widget) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{3}
+ return fileDescriptor_50cab1d8463dea41, []int{3}
}
+
func (m *Widget) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Widget.Unmarshal(m, b)
}
func (m *Widget) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Widget.Marshal(b, m, deterministic)
}
-func (dst *Widget) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Widget.Merge(dst, src)
+func (m *Widget) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Widget.Merge(m, src)
}
func (m *Widget) XXX_Size() int {
return xxx_messageInfo_Widget.Size(m)
@@ -470,16 +544,17 @@ func (m *Maps) Reset() { *m = Maps{} }
func (m *Maps) String() string { return proto.CompactTextString(m) }
func (*Maps) ProtoMessage() {}
func (*Maps) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{4}
+ return fileDescriptor_50cab1d8463dea41, []int{4}
}
+
func (m *Maps) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Maps.Unmarshal(m, b)
}
func (m *Maps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Maps.Marshal(b, m, deterministic)
}
-func (dst *Maps) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Maps.Merge(dst, src)
+func (m *Maps) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Maps.Merge(m, src)
}
func (m *Maps) XXX_Size() int {
return xxx_messageInfo_Maps.Size(m)
@@ -521,16 +596,17 @@ func (m *MsgWithOneof) Reset() { *m = MsgWithOneof{} }
func (m *MsgWithOneof) String() string { return proto.CompactTextString(m) }
func (*MsgWithOneof) ProtoMessage() {}
func (*MsgWithOneof) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{5}
+ return fileDescriptor_50cab1d8463dea41, []int{5}
}
+
func (m *MsgWithOneof) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgWithOneof.Unmarshal(m, b)
}
func (m *MsgWithOneof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgWithOneof.Marshal(b, m, deterministic)
}
-func (dst *MsgWithOneof) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MsgWithOneof.Merge(dst, src)
+func (m *MsgWithOneof) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MsgWithOneof.Merge(m, src)
}
func (m *MsgWithOneof) XXX_Size() int {
return xxx_messageInfo_MsgWithOneof.Size(m)
@@ -548,23 +624,31 @@ type isMsgWithOneof_Union interface {
type MsgWithOneof_Title struct {
Title string `protobuf:"bytes,1,opt,name=title,oneof"`
}
+
type MsgWithOneof_Salary struct {
Salary int64 `protobuf:"varint,2,opt,name=salary,oneof"`
}
+
type MsgWithOneof_Country struct {
Country string `protobuf:"bytes,3,opt,name=Country,oneof"`
}
+
type MsgWithOneof_HomeAddress struct {
HomeAddress string `protobuf:"bytes,4,opt,name=home_address,json=homeAddress,oneof"`
}
+
type MsgWithOneof_MsgWithRequired struct {
MsgWithRequired *MsgWithRequired `protobuf:"bytes,5,opt,name=msg_with_required,json=msgWithRequired,oneof"`
}
-func (*MsgWithOneof_Title) isMsgWithOneof_Union() {}
-func (*MsgWithOneof_Salary) isMsgWithOneof_Union() {}
-func (*MsgWithOneof_Country) isMsgWithOneof_Union() {}
-func (*MsgWithOneof_HomeAddress) isMsgWithOneof_Union() {}
+func (*MsgWithOneof_Title) isMsgWithOneof_Union() {}
+
+func (*MsgWithOneof_Salary) isMsgWithOneof_Union() {}
+
+func (*MsgWithOneof_Country) isMsgWithOneof_Union() {}
+
+func (*MsgWithOneof_HomeAddress) isMsgWithOneof_Union() {}
+
func (*MsgWithOneof_MsgWithRequired) isMsgWithOneof_Union() {}
func (m *MsgWithOneof) GetUnion() isMsgWithOneof_Union {
@@ -609,9 +693,9 @@ func (m *MsgWithOneof) GetMsgWithRequired() *MsgWithRequired {
return nil
}
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*MsgWithOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _MsgWithOneof_OneofMarshaler, _MsgWithOneof_OneofUnmarshaler, _MsgWithOneof_OneofSizer, []interface{}{
+// XXX_OneofWrappers is for the internal use of the proto package.
+func (*MsgWithOneof) XXX_OneofWrappers() []interface{} {
+ return []interface{}{
(*MsgWithOneof_Title)(nil),
(*MsgWithOneof_Salary)(nil),
(*MsgWithOneof_Country)(nil),
@@ -620,109 +704,6 @@ func (*MsgWithOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer)
}
}
-func _MsgWithOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*MsgWithOneof)
- // union
- switch x := m.Union.(type) {
- case *MsgWithOneof_Title:
- b.EncodeVarint(1<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.Title)
- case *MsgWithOneof_Salary:
- b.EncodeVarint(2<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Salary))
- case *MsgWithOneof_Country:
- b.EncodeVarint(3<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.Country)
- case *MsgWithOneof_HomeAddress:
- b.EncodeVarint(4<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.HomeAddress)
- case *MsgWithOneof_MsgWithRequired:
- b.EncodeVarint(5<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.MsgWithRequired); err != nil {
- return err
- }
- case nil:
- default:
- return fmt.Errorf("MsgWithOneof.Union has unexpected type %T", x)
- }
- return nil
-}
-
-func _MsgWithOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*MsgWithOneof)
- switch tag {
- case 1: // union.title
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &MsgWithOneof_Title{x}
- return true, err
- case 2: // union.salary
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &MsgWithOneof_Salary{int64(x)}
- return true, err
- case 3: // union.Country
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &MsgWithOneof_Country{x}
- return true, err
- case 4: // union.home_address
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &MsgWithOneof_HomeAddress{x}
- return true, err
- case 5: // union.msg_with_required
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(MsgWithRequired)
- err := b.DecodeMessage(msg)
- m.Union = &MsgWithOneof_MsgWithRequired{msg}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _MsgWithOneof_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*MsgWithOneof)
- // union
- switch x := m.Union.(type) {
- case *MsgWithOneof_Title:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Title)))
- n += len(x.Title)
- case *MsgWithOneof_Salary:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.Salary))
- case *MsgWithOneof_Country:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Country)))
- n += len(x.Country)
- case *MsgWithOneof_HomeAddress:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.HomeAddress)))
- n += len(x.HomeAddress)
- case *MsgWithOneof_MsgWithRequired:
- s := proto.Size(x.MsgWithRequired)
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
type Real struct {
Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
@@ -735,7 +716,7 @@ func (m *Real) Reset() { *m = Real{} }
func (m *Real) String() string { return proto.CompactTextString(m) }
func (*Real) ProtoMessage() {}
func (*Real) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{6}
+ return fileDescriptor_50cab1d8463dea41, []int{6}
}
var extRange_Real = []proto.ExtensionRange{
@@ -745,14 +726,15 @@ var extRange_Real = []proto.ExtensionRange{
func (*Real) ExtensionRangeArray() []proto.ExtensionRange {
return extRange_Real
}
+
func (m *Real) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Real.Unmarshal(m, b)
}
func (m *Real) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Real.Marshal(b, m, deterministic)
}
-func (dst *Real) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Real.Merge(dst, src)
+func (m *Real) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Real.Merge(m, src)
}
func (m *Real) XXX_Size() int {
return xxx_messageInfo_Real.Size(m)
@@ -782,7 +764,7 @@ func (m *Complex) Reset() { *m = Complex{} }
func (m *Complex) String() string { return proto.CompactTextString(m) }
func (*Complex) ProtoMessage() {}
func (*Complex) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{7}
+ return fileDescriptor_50cab1d8463dea41, []int{7}
}
var extRange_Complex = []proto.ExtensionRange{
@@ -792,14 +774,15 @@ var extRange_Complex = []proto.ExtensionRange{
func (*Complex) ExtensionRangeArray() []proto.ExtensionRange {
return extRange_Complex
}
+
func (m *Complex) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Complex.Unmarshal(m, b)
}
func (m *Complex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Complex.Marshal(b, m, deterministic)
}
-func (dst *Complex) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Complex.Merge(dst, src)
+func (m *Complex) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Complex.Merge(m, src)
}
func (m *Complex) XXX_Size() int {
return xxx_messageInfo_Complex.Size(m)
@@ -821,46 +804,47 @@ var E_Complex_RealExtension = &proto.ExtensionDesc{
ExtendedType: (*Real)(nil),
ExtensionType: (*Complex)(nil),
Field: 123,
- Name: "jsonpb.Complex.real_extension",
- Tag: "bytes,123,opt,name=real_extension,json=realExtension",
- Filename: "test_objects.proto",
+ Name: "jsonpb_test.Complex.real_extension",
+ Tag: "bytes,123,opt,name=real_extension",
+ Filename: "jsonpb_proto/test2.proto",
}
type KnownTypes struct {
- An *any.Any `protobuf:"bytes,14,opt,name=an" json:"an,omitempty"`
- Dur *duration.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"`
- St *_struct.Struct `protobuf:"bytes,12,opt,name=st" json:"st,omitempty"`
- Ts *timestamp.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"`
- Lv *_struct.ListValue `protobuf:"bytes,15,opt,name=lv" json:"lv,omitempty"`
- Val *_struct.Value `protobuf:"bytes,16,opt,name=val" json:"val,omitempty"`
- Dbl *wrappers.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"`
- Flt *wrappers.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"`
- I64 *wrappers.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"`
- U64 *wrappers.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"`
- I32 *wrappers.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"`
- U32 *wrappers.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"`
- Bool *wrappers.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"`
- Str *wrappers.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"`
- Bytes *wrappers.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
+ An *anypb.Any `protobuf:"bytes,14,opt,name=an" json:"an,omitempty"`
+ Dur *durationpb.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"`
+ St *structpb.Struct `protobuf:"bytes,12,opt,name=st" json:"st,omitempty"`
+ Ts *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"`
+ Lv *structpb.ListValue `protobuf:"bytes,15,opt,name=lv" json:"lv,omitempty"`
+ Val *structpb.Value `protobuf:"bytes,16,opt,name=val" json:"val,omitempty"`
+ Dbl *wrapperspb.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"`
+ Flt *wrapperspb.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"`
+ I64 *wrapperspb.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"`
+ U64 *wrapperspb.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"`
+ I32 *wrapperspb.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"`
+ U32 *wrapperspb.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"`
+ Bool *wrapperspb.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"`
+ Str *wrapperspb.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"`
+ Bytes *wrapperspb.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
}
func (m *KnownTypes) Reset() { *m = KnownTypes{} }
func (m *KnownTypes) String() string { return proto.CompactTextString(m) }
func (*KnownTypes) ProtoMessage() {}
func (*KnownTypes) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{8}
+ return fileDescriptor_50cab1d8463dea41, []int{8}
}
+
func (m *KnownTypes) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_KnownTypes.Unmarshal(m, b)
}
func (m *KnownTypes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_KnownTypes.Marshal(b, m, deterministic)
}
-func (dst *KnownTypes) XXX_Merge(src proto.Message) {
- xxx_messageInfo_KnownTypes.Merge(dst, src)
+func (m *KnownTypes) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_KnownTypes.Merge(m, src)
}
func (m *KnownTypes) XXX_Size() int {
return xxx_messageInfo_KnownTypes.Size(m)
@@ -871,105 +855,105 @@ func (m *KnownTypes) XXX_DiscardUnknown() {
var xxx_messageInfo_KnownTypes proto.InternalMessageInfo
-func (m *KnownTypes) GetAn() *any.Any {
+func (m *KnownTypes) GetAn() *anypb.Any {
if m != nil {
return m.An
}
return nil
}
-func (m *KnownTypes) GetDur() *duration.Duration {
+func (m *KnownTypes) GetDur() *durationpb.Duration {
if m != nil {
return m.Dur
}
return nil
}
-func (m *KnownTypes) GetSt() *_struct.Struct {
+func (m *KnownTypes) GetSt() *structpb.Struct {
if m != nil {
return m.St
}
return nil
}
-func (m *KnownTypes) GetTs() *timestamp.Timestamp {
+func (m *KnownTypes) GetTs() *timestamppb.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
-func (m *KnownTypes) GetLv() *_struct.ListValue {
+func (m *KnownTypes) GetLv() *structpb.ListValue {
if m != nil {
return m.Lv
}
return nil
}
-func (m *KnownTypes) GetVal() *_struct.Value {
+func (m *KnownTypes) GetVal() *structpb.Value {
if m != nil {
return m.Val
}
return nil
}
-func (m *KnownTypes) GetDbl() *wrappers.DoubleValue {
+func (m *KnownTypes) GetDbl() *wrapperspb.DoubleValue {
if m != nil {
return m.Dbl
}
return nil
}
-func (m *KnownTypes) GetFlt() *wrappers.FloatValue {
+func (m *KnownTypes) GetFlt() *wrapperspb.FloatValue {
if m != nil {
return m.Flt
}
return nil
}
-func (m *KnownTypes) GetI64() *wrappers.Int64Value {
+func (m *KnownTypes) GetI64() *wrapperspb.Int64Value {
if m != nil {
return m.I64
}
return nil
}
-func (m *KnownTypes) GetU64() *wrappers.UInt64Value {
+func (m *KnownTypes) GetU64() *wrapperspb.UInt64Value {
if m != nil {
return m.U64
}
return nil
}
-func (m *KnownTypes) GetI32() *wrappers.Int32Value {
+func (m *KnownTypes) GetI32() *wrapperspb.Int32Value {
if m != nil {
return m.I32
}
return nil
}
-func (m *KnownTypes) GetU32() *wrappers.UInt32Value {
+func (m *KnownTypes) GetU32() *wrapperspb.UInt32Value {
if m != nil {
return m.U32
}
return nil
}
-func (m *KnownTypes) GetBool() *wrappers.BoolValue {
+func (m *KnownTypes) GetBool() *wrapperspb.BoolValue {
if m != nil {
return m.Bool
}
return nil
}
-func (m *KnownTypes) GetStr() *wrappers.StringValue {
+func (m *KnownTypes) GetStr() *wrapperspb.StringValue {
if m != nil {
return m.Str
}
return nil
}
-func (m *KnownTypes) GetBytes() *wrappers.BytesValue {
+func (m *KnownTypes) GetBytes() *wrapperspb.BytesValue {
if m != nil {
return m.Bytes
}
@@ -988,16 +972,17 @@ func (m *MsgWithRequired) Reset() { *m = MsgWithRequired{} }
func (m *MsgWithRequired) String() string { return proto.CompactTextString(m) }
func (*MsgWithRequired) ProtoMessage() {}
func (*MsgWithRequired) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{9}
+ return fileDescriptor_50cab1d8463dea41, []int{9}
}
+
func (m *MsgWithRequired) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgWithRequired.Unmarshal(m, b)
}
func (m *MsgWithRequired) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgWithRequired.Marshal(b, m, deterministic)
}
-func (dst *MsgWithRequired) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MsgWithRequired.Merge(dst, src)
+func (m *MsgWithRequired) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MsgWithRequired.Merge(m, src)
}
func (m *MsgWithRequired) XXX_Size() int {
return xxx_messageInfo_MsgWithRequired.Size(m)
@@ -1028,16 +1013,17 @@ func (m *MsgWithIndirectRequired) Reset() { *m = MsgWithIndirectRequired
func (m *MsgWithIndirectRequired) String() string { return proto.CompactTextString(m) }
func (*MsgWithIndirectRequired) ProtoMessage() {}
func (*MsgWithIndirectRequired) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{10}
+ return fileDescriptor_50cab1d8463dea41, []int{10}
}
+
func (m *MsgWithIndirectRequired) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgWithIndirectRequired.Unmarshal(m, b)
}
func (m *MsgWithIndirectRequired) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgWithIndirectRequired.Marshal(b, m, deterministic)
}
-func (dst *MsgWithIndirectRequired) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MsgWithIndirectRequired.Merge(dst, src)
+func (m *MsgWithIndirectRequired) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MsgWithIndirectRequired.Merge(m, src)
}
func (m *MsgWithIndirectRequired) XXX_Size() int {
return xxx_messageInfo_MsgWithIndirectRequired.Size(m)
@@ -1080,16 +1066,17 @@ func (m *MsgWithRequiredBytes) Reset() { *m = MsgWithRequiredBytes{} }
func (m *MsgWithRequiredBytes) String() string { return proto.CompactTextString(m) }
func (*MsgWithRequiredBytes) ProtoMessage() {}
func (*MsgWithRequiredBytes) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{11}
+ return fileDescriptor_50cab1d8463dea41, []int{11}
}
+
func (m *MsgWithRequiredBytes) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgWithRequiredBytes.Unmarshal(m, b)
}
func (m *MsgWithRequiredBytes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgWithRequiredBytes.Marshal(b, m, deterministic)
}
-func (dst *MsgWithRequiredBytes) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MsgWithRequiredBytes.Merge(dst, src)
+func (m *MsgWithRequiredBytes) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MsgWithRequiredBytes.Merge(m, src)
}
func (m *MsgWithRequiredBytes) XXX_Size() int {
return xxx_messageInfo_MsgWithRequiredBytes.Size(m)
@@ -1108,26 +1095,27 @@ func (m *MsgWithRequiredBytes) GetByts() []byte {
}
type MsgWithRequiredWKT struct {
- Str *wrappers.StringValue `protobuf:"bytes,1,req,name=str" json:"str,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
+ Str *wrapperspb.StringValue `protobuf:"bytes,1,req,name=str" json:"str,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
}
func (m *MsgWithRequiredWKT) Reset() { *m = MsgWithRequiredWKT{} }
func (m *MsgWithRequiredWKT) String() string { return proto.CompactTextString(m) }
func (*MsgWithRequiredWKT) ProtoMessage() {}
func (*MsgWithRequiredWKT) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_objects_c6f6c615ab823e65, []int{12}
+ return fileDescriptor_50cab1d8463dea41, []int{12}
}
+
func (m *MsgWithRequiredWKT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgWithRequiredWKT.Unmarshal(m, b)
}
func (m *MsgWithRequiredWKT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgWithRequiredWKT.Marshal(b, m, deterministic)
}
-func (dst *MsgWithRequiredWKT) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MsgWithRequiredWKT.Merge(dst, src)
+func (m *MsgWithRequiredWKT) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MsgWithRequiredWKT.Merge(m, src)
}
func (m *MsgWithRequiredWKT) XXX_Size() int {
return xxx_messageInfo_MsgWithRequiredWKT.Size(m)
@@ -1138,7 +1126,7 @@ func (m *MsgWithRequiredWKT) XXX_DiscardUnknown() {
var xxx_messageInfo_MsgWithRequiredWKT proto.InternalMessageInfo
-func (m *MsgWithRequiredWKT) GetStr() *wrappers.StringValue {
+func (m *MsgWithRequiredWKT) GetStr() *wrapperspb.StringValue {
if m != nil {
return m.Str
}
@@ -1149,130 +1137,140 @@ var E_Name = &proto.ExtensionDesc{
ExtendedType: (*Real)(nil),
ExtensionType: (*string)(nil),
Field: 124,
- Name: "jsonpb.name",
+ Name: "jsonpb_test.name",
Tag: "bytes,124,opt,name=name",
- Filename: "test_objects.proto",
+ Filename: "jsonpb_proto/test2.proto",
}
var E_Extm = &proto.ExtensionDesc{
ExtendedType: (*Real)(nil),
ExtensionType: (*MsgWithRequired)(nil),
Field: 125,
- Name: "jsonpb.extm",
+ Name: "jsonpb_test.extm",
Tag: "bytes,125,opt,name=extm",
- Filename: "test_objects.proto",
+ Filename: "jsonpb_proto/test2.proto",
}
func init() {
- proto.RegisterType((*Simple)(nil), "jsonpb.Simple")
- proto.RegisterType((*NonFinites)(nil), "jsonpb.NonFinites")
- proto.RegisterType((*Repeats)(nil), "jsonpb.Repeats")
- proto.RegisterType((*Widget)(nil), "jsonpb.Widget")
- proto.RegisterType((*Maps)(nil), "jsonpb.Maps")
- proto.RegisterMapType((map[bool]*Simple)(nil), "jsonpb.Maps.MBoolSimpleEntry")
- proto.RegisterMapType((map[int64]string)(nil), "jsonpb.Maps.MInt64StrEntry")
- proto.RegisterType((*MsgWithOneof)(nil), "jsonpb.MsgWithOneof")
- proto.RegisterType((*Real)(nil), "jsonpb.Real")
- proto.RegisterType((*Complex)(nil), "jsonpb.Complex")
- proto.RegisterType((*KnownTypes)(nil), "jsonpb.KnownTypes")
- proto.RegisterType((*MsgWithRequired)(nil), "jsonpb.MsgWithRequired")
- proto.RegisterType((*MsgWithIndirectRequired)(nil), "jsonpb.MsgWithIndirectRequired")
- proto.RegisterMapType((map[string]*MsgWithRequired)(nil), "jsonpb.MsgWithIndirectRequired.MapFieldEntry")
- proto.RegisterType((*MsgWithRequiredBytes)(nil), "jsonpb.MsgWithRequiredBytes")
- proto.RegisterType((*MsgWithRequiredWKT)(nil), "jsonpb.MsgWithRequiredWKT")
- proto.RegisterEnum("jsonpb.Widget_Color", Widget_Color_name, Widget_Color_value)
+ proto.RegisterEnum("jsonpb_test.Widget_Color", Widget_Color_name, Widget_Color_value)
+ proto.RegisterType((*Simple)(nil), "jsonpb_test.Simple")
+ proto.RegisterType((*NonFinites)(nil), "jsonpb_test.NonFinites")
+ proto.RegisterType((*Repeats)(nil), "jsonpb_test.Repeats")
+ proto.RegisterType((*Widget)(nil), "jsonpb_test.Widget")
+ proto.RegisterType((*Maps)(nil), "jsonpb_test.Maps")
+ proto.RegisterMapType((map[bool]*Simple)(nil), "jsonpb_test.Maps.MBoolSimpleEntry")
+ proto.RegisterMapType((map[int64]string)(nil), "jsonpb_test.Maps.MInt64StrEntry")
+ proto.RegisterType((*MsgWithOneof)(nil), "jsonpb_test.MsgWithOneof")
+ proto.RegisterType((*Real)(nil), "jsonpb_test.Real")
proto.RegisterExtension(E_Complex_RealExtension)
+ proto.RegisterType((*Complex)(nil), "jsonpb_test.Complex")
+ proto.RegisterType((*KnownTypes)(nil), "jsonpb_test.KnownTypes")
+ proto.RegisterType((*MsgWithRequired)(nil), "jsonpb_test.MsgWithRequired")
+ proto.RegisterType((*MsgWithIndirectRequired)(nil), "jsonpb_test.MsgWithIndirectRequired")
+ proto.RegisterMapType((map[string]*MsgWithRequired)(nil), "jsonpb_test.MsgWithIndirectRequired.MapFieldEntry")
+ proto.RegisterType((*MsgWithRequiredBytes)(nil), "jsonpb_test.MsgWithRequiredBytes")
+ proto.RegisterType((*MsgWithRequiredWKT)(nil), "jsonpb_test.MsgWithRequiredWKT")
proto.RegisterExtension(E_Name)
proto.RegisterExtension(E_Extm)
}
-func init() { proto.RegisterFile("test_objects.proto", fileDescriptor_test_objects_c6f6c615ab823e65) }
-
-var fileDescriptor_test_objects_c6f6c615ab823e65 = []byte{
- // 1357 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x56, 0xdd, 0x72, 0x13, 0xc7,
- 0x12, 0xf6, 0xee, 0x6a, 0xf5, 0xd3, 0xf2, 0x1f, 0x83, 0x81, 0xc5, 0x87, 0x73, 0x8e, 0x4a, 0x70,
- 0x38, 0x0a, 0xc4, 0xa2, 0x22, 0xbb, 0x5c, 0x84, 0xe4, 0x06, 0x63, 0x13, 0x08, 0xe0, 0xa4, 0xc6,
- 0x26, 0x5c, 0xaa, 0x56, 0xde, 0x91, 0x59, 0xb2, 0xbb, 0xa3, 0xcc, 0xcc, 0xda, 0xa8, 0x92, 0x54,
- 0xf9, 0x19, 0x52, 0x79, 0x82, 0x54, 0x25, 0x8f, 0x90, 0x8b, 0xbc, 0x45, 0xde, 0x28, 0x35, 0x3d,
- 0xb3, 0x5a, 0x59, 0x42, 0x95, 0x5c, 0x79, 0xbb, 0xfb, 0xeb, 0x4f, 0x33, 0xfd, 0xf5, 0x74, 0x1b,
- 0x88, 0x62, 0x52, 0xf5, 0xf9, 0xe0, 0x1d, 0x3b, 0x51, 0xb2, 0x3b, 0x12, 0x5c, 0x71, 0x52, 0x7d,
- 0x27, 0x79, 0x36, 0x1a, 0x6c, 0xde, 0x3c, 0xe5, 0xfc, 0x34, 0x61, 0x0f, 0xd0, 0x3b, 0xc8, 0x87,
- 0x0f, 0xc2, 0x6c, 0x6c, 0x20, 0x9b, 0xff, 0x99, 0x0d, 0x45, 0xb9, 0x08, 0x55, 0xcc, 0x33, 0x1b,
- 0xbf, 0x35, 0x1b, 0x97, 0x4a, 0xe4, 0x27, 0xca, 0x46, 0xff, 0x3b, 0x1b, 0x55, 0x71, 0xca, 0xa4,
- 0x0a, 0xd3, 0xd1, 0x22, 0xfa, 0x73, 0x11, 0x8e, 0x46, 0x4c, 0xd8, 0x13, 0xb6, 0x7f, 0x75, 0xa1,
- 0x7a, 0x14, 0xa7, 0xa3, 0x84, 0x91, 0x6b, 0x50, 0xe5, 0xfd, 0x01, 0xe7, 0x49, 0xe0, 0xb4, 0x9c,
- 0x4e, 0x9d, 0xfa, 0x7c, 0x8f, 0xf3, 0x84, 0xdc, 0x80, 0x1a, 0xef, 0xc7, 0x99, 0xda, 0xee, 0x05,
- 0x6e, 0xcb, 0xe9, 0xf8, 0xb4, 0xca, 0x9f, 0x6b, 0x6b, 0x12, 0xd8, 0xdd, 0x09, 0xbc, 0x96, 0xd3,
- 0xf1, 0x4c, 0x60, 0x77, 0x87, 0xdc, 0x84, 0x3a, 0xef, 0xe7, 0x26, 0xa5, 0xd2, 0x72, 0x3a, 0x2b,
- 0xb4, 0xc6, 0x5f, 0xa3, 0x59, 0x86, 0x76, 0x77, 0x02, 0xbf, 0xe5, 0x74, 0x2a, 0x36, 0x54, 0x64,
- 0x49, 0x93, 0x55, 0x6d, 0x39, 0x9d, 0x2b, 0xb4, 0xc6, 0x8f, 0xa6, 0xb2, 0xa4, 0xc9, 0xaa, 0xb5,
- 0x9c, 0x0e, 0xb1, 0xa1, 0xdd, 0x1d, 0x73, 0x88, 0x61, 0xc2, 0x43, 0x15, 0xd4, 0x5b, 0x4e, 0xc7,
- 0xa5, 0x55, 0xfe, 0x54, 0x5b, 0x26, 0x27, 0xe2, 0xf9, 0x20, 0x61, 0x41, 0xa3, 0xe5, 0x74, 0x1c,
- 0x5a, 0xe3, 0xfb, 0x68, 0x5a, 0x3a, 0x25, 0xe2, 0xec, 0x34, 0x80, 0x96, 0xd3, 0x69, 0x68, 0x3a,
- 0x34, 0x0d, 0xdd, 0x60, 0xac, 0x98, 0x0c, 0x9a, 0x2d, 0xa7, 0xb3, 0x4c, 0xab, 0x7c, 0x4f, 0x5b,
- 0xed, 0x9f, 0x1c, 0x80, 0x43, 0x9e, 0x3d, 0x8d, 0xb3, 0x58, 0x31, 0x49, 0xae, 0x82, 0x3f, 0xec,
- 0x67, 0x61, 0x86, 0xa5, 0x72, 0x69, 0x65, 0x78, 0x18, 0x66, 0xba, 0x80, 0xc3, 0xfe, 0x28, 0xce,
- 0x86, 0x58, 0x28, 0x97, 0xfa, 0xc3, 0xaf, 0xe3, 0x6c, 0x68, 0xdc, 0x99, 0x76, 0x7b, 0xd6, 0x7d,
- 0xa8, 0xdd, 0x57, 0xc1, 0x8f, 0x90, 0xa2, 0x82, 0xa7, 0xab, 0x44, 0x96, 0x22, 0x32, 0x14, 0x3e,
- 0x7a, 0xfd, 0xa8, 0xa0, 0x88, 0x0c, 0x45, 0xd5, 0xba, 0x35, 0x45, 0xfb, 0x37, 0x17, 0x6a, 0x94,
- 0x8d, 0x58, 0xa8, 0xa4, 0x86, 0x88, 0x42, 0x3d, 0x4f, 0xab, 0x27, 0x0a, 0xf5, 0xc4, 0x44, 0x3d,
- 0x4f, 0xab, 0x27, 0x26, 0xea, 0x89, 0x89, 0x7a, 0x9e, 0x56, 0x4f, 0x4c, 0xd4, 0x13, 0xa5, 0x7a,
- 0x9e, 0x56, 0x4f, 0x94, 0xea, 0x89, 0x52, 0x3d, 0x4f, 0xab, 0x27, 0x4a, 0xf5, 0x44, 0xa9, 0x9e,
- 0xa7, 0xd5, 0x13, 0x47, 0x53, 0x59, 0x13, 0xf5, 0x3c, 0xad, 0x9e, 0x28, 0xd5, 0x13, 0x13, 0xf5,
- 0x3c, 0xad, 0x9e, 0x98, 0xa8, 0x27, 0x4a, 0xf5, 0x3c, 0xad, 0x9e, 0x28, 0xd5, 0x13, 0xa5, 0x7a,
- 0x9e, 0x56, 0x4f, 0x94, 0xea, 0x89, 0x89, 0x7a, 0x9e, 0x56, 0x4f, 0x18, 0xf5, 0x7e, 0x77, 0xa1,
- 0xfa, 0x26, 0x8e, 0x4e, 0x99, 0x22, 0xf7, 0xc0, 0x3f, 0xe1, 0x09, 0x17, 0xa8, 0xdc, 0x6a, 0x6f,
- 0xa3, 0x6b, 0x9e, 0x68, 0xd7, 0x84, 0xbb, 0x4f, 0x74, 0x8c, 0x1a, 0x08, 0xd9, 0xd2, 0x7c, 0x06,
- 0xad, 0x8b, 0xb7, 0x08, 0x5d, 0x15, 0xf8, 0x97, 0xdc, 0x85, 0xaa, 0xc4, 0xa7, 0x84, 0x5d, 0xd5,
- 0xec, 0xad, 0x16, 0x68, 0xf3, 0xc0, 0xa8, 0x8d, 0x92, 0x8f, 0x4c, 0x41, 0x10, 0xa9, 0xcf, 0x39,
- 0x8f, 0xd4, 0x05, 0xb2, 0xd0, 0x9a, 0x30, 0x02, 0x07, 0x1b, 0xc8, 0xb9, 0x56, 0x20, 0xad, 0xee,
- 0xb4, 0x88, 0x93, 0x8f, 0xa1, 0x21, 0xfa, 0x05, 0xf8, 0x1a, 0xd2, 0xce, 0x81, 0xeb, 0xc2, 0x7e,
- 0xb5, 0xff, 0x07, 0xbe, 0x39, 0x74, 0x0d, 0x3c, 0x7a, 0xb0, 0xbf, 0xbe, 0x44, 0x1a, 0xe0, 0x7f,
- 0x41, 0x0f, 0x0e, 0x0e, 0xd7, 0x1d, 0x52, 0x87, 0xca, 0xde, 0xcb, 0xd7, 0x07, 0xeb, 0x6e, 0xfb,
- 0x67, 0x17, 0x2a, 0xaf, 0xc2, 0x91, 0x24, 0x9f, 0x41, 0x33, 0x35, 0xed, 0xa2, 0x6b, 0x8f, 0x3d,
- 0xd6, 0xec, 0xfd, 0xab, 0xe0, 0xd7, 0x90, 0xee, 0x2b, 0xec, 0x9f, 0x23, 0x25, 0x0e, 0x32, 0x25,
- 0xc6, 0xb4, 0x91, 0x16, 0x36, 0x79, 0x0c, 0x2b, 0x29, 0xf6, 0x66, 0x71, 0x6b, 0x17, 0xd3, 0xff,
- 0x7d, 0x39, 0x5d, 0xf7, 0xab, 0xb9, 0xb6, 0x21, 0x68, 0xa6, 0xa5, 0x67, 0xf3, 0x73, 0x58, 0xbd,
- 0xcc, 0x4f, 0xd6, 0xc1, 0xfb, 0x96, 0x8d, 0x51, 0x46, 0x8f, 0xea, 0x4f, 0xb2, 0x01, 0xfe, 0x59,
- 0x98, 0xe4, 0x0c, 0x9f, 0x5f, 0x83, 0x1a, 0xe3, 0x91, 0xfb, 0xd0, 0xd9, 0x3c, 0x84, 0xf5, 0x59,
- 0xfa, 0xe9, 0xfc, 0xba, 0xc9, 0xbf, 0x33, 0x9d, 0x3f, 0x2f, 0x4a, 0xc9, 0xd7, 0xfe, 0xd3, 0x81,
- 0xe5, 0x57, 0xf2, 0xf4, 0x4d, 0xac, 0xde, 0x7e, 0x95, 0x31, 0x3e, 0x24, 0xd7, 0xc1, 0x57, 0xb1,
- 0x4a, 0x18, 0xd2, 0x35, 0x9e, 0x2d, 0x51, 0x63, 0x92, 0x00, 0xaa, 0x32, 0x4c, 0x42, 0x31, 0x46,
- 0x4e, 0xef, 0xd9, 0x12, 0xb5, 0x36, 0xd9, 0x84, 0xda, 0x13, 0x9e, 0xeb, 0x93, 0xe0, 0x58, 0xd0,
- 0x39, 0x85, 0x83, 0xdc, 0x86, 0xe5, 0xb7, 0x3c, 0x65, 0xfd, 0x30, 0x8a, 0x04, 0x93, 0x12, 0x27,
- 0x84, 0x06, 0x34, 0xb5, 0xf7, 0xb1, 0x71, 0x92, 0x03, 0xb8, 0x92, 0xca, 0xd3, 0xfe, 0x79, 0xac,
- 0xde, 0xf6, 0x05, 0xfb, 0x2e, 0x8f, 0x05, 0x8b, 0x70, 0x6a, 0x34, 0x7b, 0x37, 0x26, 0x85, 0x35,
- 0x67, 0xa4, 0x36, 0xfc, 0x6c, 0x89, 0xae, 0xa5, 0x97, 0x5d, 0x7b, 0x35, 0xf0, 0xf3, 0x2c, 0xe6,
- 0x59, 0xfb, 0x2e, 0x54, 0x28, 0x0b, 0x93, 0xb2, 0x8a, 0x8e, 0x19, 0x35, 0x68, 0xdc, 0xab, 0xd7,
- 0xa3, 0xf5, 0x8b, 0x8b, 0x8b, 0x0b, 0xb7, 0x7d, 0xae, 0x0f, 0xae, 0x0b, 0xf2, 0x9e, 0xdc, 0x82,
- 0x46, 0x9c, 0x86, 0xa7, 0x71, 0xa6, 0x2f, 0x68, 0xe0, 0xa5, 0xa3, 0x4c, 0xe9, 0xed, 0xc3, 0xaa,
- 0x60, 0x61, 0xd2, 0x67, 0xef, 0x15, 0xcb, 0x64, 0xcc, 0x33, 0xb2, 0x5c, 0x76, 0x66, 0x98, 0x04,
- 0xdf, 0x5f, 0x6e, 0x6d, 0x4b, 0x4f, 0x57, 0x74, 0xd2, 0x41, 0x91, 0xd3, 0xfe, 0xc3, 0x07, 0x78,
- 0x91, 0xf1, 0xf3, 0xec, 0x78, 0x3c, 0x62, 0x92, 0xdc, 0x01, 0x37, 0xcc, 0x82, 0x55, 0x4c, 0xdd,
- 0xe8, 0x9a, 0x35, 0xd7, 0x2d, 0xd6, 0x5c, 0xf7, 0x71, 0x36, 0xa6, 0x6e, 0x98, 0x91, 0xfb, 0xe0,
- 0x45, 0xb9, 0x79, 0xec, 0xcd, 0xde, 0xcd, 0x39, 0xd8, 0xbe, 0x5d, 0xb6, 0x54, 0xa3, 0xc8, 0xff,
- 0xc1, 0x95, 0x2a, 0x58, 0xb6, 0x35, 0x9c, 0xc5, 0x1e, 0xe1, 0xe2, 0xa5, 0xae, 0xd4, 0x43, 0xc4,
- 0x55, 0xd2, 0xb6, 0xc9, 0xe6, 0x1c, 0xf0, 0xb8, 0xd8, 0xc1, 0xd4, 0x55, 0x52, 0x63, 0x93, 0xb3,
- 0x60, 0x6d, 0x01, 0xf6, 0x65, 0x2c, 0xd5, 0x37, 0xba, 0xc2, 0xd4, 0x4d, 0xce, 0x48, 0x07, 0xbc,
- 0xb3, 0x30, 0x09, 0xd6, 0x11, 0x7c, 0x7d, 0x0e, 0x6c, 0x80, 0x1a, 0x42, 0xba, 0xe0, 0x45, 0x83,
- 0x04, 0x5b, 0xa7, 0xd9, 0xbb, 0x35, 0x7f, 0x2f, 0x9c, 0x95, 0x16, 0x1f, 0x0d, 0x12, 0xb2, 0x05,
- 0xde, 0x30, 0x51, 0xd8, 0x49, 0xfa, 0xdd, 0xce, 0xe2, 0x71, 0xea, 0x5a, 0xf8, 0x30, 0x51, 0x1a,
- 0x1e, 0xdb, 0x15, 0xfd, 0x21, 0x38, 0xbe, 0x44, 0x0b, 0x8f, 0x77, 0x77, 0xf4, 0x69, 0xf2, 0xdd,
- 0x1d, 0x5c, 0x4e, 0x1f, 0x3a, 0xcd, 0xeb, 0x69, 0x7c, 0xbe, 0xbb, 0x83, 0xf4, 0xdb, 0x3d, 0xdc,
- 0xe5, 0x0b, 0xe8, 0xb7, 0x7b, 0x05, 0xfd, 0x76, 0x0f, 0xe9, 0xb7, 0x7b, 0xb8, 0xe0, 0x17, 0xd1,
- 0x4f, 0xf0, 0x39, 0xe2, 0x2b, 0xb8, 0x09, 0x1b, 0x0b, 0x8a, 0xae, 0x47, 0x81, 0x81, 0x23, 0x4e,
- 0xf3, 0xeb, 0xa1, 0x06, 0x0b, 0xf8, 0xcd, 0x76, 0xb1, 0xfc, 0x52, 0x09, 0xf2, 0x09, 0xf8, 0xe5,
- 0xff, 0x08, 0x1f, 0xba, 0x00, 0x6e, 0x1d, 0x93, 0x60, 0x90, 0xed, 0xdb, 0xb0, 0x36, 0xf3, 0x18,
- 0xf5, 0x00, 0x32, 0xa3, 0xd4, 0xed, 0x34, 0x90, 0xb7, 0xfd, 0x8b, 0x0b, 0x37, 0x2c, 0xea, 0x79,
- 0x16, 0xc5, 0x82, 0x9d, 0xa8, 0x09, 0xfa, 0x3e, 0x54, 0x64, 0x3e, 0x48, 0x6d, 0x27, 0x2f, 0x7a,
- 0xe1, 0x14, 0x41, 0xe4, 0x4b, 0x68, 0xa4, 0xe1, 0xa8, 0x3f, 0x8c, 0x59, 0x12, 0xd9, 0x61, 0xbb,
- 0x35, 0x93, 0x31, 0xfb, 0x03, 0x7a, 0x08, 0x3f, 0xd5, 0x78, 0x33, 0x7c, 0xeb, 0xa9, 0x35, 0xc9,
- 0x43, 0x68, 0xca, 0x24, 0x3e, 0x61, 0x96, 0xcd, 0x43, 0xb6, 0x85, 0xbf, 0x0f, 0x88, 0xc5, 0xcc,
- 0xcd, 0x63, 0x58, 0xb9, 0x44, 0x3a, 0x3d, 0x72, 0x1b, 0x66, 0xe4, 0x6e, 0x5d, 0x1e, 0xb9, 0x0b,
- 0x69, 0xa7, 0x66, 0xef, 0x3d, 0xd8, 0x98, 0x89, 0x62, 0xb5, 0x09, 0x81, 0xca, 0x60, 0xac, 0x24,
- 0xd6, 0x73, 0x99, 0xe2, 0x77, 0x7b, 0x1f, 0xc8, 0x0c, 0xf6, 0xcd, 0x8b, 0xe3, 0x42, 0x6e, 0x0d,
- 0xfc, 0x27, 0x72, 0x3f, 0x6a, 0x41, 0x25, 0x0b, 0x53, 0x36, 0x33, 0xb4, 0x7e, 0xc0, 0x5b, 0x60,
- 0xe4, 0xd1, 0xa7, 0x50, 0x61, 0xef, 0x55, 0x3a, 0x83, 0xf8, 0xf1, 0x6f, 0xa4, 0xd2, 0x29, 0x7f,
- 0x05, 0x00, 0x00, 0xff, 0xff, 0xea, 0x06, 0x1a, 0xa9, 0x37, 0x0c, 0x00, 0x00,
+func init() { proto.RegisterFile("jsonpb_proto/test2.proto", fileDescriptor_50cab1d8463dea41) }
+
+var fileDescriptor_50cab1d8463dea41 = []byte{
+ // 1510 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x57, 0xdd, 0x6e, 0xdb, 0x46,
+ 0x16, 0x36, 0x49, 0x51, 0x12, 0x8f, 0x6c, 0xc7, 0x1e, 0x3b, 0x09, 0xed, 0x0d, 0xb2, 0x84, 0xb2,
+ 0xd9, 0xd5, 0x26, 0x58, 0x79, 0x43, 0x0b, 0x42, 0x91, 0x36, 0x40, 0xe3, 0xd8, 0x6e, 0xd2, 0x24,
+ 0x4e, 0x41, 0x27, 0x0d, 0xda, 0x1b, 0x81, 0x32, 0x29, 0x99, 0x2d, 0xc9, 0x51, 0x67, 0x46, 0x4e,
+ 0x84, 0xb6, 0x80, 0xfb, 0x0a, 0x7d, 0x85, 0x02, 0xbd, 0xed, 0x5d, 0x2f, 0xfa, 0x1c, 0x45, 0x9f,
+ 0xa7, 0x98, 0x33, 0x43, 0xfd, 0x59, 0x36, 0x72, 0x65, 0xcd, 0x7c, 0x3f, 0x33, 0x9c, 0xf3, 0xf1,
+ 0x0c, 0x0d, 0xee, 0x37, 0x9c, 0xe6, 0x83, 0x6e, 0x67, 0xc0, 0xa8, 0xa0, 0x3b, 0x22, 0xe6, 0xc2,
+ 0x6f, 0xe2, 0x6f, 0x52, 0xd3, 0x88, 0x9c, 0xdb, 0xde, 0xea, 0x53, 0xda, 0x4f, 0xe3, 0x1d, 0x84,
+ 0xba, 0xc3, 0xde, 0x4e, 0x98, 0x8f, 0x14, 0x6f, 0xfb, 0xf6, 0x3c, 0x14, 0x0d, 0x59, 0x28, 0x12,
+ 0x9a, 0x6b, 0xfc, 0xd6, 0x3c, 0xce, 0x05, 0x1b, 0x9e, 0x08, 0x8d, 0xfe, 0x73, 0x1e, 0x15, 0x49,
+ 0x16, 0x73, 0x11, 0x66, 0x83, 0xcb, 0xec, 0xdf, 0xb1, 0x70, 0x30, 0x88, 0x19, 0x57, 0x78, 0xfd,
+ 0xb7, 0x12, 0x94, 0x8f, 0x93, 0x6c, 0x90, 0xc6, 0xe4, 0x3a, 0x94, 0x69, 0xa7, 0x4b, 0x69, 0xea,
+ 0x1a, 0x9e, 0xd1, 0xa8, 0x06, 0x36, 0xdd, 0xa3, 0x34, 0x25, 0x37, 0xa1, 0x42, 0x3b, 0x49, 0x2e,
+ 0x76, 0x7d, 0xd7, 0xf4, 0x8c, 0x86, 0x1d, 0x94, 0xe9, 0x33, 0x39, 0x22, 0xb7, 0xa1, 0xa6, 0x81,
+ 0x0e, 0x17, 0xcc, 0xb5, 0x10, 0x74, 0x14, 0x78, 0x2c, 0xd8, 0x58, 0xd8, 0x6e, 0xb9, 0x25, 0xcf,
+ 0x68, 0x58, 0x4a, 0xd8, 0x6e, 0x8d, 0x85, 0xed, 0x16, 0x0a, 0x6d, 0x04, 0x1d, 0x05, 0x4a, 0xe1,
+ 0x16, 0x54, 0x69, 0x67, 0xa8, 0x96, 0x2c, 0x7b, 0x46, 0x63, 0x25, 0xa8, 0xd0, 0x37, 0x38, 0x24,
+ 0x1e, 0x2c, 0x17, 0x10, 0x6a, 0x2b, 0x08, 0x83, 0x86, 0x67, 0xc4, 0xed, 0x96, 0x5b, 0xf5, 0x8c,
+ 0x46, 0x49, 0x8b, 0xdb, 0xad, 0x89, 0x58, 0x2f, 0xec, 0x20, 0x0c, 0x1a, 0x1e, 0x8b, 0xb9, 0x5a,
+ 0x19, 0x3c, 0xa3, 0xb1, 0x1e, 0x54, 0xe8, 0xf1, 0xd4, 0xca, 0x7c, 0xb2, 0x72, 0x0d, 0x61, 0xd0,
+ 0xf0, 0x8c, 0xb8, 0xdd, 0x72, 0x97, 0x3d, 0xa3, 0x41, 0xb4, 0xb8, 0x58, 0x99, 0x4f, 0x56, 0x5e,
+ 0x41, 0x18, 0x34, 0x3c, 0x3e, 0xac, 0x5e, 0x4a, 0x43, 0xe1, 0xae, 0x7a, 0x46, 0xc3, 0x0c, 0xca,
+ 0xf4, 0x50, 0x8e, 0xd4, 0x61, 0x21, 0x80, 0xca, 0x6b, 0x08, 0x3a, 0x0a, 0x1c, 0xaf, 0x1a, 0xd1,
+ 0x61, 0x37, 0x8d, 0xdd, 0x35, 0xcf, 0x68, 0x18, 0x41, 0x85, 0xee, 0xe3, 0x50, 0xad, 0xaa, 0x20,
+ 0xd4, 0xae, 0x23, 0x0c, 0x1a, 0x9e, 0x6c, 0x59, 0xb0, 0x24, 0xef, 0xbb, 0xc4, 0x33, 0x1a, 0x8e,
+ 0xdc, 0x32, 0x0e, 0xd5, 0x86, 0xba, 0x23, 0x11, 0x73, 0x77, 0xc3, 0x33, 0x1a, 0xcb, 0x41, 0x99,
+ 0xee, 0xc9, 0x51, 0xfd, 0x67, 0x03, 0xe0, 0x88, 0xe6, 0x87, 0x49, 0x9e, 0x88, 0x98, 0x93, 0x0d,
+ 0xb0, 0x7b, 0x9d, 0x3c, 0xcc, 0x31, 0x34, 0x66, 0x50, 0xea, 0x1d, 0x85, 0xb9, 0x8c, 0x52, 0xaf,
+ 0x33, 0x48, 0xf2, 0x1e, 0x46, 0xc6, 0x0c, 0xec, 0xde, 0x17, 0x49, 0xde, 0x53, 0xd3, 0xb9, 0x9c,
+ 0xb6, 0xf4, 0xf4, 0x91, 0x9c, 0xde, 0x00, 0x3b, 0x42, 0x8b, 0x12, 0x6e, 0xb0, 0x14, 0x69, 0x8b,
+ 0x48, 0x59, 0xd8, 0x38, 0x6b, 0x47, 0x85, 0x45, 0xa4, 0x2c, 0xca, 0x7a, 0x5a, 0x5a, 0xd4, 0x7f,
+ 0x35, 0xa1, 0x12, 0xc4, 0x83, 0x38, 0x14, 0x5c, 0x52, 0x58, 0x91, 0x63, 0x4b, 0xe6, 0x98, 0x15,
+ 0x39, 0x66, 0xe3, 0x1c, 0x5b, 0x32, 0xc7, 0x4c, 0xe5, 0xb8, 0x00, 0xda, 0x2d, 0xd7, 0xf2, 0x2c,
+ 0x99, 0x53, 0xa6, 0x72, 0xba, 0x05, 0x55, 0x56, 0xe4, 0xb0, 0xe4, 0x59, 0x32, 0x87, 0x4c, 0xe7,
+ 0x70, 0x0c, 0xb5, 0x5b, 0xae, 0xed, 0x59, 0x32, 0x65, 0x4c, 0xa7, 0x0c, 0x21, 0x5e, 0xa4, 0xd7,
+ 0x92, 0x19, 0x62, 0xc7, 0x53, 0x2a, 0x9d, 0x90, 0x8a, 0x67, 0xc9, 0x84, 0x30, 0x9d, 0x10, 0xdc,
+ 0x84, 0xaa, 0x7f, 0xd5, 0xb3, 0x64, 0xfd, 0x99, 0xaa, 0x3f, 0x6a, 0x74, 0x7d, 0x1d, 0xcf, 0x92,
+ 0xf5, 0x65, 0xba, 0xbe, 0xca, 0x4e, 0x55, 0x0f, 0x3c, 0x4b, 0x56, 0x8f, 0x4d, 0xaa, 0xc7, 0x74,
+ 0xf5, 0x6a, 0x9e, 0x25, 0xab, 0xc7, 0x54, 0xf5, 0xfe, 0x34, 0xa1, 0xfc, 0x36, 0x89, 0xfa, 0xb1,
+ 0x20, 0x3b, 0x60, 0x9f, 0xd0, 0x94, 0x32, 0xac, 0xdc, 0xaa, 0xbf, 0xd5, 0x9c, 0xea, 0x58, 0x4d,
+ 0xc5, 0x69, 0x3e, 0x91, 0x84, 0x40, 0xf1, 0x88, 0x2f, 0x4d, 0x95, 0x44, 0x9e, 0xe0, 0x95, 0x92,
+ 0x32, 0xc3, 0xbf, 0xe4, 0x3e, 0x94, 0x39, 0xb6, 0x17, 0x7c, 0x9f, 0x6a, 0xfe, 0xc6, 0x8c, 0x44,
+ 0x75, 0x9e, 0x40, 0x53, 0x48, 0x53, 0x9d, 0x0f, 0xd2, 0xe5, 0xb6, 0x2f, 0xa1, 0xcb, 0x43, 0xd3,
+ 0xfc, 0x0a, 0x53, 0x45, 0x77, 0x37, 0xd1, 0x7d, 0x73, 0x86, 0xae, 0x03, 0x11, 0x14, 0x24, 0xf2,
+ 0x00, 0x1c, 0xd6, 0x29, 0x14, 0xd7, 0x71, 0x81, 0xc5, 0x8a, 0x2a, 0xd3, 0xbf, 0xea, 0x77, 0xc1,
+ 0x56, 0x0f, 0x52, 0x01, 0x2b, 0x38, 0xd8, 0x5f, 0x5b, 0x22, 0x0e, 0xd8, 0x9f, 0x05, 0x07, 0x07,
+ 0x47, 0x6b, 0x06, 0xa9, 0x42, 0x69, 0xef, 0xc5, 0x9b, 0x83, 0x35, 0xb3, 0xfe, 0x8b, 0x09, 0xa5,
+ 0x97, 0xe1, 0x80, 0x93, 0x4f, 0xa1, 0x96, 0x4d, 0xf5, 0x36, 0x03, 0x17, 0xf1, 0x66, 0x16, 0x91,
+ 0xbc, 0xe6, 0xcb, 0xa2, 0xdb, 0x1d, 0xe4, 0x82, 0x8d, 0x02, 0x27, 0x1b, 0x77, 0xbf, 0x43, 0x58,
+ 0xc9, 0x30, 0xbe, 0xc5, 0x49, 0x98, 0xe8, 0x51, 0x5f, 0xe0, 0x21, 0x73, 0xad, 0x8e, 0x42, 0xb9,
+ 0xd4, 0xb2, 0xc9, 0xcc, 0xf6, 0x27, 0xb0, 0x3a, 0xbb, 0x08, 0x59, 0x03, 0xeb, 0xdb, 0x78, 0x84,
+ 0xe5, 0xb6, 0x02, 0xf9, 0x93, 0x6c, 0x82, 0x7d, 0x16, 0xa6, 0xc3, 0x18, 0x5f, 0x53, 0x27, 0x50,
+ 0x83, 0x87, 0xe6, 0x47, 0xc6, 0xf6, 0x31, 0xac, 0xcd, 0xdb, 0x4f, 0xeb, 0xab, 0x4a, 0xff, 0xdf,
+ 0x69, 0xfd, 0x25, 0xd5, 0x9a, 0x98, 0xd6, 0xff, 0x32, 0x60, 0xf9, 0x25, 0xef, 0xbf, 0x4d, 0xc4,
+ 0xe9, 0xab, 0x3c, 0xa6, 0x3d, 0x72, 0x03, 0x6c, 0x91, 0x88, 0x34, 0x46, 0x4f, 0xe7, 0xe9, 0x52,
+ 0xa0, 0x86, 0xc4, 0x85, 0x32, 0x0f, 0xd3, 0x90, 0x8d, 0xd0, 0xd8, 0x7a, 0xba, 0x14, 0xe8, 0x31,
+ 0xd9, 0x86, 0xca, 0x13, 0x3a, 0x94, 0xdb, 0xc1, 0x1e, 0x22, 0x35, 0xc5, 0x04, 0xb9, 0x03, 0xcb,
+ 0xa7, 0x34, 0x8b, 0x3b, 0x61, 0x14, 0xb1, 0x98, 0x73, 0x6c, 0x27, 0x92, 0x50, 0x93, 0xb3, 0x8f,
+ 0xd5, 0x24, 0xf9, 0x1c, 0xd6, 0x33, 0xde, 0xef, 0xbc, 0x4b, 0xc4, 0x69, 0x87, 0xc5, 0xdf, 0x0d,
+ 0x13, 0x16, 0x47, 0xd8, 0x62, 0x6a, 0xfe, 0xad, 0xd9, 0x23, 0x56, 0x1b, 0x0d, 0x34, 0xe7, 0xe9,
+ 0x52, 0x70, 0x2d, 0x9b, 0x9d, 0xda, 0xab, 0x80, 0x3d, 0xcc, 0x13, 0x9a, 0xd7, 0xff, 0x0d, 0xa5,
+ 0x20, 0x0e, 0xd3, 0xc9, 0x79, 0x1a, 0xaa, 0x39, 0xe1, 0xe0, 0x5e, 0xb5, 0x1a, 0xad, 0x9d, 0x9f,
+ 0x9f, 0x9f, 0x9b, 0xf5, 0x9f, 0x0c, 0xb9, 0x7d, 0x79, 0x2c, 0xef, 0xc9, 0x2d, 0x70, 0x92, 0x2c,
+ 0xec, 0x27, 0xb9, 0x7c, 0x4c, 0xc5, 0x9f, 0x4c, 0x4c, 0x34, 0xfe, 0x11, 0xac, 0xb2, 0x38, 0x4c,
+ 0x3b, 0xf1, 0x7b, 0x11, 0xe7, 0x3c, 0xa1, 0x39, 0x59, 0x9f, 0xcb, 0x6c, 0x98, 0xba, 0xdf, 0x2f,
+ 0x88, 0xbf, 0x5e, 0x28, 0x58, 0x91, 0xf2, 0x83, 0x42, 0x5d, 0xff, 0xc3, 0x06, 0x78, 0x9e, 0xd3,
+ 0x77, 0xf9, 0xeb, 0xd1, 0x20, 0xe6, 0xe4, 0x5f, 0x60, 0x86, 0x39, 0xde, 0x39, 0x52, 0xaf, 0xbe,
+ 0x16, 0x9a, 0xc5, 0xd7, 0x42, 0xf3, 0x71, 0x3e, 0x0a, 0xcc, 0x30, 0x27, 0xf7, 0xc1, 0x8a, 0x86,
+ 0xaa, 0x53, 0xd4, 0xfc, 0xad, 0x0b, 0xb4, 0x7d, 0xfd, 0xcd, 0x12, 0x48, 0x16, 0xf9, 0x0f, 0x98,
+ 0x5c, 0xe0, 0x15, 0x58, 0xf3, 0x6f, 0x5e, 0xe0, 0x1e, 0xe3, 0xf7, 0x4b, 0x60, 0x72, 0x41, 0xee,
+ 0x81, 0x29, 0xb8, 0xce, 0xce, 0xf6, 0x05, 0xe2, 0xeb, 0xe2, 0x53, 0x26, 0x30, 0x05, 0x97, 0xdc,
+ 0xf4, 0x0c, 0xaf, 0xbf, 0x45, 0xdc, 0x17, 0x09, 0x17, 0x5f, 0xca, 0xc3, 0x0e, 0xcc, 0xf4, 0x8c,
+ 0x34, 0xc0, 0x3a, 0x0b, 0x53, 0xbc, 0x0e, 0x6b, 0xfe, 0x8d, 0x0b, 0x64, 0x45, 0x94, 0x14, 0xd2,
+ 0x04, 0x2b, 0xea, 0xa6, 0x18, 0x25, 0x59, 0xff, 0x0b, 0xcf, 0x85, 0x8d, 0x56, 0xf3, 0xa3, 0x6e,
+ 0x4a, 0xfe, 0x07, 0x56, 0x2f, 0x15, 0x98, 0xac, 0x9a, 0xff, 0x8f, 0x0b, 0x7c, 0x6c, 0xd9, 0x9a,
+ 0xde, 0x4b, 0x85, 0xa4, 0x27, 0x78, 0x43, 0x2c, 0xa6, 0xe3, 0xeb, 0xa9, 0xe9, 0x49, 0xbb, 0x25,
+ 0x77, 0x33, 0x6c, 0xb7, 0xf0, 0x66, 0x5b, 0xb4, 0x9b, 0x37, 0xd3, 0xfc, 0x61, 0xbb, 0x85, 0xf6,
+ 0xbb, 0x3e, 0x7e, 0x04, 0x5d, 0x62, 0xbf, 0xeb, 0x17, 0xf6, 0xbb, 0x3e, 0xda, 0xef, 0xfa, 0xf8,
+ 0x55, 0x74, 0x99, 0xfd, 0x98, 0x3f, 0x44, 0x7e, 0x09, 0xaf, 0x51, 0xe7, 0x92, 0x43, 0x97, 0xfd,
+ 0x41, 0xd1, 0x91, 0x27, 0xfd, 0x65, 0xcf, 0x83, 0x4b, 0xfc, 0xd5, 0xd5, 0xa4, 0xfd, 0xb9, 0x60,
+ 0xe4, 0x01, 0xd8, 0xc5, 0x15, 0xb5, 0xf8, 0x01, 0xf0, 0xca, 0x52, 0x02, 0xc5, 0xac, 0xdf, 0x81,
+ 0x6b, 0x73, 0xef, 0xa5, 0xec, 0x4a, 0xaa, 0xd3, 0x9a, 0x0d, 0x07, 0x7d, 0xeb, 0xbf, 0x9b, 0x70,
+ 0x53, 0xb3, 0x9e, 0xe5, 0x51, 0xc2, 0xe2, 0x13, 0x31, 0x66, 0xff, 0x1f, 0x4a, 0x7c, 0xd8, 0xcd,
+ 0x74, 0x92, 0xaf, 0x7c, 0xe3, 0x03, 0x64, 0x92, 0x57, 0xe0, 0x64, 0xe1, 0xa0, 0xd3, 0x4b, 0xe2,
+ 0x34, 0xd2, 0xbd, 0xd8, 0x5f, 0x24, 0x9b, 0x5f, 0x4a, 0xf6, 0xe8, 0x43, 0x29, 0x52, 0xbd, 0xb9,
+ 0x9a, 0xe9, 0x21, 0x79, 0x04, 0x35, 0x9e, 0x26, 0x27, 0xb1, 0xb6, 0xb4, 0xd0, 0xf2, 0xea, 0x9d,
+ 0x00, 0x0a, 0x50, 0xbe, 0xfd, 0x15, 0xac, 0xcc, 0x38, 0x4f, 0xb7, 0x65, 0x47, 0xb5, 0x65, 0x7f,
+ 0xb6, 0x2d, 0x5f, 0xed, 0x3d, 0xd5, 0x9f, 0xef, 0xc1, 0xe6, 0x1c, 0x8a, 0x15, 0x20, 0x04, 0x4a,
+ 0xdd, 0x91, 0xe0, 0x78, 0xc6, 0xcb, 0x01, 0xfe, 0xae, 0xef, 0x03, 0x99, 0xe3, 0xbe, 0x7d, 0xfe,
+ 0xba, 0x88, 0x80, 0x24, 0x7e, 0x48, 0x04, 0x1e, 0xde, 0x85, 0x52, 0x1e, 0x66, 0xf1, 0xa2, 0x96,
+ 0xf6, 0x03, 0x3e, 0x0f, 0xc2, 0x0f, 0x9f, 0x40, 0x29, 0x7e, 0x2f, 0xb2, 0x45, 0xb4, 0x1f, 0x3f,
+ 0xa4, 0x90, 0x52, 0xbc, 0xf7, 0xe8, 0xeb, 0x8f, 0xfb, 0x89, 0x38, 0x1d, 0x76, 0x9b, 0x27, 0x34,
+ 0xdb, 0xe9, 0xd3, 0x34, 0xcc, 0xfb, 0x93, 0xff, 0x8b, 0x92, 0x5c, 0xc4, 0x2c, 0x0f, 0x53, 0xfc,
+ 0x27, 0x0e, 0x67, 0xf9, 0xce, 0xf4, 0x3f, 0x77, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0xba, 0x6b,
+ 0x0b, 0xa0, 0xeb, 0x0d, 0x00, 0x00,
}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test2.proto
similarity index 61%
rename from vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
rename to vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test2.proto
index 36eb6e8c6..d34dc33d6 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test2.proto
@@ -1,57 +1,40 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
syntax = "proto2";
+option go_package = "github.com/golang/protobuf/internal/testprotos/jsonpb_proto";
+
import "google/protobuf/any.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";
-package jsonpb;
+package jsonpb_test;
// Test message for holding primitive types.
message Simple {
optional bool o_bool = 1;
optional int32 o_int32 = 2;
- optional int64 o_int64 = 3;
- optional uint32 o_uint32 = 4;
- optional uint64 o_uint64 = 5;
- optional sint32 o_sint32 = 6;
- optional sint64 o_sint64 = 7;
- optional float o_float = 8;
- optional double o_double = 9;
- optional string o_string = 10;
- optional bytes o_bytes = 11;
+ optional int32 o_int32_str = 3;
+ optional int64 o_int64 = 4;
+ optional int64 o_int64_str = 5;
+ optional uint32 o_uint32 = 6;
+ optional uint32 o_uint32_str = 7;
+ optional uint64 o_uint64 = 8;
+ optional uint64 o_uint64_str = 9;
+ optional sint32 o_sint32 = 10;
+ optional sint32 o_sint32_str = 11;
+ optional sint64 o_sint64 = 12;
+ optional sint64 o_sint64_str = 13;
+ optional float o_float = 14;
+ optional float o_float_str = 15;
+ optional double o_double = 16;
+ optional double o_double_str = 17;
+ optional string o_string = 18;
+ optional bytes o_bytes = 19;
}
// Test message for holding special non-finites primitives.
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test3.pb.go
similarity index 50%
rename from vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
rename to vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test3.pb.go
index 1bcce029c..cb9a81411 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test3.pb.go
@@ -1,11 +1,13 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: more_test_objects.proto
+// source: jsonpb_proto/test3.proto
-package jsonpb
+package jsonpb_proto
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
+import (
+ fmt "fmt"
+ proto "github.com/golang/protobuf/proto"
+ math "math"
+)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
@@ -16,7 +18,7 @@ var _ = math.Inf
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type Numeral int32
@@ -31,6 +33,7 @@ var Numeral_name = map[int32]string{
1: "ARABIC",
2: "ROMAN",
}
+
var Numeral_value = map[string]int32{
"UNKNOWN": 0,
"ARABIC": 1,
@@ -40,12 +43,13 @@ var Numeral_value = map[string]int32{
func (x Numeral) String() string {
return proto.EnumName(Numeral_name, int32(x))
}
+
func (Numeral) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{0}
+ return fileDescriptor_813baf511b225405, []int{0}
}
type Simple3 struct {
- Dub float64 `protobuf:"fixed64,1,opt,name=dub" json:"dub,omitempty"`
+ Dub float64 `protobuf:"fixed64,1,opt,name=dub,proto3" json:"dub,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -55,16 +59,17 @@ func (m *Simple3) Reset() { *m = Simple3{} }
func (m *Simple3) String() string { return proto.CompactTextString(m) }
func (*Simple3) ProtoMessage() {}
func (*Simple3) Descriptor() ([]byte, []int) {
- return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{0}
+ return fileDescriptor_813baf511b225405, []int{0}
}
+
func (m *Simple3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Simple3.Unmarshal(m, b)
}
func (m *Simple3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Simple3.Marshal(b, m, deterministic)
}
-func (dst *Simple3) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Simple3.Merge(dst, src)
+func (m *Simple3) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Simple3.Merge(m, src)
}
func (m *Simple3) XXX_Size() int {
return xxx_messageInfo_Simple3.Size(m)
@@ -83,7 +88,7 @@ func (m *Simple3) GetDub() float64 {
}
type SimpleSlice3 struct {
- Slices []string `protobuf:"bytes,1,rep,name=slices" json:"slices,omitempty"`
+ Slices []string `protobuf:"bytes,1,rep,name=slices,proto3" json:"slices,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -93,16 +98,17 @@ func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} }
func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) }
func (*SimpleSlice3) ProtoMessage() {}
func (*SimpleSlice3) Descriptor() ([]byte, []int) {
- return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{1}
+ return fileDescriptor_813baf511b225405, []int{1}
}
+
func (m *SimpleSlice3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SimpleSlice3.Unmarshal(m, b)
}
func (m *SimpleSlice3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SimpleSlice3.Marshal(b, m, deterministic)
}
-func (dst *SimpleSlice3) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SimpleSlice3.Merge(dst, src)
+func (m *SimpleSlice3) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SimpleSlice3.Merge(m, src)
}
func (m *SimpleSlice3) XXX_Size() int {
return xxx_messageInfo_SimpleSlice3.Size(m)
@@ -121,7 +127,7 @@ func (m *SimpleSlice3) GetSlices() []string {
}
type SimpleMap3 struct {
- Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy,proto3" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -131,16 +137,17 @@ func (m *SimpleMap3) Reset() { *m = SimpleMap3{} }
func (m *SimpleMap3) String() string { return proto.CompactTextString(m) }
func (*SimpleMap3) ProtoMessage() {}
func (*SimpleMap3) Descriptor() ([]byte, []int) {
- return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{2}
+ return fileDescriptor_813baf511b225405, []int{2}
}
+
func (m *SimpleMap3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SimpleMap3.Unmarshal(m, b)
}
func (m *SimpleMap3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SimpleMap3.Marshal(b, m, deterministic)
}
-func (dst *SimpleMap3) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SimpleMap3.Merge(dst, src)
+func (m *SimpleMap3) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SimpleMap3.Merge(m, src)
}
func (m *SimpleMap3) XXX_Size() int {
return xxx_messageInfo_SimpleMap3.Size(m)
@@ -159,7 +166,7 @@ func (m *SimpleMap3) GetStringy() map[string]string {
}
type SimpleNull3 struct {
- Simple *Simple3 `protobuf:"bytes,1,opt,name=simple" json:"simple,omitempty"`
+ Simple *Simple3 `protobuf:"bytes,1,opt,name=simple,proto3" json:"simple,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -169,16 +176,17 @@ func (m *SimpleNull3) Reset() { *m = SimpleNull3{} }
func (m *SimpleNull3) String() string { return proto.CompactTextString(m) }
func (*SimpleNull3) ProtoMessage() {}
func (*SimpleNull3) Descriptor() ([]byte, []int) {
- return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{3}
+ return fileDescriptor_813baf511b225405, []int{3}
}
+
func (m *SimpleNull3) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SimpleNull3.Unmarshal(m, b)
}
func (m *SimpleNull3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SimpleNull3.Marshal(b, m, deterministic)
}
-func (dst *SimpleNull3) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SimpleNull3.Merge(dst, src)
+func (m *SimpleNull3) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SimpleNull3.Merge(m, src)
}
func (m *SimpleNull3) XXX_Size() int {
return xxx_messageInfo_SimpleNull3.Size(m)
@@ -197,16 +205,16 @@ func (m *SimpleNull3) GetSimple() *Simple3 {
}
type Mappy struct {
- Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- Strry map[string]string `protobuf:"bytes,2,rep,name=strry" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=jsonpb.Numeral"`
- S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy,proto3" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ Strry map[string]string `protobuf:"bytes,2,rep,name=strry,proto3" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy,proto3" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy,proto3" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly,proto3" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy,proto3" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3,enum=jsonpb_test.Numeral"`
+ S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly,proto3" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly,proto3" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly,proto3" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly,proto3" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -216,16 +224,17 @@ func (m *Mappy) Reset() { *m = Mappy{} }
func (m *Mappy) String() string { return proto.CompactTextString(m) }
func (*Mappy) ProtoMessage() {}
func (*Mappy) Descriptor() ([]byte, []int) {
- return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{4}
+ return fileDescriptor_813baf511b225405, []int{4}
}
+
func (m *Mappy) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Mappy.Unmarshal(m, b)
}
func (m *Mappy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Mappy.Marshal(b, m, deterministic)
}
-func (dst *Mappy) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Mappy.Merge(dst, src)
+func (m *Mappy) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Mappy.Merge(m, src)
}
func (m *Mappy) XXX_Size() int {
return xxx_messageInfo_Mappy.Size(m)
@@ -307,62 +316,63 @@ func (m *Mappy) GetU64Booly() map[uint64]bool {
}
func init() {
- proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3")
- proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3")
- proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3")
- proto.RegisterMapType((map[string]string)(nil), "jsonpb.SimpleMap3.StringyEntry")
- proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3")
- proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy")
- proto.RegisterMapType((map[bool]bool)(nil), "jsonpb.Mappy.BoolyEntry")
- proto.RegisterMapType((map[int64]string)(nil), "jsonpb.Mappy.BuggyEntry")
- proto.RegisterMapType((map[string]Numeral)(nil), "jsonpb.Mappy.EnumyEntry")
- proto.RegisterMapType((map[int64]int32)(nil), "jsonpb.Mappy.NummyEntry")
- proto.RegisterMapType((map[int32]*Simple3)(nil), "jsonpb.Mappy.ObjjyEntry")
- proto.RegisterMapType((map[int32]bool)(nil), "jsonpb.Mappy.S32boolyEntry")
- proto.RegisterMapType((map[int64]bool)(nil), "jsonpb.Mappy.S64boolyEntry")
- proto.RegisterMapType((map[string]string)(nil), "jsonpb.Mappy.StrryEntry")
- proto.RegisterMapType((map[uint32]bool)(nil), "jsonpb.Mappy.U32boolyEntry")
- proto.RegisterMapType((map[uint64]bool)(nil), "jsonpb.Mappy.U64boolyEntry")
- proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value)
-}
-
-func init() {
- proto.RegisterFile("more_test_objects.proto", fileDescriptor_more_test_objects_bef0d79b901f4c4a)
-}
-
-var fileDescriptor_more_test_objects_bef0d79b901f4c4a = []byte{
- // 526 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c,
- 0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0,
- 0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2,
- 0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48,
- 0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3,
- 0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79,
- 0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e,
- 0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94,
- 0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e,
- 0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5,
- 0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13,
- 0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3,
- 0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe,
- 0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46,
- 0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7,
- 0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01,
- 0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0,
- 0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2,
- 0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93,
- 0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8,
- 0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7,
- 0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15,
- 0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11,
- 0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f,
- 0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b,
- 0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf,
- 0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda,
- 0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43,
- 0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9,
- 0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0,
- 0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe,
- 0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe,
- 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00,
+ proto.RegisterEnum("jsonpb_test.Numeral", Numeral_name, Numeral_value)
+ proto.RegisterType((*Simple3)(nil), "jsonpb_test.Simple3")
+ proto.RegisterType((*SimpleSlice3)(nil), "jsonpb_test.SimpleSlice3")
+ proto.RegisterType((*SimpleMap3)(nil), "jsonpb_test.SimpleMap3")
+ proto.RegisterMapType((map[string]string)(nil), "jsonpb_test.SimpleMap3.StringyEntry")
+ proto.RegisterType((*SimpleNull3)(nil), "jsonpb_test.SimpleNull3")
+ proto.RegisterType((*Mappy)(nil), "jsonpb_test.Mappy")
+ proto.RegisterMapType((map[bool]bool)(nil), "jsonpb_test.Mappy.BoolyEntry")
+ proto.RegisterMapType((map[int64]string)(nil), "jsonpb_test.Mappy.BuggyEntry")
+ proto.RegisterMapType((map[string]Numeral)(nil), "jsonpb_test.Mappy.EnumyEntry")
+ proto.RegisterMapType((map[int64]int32)(nil), "jsonpb_test.Mappy.NummyEntry")
+ proto.RegisterMapType((map[int32]*Simple3)(nil), "jsonpb_test.Mappy.ObjjyEntry")
+ proto.RegisterMapType((map[int32]bool)(nil), "jsonpb_test.Mappy.S32boolyEntry")
+ proto.RegisterMapType((map[int64]bool)(nil), "jsonpb_test.Mappy.S64boolyEntry")
+ proto.RegisterMapType((map[string]string)(nil), "jsonpb_test.Mappy.StrryEntry")
+ proto.RegisterMapType((map[uint32]bool)(nil), "jsonpb_test.Mappy.U32boolyEntry")
+ proto.RegisterMapType((map[uint64]bool)(nil), "jsonpb_test.Mappy.U64boolyEntry")
+}
+
+func init() { proto.RegisterFile("jsonpb_proto/test3.proto", fileDescriptor_813baf511b225405) }
+
+var fileDescriptor_813baf511b225405 = []byte{
+ // 563 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x95, 0xdd, 0x8a, 0xd3, 0x40,
+ 0x14, 0xc7, 0x4d, 0xbb, 0x69, 0x9b, 0xd3, 0x5d, 0x29, 0xc3, 0x22, 0xa1, 0x22, 0x94, 0x22, 0xb2,
+ 0x2c, 0x9a, 0x40, 0x23, 0xb2, 0x6c, 0x55, 0x68, 0x65, 0x2f, 0x44, 0x9a, 0x42, 0x4a, 0x11, 0xbc,
+ 0x91, 0x64, 0x8d, 0x31, 0x35, 0x5f, 0x24, 0x19, 0x21, 0x6f, 0xe0, 0x2b, 0xf9, 0x76, 0x32, 0x1f,
+ 0xd9, 0x4c, 0x4a, 0x86, 0xea, 0xd5, 0x9e, 0x99, 0xf3, 0xff, 0xe5, 0x7c, 0xec, 0xbf, 0x0c, 0xe8,
+ 0x87, 0x22, 0x4d, 0x32, 0xef, 0x6b, 0x96, 0xa7, 0x65, 0x6a, 0x96, 0x7e, 0x51, 0x5a, 0x06, 0x8d,
+ 0xd1, 0x98, 0x67, 0xc8, 0xdd, 0xfc, 0x29, 0x0c, 0x77, 0x61, 0x9c, 0x45, 0xbe, 0x85, 0x26, 0xd0,
+ 0xff, 0x86, 0x3d, 0x5d, 0x99, 0x29, 0x57, 0x8a, 0x43, 0xc2, 0xf9, 0x0b, 0x38, 0x67, 0xc9, 0x5d,
+ 0x14, 0xde, 0xfb, 0x16, 0x7a, 0x02, 0x83, 0x82, 0x44, 0x85, 0xae, 0xcc, 0xfa, 0x57, 0x9a, 0xc3,
+ 0x4f, 0xf3, 0xdf, 0x0a, 0x00, 0x13, 0x6e, 0xdc, 0xcc, 0x42, 0xef, 0x61, 0x58, 0x94, 0x79, 0x98,
+ 0x04, 0x15, 0xd5, 0x8d, 0x17, 0xcf, 0x0d, 0xa1, 0xa4, 0xd1, 0x28, 0x8d, 0x1d, 0x93, 0xdd, 0x25,
+ 0x65, 0x5e, 0x39, 0x35, 0x34, 0xbd, 0x85, 0x73, 0x31, 0x41, 0x1a, 0xfb, 0xe9, 0x57, 0xb4, 0x31,
+ 0xcd, 0x21, 0x21, 0xba, 0x04, 0xf5, 0x97, 0x1b, 0x61, 0x5f, 0xef, 0xd1, 0x3b, 0x76, 0xb8, 0xed,
+ 0xdd, 0x28, 0xf3, 0x25, 0x8c, 0xd9, 0xf7, 0x6d, 0x1c, 0x45, 0x16, 0x7a, 0x09, 0x83, 0x82, 0x1e,
+ 0x29, 0x3d, 0x5e, 0x5c, 0x76, 0x74, 0x62, 0x39, 0x5c, 0x33, 0xff, 0xa3, 0x81, 0xba, 0x71, 0xb3,
+ 0xac, 0x42, 0x16, 0xa8, 0x09, 0x8e, 0xe3, 0x7a, 0x80, 0x67, 0x2d, 0x8c, 0x4a, 0x0c, 0x9b, 0xe4,
+ 0x59, 0xe7, 0x4c, 0x4b, 0xa0, 0xa2, 0xcc, 0xf3, 0x4a, 0xef, 0x49, 0xa1, 0x1d, 0xc9, 0x73, 0x88,
+ 0x6a, 0x09, 0x94, 0x7a, 0x87, 0x43, 0xa5, 0xf7, 0xa5, 0xd0, 0x96, 0xe4, 0x39, 0x44, 0xb5, 0x04,
+ 0xf2, 0x70, 0x10, 0x54, 0xfa, 0x99, 0x14, 0x5a, 0x93, 0x3c, 0x87, 0xa8, 0x96, 0x42, 0x69, 0x1a,
+ 0x55, 0xba, 0x2a, 0x87, 0x48, 0xbe, 0x86, 0x48, 0x4c, 0x20, 0x3f, 0xc1, 0x71, 0xa5, 0x0f, 0xa4,
+ 0xd0, 0x1d, 0xc9, 0x73, 0x88, 0x6a, 0xd1, 0x5b, 0x18, 0x15, 0xd6, 0x82, 0x15, 0x1b, 0x52, 0x6e,
+ 0xd6, 0xb5, 0x0b, 0x2e, 0x61, 0xe8, 0x03, 0x41, 0xe9, 0x37, 0xaf, 0x19, 0x3d, 0x92, 0xd3, 0x5c,
+ 0x52, 0xd3, 0xfc, 0x48, 0x68, 0x5c, 0xd7, 0xd6, 0xa4, 0xf4, 0xbe, 0x5d, 0x1b, 0x0b, 0xb5, 0x71,
+ 0x5d, 0x1b, 0xe4, 0x74, 0xbb, 0x76, 0x4d, 0x4c, 0x6f, 0x00, 0x1a, 0x57, 0x88, 0xb6, 0xed, 0x77,
+ 0xd8, 0x56, 0x15, 0x6c, 0x4b, 0xc8, 0xc6, 0x1a, 0xff, 0x63, 0xf8, 0xa9, 0x0d, 0xd0, 0xf8, 0x43,
+ 0x24, 0x55, 0x46, 0x5e, 0x8b, 0xa4, 0xec, 0x07, 0xd0, 0xee, 0xa4, 0xb1, 0xce, 0xa9, 0x19, 0xb4,
+ 0x63, 0xf2, 0x61, 0x2b, 0x22, 0x39, 0xea, 0x20, 0x47, 0x47, 0x33, 0x34, 0x26, 0xea, 0x98, 0xbe,
+ 0x35, 0xc3, 0xe3, 0xa3, 0x19, 0x6c, 0x1c, 0xfb, 0xb9, 0x1b, 0x89, 0xdf, 0x5b, 0xc2, 0x45, 0xcb,
+ 0x5c, 0x1d, 0x6b, 0x91, 0x37, 0x43, 0x60, 0xf1, 0xff, 0x7b, 0x6a, 0x07, 0xc7, 0xf0, 0x5e, 0x56,
+ 0xf9, 0xe2, 0x5f, 0x60, 0x59, 0xe5, 0xb3, 0x13, 0xf0, 0xf5, 0x2b, 0x18, 0xf2, 0x4d, 0xa0, 0x31,
+ 0x0c, 0xf7, 0xf6, 0x27, 0x7b, 0xfb, 0xd9, 0x9e, 0x3c, 0x42, 0x00, 0x83, 0x95, 0xb3, 0x5a, 0x7f,
+ 0xfc, 0x30, 0x51, 0x90, 0x06, 0xaa, 0xb3, 0xdd, 0xac, 0xec, 0x49, 0x6f, 0xfd, 0xee, 0xcb, 0x32,
+ 0x08, 0xcb, 0x1f, 0xd8, 0x33, 0xee, 0xd3, 0xd8, 0x0c, 0xd2, 0xc8, 0x4d, 0x02, 0x93, 0xbe, 0x0f,
+ 0x1e, 0xfe, 0x6e, 0x86, 0x49, 0xe9, 0xe7, 0x89, 0x1b, 0xd1, 0x77, 0x83, 0xde, 0x16, 0xa6, 0xf8,
+ 0x9e, 0x78, 0x03, 0xfa, 0xc7, 0xfa, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x7c, 0xda, 0x44, 0x24, 0x66,
+ 0x06, 0x00, 0x00,
}
diff --git a/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test3.proto b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test3.proto
new file mode 100644
index 000000000..dbeb2b589
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/jsonpb_proto/test3.proto
@@ -0,0 +1,44 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+syntax = "proto3";
+
+option go_package = "github.com/golang/protobuf/internal/testprotos/jsonpb_proto";
+
+package jsonpb_test;
+
+message Simple3 {
+ double dub = 1;
+}
+
+message SimpleSlice3 {
+ repeated string slices = 1;
+}
+
+message SimpleMap3 {
+ map stringy = 1;
+}
+
+message SimpleNull3 {
+ Simple3 simple = 1;
+}
+
+enum Numeral {
+ UNKNOWN = 0;
+ ARABIC = 1;
+ ROMAN = 2;
+}
+
+message Mappy {
+ map nummy = 1;
+ map strry = 2;
+ map objjy = 3;
+ map buggy = 4;
+ map booly = 5;
+ map enumy = 6;
+ map s32booly = 7;
+ map s64booly = 8;
+ map u32booly = 9;
+ map u64booly = 10;
+}
diff --git a/vendor/github.com/golang/protobuf/proto/test_proto/test.pb.go b/vendor/github.com/golang/protobuf/internal/testprotos/proto2_proto/test.pb.go
similarity index 59%
rename from vendor/github.com/golang/protobuf/proto/test_proto/test.pb.go
rename to vendor/github.com/golang/protobuf/internal/testprotos/proto2_proto/test.pb.go
index 049b5dd2c..cd202f971 100644
--- a/vendor/github.com/golang/protobuf/proto/test_proto/test.pb.go
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/proto2_proto/test.pb.go
@@ -1,11 +1,13 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: test_proto/test.proto
+// source: proto2_proto/test.proto
-package test_proto // import "github.com/golang/protobuf/proto/test_proto"
+package proto2_proto
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
+import (
+ fmt "fmt"
+ proto "github.com/golang/protobuf/proto"
+ math "math"
+)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
@@ -16,7 +18,7 @@ var _ = math.Inf
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type FOO int32
@@ -27,6 +29,7 @@ const (
var FOO_name = map[int32]string{
1: "FOO1",
}
+
var FOO_value = map[string]int32{
"FOO1": 1,
}
@@ -36,9 +39,11 @@ func (x FOO) Enum() *FOO {
*p = x
return p
}
+
func (x FOO) String() string {
return proto.EnumName(FOO_name, int32(x))
}
+
func (x *FOO) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO")
if err != nil {
@@ -47,8 +52,9 @@ func (x *FOO) UnmarshalJSON(data []byte) error {
*x = FOO(value)
return nil
}
+
func (FOO) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{0}
}
// An enum, for completeness.
@@ -89,6 +95,7 @@ var GoTest_KIND_name = map[int32]string{
11: "TABLE",
12: "FUNCTION",
}
+
var GoTest_KIND_value = map[string]int32{
"VOID": 0,
"BOOL": 1,
@@ -110,9 +117,11 @@ func (x GoTest_KIND) Enum() *GoTest_KIND {
*p = x
return p
}
+
func (x GoTest_KIND) String() string {
return proto.EnumName(GoTest_KIND_name, int32(x))
}
+
func (x *GoTest_KIND) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND")
if err != nil {
@@ -121,8 +130,9 @@ func (x *GoTest_KIND) UnmarshalJSON(data []byte) error {
*x = GoTest_KIND(value)
return nil
}
+
func (GoTest_KIND) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{2, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{2, 0}
}
type MyMessage_Color int32
@@ -138,6 +148,7 @@ var MyMessage_Color_name = map[int32]string{
1: "GREEN",
2: "BLUE",
}
+
var MyMessage_Color_value = map[string]int32{
"RED": 0,
"GREEN": 1,
@@ -149,9 +160,11 @@ func (x MyMessage_Color) Enum() *MyMessage_Color {
*p = x
return p
}
+
func (x MyMessage_Color) String() string {
return proto.EnumName(MyMessage_Color_name, int32(x))
}
+
func (x *MyMessage_Color) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color")
if err != nil {
@@ -160,8 +173,9 @@ func (x *MyMessage_Color) UnmarshalJSON(data []byte) error {
*x = MyMessage_Color(value)
return nil
}
+
func (MyMessage_Color) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{13, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{13, 0}
}
type DefaultsMessage_DefaultsEnum int32
@@ -177,6 +191,7 @@ var DefaultsMessage_DefaultsEnum_name = map[int32]string{
1: "ONE",
2: "TWO",
}
+
var DefaultsMessage_DefaultsEnum_value = map[string]int32{
"ZERO": 0,
"ONE": 1,
@@ -188,9 +203,11 @@ func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum {
*p = x
return p
}
+
func (x DefaultsMessage_DefaultsEnum) String() string {
return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x))
}
+
func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum")
if err != nil {
@@ -199,8 +216,9 @@ func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error {
*x = DefaultsMessage_DefaultsEnum(value)
return nil
}
+
func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{16, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{16, 0}
}
type Defaults_Color int32
@@ -216,6 +234,7 @@ var Defaults_Color_name = map[int32]string{
1: "GREEN",
2: "BLUE",
}
+
var Defaults_Color_value = map[string]int32{
"RED": 0,
"GREEN": 1,
@@ -227,9 +246,11 @@ func (x Defaults_Color) Enum() *Defaults_Color {
*p = x
return p
}
+
func (x Defaults_Color) String() string {
return proto.EnumName(Defaults_Color_name, int32(x))
}
+
func (x *Defaults_Color) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color")
if err != nil {
@@ -238,8 +259,9 @@ func (x *Defaults_Color) UnmarshalJSON(data []byte) error {
*x = Defaults_Color(value)
return nil
}
+
func (Defaults_Color) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{21, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{20, 0}
}
type RepeatedEnum_Color int32
@@ -251,6 +273,7 @@ const (
var RepeatedEnum_Color_name = map[int32]string{
1: "RED",
}
+
var RepeatedEnum_Color_value = map[string]int32{
"RED": 1,
}
@@ -260,9 +283,11 @@ func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color {
*p = x
return p
}
+
func (x RepeatedEnum_Color) String() string {
return proto.EnumName(RepeatedEnum_Color_name, int32(x))
}
+
func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error {
value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color")
if err != nil {
@@ -271,12 +296,13 @@ func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error {
*x = RepeatedEnum_Color(value)
return nil
}
+
func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{23, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{22, 0}
}
type GoEnum struct {
- Foo *FOO `protobuf:"varint,1,req,name=foo,enum=test_proto.FOO" json:"foo,omitempty"`
+ Foo *FOO `protobuf:"varint,1,req,name=foo,enum=proto2_test.FOO" json:"foo,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -286,16 +312,17 @@ func (m *GoEnum) Reset() { *m = GoEnum{} }
func (m *GoEnum) String() string { return proto.CompactTextString(m) }
func (*GoEnum) ProtoMessage() {}
func (*GoEnum) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{0}
}
+
func (m *GoEnum) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoEnum.Unmarshal(m, b)
}
func (m *GoEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoEnum.Marshal(b, m, deterministic)
}
-func (dst *GoEnum) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoEnum.Merge(dst, src)
+func (m *GoEnum) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoEnum.Merge(m, src)
}
func (m *GoEnum) XXX_Size() int {
return xxx_messageInfo_GoEnum.Size(m)
@@ -325,16 +352,17 @@ func (m *GoTestField) Reset() { *m = GoTestField{} }
func (m *GoTestField) String() string { return proto.CompactTextString(m) }
func (*GoTestField) ProtoMessage() {}
func (*GoTestField) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{1}
+ return fileDescriptor_e5b3e7ca68f98362, []int{1}
}
+
func (m *GoTestField) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTestField.Unmarshal(m, b)
}
func (m *GoTestField) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTestField.Marshal(b, m, deterministic)
}
-func (dst *GoTestField) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTestField.Merge(dst, src)
+func (m *GoTestField) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTestField.Merge(m, src)
}
func (m *GoTestField) XXX_Size() int {
return xxx_messageInfo_GoTestField.Size(m)
@@ -361,7 +389,7 @@ func (m *GoTestField) GetType() string {
type GoTest struct {
// Some typical parameters
- Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=test_proto.GoTest_KIND" json:"Kind,omitempty"`
+ Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=proto2_test.GoTest_KIND" json:"Kind,omitempty"`
Table *string `protobuf:"bytes,2,opt,name=Table" json:"Table,omitempty"`
Param *int32 `protobuf:"varint,3,opt,name=Param" json:"Param,omitempty"`
// Required, repeated and optional foreign fields.
@@ -458,16 +486,17 @@ func (m *GoTest) Reset() { *m = GoTest{} }
func (m *GoTest) String() string { return proto.CompactTextString(m) }
func (*GoTest) ProtoMessage() {}
func (*GoTest) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{2}
+ return fileDescriptor_e5b3e7ca68f98362, []int{2}
}
+
func (m *GoTest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTest.Unmarshal(m, b)
}
func (m *GoTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTest.Marshal(b, m, deterministic)
}
-func (dst *GoTest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTest.Merge(dst, src)
+func (m *GoTest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTest.Merge(m, src)
}
func (m *GoTest) XXX_Size() int {
return xxx_messageInfo_GoTest.Size(m)
@@ -1082,16 +1111,17 @@ func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} }
func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) }
func (*GoTest_RequiredGroup) ProtoMessage() {}
func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{2, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{2, 0}
}
+
func (m *GoTest_RequiredGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTest_RequiredGroup.Unmarshal(m, b)
}
func (m *GoTest_RequiredGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTest_RequiredGroup.Marshal(b, m, deterministic)
}
-func (dst *GoTest_RequiredGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTest_RequiredGroup.Merge(dst, src)
+func (m *GoTest_RequiredGroup) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTest_RequiredGroup.Merge(m, src)
}
func (m *GoTest_RequiredGroup) XXX_Size() int {
return xxx_messageInfo_GoTest_RequiredGroup.Size(m)
@@ -1120,16 +1150,17 @@ func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} }
func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) }
func (*GoTest_RepeatedGroup) ProtoMessage() {}
func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{2, 1}
+ return fileDescriptor_e5b3e7ca68f98362, []int{2, 1}
}
+
func (m *GoTest_RepeatedGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTest_RepeatedGroup.Unmarshal(m, b)
}
func (m *GoTest_RepeatedGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTest_RepeatedGroup.Marshal(b, m, deterministic)
}
-func (dst *GoTest_RepeatedGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTest_RepeatedGroup.Merge(dst, src)
+func (m *GoTest_RepeatedGroup) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTest_RepeatedGroup.Merge(m, src)
}
func (m *GoTest_RepeatedGroup) XXX_Size() int {
return xxx_messageInfo_GoTest_RepeatedGroup.Size(m)
@@ -1158,16 +1189,17 @@ func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} }
func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) }
func (*GoTest_OptionalGroup) ProtoMessage() {}
func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{2, 2}
+ return fileDescriptor_e5b3e7ca68f98362, []int{2, 2}
}
+
func (m *GoTest_OptionalGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTest_OptionalGroup.Unmarshal(m, b)
}
func (m *GoTest_OptionalGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTest_OptionalGroup.Marshal(b, m, deterministic)
}
-func (dst *GoTest_OptionalGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTest_OptionalGroup.Merge(dst, src)
+func (m *GoTest_OptionalGroup) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTest_OptionalGroup.Merge(m, src)
}
func (m *GoTest_OptionalGroup) XXX_Size() int {
return xxx_messageInfo_GoTest_OptionalGroup.Size(m)
@@ -1197,16 +1229,17 @@ func (m *GoTestRequiredGroupField) Reset() { *m = GoTestRequiredGroupFie
func (m *GoTestRequiredGroupField) String() string { return proto.CompactTextString(m) }
func (*GoTestRequiredGroupField) ProtoMessage() {}
func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{3}
+ return fileDescriptor_e5b3e7ca68f98362, []int{3}
}
+
func (m *GoTestRequiredGroupField) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTestRequiredGroupField.Unmarshal(m, b)
}
func (m *GoTestRequiredGroupField) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTestRequiredGroupField.Marshal(b, m, deterministic)
}
-func (dst *GoTestRequiredGroupField) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTestRequiredGroupField.Merge(dst, src)
+func (m *GoTestRequiredGroupField) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTestRequiredGroupField.Merge(m, src)
}
func (m *GoTestRequiredGroupField) XXX_Size() int {
return xxx_messageInfo_GoTestRequiredGroupField.Size(m)
@@ -1235,16 +1268,17 @@ func (m *GoTestRequiredGroupField_Group) Reset() { *m = GoTestRequiredGr
func (m *GoTestRequiredGroupField_Group) String() string { return proto.CompactTextString(m) }
func (*GoTestRequiredGroupField_Group) ProtoMessage() {}
func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{3, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{3, 0}
}
+
func (m *GoTestRequiredGroupField_Group) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoTestRequiredGroupField_Group.Unmarshal(m, b)
}
func (m *GoTestRequiredGroupField_Group) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoTestRequiredGroupField_Group.Marshal(b, m, deterministic)
}
-func (dst *GoTestRequiredGroupField_Group) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoTestRequiredGroupField_Group.Merge(dst, src)
+func (m *GoTestRequiredGroupField_Group) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoTestRequiredGroupField_Group.Merge(m, src)
}
func (m *GoTestRequiredGroupField_Group) XXX_Size() int {
return xxx_messageInfo_GoTestRequiredGroupField_Group.Size(m)
@@ -1280,16 +1314,17 @@ func (m *GoSkipTest) Reset() { *m = GoSkipTest{} }
func (m *GoSkipTest) String() string { return proto.CompactTextString(m) }
func (*GoSkipTest) ProtoMessage() {}
func (*GoSkipTest) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{4}
+ return fileDescriptor_e5b3e7ca68f98362, []int{4}
}
+
func (m *GoSkipTest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoSkipTest.Unmarshal(m, b)
}
func (m *GoSkipTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoSkipTest.Marshal(b, m, deterministic)
}
-func (dst *GoSkipTest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoSkipTest.Merge(dst, src)
+func (m *GoSkipTest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoSkipTest.Merge(m, src)
}
func (m *GoSkipTest) XXX_Size() int {
return xxx_messageInfo_GoSkipTest.Size(m)
@@ -1347,16 +1382,17 @@ func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} }
func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) }
func (*GoSkipTest_SkipGroup) ProtoMessage() {}
func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{4, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{4, 0}
}
+
func (m *GoSkipTest_SkipGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GoSkipTest_SkipGroup.Unmarshal(m, b)
}
func (m *GoSkipTest_SkipGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GoSkipTest_SkipGroup.Marshal(b, m, deterministic)
}
-func (dst *GoSkipTest_SkipGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GoSkipTest_SkipGroup.Merge(dst, src)
+func (m *GoSkipTest_SkipGroup) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GoSkipTest_SkipGroup.Merge(m, src)
}
func (m *GoSkipTest_SkipGroup) XXX_Size() int {
return xxx_messageInfo_GoSkipTest_SkipGroup.Size(m)
@@ -1394,16 +1430,17 @@ func (m *NonPackedTest) Reset() { *m = NonPackedTest{} }
func (m *NonPackedTest) String() string { return proto.CompactTextString(m) }
func (*NonPackedTest) ProtoMessage() {}
func (*NonPackedTest) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{5}
+ return fileDescriptor_e5b3e7ca68f98362, []int{5}
}
+
func (m *NonPackedTest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_NonPackedTest.Unmarshal(m, b)
}
func (m *NonPackedTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_NonPackedTest.Marshal(b, m, deterministic)
}
-func (dst *NonPackedTest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_NonPackedTest.Merge(dst, src)
+func (m *NonPackedTest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_NonPackedTest.Merge(m, src)
}
func (m *NonPackedTest) XXX_Size() int {
return xxx_messageInfo_NonPackedTest.Size(m)
@@ -1432,16 +1469,17 @@ func (m *PackedTest) Reset() { *m = PackedTest{} }
func (m *PackedTest) String() string { return proto.CompactTextString(m) }
func (*PackedTest) ProtoMessage() {}
func (*PackedTest) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{6}
+ return fileDescriptor_e5b3e7ca68f98362, []int{6}
}
+
func (m *PackedTest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PackedTest.Unmarshal(m, b)
}
func (m *PackedTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PackedTest.Marshal(b, m, deterministic)
}
-func (dst *PackedTest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_PackedTest.Merge(dst, src)
+func (m *PackedTest) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PackedTest.Merge(m, src)
}
func (m *PackedTest) XXX_Size() int {
return xxx_messageInfo_PackedTest.Size(m)
@@ -1471,16 +1509,17 @@ func (m *MaxTag) Reset() { *m = MaxTag{} }
func (m *MaxTag) String() string { return proto.CompactTextString(m) }
func (*MaxTag) ProtoMessage() {}
func (*MaxTag) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{7}
+ return fileDescriptor_e5b3e7ca68f98362, []int{7}
}
+
func (m *MaxTag) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MaxTag.Unmarshal(m, b)
}
func (m *MaxTag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MaxTag.Marshal(b, m, deterministic)
}
-func (dst *MaxTag) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MaxTag.Merge(dst, src)
+func (m *MaxTag) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MaxTag.Merge(m, src)
}
func (m *MaxTag) XXX_Size() int {
return xxx_messageInfo_MaxTag.Size(m)
@@ -1510,16 +1549,17 @@ func (m *OldMessage) Reset() { *m = OldMessage{} }
func (m *OldMessage) String() string { return proto.CompactTextString(m) }
func (*OldMessage) ProtoMessage() {}
func (*OldMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{8}
+ return fileDescriptor_e5b3e7ca68f98362, []int{8}
}
+
func (m *OldMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_OldMessage.Unmarshal(m, b)
}
func (m *OldMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_OldMessage.Marshal(b, m, deterministic)
}
-func (dst *OldMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OldMessage.Merge(dst, src)
+func (m *OldMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_OldMessage.Merge(m, src)
}
func (m *OldMessage) XXX_Size() int {
return xxx_messageInfo_OldMessage.Size(m)
@@ -1555,16 +1595,17 @@ func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} }
func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) }
func (*OldMessage_Nested) ProtoMessage() {}
func (*OldMessage_Nested) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{8, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{8, 0}
}
+
func (m *OldMessage_Nested) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_OldMessage_Nested.Unmarshal(m, b)
}
func (m *OldMessage_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_OldMessage_Nested.Marshal(b, m, deterministic)
}
-func (dst *OldMessage_Nested) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OldMessage_Nested.Merge(dst, src)
+func (m *OldMessage_Nested) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_OldMessage_Nested.Merge(m, src)
}
func (m *OldMessage_Nested) XXX_Size() int {
return xxx_messageInfo_OldMessage_Nested.Size(m)
@@ -1597,16 +1638,17 @@ func (m *NewMessage) Reset() { *m = NewMessage{} }
func (m *NewMessage) String() string { return proto.CompactTextString(m) }
func (*NewMessage) ProtoMessage() {}
func (*NewMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{9}
+ return fileDescriptor_e5b3e7ca68f98362, []int{9}
}
+
func (m *NewMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_NewMessage.Unmarshal(m, b)
}
func (m *NewMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_NewMessage.Marshal(b, m, deterministic)
}
-func (dst *NewMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_NewMessage.Merge(dst, src)
+func (m *NewMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_NewMessage.Merge(m, src)
}
func (m *NewMessage) XXX_Size() int {
return xxx_messageInfo_NewMessage.Size(m)
@@ -1643,16 +1685,17 @@ func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} }
func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) }
func (*NewMessage_Nested) ProtoMessage() {}
func (*NewMessage_Nested) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{9, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{9, 0}
}
+
func (m *NewMessage_Nested) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_NewMessage_Nested.Unmarshal(m, b)
}
func (m *NewMessage_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_NewMessage_Nested.Marshal(b, m, deterministic)
}
-func (dst *NewMessage_Nested) XXX_Merge(src proto.Message) {
- xxx_messageInfo_NewMessage_Nested.Merge(dst, src)
+func (m *NewMessage_Nested) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_NewMessage_Nested.Merge(m, src)
}
func (m *NewMessage_Nested) XXX_Size() int {
return xxx_messageInfo_NewMessage_Nested.Size(m)
@@ -1690,16 +1733,17 @@ func (m *InnerMessage) Reset() { *m = InnerMessage{} }
func (m *InnerMessage) String() string { return proto.CompactTextString(m) }
func (*InnerMessage) ProtoMessage() {}
func (*InnerMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{10}
+ return fileDescriptor_e5b3e7ca68f98362, []int{10}
}
+
func (m *InnerMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_InnerMessage.Unmarshal(m, b)
}
func (m *InnerMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_InnerMessage.Marshal(b, m, deterministic)
}
-func (dst *InnerMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_InnerMessage.Merge(dst, src)
+func (m *InnerMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_InnerMessage.Merge(m, src)
}
func (m *InnerMessage) XXX_Size() int {
return xxx_messageInfo_InnerMessage.Size(m)
@@ -1748,7 +1792,7 @@ func (m *OtherMessage) Reset() { *m = OtherMessage{} }
func (m *OtherMessage) String() string { return proto.CompactTextString(m) }
func (*OtherMessage) ProtoMessage() {}
func (*OtherMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{11}
+ return fileDescriptor_e5b3e7ca68f98362, []int{11}
}
var extRange_OtherMessage = []proto.ExtensionRange{
@@ -1758,14 +1802,15 @@ var extRange_OtherMessage = []proto.ExtensionRange{
func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange {
return extRange_OtherMessage
}
+
func (m *OtherMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_OtherMessage.Unmarshal(m, b)
}
func (m *OtherMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_OtherMessage.Marshal(b, m, deterministic)
}
-func (dst *OtherMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OtherMessage.Merge(dst, src)
+func (m *OtherMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_OtherMessage.Merge(m, src)
}
func (m *OtherMessage) XXX_Size() int {
return xxx_messageInfo_OtherMessage.Size(m)
@@ -1815,16 +1860,17 @@ func (m *RequiredInnerMessage) Reset() { *m = RequiredInnerMessage{} }
func (m *RequiredInnerMessage) String() string { return proto.CompactTextString(m) }
func (*RequiredInnerMessage) ProtoMessage() {}
func (*RequiredInnerMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{12}
+ return fileDescriptor_e5b3e7ca68f98362, []int{12}
}
+
func (m *RequiredInnerMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_RequiredInnerMessage.Unmarshal(m, b)
}
func (m *RequiredInnerMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_RequiredInnerMessage.Marshal(b, m, deterministic)
}
-func (dst *RequiredInnerMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_RequiredInnerMessage.Merge(dst, src)
+func (m *RequiredInnerMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RequiredInnerMessage.Merge(m, src)
}
func (m *RequiredInnerMessage) XXX_Size() int {
return xxx_messageInfo_RequiredInnerMessage.Size(m)
@@ -1851,7 +1897,7 @@ type MyMessage struct {
Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"`
WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"`
RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"`
- Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=test_proto.MyMessage_Color" json:"bikeshed,omitempty"`
+ Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=proto2_test.MyMessage_Color" json:"bikeshed,omitempty"`
Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
// This field becomes [][]byte in the generated code.
RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"`
@@ -1866,7 +1912,7 @@ func (m *MyMessage) Reset() { *m = MyMessage{} }
func (m *MyMessage) String() string { return proto.CompactTextString(m) }
func (*MyMessage) ProtoMessage() {}
func (*MyMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{13}
+ return fileDescriptor_e5b3e7ca68f98362, []int{13}
}
var extRange_MyMessage = []proto.ExtensionRange{
@@ -1876,14 +1922,15 @@ var extRange_MyMessage = []proto.ExtensionRange{
func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange {
return extRange_MyMessage
}
+
func (m *MyMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MyMessage.Unmarshal(m, b)
}
func (m *MyMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MyMessage.Marshal(b, m, deterministic)
}
-func (dst *MyMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MyMessage.Merge(dst, src)
+func (m *MyMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MyMessage.Merge(m, src)
}
func (m *MyMessage) XXX_Size() int {
return xxx_messageInfo_MyMessage.Size(m)
@@ -1989,16 +2036,17 @@ func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} }
func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) }
func (*MyMessage_SomeGroup) ProtoMessage() {}
func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{13, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{13, 0}
}
+
func (m *MyMessage_SomeGroup) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MyMessage_SomeGroup.Unmarshal(m, b)
}
func (m *MyMessage_SomeGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MyMessage_SomeGroup.Marshal(b, m, deterministic)
}
-func (dst *MyMessage_SomeGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MyMessage_SomeGroup.Merge(dst, src)
+func (m *MyMessage_SomeGroup) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MyMessage_SomeGroup.Merge(m, src)
}
func (m *MyMessage_SomeGroup) XXX_Size() int {
return xxx_messageInfo_MyMessage_SomeGroup.Size(m)
@@ -2028,16 +2076,17 @@ func (m *Ext) Reset() { *m = Ext{} }
func (m *Ext) String() string { return proto.CompactTextString(m) }
func (*Ext) ProtoMessage() {}
func (*Ext) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{14}
+ return fileDescriptor_e5b3e7ca68f98362, []int{14}
}
+
func (m *Ext) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Ext.Unmarshal(m, b)
}
func (m *Ext) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Ext.Marshal(b, m, deterministic)
}
-func (dst *Ext) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Ext.Merge(dst, src)
+func (m *Ext) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Ext.Merge(m, src)
}
func (m *Ext) XXX_Size() int {
return xxx_messageInfo_Ext.Size(m)
@@ -2066,27 +2115,27 @@ var E_Ext_More = &proto.ExtensionDesc{
ExtendedType: (*MyMessage)(nil),
ExtensionType: (*Ext)(nil),
Field: 103,
- Name: "test_proto.Ext.more",
+ Name: "proto2_test.Ext.more",
Tag: "bytes,103,opt,name=more",
- Filename: "test_proto/test.proto",
+ Filename: "proto2_proto/test.proto",
}
var E_Ext_Text = &proto.ExtensionDesc{
ExtendedType: (*MyMessage)(nil),
ExtensionType: (*string)(nil),
Field: 104,
- Name: "test_proto.Ext.text",
+ Name: "proto2_test.Ext.text",
Tag: "bytes,104,opt,name=text",
- Filename: "test_proto/test.proto",
+ Filename: "proto2_proto/test.proto",
}
var E_Ext_Number = &proto.ExtensionDesc{
ExtendedType: (*MyMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 105,
- Name: "test_proto.Ext.number",
+ Name: "proto2_test.Ext.number",
Tag: "varint,105,opt,name=number",
- Filename: "test_proto/test.proto",
+ Filename: "proto2_proto/test.proto",
}
type ComplexExtension struct {
@@ -2102,16 +2151,17 @@ func (m *ComplexExtension) Reset() { *m = ComplexExtension{} }
func (m *ComplexExtension) String() string { return proto.CompactTextString(m) }
func (*ComplexExtension) ProtoMessage() {}
func (*ComplexExtension) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{15}
+ return fileDescriptor_e5b3e7ca68f98362, []int{15}
}
+
func (m *ComplexExtension) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ComplexExtension.Unmarshal(m, b)
}
func (m *ComplexExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ComplexExtension.Marshal(b, m, deterministic)
}
-func (dst *ComplexExtension) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ComplexExtension.Merge(dst, src)
+func (m *ComplexExtension) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ComplexExtension.Merge(m, src)
}
func (m *ComplexExtension) XXX_Size() int {
return xxx_messageInfo_ComplexExtension.Size(m)
@@ -2154,7 +2204,7 @@ func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} }
func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) }
func (*DefaultsMessage) ProtoMessage() {}
func (*DefaultsMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{16}
+ return fileDescriptor_e5b3e7ca68f98362, []int{16}
}
var extRange_DefaultsMessage = []proto.ExtensionRange{
@@ -2164,14 +2214,15 @@ var extRange_DefaultsMessage = []proto.ExtensionRange{
func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange {
return extRange_DefaultsMessage
}
+
func (m *DefaultsMessage) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_DefaultsMessage.Unmarshal(m, b)
}
func (m *DefaultsMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_DefaultsMessage.Marshal(b, m, deterministic)
}
-func (dst *DefaultsMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DefaultsMessage.Merge(dst, src)
+func (m *DefaultsMessage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_DefaultsMessage.Merge(m, src)
}
func (m *DefaultsMessage) XXX_Size() int {
return xxx_messageInfo_DefaultsMessage.Size(m)
@@ -2182,52 +2233,6 @@ func (m *DefaultsMessage) XXX_DiscardUnknown() {
var xxx_messageInfo_DefaultsMessage proto.InternalMessageInfo
-type MyMessageSet struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `protobuf_messageset:"1" json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MyMessageSet) Reset() { *m = MyMessageSet{} }
-func (m *MyMessageSet) String() string { return proto.CompactTextString(m) }
-func (*MyMessageSet) ProtoMessage() {}
-func (*MyMessageSet) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{17}
-}
-
-func (m *MyMessageSet) MarshalJSON() ([]byte, error) {
- return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions)
-}
-func (m *MyMessageSet) UnmarshalJSON(buf []byte) error {
- return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)
-}
-
-var extRange_MyMessageSet = []proto.ExtensionRange{
- {Start: 100, End: 2147483646},
-}
-
-func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MyMessageSet
-}
-func (m *MyMessageSet) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MyMessageSet.Unmarshal(m, b)
-}
-func (m *MyMessageSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MyMessageSet.Marshal(b, m, deterministic)
-}
-func (dst *MyMessageSet) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MyMessageSet.Merge(dst, src)
-}
-func (m *MyMessageSet) XXX_Size() int {
- return xxx_messageInfo_MyMessageSet.Size(m)
-}
-func (m *MyMessageSet) XXX_DiscardUnknown() {
- xxx_messageInfo_MyMessageSet.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MyMessageSet proto.InternalMessageInfo
-
type Empty struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
@@ -2238,16 +2243,17 @@ func (m *Empty) Reset() { *m = Empty{} }
func (m *Empty) String() string { return proto.CompactTextString(m) }
func (*Empty) ProtoMessage() {}
func (*Empty) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{18}
+ return fileDescriptor_e5b3e7ca68f98362, []int{17}
}
+
func (m *Empty) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Empty.Unmarshal(m, b)
}
func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Empty.Marshal(b, m, deterministic)
}
-func (dst *Empty) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Empty.Merge(dst, src)
+func (m *Empty) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Empty.Merge(m, src)
}
func (m *Empty) XXX_Size() int {
return xxx_messageInfo_Empty.Size(m)
@@ -2269,16 +2275,17 @@ func (m *MessageList) Reset() { *m = MessageList{} }
func (m *MessageList) String() string { return proto.CompactTextString(m) }
func (*MessageList) ProtoMessage() {}
func (*MessageList) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{19}
+ return fileDescriptor_e5b3e7ca68f98362, []int{18}
}
+
func (m *MessageList) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MessageList.Unmarshal(m, b)
}
func (m *MessageList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MessageList.Marshal(b, m, deterministic)
}
-func (dst *MessageList) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageList.Merge(dst, src)
+func (m *MessageList) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MessageList.Merge(m, src)
}
func (m *MessageList) XXX_Size() int {
return xxx_messageInfo_MessageList.Size(m)
@@ -2308,16 +2315,17 @@ func (m *MessageList_Message) Reset() { *m = MessageList_Message{} }
func (m *MessageList_Message) String() string { return proto.CompactTextString(m) }
func (*MessageList_Message) ProtoMessage() {}
func (*MessageList_Message) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{19, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{18, 0}
}
+
func (m *MessageList_Message) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MessageList_Message.Unmarshal(m, b)
}
func (m *MessageList_Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MessageList_Message.Marshal(b, m, deterministic)
}
-func (dst *MessageList_Message) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageList_Message.Merge(dst, src)
+func (m *MessageList_Message) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MessageList_Message.Merge(m, src)
}
func (m *MessageList_Message) XXX_Size() int {
return xxx_messageInfo_MessageList_Message.Size(m)
@@ -2354,16 +2362,17 @@ func (m *Strings) Reset() { *m = Strings{} }
func (m *Strings) String() string { return proto.CompactTextString(m) }
func (*Strings) ProtoMessage() {}
func (*Strings) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{20}
+ return fileDescriptor_e5b3e7ca68f98362, []int{19}
}
+
func (m *Strings) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Strings.Unmarshal(m, b)
}
func (m *Strings) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Strings.Marshal(b, m, deterministic)
}
-func (dst *Strings) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Strings.Merge(dst, src)
+func (m *Strings) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Strings.Merge(m, src)
}
func (m *Strings) XXX_Size() int {
return xxx_messageInfo_Strings.Size(m)
@@ -2404,7 +2413,7 @@ type Defaults struct {
F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,def=Bignose" json:"F_Bytes,omitempty"`
F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,def=-32" json:"F_Sint32,omitempty"`
F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,def=-64" json:"F_Sint64,omitempty"`
- F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=test_proto.Defaults_Color,def=1" json:"F_Enum,omitempty"`
+ F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=proto2_test.Defaults_Color,def=1" json:"F_Enum,omitempty"`
// More fields with crazy defaults.
F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=FPinf,def=inf" json:"F_Pinf,omitempty"`
F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=FNinf,def=-inf" json:"F_Ninf,omitempty"`
@@ -2422,16 +2431,17 @@ func (m *Defaults) Reset() { *m = Defaults{} }
func (m *Defaults) String() string { return proto.CompactTextString(m) }
func (*Defaults) ProtoMessage() {}
func (*Defaults) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{21}
+ return fileDescriptor_e5b3e7ca68f98362, []int{20}
}
+
func (m *Defaults) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Defaults.Unmarshal(m, b)
}
func (m *Defaults) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Defaults.Marshal(b, m, deterministic)
}
-func (dst *Defaults) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Defaults.Merge(dst, src)
+func (m *Defaults) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Defaults.Merge(m, src)
}
func (m *Defaults) XXX_Size() int {
return xxx_messageInfo_Defaults.Size(m)
@@ -2607,16 +2617,17 @@ func (m *SubDefaults) Reset() { *m = SubDefaults{} }
func (m *SubDefaults) String() string { return proto.CompactTextString(m) }
func (*SubDefaults) ProtoMessage() {}
func (*SubDefaults) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{22}
+ return fileDescriptor_e5b3e7ca68f98362, []int{21}
}
+
func (m *SubDefaults) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SubDefaults.Unmarshal(m, b)
}
func (m *SubDefaults) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SubDefaults.Marshal(b, m, deterministic)
}
-func (dst *SubDefaults) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SubDefaults.Merge(dst, src)
+func (m *SubDefaults) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SubDefaults.Merge(m, src)
}
func (m *SubDefaults) XXX_Size() int {
return xxx_messageInfo_SubDefaults.Size(m)
@@ -2637,7 +2648,7 @@ func (m *SubDefaults) GetN() int64 {
}
type RepeatedEnum struct {
- Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=test_proto.RepeatedEnum_Color" json:"color,omitempty"`
+ Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=proto2_test.RepeatedEnum_Color" json:"color,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
@@ -2647,16 +2658,17 @@ func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} }
func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) }
func (*RepeatedEnum) ProtoMessage() {}
func (*RepeatedEnum) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{23}
+ return fileDescriptor_e5b3e7ca68f98362, []int{22}
}
+
func (m *RepeatedEnum) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_RepeatedEnum.Unmarshal(m, b)
}
func (m *RepeatedEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_RepeatedEnum.Marshal(b, m, deterministic)
}
-func (dst *RepeatedEnum) XXX_Merge(src proto.Message) {
- xxx_messageInfo_RepeatedEnum.Merge(dst, src)
+func (m *RepeatedEnum) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RepeatedEnum.Merge(m, src)
}
func (m *RepeatedEnum) XXX_Size() int {
return xxx_messageInfo_RepeatedEnum.Size(m)
@@ -2691,16 +2703,17 @@ func (m *MoreRepeated) Reset() { *m = MoreRepeated{} }
func (m *MoreRepeated) String() string { return proto.CompactTextString(m) }
func (*MoreRepeated) ProtoMessage() {}
func (*MoreRepeated) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{24}
+ return fileDescriptor_e5b3e7ca68f98362, []int{23}
}
+
func (m *MoreRepeated) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MoreRepeated.Unmarshal(m, b)
}
func (m *MoreRepeated) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MoreRepeated.Marshal(b, m, deterministic)
}
-func (dst *MoreRepeated) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MoreRepeated.Merge(dst, src)
+func (m *MoreRepeated) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MoreRepeated.Merge(m, src)
}
func (m *MoreRepeated) XXX_Size() int {
return xxx_messageInfo_MoreRepeated.Size(m)
@@ -2771,16 +2784,17 @@ func (m *GroupOld) Reset() { *m = GroupOld{} }
func (m *GroupOld) String() string { return proto.CompactTextString(m) }
func (*GroupOld) ProtoMessage() {}
func (*GroupOld) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{25}
+ return fileDescriptor_e5b3e7ca68f98362, []int{24}
}
+
func (m *GroupOld) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GroupOld.Unmarshal(m, b)
}
func (m *GroupOld) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GroupOld.Marshal(b, m, deterministic)
}
-func (dst *GroupOld) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GroupOld.Merge(dst, src)
+func (m *GroupOld) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GroupOld.Merge(m, src)
}
func (m *GroupOld) XXX_Size() int {
return xxx_messageInfo_GroupOld.Size(m)
@@ -2809,16 +2823,17 @@ func (m *GroupOld_G) Reset() { *m = GroupOld_G{} }
func (m *GroupOld_G) String() string { return proto.CompactTextString(m) }
func (*GroupOld_G) ProtoMessage() {}
func (*GroupOld_G) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{25, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{24, 0}
}
+
func (m *GroupOld_G) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GroupOld_G.Unmarshal(m, b)
}
func (m *GroupOld_G) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GroupOld_G.Marshal(b, m, deterministic)
}
-func (dst *GroupOld_G) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GroupOld_G.Merge(dst, src)
+func (m *GroupOld_G) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GroupOld_G.Merge(m, src)
}
func (m *GroupOld_G) XXX_Size() int {
return xxx_messageInfo_GroupOld_G.Size(m)
@@ -2847,16 +2862,17 @@ func (m *GroupNew) Reset() { *m = GroupNew{} }
func (m *GroupNew) String() string { return proto.CompactTextString(m) }
func (*GroupNew) ProtoMessage() {}
func (*GroupNew) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{26}
+ return fileDescriptor_e5b3e7ca68f98362, []int{25}
}
+
func (m *GroupNew) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GroupNew.Unmarshal(m, b)
}
func (m *GroupNew) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GroupNew.Marshal(b, m, deterministic)
}
-func (dst *GroupNew) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GroupNew.Merge(dst, src)
+func (m *GroupNew) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GroupNew.Merge(m, src)
}
func (m *GroupNew) XXX_Size() int {
return xxx_messageInfo_GroupNew.Size(m)
@@ -2886,16 +2902,17 @@ func (m *GroupNew_G) Reset() { *m = GroupNew_G{} }
func (m *GroupNew_G) String() string { return proto.CompactTextString(m) }
func (*GroupNew_G) ProtoMessage() {}
func (*GroupNew_G) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{26, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{25, 0}
}
+
func (m *GroupNew_G) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GroupNew_G.Unmarshal(m, b)
}
func (m *GroupNew_G) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GroupNew_G.Marshal(b, m, deterministic)
}
-func (dst *GroupNew_G) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GroupNew_G.Merge(dst, src)
+func (m *GroupNew_G) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GroupNew_G.Merge(m, src)
}
func (m *GroupNew_G) XXX_Size() int {
return xxx_messageInfo_GroupNew_G.Size(m)
@@ -2932,16 +2949,17 @@ func (m *FloatingPoint) Reset() { *m = FloatingPoint{} }
func (m *FloatingPoint) String() string { return proto.CompactTextString(m) }
func (*FloatingPoint) ProtoMessage() {}
func (*FloatingPoint) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{27}
+ return fileDescriptor_e5b3e7ca68f98362, []int{26}
}
+
func (m *FloatingPoint) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_FloatingPoint.Unmarshal(m, b)
}
func (m *FloatingPoint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_FloatingPoint.Marshal(b, m, deterministic)
}
-func (dst *FloatingPoint) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FloatingPoint.Merge(dst, src)
+func (m *FloatingPoint) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_FloatingPoint.Merge(m, src)
}
func (m *FloatingPoint) XXX_Size() int {
return xxx_messageInfo_FloatingPoint.Size(m)
@@ -2980,16 +2998,17 @@ func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
func (*MessageWithMap) ProtoMessage() {}
func (*MessageWithMap) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{28}
+ return fileDescriptor_e5b3e7ca68f98362, []int{27}
}
+
func (m *MessageWithMap) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MessageWithMap.Unmarshal(m, b)
}
func (m *MessageWithMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MessageWithMap.Marshal(b, m, deterministic)
}
-func (dst *MessageWithMap) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageWithMap.Merge(dst, src)
+func (m *MessageWithMap) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MessageWithMap.Merge(m, src)
}
func (m *MessageWithMap) XXX_Size() int {
return xxx_messageInfo_MessageWithMap.Size(m)
@@ -3060,16 +3079,17 @@ func (m *Oneof) Reset() { *m = Oneof{} }
func (m *Oneof) String() string { return proto.CompactTextString(m) }
func (*Oneof) ProtoMessage() {}
func (*Oneof) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{29}
+ return fileDescriptor_e5b3e7ca68f98362, []int{28}
}
+
func (m *Oneof) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Oneof.Unmarshal(m, b)
}
func (m *Oneof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Oneof.Marshal(b, m, deterministic)
}
-func (dst *Oneof) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Oneof.Merge(dst, src)
+func (m *Oneof) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Oneof.Merge(m, src)
}
func (m *Oneof) XXX_Size() int {
return xxx_messageInfo_Oneof.Size(m)
@@ -3083,83 +3103,108 @@ var xxx_messageInfo_Oneof proto.InternalMessageInfo
type isOneof_Union interface {
isOneof_Union()
}
-type isOneof_Tormato interface {
- isOneof_Tormato()
-}
type Oneof_F_Bool struct {
F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,oneof"`
}
+
type Oneof_F_Int32 struct {
F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,oneof"`
}
+
type Oneof_F_Int64 struct {
F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,oneof"`
}
+
type Oneof_F_Fixed32 struct {
F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,oneof"`
}
+
type Oneof_F_Fixed64 struct {
F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,oneof"`
}
+
type Oneof_F_Uint32 struct {
F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,oneof"`
}
+
type Oneof_F_Uint64 struct {
F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,oneof"`
}
+
type Oneof_F_Float struct {
F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,oneof"`
}
+
type Oneof_F_Double struct {
F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,oneof"`
}
+
type Oneof_F_String struct {
F_String string `protobuf:"bytes,10,opt,name=F_String,json=FString,oneof"`
}
+
type Oneof_F_Bytes struct {
F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,oneof"`
}
+
type Oneof_F_Sint32 struct {
F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,oneof"`
}
+
type Oneof_F_Sint64 struct {
F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,oneof"`
}
+
type Oneof_F_Enum struct {
- F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=test_proto.MyMessage_Color,oneof"`
+ F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=proto2_test.MyMessage_Color,oneof"`
}
+
type Oneof_F_Message struct {
F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=FMessage,oneof"`
}
+
type Oneof_FGroup struct {
FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"`
}
+
type Oneof_F_Largest_Tag struct {
F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=FLargestTag,oneof"`
}
-type Oneof_Value struct {
- Value int32 `protobuf:"varint,100,opt,name=value,oneof"`
-}
-func (*Oneof_F_Bool) isOneof_Union() {}
-func (*Oneof_F_Int32) isOneof_Union() {}
-func (*Oneof_F_Int64) isOneof_Union() {}
-func (*Oneof_F_Fixed32) isOneof_Union() {}
-func (*Oneof_F_Fixed64) isOneof_Union() {}
-func (*Oneof_F_Uint32) isOneof_Union() {}
-func (*Oneof_F_Uint64) isOneof_Union() {}
-func (*Oneof_F_Float) isOneof_Union() {}
-func (*Oneof_F_Double) isOneof_Union() {}
-func (*Oneof_F_String) isOneof_Union() {}
-func (*Oneof_F_Bytes) isOneof_Union() {}
-func (*Oneof_F_Sint32) isOneof_Union() {}
-func (*Oneof_F_Sint64) isOneof_Union() {}
-func (*Oneof_F_Enum) isOneof_Union() {}
-func (*Oneof_F_Message) isOneof_Union() {}
-func (*Oneof_FGroup) isOneof_Union() {}
+func (*Oneof_F_Bool) isOneof_Union() {}
+
+func (*Oneof_F_Int32) isOneof_Union() {}
+
+func (*Oneof_F_Int64) isOneof_Union() {}
+
+func (*Oneof_F_Fixed32) isOneof_Union() {}
+
+func (*Oneof_F_Fixed64) isOneof_Union() {}
+
+func (*Oneof_F_Uint32) isOneof_Union() {}
+
+func (*Oneof_F_Uint64) isOneof_Union() {}
+
+func (*Oneof_F_Float) isOneof_Union() {}
+
+func (*Oneof_F_Double) isOneof_Union() {}
+
+func (*Oneof_F_String) isOneof_Union() {}
+
+func (*Oneof_F_Bytes) isOneof_Union() {}
+
+func (*Oneof_F_Sint32) isOneof_Union() {}
+
+func (*Oneof_F_Sint64) isOneof_Union() {}
+
+func (*Oneof_F_Enum) isOneof_Union() {}
+
+func (*Oneof_F_Message) isOneof_Union() {}
+
+func (*Oneof_FGroup) isOneof_Union() {}
+
func (*Oneof_F_Largest_Tag) isOneof_Union() {}
-func (*Oneof_Value) isOneof_Tormato() {}
func (m *Oneof) GetUnion() isOneof_Union {
if m != nil {
@@ -3167,12 +3212,6 @@ func (m *Oneof) GetUnion() isOneof_Union {
}
return nil
}
-func (m *Oneof) GetTormato() isOneof_Tormato {
- if m != nil {
- return m.Tormato
- }
- return nil
-}
func (m *Oneof) GetF_Bool() bool {
if x, ok := m.GetUnion().(*Oneof_F_Bool); ok {
@@ -3293,6 +3332,23 @@ func (m *Oneof) GetF_Largest_Tag() int32 {
return 0
}
+type isOneof_Tormato interface {
+ isOneof_Tormato()
+}
+
+type Oneof_Value struct {
+ Value int32 `protobuf:"varint,100,opt,name=value,oneof"`
+}
+
+func (*Oneof_Value) isOneof_Tormato() {}
+
+func (m *Oneof) GetTormato() isOneof_Tormato {
+ if m != nil {
+ return m.Tormato
+ }
+ return nil
+}
+
func (m *Oneof) GetValue() int32 {
if x, ok := m.GetTormato().(*Oneof_Value); ok {
return x.Value
@@ -3300,9 +3356,9 @@ func (m *Oneof) GetValue() int32 {
return 0
}
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{
+// XXX_OneofWrappers is for the internal use of the proto package.
+func (*Oneof) XXX_OneofWrappers() []interface{} {
+ return []interface{}{
(*Oneof_F_Bool)(nil),
(*Oneof_F_Int32)(nil),
(*Oneof_F_Int64)(nil),
@@ -3324,298 +3380,6 @@ func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error,
}
}
-func _Oneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*Oneof)
- // union
- switch x := m.Union.(type) {
- case *Oneof_F_Bool:
- t := uint64(0)
- if x.F_Bool {
- t = 1
- }
- b.EncodeVarint(1<<3 | proto.WireVarint)
- b.EncodeVarint(t)
- case *Oneof_F_Int32:
- b.EncodeVarint(2<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Int32))
- case *Oneof_F_Int64:
- b.EncodeVarint(3<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Int64))
- case *Oneof_F_Fixed32:
- b.EncodeVarint(4<<3 | proto.WireFixed32)
- b.EncodeFixed32(uint64(x.F_Fixed32))
- case *Oneof_F_Fixed64:
- b.EncodeVarint(5<<3 | proto.WireFixed64)
- b.EncodeFixed64(uint64(x.F_Fixed64))
- case *Oneof_F_Uint32:
- b.EncodeVarint(6<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Uint32))
- case *Oneof_F_Uint64:
- b.EncodeVarint(7<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Uint64))
- case *Oneof_F_Float:
- b.EncodeVarint(8<<3 | proto.WireFixed32)
- b.EncodeFixed32(uint64(math.Float32bits(x.F_Float)))
- case *Oneof_F_Double:
- b.EncodeVarint(9<<3 | proto.WireFixed64)
- b.EncodeFixed64(math.Float64bits(x.F_Double))
- case *Oneof_F_String:
- b.EncodeVarint(10<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.F_String)
- case *Oneof_F_Bytes:
- b.EncodeVarint(11<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.F_Bytes)
- case *Oneof_F_Sint32:
- b.EncodeVarint(12<<3 | proto.WireVarint)
- b.EncodeZigzag32(uint64(x.F_Sint32))
- case *Oneof_F_Sint64:
- b.EncodeVarint(13<<3 | proto.WireVarint)
- b.EncodeZigzag64(uint64(x.F_Sint64))
- case *Oneof_F_Enum:
- b.EncodeVarint(14<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Enum))
- case *Oneof_F_Message:
- b.EncodeVarint(15<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.F_Message); err != nil {
- return err
- }
- case *Oneof_FGroup:
- b.EncodeVarint(16<<3 | proto.WireStartGroup)
- if err := b.Marshal(x.FGroup); err != nil {
- return err
- }
- b.EncodeVarint(16<<3 | proto.WireEndGroup)
- case *Oneof_F_Largest_Tag:
- b.EncodeVarint(536870911<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Largest_Tag))
- case nil:
- default:
- return fmt.Errorf("Oneof.Union has unexpected type %T", x)
- }
- // tormato
- switch x := m.Tormato.(type) {
- case *Oneof_Value:
- b.EncodeVarint(100<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Value))
- case nil:
- default:
- return fmt.Errorf("Oneof.Tormato has unexpected type %T", x)
- }
- return nil
-}
-
-func _Oneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*Oneof)
- switch tag {
- case 1: // union.F_Bool
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Bool{x != 0}
- return true, err
- case 2: // union.F_Int32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Int32{int32(x)}
- return true, err
- case 3: // union.F_Int64
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Int64{int64(x)}
- return true, err
- case 4: // union.F_Fixed32
- if wire != proto.WireFixed32 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed32()
- m.Union = &Oneof_F_Fixed32{uint32(x)}
- return true, err
- case 5: // union.F_Fixed64
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Oneof_F_Fixed64{x}
- return true, err
- case 6: // union.F_Uint32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Uint32{uint32(x)}
- return true, err
- case 7: // union.F_Uint64
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Uint64{x}
- return true, err
- case 8: // union.F_Float
- if wire != proto.WireFixed32 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed32()
- m.Union = &Oneof_F_Float{math.Float32frombits(uint32(x))}
- return true, err
- case 9: // union.F_Double
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Oneof_F_Double{math.Float64frombits(x)}
- return true, err
- case 10: // union.F_String
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &Oneof_F_String{x}
- return true, err
- case 11: // union.F_Bytes
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Union = &Oneof_F_Bytes{x}
- return true, err
- case 12: // union.F_Sint32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeZigzag32()
- m.Union = &Oneof_F_Sint32{int32(x)}
- return true, err
- case 13: // union.F_Sint64
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeZigzag64()
- m.Union = &Oneof_F_Sint64{int64(x)}
- return true, err
- case 14: // union.F_Enum
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Enum{MyMessage_Color(x)}
- return true, err
- case 15: // union.F_Message
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(GoTestField)
- err := b.DecodeMessage(msg)
- m.Union = &Oneof_F_Message{msg}
- return true, err
- case 16: // union.f_group
- if wire != proto.WireStartGroup {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Oneof_F_Group)
- err := b.DecodeGroup(msg)
- m.Union = &Oneof_FGroup{msg}
- return true, err
- case 536870911: // union.F_Largest_Tag
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Largest_Tag{int32(x)}
- return true, err
- case 100: // tormato.value
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Tormato = &Oneof_Value{int32(x)}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _Oneof_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*Oneof)
- // union
- switch x := m.Union.(type) {
- case *Oneof_F_Bool:
- n += 1 // tag and wire
- n += 1
- case *Oneof_F_Int32:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.F_Int32))
- case *Oneof_F_Int64:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.F_Int64))
- case *Oneof_F_Fixed32:
- n += 1 // tag and wire
- n += 4
- case *Oneof_F_Fixed64:
- n += 1 // tag and wire
- n += 8
- case *Oneof_F_Uint32:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.F_Uint32))
- case *Oneof_F_Uint64:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.F_Uint64))
- case *Oneof_F_Float:
- n += 1 // tag and wire
- n += 4
- case *Oneof_F_Double:
- n += 1 // tag and wire
- n += 8
- case *Oneof_F_String:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.F_String)))
- n += len(x.F_String)
- case *Oneof_F_Bytes:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.F_Bytes)))
- n += len(x.F_Bytes)
- case *Oneof_F_Sint32:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64((uint32(x.F_Sint32) << 1) ^ uint32((int32(x.F_Sint32) >> 31))))
- case *Oneof_F_Sint64:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(uint64(x.F_Sint64<<1) ^ uint64((int64(x.F_Sint64) >> 63))))
- case *Oneof_F_Enum:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.F_Enum))
- case *Oneof_F_Message:
- s := proto.Size(x.F_Message)
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case *Oneof_FGroup:
- n += 2 // tag and wire
- n += proto.Size(x.FGroup)
- n += 2 // tag and wire
- case *Oneof_F_Largest_Tag:
- n += 10 // tag and wire
- n += proto.SizeVarint(uint64(x.F_Largest_Tag))
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- // tormato
- switch x := m.Tormato.(type) {
- case *Oneof_Value:
- n += 2 // tag and wire
- n += proto.SizeVarint(uint64(x.Value))
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
type Oneof_F_Group struct {
X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
@@ -3627,16 +3391,17 @@ func (m *Oneof_F_Group) Reset() { *m = Oneof_F_Group{} }
func (m *Oneof_F_Group) String() string { return proto.CompactTextString(m) }
func (*Oneof_F_Group) ProtoMessage() {}
func (*Oneof_F_Group) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{29, 0}
+ return fileDescriptor_e5b3e7ca68f98362, []int{28, 0}
}
+
func (m *Oneof_F_Group) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Oneof_F_Group.Unmarshal(m, b)
}
func (m *Oneof_F_Group) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Oneof_F_Group.Marshal(b, m, deterministic)
}
-func (dst *Oneof_F_Group) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Oneof_F_Group.Merge(dst, src)
+func (m *Oneof_F_Group) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Oneof_F_Group.Merge(m, src)
}
func (m *Oneof_F_Group) XXX_Size() int {
return xxx_messageInfo_Oneof_F_Group.Size(m)
@@ -3675,16 +3440,17 @@ func (m *Communique) Reset() { *m = Communique{} }
func (m *Communique) String() string { return proto.CompactTextString(m) }
func (*Communique) ProtoMessage() {}
func (*Communique) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_74787bfc6550f8a7, []int{30}
+ return fileDescriptor_e5b3e7ca68f98362, []int{29}
}
+
func (m *Communique) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Communique.Unmarshal(m, b)
}
func (m *Communique) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Communique.Marshal(b, m, deterministic)
}
-func (dst *Communique) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Communique.Merge(dst, src)
+func (m *Communique) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Communique.Merge(m, src)
}
func (m *Communique) XXX_Size() int {
return xxx_messageInfo_Communique.Size(m)
@@ -3695,6 +3461,13 @@ func (m *Communique) XXX_DiscardUnknown() {
var xxx_messageInfo_Communique proto.InternalMessageInfo
+func (m *Communique) GetMakeMeCry() bool {
+ if m != nil && m.MakeMeCry != nil {
+ return *m.MakeMeCry
+ }
+ return false
+}
+
type isCommunique_Union interface {
isCommunique_Union()
}
@@ -3702,28 +3475,38 @@ type isCommunique_Union interface {
type Communique_Number struct {
Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
}
+
type Communique_Name struct {
Name string `protobuf:"bytes,6,opt,name=name,oneof"`
}
+
type Communique_Data struct {
Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
}
+
type Communique_TempC struct {
TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
}
+
type Communique_Col struct {
- Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=test_proto.MyMessage_Color,oneof"`
+ Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=proto2_test.MyMessage_Color,oneof"`
}
+
type Communique_Msg struct {
Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"`
}
func (*Communique_Number) isCommunique_Union() {}
-func (*Communique_Name) isCommunique_Union() {}
-func (*Communique_Data) isCommunique_Union() {}
-func (*Communique_TempC) isCommunique_Union() {}
-func (*Communique_Col) isCommunique_Union() {}
-func (*Communique_Msg) isCommunique_Union() {}
+
+func (*Communique_Name) isCommunique_Union() {}
+
+func (*Communique_Data) isCommunique_Union() {}
+
+func (*Communique_TempC) isCommunique_Union() {}
+
+func (*Communique_Col) isCommunique_Union() {}
+
+func (*Communique_Msg) isCommunique_Union() {}
func (m *Communique) GetUnion() isCommunique_Union {
if m != nil {
@@ -3732,13 +3515,6 @@ func (m *Communique) GetUnion() isCommunique_Union {
return nil
}
-func (m *Communique) GetMakeMeCry() bool {
- if m != nil && m.MakeMeCry != nil {
- return *m.MakeMeCry
- }
- return false
-}
-
func (m *Communique) GetNumber() int32 {
if x, ok := m.GetUnion().(*Communique_Number); ok {
return x.Number
@@ -3781,9 +3557,9 @@ func (m *Communique) GetMsg() *Strings {
return nil
}
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{
+// XXX_OneofWrappers is for the internal use of the proto package.
+func (*Communique) XXX_OneofWrappers() []interface{} {
+ return []interface{}{
(*Communique_Number)(nil),
(*Communique_Name)(nil),
(*Communique_Data)(nil),
@@ -3793,944 +3569,478 @@ func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) er
}
}
-func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*Communique)
- // union
- switch x := m.Union.(type) {
- case *Communique_Number:
- b.EncodeVarint(5<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Number))
- case *Communique_Name:
- b.EncodeVarint(6<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.Name)
- case *Communique_Data:
- b.EncodeVarint(7<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.Data)
- case *Communique_TempC:
- b.EncodeVarint(8<<3 | proto.WireFixed64)
- b.EncodeFixed64(math.Float64bits(x.TempC))
- case *Communique_Col:
- b.EncodeVarint(9<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Col))
- case *Communique_Msg:
- b.EncodeVarint(10<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.Msg); err != nil {
- return err
- }
- case nil:
- default:
- return fmt.Errorf("Communique.Union has unexpected type %T", x)
+type TestUTF8 struct {
+ Scalar *string `protobuf:"bytes,1,opt,name=scalar" json:"scalar,omitempty"`
+ Vector []string `protobuf:"bytes,2,rep,name=vector" json:"vector,omitempty"`
+ // Types that are valid to be assigned to Oneof:
+ // *TestUTF8_Field
+ Oneof isTestUTF8_Oneof `protobuf_oneof:"oneof"`
+ MapKey map[string]int64 `protobuf:"bytes,4,rep,name=map_key,json=mapKey" json:"map_key,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ MapValue map[int64]string `protobuf:"bytes,5,rep,name=map_value,json=mapValue" json:"map_value,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *TestUTF8) Reset() { *m = TestUTF8{} }
+func (m *TestUTF8) String() string { return proto.CompactTextString(m) }
+func (*TestUTF8) ProtoMessage() {}
+func (*TestUTF8) Descriptor() ([]byte, []int) {
+ return fileDescriptor_e5b3e7ca68f98362, []int{30}
+}
+
+func (m *TestUTF8) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_TestUTF8.Unmarshal(m, b)
+}
+func (m *TestUTF8) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_TestUTF8.Marshal(b, m, deterministic)
+}
+func (m *TestUTF8) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_TestUTF8.Merge(m, src)
+}
+func (m *TestUTF8) XXX_Size() int {
+ return xxx_messageInfo_TestUTF8.Size(m)
+}
+func (m *TestUTF8) XXX_DiscardUnknown() {
+ xxx_messageInfo_TestUTF8.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_TestUTF8 proto.InternalMessageInfo
+
+func (m *TestUTF8) GetScalar() string {
+ if m != nil && m.Scalar != nil {
+ return *m.Scalar
+ }
+ return ""
+}
+
+func (m *TestUTF8) GetVector() []string {
+ if m != nil {
+ return m.Vector
+ }
+ return nil
+}
+
+type isTestUTF8_Oneof interface {
+ isTestUTF8_Oneof()
+}
+
+type TestUTF8_Field struct {
+ Field string `protobuf:"bytes,3,opt,name=field,oneof"`
+}
+
+func (*TestUTF8_Field) isTestUTF8_Oneof() {}
+
+func (m *TestUTF8) GetOneof() isTestUTF8_Oneof {
+ if m != nil {
+ return m.Oneof
+ }
+ return nil
+}
+
+func (m *TestUTF8) GetField() string {
+ if x, ok := m.GetOneof().(*TestUTF8_Field); ok {
+ return x.Field
+ }
+ return ""
+}
+
+func (m *TestUTF8) GetMapKey() map[string]int64 {
+ if m != nil {
+ return m.MapKey
+ }
+ return nil
+}
+
+func (m *TestUTF8) GetMapValue() map[int64]string {
+ if m != nil {
+ return m.MapValue
}
return nil
}
-func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*Communique)
- switch tag {
- case 5: // union.number
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Number{int32(x)}
- return true, err
- case 6: // union.name
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &Communique_Name{x}
- return true, err
- case 7: // union.data
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Union = &Communique_Data{x}
- return true, err
- case 8: // union.temp_c
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Communique_TempC{math.Float64frombits(x)}
- return true, err
- case 9: // union.col
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Col{MyMessage_Color(x)}
- return true, err
- case 10: // union.msg
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Strings)
- err := b.DecodeMessage(msg)
- m.Union = &Communique_Msg{msg}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _Communique_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*Communique)
- // union
- switch x := m.Union.(type) {
- case *Communique_Number:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.Number))
- case *Communique_Name:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Name)))
- n += len(x.Name)
- case *Communique_Data:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Data)))
- n += len(x.Data)
- case *Communique_TempC:
- n += 1 // tag and wire
- n += 8
- case *Communique_Col:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.Col))
- case *Communique_Msg:
- s := proto.Size(x.Msg)
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
+// XXX_OneofWrappers is for the internal use of the proto package.
+func (*TestUTF8) XXX_OneofWrappers() []interface{} {
+ return []interface{}{
+ (*TestUTF8_Field)(nil),
+ }
}
var E_Greeting = &proto.ExtensionDesc{
ExtendedType: (*MyMessage)(nil),
ExtensionType: ([]string)(nil),
Field: 106,
- Name: "test_proto.greeting",
+ Name: "proto2_test.greeting",
Tag: "bytes,106,rep,name=greeting",
- Filename: "test_proto/test.proto",
+ Filename: "proto2_proto/test.proto",
}
var E_Complex = &proto.ExtensionDesc{
ExtendedType: (*OtherMessage)(nil),
ExtensionType: (*ComplexExtension)(nil),
Field: 200,
- Name: "test_proto.complex",
+ Name: "proto2_test.complex",
Tag: "bytes,200,opt,name=complex",
- Filename: "test_proto/test.proto",
+ Filename: "proto2_proto/test.proto",
}
var E_RComplex = &proto.ExtensionDesc{
ExtendedType: (*OtherMessage)(nil),
ExtensionType: ([]*ComplexExtension)(nil),
Field: 201,
- Name: "test_proto.r_complex",
- Tag: "bytes,201,rep,name=r_complex,json=rComplex",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.r_complex",
+ Tag: "bytes,201,rep,name=r_complex",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultDouble = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*float64)(nil),
Field: 101,
- Name: "test_proto.no_default_double",
- Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_double",
+ Tag: "fixed64,101,opt,name=no_default_double",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultFloat = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*float32)(nil),
Field: 102,
- Name: "test_proto.no_default_float",
- Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_float",
+ Tag: "fixed32,102,opt,name=no_default_float",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultInt32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 103,
- Name: "test_proto.no_default_int32",
- Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_int32",
+ Tag: "varint,103,opt,name=no_default_int32",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultInt64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int64)(nil),
Field: 104,
- Name: "test_proto.no_default_int64",
- Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_int64",
+ Tag: "varint,104,opt,name=no_default_int64",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultUint32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint32)(nil),
Field: 105,
- Name: "test_proto.no_default_uint32",
- Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_uint32",
+ Tag: "varint,105,opt,name=no_default_uint32",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultUint64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint64)(nil),
Field: 106,
- Name: "test_proto.no_default_uint64",
- Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_uint64",
+ Tag: "varint,106,opt,name=no_default_uint64",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultSint32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 107,
- Name: "test_proto.no_default_sint32",
- Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_sint32",
+ Tag: "zigzag32,107,opt,name=no_default_sint32",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultSint64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int64)(nil),
Field: 108,
- Name: "test_proto.no_default_sint64",
- Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_sint64",
+ Tag: "zigzag64,108,opt,name=no_default_sint64",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultFixed32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint32)(nil),
Field: 109,
- Name: "test_proto.no_default_fixed32",
- Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_fixed32",
+ Tag: "fixed32,109,opt,name=no_default_fixed32",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultFixed64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint64)(nil),
Field: 110,
- Name: "test_proto.no_default_fixed64",
- Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_fixed64",
+ Tag: "fixed64,110,opt,name=no_default_fixed64",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultSfixed32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 111,
- Name: "test_proto.no_default_sfixed32",
- Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_sfixed32",
+ Tag: "fixed32,111,opt,name=no_default_sfixed32",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultSfixed64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int64)(nil),
Field: 112,
- Name: "test_proto.no_default_sfixed64",
- Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_sfixed64",
+ Tag: "fixed64,112,opt,name=no_default_sfixed64",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultBool = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*bool)(nil),
Field: 113,
- Name: "test_proto.no_default_bool",
- Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_bool",
+ Tag: "varint,113,opt,name=no_default_bool",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultString = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*string)(nil),
Field: 114,
- Name: "test_proto.no_default_string",
- Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_string",
+ Tag: "bytes,114,opt,name=no_default_string",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultBytes = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: ([]byte)(nil),
Field: 115,
- Name: "test_proto.no_default_bytes",
- Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_bytes",
+ Tag: "bytes,115,opt,name=no_default_bytes",
+ Filename: "proto2_proto/test.proto",
}
var E_NoDefaultEnum = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
Field: 116,
- Name: "test_proto.no_default_enum",
- Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=test_proto.DefaultsMessage_DefaultsEnum",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.no_default_enum",
+ Tag: "varint,116,opt,name=no_default_enum,enum=proto2_test.DefaultsMessage_DefaultsEnum",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultDouble = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*float64)(nil),
Field: 201,
- Name: "test_proto.default_double",
- Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_double",
+ Tag: "fixed64,201,opt,name=default_double,def=3.1415",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultFloat = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*float32)(nil),
Field: 202,
- Name: "test_proto.default_float",
- Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_float",
+ Tag: "fixed32,202,opt,name=default_float,def=3.14",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultInt32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 203,
- Name: "test_proto.default_int32",
- Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_int32",
+ Tag: "varint,203,opt,name=default_int32,def=42",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultInt64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int64)(nil),
Field: 204,
- Name: "test_proto.default_int64",
- Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_int64",
+ Tag: "varint,204,opt,name=default_int64,def=43",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultUint32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint32)(nil),
Field: 205,
- Name: "test_proto.default_uint32",
- Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_uint32",
+ Tag: "varint,205,opt,name=default_uint32,def=44",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultUint64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint64)(nil),
Field: 206,
- Name: "test_proto.default_uint64",
- Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_uint64",
+ Tag: "varint,206,opt,name=default_uint64,def=45",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultSint32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 207,
- Name: "test_proto.default_sint32",
- Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_sint32",
+ Tag: "zigzag32,207,opt,name=default_sint32,def=46",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultSint64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int64)(nil),
Field: 208,
- Name: "test_proto.default_sint64",
- Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_sint64",
+ Tag: "zigzag64,208,opt,name=default_sint64,def=47",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultFixed32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint32)(nil),
Field: 209,
- Name: "test_proto.default_fixed32",
- Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_fixed32",
+ Tag: "fixed32,209,opt,name=default_fixed32,def=48",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultFixed64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*uint64)(nil),
Field: 210,
- Name: "test_proto.default_fixed64",
- Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_fixed64",
+ Tag: "fixed64,210,opt,name=default_fixed64,def=49",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultSfixed32 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int32)(nil),
Field: 211,
- Name: "test_proto.default_sfixed32",
- Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_sfixed32",
+ Tag: "fixed32,211,opt,name=default_sfixed32,def=50",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultSfixed64 = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*int64)(nil),
Field: 212,
- Name: "test_proto.default_sfixed64",
- Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_sfixed64",
+ Tag: "fixed64,212,opt,name=default_sfixed64,def=51",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultBool = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*bool)(nil),
Field: 213,
- Name: "test_proto.default_bool",
- Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_bool",
+ Tag: "varint,213,opt,name=default_bool,def=1",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultString = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*string)(nil),
Field: 214,
- Name: "test_proto.default_string",
- Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string,def=foo",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_string",
+ Tag: "bytes,214,opt,name=default_string,def=Hello, string,def=foo",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultBytes = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: ([]byte)(nil),
Field: 215,
- Name: "test_proto.default_bytes",
- Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_bytes",
+ Tag: "bytes,215,opt,name=default_bytes,def=Hello, bytes",
+ Filename: "proto2_proto/test.proto",
}
var E_DefaultEnum = &proto.ExtensionDesc{
ExtendedType: (*DefaultsMessage)(nil),
ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
Field: 216,
- Name: "test_proto.default_enum",
- Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=test_proto.DefaultsMessage_DefaultsEnum,def=1",
- Filename: "test_proto/test.proto",
-}
-
-var E_X201 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 201,
- Name: "test_proto.x201",
- Tag: "bytes,201,opt,name=x201",
- Filename: "test_proto/test.proto",
-}
-
-var E_X202 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 202,
- Name: "test_proto.x202",
- Tag: "bytes,202,opt,name=x202",
- Filename: "test_proto/test.proto",
-}
-
-var E_X203 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 203,
- Name: "test_proto.x203",
- Tag: "bytes,203,opt,name=x203",
- Filename: "test_proto/test.proto",
-}
-
-var E_X204 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 204,
- Name: "test_proto.x204",
- Tag: "bytes,204,opt,name=x204",
- Filename: "test_proto/test.proto",
-}
-
-var E_X205 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 205,
- Name: "test_proto.x205",
- Tag: "bytes,205,opt,name=x205",
- Filename: "test_proto/test.proto",
-}
-
-var E_X206 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 206,
- Name: "test_proto.x206",
- Tag: "bytes,206,opt,name=x206",
- Filename: "test_proto/test.proto",
-}
-
-var E_X207 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 207,
- Name: "test_proto.x207",
- Tag: "bytes,207,opt,name=x207",
- Filename: "test_proto/test.proto",
-}
-
-var E_X208 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 208,
- Name: "test_proto.x208",
- Tag: "bytes,208,opt,name=x208",
- Filename: "test_proto/test.proto",
-}
-
-var E_X209 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 209,
- Name: "test_proto.x209",
- Tag: "bytes,209,opt,name=x209",
- Filename: "test_proto/test.proto",
-}
-
-var E_X210 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 210,
- Name: "test_proto.x210",
- Tag: "bytes,210,opt,name=x210",
- Filename: "test_proto/test.proto",
-}
-
-var E_X211 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 211,
- Name: "test_proto.x211",
- Tag: "bytes,211,opt,name=x211",
- Filename: "test_proto/test.proto",
-}
-
-var E_X212 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 212,
- Name: "test_proto.x212",
- Tag: "bytes,212,opt,name=x212",
- Filename: "test_proto/test.proto",
-}
-
-var E_X213 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 213,
- Name: "test_proto.x213",
- Tag: "bytes,213,opt,name=x213",
- Filename: "test_proto/test.proto",
-}
-
-var E_X214 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 214,
- Name: "test_proto.x214",
- Tag: "bytes,214,opt,name=x214",
- Filename: "test_proto/test.proto",
-}
-
-var E_X215 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 215,
- Name: "test_proto.x215",
- Tag: "bytes,215,opt,name=x215",
- Filename: "test_proto/test.proto",
-}
-
-var E_X216 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 216,
- Name: "test_proto.x216",
- Tag: "bytes,216,opt,name=x216",
- Filename: "test_proto/test.proto",
-}
-
-var E_X217 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 217,
- Name: "test_proto.x217",
- Tag: "bytes,217,opt,name=x217",
- Filename: "test_proto/test.proto",
-}
-
-var E_X218 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 218,
- Name: "test_proto.x218",
- Tag: "bytes,218,opt,name=x218",
- Filename: "test_proto/test.proto",
-}
-
-var E_X219 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 219,
- Name: "test_proto.x219",
- Tag: "bytes,219,opt,name=x219",
- Filename: "test_proto/test.proto",
-}
-
-var E_X220 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 220,
- Name: "test_proto.x220",
- Tag: "bytes,220,opt,name=x220",
- Filename: "test_proto/test.proto",
-}
-
-var E_X221 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 221,
- Name: "test_proto.x221",
- Tag: "bytes,221,opt,name=x221",
- Filename: "test_proto/test.proto",
-}
-
-var E_X222 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 222,
- Name: "test_proto.x222",
- Tag: "bytes,222,opt,name=x222",
- Filename: "test_proto/test.proto",
-}
-
-var E_X223 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 223,
- Name: "test_proto.x223",
- Tag: "bytes,223,opt,name=x223",
- Filename: "test_proto/test.proto",
-}
-
-var E_X224 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 224,
- Name: "test_proto.x224",
- Tag: "bytes,224,opt,name=x224",
- Filename: "test_proto/test.proto",
-}
-
-var E_X225 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 225,
- Name: "test_proto.x225",
- Tag: "bytes,225,opt,name=x225",
- Filename: "test_proto/test.proto",
-}
-
-var E_X226 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 226,
- Name: "test_proto.x226",
- Tag: "bytes,226,opt,name=x226",
- Filename: "test_proto/test.proto",
-}
-
-var E_X227 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 227,
- Name: "test_proto.x227",
- Tag: "bytes,227,opt,name=x227",
- Filename: "test_proto/test.proto",
-}
-
-var E_X228 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 228,
- Name: "test_proto.x228",
- Tag: "bytes,228,opt,name=x228",
- Filename: "test_proto/test.proto",
-}
-
-var E_X229 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 229,
- Name: "test_proto.x229",
- Tag: "bytes,229,opt,name=x229",
- Filename: "test_proto/test.proto",
-}
-
-var E_X230 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 230,
- Name: "test_proto.x230",
- Tag: "bytes,230,opt,name=x230",
- Filename: "test_proto/test.proto",
-}
-
-var E_X231 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 231,
- Name: "test_proto.x231",
- Tag: "bytes,231,opt,name=x231",
- Filename: "test_proto/test.proto",
-}
-
-var E_X232 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 232,
- Name: "test_proto.x232",
- Tag: "bytes,232,opt,name=x232",
- Filename: "test_proto/test.proto",
-}
-
-var E_X233 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 233,
- Name: "test_proto.x233",
- Tag: "bytes,233,opt,name=x233",
- Filename: "test_proto/test.proto",
-}
-
-var E_X234 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 234,
- Name: "test_proto.x234",
- Tag: "bytes,234,opt,name=x234",
- Filename: "test_proto/test.proto",
-}
-
-var E_X235 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 235,
- Name: "test_proto.x235",
- Tag: "bytes,235,opt,name=x235",
- Filename: "test_proto/test.proto",
-}
-
-var E_X236 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 236,
- Name: "test_proto.x236",
- Tag: "bytes,236,opt,name=x236",
- Filename: "test_proto/test.proto",
-}
-
-var E_X237 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 237,
- Name: "test_proto.x237",
- Tag: "bytes,237,opt,name=x237",
- Filename: "test_proto/test.proto",
-}
-
-var E_X238 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 238,
- Name: "test_proto.x238",
- Tag: "bytes,238,opt,name=x238",
- Filename: "test_proto/test.proto",
-}
-
-var E_X239 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 239,
- Name: "test_proto.x239",
- Tag: "bytes,239,opt,name=x239",
- Filename: "test_proto/test.proto",
-}
-
-var E_X240 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 240,
- Name: "test_proto.x240",
- Tag: "bytes,240,opt,name=x240",
- Filename: "test_proto/test.proto",
-}
-
-var E_X241 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 241,
- Name: "test_proto.x241",
- Tag: "bytes,241,opt,name=x241",
- Filename: "test_proto/test.proto",
-}
-
-var E_X242 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 242,
- Name: "test_proto.x242",
- Tag: "bytes,242,opt,name=x242",
- Filename: "test_proto/test.proto",
-}
-
-var E_X243 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 243,
- Name: "test_proto.x243",
- Tag: "bytes,243,opt,name=x243",
- Filename: "test_proto/test.proto",
-}
-
-var E_X244 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 244,
- Name: "test_proto.x244",
- Tag: "bytes,244,opt,name=x244",
- Filename: "test_proto/test.proto",
-}
-
-var E_X245 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 245,
- Name: "test_proto.x245",
- Tag: "bytes,245,opt,name=x245",
- Filename: "test_proto/test.proto",
-}
-
-var E_X246 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 246,
- Name: "test_proto.x246",
- Tag: "bytes,246,opt,name=x246",
- Filename: "test_proto/test.proto",
-}
-
-var E_X247 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 247,
- Name: "test_proto.x247",
- Tag: "bytes,247,opt,name=x247",
- Filename: "test_proto/test.proto",
-}
-
-var E_X248 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 248,
- Name: "test_proto.x248",
- Tag: "bytes,248,opt,name=x248",
- Filename: "test_proto/test.proto",
-}
-
-var E_X249 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 249,
- Name: "test_proto.x249",
- Tag: "bytes,249,opt,name=x249",
- Filename: "test_proto/test.proto",
-}
-
-var E_X250 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 250,
- Name: "test_proto.x250",
- Tag: "bytes,250,opt,name=x250",
- Filename: "test_proto/test.proto",
+ Name: "proto2_test.default_enum",
+ Tag: "varint,216,opt,name=default_enum,enum=proto2_test.DefaultsMessage_DefaultsEnum,def=1",
+ Filename: "proto2_proto/test.proto",
}
func init() {
- proto.RegisterType((*GoEnum)(nil), "test_proto.GoEnum")
- proto.RegisterType((*GoTestField)(nil), "test_proto.GoTestField")
- proto.RegisterType((*GoTest)(nil), "test_proto.GoTest")
- proto.RegisterType((*GoTest_RequiredGroup)(nil), "test_proto.GoTest.RequiredGroup")
- proto.RegisterType((*GoTest_RepeatedGroup)(nil), "test_proto.GoTest.RepeatedGroup")
- proto.RegisterType((*GoTest_OptionalGroup)(nil), "test_proto.GoTest.OptionalGroup")
- proto.RegisterType((*GoTestRequiredGroupField)(nil), "test_proto.GoTestRequiredGroupField")
- proto.RegisterType((*GoTestRequiredGroupField_Group)(nil), "test_proto.GoTestRequiredGroupField.Group")
- proto.RegisterType((*GoSkipTest)(nil), "test_proto.GoSkipTest")
- proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "test_proto.GoSkipTest.SkipGroup")
- proto.RegisterType((*NonPackedTest)(nil), "test_proto.NonPackedTest")
- proto.RegisterType((*PackedTest)(nil), "test_proto.PackedTest")
- proto.RegisterType((*MaxTag)(nil), "test_proto.MaxTag")
- proto.RegisterType((*OldMessage)(nil), "test_proto.OldMessage")
- proto.RegisterType((*OldMessage_Nested)(nil), "test_proto.OldMessage.Nested")
- proto.RegisterType((*NewMessage)(nil), "test_proto.NewMessage")
- proto.RegisterType((*NewMessage_Nested)(nil), "test_proto.NewMessage.Nested")
- proto.RegisterType((*InnerMessage)(nil), "test_proto.InnerMessage")
- proto.RegisterType((*OtherMessage)(nil), "test_proto.OtherMessage")
- proto.RegisterType((*RequiredInnerMessage)(nil), "test_proto.RequiredInnerMessage")
- proto.RegisterType((*MyMessage)(nil), "test_proto.MyMessage")
- proto.RegisterType((*MyMessage_SomeGroup)(nil), "test_proto.MyMessage.SomeGroup")
- proto.RegisterType((*Ext)(nil), "test_proto.Ext")
- proto.RegisterMapType((map[int32]int32)(nil), "test_proto.Ext.MapFieldEntry")
- proto.RegisterType((*ComplexExtension)(nil), "test_proto.ComplexExtension")
- proto.RegisterType((*DefaultsMessage)(nil), "test_proto.DefaultsMessage")
- proto.RegisterType((*MyMessageSet)(nil), "test_proto.MyMessageSet")
- proto.RegisterType((*Empty)(nil), "test_proto.Empty")
- proto.RegisterType((*MessageList)(nil), "test_proto.MessageList")
- proto.RegisterType((*MessageList_Message)(nil), "test_proto.MessageList.Message")
- proto.RegisterType((*Strings)(nil), "test_proto.Strings")
- proto.RegisterType((*Defaults)(nil), "test_proto.Defaults")
- proto.RegisterType((*SubDefaults)(nil), "test_proto.SubDefaults")
- proto.RegisterType((*RepeatedEnum)(nil), "test_proto.RepeatedEnum")
- proto.RegisterType((*MoreRepeated)(nil), "test_proto.MoreRepeated")
- proto.RegisterType((*GroupOld)(nil), "test_proto.GroupOld")
- proto.RegisterType((*GroupOld_G)(nil), "test_proto.GroupOld.G")
- proto.RegisterType((*GroupNew)(nil), "test_proto.GroupNew")
- proto.RegisterType((*GroupNew_G)(nil), "test_proto.GroupNew.G")
- proto.RegisterType((*FloatingPoint)(nil), "test_proto.FloatingPoint")
- proto.RegisterType((*MessageWithMap)(nil), "test_proto.MessageWithMap")
- proto.RegisterMapType((map[bool][]byte)(nil), "test_proto.MessageWithMap.ByteMappingEntry")
- proto.RegisterMapType((map[int64]*FloatingPoint)(nil), "test_proto.MessageWithMap.MsgMappingEntry")
- proto.RegisterMapType((map[int32]string)(nil), "test_proto.MessageWithMap.NameMappingEntry")
- proto.RegisterMapType((map[string]string)(nil), "test_proto.MessageWithMap.StrToStrEntry")
- proto.RegisterType((*Oneof)(nil), "test_proto.Oneof")
- proto.RegisterType((*Oneof_F_Group)(nil), "test_proto.Oneof.F_Group")
- proto.RegisterType((*Communique)(nil), "test_proto.Communique")
- proto.RegisterEnum("test_proto.FOO", FOO_name, FOO_value)
- proto.RegisterEnum("test_proto.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value)
- proto.RegisterEnum("test_proto.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value)
- proto.RegisterEnum("test_proto.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value)
- proto.RegisterEnum("test_proto.Defaults_Color", Defaults_Color_name, Defaults_Color_value)
- proto.RegisterEnum("test_proto.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value)
+ proto.RegisterEnum("proto2_test.FOO", FOO_name, FOO_value)
+ proto.RegisterEnum("proto2_test.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value)
+ proto.RegisterEnum("proto2_test.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value)
+ proto.RegisterEnum("proto2_test.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value)
+ proto.RegisterEnum("proto2_test.Defaults_Color", Defaults_Color_name, Defaults_Color_value)
+ proto.RegisterEnum("proto2_test.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value)
+ proto.RegisterType((*GoEnum)(nil), "proto2_test.GoEnum")
+ proto.RegisterType((*GoTestField)(nil), "proto2_test.GoTestField")
+ proto.RegisterType((*GoTest)(nil), "proto2_test.GoTest")
+ proto.RegisterType((*GoTest_RequiredGroup)(nil), "proto2_test.GoTest.RequiredGroup")
+ proto.RegisterType((*GoTest_RepeatedGroup)(nil), "proto2_test.GoTest.RepeatedGroup")
+ proto.RegisterType((*GoTest_OptionalGroup)(nil), "proto2_test.GoTest.OptionalGroup")
+ proto.RegisterType((*GoTestRequiredGroupField)(nil), "proto2_test.GoTestRequiredGroupField")
+ proto.RegisterType((*GoTestRequiredGroupField_Group)(nil), "proto2_test.GoTestRequiredGroupField.Group")
+ proto.RegisterType((*GoSkipTest)(nil), "proto2_test.GoSkipTest")
+ proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "proto2_test.GoSkipTest.SkipGroup")
+ proto.RegisterType((*NonPackedTest)(nil), "proto2_test.NonPackedTest")
+ proto.RegisterType((*PackedTest)(nil), "proto2_test.PackedTest")
+ proto.RegisterType((*MaxTag)(nil), "proto2_test.MaxTag")
+ proto.RegisterType((*OldMessage)(nil), "proto2_test.OldMessage")
+ proto.RegisterType((*OldMessage_Nested)(nil), "proto2_test.OldMessage.Nested")
+ proto.RegisterType((*NewMessage)(nil), "proto2_test.NewMessage")
+ proto.RegisterType((*NewMessage_Nested)(nil), "proto2_test.NewMessage.Nested")
+ proto.RegisterType((*InnerMessage)(nil), "proto2_test.InnerMessage")
+ proto.RegisterType((*OtherMessage)(nil), "proto2_test.OtherMessage")
+ proto.RegisterType((*RequiredInnerMessage)(nil), "proto2_test.RequiredInnerMessage")
+ proto.RegisterType((*MyMessage)(nil), "proto2_test.MyMessage")
+ proto.RegisterType((*MyMessage_SomeGroup)(nil), "proto2_test.MyMessage.SomeGroup")
proto.RegisterExtension(E_Ext_More)
proto.RegisterExtension(E_Ext_Text)
proto.RegisterExtension(E_Ext_Number)
+ proto.RegisterType((*Ext)(nil), "proto2_test.Ext")
+ proto.RegisterMapType((map[int32]int32)(nil), "proto2_test.Ext.MapFieldEntry")
+ proto.RegisterType((*ComplexExtension)(nil), "proto2_test.ComplexExtension")
+ proto.RegisterType((*DefaultsMessage)(nil), "proto2_test.DefaultsMessage")
+ proto.RegisterType((*Empty)(nil), "proto2_test.Empty")
+ proto.RegisterType((*MessageList)(nil), "proto2_test.MessageList")
+ proto.RegisterType((*MessageList_Message)(nil), "proto2_test.MessageList.Message")
+ proto.RegisterType((*Strings)(nil), "proto2_test.Strings")
+ proto.RegisterType((*Defaults)(nil), "proto2_test.Defaults")
+ proto.RegisterType((*SubDefaults)(nil), "proto2_test.SubDefaults")
+ proto.RegisterType((*RepeatedEnum)(nil), "proto2_test.RepeatedEnum")
+ proto.RegisterType((*MoreRepeated)(nil), "proto2_test.MoreRepeated")
+ proto.RegisterType((*GroupOld)(nil), "proto2_test.GroupOld")
+ proto.RegisterType((*GroupOld_G)(nil), "proto2_test.GroupOld.G")
+ proto.RegisterType((*GroupNew)(nil), "proto2_test.GroupNew")
+ proto.RegisterType((*GroupNew_G)(nil), "proto2_test.GroupNew.G")
+ proto.RegisterType((*FloatingPoint)(nil), "proto2_test.FloatingPoint")
+ proto.RegisterType((*MessageWithMap)(nil), "proto2_test.MessageWithMap")
+ proto.RegisterMapType((map[bool][]byte)(nil), "proto2_test.MessageWithMap.ByteMappingEntry")
+ proto.RegisterMapType((map[int64]*FloatingPoint)(nil), "proto2_test.MessageWithMap.MsgMappingEntry")
+ proto.RegisterMapType((map[int32]string)(nil), "proto2_test.MessageWithMap.NameMappingEntry")
+ proto.RegisterMapType((map[string]string)(nil), "proto2_test.MessageWithMap.StrToStrEntry")
+ proto.RegisterType((*Oneof)(nil), "proto2_test.Oneof")
+ proto.RegisterType((*Oneof_F_Group)(nil), "proto2_test.Oneof.F_Group")
+ proto.RegisterType((*Communique)(nil), "proto2_test.Communique")
+ proto.RegisterType((*TestUTF8)(nil), "proto2_test.TestUTF8")
+ proto.RegisterMapType((map[string]int64)(nil), "proto2_test.TestUTF8.MapKeyEntry")
+ proto.RegisterMapType((map[int64]string)(nil), "proto2_test.TestUTF8.MapValueEntry")
proto.RegisterExtension(E_Greeting)
proto.RegisterExtension(E_Complex)
proto.RegisterExtension(E_RComplex)
@@ -4766,353 +4076,281 @@ func init() {
proto.RegisterExtension(E_DefaultString)
proto.RegisterExtension(E_DefaultBytes)
proto.RegisterExtension(E_DefaultEnum)
- proto.RegisterExtension(E_X201)
- proto.RegisterExtension(E_X202)
- proto.RegisterExtension(E_X203)
- proto.RegisterExtension(E_X204)
- proto.RegisterExtension(E_X205)
- proto.RegisterExtension(E_X206)
- proto.RegisterExtension(E_X207)
- proto.RegisterExtension(E_X208)
- proto.RegisterExtension(E_X209)
- proto.RegisterExtension(E_X210)
- proto.RegisterExtension(E_X211)
- proto.RegisterExtension(E_X212)
- proto.RegisterExtension(E_X213)
- proto.RegisterExtension(E_X214)
- proto.RegisterExtension(E_X215)
- proto.RegisterExtension(E_X216)
- proto.RegisterExtension(E_X217)
- proto.RegisterExtension(E_X218)
- proto.RegisterExtension(E_X219)
- proto.RegisterExtension(E_X220)
- proto.RegisterExtension(E_X221)
- proto.RegisterExtension(E_X222)
- proto.RegisterExtension(E_X223)
- proto.RegisterExtension(E_X224)
- proto.RegisterExtension(E_X225)
- proto.RegisterExtension(E_X226)
- proto.RegisterExtension(E_X227)
- proto.RegisterExtension(E_X228)
- proto.RegisterExtension(E_X229)
- proto.RegisterExtension(E_X230)
- proto.RegisterExtension(E_X231)
- proto.RegisterExtension(E_X232)
- proto.RegisterExtension(E_X233)
- proto.RegisterExtension(E_X234)
- proto.RegisterExtension(E_X235)
- proto.RegisterExtension(E_X236)
- proto.RegisterExtension(E_X237)
- proto.RegisterExtension(E_X238)
- proto.RegisterExtension(E_X239)
- proto.RegisterExtension(E_X240)
- proto.RegisterExtension(E_X241)
- proto.RegisterExtension(E_X242)
- proto.RegisterExtension(E_X243)
- proto.RegisterExtension(E_X244)
- proto.RegisterExtension(E_X245)
- proto.RegisterExtension(E_X246)
- proto.RegisterExtension(E_X247)
- proto.RegisterExtension(E_X248)
- proto.RegisterExtension(E_X249)
- proto.RegisterExtension(E_X250)
-}
-
-func init() { proto.RegisterFile("test_proto/test.proto", fileDescriptor_test_74787bfc6550f8a7) }
-
-var fileDescriptor_test_74787bfc6550f8a7 = []byte{
- // 4680 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5b, 0xd9, 0x73, 0x1b, 0x47,
- 0x7a, 0xd7, 0x0c, 0xee, 0x0f, 0x20, 0x31, 0x6c, 0xd1, 0x12, 0x44, 0x59, 0xd2, 0x08, 0x6b, 0xaf,
- 0x61, 0xc9, 0xa2, 0x48, 0x60, 0x08, 0x49, 0x70, 0xec, 0xb2, 0x0e, 0x82, 0x62, 0x49, 0x24, 0xe4,
- 0x21, 0x6d, 0x67, 0x95, 0x07, 0x14, 0x48, 0x0c, 0x40, 0xac, 0x80, 0x19, 0x18, 0x18, 0x44, 0x64,
- 0x52, 0xa9, 0xf2, 0x63, 0xaa, 0xf2, 0x94, 0x4d, 0x52, 0x95, 0xf7, 0xbc, 0xe4, 0x25, 0xd7, 0x43,
- 0xf2, 0x37, 0xc4, 0xd7, 0x5e, 0xde, 0x2b, 0xc9, 0x26, 0x9b, 0xfb, 0xce, 0xe6, 0xde, 0x23, 0x2f,
- 0x4e, 0xf5, 0xd7, 0x3d, 0x33, 0x3d, 0x03, 0xa8, 0x45, 0x3e, 0x71, 0xa6, 0xfb, 0xf7, 0xfd, 0xfa,
- 0xfa, 0xf5, 0xf7, 0xf5, 0xd7, 0x18, 0xc2, 0x0b, 0xae, 0x35, 0x76, 0x9b, 0xc3, 0x91, 0xe3, 0x3a,
- 0xd7, 0xe9, 0xe3, 0x32, 0x3e, 0x12, 0x08, 0x8a, 0x8b, 0x57, 0x21, 0xb9, 0xe1, 0xac, 0xdb, 0x93,
- 0x01, 0xb9, 0x0c, 0xb1, 0x8e, 0xe3, 0x14, 0x14, 0x5d, 0x2d, 0xcd, 0x97, 0xf3, 0xcb, 0x01, 0x66,
- 0xb9, 0xde, 0x68, 0x98, 0xb4, 0xae, 0x78, 0x03, 0xb2, 0x1b, 0xce, 0xae, 0x35, 0x76, 0xeb, 0x3d,
- 0xab, 0xdf, 0x26, 0x8b, 0x90, 0x78, 0xd8, 0xda, 0xb3, 0xfa, 0x68, 0x93, 0x31, 0xd9, 0x0b, 0x21,
- 0x10, 0xdf, 0x3d, 0x1a, 0x5a, 0x05, 0x15, 0x0b, 0xf1, 0xb9, 0xf8, 0x87, 0x45, 0xda, 0x0c, 0xb5,
- 0x24, 0x57, 0x21, 0xfe, 0xa0, 0x67, 0xb7, 0x79, 0x3b, 0x67, 0xc5, 0x76, 0x18, 0x62, 0xf9, 0xc1,
- 0xe6, 0xf6, 0x3d, 0x13, 0x41, 0xb4, 0x85, 0xdd, 0xd6, 0x5e, 0x9f, 0x92, 0x29, 0xb4, 0x05, 0x7c,
- 0xa1, 0xa5, 0x8f, 0x5a, 0xa3, 0xd6, 0xa0, 0x10, 0xd3, 0x95, 0x52, 0xc2, 0x64, 0x2f, 0xe4, 0x0d,
- 0x98, 0x33, 0xad, 0xf7, 0x27, 0xbd, 0x91, 0xd5, 0xc6, 0xee, 0x15, 0xe2, 0xba, 0x5a, 0xca, 0xce,
- 0x6a, 0x01, 0xab, 0xcd, 0x30, 0x9a, 0x99, 0x0f, 0xad, 0x96, 0xeb, 0x99, 0x27, 0xf4, 0xd8, 0x73,
- 0xcc, 0x05, 0x34, 0x35, 0x6f, 0x0c, 0xdd, 0x9e, 0x63, 0xb7, 0xfa, 0xcc, 0x3c, 0xa9, 0x2b, 0x52,
- 0xf3, 0x10, 0x9a, 0x7c, 0x11, 0xf2, 0xf5, 0xe6, 0x1d, 0xc7, 0xe9, 0x37, 0x47, 0xbc, 0x57, 0x05,
- 0xd0, 0xd5, 0x52, 0xda, 0x9c, 0xab, 0xd3, 0x52, 0xaf, 0xab, 0xa4, 0x04, 0x5a, 0xbd, 0xb9, 0x69,
- 0xbb, 0x95, 0x72, 0x00, 0xcc, 0xea, 0x6a, 0x29, 0x61, 0xce, 0xd7, 0xb1, 0x78, 0x0a, 0x59, 0x35,
- 0x02, 0x64, 0x4e, 0x57, 0x4b, 0x31, 0x86, 0xac, 0x1a, 0x3e, 0xf2, 0x35, 0x20, 0xf5, 0x66, 0xbd,
- 0x77, 0x68, 0xb5, 0x45, 0xd6, 0x39, 0x5d, 0x2d, 0xa5, 0x4c, 0xad, 0xce, 0x2b, 0x66, 0xa0, 0x45,
- 0xe6, 0x79, 0x5d, 0x2d, 0x25, 0x3d, 0xb4, 0xc0, 0x7d, 0x05, 0x16, 0xea, 0xcd, 0x77, 0x7a, 0xe1,
- 0x0e, 0xe7, 0x75, 0xb5, 0x34, 0x67, 0xe6, 0xeb, 0xac, 0x7c, 0x1a, 0x2b, 0x12, 0x6b, 0xba, 0x5a,
- 0x8a, 0x73, 0xac, 0xc0, 0x8b, 0xa3, 0xab, 0xf7, 0x9d, 0x96, 0x1b, 0x40, 0x17, 0x74, 0xb5, 0xa4,
- 0x9a, 0xf3, 0x75, 0x2c, 0x0e, 0xb3, 0xde, 0x73, 0x26, 0x7b, 0x7d, 0x2b, 0x80, 0x12, 0x5d, 0x2d,
- 0x29, 0x66, 0xbe, 0xce, 0xca, 0xc3, 0xd8, 0x1d, 0x77, 0xd4, 0xb3, 0xbb, 0x01, 0xf6, 0x34, 0xea,
- 0x38, 0x5f, 0x67, 0xe5, 0xe1, 0x1e, 0xdc, 0x39, 0x72, 0xad, 0x71, 0x00, 0xb5, 0x74, 0xb5, 0x94,
- 0x33, 0xe7, 0xeb, 0x58, 0x1c, 0x61, 0x8d, 0xcc, 0x41, 0x47, 0x57, 0x4b, 0x0b, 0x94, 0x75, 0xc6,
- 0x1c, 0xec, 0x44, 0xe6, 0xa0, 0xab, 0xab, 0x25, 0xc2, 0xb1, 0xc2, 0x1c, 0x2c, 0xc3, 0xe9, 0x7a,
- 0x73, 0xa7, 0x13, 0x5d, 0xb8, 0x03, 0x5d, 0x2d, 0xe5, 0xcd, 0x85, 0xba, 0x57, 0x33, 0x0b, 0x2f,
- 0xb2, 0xf7, 0x74, 0xb5, 0xa4, 0xf9, 0x78, 0x81, 0x5f, 0xd4, 0x24, 0x93, 0x7a, 0x61, 0x51, 0x8f,
- 0x09, 0x9a, 0x64, 0x85, 0x61, 0x4d, 0x72, 0xe0, 0x0b, 0x7a, 0x4c, 0xd4, 0x64, 0x04, 0x89, 0xcd,
- 0x73, 0xe4, 0x19, 0x3d, 0x26, 0x6a, 0x92, 0x23, 0x23, 0x9a, 0xe4, 0xd8, 0xb3, 0x7a, 0x2c, 0xac,
- 0xc9, 0x29, 0xb4, 0xc8, 0x5c, 0xd0, 0x63, 0x61, 0x4d, 0x72, 0x74, 0x58, 0x93, 0x1c, 0x7c, 0x4e,
- 0x8f, 0x85, 0x34, 0x19, 0xc5, 0x8a, 0xc4, 0x4b, 0x7a, 0x2c, 0xa4, 0x49, 0x71, 0x74, 0x9e, 0x26,
- 0x39, 0xf4, 0xbc, 0x1e, 0x13, 0x35, 0x29, 0xb2, 0xfa, 0x9a, 0xe4, 0xd0, 0x17, 0xf5, 0x58, 0x48,
- 0x93, 0x22, 0xd6, 0xd7, 0x24, 0xc7, 0x5e, 0xd0, 0x63, 0x21, 0x4d, 0x72, 0xec, 0xab, 0xa2, 0x26,
- 0x39, 0xf4, 0x43, 0x45, 0x8f, 0x89, 0xa2, 0xe4, 0xd0, 0xab, 0x21, 0x51, 0x72, 0xec, 0x47, 0x14,
- 0x2b, 0xaa, 0x32, 0x0a, 0x16, 0x67, 0xe1, 0x63, 0x0a, 0x16, 0x65, 0xc9, 0xc1, 0xd7, 0x23, 0xb2,
- 0xe4, 0xf0, 0x4f, 0x28, 0x3c, 0xac, 0xcb, 0x69, 0x03, 0x91, 0xff, 0x53, 0x6a, 0x10, 0x16, 0x26,
- 0x37, 0x08, 0x84, 0xe9, 0x70, 0x27, 0x5a, 0xb8, 0xa8, 0x2b, 0xbe, 0x30, 0x3d, 0xcf, 0x2a, 0x0a,
- 0xd3, 0x07, 0x5e, 0xc2, 0x90, 0xc1, 0x85, 0x39, 0x85, 0xac, 0x1a, 0x01, 0x52, 0xd7, 0x95, 0x40,
- 0x98, 0x3e, 0x32, 0x24, 0x4c, 0x1f, 0x7b, 0x59, 0x57, 0x44, 0x61, 0xce, 0x40, 0x8b, 0xcc, 0x45,
- 0x5d, 0x11, 0x85, 0xe9, 0xa3, 0x45, 0x61, 0xfa, 0xe0, 0x2f, 0xe8, 0x8a, 0x20, 0xcc, 0x69, 0xac,
- 0x48, 0xfc, 0x92, 0xae, 0x08, 0xc2, 0x0c, 0x8f, 0x8e, 0x09, 0xd3, 0x87, 0xbe, 0xac, 0x2b, 0x81,
- 0x30, 0xc3, 0xac, 0x5c, 0x98, 0x3e, 0xf4, 0x8b, 0xba, 0x22, 0x08, 0x33, 0x8c, 0xe5, 0xc2, 0xf4,
- 0xb1, 0xaf, 0x60, 0x9c, 0xf6, 0x84, 0xe9, 0x63, 0x05, 0x61, 0xfa, 0xd0, 0xdf, 0xa1, 0x31, 0xdd,
- 0x17, 0xa6, 0x0f, 0x15, 0x85, 0xe9, 0x63, 0x7f, 0x97, 0x62, 0x03, 0x61, 0x4e, 0x83, 0xc5, 0x59,
- 0xf8, 0x3d, 0x0a, 0x0e, 0x84, 0xe9, 0x83, 0xc3, 0xc2, 0xf4, 0xe1, 0xbf, 0x4f, 0xe1, 0xa2, 0x30,
- 0x67, 0x19, 0x88, 0xfc, 0x7f, 0x40, 0x0d, 0x44, 0x61, 0xfa, 0x06, 0xcb, 0x38, 0x4c, 0x2a, 0xcc,
- 0xb6, 0xd5, 0x69, 0x4d, 0xfa, 0x54, 0xc6, 0x25, 0xaa, 0xcc, 0x5a, 0xdc, 0x1d, 0x4d, 0x2c, 0x3a,
- 0x56, 0xc7, 0xe9, 0xdf, 0xf3, 0xea, 0xc8, 0x32, 0xed, 0x3e, 0x13, 0x68, 0x60, 0xf0, 0x2a, 0x55,
- 0x68, 0x4d, 0xad, 0x94, 0xcd, 0x3c, 0x53, 0xe9, 0x34, 0xbe, 0x6a, 0x08, 0xf8, 0x2b, 0x54, 0xa7,
- 0x35, 0xb5, 0x6a, 0x30, 0x7c, 0xd5, 0x08, 0xf0, 0x15, 0x3a, 0x00, 0x4f, 0xac, 0x81, 0xc5, 0x55,
- 0xaa, 0xd6, 0x5a, 0xac, 0x52, 0x5e, 0x31, 0x17, 0x3c, 0xc9, 0xce, 0x32, 0x0a, 0x35, 0xf3, 0x1a,
- 0x15, 0x6d, 0x2d, 0x56, 0x35, 0x7c, 0x23, 0xb1, 0xa5, 0x32, 0x15, 0x3a, 0x97, 0x6e, 0x60, 0x73,
- 0x8d, 0x6a, 0xb7, 0x16, 0xaf, 0x94, 0x57, 0x56, 0x4c, 0x8d, 0x2b, 0x78, 0x86, 0x4d, 0xa8, 0x9d,
- 0x65, 0xaa, 0xe1, 0x5a, 0xbc, 0x6a, 0xf8, 0x36, 0xe1, 0x76, 0x16, 0x3c, 0x29, 0x07, 0x26, 0xd7,
- 0xa9, 0x96, 0x6b, 0xc9, 0xca, 0xaa, 0xb1, 0xba, 0x76, 0xcb, 0xcc, 0x33, 0x4d, 0x07, 0x36, 0x06,
- 0x6d, 0x87, 0x8b, 0x3a, 0x30, 0x5a, 0xa1, 0xaa, 0xae, 0x25, 0xcb, 0x37, 0x56, 0x6f, 0x96, 0x6f,
- 0x9a, 0x1a, 0x57, 0x77, 0x60, 0xf5, 0x26, 0xb5, 0xe2, 0xf2, 0x0e, 0xac, 0x56, 0xa9, 0xbe, 0x6b,
- 0xda, 0x81, 0xd5, 0xef, 0x3b, 0xaf, 0xe9, 0xc5, 0xa7, 0xce, 0xa8, 0xdf, 0xbe, 0x5c, 0x04, 0x53,
- 0xe3, 0x8a, 0x17, 0x5b, 0x5d, 0xf0, 0x24, 0x1f, 0x98, 0xff, 0x2a, 0x3d, 0xb1, 0xe6, 0x6a, 0xa9,
- 0x3b, 0xbd, 0xae, 0xed, 0x8c, 0x2d, 0x33, 0xcf, 0xc4, 0x1f, 0x99, 0x93, 0x9d, 0xe8, 0x3c, 0x7e,
- 0x85, 0x9a, 0x2d, 0xd4, 0x62, 0xd7, 0x2a, 0x65, 0xda, 0xd2, 0xac, 0x79, 0xdc, 0x89, 0xce, 0xe3,
- 0xaf, 0x51, 0x1b, 0x52, 0x8b, 0x5d, 0xab, 0x1a, 0xdc, 0x46, 0x9c, 0xc7, 0x2a, 0x2c, 0x0a, 0x7b,
- 0x21, 0xb0, 0xfa, 0x75, 0x6a, 0x95, 0x67, 0x2d, 0x11, 0x7f, 0x47, 0xcc, 0xb4, 0x0b, 0xb5, 0xf6,
- 0x1b, 0xd4, 0x4e, 0x63, 0xad, 0x11, 0x7f, 0x63, 0x04, 0x76, 0x37, 0xe0, 0x4c, 0xe4, 0x2c, 0xd1,
- 0x1c, 0xb6, 0xf6, 0x9f, 0x58, 0xed, 0x42, 0x99, 0x1e, 0x29, 0xee, 0xa8, 0x9a, 0x62, 0x9e, 0x0e,
- 0x1d, 0x2b, 0x1e, 0x61, 0x35, 0xb9, 0x05, 0x67, 0xa3, 0x87, 0x0b, 0xcf, 0xb2, 0x42, 0xcf, 0x18,
- 0x68, 0xb9, 0x18, 0x3e, 0x67, 0x44, 0x4c, 0x85, 0xa0, 0xe2, 0x99, 0x1a, 0xf4, 0xd0, 0x11, 0x98,
- 0x06, 0xb1, 0x85, 0x9b, 0xbe, 0x01, 0xe7, 0xa6, 0x8f, 0x1f, 0x9e, 0xf1, 0x1a, 0x3d, 0x85, 0xa0,
- 0xf1, 0x99, 0xe8, 0x49, 0x64, 0xca, 0x7c, 0x46, 0xdb, 0x55, 0x7a, 0x2c, 0x11, 0xcd, 0xa7, 0x5a,
- 0x7f, 0x1d, 0x0a, 0x53, 0x07, 0x14, 0xcf, 0xfa, 0x06, 0x3d, 0xa7, 0xa0, 0xf5, 0x0b, 0x91, 0xb3,
- 0x4a, 0xd4, 0x78, 0x46, 0xd3, 0x37, 0xe9, 0xc1, 0x45, 0x30, 0x9e, 0x6a, 0x19, 0xa7, 0x2c, 0x7c,
- 0x84, 0xf1, 0x6c, 0x6f, 0xd1, 0x93, 0x0c, 0x9f, 0xb2, 0xd0, 0x69, 0x46, 0x6c, 0x37, 0x72, 0xa6,
- 0xf1, 0x6c, 0x6b, 0xf4, 0x68, 0xc3, 0xdb, 0x0d, 0x1f, 0x6f, 0xb8, 0xf1, 0xcf, 0x50, 0xe3, 0x9d,
- 0xd9, 0x23, 0xfe, 0x51, 0x8c, 0x1e, 0x4a, 0xb8, 0xf5, 0xce, 0xac, 0x21, 0xfb, 0xd6, 0x33, 0x86,
- 0xfc, 0x63, 0x6a, 0x4d, 0x04, 0xeb, 0xa9, 0x31, 0xbf, 0x05, 0x4b, 0x33, 0xce, 0x2b, 0x9e, 0xfd,
- 0x4f, 0xa8, 0x7d, 0x1e, 0xed, 0xcf, 0x4e, 0x1d, 0x5d, 0xa6, 0x19, 0x66, 0xf4, 0xe0, 0xa7, 0x94,
- 0x41, 0x0b, 0x31, 0x4c, 0xf5, 0xa1, 0x0e, 0x73, 0xde, 0x79, 0xbc, 0x3b, 0x72, 0x26, 0xc3, 0x42,
- 0x5d, 0x57, 0x4b, 0x50, 0xd6, 0x67, 0x64, 0xc7, 0xde, 0xf1, 0x7c, 0x83, 0xe2, 0xcc, 0xb0, 0x19,
- 0xe3, 0x61, 0xcc, 0x8c, 0xe7, 0x91, 0x1e, 0x7b, 0x26, 0x0f, 0xc3, 0xf9, 0x3c, 0x82, 0x19, 0xe5,
- 0xf1, 0xc2, 0x1d, 0xe3, 0x79, 0xac, 0x2b, 0xcf, 0xe0, 0xf1, 0x82, 0x1f, 0xe7, 0x09, 0x99, 0x2d,
- 0xad, 0x05, 0x39, 0x39, 0xd6, 0x93, 0x97, 0xa2, 0x49, 0xfa, 0x06, 0x66, 0x57, 0xe1, 0x42, 0x66,
- 0x26, 0x74, 0x6f, 0xda, 0xec, 0xed, 0x67, 0x98, 0x85, 0x7a, 0x33, 0x6d, 0xf6, 0x73, 0x33, 0xcc,
- 0x8a, 0xbf, 0xa9, 0x40, 0xfc, 0xc1, 0xe6, 0xf6, 0x3d, 0x92, 0x86, 0xf8, 0xbb, 0x8d, 0xcd, 0x7b,
- 0xda, 0x29, 0xfa, 0x74, 0xa7, 0xd1, 0x78, 0xa8, 0x29, 0x24, 0x03, 0x89, 0x3b, 0x5f, 0xda, 0x5d,
- 0xdf, 0xd1, 0x54, 0x92, 0x87, 0x6c, 0x7d, 0x73, 0x7b, 0x63, 0xdd, 0x7c, 0x64, 0x6e, 0x6e, 0xef,
- 0x6a, 0x31, 0x5a, 0x57, 0x7f, 0xd8, 0xb8, 0xbd, 0xab, 0xc5, 0x49, 0x0a, 0x62, 0xb4, 0x2c, 0x41,
- 0x00, 0x92, 0x3b, 0xbb, 0xe6, 0xe6, 0xf6, 0x86, 0x96, 0xa4, 0x2c, 0xbb, 0x9b, 0x5b, 0xeb, 0x5a,
- 0x8a, 0x22, 0x77, 0xdf, 0x79, 0xf4, 0x70, 0x5d, 0x4b, 0xd3, 0xc7, 0xdb, 0xa6, 0x79, 0xfb, 0x4b,
- 0x5a, 0x86, 0x1a, 0x6d, 0xdd, 0x7e, 0xa4, 0x01, 0x56, 0xdf, 0xbe, 0xf3, 0x70, 0x5d, 0xcb, 0x92,
- 0x1c, 0xa4, 0xeb, 0xef, 0x6c, 0xdf, 0xdd, 0xdd, 0x6c, 0x6c, 0x6b, 0xb9, 0xe2, 0x2f, 0x42, 0x81,
- 0x4d, 0x73, 0x68, 0x16, 0xd9, 0x95, 0xc1, 0x5b, 0x90, 0x60, 0x6b, 0xa3, 0xa0, 0x56, 0xae, 0x4c,
- 0xaf, 0xcd, 0xb4, 0xd1, 0x32, 0x5b, 0x25, 0x66, 0xb8, 0x74, 0x01, 0x12, 0x6c, 0x9e, 0x16, 0x21,
- 0xc1, 0xe6, 0x47, 0xc5, 0xab, 0x04, 0xf6, 0x52, 0xfc, 0x2d, 0x15, 0x60, 0xc3, 0xd9, 0x79, 0xd2,
- 0x1b, 0xe2, 0xc5, 0xcd, 0x05, 0x80, 0xf1, 0x93, 0xde, 0xb0, 0x89, 0x3b, 0x90, 0x5f, 0x3a, 0x64,
- 0x68, 0x09, 0xfa, 0x5e, 0x72, 0x19, 0x72, 0x58, 0xcd, 0xb7, 0x08, 0xde, 0x35, 0xa4, 0xcc, 0x2c,
- 0x2d, 0xe3, 0x4e, 0x32, 0x0c, 0xa9, 0x1a, 0x78, 0xc5, 0x90, 0x14, 0x20, 0x55, 0x83, 0x5c, 0x02,
- 0x7c, 0x6d, 0x8e, 0x31, 0x9a, 0xe2, 0xb5, 0x42, 0xc6, 0xc4, 0x76, 0x59, 0x7c, 0x25, 0x6f, 0x02,
- 0xb6, 0xc9, 0x46, 0x9e, 0x9f, 0xb5, 0x4b, 0xbc, 0x0e, 0x2f, 0xd3, 0x07, 0x36, 0xde, 0xc0, 0x64,
- 0xa9, 0x01, 0x19, 0xbf, 0x9c, 0xb6, 0x86, 0xa5, 0x7c, 0x4c, 0x1a, 0x8e, 0x09, 0xb0, 0xc8, 0x1f,
- 0x14, 0x03, 0xf0, 0xfe, 0x2c, 0x60, 0x7f, 0x98, 0x11, 0xeb, 0x50, 0xf1, 0x02, 0xcc, 0x6d, 0x3b,
- 0x36, 0xdb, 0xc7, 0x38, 0x4f, 0x39, 0x50, 0x5a, 0x05, 0x05, 0xf3, 0x5f, 0xa5, 0x55, 0xbc, 0x08,
- 0x20, 0xd4, 0x69, 0xa0, 0xec, 0xb1, 0x3a, 0xf4, 0x07, 0xca, 0x5e, 0xf1, 0x2a, 0x24, 0xb7, 0x5a,
- 0x87, 0xbb, 0xad, 0x2e, 0xb9, 0x0c, 0xd0, 0x6f, 0x8d, 0xdd, 0x66, 0x07, 0x57, 0xe2, 0xf3, 0xcf,
- 0x3f, 0xff, 0x5c, 0xc1, 0xc3, 0x74, 0x86, 0x96, 0xb2, 0x15, 0x19, 0x03, 0x34, 0xfa, 0xed, 0x2d,
- 0x6b, 0x3c, 0x6e, 0x75, 0x2d, 0xb2, 0x06, 0x49, 0xdb, 0x1a, 0xd3, 0xe8, 0xab, 0xe0, 0x5d, 0xd3,
- 0x05, 0x71, 0x1e, 0x02, 0xdc, 0xf2, 0x36, 0x82, 0x4c, 0x0e, 0x26, 0x1a, 0xc4, 0xec, 0xc9, 0x00,
- 0x6f, 0xd4, 0x12, 0x26, 0x7d, 0x5c, 0x7a, 0x11, 0x92, 0x0c, 0x43, 0x08, 0xc4, 0xed, 0xd6, 0xc0,
- 0x2a, 0xb0, 0x96, 0xf1, 0xb9, 0xf8, 0x15, 0x05, 0x60, 0xdb, 0x7a, 0x7a, 0xac, 0x56, 0x03, 0x9c,
- 0xa4, 0xd5, 0x18, 0x6b, 0xf5, 0x75, 0x59, 0xab, 0x54, 0x6d, 0x1d, 0xc7, 0x69, 0x37, 0xd9, 0x42,
- 0xb3, 0xeb, 0xbf, 0x0c, 0x2d, 0xc1, 0x95, 0x2b, 0x3e, 0x86, 0xdc, 0xa6, 0x6d, 0x5b, 0x23, 0xaf,
- 0x57, 0x04, 0xe2, 0x07, 0xce, 0xd8, 0xe5, 0x37, 0x91, 0xf8, 0x4c, 0x0a, 0x10, 0x1f, 0x3a, 0x23,
- 0x97, 0x8d, 0xb4, 0x16, 0x37, 0x56, 0x56, 0x56, 0x4c, 0x2c, 0x21, 0x2f, 0x42, 0x66, 0xdf, 0xb1,
- 0x6d, 0x6b, 0x9f, 0x0e, 0x23, 0x86, 0xa9, 0x63, 0x50, 0x50, 0xfc, 0x65, 0x05, 0x72, 0x0d, 0xf7,
- 0x20, 0x20, 0xd7, 0x20, 0xf6, 0xc4, 0x3a, 0xc2, 0xee, 0xc5, 0x4c, 0xfa, 0x48, 0x37, 0xcc, 0xcf,
- 0xb7, 0xfa, 0x13, 0x76, 0x2f, 0x99, 0x33, 0xd9, 0x0b, 0x39, 0x03, 0xc9, 0xa7, 0x56, 0xaf, 0x7b,
- 0xe0, 0x22, 0xa7, 0x6a, 0xf2, 0x37, 0xb2, 0x0c, 0x89, 0x1e, 0xed, 0x6c, 0x21, 0x8e, 0x33, 0x56,
- 0x10, 0x67, 0x4c, 0x1c, 0x85, 0xc9, 0x60, 0x57, 0xd2, 0xe9, 0xb6, 0xf6, 0xc1, 0x07, 0x1f, 0x7c,
- 0xa0, 0x16, 0x0f, 0x60, 0xd1, 0xdb, 0xc4, 0xa1, 0xe1, 0x3e, 0x82, 0x42, 0xdf, 0x72, 0x9a, 0x9d,
- 0x9e, 0xdd, 0xea, 0xf7, 0x8f, 0x9a, 0x4f, 0x1d, 0xbb, 0xd9, 0xb2, 0x9b, 0xce, 0x78, 0xbf, 0x35,
- 0xc2, 0x29, 0x90, 0x35, 0xb2, 0xd8, 0xb7, 0x9c, 0x3a, 0x33, 0x7c, 0xcf, 0xb1, 0x6f, 0xdb, 0x0d,
- 0x6a, 0x55, 0xfc, 0x2c, 0x0e, 0x99, 0xad, 0x23, 0x8f, 0x7f, 0x11, 0x12, 0xfb, 0xce, 0xc4, 0x66,
- 0xf3, 0x99, 0x30, 0xd9, 0x8b, 0xbf, 0x4e, 0xaa, 0xb0, 0x4e, 0x8b, 0x90, 0x78, 0x7f, 0xe2, 0xb8,
- 0x16, 0x0e, 0x39, 0x63, 0xb2, 0x17, 0x3a, 0x63, 0x43, 0xcb, 0x2d, 0xc4, 0xf1, 0x9a, 0x82, 0x3e,
- 0x06, 0x73, 0x90, 0x38, 0xd6, 0x1c, 0x90, 0x15, 0x48, 0x3a, 0x74, 0x0d, 0xc6, 0x85, 0x24, 0xde,
- 0xc3, 0x86, 0x0c, 0xc4, 0xd5, 0x31, 0x39, 0x8e, 0x3c, 0x80, 0x85, 0xa7, 0x56, 0x73, 0x30, 0x19,
- 0xbb, 0xcd, 0xae, 0xd3, 0x6c, 0x5b, 0xd6, 0xd0, 0x1a, 0x15, 0xe6, 0xb0, 0xb5, 0x90, 0x87, 0x98,
- 0x35, 0xa1, 0xe6, 0xfc, 0x53, 0x6b, 0x6b, 0x32, 0x76, 0x37, 0x9c, 0x7b, 0x68, 0x47, 0xd6, 0x20,
- 0x33, 0xb2, 0xa8, 0x5f, 0xa0, 0x5d, 0xce, 0x4d, 0xf7, 0x20, 0x64, 0x9c, 0x1e, 0x59, 0x43, 0x2c,
- 0x20, 0x37, 0x20, 0xbd, 0xd7, 0x7b, 0x62, 0x8d, 0x0f, 0xac, 0x76, 0x21, 0xa5, 0x2b, 0xa5, 0xf9,
- 0xf2, 0x79, 0xd1, 0xca, 0x9f, 0xe0, 0xe5, 0xbb, 0x4e, 0xdf, 0x19, 0x99, 0x3e, 0x98, 0xbc, 0x01,
- 0x99, 0xb1, 0x33, 0xb0, 0x98, 0xda, 0xd3, 0x18, 0x6c, 0x2f, 0xcd, 0xb6, 0xdc, 0x71, 0x06, 0x96,
- 0xe7, 0xd5, 0x3c, 0x0b, 0x72, 0x9e, 0x75, 0x77, 0x8f, 0x26, 0x13, 0x05, 0xc0, 0x0b, 0x1f, 0xda,
- 0x29, 0x4c, 0x2e, 0xc8, 0x12, 0xed, 0x54, 0xb7, 0x43, 0xcf, 0x6c, 0x85, 0x2c, 0xe6, 0xf2, 0xfe,
- 0xfb, 0xd2, 0x6b, 0x90, 0xf1, 0x09, 0x03, 0x77, 0xc8, 0x5c, 0x50, 0x06, 0x3d, 0x04, 0x73, 0x87,
- 0xcc, 0xff, 0xbc, 0x0c, 0x09, 0xec, 0x38, 0x8d, 0x5c, 0xe6, 0x3a, 0x0d, 0x94, 0x19, 0x48, 0x6c,
- 0x98, 0xeb, 0xeb, 0xdb, 0x9a, 0x82, 0x31, 0xf3, 0xe1, 0x3b, 0xeb, 0x9a, 0x2a, 0xe8, 0xf7, 0xb7,
- 0x55, 0x88, 0xad, 0x1f, 0xa2, 0x72, 0xda, 0x2d, 0xb7, 0xe5, 0xed, 0x70, 0xfa, 0x4c, 0x6a, 0x90,
- 0x19, 0xb4, 0xbc, 0xb6, 0x54, 0x9c, 0xe2, 0x90, 0x2f, 0x59, 0x3f, 0x74, 0x97, 0xb7, 0x5a, 0xac,
- 0xe5, 0x75, 0xdb, 0x1d, 0x1d, 0x99, 0xe9, 0x01, 0x7f, 0x5d, 0x7a, 0x1d, 0xe6, 0x42, 0x55, 0xe2,
- 0x16, 0x4d, 0xcc, 0xd8, 0xa2, 0x09, 0xbe, 0x45, 0x6b, 0xea, 0x4d, 0xa5, 0x5c, 0x83, 0xf8, 0xc0,
- 0x19, 0x59, 0xe4, 0x85, 0x99, 0x13, 0x5c, 0xe8, 0xa2, 0x64, 0xf2, 0x91, 0xae, 0x98, 0x68, 0x53,
- 0x7e, 0x15, 0xe2, 0xae, 0x75, 0xe8, 0x3e, 0xcb, 0xf6, 0x80, 0x8d, 0x8f, 0x42, 0xca, 0xd7, 0x20,
- 0x69, 0x4f, 0x06, 0x7b, 0xd6, 0xe8, 0x59, 0xe0, 0x1e, 0x76, 0x8c, 0x83, 0x8a, 0xef, 0x82, 0x76,
- 0xd7, 0x19, 0x0c, 0xfb, 0xd6, 0xe1, 0xfa, 0xa1, 0x6b, 0xd9, 0xe3, 0x9e, 0x63, 0xd3, 0x31, 0x74,
- 0x7a, 0x23, 0x74, 0x6b, 0x38, 0x06, 0x7c, 0xa1, 0x6e, 0x66, 0x6c, 0xed, 0x3b, 0x76, 0x9b, 0x0f,
- 0x8d, 0xbf, 0x51, 0xb4, 0x7b, 0xd0, 0x1b, 0x51, 0x8f, 0x46, 0x83, 0x0f, 0x7b, 0x29, 0x6e, 0x40,
- 0x9e, 0xa7, 0x61, 0x63, 0xde, 0x70, 0xf1, 0x0a, 0xe4, 0xbc, 0x22, 0xfc, 0xe5, 0x27, 0x0d, 0xf1,
- 0xc7, 0xeb, 0x66, 0x43, 0x3b, 0x45, 0xd7, 0xb5, 0xb1, 0xbd, 0xae, 0x29, 0xf4, 0x61, 0xf7, 0xbd,
- 0x46, 0x68, 0x2d, 0x5f, 0x84, 0x9c, 0xdf, 0xf7, 0x1d, 0xcb, 0xc5, 0x1a, 0x1a, 0xa5, 0x52, 0x35,
- 0x35, 0xad, 0x14, 0x53, 0x90, 0x58, 0x1f, 0x0c, 0xdd, 0xa3, 0xe2, 0x2f, 0x41, 0x96, 0x83, 0x1e,
- 0xf6, 0xc6, 0x2e, 0xb9, 0x05, 0xa9, 0x01, 0x1f, 0xaf, 0x82, 0x67, 0xd1, 0xb0, 0xac, 0x03, 0xa4,
- 0xf7, 0x6c, 0x7a, 0xf8, 0xa5, 0x0a, 0xa4, 0x04, 0xf7, 0xce, 0x3d, 0x8f, 0x2a, 0x7a, 0x1e, 0xe6,
- 0xa3, 0x62, 0x82, 0x8f, 0x2a, 0x6e, 0x41, 0x8a, 0x05, 0xe6, 0x31, 0x1e, 0x37, 0x58, 0xfe, 0xce,
- 0x34, 0xc6, 0xc4, 0x97, 0x65, 0x65, 0xec, 0x0c, 0x75, 0x09, 0xb2, 0xb8, 0x67, 0x7c, 0x15, 0x52,
- 0x6f, 0x0e, 0x58, 0xc4, 0x14, 0xff, 0x47, 0x09, 0x48, 0x7b, 0x73, 0x45, 0xce, 0x43, 0x92, 0x25,
- 0xb1, 0x48, 0xe5, 0x5d, 0xea, 0x24, 0x30, 0x6d, 0x25, 0xe7, 0x21, 0xc5, 0x13, 0x55, 0x1e, 0x70,
- 0xd4, 0x4a, 0xd9, 0x4c, 0xb2, 0xc4, 0xd4, 0xaf, 0xac, 0x1a, 0xe8, 0x27, 0xd9, 0x75, 0x4d, 0x92,
- 0xa5, 0x9e, 0x44, 0x87, 0x8c, 0x9f, 0x6c, 0x62, 0x88, 0xe0, 0x77, 0x33, 0x69, 0x2f, 0xbb, 0x14,
- 0x10, 0x55, 0x03, 0x1d, 0x28, 0xbf, 0x88, 0x49, 0xd7, 0x83, 0x73, 0x53, 0xda, 0x4b, 0x19, 0xf1,
- 0x97, 0x27, 0xef, 0xd6, 0x25, 0xc5, 0x93, 0xc4, 0x00, 0x50, 0x35, 0xd0, 0x33, 0x79, 0x57, 0x2c,
- 0x29, 0x9e, 0x08, 0x92, 0x4b, 0xb4, 0x8b, 0x98, 0xd8, 0xa1, 0xff, 0x09, 0xee, 0x53, 0x92, 0x2c,
- 0xdd, 0x23, 0x97, 0x29, 0x03, 0xcb, 0xde, 0xd0, 0x35, 0x04, 0x97, 0x27, 0x29, 0x9e, 0xd4, 0x91,
- 0xab, 0x14, 0xc2, 0xa6, 0xbf, 0x00, 0xcf, 0xb8, 0x29, 0x49, 0xf1, 0x9b, 0x12, 0xa2, 0xd3, 0x06,
- 0xd1, 0x43, 0xa1, 0x57, 0x12, 0x6e, 0x45, 0x92, 0xec, 0x56, 0x84, 0x5c, 0x44, 0x3a, 0x36, 0xa8,
- 0x5c, 0x70, 0x03, 0x92, 0xe2, 0x59, 0x60, 0x50, 0x8f, 0x67, 0x49, 0xff, 0xb6, 0x23, 0xc5, 0xf3,
- 0x3c, 0x72, 0x93, 0xae, 0x17, 0x55, 0x78, 0x61, 0x1e, 0x7d, 0xf1, 0x92, 0x28, 0x3d, 0x6f, 0x55,
- 0x99, 0x2b, 0xae, 0x31, 0x37, 0x66, 0x26, 0xea, 0xb8, 0x23, 0x96, 0xa8, 0xe5, 0xa3, 0x9e, 0xdd,
- 0x29, 0xe4, 0x71, 0x2e, 0x62, 0x3d, 0xbb, 0x63, 0x26, 0xea, 0xb4, 0x84, 0xa9, 0x60, 0x9b, 0xd6,
- 0x69, 0x58, 0x17, 0xbf, 0xc6, 0x2a, 0x69, 0x11, 0x29, 0x40, 0xa2, 0xde, 0xdc, 0x6e, 0xd9, 0x85,
- 0x05, 0x66, 0x67, 0xb7, 0x6c, 0x33, 0x5e, 0xdf, 0x6e, 0xd9, 0xe4, 0x55, 0x88, 0x8d, 0x27, 0x7b,
- 0x05, 0x32, 0xfd, 0xb3, 0xe0, 0xce, 0x64, 0xcf, 0xeb, 0x8c, 0x49, 0x31, 0xe4, 0x3c, 0xa4, 0xc7,
- 0xee, 0xa8, 0xf9, 0x0b, 0xd6, 0xc8, 0x29, 0x9c, 0xc6, 0x69, 0x3c, 0x65, 0xa6, 0xc6, 0xee, 0xe8,
- 0xb1, 0x35, 0x72, 0x8e, 0xe9, 0x83, 0x8b, 0x17, 0x21, 0x2b, 0xf0, 0x92, 0x3c, 0x28, 0x36, 0x3b,
- 0xc0, 0xd4, 0x94, 0x1b, 0xa6, 0x62, 0x17, 0xdf, 0x85, 0x9c, 0x97, 0x62, 0xe1, 0x88, 0x0d, 0xba,
- 0x9b, 0xfa, 0xce, 0x08, 0x77, 0xe9, 0x7c, 0xf9, 0x62, 0x38, 0x62, 0x06, 0x40, 0x1e, 0xb9, 0x18,
- 0xb8, 0xa8, 0x45, 0x3a, 0xa3, 0x14, 0x7f, 0xa0, 0x40, 0x6e, 0xcb, 0x19, 0x05, 0xbf, 0x5f, 0x2c,
- 0x42, 0x62, 0xcf, 0x71, 0xfa, 0x63, 0x24, 0x4e, 0x9b, 0xec, 0x85, 0xbc, 0x0c, 0x39, 0x7c, 0xf0,
- 0x92, 0x64, 0xd5, 0xbf, 0x05, 0xca, 0x62, 0x39, 0xcf, 0x8b, 0x09, 0xc4, 0x7b, 0xb6, 0x3b, 0xe6,
- 0x1e, 0x0d, 0x9f, 0xc9, 0x17, 0x20, 0x4b, 0xff, 0x7a, 0x96, 0x71, 0xff, 0x34, 0x0d, 0xb4, 0x98,
- 0x1b, 0xbe, 0x02, 0x73, 0xa8, 0x01, 0x1f, 0x96, 0xf2, 0x6f, 0x7c, 0x72, 0xac, 0x82, 0x03, 0x0b,
- 0x90, 0x62, 0x0e, 0x61, 0x8c, 0x3f, 0xf8, 0x66, 0x4c, 0xef, 0x95, 0xba, 0x59, 0x4c, 0x54, 0xd8,
- 0x09, 0x24, 0x65, 0xf2, 0xb7, 0xe2, 0x5d, 0x48, 0x63, 0xb8, 0x6c, 0xf4, 0xdb, 0xe4, 0x25, 0x50,
- 0xba, 0x05, 0x0b, 0xc3, 0xf5, 0x99, 0x50, 0x16, 0xc2, 0x01, 0xcb, 0x1b, 0xa6, 0xd2, 0x5d, 0x5a,
- 0x00, 0x65, 0x83, 0xa6, 0x05, 0x87, 0xdc, 0x61, 0x2b, 0x87, 0xc5, 0xb7, 0x39, 0xc9, 0xb6, 0xf5,
- 0x54, 0x4e, 0xb2, 0x6d, 0x3d, 0x65, 0x24, 0x97, 0xa6, 0x48, 0xe8, 0xdb, 0x11, 0xff, 0x0d, 0x5c,
- 0x39, 0x2a, 0x56, 0x60, 0x0e, 0x37, 0x6a, 0xcf, 0xee, 0x3e, 0x72, 0x7a, 0x36, 0x26, 0x22, 0x1d,
- 0x3c, 0xc0, 0x29, 0xa6, 0xd2, 0xa1, 0xeb, 0x60, 0x1d, 0xb6, 0xf6, 0xd9, 0x71, 0x38, 0x6d, 0xb2,
- 0x97, 0xe2, 0xf7, 0xe3, 0x30, 0xcf, 0x9d, 0xec, 0x7b, 0x3d, 0xf7, 0x60, 0xab, 0x35, 0x24, 0xdb,
- 0x90, 0xa3, 0xfe, 0xb5, 0x39, 0x68, 0x0d, 0x87, 0x74, 0x23, 0x2b, 0x18, 0x9a, 0xaf, 0xce, 0x70,
- 0xdb, 0xdc, 0x62, 0x79, 0xbb, 0x35, 0xb0, 0xb6, 0x18, 0x9a, 0x05, 0xea, 0xac, 0x1d, 0x94, 0x90,
- 0x07, 0x90, 0x1d, 0x8c, 0xbb, 0x3e, 0x1d, 0x8b, 0xf4, 0x57, 0x24, 0x74, 0x5b, 0xe3, 0x6e, 0x88,
- 0x0d, 0x06, 0x7e, 0x01, 0xed, 0x1c, 0xf5, 0xce, 0x3e, 0x5b, 0xec, 0xb9, 0x9d, 0xa3, 0xae, 0x24,
- 0xdc, 0xb9, 0xbd, 0xa0, 0x84, 0xd4, 0x01, 0xe8, 0x56, 0x73, 0x1d, 0x9a, 0xe1, 0xa1, 0x96, 0xb2,
- 0xe5, 0x92, 0x84, 0x6d, 0xc7, 0x1d, 0xed, 0x3a, 0x3b, 0xee, 0x88, 0x1f, 0x48, 0xc6, 0xfc, 0x75,
- 0xe9, 0x4d, 0xd0, 0xa2, 0xb3, 0xf0, 0xbc, 0x33, 0x49, 0x46, 0x38, 0x93, 0x2c, 0xfd, 0x2c, 0xe4,
- 0x23, 0xc3, 0x16, 0xcd, 0x09, 0x33, 0xbf, 0x2e, 0x9a, 0x67, 0xcb, 0xe7, 0x42, 0xdf, 0x68, 0x88,
- 0x4b, 0x2f, 0x32, 0xbf, 0x09, 0x5a, 0x74, 0x0a, 0x44, 0xea, 0xb4, 0x24, 0xa1, 0x41, 0xfb, 0xd7,
- 0x61, 0x2e, 0x34, 0x68, 0xd1, 0x38, 0xf3, 0x9c, 0x61, 0x15, 0x7f, 0x25, 0x01, 0x89, 0x86, 0x6d,
- 0x39, 0x1d, 0x72, 0x36, 0x1c, 0x3b, 0xef, 0x9f, 0xf2, 0xe2, 0xe6, 0xb9, 0x48, 0xdc, 0xbc, 0x7f,
- 0xca, 0x8f, 0x9a, 0xe7, 0x22, 0x51, 0xd3, 0xab, 0xaa, 0x1a, 0xe4, 0xc2, 0x54, 0xcc, 0xbc, 0x7f,
- 0x4a, 0x08, 0x98, 0x17, 0xa6, 0x02, 0x66, 0x50, 0x5d, 0x35, 0xa8, 0x83, 0x0d, 0x47, 0xcb, 0xfb,
- 0xa7, 0x82, 0x48, 0x79, 0x3e, 0x1a, 0x29, 0xfd, 0xca, 0xaa, 0xc1, 0xba, 0x24, 0x44, 0x49, 0xec,
- 0x12, 0x8b, 0x8f, 0xe7, 0xa3, 0xf1, 0x11, 0xed, 0x78, 0x64, 0x3c, 0x1f, 0x8d, 0x8c, 0x58, 0xc9,
- 0x23, 0xe1, 0xb9, 0x48, 0x24, 0x44, 0x52, 0x16, 0x02, 0xcf, 0x47, 0x43, 0x20, 0xb3, 0x13, 0x7a,
- 0x2a, 0xc6, 0x3f, 0xbf, 0xb2, 0x6a, 0x10, 0x23, 0x12, 0xfc, 0x64, 0x89, 0x08, 0xae, 0x06, 0x86,
- 0x81, 0x2a, 0x9d, 0x38, 0xef, 0x80, 0x9a, 0x97, 0x7e, 0xc2, 0x82, 0x33, 0xea, 0x1d, 0xd0, 0x0c,
- 0x48, 0x75, 0x78, 0xae, 0xae, 0xa1, 0x27, 0x0b, 0x89, 0x13, 0x25, 0xb0, 0x5c, 0x6f, 0xa2, 0x47,
- 0xa3, 0xa3, 0xeb, 0xb0, 0x84, 0xa3, 0x04, 0x73, 0xf5, 0xe6, 0xc3, 0xd6, 0xa8, 0x4b, 0xa1, 0xbb,
- 0xad, 0xae, 0x7f, 0xeb, 0x41, 0x55, 0x90, 0xad, 0xf3, 0x9a, 0xdd, 0x56, 0x97, 0x9c, 0xf1, 0x24,
- 0xd6, 0xc6, 0x5a, 0x85, 0x8b, 0x6c, 0xe9, 0x2c, 0x9d, 0x3a, 0x46, 0x86, 0xbe, 0x71, 0x81, 0xfb,
- 0xc6, 0x3b, 0x29, 0x48, 0x4c, 0xec, 0x9e, 0x63, 0xdf, 0xc9, 0x40, 0xca, 0x75, 0x46, 0x83, 0x96,
- 0xeb, 0x14, 0x7f, 0xa8, 0x00, 0xdc, 0x75, 0x06, 0x83, 0x89, 0xdd, 0x7b, 0x7f, 0x62, 0x91, 0x8b,
- 0x90, 0x1d, 0xb4, 0x9e, 0x58, 0xcd, 0x81, 0xd5, 0xdc, 0x1f, 0x79, 0xbb, 0x21, 0x43, 0x8b, 0xb6,
- 0xac, 0xbb, 0xa3, 0x23, 0x52, 0xf0, 0x0e, 0xf0, 0xa8, 0x20, 0x14, 0x26, 0x3f, 0xd0, 0x2f, 0xf2,
- 0xe3, 0x68, 0x92, 0xaf, 0xa4, 0x77, 0x20, 0x65, 0x49, 0x4e, 0x8a, 0xaf, 0x21, 0x4b, 0x73, 0xce,
- 0x42, 0xd2, 0xb5, 0x06, 0xc3, 0xe6, 0x3e, 0x0a, 0x86, 0x8a, 0x22, 0x41, 0xdf, 0xef, 0x92, 0xeb,
- 0x10, 0xdb, 0x77, 0xfa, 0x28, 0x95, 0xe7, 0xae, 0x0e, 0x45, 0x92, 0x57, 0x20, 0x36, 0x18, 0x33,
- 0xf9, 0x64, 0xcb, 0xa7, 0x43, 0x27, 0x08, 0x16, 0xb2, 0x28, 0x70, 0x30, 0xee, 0xfa, 0x63, 0xbf,
- 0x92, 0x87, 0x58, 0xbd, 0xd1, 0xa0, 0xa7, 0x82, 0x7a, 0xa3, 0xb1, 0xaa, 0x29, 0xb5, 0x55, 0x48,
- 0x77, 0x47, 0x96, 0x45, 0x1d, 0xc5, 0xb3, 0xb2, 0x92, 0x2f, 0x63, 0x14, 0xf4, 0x61, 0xb5, 0xb7,
- 0x21, 0xb5, 0xcf, 0xf2, 0x12, 0xf2, 0xcc, 0x1c, 0xbc, 0xf0, 0xc7, 0xec, 0x2e, 0xe8, 0x45, 0x11,
- 0x10, 0xcd, 0x66, 0x4c, 0x8f, 0xa7, 0xb6, 0x0b, 0x99, 0x51, 0xf3, 0xf9, 0xa4, 0x1f, 0xb2, 0xc8,
- 0x23, 0x27, 0x4d, 0x8f, 0x78, 0x51, 0x6d, 0x03, 0x16, 0x6c, 0xc7, 0xfb, 0x49, 0xaa, 0xd9, 0xe6,
- 0xfb, 0x6e, 0xd6, 0x91, 0xcf, 0x6b, 0xc0, 0x62, 0x3f, 0x6c, 0xdb, 0x0e, 0xaf, 0x60, 0x7b, 0xb5,
- 0xb6, 0x0e, 0x9a, 0x40, 0xd4, 0x61, 0x9b, 0x5b, 0xc6, 0xd3, 0x61, 0xbf, 0xa5, 0xfb, 0x3c, 0xe8,
- 0x0f, 0x22, 0x34, 0x7c, 0xc7, 0xca, 0x68, 0xba, 0xec, 0xd3, 0x04, 0x9f, 0x06, 0x9d, 0xe0, 0x34,
- 0x0d, 0xf5, 0x5f, 0x32, 0x9a, 0x03, 0xf6, 0xdd, 0x82, 0x48, 0x53, 0x35, 0x22, 0xb3, 0x33, 0x39,
- 0x46, 0x77, 0x7a, 0xec, 0xc3, 0x03, 0x9f, 0x87, 0xb9, 0xc7, 0x19, 0x44, 0xcf, 0xeb, 0xd0, 0x97,
- 0xd9, 0x57, 0x09, 0x21, 0xa2, 0xa9, 0x1e, 0x8d, 0x8f, 0xd1, 0xa3, 0x27, 0xec, 0x23, 0x00, 0x9f,
- 0x68, 0x67, 0x56, 0x8f, 0xc6, 0xc7, 0xe8, 0x51, 0x9f, 0x7d, 0x20, 0x10, 0x22, 0xaa, 0x1a, 0xb5,
- 0x4d, 0x20, 0xe2, 0xc2, 0xf3, 0x58, 0x22, 0x65, 0x1a, 0xb0, 0x0f, 0x3f, 0x82, 0xa5, 0x67, 0x46,
- 0xb3, 0xa8, 0x9e, 0xd7, 0x29, 0x9b, 0x7d, 0x15, 0x12, 0xa6, 0xaa, 0x1a, 0xb5, 0x07, 0x70, 0x5a,
- 0x1c, 0xde, 0xb1, 0xba, 0xe5, 0xb0, 0x4f, 0x1a, 0x82, 0x01, 0x72, 0xab, 0x99, 0x64, 0xcf, 0xeb,
- 0xd8, 0x90, 0x7d, 0xee, 0x10, 0x21, 0xab, 0x1a, 0xb5, 0xbb, 0x90, 0x17, 0xc8, 0xf6, 0x30, 0x0b,
- 0x96, 0x11, 0xbd, 0xcf, 0x3e, 0xd2, 0xf1, 0x89, 0x68, 0xfc, 0x8f, 0xae, 0x1e, 0x8b, 0x88, 0x52,
- 0x9a, 0x11, 0xfb, 0xc6, 0x24, 0xe8, 0x0f, 0xda, 0x44, 0x36, 0xca, 0x1e, 0x0b, 0x9f, 0x32, 0x9e,
- 0x31, 0xfb, 0xfe, 0x24, 0xe8, 0x0e, 0x35, 0xa9, 0x0d, 0x42, 0x83, 0xb2, 0x68, 0x50, 0x94, 0xb2,
- 0xb8, 0xe8, 0xbf, 0x4b, 0x12, 0xc8, 0xb2, 0x78, 0xd9, 0x22, 0x0c, 0x9f, 0xbe, 0xd6, 0x1e, 0xc0,
- 0xfc, 0x49, 0x5c, 0xd6, 0x87, 0x0a, 0xcb, 0xbc, 0x2b, 0xcb, 0x34, 0x39, 0x37, 0xe7, 0xda, 0x21,
- 0xcf, 0xb5, 0x01, 0x73, 0x27, 0x70, 0x5b, 0x1f, 0x29, 0x2c, 0x7f, 0xa5, 0x5c, 0x66, 0xae, 0x1d,
- 0xf6, 0x5d, 0x73, 0x27, 0x70, 0x5c, 0x1f, 0x2b, 0xec, 0xc2, 0xc3, 0x28, 0xfb, 0x34, 0x9e, 0xef,
- 0x9a, 0x3b, 0x81, 0xe3, 0xfa, 0x84, 0xe5, 0xa7, 0xaa, 0x51, 0x11, 0x69, 0xd0, 0x53, 0xcc, 0x9f,
- 0xc4, 0x71, 0x7d, 0xaa, 0xe0, 0x05, 0x88, 0x6a, 0x18, 0xfe, 0xfc, 0xf8, 0xbe, 0x6b, 0xfe, 0x24,
- 0x8e, 0xeb, 0xab, 0x0a, 0x5e, 0x94, 0xa8, 0xc6, 0x5a, 0x88, 0x28, 0xdc, 0xa3, 0xe3, 0x38, 0xae,
- 0xaf, 0x29, 0x78, 0x7b, 0xa1, 0x1a, 0x55, 0x9f, 0x68, 0x67, 0xaa, 0x47, 0xc7, 0x71, 0x5c, 0x5f,
- 0xc7, 0x6c, 0xa0, 0xa6, 0x1a, 0x37, 0x42, 0x44, 0xe8, 0xbb, 0xf2, 0x27, 0x72, 0x5c, 0xdf, 0x50,
- 0xf0, 0xa2, 0x49, 0x35, 0x6e, 0x9a, 0x5e, 0x0f, 0x02, 0xdf, 0x95, 0x3f, 0x91, 0xe3, 0xfa, 0xa6,
- 0x82, 0x37, 0x52, 0xaa, 0x71, 0x2b, 0x4c, 0x85, 0xbe, 0x4b, 0x3b, 0x99, 0xe3, 0xfa, 0x4c, 0xc1,
- 0xef, 0x4f, 0xd4, 0xb5, 0x15, 0xd3, 0xeb, 0x84, 0xe0, 0xbb, 0xb4, 0x93, 0x39, 0xae, 0x6f, 0x29,
- 0xf8, 0x51, 0x8a, 0xba, 0xb6, 0x1a, 0x21, 0xab, 0x1a, 0xb5, 0x75, 0xc8, 0x1d, 0xdf, 0x71, 0x7d,
- 0x5b, 0xbc, 0xef, 0xcb, 0xb6, 0x05, 0xef, 0xf5, 0x58, 0x58, 0xbf, 0x63, 0xb8, 0xae, 0xef, 0x60,
- 0xd6, 0x54, 0x7b, 0xe1, 0x3e, 0xbb, 0x15, 0x63, 0x26, 0xaf, 0xb5, 0xad, 0xce, 0x1b, 0x1d, 0xc7,
- 0x09, 0x96, 0x94, 0x39, 0xb4, 0x46, 0xb0, 0x7b, 0x8e, 0xe1, 0xcd, 0xbe, 0xab, 0xe0, 0x25, 0x5a,
- 0x8e, 0x53, 0xa3, 0x85, 0xbf, 0x8f, 0x98, 0x6b, 0xb3, 0x83, 0x31, 0x3f, 0xdf, 0xaf, 0x7d, 0x4f,
- 0x39, 0x99, 0x63, 0xab, 0xc5, 0x1a, 0xdb, 0xeb, 0xfe, 0xe4, 0x60, 0xc9, 0x5b, 0x10, 0x3f, 0x2c,
- 0xaf, 0xac, 0x86, 0x8f, 0x78, 0xe2, 0x1d, 0x32, 0x73, 0x67, 0xd9, 0xf2, 0x42, 0xe8, 0xb2, 0x7d,
- 0x30, 0x74, 0x8f, 0x4c, 0xb4, 0xe4, 0x0c, 0x65, 0x09, 0xc3, 0x47, 0x52, 0x86, 0x32, 0x67, 0xa8,
- 0x48, 0x18, 0x3e, 0x96, 0x32, 0x54, 0x38, 0x83, 0x21, 0x61, 0xf8, 0x44, 0xca, 0x60, 0x70, 0x86,
- 0x35, 0x09, 0xc3, 0xa7, 0x52, 0x86, 0x35, 0xce, 0x50, 0x95, 0x30, 0x7c, 0x55, 0xca, 0x50, 0xe5,
- 0x0c, 0x37, 0x24, 0x0c, 0x5f, 0x93, 0x32, 0xdc, 0xe0, 0x0c, 0x37, 0x25, 0x0c, 0x5f, 0x97, 0x32,
- 0xdc, 0xe4, 0x0c, 0xb7, 0x24, 0x0c, 0xdf, 0x90, 0x32, 0xdc, 0x62, 0x0c, 0xab, 0x2b, 0x12, 0x86,
- 0x6f, 0xca, 0x18, 0x56, 0x57, 0x38, 0x83, 0x4c, 0x93, 0x9f, 0x49, 0x19, 0xb8, 0x26, 0x57, 0x65,
- 0x9a, 0xfc, 0x96, 0x94, 0x81, 0x6b, 0x72, 0x55, 0xa6, 0xc9, 0x6f, 0x4b, 0x19, 0xb8, 0x26, 0x57,
- 0x65, 0x9a, 0xfc, 0x8e, 0x94, 0x81, 0x6b, 0x72, 0x55, 0xa6, 0xc9, 0xef, 0x4a, 0x19, 0xb8, 0x26,
- 0x57, 0x65, 0x9a, 0xfc, 0x9e, 0x94, 0x81, 0x6b, 0x72, 0x55, 0xa6, 0xc9, 0x3f, 0x91, 0x32, 0x70,
- 0x4d, 0xae, 0xca, 0x34, 0xf9, 0xa7, 0x52, 0x06, 0xae, 0xc9, 0x55, 0x99, 0x26, 0xff, 0x4c, 0xca,
- 0xc0, 0x35, 0x59, 0x96, 0x69, 0xf2, 0xfb, 0x32, 0x86, 0x32, 0xd7, 0x64, 0x59, 0xa6, 0xc9, 0x3f,
- 0x97, 0x32, 0x70, 0x4d, 0x96, 0x65, 0x9a, 0xfc, 0x0b, 0x29, 0x03, 0xd7, 0x64, 0x59, 0xa6, 0xc9,
- 0x1f, 0x48, 0x19, 0xb8, 0x26, 0xcb, 0x32, 0x4d, 0xfe, 0xa5, 0x94, 0x81, 0x6b, 0xb2, 0x2c, 0xd3,
- 0xe4, 0x5f, 0x49, 0x19, 0xb8, 0x26, 0xcb, 0x32, 0x4d, 0xfe, 0xb5, 0x94, 0x81, 0x6b, 0xb2, 0x2c,
- 0xd3, 0xe4, 0xdf, 0x48, 0x19, 0xb8, 0x26, 0xcb, 0x32, 0x4d, 0xfe, 0xad, 0x94, 0x81, 0x6b, 0xb2,
- 0x2c, 0xd3, 0xe4, 0xdf, 0x49, 0x19, 0xb8, 0x26, 0x2b, 0x32, 0x4d, 0xfe, 0xbd, 0x8c, 0xa1, 0xc2,
- 0x35, 0x59, 0x91, 0x69, 0xf2, 0x1f, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, 0xff, 0x51, 0xca,
- 0xc0, 0x35, 0x59, 0x91, 0x69, 0xf2, 0x9f, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, 0xff, 0x59,
- 0xca, 0xc0, 0x35, 0x59, 0x91, 0x69, 0xf2, 0x5f, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, 0xff,
- 0x55, 0xca, 0xc0, 0x35, 0x59, 0x91, 0x69, 0xf2, 0xdf, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26,
- 0x7f, 0x28, 0x65, 0xe0, 0x9a, 0xac, 0xc8, 0x34, 0xf9, 0xef, 0x52, 0x06, 0xae, 0x49, 0x43, 0xa6,
- 0xc9, 0xff, 0x90, 0x31, 0x18, 0x5c, 0x93, 0x86, 0x4c, 0x93, 0xff, 0x29, 0x65, 0xe0, 0x9a, 0x34,
- 0x64, 0x9a, 0xfc, 0x2f, 0x29, 0x03, 0xd7, 0xa4, 0x21, 0xd3, 0xe4, 0x7f, 0x4b, 0x19, 0xb8, 0x26,
- 0x0d, 0x99, 0x26, 0xff, 0x47, 0xca, 0xc0, 0x35, 0x69, 0xc8, 0x34, 0xf9, 0xbf, 0x52, 0x06, 0xae,
- 0x49, 0x43, 0xa6, 0xc9, 0x1f, 0x49, 0x19, 0xb8, 0x26, 0x0d, 0x99, 0x26, 0x7f, 0x2c, 0x65, 0xe0,
- 0x9a, 0x34, 0x64, 0x9a, 0xfc, 0x89, 0x94, 0x81, 0x6b, 0xd2, 0x90, 0x69, 0xf2, 0xa7, 0x52, 0x06,
- 0xae, 0xc9, 0x35, 0x99, 0x26, 0xff, 0x4f, 0xc6, 0xb0, 0xb6, 0x72, 0xe7, 0xda, 0xe3, 0xab, 0xdd,
- 0x9e, 0x7b, 0x30, 0xd9, 0x5b, 0xde, 0x77, 0x06, 0xd7, 0xbb, 0x4e, 0xbf, 0x65, 0x77, 0xaf, 0x23,
- 0x6c, 0x6f, 0xd2, 0xb9, 0x1e, 0xfc, 0xeb, 0x35, 0x33, 0xfd, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff,
- 0x46, 0xc7, 0xb3, 0x38, 0x92, 0x3d, 0x00, 0x00,
+}
+
+func init() { proto.RegisterFile("proto2_proto/test.proto", fileDescriptor_e5b3e7ca68f98362) }
+
+var fileDescriptor_e5b3e7ca68f98362 = []byte{
+ // 4330 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5b, 0x4b, 0x73, 0xdb, 0x58,
+ 0x76, 0x36, 0xc0, 0xf7, 0x21, 0x25, 0x42, 0xb7, 0xd5, 0x36, 0x2d, 0xb5, 0x6d, 0x98, 0x3d, 0x3d,
+ 0xc3, 0xb6, 0xdd, 0xb4, 0x4c, 0x51, 0xb4, 0x4d, 0x4f, 0x3b, 0x63, 0xd9, 0xa2, 0xac, 0xb4, 0x24,
+ 0x7a, 0x20, 0xb9, 0xbb, 0xda, 0xb3, 0x60, 0x41, 0x22, 0x48, 0x71, 0x4c, 0x02, 0x6c, 0x12, 0x1c,
+ 0x4b, 0xa9, 0x54, 0xaa, 0xb7, 0xd9, 0xa4, 0x2a, 0x99, 0xa4, 0x2a, 0x3f, 0x20, 0xdb, 0xc9, 0x63,
+ 0x97, 0x45, 0x7e, 0x40, 0x7a, 0x1e, 0x49, 0x26, 0xef, 0xac, 0x52, 0xf9, 0x07, 0x59, 0xe5, 0xb1,
+ 0xea, 0xa9, 0x73, 0xee, 0x05, 0x70, 0x01, 0x52, 0xaf, 0x95, 0x70, 0xef, 0xfd, 0xbe, 0x73, 0x5f,
+ 0x1f, 0xce, 0x39, 0xf7, 0x12, 0x82, 0x6b, 0xc3, 0x91, 0xe3, 0x3a, 0x95, 0x16, 0xfd, 0xb9, 0xef,
+ 0x5a, 0x63, 0xb7, 0x4c, 0x8f, 0x2c, 0x2b, 0x1a, 0xb0, 0xaa, 0x78, 0x0f, 0x92, 0x9b, 0xce, 0x86,
+ 0x3d, 0x19, 0xb0, 0x22, 0xc4, 0x3a, 0x8e, 0x53, 0x50, 0x74, 0xb5, 0x34, 0x5f, 0xd1, 0xca, 0x12,
+ 0xa8, 0xdc, 0x68, 0x36, 0x0d, 0x6c, 0x2c, 0x3e, 0x84, 0xec, 0xa6, 0xb3, 0x6f, 0x8d, 0xdd, 0x46,
+ 0xcf, 0xea, 0xb7, 0xd9, 0x22, 0x24, 0xb6, 0xcd, 0x03, 0xab, 0x4f, 0xa4, 0x8c, 0xc1, 0x0b, 0x8c,
+ 0x41, 0x7c, 0xff, 0x64, 0x68, 0x15, 0x54, 0xaa, 0xa4, 0xe7, 0xe2, 0xdf, 0x14, 0xb1, 0x1f, 0x64,
+ 0xb2, 0x7b, 0x10, 0xff, 0xac, 0x67, 0xb7, 0x45, 0x47, 0x85, 0x50, 0x47, 0x1c, 0x52, 0xfe, 0x6c,
+ 0x6b, 0xf7, 0x85, 0x41, 0x28, 0xec, 0x62, 0xdf, 0x3c, 0xe8, 0xa3, 0x35, 0x05, 0xbb, 0xa0, 0x02,
+ 0xd6, 0xbe, 0x32, 0x47, 0xe6, 0xa0, 0x10, 0xd3, 0x95, 0x52, 0xc2, 0xe0, 0x05, 0xf6, 0x14, 0xe6,
+ 0x0c, 0xeb, 0xab, 0x49, 0x6f, 0x64, 0xb5, 0x69, 0x7c, 0x85, 0xb8, 0xae, 0x96, 0xb2, 0x33, 0xbb,
+ 0xa0, 0x76, 0x23, 0x0c, 0xe7, 0xfc, 0xa1, 0x65, 0xba, 0x1e, 0x3f, 0xa1, 0xc7, 0xce, 0xe3, 0x4b,
+ 0x70, 0xe4, 0x37, 0x87, 0x6e, 0xcf, 0xb1, 0xcd, 0x3e, 0xe7, 0x27, 0x75, 0xe5, 0x6c, 0x7e, 0x08,
+ 0xce, 0xbe, 0x0b, 0xf9, 0x46, 0x6b, 0xdd, 0x71, 0xfa, 0xad, 0x91, 0x18, 0x57, 0x01, 0x74, 0xb5,
+ 0x94, 0x36, 0xe6, 0x1a, 0x58, 0xeb, 0x0d, 0x96, 0x95, 0x40, 0x6b, 0xb4, 0xb6, 0x6c, 0x77, 0xb5,
+ 0x12, 0x00, 0xb3, 0xba, 0x5a, 0x4a, 0x18, 0xf3, 0x0d, 0xaa, 0x9e, 0x42, 0xd6, 0xaa, 0x01, 0x32,
+ 0xa7, 0xab, 0xa5, 0x18, 0x47, 0xd6, 0xaa, 0x3e, 0xf2, 0x1e, 0xb0, 0x46, 0xab, 0xd1, 0x3b, 0xb6,
+ 0xda, 0xb2, 0xd5, 0x39, 0x5d, 0x2d, 0xa5, 0x0c, 0xad, 0x21, 0x1a, 0x66, 0xa0, 0x65, 0xcb, 0xf3,
+ 0xba, 0x5a, 0x4a, 0x7a, 0x68, 0xc9, 0xf6, 0x1d, 0x58, 0x68, 0xb4, 0x5e, 0xf7, 0xc2, 0x03, 0xce,
+ 0xeb, 0x6a, 0x69, 0xce, 0xc8, 0x37, 0x78, 0xfd, 0x34, 0x56, 0x36, 0xac, 0xe9, 0x6a, 0x29, 0x2e,
+ 0xb0, 0x92, 0x5d, 0x9a, 0x5d, 0xa3, 0xef, 0x98, 0x6e, 0x00, 0x5d, 0xd0, 0xd5, 0x92, 0x6a, 0xcc,
+ 0x37, 0xa8, 0x3a, 0x6c, 0xf5, 0x85, 0x33, 0x39, 0xe8, 0x5b, 0x01, 0x94, 0xe9, 0x6a, 0x49, 0x31,
+ 0xf2, 0x0d, 0x5e, 0x1f, 0xc6, 0xee, 0xb9, 0xa3, 0x9e, 0xdd, 0x0d, 0xb0, 0xef, 0x91, 0x96, 0xf3,
+ 0x0d, 0x5e, 0x1f, 0x1e, 0xc1, 0xfa, 0x89, 0x6b, 0x8d, 0x03, 0xa8, 0xa5, 0xab, 0xa5, 0x9c, 0x31,
+ 0xdf, 0xa0, 0xea, 0x88, 0xd5, 0xc8, 0x1a, 0x74, 0x74, 0xb5, 0xb4, 0x80, 0x56, 0x67, 0xac, 0xc1,
+ 0x5e, 0x64, 0x0d, 0xba, 0xba, 0x5a, 0x62, 0x02, 0x2b, 0xad, 0x41, 0x19, 0xde, 0x6b, 0xb4, 0xf6,
+ 0x3a, 0xd1, 0x8d, 0x3b, 0xd2, 0xd5, 0x52, 0xde, 0x58, 0x68, 0x78, 0x2d, 0xb3, 0xf0, 0xb2, 0xf5,
+ 0x9e, 0xae, 0x96, 0x34, 0x1f, 0x2f, 0xd9, 0x97, 0x35, 0xc9, 0xb5, 0x5e, 0x58, 0xd4, 0x63, 0x92,
+ 0x26, 0x79, 0x65, 0x58, 0x93, 0x02, 0xf8, 0xbe, 0x1e, 0x93, 0x35, 0x19, 0x41, 0x52, 0xf7, 0x02,
+ 0x79, 0x55, 0x8f, 0xc9, 0x9a, 0x14, 0xc8, 0x88, 0x26, 0x05, 0xf6, 0x9a, 0x1e, 0x0b, 0x6b, 0x72,
+ 0x0a, 0x2d, 0x5b, 0x2e, 0xe8, 0xb1, 0xb0, 0x26, 0x05, 0x3a, 0xac, 0x49, 0x01, 0xbe, 0xae, 0xc7,
+ 0x42, 0x9a, 0x8c, 0x62, 0x65, 0xc3, 0x4b, 0x7a, 0x2c, 0xa4, 0x49, 0x79, 0x76, 0x9e, 0x26, 0x05,
+ 0x74, 0x59, 0x8f, 0xc9, 0x9a, 0x94, 0xad, 0xfa, 0x9a, 0x14, 0xd0, 0x0f, 0xf4, 0x58, 0x48, 0x93,
+ 0x32, 0xd6, 0xd7, 0xa4, 0xc0, 0xde, 0xd0, 0x63, 0x21, 0x4d, 0x0a, 0xec, 0xc7, 0xb2, 0x26, 0x05,
+ 0xf4, 0x1b, 0x45, 0x8f, 0xc9, 0xa2, 0x14, 0xd0, 0xbb, 0x21, 0x51, 0x0a, 0xec, 0xcf, 0x11, 0x2b,
+ 0xab, 0x32, 0x0a, 0x96, 0x57, 0xe1, 0x17, 0x08, 0x96, 0x65, 0x29, 0xc0, 0xf7, 0x23, 0xb2, 0x14,
+ 0xf0, 0x5f, 0x22, 0x3c, 0xac, 0xcb, 0x69, 0x82, 0x6c, 0xff, 0x57, 0x48, 0x08, 0x0b, 0x53, 0x10,
+ 0x02, 0x61, 0x3a, 0xc2, 0x89, 0x16, 0x6e, 0xea, 0x8a, 0x2f, 0x4c, 0xcf, 0xb3, 0xca, 0xc2, 0xf4,
+ 0x81, 0xb7, 0x28, 0x6a, 0x08, 0x61, 0x4e, 0x21, 0x6b, 0xd5, 0x00, 0xa9, 0xeb, 0x4a, 0x20, 0x4c,
+ 0x1f, 0x19, 0x12, 0xa6, 0x8f, 0xbd, 0xad, 0x2b, 0xb2, 0x30, 0x67, 0xa0, 0x65, 0xcb, 0x45, 0x5d,
+ 0x91, 0x85, 0xe9, 0xa3, 0x65, 0x61, 0xfa, 0xe0, 0x0f, 0x75, 0x45, 0x12, 0xe6, 0x34, 0x56, 0x36,
+ 0xfc, 0x1d, 0x5d, 0x91, 0x84, 0x19, 0x9e, 0x1d, 0x17, 0xa6, 0x0f, 0xfd, 0x48, 0x57, 0x02, 0x61,
+ 0x86, 0xad, 0x0a, 0x61, 0xfa, 0xd0, 0xef, 0xea, 0x8a, 0x24, 0xcc, 0x30, 0x56, 0x08, 0xd3, 0xc7,
+ 0x7e, 0x8f, 0x42, 0xb5, 0x27, 0x4c, 0x1f, 0x2b, 0x09, 0xd3, 0x87, 0xfe, 0x0c, 0xc3, 0xba, 0x2f,
+ 0x4c, 0x1f, 0x2a, 0x0b, 0xd3, 0xc7, 0xfe, 0x39, 0x62, 0x03, 0x61, 0x4e, 0x83, 0xe5, 0x55, 0xf8,
+ 0x0b, 0x04, 0x07, 0xc2, 0xf4, 0xc1, 0x61, 0x61, 0xfa, 0xf0, 0xbf, 0x44, 0xb8, 0x2c, 0xcc, 0x59,
+ 0x04, 0xd9, 0xfe, 0x5f, 0x21, 0x41, 0x16, 0xa6, 0x4f, 0x28, 0xd3, 0x34, 0x51, 0x98, 0x6d, 0xab,
+ 0x63, 0x4e, 0xfa, 0x28, 0xe3, 0x12, 0x2a, 0xb3, 0x1e, 0x77, 0x47, 0x13, 0x0b, 0xe7, 0xea, 0x38,
+ 0xfd, 0x17, 0x5e, 0x1b, 0x2b, 0xe3, 0xf0, 0xb9, 0x40, 0x03, 0xc2, 0xc7, 0xa8, 0xd0, 0xba, 0xba,
+ 0x5a, 0x31, 0xf2, 0x5c, 0xa5, 0xd3, 0xf8, 0x5a, 0x55, 0xc2, 0xdf, 0x41, 0x9d, 0xd6, 0xd5, 0x5a,
+ 0x95, 0xe3, 0x6b, 0xd5, 0x00, 0xbf, 0x8a, 0x13, 0xf0, 0xc4, 0x1a, 0x30, 0xee, 0xa2, 0x5a, 0xeb,
+ 0xb1, 0xd5, 0xca, 0x8a, 0xb1, 0xe0, 0x49, 0x76, 0x16, 0x29, 0xd4, 0xcd, 0x3d, 0x14, 0x6d, 0x3d,
+ 0x56, 0xab, 0xfa, 0x24, 0xb9, 0xa7, 0x0a, 0x0a, 0x5d, 0x48, 0x37, 0xe0, 0x7c, 0x82, 0xda, 0xad,
+ 0xc7, 0x57, 0x2b, 0x2b, 0x2b, 0x86, 0x26, 0x14, 0x3c, 0x83, 0x13, 0xea, 0xa7, 0x8c, 0x1a, 0xae,
+ 0xc7, 0x6b, 0x55, 0x9f, 0x13, 0xee, 0x67, 0xc1, 0x93, 0x72, 0x40, 0xb9, 0x8f, 0x5a, 0xae, 0x27,
+ 0x57, 0x1f, 0x54, 0x1f, 0xac, 0x3d, 0x36, 0xf2, 0x5c, 0xd3, 0x01, 0xa7, 0x8a, 0xfd, 0x08, 0x51,
+ 0x07, 0xa4, 0x15, 0x54, 0x75, 0x3d, 0x59, 0x79, 0xf8, 0xe0, 0x51, 0xe5, 0x91, 0xa1, 0x09, 0x75,
+ 0x07, 0xac, 0xa7, 0xc8, 0x12, 0xf2, 0x0e, 0x58, 0x0f, 0x50, 0xdf, 0x75, 0xed, 0xc8, 0xea, 0xf7,
+ 0x9d, 0x7b, 0x7a, 0xf1, 0x9d, 0x33, 0xea, 0xb7, 0x6f, 0x17, 0xc1, 0xd0, 0x84, 0xe2, 0xe5, 0x5e,
+ 0x17, 0x3c, 0xc9, 0x07, 0xf4, 0x3f, 0xc4, 0xa4, 0x35, 0x57, 0x4f, 0xad, 0xf7, 0xba, 0xb6, 0x33,
+ 0xb6, 0x8c, 0x3c, 0x17, 0x7f, 0x64, 0x4d, 0xf6, 0xa2, 0xeb, 0xf8, 0x47, 0x48, 0x5b, 0xa8, 0xc7,
+ 0x3e, 0x59, 0xad, 0x60, 0x4f, 0xb3, 0xd6, 0x71, 0x2f, 0xba, 0x8e, 0x3f, 0x45, 0x0e, 0xab, 0xc7,
+ 0x3e, 0xa9, 0x55, 0x05, 0x47, 0x5e, 0xc7, 0x1a, 0x2c, 0x4a, 0xef, 0x42, 0xc0, 0xfa, 0x63, 0x64,
+ 0xe5, 0x79, 0x4f, 0xcc, 0x7f, 0x23, 0x66, 0xf2, 0x42, 0xbd, 0xfd, 0x09, 0xf2, 0x34, 0xde, 0x1b,
+ 0xf3, 0x5f, 0x8c, 0x80, 0xf7, 0x10, 0xae, 0x46, 0x72, 0x89, 0xd6, 0xd0, 0x3c, 0x7c, 0x6b, 0xb5,
+ 0x0b, 0x15, 0x4c, 0x29, 0xd6, 0x55, 0x4d, 0x31, 0xde, 0x0b, 0xa5, 0x15, 0xaf, 0xa8, 0x99, 0x3d,
+ 0x86, 0x6b, 0xd1, 0xe4, 0xc2, 0x63, 0xae, 0x62, 0x8e, 0x41, 0xcc, 0xc5, 0x70, 0x9e, 0x11, 0xa1,
+ 0x4a, 0x41, 0xc5, 0xa3, 0x56, 0x31, 0xe9, 0x08, 0xa8, 0x41, 0x6c, 0x11, 0xd4, 0x4f, 0xe1, 0xfa,
+ 0x74, 0xfa, 0xe1, 0x91, 0xd7, 0x30, 0x0b, 0x21, 0xf2, 0xd5, 0x68, 0x26, 0x32, 0x45, 0x9f, 0xd1,
+ 0x77, 0x0d, 0xd3, 0x12, 0x99, 0x3e, 0xd5, 0xfb, 0x13, 0x28, 0x4c, 0x25, 0x28, 0x1e, 0xfb, 0x21,
+ 0xe6, 0x29, 0xc4, 0x7e, 0x3f, 0x92, 0xab, 0x44, 0xc9, 0x33, 0xba, 0x7e, 0x84, 0x89, 0x8b, 0x44,
+ 0x9e, 0xea, 0x99, 0x96, 0x2c, 0x9c, 0xc2, 0x78, 0xdc, 0xc7, 0x98, 0xc9, 0x88, 0x25, 0x0b, 0x65,
+ 0x33, 0x72, 0xbf, 0x91, 0x9c, 0xc6, 0xe3, 0xd6, 0x31, 0xb5, 0x11, 0xfd, 0x86, 0xd3, 0x1b, 0x41,
+ 0xfe, 0x3e, 0x92, 0xf7, 0x66, 0xcf, 0xf8, 0x7f, 0x62, 0x98, 0x94, 0x08, 0xf6, 0xde, 0xac, 0x29,
+ 0xfb, 0xec, 0x19, 0x53, 0xfe, 0x5f, 0x64, 0x33, 0x89, 0x3d, 0x35, 0xe7, 0x1f, 0xc0, 0xd2, 0x8c,
+ 0x7c, 0xc5, 0xe3, 0xff, 0x1f, 0xf2, 0xf3, 0xc4, 0xbf, 0x36, 0x95, 0xba, 0x4c, 0x5b, 0x98, 0x31,
+ 0x82, 0xff, 0x47, 0x0b, 0x5a, 0xc8, 0xc2, 0xd4, 0x18, 0x36, 0x61, 0xce, 0xcb, 0xc7, 0xbb, 0x23,
+ 0x67, 0x32, 0x2c, 0x34, 0x74, 0xb5, 0x04, 0x95, 0xdb, 0xb3, 0x4e, 0xc8, 0x5e, 0x7e, 0xbe, 0x89,
+ 0x40, 0x23, 0xcc, 0xe3, 0x86, 0xb8, 0x69, 0x6e, 0xe8, 0x95, 0x1e, 0x3b, 0xdd, 0x10, 0x07, 0xfa,
+ 0x86, 0x24, 0x1e, 0x1a, 0xf2, 0x02, 0x1e, 0x37, 0xf4, 0x46, 0x57, 0x4e, 0x33, 0xe4, 0xc5, 0x3f,
+ 0x61, 0x28, 0xc4, 0x5b, 0x5a, 0x0b, 0x4e, 0xe6, 0xd4, 0xce, 0xbe, 0x13, 0x3d, 0xaa, 0x6f, 0xd2,
+ 0x01, 0x2b, 0x5c, 0xc9, 0x69, 0xd2, 0xf8, 0xa6, 0x69, 0x3f, 0x3c, 0x85, 0x16, 0x1a, 0xcd, 0x34,
+ 0xed, 0x47, 0x33, 0x68, 0xc5, 0x3f, 0x55, 0x20, 0xfe, 0xd9, 0xd6, 0xee, 0x0b, 0x96, 0x86, 0xf8,
+ 0xe7, 0xcd, 0xad, 0x17, 0xda, 0x15, 0x7c, 0x5a, 0x6f, 0x36, 0xb7, 0x35, 0x85, 0x65, 0x20, 0xb1,
+ 0xfe, 0xe5, 0xfe, 0xc6, 0x9e, 0xa6, 0xb2, 0x3c, 0x64, 0x1b, 0x5b, 0xbb, 0x9b, 0x1b, 0xc6, 0x2b,
+ 0x63, 0x6b, 0x77, 0x5f, 0x8b, 0x61, 0x5b, 0x63, 0xbb, 0xf9, 0x6c, 0x5f, 0x8b, 0xb3, 0x14, 0xc4,
+ 0xb0, 0x2e, 0xc1, 0x00, 0x92, 0x7b, 0xfb, 0xc6, 0xd6, 0xee, 0xa6, 0x96, 0x44, 0x2b, 0xfb, 0x5b,
+ 0x3b, 0x1b, 0x5a, 0x0a, 0x91, 0xfb, 0xaf, 0x5f, 0x6d, 0x6f, 0x68, 0x69, 0x7c, 0x7c, 0x66, 0x18,
+ 0xcf, 0xbe, 0xd4, 0x32, 0x48, 0xda, 0x79, 0xf6, 0x4a, 0x03, 0x6a, 0x7e, 0xb6, 0xbe, 0xbd, 0xa1,
+ 0x65, 0x59, 0x0e, 0xd2, 0x8d, 0xd7, 0xbb, 0xcf, 0xf7, 0xb7, 0x9a, 0xbb, 0x5a, 0xae, 0xf8, 0xbb,
+ 0x50, 0xe0, 0xcb, 0x1c, 0x5a, 0x45, 0x7e, 0x6b, 0xf0, 0x0c, 0x12, 0x7c, 0x73, 0x14, 0x92, 0xcb,
+ 0xdd, 0x19, 0x9b, 0x33, 0xcd, 0x2a, 0xf3, 0x6d, 0xe2, 0xcc, 0xa5, 0x1b, 0x90, 0xe0, 0x0b, 0xb5,
+ 0x08, 0x09, 0xbe, 0x40, 0x2a, 0x5d, 0x27, 0xf0, 0x42, 0xf1, 0xcf, 0x54, 0x80, 0x4d, 0x67, 0xef,
+ 0x6d, 0x6f, 0x48, 0x17, 0x38, 0x37, 0x00, 0xc6, 0x6f, 0x7b, 0xc3, 0x16, 0xbd, 0x85, 0xe2, 0xe2,
+ 0x21, 0x83, 0x35, 0xe4, 0x7f, 0xd9, 0x6d, 0xc8, 0x51, 0xb3, 0x78, 0x4d, 0xe8, 0xbe, 0x21, 0x65,
+ 0x64, 0xb1, 0x4e, 0x38, 0xca, 0x30, 0xa4, 0x56, 0xa5, 0x6b, 0x86, 0xa4, 0x04, 0xa9, 0x55, 0xd9,
+ 0x2d, 0xa0, 0x62, 0x6b, 0x4c, 0x11, 0x95, 0xae, 0x16, 0x32, 0x06, 0xf5, 0xcb, 0x63, 0x2c, 0xfb,
+ 0x2d, 0xa0, 0x3e, 0xf9, 0xd4, 0xf3, 0x33, 0xdf, 0x14, 0x6f, 0xc4, 0x65, 0x7c, 0xe0, 0x13, 0x0e,
+ 0x38, 0x4b, 0x4d, 0xc8, 0xf8, 0xf5, 0xd8, 0x1d, 0xd5, 0x8a, 0x49, 0x69, 0x34, 0x29, 0xa0, 0x2a,
+ 0x7f, 0x56, 0x1c, 0x20, 0x06, 0xb4, 0x40, 0x03, 0xe2, 0x24, 0x3e, 0xa2, 0xe2, 0x0d, 0x98, 0xdb,
+ 0x75, 0x6c, 0xfe, 0x32, 0xd3, 0x42, 0xe5, 0x40, 0x31, 0x0b, 0x0a, 0x1d, 0x82, 0x15, 0xb3, 0x78,
+ 0x13, 0x40, 0x6a, 0xd3, 0x40, 0x39, 0xe0, 0x6d, 0xe4, 0x14, 0x94, 0x83, 0xe2, 0x5d, 0x48, 0xee,
+ 0x98, 0xc7, 0xfb, 0x66, 0x97, 0xdd, 0x06, 0xe8, 0x9b, 0x63, 0xb7, 0xd5, 0xa1, 0xad, 0xf8, 0xf6,
+ 0xdb, 0x6f, 0xbf, 0x55, 0x28, 0xa3, 0xce, 0x60, 0x2d, 0xdf, 0x12, 0x17, 0xa0, 0xd9, 0x6f, 0xef,
+ 0x58, 0xe3, 0xb1, 0xd9, 0xb5, 0x58, 0x0d, 0x92, 0xb6, 0x35, 0xc6, 0x10, 0xac, 0xd0, 0x8d, 0xd3,
+ 0xcd, 0xd0, 0x42, 0x04, 0xc0, 0xf2, 0x2e, 0xa1, 0x0c, 0x81, 0x66, 0x1a, 0xc4, 0xec, 0xc9, 0x80,
+ 0xae, 0xd6, 0x12, 0x06, 0x3e, 0x2e, 0x7d, 0x00, 0x49, 0x8e, 0x61, 0x0c, 0xe2, 0xb6, 0x39, 0xb0,
+ 0x0a, 0xbc, 0x6b, 0x7a, 0x2e, 0xfe, 0x54, 0x01, 0xd8, 0xb5, 0xde, 0x5d, 0xac, 0xdb, 0x00, 0x78,
+ 0x46, 0xb7, 0x31, 0xde, 0xed, 0x93, 0xb3, 0xba, 0x45, 0xc1, 0x75, 0x1c, 0xa7, 0xdd, 0xe2, 0x7b,
+ 0xcd, 0x2f, 0x02, 0x33, 0x58, 0x43, 0x7b, 0x57, 0x7c, 0x03, 0xb9, 0x2d, 0xdb, 0xb6, 0x46, 0xde,
+ 0xb0, 0x18, 0xc4, 0x8f, 0x9c, 0xb1, 0x2b, 0x2e, 0x25, 0xe9, 0x99, 0x15, 0x20, 0x3e, 0x74, 0x46,
+ 0x2e, 0x9f, 0x6a, 0x3d, 0x5e, 0x5d, 0x59, 0x59, 0x31, 0xa8, 0x86, 0x7d, 0x00, 0x99, 0x43, 0xc7,
+ 0xb6, 0xad, 0x43, 0x9c, 0x47, 0x8c, 0x4e, 0x90, 0x41, 0x45, 0xf1, 0xf7, 0x15, 0xc8, 0x35, 0xdd,
+ 0xa3, 0xc0, 0xb8, 0x06, 0xb1, 0xb7, 0xd6, 0x09, 0x0d, 0x2f, 0x66, 0xe0, 0x23, 0xbe, 0x33, 0x3f,
+ 0x31, 0xfb, 0x13, 0x7e, 0x43, 0x99, 0x33, 0x78, 0x81, 0x5d, 0x85, 0xe4, 0x3b, 0xab, 0xd7, 0x3d,
+ 0x72, 0xc9, 0xa6, 0x6a, 0x88, 0x12, 0xbb, 0x0f, 0x89, 0x1e, 0x0e, 0xb6, 0x10, 0xa7, 0x25, 0xbb,
+ 0x1e, 0x5a, 0x32, 0x79, 0x1a, 0x06, 0xc7, 0xdd, 0x49, 0xa7, 0xdb, 0xda, 0xd7, 0x5f, 0x7f, 0xfd,
+ 0xb5, 0x5a, 0xec, 0xc1, 0xa2, 0xf7, 0x22, 0x87, 0xe6, 0xfb, 0x43, 0x28, 0xf4, 0x2d, 0xa7, 0xd5,
+ 0xe9, 0xd9, 0x66, 0xbf, 0x7f, 0xd2, 0x7a, 0xe7, 0xd8, 0x2d, 0xd3, 0x6e, 0x39, 0xe3, 0x43, 0x73,
+ 0x44, 0x6b, 0x70, 0x66, 0x2f, 0x8b, 0x7d, 0xcb, 0x69, 0x70, 0xe6, 0x17, 0x8e, 0xfd, 0xcc, 0x6e,
+ 0x22, 0xad, 0xf8, 0x1f, 0x71, 0xc8, 0xec, 0x9c, 0x78, 0x1d, 0x2c, 0x42, 0xe2, 0xd0, 0x99, 0xd8,
+ 0x7c, 0x45, 0x13, 0x06, 0x2f, 0xf8, 0x3b, 0xa5, 0x4a, 0x3b, 0xb5, 0x08, 0x89, 0xaf, 0x26, 0x8e,
+ 0x6b, 0xd1, 0xa4, 0x33, 0x06, 0x2f, 0xe0, 0x9a, 0x0d, 0x2d, 0xb7, 0x10, 0xa7, 0xfb, 0x0a, 0x7c,
+ 0x0c, 0x56, 0x21, 0x71, 0xb1, 0x55, 0x60, 0x0f, 0x20, 0xe9, 0xe0, 0x36, 0x8c, 0x0b, 0x49, 0xba,
+ 0x93, 0x0d, 0x33, 0xe4, 0x1d, 0x32, 0x04, 0x90, 0x6d, 0xc3, 0xc2, 0x3b, 0xab, 0x35, 0x98, 0x8c,
+ 0xdd, 0x56, 0xd7, 0x69, 0xb5, 0x2d, 0x6b, 0x68, 0x8d, 0x0a, 0x73, 0xd4, 0x5f, 0xd8, 0x51, 0xcc,
+ 0x5a, 0x54, 0x63, 0xfe, 0x9d, 0xb5, 0x33, 0x19, 0xbb, 0x9b, 0xce, 0x0b, 0x22, 0xb2, 0x1a, 0x64,
+ 0x46, 0x16, 0xba, 0x07, 0x1c, 0x75, 0x6e, 0xc6, 0x18, 0x42, 0xec, 0xf4, 0xc8, 0x1a, 0x52, 0x05,
+ 0x7b, 0x04, 0xe9, 0x83, 0xde, 0x5b, 0x6b, 0x7c, 0x64, 0xb5, 0x0b, 0x29, 0x5d, 0x29, 0xcd, 0x57,
+ 0x3e, 0x08, 0xd1, 0xfc, 0x55, 0x2e, 0x3f, 0x77, 0xfa, 0xce, 0xc8, 0xf0, 0xd1, 0xec, 0x29, 0x64,
+ 0xc6, 0xce, 0xc0, 0xe2, 0xa2, 0x4f, 0x53, 0xe0, 0xd5, 0x4f, 0xa1, 0xee, 0x39, 0x03, 0xcb, 0xf3,
+ 0x6f, 0x1e, 0x85, 0x2d, 0xf3, 0x11, 0x1f, 0xe0, 0xd9, 0xa2, 0x00, 0x74, 0xff, 0x83, 0xc3, 0xa2,
+ 0xb3, 0x06, 0x5b, 0xc2, 0x61, 0x75, 0x3b, 0x98, 0xc2, 0x15, 0xb2, 0x74, 0xb4, 0xf7, 0xcb, 0x4b,
+ 0xf7, 0x20, 0xe3, 0x1b, 0x0c, 0x1c, 0x23, 0x77, 0x46, 0x19, 0x72, 0x15, 0xdc, 0x31, 0x72, 0x4f,
+ 0xf4, 0x11, 0x24, 0x68, 0xe4, 0x18, 0xc5, 0x8c, 0x0d, 0x0c, 0x9a, 0x19, 0x48, 0x6c, 0x1a, 0x1b,
+ 0x1b, 0xbb, 0x9a, 0x42, 0xf1, 0x73, 0xfb, 0xf5, 0x86, 0xa6, 0x4a, 0x32, 0xfe, 0x99, 0x0a, 0xb1,
+ 0x8d, 0x63, 0xd2, 0x4f, 0xdb, 0x74, 0x4d, 0xef, 0x4d, 0xc7, 0x67, 0xf6, 0x04, 0x32, 0x03, 0xd3,
+ 0xeb, 0x4b, 0xa5, 0x55, 0x0e, 0x3b, 0x95, 0x8d, 0x63, 0xb7, 0xbc, 0x63, 0xf2, 0xae, 0x37, 0x6c,
+ 0x77, 0x74, 0x62, 0xa4, 0x07, 0xa2, 0xb8, 0xf4, 0x04, 0xe6, 0x42, 0x4d, 0xf2, 0xbb, 0x9a, 0x98,
+ 0xf1, 0xae, 0x26, 0xc4, 0xbb, 0x5a, 0x57, 0x1f, 0x29, 0x95, 0xef, 0x43, 0x7c, 0xe0, 0x8c, 0x2c,
+ 0x76, 0x75, 0xf6, 0x12, 0x17, 0xba, 0x24, 0x1c, 0x2d, 0x3a, 0x18, 0x83, 0x58, 0x95, 0x3b, 0x10,
+ 0x77, 0xad, 0x63, 0xf7, 0x54, 0xf6, 0x11, 0x9f, 0x23, 0x62, 0x2a, 0x65, 0x48, 0xda, 0x93, 0xc1,
+ 0x81, 0x35, 0x3a, 0x15, 0xdd, 0xa3, 0xc1, 0x09, 0x54, 0xf1, 0x73, 0xd0, 0x9e, 0x3b, 0x83, 0x61,
+ 0xdf, 0x3a, 0xde, 0x38, 0x76, 0x2d, 0x7b, 0xdc, 0x73, 0x6c, 0x9c, 0x47, 0xa7, 0x37, 0x22, 0x1f,
+ 0x47, 0xf3, 0xa0, 0x02, 0xfa, 0x9c, 0xb1, 0x75, 0xe8, 0xd8, 0x6d, 0x31, 0x3d, 0x51, 0x42, 0xb4,
+ 0x7b, 0xd4, 0x1b, 0xa1, 0x7b, 0xc3, 0x58, 0xc4, 0x0b, 0xc5, 0x4d, 0xc8, 0x8b, 0xa3, 0xd9, 0x58,
+ 0x74, 0x5c, 0xbc, 0x03, 0x39, 0xaf, 0x8a, 0x7e, 0x12, 0x4a, 0x43, 0xfc, 0xcd, 0x86, 0xd1, 0xd4,
+ 0xae, 0xe0, 0xe6, 0x36, 0x77, 0x37, 0x34, 0x05, 0x1f, 0xf6, 0xbf, 0x68, 0x86, 0x36, 0x34, 0x05,
+ 0x89, 0x8d, 0xc1, 0xd0, 0x3d, 0x29, 0xfe, 0x1e, 0x64, 0x85, 0xa5, 0xed, 0xde, 0xd8, 0x65, 0x75,
+ 0x48, 0x0d, 0xc4, 0x8c, 0x14, 0x4a, 0x40, 0x23, 0xf2, 0x0d, 0xa0, 0xde, 0xb3, 0xe1, 0x11, 0x96,
+ 0x56, 0x21, 0x25, 0xb9, 0x73, 0xe1, 0x67, 0x54, 0xd9, 0xcf, 0x70, 0x8f, 0x14, 0x93, 0x3c, 0x52,
+ 0x71, 0x07, 0x52, 0x3c, 0x14, 0x8f, 0x29, 0xc3, 0xe0, 0xc7, 0x76, 0xae, 0x25, 0x2e, 0xb2, 0x2c,
+ 0xaf, 0xe3, 0x79, 0xd3, 0x2d, 0xc8, 0xd2, 0xbb, 0xe1, 0xab, 0x0d, 0xbd, 0x37, 0x50, 0x15, 0x57,
+ 0xf6, 0x5f, 0x27, 0x20, 0xed, 0x2d, 0x07, 0x5b, 0x86, 0x24, 0x3f, 0xbb, 0x92, 0x29, 0xef, 0x2e,
+ 0x27, 0x41, 0xa7, 0x55, 0xb6, 0x0c, 0x29, 0x71, 0x3e, 0x15, 0x01, 0x46, 0x5d, 0xad, 0x18, 0x49,
+ 0x7e, 0x1e, 0xf5, 0x1b, 0x6b, 0x55, 0xf2, 0x8a, 0xfc, 0x96, 0x26, 0xc9, 0x4f, 0x9c, 0x4c, 0x87,
+ 0x8c, 0x7f, 0xc6, 0xa4, 0x90, 0x20, 0xae, 0x64, 0xd2, 0xde, 0xa1, 0x52, 0x42, 0xd4, 0xaa, 0xe4,
+ 0x2e, 0xc5, 0xfd, 0x4b, 0xba, 0x11, 0xa4, 0x4a, 0x69, 0xef, 0xa4, 0x48, 0xbf, 0x38, 0x79, 0x97,
+ 0x2d, 0x29, 0x71, 0x36, 0x0c, 0x00, 0xb5, 0x2a, 0xf9, 0x20, 0xef, 0x66, 0x25, 0x25, 0xce, 0x7f,
+ 0xec, 0x16, 0x0e, 0x91, 0xce, 0x73, 0xe4, 0x68, 0x82, 0x6b, 0x94, 0x24, 0x3f, 0xe5, 0xb1, 0xdb,
+ 0x68, 0x81, 0x1f, 0xda, 0xc8, 0x05, 0x04, 0x77, 0x26, 0x29, 0x71, 0x96, 0x63, 0x77, 0x11, 0xc2,
+ 0x97, 0xbf, 0x00, 0xa7, 0x5c, 0x90, 0xa4, 0xc4, 0x05, 0x09, 0xd3, 0xb1, 0x43, 0xf2, 0x44, 0xe4,
+ 0x7d, 0xa4, 0xcb, 0x90, 0x24, 0xbf, 0x0c, 0x61, 0x37, 0xc9, 0x1c, 0x9f, 0x54, 0x2e, 0xb8, 0xf8,
+ 0x48, 0x89, 0xc3, 0x5f, 0xd0, 0x4e, 0xe9, 0xa3, 0x7f, 0xc9, 0x91, 0x12, 0xc7, 0x3b, 0xf6, 0x18,
+ 0xf7, 0x0b, 0x45, 0x5c, 0x98, 0x27, 0xaf, 0xbb, 0x1c, 0xd2, 0x9e, 0xb7, 0xad, 0xdc, 0xe9, 0xd6,
+ 0xb9, 0xbf, 0x32, 0x12, 0x0d, 0x52, 0xfd, 0x12, 0x52, 0x5f, 0xf5, 0xec, 0x4e, 0x21, 0x4f, 0x8b,
+ 0x11, 0xeb, 0xd9, 0x1d, 0x23, 0xd1, 0xc0, 0x1a, 0x2e, 0x83, 0x5d, 0x6c, 0xd3, 0xa8, 0x2d, 0xfe,
+ 0x09, 0x6f, 0xc4, 0x2a, 0x56, 0x80, 0x44, 0xa3, 0xb5, 0x6b, 0xda, 0x85, 0x05, 0xce, 0xb3, 0x4d,
+ 0xdb, 0x88, 0x37, 0x76, 0x4d, 0x9b, 0xdd, 0x81, 0xd8, 0x78, 0x72, 0x50, 0x60, 0x33, 0x7e, 0x0f,
+ 0xdc, 0x9b, 0x1c, 0x78, 0xa3, 0x31, 0x10, 0xc4, 0x96, 0x21, 0x3d, 0x76, 0x47, 0xad, 0xdf, 0xb1,
+ 0x46, 0x4e, 0xe1, 0x3d, 0x5a, 0xc8, 0x2b, 0x46, 0x6a, 0xec, 0x8e, 0xde, 0x58, 0x23, 0xe7, 0x82,
+ 0xde, 0xb6, 0x78, 0x13, 0xb2, 0x92, 0x5d, 0x96, 0x07, 0xc5, 0xe6, 0x29, 0x4b, 0x5d, 0x79, 0x68,
+ 0x28, 0x76, 0xf1, 0x0b, 0xc8, 0x79, 0x07, 0x2b, 0x9a, 0xf2, 0x1a, 0xbe, 0x4f, 0x7d, 0x67, 0x44,
+ 0x2f, 0xea, 0x7c, 0xe5, 0x56, 0x24, 0x3e, 0x06, 0x48, 0x11, 0xa5, 0x38, 0xba, 0xa8, 0x45, 0x46,
+ 0xa3, 0x14, 0xff, 0x53, 0x81, 0xdc, 0x8e, 0x33, 0x0a, 0x7e, 0xb9, 0x58, 0x84, 0xc4, 0x81, 0xe3,
+ 0xf4, 0xc7, 0x64, 0x39, 0x6d, 0xf0, 0x02, 0xfb, 0x08, 0x72, 0xf4, 0xe0, 0x1d, 0x8f, 0x55, 0xff,
+ 0xfe, 0x27, 0x4b, 0xf5, 0xe2, 0x44, 0xcc, 0x20, 0xde, 0xb3, 0xdd, 0xb1, 0xf0, 0x5b, 0xf4, 0xcc,
+ 0x3e, 0x84, 0x2c, 0xfe, 0xf5, 0x98, 0x71, 0x3f, 0x85, 0x06, 0xac, 0x16, 0xc4, 0xef, 0xc1, 0x1c,
+ 0xc9, 0xc0, 0x87, 0xa5, 0xfc, 0xbb, 0x9e, 0x1c, 0x6f, 0x10, 0xc0, 0x02, 0xa4, 0xb8, 0x4f, 0x18,
+ 0xd3, 0x8f, 0xbd, 0x19, 0xc3, 0x2b, 0xa2, 0x33, 0xa5, 0xe3, 0x09, 0xcf, 0x38, 0x52, 0x86, 0x28,
+ 0x15, 0x5f, 0x40, 0x9a, 0x22, 0x63, 0xb3, 0xdf, 0x66, 0x1f, 0x81, 0xd2, 0x2d, 0x58, 0x14, 0x9a,
+ 0xaf, 0x85, 0xcf, 0x1e, 0x02, 0x51, 0xde, 0x34, 0x94, 0xee, 0xd2, 0x02, 0x28, 0x9b, 0x78, 0x18,
+ 0x38, 0x16, 0x7e, 0x59, 0x39, 0x2e, 0x1a, 0xc2, 0xca, 0xae, 0xf5, 0xee, 0x1c, 0x2b, 0xbb, 0xd6,
+ 0x3b, 0x6e, 0xe5, 0xd6, 0x94, 0x15, 0x2c, 0x9d, 0x88, 0x9f, 0xc0, 0x95, 0x93, 0xe2, 0x2a, 0xcc,
+ 0xd1, 0xdb, 0xda, 0xb3, 0xbb, 0xaf, 0x9c, 0x9e, 0x4d, 0xe7, 0x8f, 0x0e, 0xe5, 0x6c, 0x8a, 0xa1,
+ 0x74, 0x70, 0x27, 0xac, 0x63, 0xf3, 0x90, 0xe7, 0xc0, 0x69, 0x83, 0x17, 0x8a, 0xff, 0x15, 0x87,
+ 0x79, 0xe1, 0x69, 0xbf, 0xe8, 0xb9, 0x47, 0x3b, 0xe6, 0x90, 0x35, 0x21, 0x87, 0x4e, 0xb6, 0x35,
+ 0x30, 0x87, 0x43, 0x7c, 0x9b, 0x15, 0x8a, 0xc3, 0xf7, 0x66, 0x39, 0x6f, 0x41, 0x29, 0xef, 0x9a,
+ 0x03, 0x6b, 0x87, 0xc3, 0x79, 0x54, 0xce, 0xda, 0x41, 0x0d, 0xdb, 0x86, 0xec, 0x60, 0xdc, 0xf5,
+ 0xed, 0xf1, 0xb8, 0x7e, 0xf7, 0x2c, 0x7b, 0x3b, 0xe3, 0x6e, 0xc8, 0x1c, 0x0c, 0xfc, 0x0a, 0x1c,
+ 0x1e, 0x3a, 0x69, 0xdf, 0x5c, 0xec, 0xfc, 0xe1, 0xa1, 0x4b, 0x09, 0x0f, 0xef, 0x20, 0xa8, 0x61,
+ 0x9b, 0x00, 0xf8, 0xc2, 0xb9, 0x0e, 0x9e, 0xed, 0x48, 0x50, 0xd9, 0xca, 0xc7, 0x67, 0x99, 0xdb,
+ 0x73, 0x47, 0xfb, 0xce, 0x9e, 0x3b, 0x12, 0x09, 0xc8, 0x58, 0x14, 0x97, 0x9e, 0x82, 0x16, 0x5d,
+ 0x88, 0xf3, 0x72, 0x90, 0x8c, 0x94, 0x83, 0x2c, 0x7d, 0x09, 0xf9, 0xc8, 0xc4, 0x65, 0x3a, 0xe3,
+ 0xf4, 0x15, 0x99, 0x9e, 0xad, 0x2c, 0x85, 0x3f, 0xd4, 0x90, 0xf7, 0x5f, 0x36, 0xfd, 0x14, 0xb4,
+ 0xe8, 0x22, 0xc8, 0xb6, 0xd3, 0x67, 0x1c, 0x65, 0x88, 0xff, 0x04, 0xe6, 0x42, 0xb3, 0x96, 0xc9,
+ 0x99, 0x73, 0xe6, 0x55, 0xfc, 0x83, 0x04, 0x24, 0x9a, 0xb6, 0xe5, 0x74, 0xd8, 0xb5, 0x70, 0x14,
+ 0x7d, 0x79, 0xc5, 0x8b, 0xa0, 0xd7, 0x23, 0x11, 0xf4, 0xe5, 0x15, 0x3f, 0x7e, 0x5e, 0x8f, 0xc4,
+ 0x4f, 0xaf, 0xa9, 0x56, 0x65, 0x37, 0xa6, 0xa2, 0xe7, 0xcb, 0x2b, 0x52, 0xe8, 0xbc, 0x31, 0x15,
+ 0x3a, 0x83, 0xe6, 0x5a, 0x15, 0x1d, 0x6d, 0x38, 0x6e, 0xbe, 0xbc, 0x12, 0xc4, 0xcc, 0xe5, 0x68,
+ 0xcc, 0xf4, 0x1b, 0x6b, 0x55, 0x3e, 0x24, 0x29, 0x5e, 0xd2, 0x90, 0x78, 0xa4, 0x5c, 0x8e, 0x46,
+ 0x4a, 0xe2, 0x89, 0x18, 0xb9, 0x1c, 0x8d, 0x91, 0xd4, 0x28, 0x62, 0xe2, 0xf5, 0x48, 0x4c, 0x24,
+ 0xa3, 0x3c, 0x18, 0x2e, 0x47, 0x83, 0x21, 0xe7, 0x49, 0x23, 0x95, 0x23, 0xa1, 0xdf, 0x58, 0xab,
+ 0xb2, 0xb5, 0x48, 0x18, 0x3c, 0xf3, 0xf0, 0x41, 0xdb, 0x41, 0xf1, 0xe0, 0x21, 0xae, 0x9c, 0x97,
+ 0x8e, 0xe6, 0xcf, 0xfe, 0x8a, 0x85, 0xd6, 0xd4, 0x4b, 0xd6, 0xd6, 0x20, 0xd5, 0x11, 0xe7, 0x74,
+ 0x8d, 0x3c, 0x5a, 0x58, 0x9f, 0xa4, 0x82, 0x72, 0xa3, 0x45, 0x9e, 0x0d, 0x27, 0xd8, 0xe1, 0xa7,
+ 0x8c, 0x12, 0xcc, 0x35, 0x5a, 0xdb, 0xe6, 0xa8, 0x6b, 0x8d, 0xdd, 0xd6, 0xbe, 0xd9, 0xf5, 0x2f,
+ 0x3d, 0x50, 0x08, 0xd9, 0x86, 0x68, 0xd9, 0x37, 0xbb, 0xec, 0xaa, 0xa7, 0xb2, 0x36, 0xb5, 0x2a,
+ 0x42, 0x67, 0x4b, 0xd7, 0x70, 0xf5, 0xb8, 0x31, 0xf2, 0x91, 0x0b, 0xc2, 0x47, 0xae, 0xa7, 0x20,
+ 0x31, 0xb1, 0x7b, 0x8e, 0xbd, 0x9e, 0x81, 0x94, 0xeb, 0x8c, 0x06, 0xa6, 0xeb, 0x14, 0xff, 0x5b,
+ 0x01, 0x78, 0xee, 0x0c, 0x06, 0x13, 0xbb, 0xf7, 0xd5, 0xc4, 0x62, 0x37, 0x21, 0x3b, 0x30, 0xdf,
+ 0x5a, 0xad, 0x81, 0xd5, 0x3a, 0x1c, 0x79, 0x2f, 0x44, 0x06, 0xab, 0x76, 0xac, 0xe7, 0xa3, 0x13,
+ 0x56, 0xf0, 0x32, 0x76, 0x12, 0x11, 0x69, 0x53, 0x64, 0xf0, 0x8b, 0x22, 0x37, 0x4d, 0x8a, 0xcd,
+ 0xf4, 0xb2, 0x53, 0x7e, 0xb2, 0x49, 0x89, 0x6d, 0xe4, 0x67, 0x9b, 0x6b, 0x90, 0x74, 0xad, 0xc1,
+ 0xb0, 0x75, 0x48, 0x9a, 0x41, 0x5d, 0x24, 0xb0, 0xfc, 0x9c, 0xad, 0x40, 0xec, 0xd0, 0xe9, 0x93,
+ 0x5a, 0xce, 0xdf, 0x20, 0x84, 0xb2, 0x12, 0xc4, 0x06, 0x63, 0x2e, 0xa1, 0x6c, 0x65, 0x31, 0x9c,
+ 0x4e, 0xf0, 0xf0, 0x85, 0xc8, 0xc1, 0xb8, 0xeb, 0xcf, 0xbe, 0xf8, 0x6b, 0x15, 0xd2, 0xb8, 0x65,
+ 0xaf, 0xf7, 0x1b, 0x8f, 0xe8, 0xa0, 0x70, 0x68, 0xf6, 0xe9, 0x7e, 0x00, 0xdf, 0x55, 0x51, 0xc2,
+ 0xfa, 0x9f, 0x58, 0x87, 0xae, 0x33, 0x22, 0x1f, 0x9d, 0x31, 0x44, 0x09, 0x17, 0x9d, 0x27, 0xc9,
+ 0x31, 0x31, 0x4f, 0x5e, 0xa4, 0x0c, 0xdf, 0x1c, 0xb6, 0xd0, 0x11, 0x70, 0xb7, 0x19, 0x3e, 0x58,
+ 0x7b, 0xfd, 0xe1, 0x89, 0xed, 0x33, 0xeb, 0x84, 0xbb, 0xcb, 0xe4, 0x80, 0x0a, 0xec, 0x07, 0xfc,
+ 0xa8, 0xc7, 0x37, 0x93, 0x7f, 0x68, 0xf5, 0xe1, 0xa9, 0xec, 0xcf, 0x11, 0x15, 0x9c, 0xf7, 0xa8,
+ 0xb8, 0xf4, 0x18, 0xb2, 0x92, 0xe1, 0xf3, 0x3c, 0x52, 0x2c, 0xe2, 0xce, 0x42, 0x56, 0xcf, 0xbb,
+ 0xd6, 0x91, 0xdd, 0x19, 0xae, 0xa9, 0x83, 0x3a, 0xbe, 0x93, 0x87, 0x58, 0xa3, 0xd9, 0xc4, 0xb4,
+ 0xab, 0xd1, 0x6c, 0x3e, 0xd0, 0x94, 0x7a, 0x05, 0xd2, 0xdd, 0x91, 0x65, 0xa1, 0x07, 0x3e, 0xf5,
+ 0x70, 0xf7, 0x63, 0x5a, 0x59, 0x1f, 0x57, 0xdf, 0x83, 0xd4, 0x21, 0x3f, 0xde, 0xb1, 0xd3, 0x2f,
+ 0x35, 0x0a, 0x7f, 0xcb, 0x6f, 0xd8, 0x6e, 0x84, 0x10, 0xd1, 0x63, 0xa1, 0xe1, 0x59, 0xaa, 0x7f,
+ 0x0e, 0x99, 0x51, 0xeb, 0x02, 0x66, 0xbf, 0xe1, 0xb1, 0xfd, 0x1c, 0xb3, 0xe9, 0x91, 0xa8, 0xaa,
+ 0xbf, 0x84, 0x05, 0xdb, 0xf1, 0x7e, 0xf1, 0x6b, 0xb5, 0xb9, 0x57, 0xfb, 0x60, 0x66, 0x6a, 0xed,
+ 0x75, 0x61, 0xf1, 0x0f, 0x07, 0x6c, 0x47, 0x34, 0x70, 0x57, 0x58, 0x6f, 0x80, 0x26, 0x59, 0xa2,
+ 0x8b, 0x87, 0x73, 0x0c, 0x75, 0xf8, 0xc7, 0x0a, 0xbe, 0x21, 0xf2, 0xb7, 0x11, 0x3b, 0xdc, 0x23,
+ 0x9e, 0x6d, 0xa7, 0xcb, 0x3f, 0xfe, 0xf0, 0xed, 0x50, 0x94, 0x99, 0xb6, 0x53, 0xab, 0x9e, 0x63,
+ 0xe7, 0x88, 0x7f, 0x1a, 0x22, 0xdb, 0xa9, 0x55, 0x23, 0x2b, 0x34, 0xb9, 0xc8, 0x80, 0x7a, 0xfc,
+ 0xe3, 0x0e, 0xdf, 0x10, 0x8f, 0x40, 0x33, 0x2c, 0x9d, 0x3b, 0xa4, 0x1f, 0xf3, 0x4f, 0x3f, 0x42,
+ 0x96, 0xa6, 0xc6, 0x34, 0xbe, 0xc8, 0x98, 0xde, 0xf2, 0x4f, 0x2d, 0x7c, 0x4b, 0x7b, 0xb3, 0xc6,
+ 0x34, 0xbe, 0xc8, 0x98, 0xfa, 0xfc, 0x3b, 0x8c, 0x90, 0xa5, 0x5a, 0xb5, 0xfe, 0xdb, 0xc0, 0xe4,
+ 0xfd, 0x17, 0x11, 0xfb, 0x6c, 0x53, 0x03, 0xfe, 0x81, 0x4d, 0xa0, 0x00, 0xce, 0x9a, 0x65, 0xeb,
+ 0xdc, 0x61, 0xd9, 0xfc, 0xf3, 0x9b, 0xb0, 0xad, 0x5a, 0xb5, 0xbe, 0x0d, 0xef, 0xc9, 0x33, 0xbc,
+ 0xd8, 0xc0, 0x1c, 0xfe, 0xf1, 0x48, 0x30, 0x47, 0x41, 0x9b, 0x69, 0xed, 0xdc, 0xa1, 0x0d, 0xf9,
+ 0x97, 0x25, 0x11, 0x6b, 0xb5, 0x6a, 0xfd, 0x05, 0xe4, 0x25, 0x6b, 0x78, 0x50, 0x3a, 0xc7, 0xd2,
+ 0x57, 0xfc, 0x83, 0x28, 0xdf, 0x12, 0xa6, 0x5a, 0xd1, 0x3d, 0xe4, 0xc9, 0xc7, 0xd9, 0x76, 0x46,
+ 0xfc, 0x83, 0x9e, 0x60, 0x44, 0x44, 0x8a, 0xbc, 0x33, 0x74, 0x73, 0x72, 0x8e, 0xa1, 0x31, 0xff,
+ 0xda, 0x27, 0x18, 0x10, 0x72, 0xea, 0x4e, 0x68, 0x5e, 0x16, 0x26, 0x20, 0x67, 0x9b, 0x71, 0x29,
+ 0x54, 0x7e, 0x7c, 0x16, 0xa6, 0x2c, 0x5f, 0x64, 0x49, 0x4b, 0x80, 0xc5, 0xfa, 0x36, 0xcc, 0x5f,
+ 0xca, 0x87, 0x7d, 0xa3, 0xf0, 0x3b, 0x8f, 0xd5, 0xf2, 0x83, 0xea, 0x83, 0x35, 0x63, 0xae, 0x1d,
+ 0x72, 0x65, 0x2f, 0x61, 0xee, 0x32, 0x7e, 0xec, 0xe7, 0x0a, 0xbf, 0x39, 0x40, 0x63, 0x46, 0xae,
+ 0x1d, 0x76, 0x66, 0x73, 0x97, 0xf1, 0x64, 0xbf, 0x50, 0xf8, 0x65, 0x53, 0xb5, 0xe2, 0xdb, 0xf1,
+ 0x9c, 0xd9, 0xdc, 0x65, 0x3c, 0xd9, 0x2f, 0xf9, 0xd5, 0x80, 0x5a, 0x5d, 0x95, 0xed, 0x90, 0xe3,
+ 0x98, 0xbf, 0x94, 0x27, 0xfb, 0x95, 0x42, 0xd7, 0x4f, 0x6a, 0xb5, 0xea, 0xaf, 0x91, 0xef, 0xcc,
+ 0xe6, 0x2f, 0xe5, 0xc9, 0xfe, 0x4e, 0xa1, 0x7b, 0x2a, 0xb5, 0xba, 0x16, 0xb2, 0x14, 0x1e, 0xd3,
+ 0x85, 0x3c, 0xd9, 0xdf, 0x2b, 0x74, 0x7b, 0xa4, 0x56, 0x6b, 0xbe, 0xa5, 0xbd, 0xa9, 0x31, 0x5d,
+ 0xc8, 0x93, 0xfd, 0x03, 0x9d, 0xc2, 0xea, 0x6a, 0xf5, 0x61, 0xc8, 0x12, 0x39, 0xb3, 0xfc, 0xe5,
+ 0x3c, 0xd9, 0xaf, 0x15, 0xba, 0xea, 0x53, 0xab, 0x8f, 0x0c, 0x6f, 0x0c, 0x81, 0x33, 0xcb, 0x5f,
+ 0xce, 0x93, 0xfd, 0xa3, 0x42, 0x97, 0x82, 0x6a, 0xf5, 0x71, 0xd8, 0x16, 0x39, 0x33, 0xed, 0x92,
+ 0x9e, 0xec, 0x9f, 0x14, 0xfa, 0xf4, 0x47, 0x5d, 0x5b, 0x31, 0xbc, 0x61, 0x48, 0xce, 0x4c, 0xbb,
+ 0xa4, 0x27, 0xfb, 0x67, 0x85, 0x3e, 0x08, 0x52, 0xd7, 0x1e, 0x44, 0xac, 0xd5, 0xaa, 0xf5, 0x06,
+ 0xe4, 0x2e, 0xe1, 0xc9, 0xfe, 0x45, 0xbe, 0x75, 0xcd, 0xb6, 0x25, 0x77, 0xf6, 0x23, 0x69, 0x17,
+ 0x2f, 0xe2, 0xcb, 0xfe, 0x95, 0x12, 0xc4, 0xfa, 0xfb, 0x2f, 0xf9, 0xe5, 0x24, 0xe7, 0xdc, 0x6b,
+ 0x5b, 0x9d, 0x4f, 0x3b, 0x8e, 0x13, 0x6c, 0x2c, 0xf7, 0x70, 0xaf, 0x82, 0x17, 0xe9, 0x22, 0xee,
+ 0xed, 0xdf, 0x14, 0xba, 0xcc, 0xcc, 0x09, 0xdb, 0x44, 0xf1, 0x5f, 0x29, 0xee, 0xeb, 0x86, 0xc1,
+ 0xb4, 0x2f, 0xe0, 0xe8, 0xfe, 0x5d, 0xb9, 0xa4, 0xa7, 0xab, 0xc7, 0x9a, 0xbb, 0x1b, 0xfe, 0x02,
+ 0x61, 0xcd, 0xfa, 0xa7, 0x6f, 0x9e, 0x74, 0x7b, 0xee, 0xd1, 0xe4, 0xa0, 0x7c, 0xe8, 0x0c, 0xee,
+ 0x77, 0x9d, 0xbe, 0x69, 0x77, 0xef, 0x93, 0xbd, 0x83, 0x49, 0xe7, 0x7e, 0xcf, 0x76, 0xad, 0x91,
+ 0x6d, 0xf6, 0xe9, 0x1f, 0x44, 0xa8, 0x76, 0x7c, 0x5f, 0xfe, 0xc7, 0x91, 0xdf, 0x04, 0x00, 0x00,
+ 0xff, 0xff, 0x4a, 0x65, 0x66, 0xff, 0x47, 0x32, 0x00, 0x00,
}
diff --git a/vendor/github.com/golang/protobuf/proto/test_proto/test.proto b/vendor/github.com/golang/protobuf/internal/testprotos/proto2_proto/test.proto
similarity index 79%
rename from vendor/github.com/golang/protobuf/proto/test_proto/test.proto
rename to vendor/github.com/golang/protobuf/internal/testprotos/proto2_proto/test.proto
index 22068a959..3b9fe04e2 100644
--- a/vendor/github.com/golang/protobuf/proto/test_proto/test.proto
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/proto2_proto/test.proto
@@ -1,41 +1,14 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
// A feature-rich test file for the protocol compiler and libraries.
syntax = "proto2";
-option go_package = "github.com/golang/protobuf/proto/test_proto";
+option go_package = "github.com/golang/protobuf/internal/testprotos/proto2_proto";
-package test_proto;
+package proto2_test;
enum FOO { FOO1 = 1; };
@@ -361,67 +334,9 @@ extend DefaultsMessage {
optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE];
}
-message MyMessageSet {
- option message_set_wire_format = true;
- extensions 100 to max;
-}
-
message Empty {
}
-extend MyMessageSet {
- optional Empty x201 = 201;
- optional Empty x202 = 202;
- optional Empty x203 = 203;
- optional Empty x204 = 204;
- optional Empty x205 = 205;
- optional Empty x206 = 206;
- optional Empty x207 = 207;
- optional Empty x208 = 208;
- optional Empty x209 = 209;
- optional Empty x210 = 210;
- optional Empty x211 = 211;
- optional Empty x212 = 212;
- optional Empty x213 = 213;
- optional Empty x214 = 214;
- optional Empty x215 = 215;
- optional Empty x216 = 216;
- optional Empty x217 = 217;
- optional Empty x218 = 218;
- optional Empty x219 = 219;
- optional Empty x220 = 220;
- optional Empty x221 = 221;
- optional Empty x222 = 222;
- optional Empty x223 = 223;
- optional Empty x224 = 224;
- optional Empty x225 = 225;
- optional Empty x226 = 226;
- optional Empty x227 = 227;
- optional Empty x228 = 228;
- optional Empty x229 = 229;
- optional Empty x230 = 230;
- optional Empty x231 = 231;
- optional Empty x232 = 232;
- optional Empty x233 = 233;
- optional Empty x234 = 234;
- optional Empty x235 = 235;
- optional Empty x236 = 236;
- optional Empty x237 = 237;
- optional Empty x238 = 238;
- optional Empty x239 = 239;
- optional Empty x240 = 240;
- optional Empty x241 = 241;
- optional Empty x242 = 242;
- optional Empty x243 = 243;
- optional Empty x244 = 244;
- optional Empty x245 = 245;
- optional Empty x246 = 246;
- optional Empty x247 = 247;
- optional Empty x248 = 248;
- optional Empty x249 = 249;
- optional Empty x250 = 250;
-}
-
message MessageList {
repeated group Message = 1 {
required string name = 2;
@@ -560,3 +475,11 @@ message Communique {
Strings msg = 10;
}
}
+
+message TestUTF8 {
+ optional string scalar = 1;
+ repeated string vector = 2;
+ oneof oneof { string field = 3; }
+ map map_key = 4;
+ map map_value = 5;
+}
diff --git a/vendor/github.com/golang/protobuf/internal/testprotos/proto3_proto/test.pb.go b/vendor/github.com/golang/protobuf/internal/testprotos/proto3_proto/test.pb.go
new file mode 100644
index 000000000..0aa2d9d07
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/proto3_proto/test.pb.go
@@ -0,0 +1,579 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: proto3_proto/test.proto
+
+package proto3_proto
+
+import (
+ fmt "fmt"
+ proto2_proto "github.com/golang/protobuf/internal/testprotos/proto2_proto"
+ proto "github.com/golang/protobuf/proto"
+ anypb "google.golang.org/protobuf/types/known/anypb"
+ math "math"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
+
+type Message_Humour int32
+
+const (
+ Message_UNKNOWN Message_Humour = 0
+ Message_PUNS Message_Humour = 1
+ Message_SLAPSTICK Message_Humour = 2
+ Message_BILL_BAILEY Message_Humour = 3
+)
+
+var Message_Humour_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "PUNS",
+ 2: "SLAPSTICK",
+ 3: "BILL_BAILEY",
+}
+
+var Message_Humour_value = map[string]int32{
+ "UNKNOWN": 0,
+ "PUNS": 1,
+ "SLAPSTICK": 2,
+ "BILL_BAILEY": 3,
+}
+
+func (x Message_Humour) String() string {
+ return proto.EnumName(Message_Humour_name, int32(x))
+}
+
+func (Message_Humour) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{0, 0}
+}
+
+type Message struct {
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,proto3,enum=proto3_test.Message_Humour" json:"hilarity,omitempty"`
+ HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm,proto3" json:"height_in_cm,omitempty"`
+ Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
+ ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount,proto3" json:"result_count,omitempty"`
+ TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman,proto3" json:"true_scotsman,omitempty"`
+ Score float32 `protobuf:"fixed32,9,opt,name=score,proto3" json:"score,omitempty"`
+ Key []uint64 `protobuf:"varint,5,rep,packed,name=key,proto3" json:"key,omitempty"`
+ ShortKey []int32 `protobuf:"varint,19,rep,packed,name=short_key,json=shortKey,proto3" json:"short_key,omitempty"`
+ Nested *Nested `protobuf:"bytes,6,opt,name=nested,proto3" json:"nested,omitempty"`
+ RFunny []Message_Humour `protobuf:"varint,16,rep,packed,name=r_funny,json=rFunny,proto3,enum=proto3_test.Message_Humour" json:"r_funny,omitempty"`
+ Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain,proto3" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Proto2Field *proto2_proto.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field,proto3" json:"proto2_field,omitempty"`
+ Proto2Value map[string]*proto2_proto.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value,proto3" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Anything *anypb.Any `protobuf:"bytes,14,opt,name=anything,proto3" json:"anything,omitempty"`
+ ManyThings []*anypb.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings,proto3" json:"many_things,omitempty"`
+ Submessage *Message `protobuf:"bytes,17,opt,name=submessage,proto3" json:"submessage,omitempty"`
+ Children []*Message `protobuf:"bytes,18,rep,name=children,proto3" json:"children,omitempty"`
+ StringMap map[string]string `protobuf:"bytes,20,rep,name=string_map,json=stringMap,proto3" json:"string_map,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Message) Reset() { *m = Message{} }
+func (m *Message) String() string { return proto.CompactTextString(m) }
+func (*Message) ProtoMessage() {}
+func (*Message) Descriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{0}
+}
+
+func (m *Message) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Message.Unmarshal(m, b)
+}
+func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Message.Marshal(b, m, deterministic)
+}
+func (m *Message) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Message.Merge(m, src)
+}
+func (m *Message) XXX_Size() int {
+ return xxx_messageInfo_Message.Size(m)
+}
+func (m *Message) XXX_DiscardUnknown() {
+ xxx_messageInfo_Message.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Message proto.InternalMessageInfo
+
+func (m *Message) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *Message) GetHilarity() Message_Humour {
+ if m != nil {
+ return m.Hilarity
+ }
+ return Message_UNKNOWN
+}
+
+func (m *Message) GetHeightInCm() uint32 {
+ if m != nil {
+ return m.HeightInCm
+ }
+ return 0
+}
+
+func (m *Message) GetData() []byte {
+ if m != nil {
+ return m.Data
+ }
+ return nil
+}
+
+func (m *Message) GetResultCount() int64 {
+ if m != nil {
+ return m.ResultCount
+ }
+ return 0
+}
+
+func (m *Message) GetTrueScotsman() bool {
+ if m != nil {
+ return m.TrueScotsman
+ }
+ return false
+}
+
+func (m *Message) GetScore() float32 {
+ if m != nil {
+ return m.Score
+ }
+ return 0
+}
+
+func (m *Message) GetKey() []uint64 {
+ if m != nil {
+ return m.Key
+ }
+ return nil
+}
+
+func (m *Message) GetShortKey() []int32 {
+ if m != nil {
+ return m.ShortKey
+ }
+ return nil
+}
+
+func (m *Message) GetNested() *Nested {
+ if m != nil {
+ return m.Nested
+ }
+ return nil
+}
+
+func (m *Message) GetRFunny() []Message_Humour {
+ if m != nil {
+ return m.RFunny
+ }
+ return nil
+}
+
+func (m *Message) GetTerrain() map[string]*Nested {
+ if m != nil {
+ return m.Terrain
+ }
+ return nil
+}
+
+func (m *Message) GetProto2Field() *proto2_proto.SubDefaults {
+ if m != nil {
+ return m.Proto2Field
+ }
+ return nil
+}
+
+func (m *Message) GetProto2Value() map[string]*proto2_proto.SubDefaults {
+ if m != nil {
+ return m.Proto2Value
+ }
+ return nil
+}
+
+func (m *Message) GetAnything() *anypb.Any {
+ if m != nil {
+ return m.Anything
+ }
+ return nil
+}
+
+func (m *Message) GetManyThings() []*anypb.Any {
+ if m != nil {
+ return m.ManyThings
+ }
+ return nil
+}
+
+func (m *Message) GetSubmessage() *Message {
+ if m != nil {
+ return m.Submessage
+ }
+ return nil
+}
+
+func (m *Message) GetChildren() []*Message {
+ if m != nil {
+ return m.Children
+ }
+ return nil
+}
+
+func (m *Message) GetStringMap() map[string]string {
+ if m != nil {
+ return m.StringMap
+ }
+ return nil
+}
+
+type Nested struct {
+ Bunny string `protobuf:"bytes,1,opt,name=bunny,proto3" json:"bunny,omitempty"`
+ Cute bool `protobuf:"varint,2,opt,name=cute,proto3" json:"cute,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Nested) Reset() { *m = Nested{} }
+func (m *Nested) String() string { return proto.CompactTextString(m) }
+func (*Nested) ProtoMessage() {}
+func (*Nested) Descriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{1}
+}
+
+func (m *Nested) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_Nested.Unmarshal(m, b)
+}
+func (m *Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_Nested.Marshal(b, m, deterministic)
+}
+func (m *Nested) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Nested.Merge(m, src)
+}
+func (m *Nested) XXX_Size() int {
+ return xxx_messageInfo_Nested.Size(m)
+}
+func (m *Nested) XXX_DiscardUnknown() {
+ xxx_messageInfo_Nested.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Nested proto.InternalMessageInfo
+
+func (m *Nested) GetBunny() string {
+ if m != nil {
+ return m.Bunny
+ }
+ return ""
+}
+
+func (m *Nested) GetCute() bool {
+ if m != nil {
+ return m.Cute
+ }
+ return false
+}
+
+type MessageWithMap struct {
+ ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping,proto3" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
+func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
+func (*MessageWithMap) ProtoMessage() {}
+func (*MessageWithMap) Descriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{2}
+}
+
+func (m *MessageWithMap) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_MessageWithMap.Unmarshal(m, b)
+}
+func (m *MessageWithMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_MessageWithMap.Marshal(b, m, deterministic)
+}
+func (m *MessageWithMap) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MessageWithMap.Merge(m, src)
+}
+func (m *MessageWithMap) XXX_Size() int {
+ return xxx_messageInfo_MessageWithMap.Size(m)
+}
+func (m *MessageWithMap) XXX_DiscardUnknown() {
+ xxx_messageInfo_MessageWithMap.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MessageWithMap proto.InternalMessageInfo
+
+func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
+ if m != nil {
+ return m.ByteMapping
+ }
+ return nil
+}
+
+type IntMap struct {
+ Rtt map[int32]int32 `protobuf:"bytes,1,rep,name=rtt,proto3" json:"rtt,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *IntMap) Reset() { *m = IntMap{} }
+func (m *IntMap) String() string { return proto.CompactTextString(m) }
+func (*IntMap) ProtoMessage() {}
+func (*IntMap) Descriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{3}
+}
+
+func (m *IntMap) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_IntMap.Unmarshal(m, b)
+}
+func (m *IntMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_IntMap.Marshal(b, m, deterministic)
+}
+func (m *IntMap) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_IntMap.Merge(m, src)
+}
+func (m *IntMap) XXX_Size() int {
+ return xxx_messageInfo_IntMap.Size(m)
+}
+func (m *IntMap) XXX_DiscardUnknown() {
+ xxx_messageInfo_IntMap.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_IntMap proto.InternalMessageInfo
+
+func (m *IntMap) GetRtt() map[int32]int32 {
+ if m != nil {
+ return m.Rtt
+ }
+ return nil
+}
+
+type IntMaps struct {
+ Maps []*IntMap `protobuf:"bytes,1,rep,name=maps,proto3" json:"maps,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *IntMaps) Reset() { *m = IntMaps{} }
+func (m *IntMaps) String() string { return proto.CompactTextString(m) }
+func (*IntMaps) ProtoMessage() {}
+func (*IntMaps) Descriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{4}
+}
+
+func (m *IntMaps) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_IntMaps.Unmarshal(m, b)
+}
+func (m *IntMaps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_IntMaps.Marshal(b, m, deterministic)
+}
+func (m *IntMaps) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_IntMaps.Merge(m, src)
+}
+func (m *IntMaps) XXX_Size() int {
+ return xxx_messageInfo_IntMaps.Size(m)
+}
+func (m *IntMaps) XXX_DiscardUnknown() {
+ xxx_messageInfo_IntMaps.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_IntMaps proto.InternalMessageInfo
+
+func (m *IntMaps) GetMaps() []*IntMap {
+ if m != nil {
+ return m.Maps
+ }
+ return nil
+}
+
+type TestUTF8 struct {
+ Scalar string `protobuf:"bytes,1,opt,name=scalar,proto3" json:"scalar,omitempty"`
+ Vector []string `protobuf:"bytes,2,rep,name=vector,proto3" json:"vector,omitempty"`
+ // Types that are valid to be assigned to Oneof:
+ // *TestUTF8_Field
+ Oneof isTestUTF8_Oneof `protobuf_oneof:"oneof"`
+ MapKey map[string]int64 `protobuf:"bytes,4,rep,name=map_key,json=mapKey,proto3" json:"map_key,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
+ MapValue map[int64]string `protobuf:"bytes,5,rep,name=map_value,json=mapValue,proto3" json:"map_value,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *TestUTF8) Reset() { *m = TestUTF8{} }
+func (m *TestUTF8) String() string { return proto.CompactTextString(m) }
+func (*TestUTF8) ProtoMessage() {}
+func (*TestUTF8) Descriptor() ([]byte, []int) {
+ return fileDescriptor_ff83f0b8d2b92afa, []int{5}
+}
+
+func (m *TestUTF8) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_TestUTF8.Unmarshal(m, b)
+}
+func (m *TestUTF8) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_TestUTF8.Marshal(b, m, deterministic)
+}
+func (m *TestUTF8) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_TestUTF8.Merge(m, src)
+}
+func (m *TestUTF8) XXX_Size() int {
+ return xxx_messageInfo_TestUTF8.Size(m)
+}
+func (m *TestUTF8) XXX_DiscardUnknown() {
+ xxx_messageInfo_TestUTF8.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_TestUTF8 proto.InternalMessageInfo
+
+func (m *TestUTF8) GetScalar() string {
+ if m != nil {
+ return m.Scalar
+ }
+ return ""
+}
+
+func (m *TestUTF8) GetVector() []string {
+ if m != nil {
+ return m.Vector
+ }
+ return nil
+}
+
+type isTestUTF8_Oneof interface {
+ isTestUTF8_Oneof()
+}
+
+type TestUTF8_Field struct {
+ Field string `protobuf:"bytes,3,opt,name=field,proto3,oneof"`
+}
+
+func (*TestUTF8_Field) isTestUTF8_Oneof() {}
+
+func (m *TestUTF8) GetOneof() isTestUTF8_Oneof {
+ if m != nil {
+ return m.Oneof
+ }
+ return nil
+}
+
+func (m *TestUTF8) GetField() string {
+ if x, ok := m.GetOneof().(*TestUTF8_Field); ok {
+ return x.Field
+ }
+ return ""
+}
+
+func (m *TestUTF8) GetMapKey() map[string]int64 {
+ if m != nil {
+ return m.MapKey
+ }
+ return nil
+}
+
+func (m *TestUTF8) GetMapValue() map[int64]string {
+ if m != nil {
+ return m.MapValue
+ }
+ return nil
+}
+
+// XXX_OneofWrappers is for the internal use of the proto package.
+func (*TestUTF8) XXX_OneofWrappers() []interface{} {
+ return []interface{}{
+ (*TestUTF8_Field)(nil),
+ }
+}
+
+func init() {
+ proto.RegisterEnum("proto3_test.Message_Humour", Message_Humour_name, Message_Humour_value)
+ proto.RegisterType((*Message)(nil), "proto3_test.Message")
+ proto.RegisterMapType((map[string]*proto2_proto.SubDefaults)(nil), "proto3_test.Message.Proto2ValueEntry")
+ proto.RegisterMapType((map[string]string)(nil), "proto3_test.Message.StringMapEntry")
+ proto.RegisterMapType((map[string]*Nested)(nil), "proto3_test.Message.TerrainEntry")
+ proto.RegisterType((*Nested)(nil), "proto3_test.Nested")
+ proto.RegisterType((*MessageWithMap)(nil), "proto3_test.MessageWithMap")
+ proto.RegisterMapType((map[bool][]byte)(nil), "proto3_test.MessageWithMap.ByteMappingEntry")
+ proto.RegisterType((*IntMap)(nil), "proto3_test.IntMap")
+ proto.RegisterMapType((map[int32]int32)(nil), "proto3_test.IntMap.RttEntry")
+ proto.RegisterType((*IntMaps)(nil), "proto3_test.IntMaps")
+ proto.RegisterType((*TestUTF8)(nil), "proto3_test.TestUTF8")
+ proto.RegisterMapType((map[string]int64)(nil), "proto3_test.TestUTF8.MapKeyEntry")
+ proto.RegisterMapType((map[int64]string)(nil), "proto3_test.TestUTF8.MapValueEntry")
+}
+
+func init() { proto.RegisterFile("proto3_proto/test.proto", fileDescriptor_ff83f0b8d2b92afa) }
+
+var fileDescriptor_ff83f0b8d2b92afa = []byte{
+ // 926 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x55, 0x6d, 0x6f, 0xdb, 0x36,
+ 0x10, 0xae, 0x2c, 0xbf, 0xc8, 0x67, 0x3b, 0xf5, 0x98, 0xa0, 0xe3, 0xdc, 0x7d, 0x50, 0x5d, 0x0c,
+ 0xd3, 0xb0, 0x41, 0x1e, 0xbc, 0x6e, 0xeb, 0x9a, 0xbd, 0xc5, 0x59, 0x83, 0x18, 0x89, 0x9d, 0x40,
+ 0x76, 0xd6, 0x6d, 0x5f, 0x04, 0xda, 0xa1, 0x6d, 0x61, 0x12, 0x65, 0x88, 0x54, 0x01, 0xfd, 0x9c,
+ 0xfd, 0xa4, 0xfd, 0xa2, 0x0d, 0x24, 0xe5, 0x54, 0x6e, 0x15, 0xe4, 0x93, 0x79, 0x8f, 0x9f, 0xbb,
+ 0xe7, 0x78, 0x77, 0x3c, 0xc1, 0xc7, 0xdb, 0x24, 0x16, 0xf1, 0x37, 0xbe, 0xfa, 0x19, 0x08, 0xca,
+ 0x85, 0xab, 0x8e, 0xa8, 0x95, 0xff, 0x21, 0xa1, 0xde, 0x27, 0xeb, 0x38, 0x5e, 0x87, 0x74, 0xa0,
+ 0xb0, 0x45, 0xba, 0x1a, 0x10, 0x96, 0x69, 0x5e, 0x4f, 0x07, 0x18, 0x7e, 0x10, 0xa0, 0xff, 0x9f,
+ 0x05, 0x8d, 0x09, 0xe5, 0x9c, 0xac, 0x29, 0x42, 0x50, 0x65, 0x24, 0xa2, 0xd8, 0xb0, 0x0d, 0xa7,
+ 0xe9, 0xa9, 0x33, 0xfa, 0x1e, 0xac, 0x4d, 0x10, 0x92, 0x24, 0x10, 0x19, 0xae, 0xd8, 0x86, 0x73,
+ 0x30, 0x7c, 0xea, 0x16, 0x34, 0xdd, 0xdc, 0xd7, 0x3d, 0x4f, 0xa3, 0x38, 0x4d, 0xbc, 0x3b, 0x32,
+ 0xb2, 0xa1, 0xbd, 0xa1, 0xc1, 0x7a, 0x23, 0xfc, 0x80, 0xf9, 0xcb, 0x08, 0x9b, 0xb6, 0xe1, 0x74,
+ 0x3c, 0xd0, 0xd8, 0x98, 0x9d, 0x46, 0x52, 0xee, 0x96, 0x08, 0x82, 0xab, 0xb6, 0xe1, 0xb4, 0x3d,
+ 0x75, 0x46, 0xcf, 0xa0, 0x9d, 0x50, 0x9e, 0x86, 0xc2, 0x5f, 0xc6, 0x29, 0x13, 0xb8, 0x61, 0x1b,
+ 0x8e, 0xe9, 0xb5, 0x34, 0x76, 0x2a, 0x21, 0xf4, 0x1c, 0x3a, 0x22, 0x49, 0xa9, 0xcf, 0x97, 0xb1,
+ 0xe0, 0x11, 0x61, 0xd8, 0xb2, 0x0d, 0xc7, 0xf2, 0xda, 0x12, 0x9c, 0xe5, 0x18, 0x3a, 0x82, 0x1a,
+ 0x5f, 0xc6, 0x09, 0xc5, 0x4d, 0xdb, 0x70, 0x2a, 0x9e, 0x36, 0x50, 0x17, 0xcc, 0xbf, 0x69, 0x86,
+ 0x6b, 0xb6, 0xe9, 0x54, 0x3d, 0x79, 0x44, 0x4f, 0xa1, 0xc9, 0x37, 0x71, 0x22, 0x7c, 0x89, 0x1f,
+ 0xda, 0xa6, 0x53, 0xf3, 0x2c, 0x05, 0x5c, 0xd0, 0x0c, 0x7d, 0x09, 0x75, 0x46, 0xb9, 0xa0, 0xb7,
+ 0xb8, 0x6e, 0x1b, 0x4e, 0x6b, 0x78, 0xb8, 0x77, 0xf3, 0xa9, 0xfa, 0xcb, 0xcb, 0x29, 0xe8, 0x05,
+ 0x34, 0x12, 0x7f, 0x95, 0x32, 0x96, 0xe1, 0xae, 0x6d, 0x3e, 0x54, 0xa7, 0x7a, 0x72, 0x26, 0xa9,
+ 0xe8, 0x18, 0x1a, 0x82, 0x26, 0x09, 0x09, 0x18, 0x06, 0xdb, 0x74, 0x5a, 0xc3, 0x67, 0xa5, 0x5e,
+ 0x73, 0xcd, 0x79, 0xcd, 0x44, 0x92, 0x79, 0x3b, 0x0f, 0x74, 0x0c, 0xed, 0xbc, 0xad, 0xab, 0x80,
+ 0x86, 0xb7, 0xb8, 0xa5, 0xb2, 0xc4, 0x6e, 0x0e, 0xaa, 0x08, 0xb3, 0x74, 0xf1, 0x1b, 0x5d, 0x91,
+ 0x34, 0x14, 0xdc, 0xd3, 0xc3, 0x32, 0x3c, 0x93, 0x64, 0x74, 0x7e, 0xe7, 0xfc, 0x96, 0x84, 0x29,
+ 0xc5, 0x1d, 0x25, 0xff, 0x59, 0xa9, 0xfc, 0xb5, 0x22, 0xfe, 0x2e, 0x79, 0x3a, 0x85, 0x3c, 0x92,
+ 0x42, 0xd0, 0xd7, 0x60, 0x11, 0x96, 0x89, 0x4d, 0xc0, 0xd6, 0xf8, 0x40, 0xa5, 0x70, 0xe4, 0xea,
+ 0x49, 0x74, 0x77, 0x93, 0xe8, 0x9e, 0xb0, 0xcc, 0xbb, 0x63, 0xa1, 0x6f, 0xa1, 0x15, 0x11, 0x96,
+ 0xf9, 0xca, 0xe2, 0xf8, 0xb1, 0x92, 0x2e, 0x77, 0x02, 0x49, 0x9c, 0x2b, 0x1e, 0x7a, 0x01, 0xc0,
+ 0xd3, 0x45, 0xa4, 0x93, 0xc2, 0x1f, 0xe5, 0x52, 0x25, 0x09, 0x7b, 0x05, 0x9e, 0x4c, 0x6f, 0xb9,
+ 0x09, 0xc2, 0xdb, 0x84, 0x32, 0x8c, 0x72, 0xa5, 0x32, 0x9f, 0x3b, 0x16, 0x1a, 0x01, 0x70, 0x91,
+ 0x04, 0x6c, 0xed, 0x47, 0x64, 0x8b, 0x8f, 0x94, 0xcf, 0xf3, 0xd2, 0xc2, 0xcc, 0x14, 0x6d, 0x42,
+ 0xb6, 0xba, 0x2c, 0x4d, 0xbe, 0xb3, 0x7b, 0x57, 0xd0, 0x2e, 0x36, 0x6d, 0x37, 0x7a, 0xfa, 0x69,
+ 0xa9, 0xd1, 0xfb, 0x02, 0x6a, 0xba, 0xf2, 0x95, 0xfb, 0x87, 0x4b, 0x33, 0x5e, 0x55, 0x5e, 0x1a,
+ 0xbd, 0x3f, 0xa0, 0xfb, 0x7e, 0x1b, 0x4a, 0x82, 0xba, 0xfb, 0x41, 0xef, 0x9f, 0x85, 0x42, 0xe4,
+ 0x1f, 0xe1, 0x60, 0xff, 0x1e, 0x25, 0x71, 0x8f, 0x8a, 0x71, 0x9b, 0x05, 0xef, 0xfe, 0x2f, 0x50,
+ 0xd7, 0x33, 0x8d, 0x5a, 0xd0, 0xb8, 0x99, 0x5e, 0x4c, 0xaf, 0xde, 0x4c, 0xbb, 0x8f, 0x90, 0x05,
+ 0xd5, 0xeb, 0x9b, 0xe9, 0xac, 0x6b, 0xa0, 0x0e, 0x34, 0x67, 0x97, 0x27, 0xd7, 0xb3, 0xf9, 0xf8,
+ 0xf4, 0xa2, 0x5b, 0x41, 0x8f, 0xa1, 0x35, 0x1a, 0x5f, 0x5e, 0xfa, 0xa3, 0x93, 0xf1, 0xe5, 0xeb,
+ 0x3f, 0xbb, 0x66, 0x7f, 0x08, 0x75, 0x7d, 0x5b, 0x29, 0xb2, 0x50, 0x0f, 0x48, 0x0b, 0x6b, 0x43,
+ 0xae, 0x89, 0x65, 0x2a, 0xb4, 0xb2, 0xe5, 0xa9, 0x73, 0xff, 0x1f, 0x03, 0x0e, 0xf2, 0x1e, 0xbc,
+ 0x09, 0xc4, 0x66, 0x42, 0xb6, 0xe8, 0x0a, 0xda, 0x8b, 0x4c, 0x50, 0xd9, 0xb2, 0xad, 0x9c, 0x44,
+ 0x43, 0xb5, 0xed, 0xab, 0xb2, 0xb6, 0xe5, 0x2e, 0xee, 0x28, 0x13, 0x74, 0xa2, 0xe9, 0xf9, 0x58,
+ 0x2f, 0xde, 0x21, 0xbd, 0x9f, 0xa1, 0xfb, 0x3e, 0xa1, 0x58, 0x18, 0xab, 0xa4, 0x30, 0xed, 0x62,
+ 0x61, 0xb6, 0x50, 0x1f, 0x33, 0x21, 0x53, 0x73, 0xc1, 0x4c, 0x84, 0xc8, 0x33, 0xfa, 0x74, 0x2f,
+ 0x23, 0xcd, 0x70, 0x3d, 0x21, 0x74, 0x06, 0x92, 0xd8, 0xfb, 0x0e, 0xac, 0x1d, 0x50, 0x54, 0xac,
+ 0x95, 0x28, 0xd6, 0x8a, 0x8a, 0x43, 0x68, 0xe8, 0x78, 0x1c, 0x7d, 0x0e, 0xd5, 0x88, 0x6c, 0x79,
+ 0xae, 0x79, 0x58, 0xa2, 0xe9, 0x29, 0x42, 0xff, 0xdf, 0x0a, 0x58, 0x73, 0xca, 0xc5, 0xcd, 0xfc,
+ 0xec, 0x25, 0x7a, 0x02, 0x75, 0xbe, 0x24, 0x21, 0x49, 0xf2, 0x0e, 0xe4, 0x96, 0xc4, 0xdf, 0xd2,
+ 0xa5, 0x88, 0x13, 0x5c, 0xb1, 0x4d, 0x89, 0x6b, 0x0b, 0x3d, 0x81, 0x9a, 0xde, 0x3c, 0x72, 0xb9,
+ 0x37, 0xcf, 0x1f, 0x79, 0xda, 0x44, 0xaf, 0xa0, 0x11, 0x91, 0xad, 0xda, 0xa9, 0xd5, 0x92, 0xad,
+ 0xb6, 0xd3, 0x73, 0x27, 0x64, 0x7b, 0x41, 0x33, 0x7d, 0xf3, 0x7a, 0xa4, 0x0c, 0xf4, 0x2b, 0x34,
+ 0xa5, 0xaf, 0xbe, 0x62, 0xad, 0xe4, 0xed, 0x15, 0xbd, 0x0b, 0x2b, 0xc9, 0x8a, 0x72, 0xb3, 0xf7,
+ 0x03, 0xb4, 0x0a, 0x81, 0x1f, 0x1a, 0x66, 0xb3, 0xf8, 0x14, 0x8e, 0xa1, 0xb3, 0x17, 0xb5, 0xe8,
+ 0x6c, 0x3e, 0xf0, 0x12, 0x46, 0x0d, 0xa8, 0xc5, 0x8c, 0xc6, 0xab, 0xd1, 0x4f, 0x7f, 0x1d, 0xaf,
+ 0x03, 0xb1, 0x49, 0x17, 0xee, 0x32, 0x8e, 0x06, 0xeb, 0x38, 0x24, 0x6c, 0xfd, 0xee, 0xa3, 0x1c,
+ 0x30, 0x41, 0x13, 0x46, 0x42, 0xf5, 0x15, 0x56, 0x28, 0x1f, 0x14, 0x3f, 0xef, 0x8b, 0xba, 0xb6,
+ 0xfe, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x10, 0x03, 0x1b, 0x06, 0xf5, 0x07, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/internal/testprotos/proto3_proto/test.proto b/vendor/github.com/golang/protobuf/internal/testprotos/proto3_proto/test.proto
new file mode 100644
index 000000000..b1c6749d1
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/proto3_proto/test.proto
@@ -0,0 +1,72 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+syntax = "proto3";
+
+option go_package = "github.com/golang/protobuf/internal/testprotos/proto3_proto";
+
+import "google/protobuf/any.proto";
+import "proto2_proto/test.proto";
+
+package proto3_test;
+
+message Message {
+ enum Humour {
+ UNKNOWN = 0;
+ PUNS = 1;
+ SLAPSTICK = 2;
+ BILL_BAILEY = 3;
+ }
+
+ string name = 1;
+ Humour hilarity = 2;
+ uint32 height_in_cm = 3;
+ bytes data = 4;
+ int64 result_count = 7;
+ bool true_scotsman = 8;
+ float score = 9;
+
+ repeated uint64 key = 5;
+ repeated int32 short_key = 19;
+ Nested nested = 6;
+ repeated Humour r_funny = 16;
+
+ map terrain = 10;
+ proto2_test.SubDefaults proto2_field = 11;
+ map proto2_value = 13;
+
+ google.protobuf.Any anything = 14;
+ repeated google.protobuf.Any many_things = 15;
+
+ Message submessage = 17;
+ repeated Message children = 18;
+
+ map string_map = 20;
+}
+
+message Nested {
+ string bunny = 1;
+ bool cute = 2;
+}
+
+message MessageWithMap {
+ map byte_mapping = 1;
+}
+
+
+message IntMap {
+ map rtt = 1;
+}
+
+message IntMaps {
+ repeated IntMap maps = 1;
+}
+
+message TestUTF8 {
+ string scalar = 1;
+ repeated string vector = 2;
+ oneof oneof { string field = 3; }
+ map map_key = 4;
+ map map_value = 5;
+}
diff --git a/vendor/github.com/golang/protobuf/internal/testprotos/regenerate.bash b/vendor/github.com/golang/protobuf/internal/testprotos/regenerate.bash
new file mode 100644
index 000000000..c2eb29703
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/internal/testprotos/regenerate.bash
@@ -0,0 +1,17 @@
+#!/bin/bash
+# Copyright 2020 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+# NOTE: The integration scripts deliberately do not check to
+# make sure that the test protos have been regenerated.
+# It is intentional that older versions of the .pb.go files
+# are checked in to ensure that they continue to function.
+#
+# Versions used:
+# protoc: v3.9.1
+# protoc-gen-go: v1.3.2
+
+for X in $(find . -name "*.proto" | sed "s|^\./||"); do
+ protoc -I$(pwd) --go_out=paths=source_relative:. $X
+done
diff --git a/vendor/github.com/golang/protobuf/jsonpb/decode.go b/vendor/github.com/golang/protobuf/jsonpb/decode.go
new file mode 100644
index 000000000..7c6c5a524
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/decode.go
@@ -0,0 +1,514 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package jsonpb
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ "google.golang.org/protobuf/encoding/protojson"
+ protoV2 "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+)
+
+const wrapJSONUnmarshalV2 = false
+
+// UnmarshalNext unmarshals the next JSON object from d into m.
+func UnmarshalNext(d *json.Decoder, m proto.Message) error {
+ return new(Unmarshaler).UnmarshalNext(d, m)
+}
+
+// Unmarshal unmarshals a JSON object from r into m.
+func Unmarshal(r io.Reader, m proto.Message) error {
+ return new(Unmarshaler).Unmarshal(r, m)
+}
+
+// UnmarshalString unmarshals a JSON object from s into m.
+func UnmarshalString(s string, m proto.Message) error {
+ return new(Unmarshaler).Unmarshal(strings.NewReader(s), m)
+}
+
+// Unmarshaler is a configurable object for converting from a JSON
+// representation to a protocol buffer object.
+type Unmarshaler struct {
+ // AllowUnknownFields specifies whether to allow messages to contain
+ // unknown JSON fields, as opposed to failing to unmarshal.
+ AllowUnknownFields bool
+
+ // AnyResolver is used to resolve the google.protobuf.Any well-known type.
+ // If unset, the global registry is used by default.
+ AnyResolver AnyResolver
+}
+
+// JSONPBUnmarshaler is implemented by protobuf messages that customize the way
+// they are unmarshaled from JSON. Messages that implement this should also
+// implement JSONPBMarshaler so that the custom format can be produced.
+//
+// The JSON unmarshaling must follow the JSON to proto specification:
+// https://developers.google.com/protocol-buffers/docs/proto3#json
+//
+// Deprecated: Custom types should implement protobuf reflection instead.
+type JSONPBUnmarshaler interface {
+ UnmarshalJSONPB(*Unmarshaler, []byte) error
+}
+
+// Unmarshal unmarshals a JSON object from r into m.
+func (u *Unmarshaler) Unmarshal(r io.Reader, m proto.Message) error {
+ return u.UnmarshalNext(json.NewDecoder(r), m)
+}
+
+// UnmarshalNext unmarshals the next JSON object from d into m.
+func (u *Unmarshaler) UnmarshalNext(d *json.Decoder, m proto.Message) error {
+ if m == nil {
+ return errors.New("invalid nil message")
+ }
+
+ // Parse the next JSON object from the stream.
+ raw := json.RawMessage{}
+ if err := d.Decode(&raw); err != nil {
+ return err
+ }
+
+ // Check for custom unmarshalers first since they may not properly
+ // implement protobuf reflection that the logic below relies on.
+ if jsu, ok := m.(JSONPBUnmarshaler); ok {
+ return jsu.UnmarshalJSONPB(u, raw)
+ }
+
+ mr := proto.MessageReflect(m)
+
+ // NOTE: For historical reasons, a top-level null is treated as a noop.
+ // This is incorrect, but kept for compatibility.
+ if string(raw) == "null" && mr.Descriptor().FullName() != "google.protobuf.Value" {
+ return nil
+ }
+
+ if wrapJSONUnmarshalV2 {
+ // NOTE: If input message is non-empty, we need to preserve merge semantics
+ // of the old jsonpb implementation. These semantics are not supported by
+ // the protobuf JSON specification.
+ isEmpty := true
+ mr.Range(func(protoreflect.FieldDescriptor, protoreflect.Value) bool {
+ isEmpty = false // at least one iteration implies non-empty
+ return false
+ })
+ if !isEmpty {
+ // Perform unmarshaling into a newly allocated, empty message.
+ mr = mr.New()
+
+ // Use a defer to copy all unmarshaled fields into the original message.
+ dst := proto.MessageReflect(m)
+ defer mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
+ dst.Set(fd, v)
+ return true
+ })
+ }
+
+ // Unmarshal using the v2 JSON unmarshaler.
+ opts := protojson.UnmarshalOptions{
+ DiscardUnknown: u.AllowUnknownFields,
+ }
+ if u.AnyResolver != nil {
+ opts.Resolver = anyResolver{u.AnyResolver}
+ }
+ return opts.Unmarshal(raw, mr.Interface())
+ } else {
+ if err := u.unmarshalMessage(mr, raw); err != nil {
+ return err
+ }
+ return protoV2.CheckInitialized(mr.Interface())
+ }
+}
+
+func (u *Unmarshaler) unmarshalMessage(m protoreflect.Message, in []byte) error {
+ md := m.Descriptor()
+ fds := md.Fields()
+
+ if string(in) == "null" && md.FullName() != "google.protobuf.Value" {
+ return nil
+ }
+
+ if jsu, ok := proto.MessageV1(m.Interface()).(JSONPBUnmarshaler); ok {
+ return jsu.UnmarshalJSONPB(u, in)
+ }
+
+ switch wellKnownType(md.FullName()) {
+ case "Any":
+ var jsonObject map[string]json.RawMessage
+ if err := json.Unmarshal(in, &jsonObject); err != nil {
+ return err
+ }
+
+ rawTypeURL, ok := jsonObject["@type"]
+ if !ok {
+ return errors.New("Any JSON doesn't have '@type'")
+ }
+ typeURL, err := unquoteString(string(rawTypeURL))
+ if err != nil {
+ return fmt.Errorf("can't unmarshal Any's '@type': %q", rawTypeURL)
+ }
+ m.Set(fds.ByNumber(1), protoreflect.ValueOfString(typeURL))
+
+ var m2 protoreflect.Message
+ if u.AnyResolver != nil {
+ mi, err := u.AnyResolver.Resolve(typeURL)
+ if err != nil {
+ return err
+ }
+ m2 = proto.MessageReflect(mi)
+ } else {
+ mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL)
+ if err != nil {
+ if err == protoregistry.NotFound {
+ return fmt.Errorf("could not resolve Any message type: %v", typeURL)
+ }
+ return err
+ }
+ m2 = mt.New()
+ }
+
+ if wellKnownType(m2.Descriptor().FullName()) != "" {
+ rawValue, ok := jsonObject["value"]
+ if !ok {
+ return errors.New("Any JSON doesn't have 'value'")
+ }
+ if err := u.unmarshalMessage(m2, rawValue); err != nil {
+ return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err)
+ }
+ } else {
+ delete(jsonObject, "@type")
+ rawJSON, err := json.Marshal(jsonObject)
+ if err != nil {
+ return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
+ }
+ if err = u.unmarshalMessage(m2, rawJSON); err != nil {
+ return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err)
+ }
+ }
+
+ rawWire, err := protoV2.Marshal(m2.Interface())
+ if err != nil {
+ return fmt.Errorf("can't marshal proto %v into Any.Value: %v", typeURL, err)
+ }
+ m.Set(fds.ByNumber(2), protoreflect.ValueOfBytes(rawWire))
+ return nil
+ case "BoolValue", "BytesValue", "StringValue",
+ "Int32Value", "UInt32Value", "FloatValue",
+ "Int64Value", "UInt64Value", "DoubleValue":
+ fd := fds.ByNumber(1)
+ v, err := u.unmarshalValue(m.NewField(fd), in, fd)
+ if err != nil {
+ return err
+ }
+ m.Set(fd, v)
+ return nil
+ case "Duration":
+ v, err := unquoteString(string(in))
+ if err != nil {
+ return err
+ }
+ d, err := time.ParseDuration(v)
+ if err != nil {
+ return fmt.Errorf("bad Duration: %v", err)
+ }
+
+ sec := d.Nanoseconds() / 1e9
+ nsec := d.Nanoseconds() % 1e9
+ m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec)))
+ m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec)))
+ return nil
+ case "Timestamp":
+ v, err := unquoteString(string(in))
+ if err != nil {
+ return err
+ }
+ t, err := time.Parse(time.RFC3339Nano, v)
+ if err != nil {
+ return fmt.Errorf("bad Timestamp: %v", err)
+ }
+
+ sec := t.Unix()
+ nsec := t.Nanosecond()
+ m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec)))
+ m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec)))
+ return nil
+ case "Value":
+ switch {
+ case string(in) == "null":
+ m.Set(fds.ByNumber(1), protoreflect.ValueOfEnum(0))
+ case string(in) == "true":
+ m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(true))
+ case string(in) == "false":
+ m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(false))
+ case hasPrefixAndSuffix('"', in, '"'):
+ s, err := unquoteString(string(in))
+ if err != nil {
+ return fmt.Errorf("unrecognized type for Value %q", in)
+ }
+ m.Set(fds.ByNumber(3), protoreflect.ValueOfString(s))
+ case hasPrefixAndSuffix('[', in, ']'):
+ v := m.Mutable(fds.ByNumber(6))
+ return u.unmarshalMessage(v.Message(), in)
+ case hasPrefixAndSuffix('{', in, '}'):
+ v := m.Mutable(fds.ByNumber(5))
+ return u.unmarshalMessage(v.Message(), in)
+ default:
+ f, err := strconv.ParseFloat(string(in), 0)
+ if err != nil {
+ return fmt.Errorf("unrecognized type for Value %q", in)
+ }
+ m.Set(fds.ByNumber(2), protoreflect.ValueOfFloat64(f))
+ }
+ return nil
+ case "ListValue":
+ var jsonArray []json.RawMessage
+ if err := json.Unmarshal(in, &jsonArray); err != nil {
+ return fmt.Errorf("bad ListValue: %v", err)
+ }
+
+ lv := m.Mutable(fds.ByNumber(1)).List()
+ for _, raw := range jsonArray {
+ ve := lv.NewElement()
+ if err := u.unmarshalMessage(ve.Message(), raw); err != nil {
+ return err
+ }
+ lv.Append(ve)
+ }
+ return nil
+ case "Struct":
+ var jsonObject map[string]json.RawMessage
+ if err := json.Unmarshal(in, &jsonObject); err != nil {
+ return fmt.Errorf("bad StructValue: %v", err)
+ }
+
+ mv := m.Mutable(fds.ByNumber(1)).Map()
+ for key, raw := range jsonObject {
+ kv := protoreflect.ValueOf(key).MapKey()
+ vv := mv.NewValue()
+ if err := u.unmarshalMessage(vv.Message(), raw); err != nil {
+ return fmt.Errorf("bad value in StructValue for key %q: %v", key, err)
+ }
+ mv.Set(kv, vv)
+ }
+ return nil
+ }
+
+ var jsonObject map[string]json.RawMessage
+ if err := json.Unmarshal(in, &jsonObject); err != nil {
+ return err
+ }
+
+ // Handle known fields.
+ for i := 0; i < fds.Len(); i++ {
+ fd := fds.Get(i)
+ if fd.IsWeak() && fd.Message().IsPlaceholder() {
+ continue // weak reference is not linked in
+ }
+
+ // Search for any raw JSON value associated with this field.
+ var raw json.RawMessage
+ name := string(fd.Name())
+ if fd.Kind() == protoreflect.GroupKind {
+ name = string(fd.Message().Name())
+ }
+ if v, ok := jsonObject[name]; ok {
+ delete(jsonObject, name)
+ raw = v
+ }
+ name = string(fd.JSONName())
+ if v, ok := jsonObject[name]; ok {
+ delete(jsonObject, name)
+ raw = v
+ }
+
+ // Unmarshal the field value.
+ if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd)) {
+ continue
+ }
+ v, err := u.unmarshalValue(m.NewField(fd), raw, fd)
+ if err != nil {
+ return err
+ }
+ m.Set(fd, v)
+ }
+
+ // Handle extension fields.
+ for name, raw := range jsonObject {
+ if !strings.HasPrefix(name, "[") || !strings.HasSuffix(name, "]") {
+ continue
+ }
+
+ // Resolve the extension field by name.
+ xname := protoreflect.FullName(name[len("[") : len(name)-len("]")])
+ xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname)
+ if xt == nil && isMessageSet(md) {
+ xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension"))
+ }
+ if xt == nil {
+ continue
+ }
+ delete(jsonObject, name)
+ fd := xt.TypeDescriptor()
+ if fd.ContainingMessage().FullName() != m.Descriptor().FullName() {
+ return fmt.Errorf("extension field %q does not extend message %q", xname, m.Descriptor().FullName())
+ }
+
+ // Unmarshal the field value.
+ if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd)) {
+ continue
+ }
+ v, err := u.unmarshalValue(m.NewField(fd), raw, fd)
+ if err != nil {
+ return err
+ }
+ m.Set(fd, v)
+ }
+
+ if !u.AllowUnknownFields && len(jsonObject) > 0 {
+ for name := range jsonObject {
+ return fmt.Errorf("unknown field %q in %v", name, md.FullName())
+ }
+ }
+ return nil
+}
+
+func isSingularWellKnownValue(fd protoreflect.FieldDescriptor) bool {
+ if md := fd.Message(); md != nil {
+ return md.FullName() == "google.protobuf.Value" && fd.Cardinality() != protoreflect.Repeated
+ }
+ return false
+}
+
+func (u *Unmarshaler) unmarshalValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
+ switch {
+ case fd.IsList():
+ var jsonArray []json.RawMessage
+ if err := json.Unmarshal(in, &jsonArray); err != nil {
+ return v, err
+ }
+ lv := v.List()
+ for _, raw := range jsonArray {
+ ve, err := u.unmarshalSingularValue(lv.NewElement(), raw, fd)
+ if err != nil {
+ return v, err
+ }
+ lv.Append(ve)
+ }
+ return v, nil
+ case fd.IsMap():
+ var jsonObject map[string]json.RawMessage
+ if err := json.Unmarshal(in, &jsonObject); err != nil {
+ return v, err
+ }
+ kfd := fd.MapKey()
+ vfd := fd.MapValue()
+ mv := v.Map()
+ for key, raw := range jsonObject {
+ var kv protoreflect.MapKey
+ if kfd.Kind() == protoreflect.StringKind {
+ kv = protoreflect.ValueOf(key).MapKey()
+ } else {
+ v, err := u.unmarshalSingularValue(kfd.Default(), []byte(key), kfd)
+ if err != nil {
+ return v, err
+ }
+ kv = v.MapKey()
+ }
+
+ vv, err := u.unmarshalSingularValue(mv.NewValue(), raw, vfd)
+ if err != nil {
+ return v, err
+ }
+ mv.Set(kv, vv)
+ }
+ return v, nil
+ default:
+ return u.unmarshalSingularValue(v, in, fd)
+ }
+}
+
+var nonFinite = map[string]float64{
+ `"NaN"`: math.NaN(),
+ `"Infinity"`: math.Inf(+1),
+ `"-Infinity"`: math.Inf(-1),
+}
+
+func (u *Unmarshaler) unmarshalSingularValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
+ switch fd.Kind() {
+ case protoreflect.BoolKind:
+ return unmarshalValue(in, new(bool))
+ case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
+ return unmarshalValue(trimQuote(in), new(int32))
+ case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
+ return unmarshalValue(trimQuote(in), new(int64))
+ case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
+ return unmarshalValue(trimQuote(in), new(uint32))
+ case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
+ return unmarshalValue(trimQuote(in), new(uint64))
+ case protoreflect.FloatKind:
+ if f, ok := nonFinite[string(in)]; ok {
+ return protoreflect.ValueOfFloat32(float32(f)), nil
+ }
+ return unmarshalValue(trimQuote(in), new(float32))
+ case protoreflect.DoubleKind:
+ if f, ok := nonFinite[string(in)]; ok {
+ return protoreflect.ValueOfFloat64(float64(f)), nil
+ }
+ return unmarshalValue(trimQuote(in), new(float64))
+ case protoreflect.StringKind:
+ return unmarshalValue(in, new(string))
+ case protoreflect.BytesKind:
+ return unmarshalValue(in, new([]byte))
+ case protoreflect.EnumKind:
+ if hasPrefixAndSuffix('"', in, '"') {
+ vd := fd.Enum().Values().ByName(protoreflect.Name(trimQuote(in)))
+ if vd == nil {
+ return v, fmt.Errorf("unknown value %q for enum %s", in, fd.Enum().FullName())
+ }
+ return protoreflect.ValueOfEnum(vd.Number()), nil
+ }
+ return unmarshalValue(in, new(protoreflect.EnumNumber))
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ err := u.unmarshalMessage(v.Message(), in)
+ return v, err
+ default:
+ panic(fmt.Sprintf("invalid kind %v", fd.Kind()))
+ }
+}
+
+func unmarshalValue(in []byte, v interface{}) (protoreflect.Value, error) {
+ err := json.Unmarshal(in, v)
+ return protoreflect.ValueOf(reflect.ValueOf(v).Elem().Interface()), err
+}
+
+func unquoteString(in string) (out string, err error) {
+ err = json.Unmarshal([]byte(in), &out)
+ return out, err
+}
+
+func hasPrefixAndSuffix(prefix byte, in []byte, suffix byte) bool {
+ if len(in) >= 2 && in[0] == prefix && in[len(in)-1] == suffix {
+ return true
+ }
+ return false
+}
+
+// trimQuote is like unquoteString but simply strips surrounding quotes.
+// This is incorrect, but is behavior done by the legacy implementation.
+func trimQuote(in []byte) []byte {
+ if len(in) >= 2 && in[0] == '"' && in[len(in)-1] == '"' {
+ in = in[1 : len(in)-1]
+ }
+ return in
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/encode.go b/vendor/github.com/golang/protobuf/jsonpb/encode.go
new file mode 100644
index 000000000..685c80a62
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/encode.go
@@ -0,0 +1,559 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package jsonpb
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ "google.golang.org/protobuf/encoding/protojson"
+ protoV2 "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+)
+
+const wrapJSONMarshalV2 = false
+
+// Marshaler is a configurable object for marshaling protocol buffer messages
+// to the specified JSON representation.
+type Marshaler struct {
+ // OrigName specifies whether to use the original protobuf name for fields.
+ OrigName bool
+
+ // EnumsAsInts specifies whether to render enum values as integers,
+ // as opposed to string values.
+ EnumsAsInts bool
+
+ // EmitDefaults specifies whether to render fields with zero values.
+ EmitDefaults bool
+
+ // Indent controls whether the output is compact or not.
+ // If empty, the output is compact JSON. Otherwise, every JSON object
+ // entry and JSON array value will be on its own line.
+ // Each line will be preceded by repeated copies of Indent, where the
+ // number of copies is the current indentation depth.
+ Indent string
+
+ // AnyResolver is used to resolve the google.protobuf.Any well-known type.
+ // If unset, the global registry is used by default.
+ AnyResolver AnyResolver
+}
+
+// JSONPBMarshaler is implemented by protobuf messages that customize the
+// way they are marshaled to JSON. Messages that implement this should also
+// implement JSONPBUnmarshaler so that the custom format can be parsed.
+//
+// The JSON marshaling must follow the proto to JSON specification:
+// https://developers.google.com/protocol-buffers/docs/proto3#json
+//
+// Deprecated: Custom types should implement protobuf reflection instead.
+type JSONPBMarshaler interface {
+ MarshalJSONPB(*Marshaler) ([]byte, error)
+}
+
+// Marshal serializes a protobuf message as JSON into w.
+func (jm *Marshaler) Marshal(w io.Writer, m proto.Message) error {
+ b, err := jm.marshal(m)
+ if len(b) > 0 {
+ if _, err := w.Write(b); err != nil {
+ return err
+ }
+ }
+ return err
+}
+
+// MarshalToString serializes a protobuf message as JSON in string form.
+func (jm *Marshaler) MarshalToString(m proto.Message) (string, error) {
+ b, err := jm.marshal(m)
+ if err != nil {
+ return "", err
+ }
+ return string(b), nil
+}
+
+func (jm *Marshaler) marshal(m proto.Message) ([]byte, error) {
+ v := reflect.ValueOf(m)
+ if m == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
+ return nil, errors.New("Marshal called with nil")
+ }
+
+ // Check for custom marshalers first since they may not properly
+ // implement protobuf reflection that the logic below relies on.
+ if jsm, ok := m.(JSONPBMarshaler); ok {
+ return jsm.MarshalJSONPB(jm)
+ }
+
+ if wrapJSONMarshalV2 {
+ opts := protojson.MarshalOptions{
+ UseProtoNames: jm.OrigName,
+ UseEnumNumbers: jm.EnumsAsInts,
+ EmitUnpopulated: jm.EmitDefaults,
+ Indent: jm.Indent,
+ }
+ if jm.AnyResolver != nil {
+ opts.Resolver = anyResolver{jm.AnyResolver}
+ }
+ return opts.Marshal(proto.MessageReflect(m).Interface())
+ } else {
+ // Check for unpopulated required fields first.
+ m2 := proto.MessageReflect(m)
+ if err := protoV2.CheckInitialized(m2.Interface()); err != nil {
+ return nil, err
+ }
+
+ w := jsonWriter{Marshaler: jm}
+ err := w.marshalMessage(m2, "", "")
+ return w.buf, err
+ }
+}
+
+type jsonWriter struct {
+ *Marshaler
+ buf []byte
+}
+
+func (w *jsonWriter) write(s string) {
+ w.buf = append(w.buf, s...)
+}
+
+func (w *jsonWriter) marshalMessage(m protoreflect.Message, indent, typeURL string) error {
+ if jsm, ok := proto.MessageV1(m.Interface()).(JSONPBMarshaler); ok {
+ b, err := jsm.MarshalJSONPB(w.Marshaler)
+ if err != nil {
+ return err
+ }
+ if typeURL != "" {
+ // we are marshaling this object to an Any type
+ var js map[string]*json.RawMessage
+ if err = json.Unmarshal(b, &js); err != nil {
+ return fmt.Errorf("type %T produced invalid JSON: %v", m.Interface(), err)
+ }
+ turl, err := json.Marshal(typeURL)
+ if err != nil {
+ return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
+ }
+ js["@type"] = (*json.RawMessage)(&turl)
+ if b, err = json.Marshal(js); err != nil {
+ return err
+ }
+ }
+ w.write(string(b))
+ return nil
+ }
+
+ md := m.Descriptor()
+ fds := md.Fields()
+
+ // Handle well-known types.
+ const secondInNanos = int64(time.Second / time.Nanosecond)
+ switch wellKnownType(md.FullName()) {
+ case "Any":
+ return w.marshalAny(m, indent)
+ case "BoolValue", "BytesValue", "StringValue",
+ "Int32Value", "UInt32Value", "FloatValue",
+ "Int64Value", "UInt64Value", "DoubleValue":
+ fd := fds.ByNumber(1)
+ return w.marshalValue(fd, m.Get(fd), indent)
+ case "Duration":
+ const maxSecondsInDuration = 315576000000
+ // "Generated output always contains 0, 3, 6, or 9 fractional digits,
+ // depending on required precision."
+ s := m.Get(fds.ByNumber(1)).Int()
+ ns := m.Get(fds.ByNumber(2)).Int()
+ if s < -maxSecondsInDuration || s > maxSecondsInDuration {
+ return fmt.Errorf("seconds out of range %v", s)
+ }
+ if ns <= -secondInNanos || ns >= secondInNanos {
+ return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
+ }
+ if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
+ return errors.New("signs of seconds and nanos do not match")
+ }
+ var sign string
+ if s < 0 || ns < 0 {
+ sign, s, ns = "-", -1*s, -1*ns
+ }
+ x := fmt.Sprintf("%s%d.%09d", sign, s, ns)
+ x = strings.TrimSuffix(x, "000")
+ x = strings.TrimSuffix(x, "000")
+ x = strings.TrimSuffix(x, ".000")
+ w.write(fmt.Sprintf(`"%vs"`, x))
+ return nil
+ case "Timestamp":
+ // "RFC 3339, where generated output will always be Z-normalized
+ // and uses 0, 3, 6 or 9 fractional digits."
+ s := m.Get(fds.ByNumber(1)).Int()
+ ns := m.Get(fds.ByNumber(2)).Int()
+ if ns < 0 || ns >= secondInNanos {
+ return fmt.Errorf("ns out of range [0, %v)", secondInNanos)
+ }
+ t := time.Unix(s, ns).UTC()
+ // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
+ x := t.Format("2006-01-02T15:04:05.000000000")
+ x = strings.TrimSuffix(x, "000")
+ x = strings.TrimSuffix(x, "000")
+ x = strings.TrimSuffix(x, ".000")
+ w.write(fmt.Sprintf(`"%vZ"`, x))
+ return nil
+ case "Value":
+ // JSON value; which is a null, number, string, bool, object, or array.
+ od := md.Oneofs().Get(0)
+ fd := m.WhichOneof(od)
+ if fd == nil {
+ return errors.New("nil Value")
+ }
+ return w.marshalValue(fd, m.Get(fd), indent)
+ case "Struct", "ListValue":
+ // JSON object or array.
+ fd := fds.ByNumber(1)
+ return w.marshalValue(fd, m.Get(fd), indent)
+ }
+
+ w.write("{")
+ if w.Indent != "" {
+ w.write("\n")
+ }
+
+ firstField := true
+ if typeURL != "" {
+ if err := w.marshalTypeURL(indent, typeURL); err != nil {
+ return err
+ }
+ firstField = false
+ }
+
+ for i := 0; i < fds.Len(); {
+ fd := fds.Get(i)
+ if od := fd.ContainingOneof(); od != nil {
+ fd = m.WhichOneof(od)
+ i += od.Fields().Len()
+ if fd == nil {
+ continue
+ }
+ } else {
+ i++
+ }
+
+ v := m.Get(fd)
+
+ if !m.Has(fd) {
+ if !w.EmitDefaults || fd.ContainingOneof() != nil {
+ continue
+ }
+ if fd.Cardinality() != protoreflect.Repeated && (fd.Message() != nil || fd.Syntax() == protoreflect.Proto2) {
+ v = protoreflect.Value{} // use "null" for singular messages or proto2 scalars
+ }
+ }
+
+ if !firstField {
+ w.writeComma()
+ }
+ if err := w.marshalField(fd, v, indent); err != nil {
+ return err
+ }
+ firstField = false
+ }
+
+ // Handle proto2 extensions.
+ if md.ExtensionRanges().Len() > 0 {
+ // Collect a sorted list of all extension descriptor and values.
+ type ext struct {
+ desc protoreflect.FieldDescriptor
+ val protoreflect.Value
+ }
+ var exts []ext
+ m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
+ if fd.IsExtension() {
+ exts = append(exts, ext{fd, v})
+ }
+ return true
+ })
+ sort.Slice(exts, func(i, j int) bool {
+ return exts[i].desc.Number() < exts[j].desc.Number()
+ })
+
+ for _, ext := range exts {
+ if !firstField {
+ w.writeComma()
+ }
+ if err := w.marshalField(ext.desc, ext.val, indent); err != nil {
+ return err
+ }
+ firstField = false
+ }
+ }
+
+ if w.Indent != "" {
+ w.write("\n")
+ w.write(indent)
+ }
+ w.write("}")
+ return nil
+}
+
+func (w *jsonWriter) writeComma() {
+ if w.Indent != "" {
+ w.write(",\n")
+ } else {
+ w.write(",")
+ }
+}
+
+func (w *jsonWriter) marshalAny(m protoreflect.Message, indent string) error {
+ // "If the Any contains a value that has a special JSON mapping,
+ // it will be converted as follows: {"@type": xxx, "value": yyy}.
+ // Otherwise, the value will be converted into a JSON object,
+ // and the "@type" field will be inserted to indicate the actual data type."
+ md := m.Descriptor()
+ typeURL := m.Get(md.Fields().ByNumber(1)).String()
+ rawVal := m.Get(md.Fields().ByNumber(2)).Bytes()
+
+ var m2 protoreflect.Message
+ if w.AnyResolver != nil {
+ mi, err := w.AnyResolver.Resolve(typeURL)
+ if err != nil {
+ return err
+ }
+ m2 = proto.MessageReflect(mi)
+ } else {
+ mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL)
+ if err != nil {
+ return err
+ }
+ m2 = mt.New()
+ }
+
+ if err := protoV2.Unmarshal(rawVal, m2.Interface()); err != nil {
+ return err
+ }
+
+ if wellKnownType(m2.Descriptor().FullName()) == "" {
+ return w.marshalMessage(m2, indent, typeURL)
+ }
+
+ w.write("{")
+ if w.Indent != "" {
+ w.write("\n")
+ }
+ if err := w.marshalTypeURL(indent, typeURL); err != nil {
+ return err
+ }
+ w.writeComma()
+ if w.Indent != "" {
+ w.write(indent)
+ w.write(w.Indent)
+ w.write(`"value": `)
+ } else {
+ w.write(`"value":`)
+ }
+ if err := w.marshalMessage(m2, indent+w.Indent, ""); err != nil {
+ return err
+ }
+ if w.Indent != "" {
+ w.write("\n")
+ w.write(indent)
+ }
+ w.write("}")
+ return nil
+}
+
+func (w *jsonWriter) marshalTypeURL(indent, typeURL string) error {
+ if w.Indent != "" {
+ w.write(indent)
+ w.write(w.Indent)
+ }
+ w.write(`"@type":`)
+ if w.Indent != "" {
+ w.write(" ")
+ }
+ b, err := json.Marshal(typeURL)
+ if err != nil {
+ return err
+ }
+ w.write(string(b))
+ return nil
+}
+
+// marshalField writes field description and value to the Writer.
+func (w *jsonWriter) marshalField(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
+ if w.Indent != "" {
+ w.write(indent)
+ w.write(w.Indent)
+ }
+ w.write(`"`)
+ switch {
+ case fd.IsExtension():
+ // For message set, use the fname of the message as the extension name.
+ name := string(fd.FullName())
+ if isMessageSet(fd.ContainingMessage()) {
+ name = strings.TrimSuffix(name, ".message_set_extension")
+ }
+
+ w.write("[" + name + "]")
+ case w.OrigName:
+ name := string(fd.Name())
+ if fd.Kind() == protoreflect.GroupKind {
+ name = string(fd.Message().Name())
+ }
+ w.write(name)
+ default:
+ w.write(string(fd.JSONName()))
+ }
+ w.write(`":`)
+ if w.Indent != "" {
+ w.write(" ")
+ }
+ return w.marshalValue(fd, v, indent)
+}
+
+func (w *jsonWriter) marshalValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
+ switch {
+ case fd.IsList():
+ w.write("[")
+ comma := ""
+ lv := v.List()
+ for i := 0; i < lv.Len(); i++ {
+ w.write(comma)
+ if w.Indent != "" {
+ w.write("\n")
+ w.write(indent)
+ w.write(w.Indent)
+ w.write(w.Indent)
+ }
+ if err := w.marshalSingularValue(fd, lv.Get(i), indent+w.Indent); err != nil {
+ return err
+ }
+ comma = ","
+ }
+ if w.Indent != "" {
+ w.write("\n")
+ w.write(indent)
+ w.write(w.Indent)
+ }
+ w.write("]")
+ return nil
+ case fd.IsMap():
+ kfd := fd.MapKey()
+ vfd := fd.MapValue()
+ mv := v.Map()
+
+ // Collect a sorted list of all map keys and values.
+ type entry struct{ key, val protoreflect.Value }
+ var entries []entry
+ mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
+ entries = append(entries, entry{k.Value(), v})
+ return true
+ })
+ sort.Slice(entries, func(i, j int) bool {
+ switch kfd.Kind() {
+ case protoreflect.BoolKind:
+ return !entries[i].key.Bool() && entries[j].key.Bool()
+ case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
+ return entries[i].key.Int() < entries[j].key.Int()
+ case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
+ return entries[i].key.Uint() < entries[j].key.Uint()
+ case protoreflect.StringKind:
+ return entries[i].key.String() < entries[j].key.String()
+ default:
+ panic("invalid kind")
+ }
+ })
+
+ w.write(`{`)
+ comma := ""
+ for _, entry := range entries {
+ w.write(comma)
+ if w.Indent != "" {
+ w.write("\n")
+ w.write(indent)
+ w.write(w.Indent)
+ w.write(w.Indent)
+ }
+
+ s := fmt.Sprint(entry.key.Interface())
+ b, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ w.write(string(b))
+
+ w.write(`:`)
+ if w.Indent != "" {
+ w.write(` `)
+ }
+
+ if err := w.marshalSingularValue(vfd, entry.val, indent+w.Indent); err != nil {
+ return err
+ }
+ comma = ","
+ }
+ if w.Indent != "" {
+ w.write("\n")
+ w.write(indent)
+ w.write(w.Indent)
+ }
+ w.write(`}`)
+ return nil
+ default:
+ return w.marshalSingularValue(fd, v, indent)
+ }
+}
+
+func (w *jsonWriter) marshalSingularValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error {
+ switch {
+ case !v.IsValid():
+ w.write("null")
+ return nil
+ case fd.Message() != nil:
+ return w.marshalMessage(v.Message(), indent+w.Indent, "")
+ case fd.Enum() != nil:
+ if fd.Enum().FullName() == "google.protobuf.NullValue" {
+ w.write("null")
+ return nil
+ }
+
+ vd := fd.Enum().Values().ByNumber(v.Enum())
+ if vd == nil || w.EnumsAsInts {
+ w.write(strconv.Itoa(int(v.Enum())))
+ } else {
+ w.write(`"` + string(vd.Name()) + `"`)
+ }
+ return nil
+ default:
+ switch v.Interface().(type) {
+ case float32, float64:
+ switch {
+ case math.IsInf(v.Float(), +1):
+ w.write(`"Infinity"`)
+ return nil
+ case math.IsInf(v.Float(), -1):
+ w.write(`"-Infinity"`)
+ return nil
+ case math.IsNaN(v.Float()):
+ w.write(`"NaN"`)
+ return nil
+ }
+ case int64, uint64:
+ w.write(fmt.Sprintf(`"%d"`, v.Interface()))
+ return nil
+ }
+
+ b, err := json.Marshal(v.Interface())
+ if err != nil {
+ return err
+ }
+ w.write(string(b))
+ return nil
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/json.go b/vendor/github.com/golang/protobuf/jsonpb/json.go
new file mode 100644
index 000000000..480e2448d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/json.go
@@ -0,0 +1,69 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package jsonpb provides functionality to marshal and unmarshal between a
+// protocol buffer message and JSON. It follows the specification at
+// https://developers.google.com/protocol-buffers/docs/proto3#json.
+//
+// Do not rely on the default behavior of the standard encoding/json package
+// when called on generated message types as it does not operate correctly.
+//
+// Deprecated: Use the "google.golang.org/protobuf/encoding/protojson"
+// package instead.
+package jsonpb
+
+import (
+ "github.com/golang/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+ "google.golang.org/protobuf/runtime/protoimpl"
+)
+
+// AnyResolver takes a type URL, present in an Any message,
+// and resolves it into an instance of the associated message.
+type AnyResolver interface {
+ Resolve(typeURL string) (proto.Message, error)
+}
+
+type anyResolver struct{ AnyResolver }
+
+func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
+ return r.FindMessageByURL(string(message))
+}
+
+func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) {
+ m, err := r.Resolve(url)
+ if err != nil {
+ return nil, err
+ }
+ return protoimpl.X.MessageTypeOf(m), nil
+}
+
+func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
+ return protoregistry.GlobalTypes.FindExtensionByName(field)
+}
+
+func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
+ return protoregistry.GlobalTypes.FindExtensionByNumber(message, field)
+}
+
+func wellKnownType(s protoreflect.FullName) string {
+ if s.Parent() == "google.protobuf" {
+ switch s.Name() {
+ case "Empty", "Any",
+ "BoolValue", "BytesValue", "StringValue",
+ "Int32Value", "UInt32Value", "FloatValue",
+ "Int64Value", "UInt64Value", "DoubleValue",
+ "Duration", "Timestamp",
+ "NullValue", "Struct", "Value", "ListValue":
+ return string(s.Name())
+ }
+ }
+ return ""
+}
+
+func isMessageSet(md protoreflect.MessageDescriptor) bool {
+ ms, ok := md.(interface{ IsMessageSet() bool })
+ return ok && ms.IsMessageSet()
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go b/vendor/github.com/golang/protobuf/jsonpb/json_test.go
similarity index 51%
rename from vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
rename to vendor/github.com/golang/protobuf/jsonpb/json_test.go
index 54ed681a0..0ef23f2d3 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
+++ b/vendor/github.com/golang/protobuf/jsonpb/json_test.go
@@ -1,38 +1,12 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package jsonpb
import (
"bytes"
+ "compress/gzip"
"encoding/json"
"io"
"math"
@@ -41,10 +15,11 @@ import (
"testing"
"github.com/golang/protobuf/proto"
-
- pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
"github.com/golang/protobuf/ptypes"
+
+ pb2 "github.com/golang/protobuf/internal/testprotos/jsonpb_proto"
+ pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
+ descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
anypb "github.com/golang/protobuf/ptypes/any"
durpb "github.com/golang/protobuf/ptypes/duration"
stpb "github.com/golang/protobuf/ptypes/struct"
@@ -59,49 +34,117 @@ var (
Indent: " ",
}
- simpleObject = &pb.Simple{
- OInt32: proto.Int32(-32),
- OInt64: proto.Int64(-6400000000),
- OUint32: proto.Uint32(32),
- OUint64: proto.Uint64(6400000000),
- OSint32: proto.Int32(-13),
- OSint64: proto.Int64(-2600000000),
- OFloat: proto.Float32(3.14),
- ODouble: proto.Float64(6.02214179e23),
- OBool: proto.Bool(true),
- OString: proto.String("hello \"there\""),
- OBytes: []byte("beep boop"),
+ simpleObject = &pb2.Simple{
+ OInt32: proto.Int32(-32),
+ OInt32Str: proto.Int32(-32),
+ OInt64: proto.Int64(-6400000000),
+ OInt64Str: proto.Int64(-6400000000),
+ OUint32: proto.Uint32(32),
+ OUint32Str: proto.Uint32(32),
+ OUint64: proto.Uint64(6400000000),
+ OUint64Str: proto.Uint64(6400000000),
+ OSint32: proto.Int32(-13),
+ OSint32Str: proto.Int32(-13),
+ OSint64: proto.Int64(-2600000000),
+ OSint64Str: proto.Int64(-2600000000),
+ OFloat: proto.Float32(3.14),
+ OFloatStr: proto.Float32(3.14),
+ ODouble: proto.Float64(6.02214179e23),
+ ODoubleStr: proto.Float64(6.02214179e23),
+ OBool: proto.Bool(true),
+ OString: proto.String("hello \"there\""),
+ OBytes: []byte("beep boop"),
}
- simpleObjectJSON = `{` +
+ simpleObjectInputJSON = `{` +
+ `"oBool":true,` +
+ `"oInt32":-32,` +
+ `"oInt32Str":"-32",` +
+ `"oInt64":-6400000000,` +
+ `"oInt64Str":"-6400000000",` +
+ `"oUint32":32,` +
+ `"oUint32Str":"32",` +
+ `"oUint64":6400000000,` +
+ `"oUint64Str":"6400000000",` +
+ `"oSint32":-13,` +
+ `"oSint32Str":"-13",` +
+ `"oSint64":-2600000000,` +
+ `"oSint64Str":"-2600000000",` +
+ `"oFloat":3.14,` +
+ `"oFloatStr":"3.14",` +
+ `"oDouble":6.02214179e+23,` +
+ `"oDoubleStr":"6.02214179e+23",` +
+ `"oString":"hello \"there\"",` +
+ `"oBytes":"YmVlcCBib29w"` +
+ `}`
+
+ simpleObjectOutputJSON = `{` +
`"oBool":true,` +
`"oInt32":-32,` +
+ `"oInt32Str":-32,` +
`"oInt64":"-6400000000",` +
+ `"oInt64Str":"-6400000000",` +
`"oUint32":32,` +
+ `"oUint32Str":32,` +
`"oUint64":"6400000000",` +
+ `"oUint64Str":"6400000000",` +
`"oSint32":-13,` +
+ `"oSint32Str":-13,` +
`"oSint64":"-2600000000",` +
+ `"oSint64Str":"-2600000000",` +
`"oFloat":3.14,` +
+ `"oFloatStr":3.14,` +
`"oDouble":6.02214179e+23,` +
+ `"oDoubleStr":6.02214179e+23,` +
`"oString":"hello \"there\"",` +
`"oBytes":"YmVlcCBib29w"` +
`}`
- simpleObjectPrettyJSON = `{
+ simpleObjectInputPrettyJSON = `{
"oBool": true,
"oInt32": -32,
+ "oInt32Str": "-32",
+ "oInt64": -6400000000,
+ "oInt64Str": "-6400000000",
+ "oUint32": 32,
+ "oUint32Str": "32",
+ "oUint64": 6400000000,
+ "oUint64Str": "6400000000",
+ "oSint32": -13,
+ "oSint32Str": "-13",
+ "oSint64": -2600000000,
+ "oSint64Str": "-2600000000",
+ "oFloat": 3.14,
+ "oFloatStr": "3.14",
+ "oDouble": 6.02214179e+23,
+ "oDoubleStr": "6.02214179e+23",
+ "oString": "hello \"there\"",
+ "oBytes": "YmVlcCBib29w"
+}`
+
+ simpleObjectOutputPrettyJSON = `{
+ "oBool": true,
+ "oInt32": -32,
+ "oInt32Str": -32,
"oInt64": "-6400000000",
+ "oInt64Str": "-6400000000",
"oUint32": 32,
+ "oUint32Str": 32,
"oUint64": "6400000000",
+ "oUint64Str": "6400000000",
"oSint32": -13,
+ "oSint32Str": -13,
"oSint64": "-2600000000",
+ "oSint64Str": "-2600000000",
"oFloat": 3.14,
+ "oFloatStr": 3.14,
"oDouble": 6.02214179e+23,
+ "oDoubleStr": 6.02214179e+23,
"oString": "hello \"there\"",
"oBytes": "YmVlcCBib29w"
}`
- repeatsObject = &pb.Repeats{
+ repeatsObject = &pb2.Repeats{
RBool: []bool{true, false, true},
RInt32: []int32{-3, -4, -5},
RInt64: []int64{-123456789, -987654321},
@@ -180,17 +223,17 @@ var (
]
}`
- innerSimple = &pb.Simple{OInt32: proto.Int32(-32)}
- innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)}
- innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}}
- innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}}
- complexObject = &pb.Widget{
- Color: pb.Widget_GREEN.Enum(),
- RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE},
+ innerSimple = &pb2.Simple{OInt32: proto.Int32(-32)}
+ innerSimple2 = &pb2.Simple{OInt64: proto.Int64(25)}
+ innerRepeats = &pb2.Repeats{RString: []string{"roses", "red"}}
+ innerRepeats2 = &pb2.Repeats{RString: []string{"violets", "blue"}}
+ complexObject = &pb2.Widget{
+ Color: pb2.Widget_GREEN.Enum(),
+ RColor: []pb2.Widget_Color{pb2.Widget_RED, pb2.Widget_GREEN, pb2.Widget_BLUE},
Simple: innerSimple,
- RSimple: []*pb.Simple{innerSimple, innerSimple2},
+ RSimple: []*pb2.Simple{innerSimple, innerSimple2},
Repeats: innerRepeats,
- RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2},
+ RRepeats: []*pb2.Repeats{innerRepeats, innerRepeats2},
}
complexObjectJSON = `{"color":"GREEN",` +
@@ -266,33 +309,33 @@ var (
}
}
}`
- realNumber = &pb.Real{Value: proto.Float64(3.14159265359)}
+ realNumber = &pb2.Real{Value: proto.Float64(3.14159265359)}
realNumberName = "Pi"
- complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)}
+ complexNumber = &pb2.Complex{Imaginary: proto.Float64(0.5772156649)}
realNumberJSON = `{` +
`"value":3.14159265359,` +
- `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` +
- `"[jsonpb.name]":"Pi"` +
+ `"[jsonpb_test.Complex.real_extension]":{"imaginary":0.5772156649},` +
+ `"[jsonpb_test.name]":"Pi"` +
`}`
- anySimple = &pb.KnownTypes{
+ anySimple = &pb2.KnownTypes{
An: &anypb.Any{
- TypeUrl: "something.example.com/jsonpb.Simple",
+ TypeUrl: "something.example.com/jsonpb_test.Simple",
Value: []byte{
- // &pb.Simple{OBool:true}
+ // &pb2.Simple{OBool:true}
1 << 3, 1,
},
},
}
- anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}`
+ anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb_test.Simple","oBool":true}}`
anySimplePrettyJSON = `{
"an": {
- "@type": "something.example.com/jsonpb.Simple",
+ "@type": "something.example.com/jsonpb_test.Simple",
"oBool": true
}
}`
- anyWellKnown = &pb.KnownTypes{
+ anyWellKnown = &pb2.KnownTypes{
An: &anypb.Any{
TypeUrl: "type.googleapis.com/google.protobuf.Duration",
Value: []byte{
@@ -310,7 +353,7 @@ var (
}
}`
- nonFinites = &pb.NonFinites{
+ nonFinites = &pb2.NonFinites{
FNan: proto.Float32(float32(math.NaN())),
FPinf: proto.Float32(float32(math.Inf(1))),
FNinf: proto.Float32(float32(math.Inf(-1))),
@@ -329,10 +372,10 @@ var (
)
func init() {
- if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil {
+ if err := proto.SetExtension(realNumber, pb2.E_Name, &realNumberName); err != nil {
panic(err)
}
- if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil {
+ if err := proto.SetExtension(realNumber, pb2.E_Complex_RealExtension, complexNumber); err != nil {
panic(err)
}
}
@@ -343,92 +386,98 @@ var marshalingTests = []struct {
pb proto.Message
json string
}{
- {"simple flat object", marshaler, simpleObject, simpleObjectJSON},
- {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON},
+ {"simple flat object", marshaler, simpleObject, simpleObjectOutputJSON},
+ {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectOutputPrettyJSON},
{"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON},
{"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON},
{"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON},
{"nested message/enum flat object", marshaler, complexObject, complexObjectJSON},
{"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON},
{"enum-string flat object", Marshaler{},
- &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`},
+ &pb2.Widget{Color: pb2.Widget_BLUE.Enum()}, `{"color":"BLUE"}`},
{"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "},
- &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON},
+ &pb2.Widget{Color: pb2.Widget_BLUE.Enum()}, colorPrettyJSON},
{"unknown enum value object", marshalerAllOptions,
- &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON},
+ &pb2.Widget{Color: pb2.Widget_Color(1000).Enum(), RColor: []pb2.Widget_Color{pb2.Widget_RED}}, colorListPrettyJSON},
{"repeated proto3 enum", Marshaler{},
- &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
- proto3pb.Message_PUNS,
- proto3pb.Message_SLAPSTICK,
+ &pb3.Message{RFunny: []pb3.Message_Humour{
+ pb3.Message_PUNS,
+ pb3.Message_SLAPSTICK,
}},
`{"rFunny":["PUNS","SLAPSTICK"]}`},
{"repeated proto3 enum as int", Marshaler{EnumsAsInts: true},
- &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
- proto3pb.Message_PUNS,
- proto3pb.Message_SLAPSTICK,
+ &pb3.Message{RFunny: []pb3.Message_Humour{
+ pb3.Message_PUNS,
+ pb3.Message_SLAPSTICK,
}},
`{"rFunny":[1,2]}`},
- {"empty value", marshaler, &pb.Simple3{}, `{}`},
- {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`},
- {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`},
- {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`},
- {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`},
- {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`},
- {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON},
+ {"empty value", marshaler, &pb2.Simple3{}, `{}`},
+ {"empty value emitted", Marshaler{EmitDefaults: true}, &pb2.Simple3{}, `{"dub":0}`},
+ {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb2.SimpleSlice3{}, `{"slices":[]}`},
+ {"empty map emitted", Marshaler{EmitDefaults: true}, &pb2.SimpleMap3{}, `{"stringy":{}}`},
+ {"nested struct null", Marshaler{EmitDefaults: true}, &pb2.SimpleNull3{}, `{"simple":null}`},
+ {"map", marshaler, &pb2.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`},
+ {"map", marshalerAllOptions, &pb2.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON},
{"map", marshaler,
- &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}},
+ &pb2.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}},
`{"strry":{"\"one\"":"two","three":"four"}}`},
{"map", marshaler,
- &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`},
+ &pb2.Mappy{Objjy: map[int32]*pb2.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`},
{"map", marshalerAllOptions,
- &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON},
- {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}},
+ &pb2.Mappy{Objjy: map[int32]*pb2.Simple3{1: {Dub: 1}}}, objjyPrettyJSON},
+ {"map", marshaler, &pb2.Mappy{Buggy: map[int64]string{1234: "yup"}},
`{"buggy":{"1234":"yup"}}`},
- {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`},
- // TODO: This is broken.
- //{"map", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`},
- {"map", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`},
- {"map", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`},
- {"map", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`},
- {"map", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`},
- {"map", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`},
- {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}},
+ {"map", marshaler, &pb2.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`},
+ {"map", marshaler, &pb2.Mappy{Enumy: map[string]pb2.Numeral{"XIV": pb2.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}}`},
+ {"map", Marshaler{EnumsAsInts: true}, &pb2.Mappy{Enumy: map[string]pb2.Numeral{"XIV": pb2.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`},
+ {"map", marshaler, &pb2.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"map", marshaler, &pb2.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"map", marshaler, &pb2.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"map", marshaler, &pb2.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"proto2 map", marshaler, &pb2.Maps{MInt64Str: map[int64]string{213: "cat"}},
`{"mInt64Str":{"213":"cat"}}`},
{"proto2 map", marshaler,
- &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}},
+ &pb2.Maps{MBoolSimple: map[bool]*pb2.Simple{true: {OInt32: proto.Int32(1)}}},
`{"mBoolSimple":{"true":{"oInt32":1}}}`},
- {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`},
- {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`},
- {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)},
+ {"oneof, not set", marshaler, &pb2.MsgWithOneof{}, `{}`},
+ {"oneof, set", marshaler, &pb2.MsgWithOneof{Union: &pb2.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`},
+ {"force orig_name", Marshaler{OrigName: true}, &pb2.Simple{OInt32: proto.Int32(4)},
`{"o_int32":4}`},
{"proto2 extension", marshaler, realNumber, realNumberJSON},
{"Any with message", marshaler, anySimple, anySimpleJSON},
{"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON},
{"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON},
{"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON},
- {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3s"}`},
- {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3, Nanos: 1e6}}, `{"dur":"3.001s"}`},
- {"Duration beyond float64 precision", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 100000000, Nanos: 1}}, `{"dur":"100000000.000000001s"}`},
- {"negative Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: -123, Nanos: -456}}, `{"dur":"-123.000000456s"}`},
- {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{
+ {"Duration empty", marshaler, &durpb.Duration{}, `"0s"`},
+ {"Duration with secs", marshaler, &durpb.Duration{Seconds: 3}, `"3s"`},
+ {"Duration with -secs", marshaler, &durpb.Duration{Seconds: -3}, `"-3s"`},
+ {"Duration with nanos", marshaler, &durpb.Duration{Nanos: 1e6}, `"0.001s"`},
+ {"Duration with -nanos", marshaler, &durpb.Duration{Nanos: -1e6}, `"-0.001s"`},
+ {"Duration with large secs", marshaler, &durpb.Duration{Seconds: 1e10, Nanos: 1}, `"10000000000.000000001s"`},
+ {"Duration with 6-digit nanos", marshaler, &durpb.Duration{Nanos: 1e4}, `"0.000010s"`},
+ {"Duration with 3-digit nanos", marshaler, &durpb.Duration{Nanos: 1e6}, `"0.001s"`},
+ {"Duration with -secs -nanos", marshaler, &durpb.Duration{Seconds: -123, Nanos: -450}, `"-123.000000450s"`},
+ {"Duration max value", marshaler, &durpb.Duration{Seconds: 315576000000, Nanos: 999999999}, `"315576000000.999999999s"`},
+ {"Duration min value", marshaler, &durpb.Duration{Seconds: -315576000000, Nanos: -999999999}, `"-315576000000.999999999s"`},
+ {"Struct", marshaler, &pb2.KnownTypes{St: &stpb.Struct{
Fields: map[string]*stpb.Value{
"one": {Kind: &stpb.Value_StringValue{"loneliest number"}},
"two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}},
},
}}, `{"st":{"one":"loneliest number","two":null}}`},
- {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`},
- {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
+ {"empty ListValue", marshaler, &pb2.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`},
+ {"basic ListValue", marshaler, &pb2.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
{Kind: &stpb.Value_StringValue{"x"}},
{Kind: &stpb.Value_NullValue{}},
{Kind: &stpb.Value_NumberValue{3}},
{Kind: &stpb.Value_BoolValue{true}},
}}}, `{"lv":["x",null,3,true]}`},
- {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`},
- {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}, `{"ts":"2014-05-13T16:53:20Z"}`},
- {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`},
- {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`},
- {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`},
- {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{
+ {"Timestamp", marshaler, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`},
+ {"Timestamp", marshaler, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}, `{"ts":"2014-05-13T16:53:20Z"}`},
+ {"number Value", marshaler, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`},
+ {"null Value", marshaler, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`},
+ {"string number value", marshaler, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`},
+ {"list of lists Value", marshaler, &pb2.KnownTypes{Val: &stpb.Value{
Kind: &stpb.Value_ListValue{&stpb.ListValue{
Values: []*stpb.Value{
{Kind: &stpb.Value_StringValue{"x"}},
@@ -444,18 +493,18 @@ var marshalingTests = []struct {
}},
}}, `{"val":["x",[["y"],"z"]]}`},
- {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`},
- {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`},
- {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`},
- {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`},
- {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`},
- {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`},
- {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`},
- {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`},
- {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`},
-
- {"required", marshaler, &pb.MsgWithRequired{Str: proto.String("hello")}, `{"str":"hello"}`},
- {"required bytes", marshaler, &pb.MsgWithRequiredBytes{Byts: []byte{}}, `{"byts":""}`},
+ {"DoubleValue", marshaler, &pb2.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`},
+ {"FloatValue", marshaler, &pb2.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`},
+ {"Int64Value", marshaler, &pb2.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`},
+ {"UInt64Value", marshaler, &pb2.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`},
+ {"Int32Value", marshaler, &pb2.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`},
+ {"UInt32Value", marshaler, &pb2.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`},
+ {"BoolValue", marshaler, &pb2.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`},
+ {"StringValue", marshaler, &pb2.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`},
+ {"BytesValue", marshaler, &pb2.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`},
+
+ {"required", marshaler, &pb2.MsgWithRequired{Str: proto.String("hello")}, `{"str":"hello"}`},
+ {"required bytes", marshaler, &pb2.MsgWithRequiredBytes{Byts: []byte{}}, `{"byts":""}`},
}
func TestMarshaling(t *testing.T) {
@@ -464,13 +513,13 @@ func TestMarshaling(t *testing.T) {
if err != nil {
t.Errorf("%s: marshaling error: %v", tt.desc, err)
} else if tt.json != json {
- t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json)
+ t.Errorf("%s:\ngot: %v\nwant: %v", tt.desc, json, tt.json)
}
}
}
func TestMarshalingNil(t *testing.T) {
- var msg *pb.Simple
+ var msg *pb2.Simple
m := &Marshaler{}
if _, err := m.MarshalToString(msg); err == nil {
t.Errorf("mashaling nil returned no error")
@@ -482,15 +531,17 @@ func TestMarshalIllegalTime(t *testing.T) {
pb proto.Message
fail bool
}{
- {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: 0}}, false},
- {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: 0}}, false},
- {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: -1}}, true},
- {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: 1}}, true},
- {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: 1000000000}}, true},
- {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: -1000000000}}, true},
- {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: 1}}, false},
- {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: -1}}, true},
- {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: 1000000000}}, true},
+ {&durpb.Duration{Seconds: 1, Nanos: 0}, false},
+ {&durpb.Duration{Seconds: -1, Nanos: 0}, false},
+ {&durpb.Duration{Seconds: 1, Nanos: -1}, true},
+ {&durpb.Duration{Seconds: -1, Nanos: 1}, true},
+ {&durpb.Duration{Seconds: 315576000001}, true},
+ {&durpb.Duration{Seconds: -315576000001}, true},
+ {&durpb.Duration{Seconds: 1, Nanos: 1000000000}, true},
+ {&durpb.Duration{Seconds: -1, Nanos: -1000000000}, true},
+ {&tspb.Timestamp{Seconds: 1, Nanos: 1}, false},
+ {&tspb.Timestamp{Seconds: 1, Nanos: -1}, true},
+ {&tspb.Timestamp{Seconds: 1, Nanos: 1000000000}, true},
}
for _, tt := range tests {
_, err := marshaler.MarshalToString(tt.pb)
@@ -505,51 +556,51 @@ func TestMarshalIllegalTime(t *testing.T) {
func TestMarshalJSONPBMarshaler(t *testing.T) {
rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
- msg := dynamicMessage{rawJson: rawJson}
+ msg := dynamicMessage{RawJson: rawJson}
str, err := new(Marshaler).MarshalToString(&msg)
if err != nil {
- t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err)
+ t.Errorf("an unexpected error while marshaling JSONPBMarshaler: %v", err)
}
if str != rawJson {
- t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson)
+ t.Errorf("marshaling JSON produced incorrect output: got %s, wanted %s", str, rawJson)
}
}
func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
- msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`}
+ msg := dynamicMessage{RawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`}
a, err := ptypes.MarshalAny(&msg)
if err != nil {
- t.Errorf("an unexpected error occurred when marshalling to Any: %v", err)
+ t.Errorf("an unexpected error while marshaling to Any: %v", err)
}
str, err := new(Marshaler).MarshalToString(a)
if err != nil {
- t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err)
+ t.Errorf("an unexpected error while marshaling Any to JSON: %v", err)
}
// after custom marshaling, it's round-tripped through JSON decoding/encoding already,
// so the keys are sorted, whitespace is compacted, and "@type" key has been added
- expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}`
- if str != expected {
- t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
+ want := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}`
+ if str != want {
+ t.Errorf("marshaling JSON produced incorrect output: got %s, wanted %s", str, want)
}
}
func TestMarshalWithCustomValidation(t *testing.T) {
- msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`, dummy: &dynamicMessage{}}
+ msg := dynamicMessage{RawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`, Dummy: &dynamicMessage{}}
js, err := new(Marshaler).MarshalToString(&msg)
if err != nil {
- t.Errorf("an unexpected error occurred when marshalling to json: %v", err)
+ t.Errorf("an unexpected error while marshaling to json: %v", err)
}
err = Unmarshal(strings.NewReader(js), &msg)
if err != nil {
- t.Errorf("an unexpected error occurred when unmarshalling from json: %v", err)
+ t.Errorf("an unexpected error while unmarshaling from json: %v", err)
}
}
// Test marshaling message containing unset required fields should produce error.
func TestMarshalUnsetRequiredFields(t *testing.T) {
- msgExt := &pb.Real{}
- proto.SetExtension(msgExt, pb.E_Extm, &pb.MsgWithRequired{})
+ msgExt := &pb2.Real{}
+ proto.SetExtension(msgExt, pb2.E_Extm, &pb2.MsgWithRequired{})
tests := []struct {
desc string
@@ -559,43 +610,43 @@ func TestMarshalUnsetRequiredFields(t *testing.T) {
{
desc: "direct required field",
marshaler: &Marshaler{},
- pb: &pb.MsgWithRequired{},
+ pb: &pb2.MsgWithRequired{},
},
{
desc: "direct required field + emit defaults",
marshaler: &Marshaler{EmitDefaults: true},
- pb: &pb.MsgWithRequired{},
+ pb: &pb2.MsgWithRequired{},
},
{
desc: "indirect required field",
marshaler: &Marshaler{},
- pb: &pb.MsgWithIndirectRequired{Subm: &pb.MsgWithRequired{}},
+ pb: &pb2.MsgWithIndirectRequired{Subm: &pb2.MsgWithRequired{}},
},
{
desc: "indirect required field + emit defaults",
marshaler: &Marshaler{EmitDefaults: true},
- pb: &pb.MsgWithIndirectRequired{Subm: &pb.MsgWithRequired{}},
+ pb: &pb2.MsgWithIndirectRequired{Subm: &pb2.MsgWithRequired{}},
},
{
desc: "direct required wkt field",
marshaler: &Marshaler{},
- pb: &pb.MsgWithRequiredWKT{},
+ pb: &pb2.MsgWithRequiredWKT{},
},
{
desc: "direct required wkt field + emit defaults",
marshaler: &Marshaler{EmitDefaults: true},
- pb: &pb.MsgWithRequiredWKT{},
+ pb: &pb2.MsgWithRequiredWKT{},
},
{
desc: "direct required bytes field",
marshaler: &Marshaler{},
- pb: &pb.MsgWithRequiredBytes{},
+ pb: &pb2.MsgWithRequiredBytes{},
},
{
desc: "required in map value",
marshaler: &Marshaler{},
- pb: &pb.MsgWithIndirectRequired{
- MapField: map[string]*pb.MsgWithRequired{
+ pb: &pb2.MsgWithIndirectRequired{
+ MapField: map[string]*pb2.MsgWithRequired{
"key": {},
},
},
@@ -603,8 +654,8 @@ func TestMarshalUnsetRequiredFields(t *testing.T) {
{
desc: "required in repeated item",
marshaler: &Marshaler{},
- pb: &pb.MsgWithIndirectRequired{
- SliceField: []*pb.MsgWithRequired{
+ pb: &pb2.MsgWithIndirectRequired{
+ SliceField: []*pb2.MsgWithRequired{
{Str: proto.String("hello")},
{},
},
@@ -613,8 +664,8 @@ func TestMarshalUnsetRequiredFields(t *testing.T) {
{
desc: "required inside oneof",
marshaler: &Marshaler{},
- pb: &pb.MsgWithOneof{
- Union: &pb.MsgWithOneof_MsgWithRequired{&pb.MsgWithRequired{}},
+ pb: &pb2.MsgWithOneof{
+ Union: &pb2.MsgWithOneof_MsgWithRequired{&pb2.MsgWithRequired{}},
},
},
{
@@ -626,7 +677,7 @@ func TestMarshalUnsetRequiredFields(t *testing.T) {
for _, tc := range tests {
if _, err := tc.marshaler.MarshalToString(tc.pb); err == nil {
- t.Errorf("%s: expecting error in marshaling with unset required fields %+v", tc.desc, tc.pb)
+ t.Errorf("%s: expected error while marshaling with unset required fields %+v", tc.desc, tc.pb)
}
}
}
@@ -637,79 +688,78 @@ var unmarshalingTests = []struct {
json string
pb proto.Message
}{
- {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject},
- {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject},
+ {"simple flat object", Unmarshaler{}, simpleObjectInputJSON, simpleObject},
+ {"simple pretty object", Unmarshaler{}, simpleObjectInputPrettyJSON, simpleObject},
{"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject},
{"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject},
{"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject},
{"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject},
- {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
- {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
- {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)},
- {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
- {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
+ {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb2.Widget{Color: pb2.Widget_BLUE.Enum()}},
+ {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb2.Widget{Color: pb2.Widget_BLUE.Enum()}},
+ {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb2.Simple)},
+ {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &pb3.Message{Hilarity: pb3.Message_PUNS}},
+ {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &pb3.Message{Hilarity: pb3.Message_PUNS}},
{"unknown enum value object",
Unmarshaler{},
"{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}",
- &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}},
+ &pb2.Widget{Color: pb2.Widget_Color(1000).Enum(), RColor: []pb2.Widget_Color{pb2.Widget_RED}}},
{"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`,
- &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
- proto3pb.Message_PUNS,
- proto3pb.Message_SLAPSTICK,
+ &pb3.Message{RFunny: []pb3.Message_Humour{
+ pb3.Message_PUNS,
+ pb3.Message_SLAPSTICK,
}}},
{"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`,
- &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
- proto3pb.Message_PUNS,
- proto3pb.Message_SLAPSTICK,
+ &pb3.Message{RFunny: []pb3.Message_Humour{
+ pb3.Message_PUNS,
+ pb3.Message_SLAPSTICK,
}}},
{"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`,
- &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
- proto3pb.Message_PUNS,
- proto3pb.Message_SLAPSTICK,
+ &pb3.Message{RFunny: []pb3.Message_Humour{
+ pb3.Message_PUNS,
+ pb3.Message_SLAPSTICK,
}}},
- {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}},
- {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}},
- {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}},
- {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}},
- {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}},
- {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}},
- {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}},
- {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}},
+ {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb2.Simple{OInt64: proto.Int64(-314)}},
+ {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb2.Simple{OUint64: proto.Uint64(123)}},
+ {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb2.Simple{ODouble: proto.Float64(math.NaN())}},
+ {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb2.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}},
+ {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb2.Simple{ODouble: proto.Float64(math.Inf(-1))}},
+ {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb2.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}},
+ {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb2.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}},
+ {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb2.Mappy{Objjy: map[int32]*pb2.Simple3{1: {Dub: 1}}}},
{"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber},
{"Any with message", Unmarshaler{}, anySimpleJSON, anySimple},
{"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple},
{"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown},
{"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown},
- // TODO: This is broken.
- //{"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
- {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
- {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}},
- {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
- {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
- {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
- {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
- {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
- {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
-
- {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
- {"Duration", Unmarshaler{}, `{"dur":"4s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 4}}},
- {"Duration with unicode", Unmarshaler{}, `{"dur": "3\u0073"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
- {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}},
- {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}},
- {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}},
- {"Timestamp with unicode", Unmarshaler{}, `{"ts": "2014-05-13T16:53:20\u005a"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}},
- {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}},
- {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}},
- {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}},
- {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}},
- {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}},
- {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
+ {"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}}`, &pb2.Mappy{Enumy: map[string]pb2.Numeral{"XIV": pb2.Numeral_ROMAN}}},
+ {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb2.Mappy{Enumy: map[string]pb2.Numeral{"XIV": pb2.Numeral_ROMAN}}},
+ {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb2.MsgWithOneof{Union: &pb2.MsgWithOneof_Salary{31000}}},
+ {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb2.MsgWithOneof{Union: &pb2.MsgWithOneof_Country{"Australia"}}},
+ {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb2.MsgWithOneof{Union: &pb2.MsgWithOneof_Country{"Australia"}}},
+ {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb2.MsgWithOneof{Union: &pb2.MsgWithOneof_HomeAddress{"Australia"}}},
+ {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb2.MsgWithOneof{Union: &pb2.MsgWithOneof_HomeAddress{"Australia"}}},
+ {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb2.Simple{OBool: proto.Bool(true)}},
+ {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb2.Simple{OBool: proto.Bool(true)}},
+
+ {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb2.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
+ {"Duration", Unmarshaler{}, `{"dur":"4s"}`, &pb2.KnownTypes{Dur: &durpb.Duration{Seconds: 4}}},
+ {"Duration with unicode", Unmarshaler{}, `{"dur": "3\u0073"}`, &pb2.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
+ {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb2.KnownTypes{Dur: nil}},
+ {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}},
+ {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20Z"}`, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}},
+ {"Timestamp with unicode", Unmarshaler{}, `{"ts": "2014-05-13T16:53:20\u005a"}`, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}},
+ {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}},
+ {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb2.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}},
+ {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb2.KnownTypes{Ts: nil}},
+ {"null Struct", Unmarshaler{}, `{"st": null}`, &pb2.KnownTypes{St: nil}},
+ {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb2.KnownTypes{St: &stpb.Struct{}}},
+ {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb2.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
"a": {Kind: &stpb.Value_StringValue{"x"}},
"b": {Kind: &stpb.Value_NullValue{}},
"c": {Kind: &stpb.Value_NumberValue{3}},
"d": {Kind: &stpb.Value_BoolValue{true}},
}}}},
- {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
+ {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb2.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
"a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{
"b": {Kind: &stpb.Value_NumberValue{1}},
"c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{
@@ -718,20 +768,20 @@ var unmarshalingTests = []struct {
}}}},
}}}},
}}}},
- {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}},
- {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}},
- {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
+ {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb2.KnownTypes{Lv: nil}},
+ {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb2.KnownTypes{Lv: &stpb.ListValue{}}},
+ {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb2.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
{Kind: &stpb.Value_StringValue{"x"}},
{Kind: &stpb.Value_NullValue{}},
{Kind: &stpb.Value_NumberValue{3}},
{Kind: &stpb.Value_BoolValue{true}},
}}}},
- {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}},
- {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}},
- {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}},
- {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}},
- {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}},
- {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{
+ {"number Value", Unmarshaler{}, `{"val":1}`, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}},
+ {"null Value", Unmarshaler{}, `{"val":null}`, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}},
+ {"bool Value", Unmarshaler{}, `{"val":true}`, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}},
+ {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}},
+ {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb2.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}},
+ {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb2.KnownTypes{Val: &stpb.Value{
Kind: &stpb.Value_ListValue{&stpb.ListValue{
Values: []*stpb.Value{
{Kind: &stpb.Value_StringValue{"x"}},
@@ -746,15 +796,15 @@ var unmarshalingTests = []struct {
},
}}}}},
- {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}},
- {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}},
- {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}},
- {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}},
- {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}},
- {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}},
- {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}},
- {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}},
- {"StringValue containing escaped character", Unmarshaler{}, `{"str":"a\/b"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "a/b"}}},
+ {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb2.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}},
+ {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb2.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}},
+ {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb2.KnownTypes{I64: &wpb.Int64Value{Value: -3}}},
+ {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb2.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}},
+ {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb2.KnownTypes{I32: &wpb.Int32Value{Value: -4}}},
+ {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb2.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}},
+ {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb2.KnownTypes{Bool: &wpb.BoolValue{Value: true}}},
+ {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb2.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}},
+ {"StringValue containing escaped character", Unmarshaler{}, `{"str":"a\/b"}`, &pb2.KnownTypes{Str: &wpb.StringValue{Value: "a/b"}}},
{"StructValue containing StringValue's", Unmarshaler{}, `{"escaped": "a\/b", "unicode": "\u00004E16\u0000754C"}`,
&stpb.Struct{
Fields: map[string]*stpb.Value{
@@ -762,31 +812,31 @@ var unmarshalingTests = []struct {
"unicode": {Kind: &stpb.Value_StringValue{"\u00004E16\u0000754C"}},
},
}},
- {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}},
+ {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb2.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}},
// Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct.
- {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}},
- {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}},
- {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}},
- {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}},
- {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}},
- {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}},
- {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}},
- {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}},
- {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}},
-
- {"required", Unmarshaler{}, `{"str":"hello"}`, &pb.MsgWithRequired{Str: proto.String("hello")}},
- {"required bytes", Unmarshaler{}, `{"byts": []}`, &pb.MsgWithRequiredBytes{Byts: []byte{}}},
+ {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb2.KnownTypes{Dbl: nil}},
+ {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb2.KnownTypes{Flt: nil}},
+ {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb2.KnownTypes{I64: nil}},
+ {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb2.KnownTypes{U64: nil}},
+ {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb2.KnownTypes{I32: nil}},
+ {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb2.KnownTypes{U32: nil}},
+ {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb2.KnownTypes{Bool: nil}},
+ {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb2.KnownTypes{Str: nil}},
+ {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb2.KnownTypes{Bytes: nil}},
+
+ {"required", Unmarshaler{}, `{"str":"hello"}`, &pb2.MsgWithRequired{Str: proto.String("hello")}},
+ {"required bytes", Unmarshaler{}, `{"byts": []}`, &pb2.MsgWithRequiredBytes{Byts: []byte{}}},
}
func TestUnmarshaling(t *testing.T) {
for _, tt := range unmarshalingTests {
- // Make a new instance of the type of our expected object.
+ // Make a new instance of the type of our wanted object.
p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p)
if err != nil {
- t.Errorf("%s: %v", tt.desc, err)
+ t.Errorf("unmarshaling %s: %v", tt.desc, err)
continue
}
@@ -800,21 +850,21 @@ func TestUnmarshaling(t *testing.T) {
}
func TestUnmarshalNullArray(t *testing.T) {
- var repeats pb.Repeats
+ var repeats pb2.Repeats
if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil {
t.Fatal(err)
}
- if !reflect.DeepEqual(repeats, pb.Repeats{}) {
+ if !proto.Equal(&repeats, &pb2.Repeats{}) {
t.Errorf("got non-nil fields in [%#v]", repeats)
}
}
func TestUnmarshalNullObject(t *testing.T) {
- var maps pb.Maps
+ var maps pb2.Maps
if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil {
t.Fatal(err)
}
- if !reflect.DeepEqual(maps, pb.Maps{}) {
+ if !proto.Equal(&maps, &pb2.Maps{}) {
t.Errorf("got non-nil fields in [%#v]", maps)
}
}
@@ -831,7 +881,7 @@ func TestUnmarshalNext(t *testing.T) {
dec := json.NewDecoder(&b)
for _, tt := range tests {
- // Make a new instance of the type of our expected object.
+ // Make a new instance of the type of our wanted object.
p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
err := tt.unmarshaler.UnmarshalNext(dec, p)
@@ -848,10 +898,10 @@ func TestUnmarshalNext(t *testing.T) {
}
}
- p := &pb.Simple{}
+ p := &pb2.Simple{}
err := new(Unmarshaler).UnmarshalNext(dec, p)
if err != io.EOF {
- t.Errorf("eof: got %v, expected io.EOF", err)
+ t.Errorf("eof: got %v, want io.EOF", err)
}
}
@@ -860,22 +910,24 @@ var unmarshalingShouldError = []struct {
in string
pb proto.Message
}{
- {"a value", "666", new(pb.Simple)},
- {"gibberish", "{adskja123;l23=-=", new(pb.Simple)},
- {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)},
- {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)},
- {"Duration containing invalid character", `{"dur": "3\U0073"}`, &pb.KnownTypes{}},
- {"Timestamp containing invalid character", `{"ts": "2014-05-13T16:53:20\U005a"}`, &pb.KnownTypes{}},
- {"StringValue containing invalid character", `{"str": "\U00004E16\U0000754C"}`, &pb.KnownTypes{}},
+ {"a value", "666", new(pb2.Simple)},
+ {"gibberish", "{adskja123;l23=-=", new(pb2.Simple)},
+ {"unknown field", `{"unknown": "foo"}`, new(pb2.Simple)},
+ {"unknown enum name", `{"hilarity":"DAVE"}`, new(pb3.Message)},
+ {"Duration containing invalid character", `{"dur": "3\U0073"}`, &pb2.KnownTypes{}},
+ {"Timestamp containing invalid character", `{"ts": "2014-05-13T16:53:20\U005a"}`, &pb2.KnownTypes{}},
+ {"StringValue containing invalid character", `{"str": "\U00004E16\U0000754C"}`, &pb2.KnownTypes{}},
{"StructValue containing invalid character", `{"str": "\U00004E16\U0000754C"}`, &stpb.Struct{}},
- {"repeated proto3 enum with non array input", `{"rFunny":"PUNS"}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{}}},
+ {"repeated proto3 enum with non array input", `{"rFunny":"PUNS"}`, &pb3.Message{RFunny: []pb3.Message_Humour{}}},
+ {"unknown extension field", `{"[ext_unknown]": "value"}`, &pb2.Real{}},
+ {"extension field for wrong message", `{"[jsonpb_test.name]": "value"}`, &pb2.Complex{}},
}
func TestUnmarshalingBadInput(t *testing.T) {
for _, tt := range unmarshalingShouldError {
err := UnmarshalString(tt.in, tt.pb)
if err == nil {
- t.Errorf("an error was expected when parsing %q instead of an object", tt.desc)
+ t.Errorf("expected error while parsing %q", tt.desc)
}
}
}
@@ -890,9 +942,9 @@ func TestAnyWithCustomResolver(t *testing.T) {
var resolvedTypeUrls []string
resolver := funcResolver(func(turl string) (proto.Message, error) {
resolvedTypeUrls = append(resolvedTypeUrls, turl)
- return new(pb.Simple), nil
+ return new(pb2.Simple), nil
})
- msg := &pb.Simple{
+ msg := &pb2.Simple{
OBytes: []byte{1, 2, 3, 4},
OBool: proto.Bool(true),
OString: proto.String("foobar"),
@@ -900,7 +952,7 @@ func TestAnyWithCustomResolver(t *testing.T) {
}
msgBytes, err := proto.Marshal(msg)
if err != nil {
- t.Errorf("an unexpected error occurred when marshaling message: %v", err)
+ t.Errorf("an unexpected error while marshaling message: %v", err)
}
// make an Any with a type URL that won't resolve w/out custom resolver
any := &anypb.Any{
@@ -911,7 +963,7 @@ func TestAnyWithCustomResolver(t *testing.T) {
m := Marshaler{AnyResolver: resolver}
js, err := m.MarshalToString(any)
if err != nil {
- t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err)
+ t.Errorf("an unexpected error while marshaling any to JSON: %v", err)
}
if len(resolvedTypeUrls) != 1 {
t.Errorf("custom resolver was not invoked during marshaling")
@@ -920,14 +972,14 @@ func TestAnyWithCustomResolver(t *testing.T) {
}
wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}`
if js != wanted {
- t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted)
+ t.Errorf("marshaling JSON produced incorrect output: got %s, wanted %s", js, wanted)
}
u := Unmarshaler{AnyResolver: resolver}
roundTrip := &anypb.Any{}
err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip)
if err != nil {
- t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err)
+ t.Errorf("an unexpected error while unmarshaling any from JSON: %v", err)
}
if len(resolvedTypeUrls) != 2 {
t.Errorf("custom resolver was not invoked during marshaling")
@@ -935,7 +987,7 @@ func TestAnyWithCustomResolver(t *testing.T) {
t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind")
}
if !proto.Equal(any, roundTrip) {
- t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any)
+ t.Errorf("message contents not set correctly after unmarshaling JSON: got %s, wanted %s", roundTrip, any)
}
}
@@ -943,10 +995,10 @@ func TestUnmarshalJSONPBUnmarshaler(t *testing.T) {
rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
var msg dynamicMessage
if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil {
- t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
+ t.Errorf("an unexpected error while parsing into JSONPBUnmarshaler: %v", err)
}
- if msg.rawJson != rawJson {
- t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson)
+ if msg.RawJson != rawJson {
+ t.Errorf("message contents not set correctly after unmarshaling JSON: got %s, wanted %s", msg.RawJson, rawJson)
}
}
@@ -957,7 +1009,7 @@ func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) {
t.Errorf("unmarshal error: %v", err)
}
- want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}}
+ want := ptrFieldMessage{}
if !proto.Equal(&ptrFieldMsg, &want) {
t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want)
}
@@ -967,25 +1019,25 @@ func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) {
rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }`
var got anypb.Any
if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil {
- t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
+ t.Errorf("an unexpected error while parsing into JSONPBUnmarshaler: %v", err)
}
- dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`}
+ dm := &dynamicMessage{RawJson: `{"baz":[0,1,2,3],"foo":"bar"}`}
var want anypb.Any
if b, err := proto.Marshal(dm); err != nil {
- t.Errorf("an unexpected error occurred when marshaling message: %v", err)
+ t.Errorf("an unexpected error while marshaling message: %v", err)
} else {
want.TypeUrl = "blah.com/" + dynamicMessageName
want.Value = b
}
if !proto.Equal(&got, &want) {
- t.Errorf("message contents not set correctly after unmarshalling JSON: got %v, wanted %v", got, want)
+ t.Errorf("message contents not set correctly after unmarshaling JSON: got %v, wanted %v", &got, &want)
}
}
const (
- dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage"
+ dynamicMessageName = "github_com.golang.protobuf.jsonpb.dynamicMessage"
)
func init() {
@@ -1007,6 +1059,10 @@ func (m *ptrFieldMessage) String() string {
func (m *ptrFieldMessage) ProtoMessage() {
}
+func (m *ptrFieldMessage) Descriptor() ([]byte, []int) {
+ return testMessageFD, []int{0}
+}
+
type stringField struct {
IsSet bool `protobuf:"varint,1,opt,name=isSet"`
StringValue string `protobuf:"bytes,2,opt,name=stringValue"`
@@ -1022,6 +1078,10 @@ func (s *stringField) String() string {
func (s *stringField) ProtoMessage() {
}
+func (s *stringField) Descriptor() ([]byte, []int) {
+ return testMessageFD, []int{1}
+}
+
func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
s.IsSet = true
s.StringValue = string(js)
@@ -1031,33 +1091,70 @@ func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
// dynamicMessage implements protobuf.Message but is not a normal generated message type.
// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support.
type dynamicMessage struct {
- rawJson string `protobuf:"bytes,1,opt,name=rawJson"`
+ RawJson string `protobuf:"bytes,1,opt,name=rawJson"`
// an unexported nested message is present just to ensure that it
// won't result in a panic (see issue #509)
- dummy *dynamicMessage `protobuf:"bytes,2,opt,name=dummy"`
+ Dummy *dynamicMessage `protobuf:"bytes,2,opt,name=dummy"`
}
func (m *dynamicMessage) Reset() {
- m.rawJson = "{}"
+ m.RawJson = "{}"
}
func (m *dynamicMessage) String() string {
- return m.rawJson
+ return m.RawJson
}
func (m *dynamicMessage) ProtoMessage() {
}
+func (m *dynamicMessage) Descriptor() ([]byte, []int) {
+ return testMessageFD, []int{2}
+}
+
func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) {
- return []byte(m.rawJson), nil
+ return []byte(m.RawJson), nil
}
func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
- m.rawJson = string(js)
+ m.RawJson = string(js)
return nil
}
+var testMessageFD = func() []byte {
+ fd := new(descpb.FileDescriptorProto)
+ proto.UnmarshalText(`
+ name: "jsonpb.proto"
+ package: "github_com.golang.protobuf.jsonpb"
+ syntax: "proto3"
+ message_type: [{
+ name: "ptrFieldMessage"
+ field: [
+ {name:"stringField" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE type_name:".github_com.golang.protobuf.jsonpb.stringField"}
+ ]
+ }, {
+ name: "stringField"
+ field: [
+ {name:"isSet" number:1 label:LABEL_OPTIONAL type:TYPE_BOOL},
+ {name:"stringValue" number:2 label:LABEL_OPTIONAL type:TYPE_STRING}
+ ]
+ }, {
+ name: "dynamicMessage"
+ field: [
+ {name:"rawJson" number:1 label:LABEL_OPTIONAL type:TYPE_BYTES},
+ {name:"dummy" number:2 label:LABEL_OPTIONAL type:TYPE_MESSAGE type_name:".github_com.golang.protobuf.jsonpb.dynamicMessage"}
+ ]
+ }]
+ `, fd)
+ b, _ := proto.Marshal(fd)
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ zw.Write(b)
+ zw.Close()
+ return buf.Bytes()
+}()
+
// Test unmarshaling message containing unset required fields should produce error.
func TestUnmarshalUnsetRequiredFields(t *testing.T) {
tests := []struct {
@@ -1067,99 +1164,99 @@ func TestUnmarshalUnsetRequiredFields(t *testing.T) {
}{
{
desc: "direct required field missing",
- pb: &pb.MsgWithRequired{},
+ pb: &pb2.MsgWithRequired{},
json: `{}`,
},
{
desc: "direct required field set to null",
- pb: &pb.MsgWithRequired{},
+ pb: &pb2.MsgWithRequired{},
json: `{"str": null}`,
},
{
desc: "indirect required field missing",
- pb: &pb.MsgWithIndirectRequired{},
+ pb: &pb2.MsgWithIndirectRequired{},
json: `{"subm": {}}`,
},
{
desc: "indirect required field set to null",
- pb: &pb.MsgWithIndirectRequired{},
+ pb: &pb2.MsgWithIndirectRequired{},
json: `{"subm": {"str": null}}`,
},
{
desc: "direct required bytes field missing",
- pb: &pb.MsgWithRequiredBytes{},
+ pb: &pb2.MsgWithRequiredBytes{},
json: `{}`,
},
{
desc: "direct required bytes field set to null",
- pb: &pb.MsgWithRequiredBytes{},
+ pb: &pb2.MsgWithRequiredBytes{},
json: `{"byts": null}`,
},
{
desc: "direct required wkt field missing",
- pb: &pb.MsgWithRequiredWKT{},
+ pb: &pb2.MsgWithRequiredWKT{},
json: `{}`,
},
{
desc: "direct required wkt field set to null",
- pb: &pb.MsgWithRequiredWKT{},
+ pb: &pb2.MsgWithRequiredWKT{},
json: `{"str": null}`,
},
{
desc: "any containing message with required field set to null",
- pb: &pb.KnownTypes{},
+ pb: &pb2.KnownTypes{},
json: `{"an": {"@type": "example.com/jsonpb.MsgWithRequired", "str": null}}`,
},
{
desc: "any containing message with missing required field",
- pb: &pb.KnownTypes{},
+ pb: &pb2.KnownTypes{},
json: `{"an": {"@type": "example.com/jsonpb.MsgWithRequired"}}`,
},
{
desc: "missing required in map value",
- pb: &pb.MsgWithIndirectRequired{},
+ pb: &pb2.MsgWithIndirectRequired{},
json: `{"map_field": {"a": {}, "b": {"str": "hi"}}}`,
},
{
desc: "required in map value set to null",
- pb: &pb.MsgWithIndirectRequired{},
+ pb: &pb2.MsgWithIndirectRequired{},
json: `{"map_field": {"a": {"str": "hello"}, "b": {"str": null}}}`,
},
{
desc: "missing required in slice item",
- pb: &pb.MsgWithIndirectRequired{},
+ pb: &pb2.MsgWithIndirectRequired{},
json: `{"slice_field": [{}, {"str": "hi"}]}`,
},
{
desc: "required in slice item set to null",
- pb: &pb.MsgWithIndirectRequired{},
+ pb: &pb2.MsgWithIndirectRequired{},
json: `{"slice_field": [{"str": "hello"}, {"str": null}]}`,
},
{
desc: "required inside oneof missing",
- pb: &pb.MsgWithOneof{},
+ pb: &pb2.MsgWithOneof{},
json: `{"msgWithRequired": {}}`,
},
{
desc: "required inside oneof set to null",
- pb: &pb.MsgWithOneof{},
+ pb: &pb2.MsgWithOneof{},
json: `{"msgWithRequired": {"str": null}}`,
},
{
desc: "required field in extension missing",
- pb: &pb.Real{},
+ pb: &pb2.Real{},
json: `{"[jsonpb.extm]":{}}`,
},
{
desc: "required field in extension set to null",
- pb: &pb.Real{},
+ pb: &pb2.Real{},
json: `{"[jsonpb.extm]":{"str": null}}`,
},
}
for _, tc := range tests {
if err := UnmarshalString(tc.json, tc.pb); err == nil {
- t.Errorf("%s: expecting error in unmarshaling with unset required fields %s", tc.desc, tc.json)
+ t.Errorf("%s: expected error while unmarshaling with unset required fields %s", tc.desc, tc.json)
}
}
}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
deleted file mode 100644
index 242e3155b..000000000
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
+++ /dev/null
@@ -1,1250 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
-Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
-It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json.
-
-This package produces a different output than the standard "encoding/json" package,
-which does not operate correctly on protocol buffers.
-*/
-package jsonpb
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "math"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/golang/protobuf/proto"
-
- stpb "github.com/golang/protobuf/ptypes/struct"
-)
-
-const secondInNanos = int64(time.Second / time.Nanosecond)
-
-// Marshaler is a configurable object for converting between
-// protocol buffer objects and a JSON representation for them.
-type Marshaler struct {
- // Whether to render enum values as integers, as opposed to string values.
- EnumsAsInts bool
-
- // Whether to render fields with zero values.
- EmitDefaults bool
-
- // A string to indent each level by. The presence of this field will
- // also cause a space to appear between the field separator and
- // value, and for newlines to be appear between fields and array
- // elements.
- Indent string
-
- // Whether to use the original (.proto) name for fields.
- OrigName bool
-
- // A custom URL resolver to use when marshaling Any messages to JSON.
- // If unset, the default resolution strategy is to extract the
- // fully-qualified type name from the type URL and pass that to
- // proto.MessageType(string).
- AnyResolver AnyResolver
-}
-
-// AnyResolver takes a type URL, present in an Any message, and resolves it into
-// an instance of the associated message.
-type AnyResolver interface {
- Resolve(typeUrl string) (proto.Message, error)
-}
-
-func defaultResolveAny(typeUrl string) (proto.Message, error) {
- // Only the part of typeUrl after the last slash is relevant.
- mname := typeUrl
- if slash := strings.LastIndex(mname, "/"); slash >= 0 {
- mname = mname[slash+1:]
- }
- mt := proto.MessageType(mname)
- if mt == nil {
- return nil, fmt.Errorf("unknown message type %q", mname)
- }
- return reflect.New(mt.Elem()).Interface().(proto.Message), nil
-}
-
-// JSONPBMarshaler is implemented by protobuf messages that customize the
-// way they are marshaled to JSON. Messages that implement this should
-// also implement JSONPBUnmarshaler so that the custom format can be
-// parsed.
-type JSONPBMarshaler interface {
- MarshalJSONPB(*Marshaler) ([]byte, error)
-}
-
-// JSONPBUnmarshaler is implemented by protobuf messages that customize
-// the way they are unmarshaled from JSON. Messages that implement this
-// should also implement JSONPBMarshaler so that the custom format can be
-// produced.
-type JSONPBUnmarshaler interface {
- UnmarshalJSONPB(*Unmarshaler, []byte) error
-}
-
-// Marshal marshals a protocol buffer into JSON.
-func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
- v := reflect.ValueOf(pb)
- if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
- return errors.New("Marshal called with nil")
- }
- // Check for unset required fields first.
- if err := checkRequiredFields(pb); err != nil {
- return err
- }
- writer := &errWriter{writer: out}
- return m.marshalObject(writer, pb, "", "")
-}
-
-// MarshalToString converts a protocol buffer object to JSON string.
-func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
- var buf bytes.Buffer
- if err := m.Marshal(&buf, pb); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
-
-type int32Slice []int32
-
-var nonFinite = map[string]float64{
- `"NaN"`: math.NaN(),
- `"Infinity"`: math.Inf(1),
- `"-Infinity"`: math.Inf(-1),
-}
-
-// For sorting extensions ids to ensure stable output.
-func (s int32Slice) Len() int { return len(s) }
-func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
-func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-
-type wkt interface {
- XXX_WellKnownType() string
-}
-
-// marshalObject writes a struct to the Writer.
-func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
- if jsm, ok := v.(JSONPBMarshaler); ok {
- b, err := jsm.MarshalJSONPB(m)
- if err != nil {
- return err
- }
- if typeURL != "" {
- // we are marshaling this object to an Any type
- var js map[string]*json.RawMessage
- if err = json.Unmarshal(b, &js); err != nil {
- return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
- }
- turl, err := json.Marshal(typeURL)
- if err != nil {
- return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
- }
- js["@type"] = (*json.RawMessage)(&turl)
- if b, err = json.Marshal(js); err != nil {
- return err
- }
- }
-
- out.write(string(b))
- return out.err
- }
-
- s := reflect.ValueOf(v).Elem()
-
- // Handle well-known types.
- if wkt, ok := v.(wkt); ok {
- switch wkt.XXX_WellKnownType() {
- case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
- "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
- // "Wrappers use the same representation in JSON
- // as the wrapped primitive type, ..."
- sprop := proto.GetProperties(s.Type())
- return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent)
- case "Any":
- // Any is a bit more involved.
- return m.marshalAny(out, v, indent)
- case "Duration":
- // "Generated output always contains 0, 3, 6, or 9 fractional digits,
- // depending on required precision."
- s, ns := s.Field(0).Int(), s.Field(1).Int()
- if ns <= -secondInNanos || ns >= secondInNanos {
- return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
- }
- if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
- return errors.New("signs of seconds and nanos do not match")
- }
- if s < 0 {
- ns = -ns
- }
- x := fmt.Sprintf("%d.%09d", s, ns)
- x = strings.TrimSuffix(x, "000")
- x = strings.TrimSuffix(x, "000")
- x = strings.TrimSuffix(x, ".000")
- out.write(`"`)
- out.write(x)
- out.write(`s"`)
- return out.err
- case "Struct", "ListValue":
- // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice.
- // TODO: pass the correct Properties if needed.
- return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent)
- case "Timestamp":
- // "RFC 3339, where generated output will always be Z-normalized
- // and uses 0, 3, 6 or 9 fractional digits."
- s, ns := s.Field(0).Int(), s.Field(1).Int()
- if ns < 0 || ns >= secondInNanos {
- return fmt.Errorf("ns out of range [0, %v)", secondInNanos)
- }
- t := time.Unix(s, ns).UTC()
- // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
- x := t.Format("2006-01-02T15:04:05.000000000")
- x = strings.TrimSuffix(x, "000")
- x = strings.TrimSuffix(x, "000")
- x = strings.TrimSuffix(x, ".000")
- out.write(`"`)
- out.write(x)
- out.write(`Z"`)
- return out.err
- case "Value":
- // Value has a single oneof.
- kind := s.Field(0)
- if kind.IsNil() {
- // "absence of any variant indicates an error"
- return errors.New("nil Value")
- }
- // oneof -> *T -> T -> T.F
- x := kind.Elem().Elem().Field(0)
- // TODO: pass the correct Properties if needed.
- return m.marshalValue(out, &proto.Properties{}, x, indent)
- }
- }
-
- out.write("{")
- if m.Indent != "" {
- out.write("\n")
- }
-
- firstField := true
-
- if typeURL != "" {
- if err := m.marshalTypeURL(out, indent, typeURL); err != nil {
- return err
- }
- firstField = false
- }
-
- for i := 0; i < s.NumField(); i++ {
- value := s.Field(i)
- valueField := s.Type().Field(i)
- if strings.HasPrefix(valueField.Name, "XXX_") {
- continue
- }
-
- // IsNil will panic on most value kinds.
- switch value.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface:
- if value.IsNil() {
- continue
- }
- }
-
- if !m.EmitDefaults {
- switch value.Kind() {
- case reflect.Bool:
- if !value.Bool() {
- continue
- }
- case reflect.Int32, reflect.Int64:
- if value.Int() == 0 {
- continue
- }
- case reflect.Uint32, reflect.Uint64:
- if value.Uint() == 0 {
- continue
- }
- case reflect.Float32, reflect.Float64:
- if value.Float() == 0 {
- continue
- }
- case reflect.String:
- if value.Len() == 0 {
- continue
- }
- case reflect.Map, reflect.Ptr, reflect.Slice:
- if value.IsNil() {
- continue
- }
- }
- }
-
- // Oneof fields need special handling.
- if valueField.Tag.Get("protobuf_oneof") != "" {
- // value is an interface containing &T{real_value}.
- sv := value.Elem().Elem() // interface -> *T -> T
- value = sv.Field(0)
- valueField = sv.Type().Field(0)
- }
- prop := jsonProperties(valueField, m.OrigName)
- if !firstField {
- m.writeSep(out)
- }
- if err := m.marshalField(out, prop, value, indent); err != nil {
- return err
- }
- firstField = false
- }
-
- // Handle proto2 extensions.
- if ep, ok := v.(proto.Message); ok {
- extensions := proto.RegisteredExtensions(v)
- // Sort extensions for stable output.
- ids := make([]int32, 0, len(extensions))
- for id, desc := range extensions {
- if !proto.HasExtension(ep, desc) {
- continue
- }
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids))
- for _, id := range ids {
- desc := extensions[id]
- if desc == nil {
- // unknown extension
- continue
- }
- ext, extErr := proto.GetExtension(ep, desc)
- if extErr != nil {
- return extErr
- }
- value := reflect.ValueOf(ext)
- var prop proto.Properties
- prop.Parse(desc.Tag)
- prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
- if !firstField {
- m.writeSep(out)
- }
- if err := m.marshalField(out, &prop, value, indent); err != nil {
- return err
- }
- firstField = false
- }
-
- }
-
- if m.Indent != "" {
- out.write("\n")
- out.write(indent)
- }
- out.write("}")
- return out.err
-}
-
-func (m *Marshaler) writeSep(out *errWriter) {
- if m.Indent != "" {
- out.write(",\n")
- } else {
- out.write(",")
- }
-}
-
-func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error {
- // "If the Any contains a value that has a special JSON mapping,
- // it will be converted as follows: {"@type": xxx, "value": yyy}.
- // Otherwise, the value will be converted into a JSON object,
- // and the "@type" field will be inserted to indicate the actual data type."
- v := reflect.ValueOf(any).Elem()
- turl := v.Field(0).String()
- val := v.Field(1).Bytes()
-
- var msg proto.Message
- var err error
- if m.AnyResolver != nil {
- msg, err = m.AnyResolver.Resolve(turl)
- } else {
- msg, err = defaultResolveAny(turl)
- }
- if err != nil {
- return err
- }
-
- if err := proto.Unmarshal(val, msg); err != nil {
- return err
- }
-
- if _, ok := msg.(wkt); ok {
- out.write("{")
- if m.Indent != "" {
- out.write("\n")
- }
- if err := m.marshalTypeURL(out, indent, turl); err != nil {
- return err
- }
- m.writeSep(out)
- if m.Indent != "" {
- out.write(indent)
- out.write(m.Indent)
- out.write(`"value": `)
- } else {
- out.write(`"value":`)
- }
- if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil {
- return err
- }
- if m.Indent != "" {
- out.write("\n")
- out.write(indent)
- }
- out.write("}")
- return out.err
- }
-
- return m.marshalObject(out, msg, indent, turl)
-}
-
-func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error {
- if m.Indent != "" {
- out.write(indent)
- out.write(m.Indent)
- }
- out.write(`"@type":`)
- if m.Indent != "" {
- out.write(" ")
- }
- b, err := json.Marshal(typeURL)
- if err != nil {
- return err
- }
- out.write(string(b))
- return out.err
-}
-
-// marshalField writes field description and value to the Writer.
-func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
- if m.Indent != "" {
- out.write(indent)
- out.write(m.Indent)
- }
- out.write(`"`)
- out.write(prop.JSONName)
- out.write(`":`)
- if m.Indent != "" {
- out.write(" ")
- }
- if err := m.marshalValue(out, prop, v, indent); err != nil {
- return err
- }
- return nil
-}
-
-// marshalValue writes the value to the Writer.
-func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
- var err error
- v = reflect.Indirect(v)
-
- // Handle nil pointer
- if v.Kind() == reflect.Invalid {
- out.write("null")
- return out.err
- }
-
- // Handle repeated elements.
- if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
- out.write("[")
- comma := ""
- for i := 0; i < v.Len(); i++ {
- sliceVal := v.Index(i)
- out.write(comma)
- if m.Indent != "" {
- out.write("\n")
- out.write(indent)
- out.write(m.Indent)
- out.write(m.Indent)
- }
- if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
- return err
- }
- comma = ","
- }
- if m.Indent != "" {
- out.write("\n")
- out.write(indent)
- out.write(m.Indent)
- }
- out.write("]")
- return out.err
- }
-
- // Handle well-known types.
- // Most are handled up in marshalObject (because 99% are messages).
- if wkt, ok := v.Interface().(wkt); ok {
- switch wkt.XXX_WellKnownType() {
- case "NullValue":
- out.write("null")
- return out.err
- }
- }
-
- // Handle enumerations.
- if !m.EnumsAsInts && prop.Enum != "" {
- // Unknown enum values will are stringified by the proto library as their
- // value. Such values should _not_ be quoted or they will be interpreted
- // as an enum string instead of their value.
- enumStr := v.Interface().(fmt.Stringer).String()
- var valStr string
- if v.Kind() == reflect.Ptr {
- valStr = strconv.Itoa(int(v.Elem().Int()))
- } else {
- valStr = strconv.Itoa(int(v.Int()))
- }
- isKnownEnum := enumStr != valStr
- if isKnownEnum {
- out.write(`"`)
- }
- out.write(enumStr)
- if isKnownEnum {
- out.write(`"`)
- }
- return out.err
- }
-
- // Handle nested messages.
- if v.Kind() == reflect.Struct {
- return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "")
- }
-
- // Handle maps.
- // Since Go randomizes map iteration, we sort keys for stable output.
- if v.Kind() == reflect.Map {
- out.write(`{`)
- keys := v.MapKeys()
- sort.Sort(mapKeys(keys))
- for i, k := range keys {
- if i > 0 {
- out.write(`,`)
- }
- if m.Indent != "" {
- out.write("\n")
- out.write(indent)
- out.write(m.Indent)
- out.write(m.Indent)
- }
-
- b, err := json.Marshal(k.Interface())
- if err != nil {
- return err
- }
- s := string(b)
-
- // If the JSON is not a string value, encode it again to make it one.
- if !strings.HasPrefix(s, `"`) {
- b, err := json.Marshal(s)
- if err != nil {
- return err
- }
- s = string(b)
- }
-
- out.write(s)
- out.write(`:`)
- if m.Indent != "" {
- out.write(` `)
- }
-
- if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil {
- return err
- }
- }
- if m.Indent != "" {
- out.write("\n")
- out.write(indent)
- out.write(m.Indent)
- }
- out.write(`}`)
- return out.err
- }
-
- // Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
- if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
- f := v.Float()
- var sval string
- switch {
- case math.IsInf(f, 1):
- sval = `"Infinity"`
- case math.IsInf(f, -1):
- sval = `"-Infinity"`
- case math.IsNaN(f):
- sval = `"NaN"`
- }
- if sval != "" {
- out.write(sval)
- return out.err
- }
- }
-
- // Default handling defers to the encoding/json library.
- b, err := json.Marshal(v.Interface())
- if err != nil {
- return err
- }
- needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
- if needToQuote {
- out.write(`"`)
- }
- out.write(string(b))
- if needToQuote {
- out.write(`"`)
- }
- return out.err
-}
-
-// Unmarshaler is a configurable object for converting from a JSON
-// representation to a protocol buffer object.
-type Unmarshaler struct {
- // Whether to allow messages to contain unknown fields, as opposed to
- // failing to unmarshal.
- AllowUnknownFields bool
-
- // A custom URL resolver to use when unmarshaling Any messages from JSON.
- // If unset, the default resolution strategy is to extract the
- // fully-qualified type name from the type URL and pass that to
- // proto.MessageType(string).
- AnyResolver AnyResolver
-}
-
-// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
-// This function is lenient and will decode any options permutations of the
-// related Marshaler.
-func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
- inputValue := json.RawMessage{}
- if err := dec.Decode(&inputValue); err != nil {
- return err
- }
- if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil {
- return err
- }
- return checkRequiredFields(pb)
-}
-
-// Unmarshal unmarshals a JSON object stream into a protocol
-// buffer. This function is lenient and will decode any options
-// permutations of the related Marshaler.
-func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
- dec := json.NewDecoder(r)
- return u.UnmarshalNext(dec, pb)
-}
-
-// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
-// This function is lenient and will decode any options permutations of the
-// related Marshaler.
-func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
- return new(Unmarshaler).UnmarshalNext(dec, pb)
-}
-
-// Unmarshal unmarshals a JSON object stream into a protocol
-// buffer. This function is lenient and will decode any options
-// permutations of the related Marshaler.
-func Unmarshal(r io.Reader, pb proto.Message) error {
- return new(Unmarshaler).Unmarshal(r, pb)
-}
-
-// UnmarshalString will populate the fields of a protocol buffer based
-// on a JSON string. This function is lenient and will decode any options
-// permutations of the related Marshaler.
-func UnmarshalString(str string, pb proto.Message) error {
- return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
-}
-
-// unmarshalValue converts/copies a value into the target.
-// prop may be nil.
-func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
- targetType := target.Type()
-
- // Allocate memory for pointer fields.
- if targetType.Kind() == reflect.Ptr {
- // If input value is "null" and target is a pointer type, then the field should be treated as not set
- // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue.
- _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler)
- if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler {
- return nil
- }
- target.Set(reflect.New(targetType.Elem()))
-
- return u.unmarshalValue(target.Elem(), inputValue, prop)
- }
-
- if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
- return jsu.UnmarshalJSONPB(u, []byte(inputValue))
- }
-
- // Handle well-known types that are not pointers.
- if w, ok := target.Addr().Interface().(wkt); ok {
- switch w.XXX_WellKnownType() {
- case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
- "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
- return u.unmarshalValue(target.Field(0), inputValue, prop)
- case "Any":
- // Use json.RawMessage pointer type instead of value to support pre-1.8 version.
- // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
- // https://github.com/golang/go/issues/14493
- var jsonFields map[string]*json.RawMessage
- if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
- return err
- }
-
- val, ok := jsonFields["@type"]
- if !ok || val == nil {
- return errors.New("Any JSON doesn't have '@type'")
- }
-
- var turl string
- if err := json.Unmarshal([]byte(*val), &turl); err != nil {
- return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
- }
- target.Field(0).SetString(turl)
-
- var m proto.Message
- var err error
- if u.AnyResolver != nil {
- m, err = u.AnyResolver.Resolve(turl)
- } else {
- m, err = defaultResolveAny(turl)
- }
- if err != nil {
- return err
- }
-
- if _, ok := m.(wkt); ok {
- val, ok := jsonFields["value"]
- if !ok {
- return errors.New("Any JSON doesn't have 'value'")
- }
-
- if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
- return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
- }
- } else {
- delete(jsonFields, "@type")
- nestedProto, err := json.Marshal(jsonFields)
- if err != nil {
- return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
- }
-
- if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
- return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
- }
- }
-
- b, err := proto.Marshal(m)
- if err != nil {
- return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
- }
- target.Field(1).SetBytes(b)
-
- return nil
- case "Duration":
- unq, err := unquote(string(inputValue))
- if err != nil {
- return err
- }
-
- d, err := time.ParseDuration(unq)
- if err != nil {
- return fmt.Errorf("bad Duration: %v", err)
- }
-
- ns := d.Nanoseconds()
- s := ns / 1e9
- ns %= 1e9
- target.Field(0).SetInt(s)
- target.Field(1).SetInt(ns)
- return nil
- case "Timestamp":
- unq, err := unquote(string(inputValue))
- if err != nil {
- return err
- }
-
- t, err := time.Parse(time.RFC3339Nano, unq)
- if err != nil {
- return fmt.Errorf("bad Timestamp: %v", err)
- }
-
- target.Field(0).SetInt(t.Unix())
- target.Field(1).SetInt(int64(t.Nanosecond()))
- return nil
- case "Struct":
- var m map[string]json.RawMessage
- if err := json.Unmarshal(inputValue, &m); err != nil {
- return fmt.Errorf("bad StructValue: %v", err)
- }
-
- target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{}))
- for k, jv := range m {
- pv := &stpb.Value{}
- if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil {
- return fmt.Errorf("bad value in StructValue for key %q: %v", k, err)
- }
- target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv))
- }
- return nil
- case "ListValue":
- var s []json.RawMessage
- if err := json.Unmarshal(inputValue, &s); err != nil {
- return fmt.Errorf("bad ListValue: %v", err)
- }
-
- target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s))))
- for i, sv := range s {
- if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil {
- return err
- }
- }
- return nil
- case "Value":
- ivStr := string(inputValue)
- if ivStr == "null" {
- target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{}))
- } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil {
- target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v}))
- } else if v, err := unquote(ivStr); err == nil {
- target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v}))
- } else if v, err := strconv.ParseBool(ivStr); err == nil {
- target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v}))
- } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil {
- lv := &stpb.ListValue{}
- target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv}))
- return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop)
- } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil {
- sv := &stpb.Struct{}
- target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv}))
- return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop)
- } else {
- return fmt.Errorf("unrecognized type for Value %q", ivStr)
- }
- return nil
- }
- }
-
- // Handle enums, which have an underlying type of int32,
- // and may appear as strings.
- // The case of an enum appearing as a number is handled
- // at the bottom of this function.
- if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
- vmap := proto.EnumValueMap(prop.Enum)
- // Don't need to do unquoting; valid enum names
- // are from a limited character set.
- s := inputValue[1 : len(inputValue)-1]
- n, ok := vmap[string(s)]
- if !ok {
- return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
- }
- if target.Kind() == reflect.Ptr { // proto2
- target.Set(reflect.New(targetType.Elem()))
- target = target.Elem()
- }
- if targetType.Kind() != reflect.Int32 {
- return fmt.Errorf("invalid target %q for enum %s", targetType.Kind(), prop.Enum)
- }
- target.SetInt(int64(n))
- return nil
- }
-
- // Handle nested messages.
- if targetType.Kind() == reflect.Struct {
- var jsonFields map[string]json.RawMessage
- if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
- return err
- }
-
- consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
- // Be liberal in what names we accept; both orig_name and camelName are okay.
- fieldNames := acceptedJSONFieldNames(prop)
-
- vOrig, okOrig := jsonFields[fieldNames.orig]
- vCamel, okCamel := jsonFields[fieldNames.camel]
- if !okOrig && !okCamel {
- return nil, false
- }
- // If, for some reason, both are present in the data, favour the camelName.
- var raw json.RawMessage
- if okOrig {
- raw = vOrig
- delete(jsonFields, fieldNames.orig)
- }
- if okCamel {
- raw = vCamel
- delete(jsonFields, fieldNames.camel)
- }
- return raw, true
- }
-
- sprops := proto.GetProperties(targetType)
- for i := 0; i < target.NumField(); i++ {
- ft := target.Type().Field(i)
- if strings.HasPrefix(ft.Name, "XXX_") {
- continue
- }
-
- valueForField, ok := consumeField(sprops.Prop[i])
- if !ok {
- continue
- }
-
- if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
- return err
- }
- }
- // Check for any oneof fields.
- if len(jsonFields) > 0 {
- for _, oop := range sprops.OneofTypes {
- raw, ok := consumeField(oop.Prop)
- if !ok {
- continue
- }
- nv := reflect.New(oop.Type.Elem())
- target.Field(oop.Field).Set(nv)
- if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
- return err
- }
- }
- }
- // Handle proto2 extensions.
- if len(jsonFields) > 0 {
- if ep, ok := target.Addr().Interface().(proto.Message); ok {
- for _, ext := range proto.RegisteredExtensions(ep) {
- name := fmt.Sprintf("[%s]", ext.Name)
- raw, ok := jsonFields[name]
- if !ok {
- continue
- }
- delete(jsonFields, name)
- nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem())
- if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil {
- return err
- }
- if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil {
- return err
- }
- }
- }
- }
- if !u.AllowUnknownFields && len(jsonFields) > 0 {
- // Pick any field to be the scapegoat.
- var f string
- for fname := range jsonFields {
- f = fname
- break
- }
- return fmt.Errorf("unknown field %q in %v", f, targetType)
- }
- return nil
- }
-
- // Handle arrays (which aren't encoded bytes)
- if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 {
- var slc []json.RawMessage
- if err := json.Unmarshal(inputValue, &slc); err != nil {
- return err
- }
- if slc != nil {
- l := len(slc)
- target.Set(reflect.MakeSlice(targetType, l, l))
- for i := 0; i < l; i++ {
- if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
- return err
- }
- }
- }
- return nil
- }
-
- // Handle maps (whose keys are always strings)
- if targetType.Kind() == reflect.Map {
- var mp map[string]json.RawMessage
- if err := json.Unmarshal(inputValue, &mp); err != nil {
- return err
- }
- if mp != nil {
- target.Set(reflect.MakeMap(targetType))
- for ks, raw := range mp {
- // Unmarshal map key. The core json library already decoded the key into a
- // string, so we handle that specially. Other types were quoted post-serialization.
- var k reflect.Value
- if targetType.Key().Kind() == reflect.String {
- k = reflect.ValueOf(ks)
- } else {
- k = reflect.New(targetType.Key()).Elem()
- // TODO: pass the correct Properties if needed.
- if err := u.unmarshalValue(k, json.RawMessage(ks), nil); err != nil {
- return err
- }
- }
-
- // Unmarshal map value.
- v := reflect.New(targetType.Elem()).Elem()
- // TODO: pass the correct Properties if needed.
- if err := u.unmarshalValue(v, raw, nil); err != nil {
- return err
- }
- target.SetMapIndex(k, v)
- }
- }
- return nil
- }
-
- // 64-bit integers can be encoded as strings. In this case we drop
- // the quotes and proceed as normal.
- isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64
- if isNum && strings.HasPrefix(string(inputValue), `"`) {
- inputValue = inputValue[1 : len(inputValue)-1]
- }
-
- // Non-finite numbers can be encoded as strings.
- isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
- if isFloat {
- if num, ok := nonFinite[string(inputValue)]; ok {
- target.SetFloat(num)
- return nil
- }
- }
-
- // Use the encoding/json for parsing other value types.
- return json.Unmarshal(inputValue, target.Addr().Interface())
-}
-
-func unquote(s string) (string, error) {
- var ret string
- err := json.Unmarshal([]byte(s), &ret)
- return ret, err
-}
-
-// jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
-func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
- var prop proto.Properties
- prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
- if origName || prop.JSONName == "" {
- prop.JSONName = prop.OrigName
- }
- return &prop
-}
-
-type fieldNames struct {
- orig, camel string
-}
-
-func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
- opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
- if prop.JSONName != "" {
- opts.camel = prop.JSONName
- }
- return opts
-}
-
-// Writer wrapper inspired by https://blog.golang.org/errors-are-values
-type errWriter struct {
- writer io.Writer
- err error
-}
-
-func (w *errWriter) write(str string) {
- if w.err != nil {
- return
- }
- _, w.err = w.writer.Write([]byte(str))
-}
-
-// Map fields may have key types of non-float scalars, strings and enums.
-// The easiest way to sort them in some deterministic order is to use fmt.
-// If this turns out to be inefficient we can always consider other options,
-// such as doing a Schwartzian transform.
-//
-// Numeric keys are sorted in numeric order per
-// https://developers.google.com/protocol-buffers/docs/proto#maps.
-type mapKeys []reflect.Value
-
-func (s mapKeys) Len() int { return len(s) }
-func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s mapKeys) Less(i, j int) bool {
- if k := s[i].Kind(); k == s[j].Kind() {
- switch k {
- case reflect.Int32, reflect.Int64:
- return s[i].Int() < s[j].Int()
- case reflect.Uint32, reflect.Uint64:
- return s[i].Uint() < s[j].Uint()
- }
- }
- return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
-}
-
-// checkRequiredFields returns an error if any required field in the given proto message is not set.
-// This function is used by both Marshal and Unmarshal. While required fields only exist in a
-// proto2 message, a proto3 message can contain proto2 message(s).
-func checkRequiredFields(pb proto.Message) error {
- // Most well-known type messages do not contain required fields. The "Any" type may contain
- // a message that has required fields.
- //
- // When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value
- // field in order to transform that into JSON, and that should have returned an error if a
- // required field is not set in the embedded message.
- //
- // When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the
- // embedded message to store the serialized message in Any.Value field, and that should have
- // returned an error if a required field is not set.
- if _, ok := pb.(wkt); ok {
- return nil
- }
-
- v := reflect.ValueOf(pb)
- // Skip message if it is not a struct pointer.
- if v.Kind() != reflect.Ptr {
- return nil
- }
- v = v.Elem()
- if v.Kind() != reflect.Struct {
- return nil
- }
-
- for i := 0; i < v.NumField(); i++ {
- field := v.Field(i)
- sfield := v.Type().Field(i)
-
- if sfield.PkgPath != "" {
- // blank PkgPath means the field is exported; skip if not exported
- continue
- }
-
- if strings.HasPrefix(sfield.Name, "XXX_") {
- continue
- }
-
- // Oneof field is an interface implemented by wrapper structs containing the actual oneof
- // field, i.e. an interface containing &T{real_value}.
- if sfield.Tag.Get("protobuf_oneof") != "" {
- if field.Kind() != reflect.Interface {
- continue
- }
- v := field.Elem()
- if v.Kind() != reflect.Ptr || v.IsNil() {
- continue
- }
- v = v.Elem()
- if v.Kind() != reflect.Struct || v.NumField() < 1 {
- continue
- }
- field = v.Field(0)
- sfield = v.Type().Field(0)
- }
-
- protoTag := sfield.Tag.Get("protobuf")
- if protoTag == "" {
- continue
- }
- var prop proto.Properties
- prop.Init(sfield.Type, sfield.Name, protoTag, &sfield)
-
- switch field.Kind() {
- case reflect.Map:
- if field.IsNil() {
- continue
- }
- // Check each map value.
- keys := field.MapKeys()
- for _, k := range keys {
- v := field.MapIndex(k)
- if err := checkRequiredFieldsInValue(v); err != nil {
- return err
- }
- }
- case reflect.Slice:
- // Handle non-repeated type, e.g. bytes.
- if !prop.Repeated {
- if prop.Required && field.IsNil() {
- return fmt.Errorf("required field %q is not set", prop.Name)
- }
- continue
- }
-
- // Handle repeated type.
- if field.IsNil() {
- continue
- }
- // Check each slice item.
- for i := 0; i < field.Len(); i++ {
- v := field.Index(i)
- if err := checkRequiredFieldsInValue(v); err != nil {
- return err
- }
- }
- case reflect.Ptr:
- if field.IsNil() {
- if prop.Required {
- return fmt.Errorf("required field %q is not set", prop.Name)
- }
- continue
- }
- if err := checkRequiredFieldsInValue(field); err != nil {
- return err
- }
- }
- }
-
- // Handle proto2 extensions.
- for _, ext := range proto.RegisteredExtensions(pb) {
- if !proto.HasExtension(pb, ext) {
- continue
- }
- ep, err := proto.GetExtension(pb, ext)
- if err != nil {
- return err
- }
- err = checkRequiredFieldsInValue(reflect.ValueOf(ep))
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func checkRequiredFieldsInValue(v reflect.Value) error {
- if pm, ok := v.Interface().(proto.Message); ok {
- return checkRequiredFields(pm)
- }
- return nil
-}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
deleted file mode 100644
index d254fa5fa..000000000
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
+++ /dev/null
@@ -1,69 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package jsonpb;
-
-message Simple3 {
- double dub = 1;
-}
-
-message SimpleSlice3 {
- repeated string slices = 1;
-}
-
-message SimpleMap3 {
- map stringy = 1;
-}
-
-message SimpleNull3 {
- Simple3 simple = 1;
-}
-
-enum Numeral {
- UNKNOWN = 0;
- ARABIC = 1;
- ROMAN = 2;
-}
-
-message Mappy {
- map nummy = 1;
- map strry = 2;
- map objjy = 3;
- map buggy = 4;
- map booly = 5;
- map enumy = 6;
- map s32booly = 7;
- map s64booly = 8;
- map u32booly = 9;
- map u64booly = 10;
-}
diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile
deleted file mode 100644
index e2e0651a9..000000000
--- a/vendor/github.com/golang/protobuf/proto/Makefile
+++ /dev/null
@@ -1,43 +0,0 @@
-# Go support for Protocol Buffers - Google's data interchange format
-#
-# Copyright 2010 The Go Authors. All rights reserved.
-# https://github.com/golang/protobuf
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-install:
- go install
-
-test: install generate-test-pbs
- go test
-
-
-generate-test-pbs:
- make install
- make -C testdata
- protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto
- make
diff --git a/vendor/github.com/golang/protobuf/proto/all_test.go b/vendor/github.com/golang/protobuf/proto/all_test.go
deleted file mode 100644
index 361f72fbd..000000000
--- a/vendor/github.com/golang/protobuf/proto/all_test.go
+++ /dev/null
@@ -1,2410 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto_test
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "math"
- "math/rand"
- "reflect"
- "runtime/debug"
- "strings"
- "sync"
- "testing"
- "time"
-
- . "github.com/golang/protobuf/proto"
- . "github.com/golang/protobuf/proto/test_proto"
-)
-
-var globalO *Buffer
-
-func old() *Buffer {
- if globalO == nil {
- globalO = NewBuffer(nil)
- }
- globalO.Reset()
- return globalO
-}
-
-func equalbytes(b1, b2 []byte, t *testing.T) {
- if len(b1) != len(b2) {
- t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2))
- return
- }
- for i := 0; i < len(b1); i++ {
- if b1[i] != b2[i] {
- t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
- }
- }
-}
-
-func initGoTestField() *GoTestField {
- f := new(GoTestField)
- f.Label = String("label")
- f.Type = String("type")
- return f
-}
-
-// These are all structurally equivalent but the tag numbers differ.
-// (It's remarkable that required, optional, and repeated all have
-// 8 letters.)
-func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
- return &GoTest_RequiredGroup{
- RequiredField: String("required"),
- }
-}
-
-func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
- return &GoTest_OptionalGroup{
- RequiredField: String("optional"),
- }
-}
-
-func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
- return &GoTest_RepeatedGroup{
- RequiredField: String("repeated"),
- }
-}
-
-func initGoTest(setdefaults bool) *GoTest {
- pb := new(GoTest)
- if setdefaults {
- pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
- pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
- pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
- pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
- pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
- pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
- pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
- pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
- pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
- pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
- pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
- pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
- pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
- pb.F_Sfixed32Defaulted = Int32(Default_GoTest_F_Sfixed32Defaulted)
- pb.F_Sfixed64Defaulted = Int64(Default_GoTest_F_Sfixed64Defaulted)
- }
-
- pb.Kind = GoTest_TIME.Enum()
- pb.RequiredField = initGoTestField()
- pb.F_BoolRequired = Bool(true)
- pb.F_Int32Required = Int32(3)
- pb.F_Int64Required = Int64(6)
- pb.F_Fixed32Required = Uint32(32)
- pb.F_Fixed64Required = Uint64(64)
- pb.F_Uint32Required = Uint32(3232)
- pb.F_Uint64Required = Uint64(6464)
- pb.F_FloatRequired = Float32(3232)
- pb.F_DoubleRequired = Float64(6464)
- pb.F_StringRequired = String("string")
- pb.F_BytesRequired = []byte("bytes")
- pb.F_Sint32Required = Int32(-32)
- pb.F_Sint64Required = Int64(-64)
- pb.F_Sfixed32Required = Int32(-32)
- pb.F_Sfixed64Required = Int64(-64)
- pb.Requiredgroup = initGoTest_RequiredGroup()
-
- return pb
-}
-
-func hex(c uint8) uint8 {
- if '0' <= c && c <= '9' {
- return c - '0'
- }
- if 'a' <= c && c <= 'f' {
- return 10 + c - 'a'
- }
- if 'A' <= c && c <= 'F' {
- return 10 + c - 'A'
- }
- return 0
-}
-
-func equal(b []byte, s string, t *testing.T) bool {
- if 2*len(b) != len(s) {
- // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t)
- fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s))
- return false
- }
- for i, j := 0, 0; i < len(b); i, j = i+1, j+2 {
- x := hex(s[j])*16 + hex(s[j+1])
- if b[i] != x {
- // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t)
- fmt.Printf("bad byte[%d]:%x %x", i, b[i], x)
- return false
- }
- }
- return true
-}
-
-func overify(t *testing.T, pb *GoTest, expected string) {
- o := old()
- err := o.Marshal(pb)
- if err != nil {
- fmt.Printf("overify marshal-1 err = %v", err)
- o.DebugPrint("", o.Bytes())
- t.Fatalf("expected = %s", expected)
- }
- if !equal(o.Bytes(), expected, t) {
- o.DebugPrint("overify neq 1", o.Bytes())
- t.Fatalf("expected = %s", expected)
- }
-
- // Now test Unmarshal by recreating the original buffer.
- pbd := new(GoTest)
- err = o.Unmarshal(pbd)
- if err != nil {
- t.Fatalf("overify unmarshal err = %v", err)
- o.DebugPrint("", o.Bytes())
- t.Fatalf("string = %s", expected)
- }
- o.Reset()
- err = o.Marshal(pbd)
- if err != nil {
- t.Errorf("overify marshal-2 err = %v", err)
- o.DebugPrint("", o.Bytes())
- t.Fatalf("string = %s", expected)
- }
- if !equal(o.Bytes(), expected, t) {
- o.DebugPrint("overify neq 2", o.Bytes())
- t.Fatalf("string = %s", expected)
- }
-}
-
-// Simple tests for numeric encode/decode primitives (varint, etc.)
-func TestNumericPrimitives(t *testing.T) {
- for i := uint64(0); i < 1e6; i += 111 {
- o := old()
- if o.EncodeVarint(i) != nil {
- t.Error("EncodeVarint")
- break
- }
- x, e := o.DecodeVarint()
- if e != nil {
- t.Fatal("DecodeVarint")
- }
- if x != i {
- t.Fatal("varint decode fail:", i, x)
- }
-
- o = old()
- if o.EncodeFixed32(i) != nil {
- t.Fatal("encFixed32")
- }
- x, e = o.DecodeFixed32()
- if e != nil {
- t.Fatal("decFixed32")
- }
- if x != i {
- t.Fatal("fixed32 decode fail:", i, x)
- }
-
- o = old()
- if o.EncodeFixed64(i*1234567) != nil {
- t.Error("encFixed64")
- break
- }
- x, e = o.DecodeFixed64()
- if e != nil {
- t.Error("decFixed64")
- break
- }
- if x != i*1234567 {
- t.Error("fixed64 decode fail:", i*1234567, x)
- break
- }
-
- o = old()
- i32 := int32(i - 12345)
- if o.EncodeZigzag32(uint64(i32)) != nil {
- t.Fatal("EncodeZigzag32")
- }
- x, e = o.DecodeZigzag32()
- if e != nil {
- t.Fatal("DecodeZigzag32")
- }
- if x != uint64(uint32(i32)) {
- t.Fatal("zigzag32 decode fail:", i32, x)
- }
-
- o = old()
- i64 := int64(i - 12345)
- if o.EncodeZigzag64(uint64(i64)) != nil {
- t.Fatal("EncodeZigzag64")
- }
- x, e = o.DecodeZigzag64()
- if e != nil {
- t.Fatal("DecodeZigzag64")
- }
- if x != uint64(i64) {
- t.Fatal("zigzag64 decode fail:", i64, x)
- }
- }
-}
-
-// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces.
-type fakeMarshaler struct {
- b []byte
- err error
-}
-
-func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err }
-func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) }
-func (f *fakeMarshaler) ProtoMessage() {}
-func (f *fakeMarshaler) Reset() {}
-
-type msgWithFakeMarshaler struct {
- M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"`
-}
-
-func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) }
-func (m *msgWithFakeMarshaler) ProtoMessage() {}
-func (m *msgWithFakeMarshaler) Reset() {}
-
-// Simple tests for proto messages that implement the Marshaler interface.
-func TestMarshalerEncoding(t *testing.T) {
- tests := []struct {
- name string
- m Message
- want []byte
- errType reflect.Type
- }{
- {
- name: "Marshaler that fails",
- m: &fakeMarshaler{
- err: errors.New("some marshal err"),
- b: []byte{5, 6, 7},
- },
- // Since the Marshal method returned bytes, they should be written to the
- // buffer. (For efficiency, we assume that Marshal implementations are
- // always correct w.r.t. RequiredNotSetError and output.)
- want: []byte{5, 6, 7},
- errType: reflect.TypeOf(errors.New("some marshal err")),
- },
- {
- name: "Marshaler that fails with RequiredNotSetError",
- m: &msgWithFakeMarshaler{
- M: &fakeMarshaler{
- err: &RequiredNotSetError{},
- b: []byte{5, 6, 7},
- },
- },
- // Since there's an error that can be continued after,
- // the buffer should be written.
- want: []byte{
- 10, 3, // for &msgWithFakeMarshaler
- 5, 6, 7, // for &fakeMarshaler
- },
- errType: reflect.TypeOf(&RequiredNotSetError{}),
- },
- {
- name: "Marshaler that succeeds",
- m: &fakeMarshaler{
- b: []byte{0, 1, 2, 3, 4, 127, 255},
- },
- want: []byte{0, 1, 2, 3, 4, 127, 255},
- },
- }
- for _, test := range tests {
- b := NewBuffer(nil)
- err := b.Marshal(test.m)
- if reflect.TypeOf(err) != test.errType {
- t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType)
- }
- if !reflect.DeepEqual(test.want, b.Bytes()) {
- t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want)
- }
- if size := Size(test.m); size != len(b.Bytes()) {
- t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes()))
- }
-
- m, mErr := Marshal(test.m)
- if !bytes.Equal(b.Bytes(), m) {
- t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes())
- }
- if !reflect.DeepEqual(err, mErr) {
- t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q",
- test.name, fmt.Sprint(mErr), fmt.Sprint(err))
- }
- }
-}
-
-// Ensure that Buffer.Marshal uses O(N) memory for N messages
-func TestBufferMarshalAllocs(t *testing.T) {
- value := &OtherMessage{Key: Int64(1)}
- msg := &MyMessage{Count: Int32(1), Others: []*OtherMessage{value}}
-
- reallocSize := func(t *testing.T, items int, prealloc int) (int64, int64) {
- var b Buffer
- b.SetBuf(make([]byte, 0, prealloc))
-
- var allocSpace int64
- prevCap := cap(b.Bytes())
- for i := 0; i < items; i++ {
- err := b.Marshal(msg)
- if err != nil {
- t.Errorf("Marshal err = %q", err)
- break
- }
- if c := cap(b.Bytes()); prevCap != c {
- allocSpace += int64(c)
- prevCap = c
- }
- }
- needSpace := int64(len(b.Bytes()))
- return allocSpace, needSpace
- }
-
- for _, prealloc := range []int{0, 100, 10000} {
- for _, items := range []int{1, 2, 5, 10, 20, 50, 100, 200, 500, 1000} {
- runtimeSpace, need := reallocSize(t, items, prealloc)
- totalSpace := int64(prealloc) + runtimeSpace
-
- runtimeRatio := float64(runtimeSpace) / float64(need)
- totalRatio := float64(totalSpace) / float64(need)
-
- if totalRatio < 1 || runtimeRatio > 4 {
- t.Errorf("needed %dB, allocated %dB total (ratio %.1f), allocated %dB at runtime (ratio %.1f)",
- need, totalSpace, totalRatio, runtimeSpace, runtimeRatio)
- }
- }
- }
-}
-
-// Simple tests for bytes
-func TestBytesPrimitives(t *testing.T) {
- o := old()
- bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
- if o.EncodeRawBytes(bytes) != nil {
- t.Error("EncodeRawBytes")
- }
- decb, e := o.DecodeRawBytes(false)
- if e != nil {
- t.Error("DecodeRawBytes")
- }
- equalbytes(bytes, decb, t)
-}
-
-// Simple tests for strings
-func TestStringPrimitives(t *testing.T) {
- o := old()
- s := "now is the time"
- if o.EncodeStringBytes(s) != nil {
- t.Error("enc_string")
- }
- decs, e := o.DecodeStringBytes()
- if e != nil {
- t.Error("dec_string")
- }
- if s != decs {
- t.Error("string encode/decode fail:", s, decs)
- }
-}
-
-// Do we catch the "required bit not set" case?
-func TestRequiredBit(t *testing.T) {
- o := old()
- pb := new(GoTest)
- err := o.Marshal(pb)
- if err == nil {
- t.Error("did not catch missing required fields")
- } else if !strings.Contains(err.Error(), "Kind") {
- t.Error("wrong error type:", err)
- }
-}
-
-// Check that all fields are nil.
-// Clearly silly, and a residue from a more interesting test with an earlier,
-// different initialization property, but it once caught a compiler bug so
-// it lives.
-func checkInitialized(pb *GoTest, t *testing.T) {
- if pb.F_BoolDefaulted != nil {
- t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
- }
- if pb.F_Int32Defaulted != nil {
- t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
- }
- if pb.F_Int64Defaulted != nil {
- t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
- }
- if pb.F_Fixed32Defaulted != nil {
- t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
- }
- if pb.F_Fixed64Defaulted != nil {
- t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
- }
- if pb.F_Uint32Defaulted != nil {
- t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
- }
- if pb.F_Uint64Defaulted != nil {
- t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
- }
- if pb.F_FloatDefaulted != nil {
- t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
- }
- if pb.F_DoubleDefaulted != nil {
- t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
- }
- if pb.F_StringDefaulted != nil {
- t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
- }
- if pb.F_BytesDefaulted != nil {
- t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
- }
- if pb.F_Sint32Defaulted != nil {
- t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
- }
- if pb.F_Sint64Defaulted != nil {
- t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
- }
-}
-
-// Does Reset() reset?
-func TestReset(t *testing.T) {
- pb := initGoTest(true)
- // muck with some values
- pb.F_BoolDefaulted = Bool(false)
- pb.F_Int32Defaulted = Int32(237)
- pb.F_Int64Defaulted = Int64(12346)
- pb.F_Fixed32Defaulted = Uint32(32000)
- pb.F_Fixed64Defaulted = Uint64(666)
- pb.F_Uint32Defaulted = Uint32(323232)
- pb.F_Uint64Defaulted = nil
- pb.F_FloatDefaulted = nil
- pb.F_DoubleDefaulted = Float64(0)
- pb.F_StringDefaulted = String("gotcha")
- pb.F_BytesDefaulted = []byte("asdfasdf")
- pb.F_Sint32Defaulted = Int32(123)
- pb.F_Sint64Defaulted = Int64(789)
- pb.Reset()
- checkInitialized(pb, t)
-}
-
-// All required fields set, no defaults provided.
-func TestEncodeDecode1(t *testing.T) {
- pb := initGoTest(false)
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 0x20
- "714000000000000000"+ // field 14, encoding 1, value 0x40
- "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
- "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
- "b304"+ // field 70, encoding 3, start group
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // field 70, encoding 4, end group
- "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff") // field 105, encoding 1, -64 fixed64
-}
-
-// All required fields set, defaults provided.
-func TestEncodeDecode2(t *testing.T) {
- pb := initGoTest(true)
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f"+ // field 403, encoding 0, value 127
- "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32
- "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64
-
-}
-
-// All default fields set to their default value by hand
-func TestEncodeDecode3(t *testing.T) {
- pb := initGoTest(false)
- pb.F_BoolDefaulted = Bool(true)
- pb.F_Int32Defaulted = Int32(32)
- pb.F_Int64Defaulted = Int64(64)
- pb.F_Fixed32Defaulted = Uint32(320)
- pb.F_Fixed64Defaulted = Uint64(640)
- pb.F_Uint32Defaulted = Uint32(3200)
- pb.F_Uint64Defaulted = Uint64(6400)
- pb.F_FloatDefaulted = Float32(314159)
- pb.F_DoubleDefaulted = Float64(271828)
- pb.F_StringDefaulted = String("hello, \"world!\"\n")
- pb.F_BytesDefaulted = []byte("Bignose")
- pb.F_Sint32Defaulted = Int32(-32)
- pb.F_Sint64Defaulted = Int64(-64)
- pb.F_Sfixed32Defaulted = Int32(-32)
- pb.F_Sfixed64Defaulted = Int64(-64)
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f"+ // field 403, encoding 0, value 127
- "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32
- "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64
-
-}
-
-// All required fields set, defaults provided, all non-defaulted optional fields have values.
-func TestEncodeDecode4(t *testing.T) {
- pb := initGoTest(true)
- pb.Table = String("hello")
- pb.Param = Int32(7)
- pb.OptionalField = initGoTestField()
- pb.F_BoolOptional = Bool(true)
- pb.F_Int32Optional = Int32(32)
- pb.F_Int64Optional = Int64(64)
- pb.F_Fixed32Optional = Uint32(3232)
- pb.F_Fixed64Optional = Uint64(6464)
- pb.F_Uint32Optional = Uint32(323232)
- pb.F_Uint64Optional = Uint64(646464)
- pb.F_FloatOptional = Float32(32.)
- pb.F_DoubleOptional = Float64(64.)
- pb.F_StringOptional = String("hello")
- pb.F_BytesOptional = []byte("Bignose")
- pb.F_Sint32Optional = Int32(-32)
- pb.F_Sint64Optional = Int64(-64)
- pb.F_Sfixed32Optional = Int32(-32)
- pb.F_Sfixed64Optional = Int64(-64)
- pb.Optionalgroup = initGoTest_OptionalGroup()
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
- "1807"+ // field 3, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "f00101"+ // field 30, encoding 0, value 1
- "f80120"+ // field 31, encoding 0, value 32
- "800240"+ // field 32, encoding 0, value 64
- "8d02a00c0000"+ // field 33, encoding 5, value 3232
- "91024019000000000000"+ // field 34, encoding 1, value 6464
- "9802a0dd13"+ // field 35, encoding 0, value 323232
- "a002c0ba27"+ // field 36, encoding 0, value 646464
- "ad0200000042"+ // field 37, encoding 5, value 32.0
- "b1020000000000005040"+ // field 38, encoding 1, value 64.0
- "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "d305"+ // start group field 90 level 1
- "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
- "d405"+ // end group field 90 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64
- "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
- "f0123f"+ // field 302, encoding 0, value 63
- "f8127f"+ // field 303, encoding 0, value 127
- "8513e0ffffff"+ // field 304, encoding 5, -32 fixed32
- "8913c0ffffffffffffff"+ // field 305, encoding 1, -64 fixed64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f"+ // field 403, encoding 0, value 127
- "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32
- "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64
-
-}
-
-// All required fields set, defaults provided, all repeated fields given two values.
-func TestEncodeDecode5(t *testing.T) {
- pb := initGoTest(true)
- pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
- pb.F_BoolRepeated = []bool{false, true}
- pb.F_Int32Repeated = []int32{32, 33}
- pb.F_Int64Repeated = []int64{64, 65}
- pb.F_Fixed32Repeated = []uint32{3232, 3333}
- pb.F_Fixed64Repeated = []uint64{6464, 6565}
- pb.F_Uint32Repeated = []uint32{323232, 333333}
- pb.F_Uint64Repeated = []uint64{646464, 656565}
- pb.F_FloatRepeated = []float32{32., 33.}
- pb.F_DoubleRepeated = []float64{64., 65.}
- pb.F_StringRepeated = []string{"hello", "sailor"}
- pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
- pb.F_Sint32Repeated = []int32{32, -32}
- pb.F_Sint64Repeated = []int64{64, -64}
- pb.F_Sfixed32Repeated = []int32{32, -32}
- pb.F_Sfixed64Repeated = []int64{64, -64}
- pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
- "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "a00100"+ // field 20, encoding 0, value 0
- "a00101"+ // field 20, encoding 0, value 1
- "a80120"+ // field 21, encoding 0, value 32
- "a80121"+ // field 21, encoding 0, value 33
- "b00140"+ // field 22, encoding 0, value 64
- "b00141"+ // field 22, encoding 0, value 65
- "bd01a00c0000"+ // field 23, encoding 5, value 3232
- "bd01050d0000"+ // field 23, encoding 5, value 3333
- "c1014019000000000000"+ // field 24, encoding 1, value 6464
- "c101a519000000000000"+ // field 24, encoding 1, value 6565
- "c801a0dd13"+ // field 25, encoding 0, value 323232
- "c80195ac14"+ // field 25, encoding 0, value 333333
- "d001c0ba27"+ // field 26, encoding 0, value 646464
- "d001b58928"+ // field 26, encoding 0, value 656565
- "dd0100000042"+ // field 27, encoding 5, value 32.0
- "dd0100000442"+ // field 27, encoding 5, value 33.0
- "e1010000000000005040"+ // field 28, encoding 1, value 64.0
- "e1010000000000405040"+ // field 28, encoding 1, value 65.0
- "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
- "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "8305"+ // start group field 80 level 1
- "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
- "8405"+ // end group field 80 level 1
- "8305"+ // start group field 80 level 1
- "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
- "8405"+ // end group field 80 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64
- "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
- "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
- "d00c40"+ // field 202, encoding 0, value 32
- "d00c3f"+ // field 202, encoding 0, value -32
- "d80c8001"+ // field 203, encoding 0, value 64
- "d80c7f"+ // field 203, encoding 0, value -64
- "e50c20000000"+ // field 204, encoding 5, 32 fixed32
- "e50ce0ffffff"+ // field 204, encoding 5, -32 fixed32
- "e90c4000000000000000"+ // field 205, encoding 1, 64 fixed64
- "e90cc0ffffffffffffff"+ // field 205, encoding 1, -64 fixed64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f"+ // field 403, encoding 0, value 127
- "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32
- "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64
-
-}
-
-// All required fields set, all packed repeated fields given two values.
-func TestEncodeDecode6(t *testing.T) {
- pb := initGoTest(false)
- pb.F_BoolRepeatedPacked = []bool{false, true}
- pb.F_Int32RepeatedPacked = []int32{32, 33}
- pb.F_Int64RepeatedPacked = []int64{64, 65}
- pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
- pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
- pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
- pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
- pb.F_FloatRepeatedPacked = []float32{32., 33.}
- pb.F_DoubleRepeatedPacked = []float64{64., 65.}
- pb.F_Sint32RepeatedPacked = []int32{32, -32}
- pb.F_Sint64RepeatedPacked = []int64{64, -64}
- pb.F_Sfixed32RepeatedPacked = []int32{32, -32}
- pb.F_Sfixed64RepeatedPacked = []int64{64, -64}
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
- "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
- "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
- "aa0308"+ // field 53, encoding 2, 8 bytes
- "a00c0000050d0000"+ // value 3232, value 3333
- "b20310"+ // field 54, encoding 2, 16 bytes
- "4019000000000000a519000000000000"+ // value 6464, value 6565
- "ba0306"+ // field 55, encoding 2, 6 bytes
- "a0dd1395ac14"+ // value 323232, value 333333
- "c20306"+ // field 56, encoding 2, 6 bytes
- "c0ba27b58928"+ // value 646464, value 656565
- "ca0308"+ // field 57, encoding 2, 8 bytes
- "0000004200000442"+ // value 32.0, value 33.0
- "d20310"+ // field 58, encoding 2, 16 bytes
- "00000000000050400000000000405040"+ // value 64.0, value 65.0
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64
- "b21f02"+ // field 502, encoding 2, 2 bytes
- "403f"+ // value 32, value -32
- "ba1f03"+ // field 503, encoding 2, 3 bytes
- "80017f"+ // value 64, value -64
- "c21f08"+ // field 504, encoding 2, 8 bytes
- "20000000e0ffffff"+ // value 32, value -32
- "ca1f10"+ // field 505, encoding 2, 16 bytes
- "4000000000000000c0ffffffffffffff") // value 64, value -64
-
-}
-
-// Test that we can encode empty bytes fields.
-func TestEncodeDecodeBytes1(t *testing.T) {
- pb := initGoTest(false)
-
- // Create our bytes
- pb.F_BytesRequired = []byte{}
- pb.F_BytesRepeated = [][]byte{{}}
- pb.F_BytesOptional = []byte{}
-
- d, err := Marshal(pb)
- if err != nil {
- t.Error(err)
- }
-
- pbd := new(GoTest)
- if err := Unmarshal(d, pbd); err != nil {
- t.Error(err)
- }
-
- if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
- t.Error("required empty bytes field is incorrect")
- }
- if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
- t.Error("repeated empty bytes field is incorrect")
- }
- if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
- t.Error("optional empty bytes field is incorrect")
- }
-}
-
-// Test that we encode nil-valued fields of a repeated bytes field correctly.
-// Since entries in a repeated field cannot be nil, nil must mean empty value.
-func TestEncodeDecodeBytes2(t *testing.T) {
- pb := initGoTest(false)
-
- // Create our bytes
- pb.F_BytesRepeated = [][]byte{nil}
-
- d, err := Marshal(pb)
- if err != nil {
- t.Error(err)
- }
-
- pbd := new(GoTest)
- if err := Unmarshal(d, pbd); err != nil {
- t.Error(err)
- }
-
- if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
- t.Error("Unexpected value for repeated bytes field")
- }
-}
-
-// All required fields set, defaults provided, all repeated fields given two values.
-func TestSkippingUnrecognizedFields(t *testing.T) {
- o := old()
- pb := initGoTestField()
-
- // Marshal it normally.
- o.Marshal(pb)
-
- // Now new a GoSkipTest record.
- skip := &GoSkipTest{
- SkipInt32: Int32(32),
- SkipFixed32: Uint32(3232),
- SkipFixed64: Uint64(6464),
- SkipString: String("skipper"),
- Skipgroup: &GoSkipTest_SkipGroup{
- GroupInt32: Int32(75),
- GroupString: String("wxyz"),
- },
- }
-
- // Marshal it into same buffer.
- o.Marshal(skip)
-
- pbd := new(GoTestField)
- o.Unmarshal(pbd)
-
- // The __unrecognized field should be a marshaling of GoSkipTest
- skipd := new(GoSkipTest)
-
- o.SetBuf(pbd.XXX_unrecognized)
- o.Unmarshal(skipd)
-
- if *skipd.SkipInt32 != *skip.SkipInt32 {
- t.Error("skip int32", skipd.SkipInt32)
- }
- if *skipd.SkipFixed32 != *skip.SkipFixed32 {
- t.Error("skip fixed32", skipd.SkipFixed32)
- }
- if *skipd.SkipFixed64 != *skip.SkipFixed64 {
- t.Error("skip fixed64", skipd.SkipFixed64)
- }
- if *skipd.SkipString != *skip.SkipString {
- t.Error("skip string", *skipd.SkipString)
- }
- if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
- t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
- }
- if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
- t.Error("skip group string", *skipd.Skipgroup.GroupString)
- }
-}
-
-// Check that unrecognized fields of a submessage are preserved.
-func TestSubmessageUnrecognizedFields(t *testing.T) {
- nm := &NewMessage{
- Nested: &NewMessage_Nested{
- Name: String("Nigel"),
- FoodGroup: String("carbs"),
- },
- }
- b, err := Marshal(nm)
- if err != nil {
- t.Fatalf("Marshal of NewMessage: %v", err)
- }
-
- // Unmarshal into an OldMessage.
- om := new(OldMessage)
- if err := Unmarshal(b, om); err != nil {
- t.Fatalf("Unmarshal to OldMessage: %v", err)
- }
- exp := &OldMessage{
- Nested: &OldMessage_Nested{
- Name: String("Nigel"),
- // normal protocol buffer users should not do this
- XXX_unrecognized: []byte("\x12\x05carbs"),
- },
- }
- if !Equal(om, exp) {
- t.Errorf("om = %v, want %v", om, exp)
- }
-
- // Clone the OldMessage.
- om = Clone(om).(*OldMessage)
- if !Equal(om, exp) {
- t.Errorf("Clone(om) = %v, want %v", om, exp)
- }
-
- // Marshal the OldMessage, then unmarshal it into an empty NewMessage.
- if b, err = Marshal(om); err != nil {
- t.Fatalf("Marshal of OldMessage: %v", err)
- }
- t.Logf("Marshal(%v) -> %q", om, b)
- nm2 := new(NewMessage)
- if err := Unmarshal(b, nm2); err != nil {
- t.Fatalf("Unmarshal to NewMessage: %v", err)
- }
- if !Equal(nm, nm2) {
- t.Errorf("NewMessage round-trip: %v => %v", nm, nm2)
- }
-}
-
-// Check that an int32 field can be upgraded to an int64 field.
-func TestNegativeInt32(t *testing.T) {
- om := &OldMessage{
- Num: Int32(-1),
- }
- b, err := Marshal(om)
- if err != nil {
- t.Fatalf("Marshal of OldMessage: %v", err)
- }
-
- // Check the size. It should be 11 bytes;
- // 1 for the field/wire type, and 10 for the negative number.
- if len(b) != 11 {
- t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b)
- }
-
- // Unmarshal into a NewMessage.
- nm := new(NewMessage)
- if err := Unmarshal(b, nm); err != nil {
- t.Fatalf("Unmarshal to NewMessage: %v", err)
- }
- want := &NewMessage{
- Num: Int64(-1),
- }
- if !Equal(nm, want) {
- t.Errorf("nm = %v, want %v", nm, want)
- }
-}
-
-// Check that we can grow an array (repeated field) to have many elements.
-// This test doesn't depend only on our encoding; for variety, it makes sure
-// we create, encode, and decode the correct contents explicitly. It's therefore
-// a bit messier.
-// This test also uses (and hence tests) the Marshal/Unmarshal functions
-// instead of the methods.
-func TestBigRepeated(t *testing.T) {
- pb := initGoTest(true)
-
- // Create the arrays
- const N = 50 // Internally the library starts much smaller.
- pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
- pb.F_Sint64Repeated = make([]int64, N)
- pb.F_Sint32Repeated = make([]int32, N)
- pb.F_BytesRepeated = make([][]byte, N)
- pb.F_StringRepeated = make([]string, N)
- pb.F_DoubleRepeated = make([]float64, N)
- pb.F_FloatRepeated = make([]float32, N)
- pb.F_Uint64Repeated = make([]uint64, N)
- pb.F_Uint32Repeated = make([]uint32, N)
- pb.F_Fixed64Repeated = make([]uint64, N)
- pb.F_Fixed32Repeated = make([]uint32, N)
- pb.F_Int64Repeated = make([]int64, N)
- pb.F_Int32Repeated = make([]int32, N)
- pb.F_BoolRepeated = make([]bool, N)
- pb.RepeatedField = make([]*GoTestField, N)
-
- // Fill in the arrays with checkable values.
- igtf := initGoTestField()
- igtrg := initGoTest_RepeatedGroup()
- for i := 0; i < N; i++ {
- pb.Repeatedgroup[i] = igtrg
- pb.F_Sint64Repeated[i] = int64(i)
- pb.F_Sint32Repeated[i] = int32(i)
- s := fmt.Sprint(i)
- pb.F_BytesRepeated[i] = []byte(s)
- pb.F_StringRepeated[i] = s
- pb.F_DoubleRepeated[i] = float64(i)
- pb.F_FloatRepeated[i] = float32(i)
- pb.F_Uint64Repeated[i] = uint64(i)
- pb.F_Uint32Repeated[i] = uint32(i)
- pb.F_Fixed64Repeated[i] = uint64(i)
- pb.F_Fixed32Repeated[i] = uint32(i)
- pb.F_Int64Repeated[i] = int64(i)
- pb.F_Int32Repeated[i] = int32(i)
- pb.F_BoolRepeated[i] = i%2 == 0
- pb.RepeatedField[i] = igtf
- }
-
- // Marshal.
- buf, _ := Marshal(pb)
-
- // Now test Unmarshal by recreating the original buffer.
- pbd := new(GoTest)
- Unmarshal(buf, pbd)
-
- // Check the checkable values
- for i := uint64(0); i < N; i++ {
- if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
- t.Error("pbd.Repeatedgroup bad")
- }
- if x := uint64(pbd.F_Sint64Repeated[i]); x != i {
- t.Error("pbd.F_Sint64Repeated bad", x, i)
- }
- if x := uint64(pbd.F_Sint32Repeated[i]); x != i {
- t.Error("pbd.F_Sint32Repeated bad", x, i)
- }
- s := fmt.Sprint(i)
- equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
- if pbd.F_StringRepeated[i] != s {
- t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
- }
- if x := uint64(pbd.F_DoubleRepeated[i]); x != i {
- t.Error("pbd.F_DoubleRepeated bad", x, i)
- }
- if x := uint64(pbd.F_FloatRepeated[i]); x != i {
- t.Error("pbd.F_FloatRepeated bad", x, i)
- }
- if x := pbd.F_Uint64Repeated[i]; x != i {
- t.Error("pbd.F_Uint64Repeated bad", x, i)
- }
- if x := uint64(pbd.F_Uint32Repeated[i]); x != i {
- t.Error("pbd.F_Uint32Repeated bad", x, i)
- }
- if x := pbd.F_Fixed64Repeated[i]; x != i {
- t.Error("pbd.F_Fixed64Repeated bad", x, i)
- }
- if x := uint64(pbd.F_Fixed32Repeated[i]); x != i {
- t.Error("pbd.F_Fixed32Repeated bad", x, i)
- }
- if x := uint64(pbd.F_Int64Repeated[i]); x != i {
- t.Error("pbd.F_Int64Repeated bad", x, i)
- }
- if x := uint64(pbd.F_Int32Repeated[i]); x != i {
- t.Error("pbd.F_Int32Repeated bad", x, i)
- }
- if x := pbd.F_BoolRepeated[i]; x != (i%2 == 0) {
- t.Error("pbd.F_BoolRepeated bad", x, i)
- }
- if pbd.RepeatedField[i] == nil { // TODO: more checking?
- t.Error("pbd.RepeatedField bad")
- }
- }
-}
-
-func TestBadWireTypeUnknown(t *testing.T) {
- var b []byte
- fmt.Sscanf("0a01780d00000000080b101612036161611521000000202c220362626225370000002203636363214200000000000000584d5a036464645900000000000056405d63000000", "%x", &b)
-
- m := new(MyMessage)
- if err := Unmarshal(b, m); err != nil {
- t.Errorf("unexpected Unmarshal error: %v", err)
- }
-
- var unknown []byte
- fmt.Sscanf("0a01780d0000000010161521000000202c2537000000214200000000000000584d5a036464645d63000000", "%x", &unknown)
- if !bytes.Equal(m.XXX_unrecognized, unknown) {
- t.Errorf("unknown bytes mismatch:\ngot %x\nwant %x", m.XXX_unrecognized, unknown)
- }
- DiscardUnknown(m)
-
- want := &MyMessage{Count: Int32(11), Name: String("aaa"), Pet: []string{"bbb", "ccc"}, Bigfloat: Float64(88)}
- if !Equal(m, want) {
- t.Errorf("message mismatch:\ngot %v\nwant %v", m, want)
- }
-}
-
-func encodeDecode(t *testing.T, in, out Message, msg string) {
- buf, err := Marshal(in)
- if err != nil {
- t.Fatalf("failed marshaling %v: %v", msg, err)
- }
- if err := Unmarshal(buf, out); err != nil {
- t.Fatalf("failed unmarshaling %v: %v", msg, err)
- }
-}
-
-func TestPackedNonPackedDecoderSwitching(t *testing.T) {
- np, p := new(NonPackedTest), new(PackedTest)
-
- // non-packed -> packed
- np.A = []int32{0, 1, 1, 2, 3, 5}
- encodeDecode(t, np, p, "non-packed -> packed")
- if !reflect.DeepEqual(np.A, p.B) {
- t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
- }
-
- // packed -> non-packed
- np.Reset()
- p.B = []int32{3, 1, 4, 1, 5, 9}
- encodeDecode(t, p, np, "packed -> non-packed")
- if !reflect.DeepEqual(p.B, np.A) {
- t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
- }
-}
-
-func TestProto1RepeatedGroup(t *testing.T) {
- pb := &MessageList{
- Message: []*MessageList_Message{
- {
- Name: String("blah"),
- Count: Int32(7),
- },
- // NOTE: pb.Message[1] is a nil
- nil,
- },
- }
-
- o := old()
- err := o.Marshal(pb)
- if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") {
- t.Fatalf("unexpected or no error when marshaling: %v", err)
- }
-}
-
-// Test that enums work. Checks for a bug introduced by making enums
-// named types instead of int32: newInt32FromUint64 would crash with
-// a type mismatch in reflect.PointTo.
-func TestEnum(t *testing.T) {
- pb := new(GoEnum)
- pb.Foo = FOO_FOO1.Enum()
- o := old()
- if err := o.Marshal(pb); err != nil {
- t.Fatal("error encoding enum:", err)
- }
- pb1 := new(GoEnum)
- if err := o.Unmarshal(pb1); err != nil {
- t.Fatal("error decoding enum:", err)
- }
- if *pb1.Foo != FOO_FOO1 {
- t.Error("expected 7 but got ", *pb1.Foo)
- }
-}
-
-// Enum types have String methods. Check that enum fields can be printed.
-// We don't care what the value actually is, just as long as it doesn't crash.
-func TestPrintingNilEnumFields(t *testing.T) {
- pb := new(GoEnum)
- _ = fmt.Sprintf("%+v", pb)
-}
-
-// Verify that absent required fields cause Marshal/Unmarshal to return errors.
-func TestRequiredFieldEnforcement(t *testing.T) {
- pb := new(GoTestField)
- _, err := Marshal(pb)
- if err == nil {
- t.Error("marshal: expected error, got nil")
- } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") {
- t.Errorf("marshal: bad error type: %v", err)
- }
-
- // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
- // so simply counting the required fields is insufficient.
- // field 1, encoding 2, value "hi"
- buf := []byte("\x0A\x02hi\x0A\x02hi")
- err = Unmarshal(buf, pb)
- if err == nil {
- t.Error("unmarshal: expected error, got nil")
- } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Type") && !strings.Contains(err.Error(), "{Unknown}") {
- // TODO: remove unknown cases once we commit to the new unmarshaler.
- t.Errorf("unmarshal: bad error type: %v", err)
- }
-}
-
-// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors.
-func TestRequiredFieldEnforcementGroups(t *testing.T) {
- pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}}
- if _, err := Marshal(pb); err == nil {
- t.Error("marshal: expected error, got nil")
- } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") {
- t.Errorf("marshal: bad error type: %v", err)
- }
-
- buf := []byte{11, 12}
- if err := Unmarshal(buf, pb); err == nil {
- t.Error("unmarshal: expected error, got nil")
- } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") && !strings.Contains(err.Error(), "Group.{Unknown}") {
- t.Errorf("unmarshal: bad error type: %v", err)
- }
-}
-
-func TestTypedNilMarshal(t *testing.T) {
- // A typed nil should return ErrNil and not crash.
- {
- var m *GoEnum
- if _, err := Marshal(m); err != ErrNil {
- t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err)
- }
- }
-
- {
- m := &Communique{Union: &Communique_Msg{nil}}
- if _, err := Marshal(m); err == nil || err == ErrNil {
- t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err)
- }
- }
-}
-
-// A type that implements the Marshaler interface, but is not nillable.
-type nonNillableInt uint64
-
-func (nni nonNillableInt) Marshal() ([]byte, error) {
- return EncodeVarint(uint64(nni)), nil
-}
-
-type NNIMessage struct {
- nni nonNillableInt
-}
-
-func (*NNIMessage) Reset() {}
-func (*NNIMessage) String() string { return "" }
-func (*NNIMessage) ProtoMessage() {}
-
-type NMMessage struct{}
-
-func (*NMMessage) Reset() {}
-func (*NMMessage) String() string { return "" }
-func (*NMMessage) ProtoMessage() {}
-
-// Verify a type that uses the Marshaler interface, but has a nil pointer.
-func TestNilMarshaler(t *testing.T) {
- // Try a struct with a Marshaler field that is nil.
- // It should be directly marshable.
- nmm := new(NMMessage)
- if _, err := Marshal(nmm); err != nil {
- t.Error("unexpected error marshaling nmm: ", err)
- }
-
- // Try a struct with a Marshaler field that is not nillable.
- nnim := new(NNIMessage)
- nnim.nni = 7
- var _ Marshaler = nnim.nni // verify it is truly a Marshaler
- if _, err := Marshal(nnim); err != nil {
- t.Error("unexpected error marshaling nnim: ", err)
- }
-}
-
-func TestAllSetDefaults(t *testing.T) {
- // Exercise SetDefaults with all scalar field types.
- m := &Defaults{
- // NaN != NaN, so override that here.
- F_Nan: Float32(1.7),
- }
- expected := &Defaults{
- F_Bool: Bool(true),
- F_Int32: Int32(32),
- F_Int64: Int64(64),
- F_Fixed32: Uint32(320),
- F_Fixed64: Uint64(640),
- F_Uint32: Uint32(3200),
- F_Uint64: Uint64(6400),
- F_Float: Float32(314159),
- F_Double: Float64(271828),
- F_String: String(`hello, "world!"` + "\n"),
- F_Bytes: []byte("Bignose"),
- F_Sint32: Int32(-32),
- F_Sint64: Int64(-64),
- F_Enum: Defaults_GREEN.Enum(),
- F_Pinf: Float32(float32(math.Inf(1))),
- F_Ninf: Float32(float32(math.Inf(-1))),
- F_Nan: Float32(1.7),
- StrZero: String(""),
- }
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestSetDefaultsWithSetField(t *testing.T) {
- // Check that a set value is not overridden.
- m := &Defaults{
- F_Int32: Int32(12),
- }
- SetDefaults(m)
- if v := m.GetF_Int32(); v != 12 {
- t.Errorf("m.FInt32 = %v, want 12", v)
- }
-}
-
-func TestSetDefaultsWithSubMessage(t *testing.T) {
- m := &OtherMessage{
- Key: Int64(123),
- Inner: &InnerMessage{
- Host: String("gopher"),
- },
- }
- expected := &OtherMessage{
- Key: Int64(123),
- Inner: &InnerMessage{
- Host: String("gopher"),
- Port: Int32(4000),
- },
- }
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) {
- m := &MyMessage{
- RepInner: []*InnerMessage{{}},
- }
- expected := &MyMessage{
- RepInner: []*InnerMessage{{
- Port: Int32(4000),
- }},
- }
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestSetDefaultWithRepeatedNonMessage(t *testing.T) {
- m := &MyMessage{
- Pet: []string{"turtle", "wombat"},
- }
- expected := Clone(m)
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestMaximumTagNumber(t *testing.T) {
- m := &MaxTag{
- LastField: String("natural goat essence"),
- }
- buf, err := Marshal(m)
- if err != nil {
- t.Fatalf("proto.Marshal failed: %v", err)
- }
- m2 := new(MaxTag)
- if err := Unmarshal(buf, m2); err != nil {
- t.Fatalf("proto.Unmarshal failed: %v", err)
- }
- if got, want := m2.GetLastField(), *m.LastField; got != want {
- t.Errorf("got %q, want %q", got, want)
- }
-}
-
-func TestJSON(t *testing.T) {
- m := &MyMessage{
- Count: Int32(4),
- Pet: []string{"bunny", "kitty"},
- Inner: &InnerMessage{
- Host: String("cauchy"),
- },
- Bikeshed: MyMessage_GREEN.Enum(),
- }
- const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}`
-
- b, err := json.Marshal(m)
- if err != nil {
- t.Fatalf("json.Marshal failed: %v", err)
- }
- s := string(b)
- if s != expected {
- t.Errorf("got %s\nwant %s", s, expected)
- }
-
- received := new(MyMessage)
- if err := json.Unmarshal(b, received); err != nil {
- t.Fatalf("json.Unmarshal failed: %v", err)
- }
- if !Equal(received, m) {
- t.Fatalf("got %s, want %s", received, m)
- }
-
- // Test unmarshalling of JSON with symbolic enum name.
- const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}`
- received.Reset()
- if err := json.Unmarshal([]byte(old), received); err != nil {
- t.Fatalf("json.Unmarshal failed: %v", err)
- }
- if !Equal(received, m) {
- t.Fatalf("got %s, want %s", received, m)
- }
-}
-
-func TestBadWireType(t *testing.T) {
- b := []byte{7<<3 | 6} // field 7, wire type 6
- pb := new(OtherMessage)
- if err := Unmarshal(b, pb); err == nil {
- t.Errorf("Unmarshal did not fail")
- } else if !strings.Contains(err.Error(), "unknown wire type") {
- t.Errorf("wrong error: %v", err)
- }
-}
-
-func TestBytesWithInvalidLength(t *testing.T) {
- // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
- b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0}
- Unmarshal(b, new(MyMessage))
-}
-
-func TestLengthOverflow(t *testing.T) {
- // Overflowing a length should not panic.
- b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01}
- Unmarshal(b, new(MyMessage))
-}
-
-func TestVarintOverflow(t *testing.T) {
- // Overflowing a 64-bit length should not be allowed.
- b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01}
- if err := Unmarshal(b, new(MyMessage)); err == nil {
- t.Fatalf("Overflowed uint64 length without error")
- }
-}
-
-func TestBytesWithInvalidLengthInGroup(t *testing.T) {
- // Overflowing a 64-bit length should not be allowed.
- b := []byte{0xbb, 0x30, 0xb2, 0x30, 0xb0, 0xb2, 0x83, 0xf1, 0xb0, 0xb2, 0xef, 0xbf, 0xbd, 0x01}
- if err := Unmarshal(b, new(MyMessage)); err == nil {
- t.Fatalf("Overflowed uint64 length without error")
- }
-}
-
-func TestUnmarshalFuzz(t *testing.T) {
- const N = 1000
- seed := time.Now().UnixNano()
- t.Logf("RNG seed is %d", seed)
- rng := rand.New(rand.NewSource(seed))
- buf := make([]byte, 20)
- for i := 0; i < N; i++ {
- for j := range buf {
- buf[j] = byte(rng.Intn(256))
- }
- fuzzUnmarshal(t, buf)
- }
-}
-
-func TestMergeMessages(t *testing.T) {
- pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}}
- data, err := Marshal(pb)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
-
- pb1 := new(MessageList)
- if err := Unmarshal(data, pb1); err != nil {
- t.Fatalf("first Unmarshal: %v", err)
- }
- if err := Unmarshal(data, pb1); err != nil {
- t.Fatalf("second Unmarshal: %v", err)
- }
- if len(pb1.Message) != 1 {
- t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message))
- }
-
- pb2 := new(MessageList)
- if err := UnmarshalMerge(data, pb2); err != nil {
- t.Fatalf("first UnmarshalMerge: %v", err)
- }
- if err := UnmarshalMerge(data, pb2); err != nil {
- t.Fatalf("second UnmarshalMerge: %v", err)
- }
- if len(pb2.Message) != 2 {
- t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message))
- }
-}
-
-func TestExtensionMarshalOrder(t *testing.T) {
- m := &MyMessage{Count: Int(123)}
- if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
-
- // Serialize m several times, and check we get the same bytes each time.
- var orig []byte
- for i := 0; i < 100; i++ {
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- if i == 0 {
- orig = b
- continue
- }
- if !bytes.Equal(b, orig) {
- t.Errorf("Bytes differ on attempt #%d", i)
- }
- }
-}
-
-func TestExtensionMapFieldMarshalDeterministic(t *testing.T) {
- m := &MyMessage{Count: Int(123)}
- if err := SetExtension(m, E_Ext_More, &Ext{MapField: map[int32]int32{1: 1, 2: 2, 3: 3, 4: 4}}); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- marshal := func(m Message) []byte {
- var b Buffer
- b.SetDeterministic(true)
- if err := b.Marshal(m); err != nil {
- t.Fatalf("Marshal failed: %v", err)
- }
- return b.Bytes()
- }
-
- want := marshal(m)
- for i := 0; i < 100; i++ {
- if got := marshal(m); !bytes.Equal(got, want) {
- t.Errorf("Marshal produced inconsistent output with determinism enabled (pass %d).\n got %v\nwant %v", i, got, want)
- }
- }
-}
-
-// Many extensions, because small maps might not iterate differently on each iteration.
-var exts = []*ExtensionDesc{
- E_X201,
- E_X202,
- E_X203,
- E_X204,
- E_X205,
- E_X206,
- E_X207,
- E_X208,
- E_X209,
- E_X210,
- E_X211,
- E_X212,
- E_X213,
- E_X214,
- E_X215,
- E_X216,
- E_X217,
- E_X218,
- E_X219,
- E_X220,
- E_X221,
- E_X222,
- E_X223,
- E_X224,
- E_X225,
- E_X226,
- E_X227,
- E_X228,
- E_X229,
- E_X230,
- E_X231,
- E_X232,
- E_X233,
- E_X234,
- E_X235,
- E_X236,
- E_X237,
- E_X238,
- E_X239,
- E_X240,
- E_X241,
- E_X242,
- E_X243,
- E_X244,
- E_X245,
- E_X246,
- E_X247,
- E_X248,
- E_X249,
- E_X250,
-}
-
-func TestMessageSetMarshalOrder(t *testing.T) {
- m := &MyMessageSet{}
- for _, x := range exts {
- if err := SetExtension(m, x, &Empty{}); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- }
-
- buf, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
-
- // Serialize m several times, and check we get the same bytes each time.
- for i := 0; i < 10; i++ {
- b1, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- if !bytes.Equal(b1, buf) {
- t.Errorf("Bytes differ on re-Marshal #%d", i)
- }
-
- m2 := &MyMessageSet{}
- if err := Unmarshal(buf, m2); err != nil {
- t.Errorf("Unmarshal: %v", err)
- }
- b2, err := Marshal(m2)
- if err != nil {
- t.Errorf("re-Marshal: %v", err)
- }
- if !bytes.Equal(b2, buf) {
- t.Errorf("Bytes differ on round-trip #%d", i)
- }
- }
-}
-
-func TestUnmarshalMergesMessages(t *testing.T) {
- // If a nested message occurs twice in the input,
- // the fields should be merged when decoding.
- a := &OtherMessage{
- Key: Int64(123),
- Inner: &InnerMessage{
- Host: String("polhode"),
- Port: Int32(1234),
- },
- }
- aData, err := Marshal(a)
- if err != nil {
- t.Fatalf("Marshal(a): %v", err)
- }
- b := &OtherMessage{
- Weight: Float32(1.2),
- Inner: &InnerMessage{
- Host: String("herpolhode"),
- Connected: Bool(true),
- },
- }
- bData, err := Marshal(b)
- if err != nil {
- t.Fatalf("Marshal(b): %v", err)
- }
- want := &OtherMessage{
- Key: Int64(123),
- Weight: Float32(1.2),
- Inner: &InnerMessage{
- Host: String("herpolhode"),
- Port: Int32(1234),
- Connected: Bool(true),
- },
- }
- got := new(OtherMessage)
- if err := Unmarshal(append(aData, bData...), got); err != nil {
- t.Fatalf("Unmarshal: %v", err)
- }
- if !Equal(got, want) {
- t.Errorf("\n got %v\nwant %v", got, want)
- }
-}
-
-func TestUnmarshalMergesGroups(t *testing.T) {
- // If a nested group occurs twice in the input,
- // the fields should be merged when decoding.
- a := &GroupNew{
- G: &GroupNew_G{
- X: Int32(7),
- Y: Int32(8),
- },
- }
- aData, err := Marshal(a)
- if err != nil {
- t.Fatalf("Marshal(a): %v", err)
- }
- b := &GroupNew{
- G: &GroupNew_G{
- X: Int32(9),
- },
- }
- bData, err := Marshal(b)
- if err != nil {
- t.Fatalf("Marshal(b): %v", err)
- }
- want := &GroupNew{
- G: &GroupNew_G{
- X: Int32(9),
- Y: Int32(8),
- },
- }
- got := new(GroupNew)
- if err := Unmarshal(append(aData, bData...), got); err != nil {
- t.Fatalf("Unmarshal: %v", err)
- }
- if !Equal(got, want) {
- t.Errorf("\n got %v\nwant %v", got, want)
- }
-}
-
-func TestEncodingSizes(t *testing.T) {
- tests := []struct {
- m Message
- n int
- }{
- {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6},
- {&Defaults{F_Int32: Int32(math.MinInt32)}, 11},
- {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6},
- {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6},
- }
- for _, test := range tests {
- b, err := Marshal(test.m)
- if err != nil {
- t.Errorf("Marshal(%v): %v", test.m, err)
- continue
- }
- if len(b) != test.n {
- t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n)
- }
- }
-}
-
-func TestRequiredNotSetError(t *testing.T) {
- pb := initGoTest(false)
- pb.RequiredField.Label = nil
- pb.F_Int32Required = nil
- pb.F_Int64Required = nil
-
- expected := "0807" + // field 1, encoding 0, value 7
- "2206" + "120474797065" + // field 4, encoding 2 (GoTestField)
- "5001" + // field 10, encoding 0, value 1
- "6d20000000" + // field 13, encoding 5, value 0x20
- "714000000000000000" + // field 14, encoding 1, value 0x40
- "78a019" + // field 15, encoding 0, value 0xca0 = 3232
- "8001c032" + // field 16, encoding 0, value 0x1940 = 6464
- "8d0100004a45" + // field 17, encoding 5, value 3232.0
- "9101000000000040b940" + // field 18, encoding 1, value 6464.0
- "9a0106" + "737472696e67" + // field 19, encoding 2, string "string"
- "b304" + // field 70, encoding 3, start group
- "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required"
- "b404" + // field 70, encoding 4, end group
- "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes"
- "b0063f" + // field 102, encoding 0, 0x3f zigzag32
- "b8067f" + // field 103, encoding 0, 0x7f zigzag64
- "c506e0ffffff" + // field 104, encoding 5, -32 fixed32
- "c906c0ffffffffffffff" // field 105, encoding 1, -64 fixed64
-
- o := old()
- bytes, err := Marshal(pb)
- if _, ok := err.(*RequiredNotSetError); !ok {
- fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err)
- o.DebugPrint("", bytes)
- t.Fatalf("expected = %s", expected)
- }
- if !strings.Contains(err.Error(), "RequiredField.Label") {
- t.Errorf("marshal-1 wrong err msg: %v", err)
- }
- if !equal(bytes, expected, t) {
- o.DebugPrint("neq 1", bytes)
- t.Fatalf("expected = %s", expected)
- }
-
- // Now test Unmarshal by recreating the original buffer.
- pbd := new(GoTest)
- err = Unmarshal(bytes, pbd)
- if _, ok := err.(*RequiredNotSetError); !ok {
- t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err)
- o.DebugPrint("", bytes)
- t.Fatalf("string = %s", expected)
- }
- if !strings.Contains(err.Error(), "RequiredField.Label") && !strings.Contains(err.Error(), "RequiredField.{Unknown}") {
- t.Errorf("unmarshal wrong err msg: %v", err)
- }
- bytes, err = Marshal(pbd)
- if _, ok := err.(*RequiredNotSetError); !ok {
- t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err)
- o.DebugPrint("", bytes)
- t.Fatalf("string = %s", expected)
- }
- if !strings.Contains(err.Error(), "RequiredField.Label") {
- t.Errorf("marshal-2 wrong err msg: %v", err)
- }
- if !equal(bytes, expected, t) {
- o.DebugPrint("neq 2", bytes)
- t.Fatalf("string = %s", expected)
- }
-}
-
-func TestRequiredNotSetErrorWithBadWireTypes(t *testing.T) {
- // Required field expects a varint, and properly found a varint.
- if err := Unmarshal([]byte{0x08, 0x00}, new(GoEnum)); err != nil {
- t.Errorf("Unmarshal = %v, want nil", err)
- }
- // Required field expects a varint, but found a fixed32 instead.
- if err := Unmarshal([]byte{0x0d, 0x00, 0x00, 0x00, 0x00}, new(GoEnum)); err == nil {
- t.Errorf("Unmarshal = nil, want RequiredNotSetError")
- }
- // Required field expects a varint, and found both a varint and fixed32 (ignored).
- m := new(GoEnum)
- if err := Unmarshal([]byte{0x08, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00}, m); err != nil {
- t.Errorf("Unmarshal = %v, want nil", err)
- }
- if !bytes.Equal(m.XXX_unrecognized, []byte{0x0d, 0x00, 0x00, 0x00, 0x00}) {
- t.Errorf("expected fixed32 to appear as unknown bytes: %x", m.XXX_unrecognized)
- }
-}
-
-func fuzzUnmarshal(t *testing.T, data []byte) {
- defer func() {
- if e := recover(); e != nil {
- t.Errorf("These bytes caused a panic: %+v", data)
- t.Logf("Stack:\n%s", debug.Stack())
- t.FailNow()
- }
- }()
-
- pb := new(MyMessage)
- Unmarshal(data, pb)
-}
-
-func TestMapFieldMarshal(t *testing.T) {
- m := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Rob",
- 4: "Ian",
- 8: "Dave",
- },
- }
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
-
- // b should be the concatenation of these three byte sequences in some order.
- parts := []string{
- "\n\a\b\x01\x12\x03Rob",
- "\n\a\b\x04\x12\x03Ian",
- "\n\b\b\x08\x12\x04Dave",
- }
- ok := false
- for i := range parts {
- for j := range parts {
- if j == i {
- continue
- }
- for k := range parts {
- if k == i || k == j {
- continue
- }
- try := parts[i] + parts[j] + parts[k]
- if bytes.Equal(b, []byte(try)) {
- ok = true
- break
- }
- }
- }
- }
- if !ok {
- t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2])
- }
- t.Logf("FYI b: %q", b)
-
- (new(Buffer)).DebugPrint("Dump of b", b)
-}
-
-func TestMapFieldDeterministicMarshal(t *testing.T) {
- m := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Rob",
- 4: "Ian",
- 8: "Dave",
- },
- }
-
- marshal := func(m Message) []byte {
- var b Buffer
- b.SetDeterministic(true)
- if err := b.Marshal(m); err != nil {
- t.Fatalf("Marshal failed: %v", err)
- }
- return b.Bytes()
- }
-
- want := marshal(m)
- for i := 0; i < 10; i++ {
- if got := marshal(m); !bytes.Equal(got, want) {
- t.Errorf("Marshal produced inconsistent output with determinism enabled (pass %d).\n got %v\nwant %v", i, got, want)
- }
- }
-}
-
-func TestMapFieldRoundTrips(t *testing.T) {
- m := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Rob",
- 4: "Ian",
- 8: "Dave",
- },
- MsgMapping: map[int64]*FloatingPoint{
- 0x7001: {F: Float64(2.0)},
- },
- ByteMapping: map[bool][]byte{
- false: []byte("that's not right!"),
- true: []byte("aye, 'tis true!"),
- },
- }
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- t.Logf("FYI b: %q", b)
- m2 := new(MessageWithMap)
- if err := Unmarshal(b, m2); err != nil {
- t.Fatalf("Unmarshal: %v", err)
- }
- if !Equal(m, m2) {
- t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", m, m2)
- }
-}
-
-func TestMapFieldWithNil(t *testing.T) {
- m1 := &MessageWithMap{
- MsgMapping: map[int64]*FloatingPoint{
- 1: nil,
- },
- }
- b, err := Marshal(m1)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- m2 := new(MessageWithMap)
- if err := Unmarshal(b, m2); err != nil {
- t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
- }
- if v, ok := m2.MsgMapping[1]; !ok {
- t.Error("msg_mapping[1] not present")
- } else if v != nil {
- t.Errorf("msg_mapping[1] not nil: %v", v)
- }
-}
-
-func TestMapFieldWithNilBytes(t *testing.T) {
- m1 := &MessageWithMap{
- ByteMapping: map[bool][]byte{
- false: {},
- true: nil,
- },
- }
- n := Size(m1)
- b, err := Marshal(m1)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- if n != len(b) {
- t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b))
- }
- m2 := new(MessageWithMap)
- if err := Unmarshal(b, m2); err != nil {
- t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
- }
- if v, ok := m2.ByteMapping[false]; !ok {
- t.Error("byte_mapping[false] not present")
- } else if len(v) != 0 {
- t.Errorf("byte_mapping[false] not empty: %#v", v)
- }
- if v, ok := m2.ByteMapping[true]; !ok {
- t.Error("byte_mapping[true] not present")
- } else if len(v) != 0 {
- t.Errorf("byte_mapping[true] not empty: %#v", v)
- }
-}
-
-func TestDecodeMapFieldMissingKey(t *testing.T) {
- b := []byte{
- 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes
- // no key
- 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m"
- }
- got := &MessageWithMap{}
- err := Unmarshal(b, got)
- if err != nil {
- t.Fatalf("failed to marshal map with missing key: %v", err)
- }
- want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}}
- if !Equal(got, want) {
- t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want)
- }
-}
-
-func TestDecodeMapFieldMissingValue(t *testing.T) {
- b := []byte{
- 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes
- 0x08, 0x01, // varint key, value 1
- // no value
- }
- got := &MessageWithMap{}
- err := Unmarshal(b, got)
- if err != nil {
- t.Fatalf("failed to marshal map with missing value: %v", err)
- }
- want := &MessageWithMap{NameMapping: map[int32]string{1: ""}}
- if !Equal(got, want) {
- t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want)
- }
-}
-
-func TestOneof(t *testing.T) {
- m := &Communique{}
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal of empty message with oneof: %v", err)
- }
- if len(b) != 0 {
- t.Errorf("Marshal of empty message yielded too many bytes: %v", b)
- }
-
- m = &Communique{
- Union: &Communique_Name{"Barry"},
- }
-
- // Round-trip.
- b, err = Marshal(m)
- if err != nil {
- t.Fatalf("Marshal of message with oneof: %v", err)
- }
- if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5)
- t.Errorf("Incorrect marshal of message with oneof: %v", b)
- }
- m.Reset()
- if err := Unmarshal(b, m); err != nil {
- t.Fatalf("Unmarshal of message with oneof: %v", err)
- }
- if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" {
- t.Errorf("After round trip, Union = %+v", m.Union)
- }
- if name := m.GetName(); name != "Barry" {
- t.Errorf("After round trip, GetName = %q, want %q", name, "Barry")
- }
-
- // Let's try with a message in the oneof.
- m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}}
- b, err = Marshal(m)
- if err != nil {
- t.Fatalf("Marshal of message with oneof set to message: %v", err)
- }
- if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16)
- t.Errorf("Incorrect marshal of message with oneof set to message: %v", b)
- }
- m.Reset()
- if err := Unmarshal(b, m); err != nil {
- t.Fatalf("Unmarshal of message with oneof set to message: %v", err)
- }
- ss, ok := m.Union.(*Communique_Msg)
- if !ok || ss.Msg.GetStringField() != "deep deep string" {
- t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union)
- }
-}
-
-func TestOneofNilBytes(t *testing.T) {
- // A oneof with nil byte slice should marshal to tag + 0 (size), with no error.
- m := &Communique{Union: &Communique_Data{Data: nil}}
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal failed: %v", err)
- }
- want := []byte{
- 7<<3 | 2, // tag 7, wire type 2
- 0, // size
- }
- if !bytes.Equal(b, want) {
- t.Errorf("Wrong result of Marshal: got %x, want %x", b, want)
- }
-}
-
-func TestInefficientPackedBool(t *testing.T) {
- // https://github.com/golang/protobuf/issues/76
- inp := []byte{
- 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes
- // Usually a bool should take a single byte,
- // but it is permitted to be any varint.
- 0xb9, 0x30,
- }
- if err := Unmarshal(inp, new(MoreRepeated)); err != nil {
- t.Error(err)
- }
-}
-
-// Make sure pure-reflect-based implementation handles
-// []int32-[]enum conversion correctly.
-func TestRepeatedEnum2(t *testing.T) {
- pb := &RepeatedEnum{
- Color: []RepeatedEnum_Color{RepeatedEnum_RED},
- }
- b, err := Marshal(pb)
- if err != nil {
- t.Fatalf("Marshal failed: %v", err)
- }
- x := new(RepeatedEnum)
- err = Unmarshal(b, x)
- if err != nil {
- t.Fatalf("Unmarshal failed: %v", err)
- }
- if !Equal(pb, x) {
- t.Errorf("Incorrect result: want: %v got: %v", pb, x)
- }
-}
-
-// TestConcurrentMarshal makes sure that it is safe to marshal
-// same message in multiple goroutines concurrently.
-func TestConcurrentMarshal(t *testing.T) {
- pb := initGoTest(true)
- const N = 100
- b := make([][]byte, N)
-
- var wg sync.WaitGroup
- for i := 0; i < N; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- var err error
- b[i], err = Marshal(pb)
- if err != nil {
- t.Errorf("marshal error: %v", err)
- }
- }(i)
- }
-
- wg.Wait()
- for i := 1; i < N; i++ {
- if !bytes.Equal(b[0], b[i]) {
- t.Errorf("concurrent marshal result not same: b[0] = %v, b[%d] = %v", b[0], i, b[i])
- }
- }
-}
-
-func TestInvalidUTF8(t *testing.T) {
- const wire = "\x12\x04\xde\xea\xca\xfe"
-
- var m GoTest
- if err := Unmarshal([]byte(wire), &m); err == nil {
- t.Errorf("Unmarshal error: got nil, want non-nil")
- }
-
- m.Reset()
- m.Table = String(wire[2:])
- if _, err := Marshal(&m); err == nil {
- t.Errorf("Marshal error: got nil, want non-nil")
- }
-}
-
-// Benchmarks
-
-func testMsg() *GoTest {
- pb := initGoTest(true)
- const N = 1000 // Internally the library starts much smaller.
- pb.F_Int32Repeated = make([]int32, N)
- pb.F_DoubleRepeated = make([]float64, N)
- for i := 0; i < N; i++ {
- pb.F_Int32Repeated[i] = int32(i)
- pb.F_DoubleRepeated[i] = float64(i)
- }
- return pb
-}
-
-func bytesMsg() *GoTest {
- pb := initGoTest(true)
- buf := make([]byte, 4000)
- for i := range buf {
- buf[i] = byte(i)
- }
- pb.F_BytesDefaulted = buf
- return pb
-}
-
-func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) {
- d, _ := marshal(pb)
- b.SetBytes(int64(len(d)))
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- marshal(pb)
- }
-}
-
-func benchmarkBufferMarshal(b *testing.B, pb Message) {
- p := NewBuffer(nil)
- benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
- p.Reset()
- err := p.Marshal(pb0)
- return p.Bytes(), err
- })
-}
-
-func benchmarkSize(b *testing.B, pb Message) {
- benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
- Size(pb)
- return nil, nil
- })
-}
-
-func newOf(pb Message) Message {
- in := reflect.ValueOf(pb)
- if in.IsNil() {
- return pb
- }
- return reflect.New(in.Type().Elem()).Interface().(Message)
-}
-
-func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) {
- d, _ := Marshal(pb)
- b.SetBytes(int64(len(d)))
- pbd := newOf(pb)
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- unmarshal(d, pbd)
- }
-}
-
-func benchmarkBufferUnmarshal(b *testing.B, pb Message) {
- p := NewBuffer(nil)
- benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error {
- p.SetBuf(d)
- return p.Unmarshal(pb0)
- })
-}
-
-// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes}
-
-func BenchmarkMarshal(b *testing.B) {
- benchmarkMarshal(b, testMsg(), Marshal)
-}
-
-func BenchmarkBufferMarshal(b *testing.B) {
- benchmarkBufferMarshal(b, testMsg())
-}
-
-func BenchmarkSize(b *testing.B) {
- benchmarkSize(b, testMsg())
-}
-
-func BenchmarkUnmarshal(b *testing.B) {
- benchmarkUnmarshal(b, testMsg(), Unmarshal)
-}
-
-func BenchmarkBufferUnmarshal(b *testing.B) {
- benchmarkBufferUnmarshal(b, testMsg())
-}
-
-func BenchmarkMarshalBytes(b *testing.B) {
- benchmarkMarshal(b, bytesMsg(), Marshal)
-}
-
-func BenchmarkBufferMarshalBytes(b *testing.B) {
- benchmarkBufferMarshal(b, bytesMsg())
-}
-
-func BenchmarkSizeBytes(b *testing.B) {
- benchmarkSize(b, bytesMsg())
-}
-
-func BenchmarkUnmarshalBytes(b *testing.B) {
- benchmarkUnmarshal(b, bytesMsg(), Unmarshal)
-}
-
-func BenchmarkBufferUnmarshalBytes(b *testing.B) {
- benchmarkBufferUnmarshal(b, bytesMsg())
-}
-
-func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) {
- b.StopTimer()
- pb := initGoTestField()
- skip := &GoSkipTest{
- SkipInt32: Int32(32),
- SkipFixed32: Uint32(3232),
- SkipFixed64: Uint64(6464),
- SkipString: String("skipper"),
- Skipgroup: &GoSkipTest_SkipGroup{
- GroupInt32: Int32(75),
- GroupString: String("wxyz"),
- },
- }
-
- pbd := new(GoTestField)
- p := NewBuffer(nil)
- p.Marshal(pb)
- p.Marshal(skip)
- p2 := NewBuffer(nil)
-
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- p2.SetBuf(p.Bytes())
- p2.Unmarshal(pbd)
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/any_test.go b/vendor/github.com/golang/protobuf/proto/any_test.go
deleted file mode 100644
index 56fc97c11..000000000
--- a/vendor/github.com/golang/protobuf/proto/any_test.go
+++ /dev/null
@@ -1,300 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto_test
-
-import (
- "strings"
- "testing"
-
- "github.com/golang/protobuf/proto"
-
- pb "github.com/golang/protobuf/proto/proto3_proto"
- testpb "github.com/golang/protobuf/proto/test_proto"
- anypb "github.com/golang/protobuf/ptypes/any"
-)
-
-var (
- expandedMarshaler = proto.TextMarshaler{ExpandAny: true}
- expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true}
-)
-
-// anyEqual reports whether two messages which may be google.protobuf.Any or may
-// contain google.protobuf.Any fields are equal. We can't use proto.Equal for
-// comparison, because semantically equivalent messages may be marshaled to
-// binary in different tag order. Instead, trust that TextMarshaler with
-// ExpandAny option works and compare the text marshaling results.
-func anyEqual(got, want proto.Message) bool {
- // if messages are proto.Equal, no need to marshal.
- if proto.Equal(got, want) {
- return true
- }
- g := expandedMarshaler.Text(got)
- w := expandedMarshaler.Text(want)
- return g == w
-}
-
-type golden struct {
- m proto.Message
- t, c string
-}
-
-var goldenMessages = makeGolden()
-
-func makeGolden() []golden {
- nested := &pb.Nested{Bunny: "Monty"}
- nb, err := proto.Marshal(nested)
- if err != nil {
- panic(err)
- }
- m1 := &pb.Message{
- Name: "David",
- ResultCount: 47,
- Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb},
- }
- m2 := &pb.Message{
- Name: "David",
- ResultCount: 47,
- Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb},
- }
- m3 := &pb.Message{
- Name: "David",
- ResultCount: 47,
- Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb},
- }
- m4 := &pb.Message{
- Name: "David",
- ResultCount: 47,
- Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb},
- }
- m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}
-
- any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}
- proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")})
- proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar"))
- any1b, err := proto.Marshal(any1)
- if err != nil {
- panic(err)
- }
- any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}}
- proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")})
- any2b, err := proto.Marshal(any2)
- if err != nil {
- panic(err)
- }
- m6 := &pb.Message{
- Name: "David",
- ResultCount: 47,
- Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
- ManyThings: []*anypb.Any{
- &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b},
- &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
- },
- }
-
- const (
- m1Golden = `
-name: "David"
-result_count: 47
-anything: <
- [type.googleapis.com/proto3_proto.Nested]: <
- bunny: "Monty"
- >
->
-`
- m2Golden = `
-name: "David"
-result_count: 47
-anything: <
- ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: <
- bunny: "Monty"
- >
->
-`
- m3Golden = `
-name: "David"
-result_count: 47
-anything: <
- ["type.googleapis.com/\"/proto3_proto.Nested"]: <
- bunny: "Monty"
- >
->
-`
- m4Golden = `
-name: "David"
-result_count: 47
-anything: <
- [type.googleapis.com/a/path/proto3_proto.Nested]: <
- bunny: "Monty"
- >
->
-`
- m5Golden = `
-[type.googleapis.com/proto3_proto.Nested]: <
- bunny: "Monty"
->
-`
- m6Golden = `
-name: "David"
-result_count: 47
-anything: <
- [type.googleapis.com/test_proto.MyMessage]: <
- count: 47
- name: "David"
- [test_proto.Ext.more]: <
- data: "foo"
- >
- [test_proto.Ext.text]: "bar"
- >
->
-many_things: <
- [type.googleapis.com/test_proto.MyMessage]: <
- count: 42
- bikeshed: GREEN
- rep_bytes: "roboto"
- [test_proto.Ext.more]: <
- data: "baz"
- >
- >
->
-many_things: <
- [type.googleapis.com/test_proto.MyMessage]: <
- count: 47
- name: "David"
- [test_proto.Ext.more]: <
- data: "foo"
- >
- [test_proto.Ext.text]: "bar"
- >
->
-`
- )
- return []golden{
- {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "},
- {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "},
- {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "},
- {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "},
- {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "},
- {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "},
- }
-}
-
-func TestMarshalGolden(t *testing.T) {
- for _, tt := range goldenMessages {
- if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want {
- t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want)
- }
- if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want {
- t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want)
- }
- }
-}
-
-func TestUnmarshalGolden(t *testing.T) {
- for _, tt := range goldenMessages {
- want := tt.m
- got := proto.Clone(tt.m)
- got.Reset()
- if err := proto.UnmarshalText(tt.t, got); err != nil {
- t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err)
- }
- if !anyEqual(got, want) {
- t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want)
- }
- got.Reset()
- if err := proto.UnmarshalText(tt.c, got); err != nil {
- t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err)
- }
- if !anyEqual(got, want) {
- t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want)
- }
- }
-}
-
-func TestMarshalUnknownAny(t *testing.T) {
- m := &pb.Message{
- Anything: &anypb.Any{
- TypeUrl: "foo",
- Value: []byte("bar"),
- },
- }
- want := `anything: <
- type_url: "foo"
- value: "bar"
->
-`
- got := expandedMarshaler.Text(m)
- if got != want {
- t.Errorf("got\n`%s`\nwant\n`%s`", got, want)
- }
-}
-
-func TestAmbiguousAny(t *testing.T) {
- pb := &anypb.Any{}
- err := proto.UnmarshalText(`
- type_url: "ttt/proto3_proto.Nested"
- value: "\n\x05Monty"
- `, pb)
- t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err)
- if err != nil {
- t.Errorf("failed to parse ambiguous Any message: %v", err)
- }
-}
-
-func TestUnmarshalOverwriteAny(t *testing.T) {
- pb := &anypb.Any{}
- err := proto.UnmarshalText(`
- [type.googleapis.com/a/path/proto3_proto.Nested]: <
- bunny: "Monty"
- >
- [type.googleapis.com/a/path/proto3_proto.Nested]: <
- bunny: "Rabbit of Caerbannog"
- >
- `, pb)
- want := `line 7: Any message unpacked multiple times, or "type_url" already set`
- if err.Error() != want {
- t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want)
- }
-}
-
-func TestUnmarshalAnyMixAndMatch(t *testing.T) {
- pb := &anypb.Any{}
- err := proto.UnmarshalText(`
- value: "\n\x05Monty"
- [type.googleapis.com/a/path/proto3_proto.Nested]: <
- bunny: "Rabbit of Caerbannog"
- >
- `, pb)
- want := `line 5: Any message unpacked multiple times, or "value" already set`
- if err.Error() != want {
- t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want)
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/buffer.go b/vendor/github.com/golang/protobuf/proto/buffer.go
new file mode 100644
index 000000000..e810e6fea
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/buffer.go
@@ -0,0 +1,324 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto
+
+import (
+ "errors"
+ "fmt"
+
+ "google.golang.org/protobuf/encoding/prototext"
+ "google.golang.org/protobuf/encoding/protowire"
+ "google.golang.org/protobuf/runtime/protoimpl"
+)
+
+const (
+ WireVarint = 0
+ WireFixed32 = 5
+ WireFixed64 = 1
+ WireBytes = 2
+ WireStartGroup = 3
+ WireEndGroup = 4
+)
+
+// EncodeVarint returns the varint encoded bytes of v.
+func EncodeVarint(v uint64) []byte {
+ return protowire.AppendVarint(nil, v)
+}
+
+// SizeVarint returns the length of the varint encoded bytes of v.
+// This is equal to len(EncodeVarint(v)).
+func SizeVarint(v uint64) int {
+ return protowire.SizeVarint(v)
+}
+
+// DecodeVarint parses a varint encoded integer from b,
+// returning the integer value and the length of the varint.
+// It returns (0, 0) if there is a parse error.
+func DecodeVarint(b []byte) (uint64, int) {
+ v, n := protowire.ConsumeVarint(b)
+ if n < 0 {
+ return 0, 0
+ }
+ return v, n
+}
+
+// Buffer is a buffer for encoding and decoding the protobuf wire format.
+// It may be reused between invocations to reduce memory usage.
+type Buffer struct {
+ buf []byte
+ idx int
+ deterministic bool
+}
+
+// NewBuffer allocates a new Buffer initialized with buf,
+// where the contents of buf are considered the unread portion of the buffer.
+func NewBuffer(buf []byte) *Buffer {
+ return &Buffer{buf: buf}
+}
+
+// SetDeterministic specifies whether to use deterministic serialization.
+//
+// Deterministic serialization guarantees that for a given binary, equal
+// messages will always be serialized to the same bytes. This implies:
+//
+// - Repeated serialization of a message will return the same bytes.
+// - Different processes of the same binary (which may be executing on
+// different machines) will serialize equal messages to the same bytes.
+//
+// Note that the deterministic serialization is NOT canonical across
+// languages. It is not guaranteed to remain stable over time. It is unstable
+// across different builds with schema changes due to unknown fields.
+// Users who need canonical serialization (e.g., persistent storage in a
+// canonical form, fingerprinting, etc.) should define their own
+// canonicalization specification and implement their own serializer rather
+// than relying on this API.
+//
+// If deterministic serialization is requested, map entries will be sorted
+// by keys in lexographical order. This is an implementation detail and
+// subject to change.
+func (b *Buffer) SetDeterministic(deterministic bool) {
+ b.deterministic = deterministic
+}
+
+// SetBuf sets buf as the internal buffer,
+// where the contents of buf are considered the unread portion of the buffer.
+func (b *Buffer) SetBuf(buf []byte) {
+ b.buf = buf
+ b.idx = 0
+}
+
+// Reset clears the internal buffer of all written and unread data.
+func (b *Buffer) Reset() {
+ b.buf = b.buf[:0]
+ b.idx = 0
+}
+
+// Bytes returns the internal buffer.
+func (b *Buffer) Bytes() []byte {
+ return b.buf
+}
+
+// Unread returns the unread portion of the buffer.
+func (b *Buffer) Unread() []byte {
+ return b.buf[b.idx:]
+}
+
+// Marshal appends the wire-format encoding of m to the buffer.
+func (b *Buffer) Marshal(m Message) error {
+ var err error
+ b.buf, err = marshalAppend(b.buf, m, b.deterministic)
+ return err
+}
+
+// Unmarshal parses the wire-format message in the buffer and
+// places the decoded results in m.
+// It does not reset m before unmarshaling.
+func (b *Buffer) Unmarshal(m Message) error {
+ err := UnmarshalMerge(b.Unread(), m)
+ b.idx = len(b.buf)
+ return err
+}
+
+type unknownFields struct{ XXX_unrecognized protoimpl.UnknownFields }
+
+func (m *unknownFields) String() string { panic("not implemented") }
+func (m *unknownFields) Reset() { panic("not implemented") }
+func (m *unknownFields) ProtoMessage() { panic("not implemented") }
+
+// DebugPrint dumps the encoded bytes of b with a header and footer including s
+// to stdout. This is only intended for debugging.
+func (*Buffer) DebugPrint(s string, b []byte) {
+ m := MessageReflect(new(unknownFields))
+ m.SetUnknown(b)
+ b, _ = prototext.MarshalOptions{AllowPartial: true, Indent: "\t"}.Marshal(m.Interface())
+ fmt.Printf("==== %s ====\n%s==== %s ====\n", s, b, s)
+}
+
+// EncodeVarint appends an unsigned varint encoding to the buffer.
+func (b *Buffer) EncodeVarint(v uint64) error {
+ b.buf = protowire.AppendVarint(b.buf, v)
+ return nil
+}
+
+// EncodeZigzag32 appends a 32-bit zig-zag varint encoding to the buffer.
+func (b *Buffer) EncodeZigzag32(v uint64) error {
+ return b.EncodeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
+}
+
+// EncodeZigzag64 appends a 64-bit zig-zag varint encoding to the buffer.
+func (b *Buffer) EncodeZigzag64(v uint64) error {
+ return b.EncodeVarint(uint64((uint64(v) << 1) ^ uint64((int64(v) >> 63))))
+}
+
+// EncodeFixed32 appends a 32-bit little-endian integer to the buffer.
+func (b *Buffer) EncodeFixed32(v uint64) error {
+ b.buf = protowire.AppendFixed32(b.buf, uint32(v))
+ return nil
+}
+
+// EncodeFixed64 appends a 64-bit little-endian integer to the buffer.
+func (b *Buffer) EncodeFixed64(v uint64) error {
+ b.buf = protowire.AppendFixed64(b.buf, uint64(v))
+ return nil
+}
+
+// EncodeRawBytes appends a length-prefixed raw bytes to the buffer.
+func (b *Buffer) EncodeRawBytes(v []byte) error {
+ b.buf = protowire.AppendBytes(b.buf, v)
+ return nil
+}
+
+// EncodeStringBytes appends a length-prefixed raw bytes to the buffer.
+// It does not validate whether v contains valid UTF-8.
+func (b *Buffer) EncodeStringBytes(v string) error {
+ b.buf = protowire.AppendString(b.buf, v)
+ return nil
+}
+
+// EncodeMessage appends a length-prefixed encoded message to the buffer.
+func (b *Buffer) EncodeMessage(m Message) error {
+ var err error
+ b.buf = protowire.AppendVarint(b.buf, uint64(Size(m)))
+ b.buf, err = marshalAppend(b.buf, m, b.deterministic)
+ return err
+}
+
+// DecodeVarint consumes an encoded unsigned varint from the buffer.
+func (b *Buffer) DecodeVarint() (uint64, error) {
+ v, n := protowire.ConsumeVarint(b.buf[b.idx:])
+ if n < 0 {
+ return 0, protowire.ParseError(n)
+ }
+ b.idx += n
+ return uint64(v), nil
+}
+
+// DecodeZigzag32 consumes an encoded 32-bit zig-zag varint from the buffer.
+func (b *Buffer) DecodeZigzag32() (uint64, error) {
+ v, err := b.DecodeVarint()
+ if err != nil {
+ return 0, err
+ }
+ return uint64((uint32(v) >> 1) ^ uint32((int32(v&1)<<31)>>31)), nil
+}
+
+// DecodeZigzag64 consumes an encoded 64-bit zig-zag varint from the buffer.
+func (b *Buffer) DecodeZigzag64() (uint64, error) {
+ v, err := b.DecodeVarint()
+ if err != nil {
+ return 0, err
+ }
+ return uint64((uint64(v) >> 1) ^ uint64((int64(v&1)<<63)>>63)), nil
+}
+
+// DecodeFixed32 consumes a 32-bit little-endian integer from the buffer.
+func (b *Buffer) DecodeFixed32() (uint64, error) {
+ v, n := protowire.ConsumeFixed32(b.buf[b.idx:])
+ if n < 0 {
+ return 0, protowire.ParseError(n)
+ }
+ b.idx += n
+ return uint64(v), nil
+}
+
+// DecodeFixed64 consumes a 64-bit little-endian integer from the buffer.
+func (b *Buffer) DecodeFixed64() (uint64, error) {
+ v, n := protowire.ConsumeFixed64(b.buf[b.idx:])
+ if n < 0 {
+ return 0, protowire.ParseError(n)
+ }
+ b.idx += n
+ return uint64(v), nil
+}
+
+// DecodeRawBytes consumes a length-prefixed raw bytes from the buffer.
+// If alloc is specified, it returns a copy the raw bytes
+// rather than a sub-slice of the buffer.
+func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) {
+ v, n := protowire.ConsumeBytes(b.buf[b.idx:])
+ if n < 0 {
+ return nil, protowire.ParseError(n)
+ }
+ b.idx += n
+ if alloc {
+ v = append([]byte(nil), v...)
+ }
+ return v, nil
+}
+
+// DecodeStringBytes consumes a length-prefixed raw bytes from the buffer.
+// It does not validate whether the raw bytes contain valid UTF-8.
+func (b *Buffer) DecodeStringBytes() (string, error) {
+ v, n := protowire.ConsumeString(b.buf[b.idx:])
+ if n < 0 {
+ return "", protowire.ParseError(n)
+ }
+ b.idx += n
+ return v, nil
+}
+
+// DecodeMessage consumes a length-prefixed message from the buffer.
+// It does not reset m before unmarshaling.
+func (b *Buffer) DecodeMessage(m Message) error {
+ v, err := b.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ return UnmarshalMerge(v, m)
+}
+
+// DecodeGroup consumes a message group from the buffer.
+// It assumes that the start group marker has already been consumed and
+// consumes all bytes until (and including the end group marker).
+// It does not reset m before unmarshaling.
+func (b *Buffer) DecodeGroup(m Message) error {
+ v, n, err := consumeGroup(b.buf[b.idx:])
+ if err != nil {
+ return err
+ }
+ b.idx += n
+ return UnmarshalMerge(v, m)
+}
+
+// consumeGroup parses b until it finds an end group marker, returning
+// the raw bytes of the message (excluding the end group marker) and the
+// the total length of the message (including the end group marker).
+func consumeGroup(b []byte) ([]byte, int, error) {
+ b0 := b
+ depth := 1 // assume this follows a start group marker
+ for {
+ _, wtyp, tagLen := protowire.ConsumeTag(b)
+ if tagLen < 0 {
+ return nil, 0, protowire.ParseError(tagLen)
+ }
+ b = b[tagLen:]
+
+ var valLen int
+ switch wtyp {
+ case protowire.VarintType:
+ _, valLen = protowire.ConsumeVarint(b)
+ case protowire.Fixed32Type:
+ _, valLen = protowire.ConsumeFixed32(b)
+ case protowire.Fixed64Type:
+ _, valLen = protowire.ConsumeFixed64(b)
+ case protowire.BytesType:
+ _, valLen = protowire.ConsumeBytes(b)
+ case protowire.StartGroupType:
+ depth++
+ case protowire.EndGroupType:
+ depth--
+ default:
+ return nil, 0, errors.New("proto: cannot parse reserved wire type")
+ }
+ if valLen < 0 {
+ return nil, 0, protowire.ParseError(valLen)
+ }
+ b = b[valLen:]
+
+ if depth == 0 {
+ return b0[:len(b0)-len(b)-tagLen], len(b0) - len(b), nil
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go
deleted file mode 100644
index 3cd3249f7..000000000
--- a/vendor/github.com/golang/protobuf/proto/clone.go
+++ /dev/null
@@ -1,253 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Protocol buffer deep copy and merge.
-// TODO: RawMessage.
-
-package proto
-
-import (
- "fmt"
- "log"
- "reflect"
- "strings"
-)
-
-// Clone returns a deep copy of a protocol buffer.
-func Clone(src Message) Message {
- in := reflect.ValueOf(src)
- if in.IsNil() {
- return src
- }
- out := reflect.New(in.Type().Elem())
- dst := out.Interface().(Message)
- Merge(dst, src)
- return dst
-}
-
-// Merger is the interface representing objects that can merge messages of the same type.
-type Merger interface {
- // Merge merges src into this message.
- // Required and optional fields that are set in src will be set to that value in dst.
- // Elements of repeated fields will be appended.
- //
- // Merge may panic if called with a different argument type than the receiver.
- Merge(src Message)
-}
-
-// generatedMerger is the custom merge method that generated protos will have.
-// We must add this method since a generate Merge method will conflict with
-// many existing protos that have a Merge data field already defined.
-type generatedMerger interface {
- XXX_Merge(src Message)
-}
-
-// Merge merges src into dst.
-// Required and optional fields that are set in src will be set to that value in dst.
-// Elements of repeated fields will be appended.
-// Merge panics if src and dst are not the same type, or if dst is nil.
-func Merge(dst, src Message) {
- if m, ok := dst.(Merger); ok {
- m.Merge(src)
- return
- }
-
- in := reflect.ValueOf(src)
- out := reflect.ValueOf(dst)
- if out.IsNil() {
- panic("proto: nil destination")
- }
- if in.Type() != out.Type() {
- panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
- }
- if in.IsNil() {
- return // Merge from nil src is a noop
- }
- if m, ok := dst.(generatedMerger); ok {
- m.XXX_Merge(src)
- return
- }
- mergeStruct(out.Elem(), in.Elem())
-}
-
-func mergeStruct(out, in reflect.Value) {
- sprop := GetProperties(in.Type())
- for i := 0; i < in.NumField(); i++ {
- f := in.Type().Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
- }
-
- if emIn, err := extendable(in.Addr().Interface()); err == nil {
- emOut, _ := extendable(out.Addr().Interface())
- mIn, muIn := emIn.extensionsRead()
- if mIn != nil {
- mOut := emOut.extensionsWrite()
- muIn.Lock()
- mergeExtension(mOut, mIn)
- muIn.Unlock()
- }
- }
-
- uf := in.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return
- }
- uin := uf.Bytes()
- if len(uin) > 0 {
- out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
- }
-}
-
-// mergeAny performs a merge between two values of the same type.
-// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
-// prop is set if this is a struct field (it may be nil).
-func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
- if in.Type() == protoMessageType {
- if !in.IsNil() {
- if out.IsNil() {
- out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
- } else {
- Merge(out.Interface().(Message), in.Interface().(Message))
- }
- }
- return
- }
- switch in.Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- if !viaPtr && isProto3Zero(in) {
- return
- }
- out.Set(in)
- case reflect.Interface:
- // Probably a oneof field; copy non-nil values.
- if in.IsNil() {
- return
- }
- // Allocate destination if it is not set, or set to a different type.
- // Otherwise we will merge as normal.
- if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
- out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
- }
- mergeAny(out.Elem(), in.Elem(), false, nil)
- case reflect.Map:
- if in.Len() == 0 {
- return
- }
- if out.IsNil() {
- out.Set(reflect.MakeMap(in.Type()))
- }
- // For maps with value types of *T or []byte we need to deep copy each value.
- elemKind := in.Type().Elem().Kind()
- for _, key := range in.MapKeys() {
- var val reflect.Value
- switch elemKind {
- case reflect.Ptr:
- val = reflect.New(in.Type().Elem().Elem())
- mergeAny(val, in.MapIndex(key), false, nil)
- case reflect.Slice:
- val = in.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- default:
- val = in.MapIndex(key)
- }
- out.SetMapIndex(key, val)
- }
- case reflect.Ptr:
- if in.IsNil() {
- return
- }
- if out.IsNil() {
- out.Set(reflect.New(in.Elem().Type()))
- }
- mergeAny(out.Elem(), in.Elem(), true, nil)
- case reflect.Slice:
- if in.IsNil() {
- return
- }
- if in.Type().Elem().Kind() == reflect.Uint8 {
- // []byte is a scalar bytes field, not a repeated field.
-
- // Edge case: if this is in a proto3 message, a zero length
- // bytes field is considered the zero value, and should not
- // be merged.
- if prop != nil && prop.proto3 && in.Len() == 0 {
- return
- }
-
- // Make a deep copy.
- // Append to []byte{} instead of []byte(nil) so that we never end up
- // with a nil result.
- out.SetBytes(append([]byte{}, in.Bytes()...))
- return
- }
- n := in.Len()
- if out.IsNil() {
- out.Set(reflect.MakeSlice(in.Type(), 0, n))
- }
- switch in.Type().Elem().Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- out.Set(reflect.AppendSlice(out, in))
- default:
- for i := 0; i < n; i++ {
- x := reflect.Indirect(reflect.New(in.Type().Elem()))
- mergeAny(x, in.Index(i), false, nil)
- out.Set(reflect.Append(out, x))
- }
- }
- case reflect.Struct:
- mergeStruct(out, in)
- default:
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to copy %v", in)
- }
-}
-
-func mergeExtension(out, in map[int32]Extension) {
- for extNum, eIn := range in {
- eOut := Extension{desc: eIn.desc}
- if eIn.value != nil {
- v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
- mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
- eOut.value = v.Interface()
- }
- if eIn.enc != nil {
- eOut.enc = make([]byte, len(eIn.enc))
- copy(eOut.enc, eIn.enc)
- }
-
- out[extNum] = eOut
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/clone_test.go b/vendor/github.com/golang/protobuf/proto/clone_test.go
deleted file mode 100644
index 0d3b12737..000000000
--- a/vendor/github.com/golang/protobuf/proto/clone_test.go
+++ /dev/null
@@ -1,390 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto_test
-
-import (
- "testing"
-
- "github.com/golang/protobuf/proto"
-
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/test_proto"
-)
-
-var cloneTestMessage = &pb.MyMessage{
- Count: proto.Int32(42),
- Name: proto.String("Dave"),
- Pet: []string{"bunny", "kitty", "horsey"},
- Inner: &pb.InnerMessage{
- Host: proto.String("niles"),
- Port: proto.Int32(9099),
- Connected: proto.Bool(true),
- },
- Others: []*pb.OtherMessage{
- {
- Value: []byte("some bytes"),
- },
- },
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(6),
- },
- RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
-}
-
-func init() {
- ext := &pb.Ext{
- Data: proto.String("extension"),
- }
- if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil {
- panic("SetExtension: " + err.Error())
- }
-}
-
-func TestClone(t *testing.T) {
- m := proto.Clone(cloneTestMessage).(*pb.MyMessage)
- if !proto.Equal(m, cloneTestMessage) {
- t.Fatalf("Clone(%v) = %v", cloneTestMessage, m)
- }
-
- // Verify it was a deep copy.
- *m.Inner.Port++
- if proto.Equal(m, cloneTestMessage) {
- t.Error("Mutating clone changed the original")
- }
- // Byte fields and repeated fields should be copied.
- if &m.Pet[0] == &cloneTestMessage.Pet[0] {
- t.Error("Pet: repeated field not copied")
- }
- if &m.Others[0] == &cloneTestMessage.Others[0] {
- t.Error("Others: repeated field not copied")
- }
- if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] {
- t.Error("Others[0].Value: bytes field not copied")
- }
- if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] {
- t.Error("RepBytes: repeated field not copied")
- }
- if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] {
- t.Error("RepBytes[0]: bytes field not copied")
- }
-}
-
-func TestCloneNil(t *testing.T) {
- var m *pb.MyMessage
- if c := proto.Clone(m); !proto.Equal(m, c) {
- t.Errorf("Clone(%v) = %v", m, c)
- }
-}
-
-var mergeTests = []struct {
- src, dst, want proto.Message
-}{
- {
- src: &pb.MyMessage{
- Count: proto.Int32(42),
- },
- dst: &pb.MyMessage{
- Name: proto.String("Dave"),
- },
- want: &pb.MyMessage{
- Count: proto.Int32(42),
- Name: proto.String("Dave"),
- },
- },
- {
- src: &pb.MyMessage{
- Inner: &pb.InnerMessage{
- Host: proto.String("hey"),
- Connected: proto.Bool(true),
- },
- Pet: []string{"horsey"},
- Others: []*pb.OtherMessage{
- {
- Value: []byte("some bytes"),
- },
- },
- },
- dst: &pb.MyMessage{
- Inner: &pb.InnerMessage{
- Host: proto.String("niles"),
- Port: proto.Int32(9099),
- },
- Pet: []string{"bunny", "kitty"},
- Others: []*pb.OtherMessage{
- {
- Key: proto.Int64(31415926535),
- },
- {
- // Explicitly test a src=nil field
- Inner: nil,
- },
- },
- },
- want: &pb.MyMessage{
- Inner: &pb.InnerMessage{
- Host: proto.String("hey"),
- Connected: proto.Bool(true),
- Port: proto.Int32(9099),
- },
- Pet: []string{"bunny", "kitty", "horsey"},
- Others: []*pb.OtherMessage{
- {
- Key: proto.Int64(31415926535),
- },
- {},
- {
- Value: []byte("some bytes"),
- },
- },
- },
- },
- {
- src: &pb.MyMessage{
- RepBytes: [][]byte{[]byte("wow")},
- },
- dst: &pb.MyMessage{
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(6),
- },
- RepBytes: [][]byte{[]byte("sham")},
- },
- want: &pb.MyMessage{
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(6),
- },
- RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
- },
- },
- // Check that a scalar bytes field replaces rather than appends.
- {
- src: &pb.OtherMessage{Value: []byte("foo")},
- dst: &pb.OtherMessage{Value: []byte("bar")},
- want: &pb.OtherMessage{Value: []byte("foo")},
- },
- {
- src: &pb.MessageWithMap{
- NameMapping: map[int32]string{6: "Nigel"},
- MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)},
- 0x4002: &pb.FloatingPoint{
- F: proto.Float64(2.0),
- },
- },
- ByteMapping: map[bool][]byte{true: []byte("wowsa")},
- },
- dst: &pb.MessageWithMap{
- NameMapping: map[int32]string{
- 6: "Bruce", // should be overwritten
- 7: "Andrew",
- },
- MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4002: &pb.FloatingPoint{
- F: proto.Float64(3.0),
- Exact: proto.Bool(true),
- }, // the entire message should be overwritten
- },
- },
- want: &pb.MessageWithMap{
- NameMapping: map[int32]string{
- 6: "Nigel",
- 7: "Andrew",
- },
- MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)},
- 0x4002: &pb.FloatingPoint{
- F: proto.Float64(2.0),
- },
- },
- ByteMapping: map[bool][]byte{true: []byte("wowsa")},
- },
- },
- // proto3 shouldn't merge zero values,
- // in the same way that proto2 shouldn't merge nils.
- {
- src: &proto3pb.Message{
- Name: "Aaron",
- Data: []byte(""), // zero value, but not nil
- },
- dst: &proto3pb.Message{
- HeightInCm: 176,
- Data: []byte("texas!"),
- },
- want: &proto3pb.Message{
- Name: "Aaron",
- HeightInCm: 176,
- Data: []byte("texas!"),
- },
- },
- { // Oneof fields should merge by assignment.
- src: &pb.Communique{Union: &pb.Communique_Number{41}},
- dst: &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}},
- want: &pb.Communique{Union: &pb.Communique_Number{41}},
- },
- { // Oneof nil is the same as not set.
- src: &pb.Communique{},
- dst: &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}},
- want: &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}},
- },
- {
- src: &pb.Communique{Union: &pb.Communique_Number{1337}},
- dst: &pb.Communique{},
- want: &pb.Communique{Union: &pb.Communique_Number{1337}},
- },
- {
- src: &pb.Communique{Union: &pb.Communique_Col{pb.MyMessage_RED}},
- dst: &pb.Communique{},
- want: &pb.Communique{Union: &pb.Communique_Col{pb.MyMessage_RED}},
- },
- {
- src: &pb.Communique{Union: &pb.Communique_Data{[]byte("hello")}},
- dst: &pb.Communique{},
- want: &pb.Communique{Union: &pb.Communique_Data{[]byte("hello")}},
- },
- {
- src: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{BytesField: []byte{1, 2, 3}}}},
- dst: &pb.Communique{},
- want: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{BytesField: []byte{1, 2, 3}}}},
- },
- {
- src: &pb.Communique{Union: &pb.Communique_Msg{}},
- dst: &pb.Communique{},
- want: &pb.Communique{Union: &pb.Communique_Msg{}},
- },
- {
- src: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{StringField: proto.String("123")}}},
- dst: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{BytesField: []byte{1, 2, 3}}}},
- want: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{StringField: proto.String("123"), BytesField: []byte{1, 2, 3}}}},
- },
- {
- src: &proto3pb.Message{
- Terrain: map[string]*proto3pb.Nested{
- "kay_a": &proto3pb.Nested{Cute: true}, // replace
- "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert
- },
- },
- dst: &proto3pb.Message{
- Terrain: map[string]*proto3pb.Nested{
- "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced
- "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep
- },
- },
- want: &proto3pb.Message{
- Terrain: map[string]*proto3pb.Nested{
- "kay_a": &proto3pb.Nested{Cute: true},
- "kay_b": &proto3pb.Nested{Bunny: "rabbit"},
- "kay_c": &proto3pb.Nested{Bunny: "bunny"},
- },
- },
- },
- {
- src: &pb.GoTest{
- F_BoolRepeated: []bool{},
- F_Int32Repeated: []int32{},
- F_Int64Repeated: []int64{},
- F_Uint32Repeated: []uint32{},
- F_Uint64Repeated: []uint64{},
- F_FloatRepeated: []float32{},
- F_DoubleRepeated: []float64{},
- F_StringRepeated: []string{},
- F_BytesRepeated: [][]byte{},
- },
- dst: &pb.GoTest{},
- want: &pb.GoTest{
- F_BoolRepeated: []bool{},
- F_Int32Repeated: []int32{},
- F_Int64Repeated: []int64{},
- F_Uint32Repeated: []uint32{},
- F_Uint64Repeated: []uint64{},
- F_FloatRepeated: []float32{},
- F_DoubleRepeated: []float64{},
- F_StringRepeated: []string{},
- F_BytesRepeated: [][]byte{},
- },
- },
- {
- src: &pb.GoTest{},
- dst: &pb.GoTest{
- F_BoolRepeated: []bool{},
- F_Int32Repeated: []int32{},
- F_Int64Repeated: []int64{},
- F_Uint32Repeated: []uint32{},
- F_Uint64Repeated: []uint64{},
- F_FloatRepeated: []float32{},
- F_DoubleRepeated: []float64{},
- F_StringRepeated: []string{},
- F_BytesRepeated: [][]byte{},
- },
- want: &pb.GoTest{
- F_BoolRepeated: []bool{},
- F_Int32Repeated: []int32{},
- F_Int64Repeated: []int64{},
- F_Uint32Repeated: []uint32{},
- F_Uint64Repeated: []uint64{},
- F_FloatRepeated: []float32{},
- F_DoubleRepeated: []float64{},
- F_StringRepeated: []string{},
- F_BytesRepeated: [][]byte{},
- },
- },
- {
- src: &pb.GoTest{
- F_BytesRepeated: [][]byte{nil, []byte{}, []byte{0}},
- },
- dst: &pb.GoTest{},
- want: &pb.GoTest{
- F_BytesRepeated: [][]byte{nil, []byte{}, []byte{0}},
- },
- },
- {
- src: &pb.MyMessage{
- Others: []*pb.OtherMessage{},
- },
- dst: &pb.MyMessage{},
- want: &pb.MyMessage{
- Others: []*pb.OtherMessage{},
- },
- },
-}
-
-func TestMerge(t *testing.T) {
- for _, m := range mergeTests {
- got := proto.Clone(m.dst)
- if !proto.Equal(got, m.dst) {
- t.Errorf("Clone()\ngot %v\nwant %v", got, m.dst)
- continue
- }
- proto.Merge(got, m.src)
- if !proto.Equal(got, m.want) {
- t.Errorf("Merge(%v, %v)\ngot %v\nwant %v", m.dst, m.src, got, m.want)
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go
deleted file mode 100644
index d9aa3c42d..000000000
--- a/vendor/github.com/golang/protobuf/proto/decode.go
+++ /dev/null
@@ -1,428 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-/*
- * Routines for decoding protocol buffer data to construct in-memory representations.
- */
-
-import (
- "errors"
- "fmt"
- "io"
-)
-
-// errOverflow is returned when an integer is too large to be represented.
-var errOverflow = errors.New("proto: integer overflow")
-
-// ErrInternalBadWireType is returned by generated code when an incorrect
-// wire type is encountered. It does not get returned to user code.
-var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
-
-// DecodeVarint reads a varint-encoded integer from the slice.
-// It returns the integer and the number of bytes consumed, or
-// zero if there is not enough.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func DecodeVarint(buf []byte) (x uint64, n int) {
- for shift := uint(0); shift < 64; shift += 7 {
- if n >= len(buf) {
- return 0, 0
- }
- b := uint64(buf[n])
- n++
- x |= (b & 0x7F) << shift
- if (b & 0x80) == 0 {
- return x, n
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- return 0, 0
-}
-
-func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
- i := p.index
- l := len(p.buf)
-
- for shift := uint(0); shift < 64; shift += 7 {
- if i >= l {
- err = io.ErrUnexpectedEOF
- return
- }
- b := p.buf[i]
- i++
- x |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- p.index = i
- return
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- err = errOverflow
- return
-}
-
-// DecodeVarint reads a varint-encoded integer from the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) DecodeVarint() (x uint64, err error) {
- i := p.index
- buf := p.buf
-
- if i >= len(buf) {
- return 0, io.ErrUnexpectedEOF
- } else if buf[i] < 0x80 {
- p.index++
- return uint64(buf[i]), nil
- } else if len(buf)-i < 10 {
- return p.decodeVarintSlow()
- }
-
- var b uint64
- // we already checked the first byte
- x = uint64(buf[i]) - 0x80
- i++
-
- b = uint64(buf[i])
- i++
- x += b << 7
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 7
-
- b = uint64(buf[i])
- i++
- x += b << 14
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 14
-
- b = uint64(buf[i])
- i++
- x += b << 21
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 21
-
- b = uint64(buf[i])
- i++
- x += b << 28
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 28
-
- b = uint64(buf[i])
- i++
- x += b << 35
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 35
-
- b = uint64(buf[i])
- i++
- x += b << 42
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 42
-
- b = uint64(buf[i])
- i++
- x += b << 49
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 49
-
- b = uint64(buf[i])
- i++
- x += b << 56
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 56
-
- b = uint64(buf[i])
- i++
- x += b << 63
- if b&0x80 == 0 {
- goto done
- }
- // x -= 0x80 << 63 // Always zero.
-
- return 0, errOverflow
-
-done:
- p.index = i
- return x, nil
-}
-
-// DecodeFixed64 reads a 64-bit integer from the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) DecodeFixed64() (x uint64, err error) {
- // x, err already 0
- i := p.index + 8
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-8])
- x |= uint64(p.buf[i-7]) << 8
- x |= uint64(p.buf[i-6]) << 16
- x |= uint64(p.buf[i-5]) << 24
- x |= uint64(p.buf[i-4]) << 32
- x |= uint64(p.buf[i-3]) << 40
- x |= uint64(p.buf[i-2]) << 48
- x |= uint64(p.buf[i-1]) << 56
- return
-}
-
-// DecodeFixed32 reads a 32-bit integer from the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) DecodeFixed32() (x uint64, err error) {
- // x, err already 0
- i := p.index + 4
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-4])
- x |= uint64(p.buf[i-3]) << 8
- x |= uint64(p.buf[i-2]) << 16
- x |= uint64(p.buf[i-1]) << 24
- return
-}
-
-// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
-// from the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
- return
-}
-
-// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
-// from the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
- return
-}
-
-// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
-// This is the format used for the bytes protocol buffer
-// type and for embedded messages.
-func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
- n, err := p.DecodeVarint()
- if err != nil {
- return nil, err
- }
-
- nb := int(n)
- if nb < 0 {
- return nil, fmt.Errorf("proto: bad byte length %d", nb)
- }
- end := p.index + nb
- if end < p.index || end > len(p.buf) {
- return nil, io.ErrUnexpectedEOF
- }
-
- if !alloc {
- // todo: check if can get more uses of alloc=false
- buf = p.buf[p.index:end]
- p.index += nb
- return
- }
-
- buf = make([]byte, nb)
- copy(buf, p.buf[p.index:])
- p.index += nb
- return
-}
-
-// DecodeStringBytes reads an encoded string from the Buffer.
-// This is the format used for the proto2 string type.
-func (p *Buffer) DecodeStringBytes() (s string, err error) {
- buf, err := p.DecodeRawBytes(false)
- if err != nil {
- return
- }
- return string(buf), nil
-}
-
-// Unmarshaler is the interface representing objects that can
-// unmarshal themselves. The argument points to data that may be
-// overwritten, so implementations should not keep references to the
-// buffer.
-// Unmarshal implementations should not clear the receiver.
-// Any unmarshaled data should be merged into the receiver.
-// Callers of Unmarshal that do not want to retain existing data
-// should Reset the receiver before calling Unmarshal.
-type Unmarshaler interface {
- Unmarshal([]byte) error
-}
-
-// newUnmarshaler is the interface representing objects that can
-// unmarshal themselves. The semantics are identical to Unmarshaler.
-//
-// This exists to support protoc-gen-go generated messages.
-// The proto package will stop type-asserting to this interface in the future.
-//
-// DO NOT DEPEND ON THIS.
-type newUnmarshaler interface {
- XXX_Unmarshal([]byte) error
-}
-
-// Unmarshal parses the protocol buffer representation in buf and places the
-// decoded result in pb. If the struct underlying pb does not match
-// the data in buf, the results can be unpredictable.
-//
-// Unmarshal resets pb before starting to unmarshal, so any
-// existing data in pb is always removed. Use UnmarshalMerge
-// to preserve and append to existing data.
-func Unmarshal(buf []byte, pb Message) error {
- pb.Reset()
- if u, ok := pb.(newUnmarshaler); ok {
- return u.XXX_Unmarshal(buf)
- }
- if u, ok := pb.(Unmarshaler); ok {
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(pb)
-}
-
-// UnmarshalMerge parses the protocol buffer representation in buf and
-// writes the decoded result to pb. If the struct underlying pb does not match
-// the data in buf, the results can be unpredictable.
-//
-// UnmarshalMerge merges into existing data in pb.
-// Most code should use Unmarshal instead.
-func UnmarshalMerge(buf []byte, pb Message) error {
- if u, ok := pb.(newUnmarshaler); ok {
- return u.XXX_Unmarshal(buf)
- }
- if u, ok := pb.(Unmarshaler); ok {
- // NOTE: The history of proto have unfortunately been inconsistent
- // whether Unmarshaler should or should not implicitly clear itself.
- // Some implementations do, most do not.
- // Thus, calling this here may or may not do what people want.
- //
- // See https://github.com/golang/protobuf/issues/424
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(pb)
-}
-
-// DecodeMessage reads a count-delimited message from the Buffer.
-func (p *Buffer) DecodeMessage(pb Message) error {
- enc, err := p.DecodeRawBytes(false)
- if err != nil {
- return err
- }
- return NewBuffer(enc).Unmarshal(pb)
-}
-
-// DecodeGroup reads a tag-delimited group from the Buffer.
-// StartGroup tag is already consumed. This function consumes
-// EndGroup tag.
-func (p *Buffer) DecodeGroup(pb Message) error {
- b := p.buf[p.index:]
- x, y := findEndGroup(b)
- if x < 0 {
- return io.ErrUnexpectedEOF
- }
- err := Unmarshal(b[:x], pb)
- p.index += y
- return err
-}
-
-// Unmarshal parses the protocol buffer representation in the
-// Buffer and places the decoded result in pb. If the struct
-// underlying pb does not match the data in the buffer, the results can be
-// unpredictable.
-//
-// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
-func (p *Buffer) Unmarshal(pb Message) error {
- // If the object can unmarshal itself, let it.
- if u, ok := pb.(newUnmarshaler); ok {
- err := u.XXX_Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
- if u, ok := pb.(Unmarshaler); ok {
- // NOTE: The history of proto have unfortunately been inconsistent
- // whether Unmarshaler should or should not implicitly clear itself.
- // Some implementations do, most do not.
- // Thus, calling this here may or may not do what people want.
- //
- // See https://github.com/golang/protobuf/issues/424
- err := u.Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
-
- // Slow workaround for messages that aren't Unmarshalers.
- // This includes some hand-coded .pb.go files and
- // bootstrap protos.
- // TODO: fix all of those and then add Unmarshal to
- // the Message interface. Then:
- // The cast above and code below can be deleted.
- // The old unmarshaler can be deleted.
- // Clients can call Unmarshal directly (can already do that, actually).
- var info InternalMessageInfo
- err := info.Unmarshal(pb, p.buf[p.index:])
- p.index = len(p.buf)
- return err
-}
diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go
deleted file mode 100644
index 949be3abd..000000000
--- a/vendor/github.com/golang/protobuf/proto/decode_test.go
+++ /dev/null
@@ -1,255 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// +build go1.7
-
-package proto_test
-
-import (
- "fmt"
- "testing"
-
- "github.com/golang/protobuf/proto"
- tpb "github.com/golang/protobuf/proto/proto3_proto"
-)
-
-var msgBlackhole = new(tpb.Message)
-
-// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and
-// 2 bytes long).
-func BenchmarkVarint32ArraySmall(b *testing.B) {
- for i := uint(1); i <= 10; i++ {
- dist := genInt32Dist([7]int{0, 3, 1}, 1< 0 {
+ m.SetUnknown(nil)
}
}
diff --git a/vendor/github.com/golang/protobuf/proto/discard_test.go b/vendor/github.com/golang/protobuf/proto/discard_test.go
index a2ff5509d..f850d9dec 100644
--- a/vendor/github.com/golang/protobuf/proto/discard_test.go
+++ b/vendor/github.com/golang/protobuf/proto/discard_test.go
@@ -1,33 +1,6 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2017 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package proto_test
@@ -35,11 +8,16 @@ import (
"testing"
"github.com/golang/protobuf/proto"
+ "google.golang.org/protobuf/testing/protopack"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/test_proto"
+ pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
+ pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
)
+var rawFields = protopack.Message{
+ protopack.Tag{5, protopack.Fixed32Type}, protopack.Uint32(4041331395),
+}.Marshal()
+
func TestDiscardUnknown(t *testing.T) {
tests := []struct {
desc string
@@ -49,104 +27,85 @@ func TestDiscardUnknown(t *testing.T) {
in: nil, want: nil, // Should not panic
}, {
desc: "NilPtr",
- in: (*proto3pb.Message)(nil), want: (*proto3pb.Message)(nil), // Should not panic
+ in: (*pb3.Message)(nil), want: (*pb3.Message)(nil), // Should not panic
}, {
desc: "Nested",
- in: &proto3pb.Message{
+ in: &pb3.Message{
Name: "Aaron",
- Nested: &proto3pb.Nested{Cute: true, XXX_unrecognized: []byte("blah")},
- XXX_unrecognized: []byte("blah"),
+ Nested: &pb3.Nested{Cute: true, XXX_unrecognized: []byte(rawFields)},
+ XXX_unrecognized: []byte(rawFields),
},
- want: &proto3pb.Message{
+ want: &pb3.Message{
Name: "Aaron",
- Nested: &proto3pb.Nested{Cute: true},
+ Nested: &pb3.Nested{Cute: true},
},
}, {
desc: "Slice",
- in: &proto3pb.Message{
+ in: &pb3.Message{
Name: "Aaron",
- Children: []*proto3pb.Message{
- {Name: "Sarah", XXX_unrecognized: []byte("blah")},
- {Name: "Abraham", XXX_unrecognized: []byte("blah")},
+ Children: []*pb3.Message{
+ {Name: "Sarah", XXX_unrecognized: []byte(rawFields)},
+ {Name: "Abraham", XXX_unrecognized: []byte(rawFields)},
},
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
},
- want: &proto3pb.Message{
+ want: &pb3.Message{
Name: "Aaron",
- Children: []*proto3pb.Message{
+ Children: []*pb3.Message{
{Name: "Sarah"},
{Name: "Abraham"},
},
},
}, {
desc: "OneOf",
- in: &pb.Communique{
- Union: &pb.Communique_Msg{&pb.Strings{
+ in: &pb2.Communique{
+ Union: &pb2.Communique_Msg{&pb2.Strings{
StringField: proto.String("123"),
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
}},
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
},
- want: &pb.Communique{
- Union: &pb.Communique_Msg{&pb.Strings{StringField: proto.String("123")}},
+ want: &pb2.Communique{
+ Union: &pb2.Communique_Msg{&pb2.Strings{StringField: proto.String("123")}},
},
}, {
desc: "Map",
- in: &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4002: &pb.FloatingPoint{
+ in: &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{
+ 0x4002: &pb2.FloatingPoint{
Exact: proto.Bool(true),
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
},
}},
- want: &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4002: &pb.FloatingPoint{Exact: proto.Bool(true)},
+ want: &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{
+ 0x4002: &pb2.FloatingPoint{Exact: proto.Bool(true)},
}},
}, {
desc: "Extension",
in: func() proto.Message {
- m := &pb.MyMessage{
+ m := &pb2.MyMessage{
Count: proto.Int32(42),
- Somegroup: &pb.MyMessage_SomeGroup{
+ Somegroup: &pb2.MyMessage_SomeGroup{
GroupField: proto.Int32(6),
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
},
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
}
- proto.SetExtension(m, pb.E_Ext_More, &pb.Ext{
+ proto.SetExtension(m, pb2.E_Ext_More, &pb2.Ext{
Data: proto.String("extension"),
- XXX_unrecognized: []byte("blah"),
+ XXX_unrecognized: []byte(rawFields),
})
return m
}(),
want: func() proto.Message {
- m := &pb.MyMessage{
+ m := &pb2.MyMessage{
Count: proto.Int32(42),
- Somegroup: &pb.MyMessage_SomeGroup{GroupField: proto.Int32(6)},
+ Somegroup: &pb2.MyMessage_SomeGroup{GroupField: proto.Int32(6)},
}
- proto.SetExtension(m, pb.E_Ext_More, &pb.Ext{Data: proto.String("extension")})
+ proto.SetExtension(m, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("extension")})
return m
}(),
}}
- // Test the legacy code path.
- for _, tt := range tests {
- // Clone the input so that we don't alter the original.
- in := tt.in
- if in != nil {
- in = proto.Clone(tt.in)
- }
-
- var m LegacyMessage
- m.Message, _ = in.(*proto3pb.Message)
- m.Communique, _ = in.(*pb.Communique)
- m.MessageWithMap, _ = in.(*pb.MessageWithMap)
- m.MyMessage, _ = in.(*pb.MyMessage)
- proto.DiscardUnknown(&m)
- if !proto.Equal(in, tt.want) {
- t.Errorf("test %s/Legacy, expected unknown fields to be discarded\ngot %v\nwant %v", tt.desc, in, tt.want)
- }
- }
-
for _, tt := range tests {
proto.DiscardUnknown(tt.in)
if !proto.Equal(tt.in, tt.want) {
@@ -154,17 +113,3 @@ func TestDiscardUnknown(t *testing.T) {
}
}
}
-
-// LegacyMessage is a proto.Message that has several nested messages.
-// This does not have the XXX_DiscardUnknown method and so forces DiscardUnknown
-// to use the legacy fallback logic.
-type LegacyMessage struct {
- Message *proto3pb.Message
- Communique *pb.Communique
- MessageWithMap *pb.MessageWithMap
- MyMessage *pb.MyMessage
-}
-
-func (m *LegacyMessage) Reset() { *m = LegacyMessage{} }
-func (m *LegacyMessage) String() string { return proto.CompactTextString(m) }
-func (*LegacyMessage) ProtoMessage() {}
diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go
deleted file mode 100644
index 4c35d3373..000000000
--- a/vendor/github.com/golang/protobuf/proto/encode.go
+++ /dev/null
@@ -1,218 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-/*
- * Routines for encoding data into the wire format for protocol buffers.
- */
-
-import (
- "errors"
- "fmt"
- "reflect"
-)
-
-// RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
-// Marshal reports this when a required field is not initialized.
-// Unmarshal reports this when a required field is missing from the wire data.
-type RequiredNotSetError struct {
- field string
-}
-
-func (e *RequiredNotSetError) Error() string {
- if e.field == "" {
- return fmt.Sprintf("proto: required field not set")
- }
- return fmt.Sprintf("proto: required field %q not set", e.field)
-}
-
-var (
- // errRepeatedHasNil is the error returned if Marshal is called with
- // a struct with a repeated field containing a nil element.
- errRepeatedHasNil = errors.New("proto: repeated field has nil element")
-
- // errOneofHasNil is the error returned if Marshal is called with
- // a struct with a oneof field containing a nil element.
- errOneofHasNil = errors.New("proto: oneof field has nil value")
-
- // ErrNil is the error returned if Marshal is called with nil.
- ErrNil = errors.New("proto: Marshal called with nil")
-
- // ErrTooLarge is the error returned if Marshal is called with a
- // message that encodes to >2GB.
- ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
-)
-
-// The fundamental encoders that put bytes on the wire.
-// Those that take integer types all accept uint64 and are
-// therefore of type valueEncoder.
-
-const maxVarintBytes = 10 // maximum length of a varint
-
-// EncodeVarint returns the varint encoding of x.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-// Not used by the package itself, but helpful to clients
-// wishing to use the same encoding.
-func EncodeVarint(x uint64) []byte {
- var buf [maxVarintBytes]byte
- var n int
- for n = 0; x > 127; n++ {
- buf[n] = 0x80 | uint8(x&0x7F)
- x >>= 7
- }
- buf[n] = uint8(x)
- n++
- return buf[0:n]
-}
-
-// EncodeVarint writes a varint-encoded integer to the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) EncodeVarint(x uint64) error {
- for x >= 1<<7 {
- p.buf = append(p.buf, uint8(x&0x7f|0x80))
- x >>= 7
- }
- p.buf = append(p.buf, uint8(x))
- return nil
-}
-
-// SizeVarint returns the varint encoding size of an integer.
-func SizeVarint(x uint64) int {
- switch {
- case x < 1<<7:
- return 1
- case x < 1<<14:
- return 2
- case x < 1<<21:
- return 3
- case x < 1<<28:
- return 4
- case x < 1<<35:
- return 5
- case x < 1<<42:
- return 6
- case x < 1<<49:
- return 7
- case x < 1<<56:
- return 8
- case x < 1<<63:
- return 9
- }
- return 10
-}
-
-// EncodeFixed64 writes a 64-bit integer to the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) EncodeFixed64(x uint64) error {
- p.buf = append(p.buf,
- uint8(x),
- uint8(x>>8),
- uint8(x>>16),
- uint8(x>>24),
- uint8(x>>32),
- uint8(x>>40),
- uint8(x>>48),
- uint8(x>>56))
- return nil
-}
-
-// EncodeFixed32 writes a 32-bit integer to the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) EncodeFixed32(x uint64) error {
- p.buf = append(p.buf,
- uint8(x),
- uint8(x>>8),
- uint8(x>>16),
- uint8(x>>24))
- return nil
-}
-
-// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
-// to the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) EncodeZigzag64(x uint64) error {
- // use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-
-// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
-// to the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) EncodeZigzag32(x uint64) error {
- // use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
-}
-
-// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
-// This is the format used for the bytes protocol buffer
-// type and for embedded messages.
-func (p *Buffer) EncodeRawBytes(b []byte) error {
- p.EncodeVarint(uint64(len(b)))
- p.buf = append(p.buf, b...)
- return nil
-}
-
-// EncodeStringBytes writes an encoded string to the Buffer.
-// This is the format used for the proto2 string type.
-func (p *Buffer) EncodeStringBytes(s string) error {
- p.EncodeVarint(uint64(len(s)))
- p.buf = append(p.buf, s...)
- return nil
-}
-
-// Marshaler is the interface representing objects that can marshal themselves.
-type Marshaler interface {
- Marshal() ([]byte, error)
-}
-
-// EncodeMessage writes the protocol buffer to the Buffer,
-// prefixed by a varint-encoded length.
-func (p *Buffer) EncodeMessage(pb Message) error {
- siz := Size(pb)
- p.EncodeVarint(uint64(siz))
- return p.Marshal(pb)
-}
-
-// All protocol buffer fields are nillable, but be careful.
-func isNil(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
- return v.IsNil()
- }
- return false
-}
diff --git a/vendor/github.com/golang/protobuf/proto/encode_test.go b/vendor/github.com/golang/protobuf/proto/encode_test.go
deleted file mode 100644
index a7209475f..000000000
--- a/vendor/github.com/golang/protobuf/proto/encode_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// +build go1.7
-
-package proto_test
-
-import (
- "strconv"
- "testing"
-
- "github.com/golang/protobuf/proto"
- tpb "github.com/golang/protobuf/proto/proto3_proto"
- "github.com/golang/protobuf/ptypes"
-)
-
-var (
- blackhole []byte
-)
-
-// BenchmarkAny creates increasingly large arbitrary Any messages. The type is always the
-// same.
-func BenchmarkAny(b *testing.B) {
- data := make([]byte, 1<<20)
- quantum := 1 << 10
- for i := uint(0); i <= 10; i++ {
- b.Run(strconv.Itoa(quantum< 0; {
+ num, _, n := protowire.ConsumeField(b)
+ has = int32(num) == xt.Field
+ b = b[n:]
}
- return e.p.extensionMap, &e.p.mu
-}
-
-// ExtensionDesc represents an extension specification.
-// Used in generated code from the protocol compiler.
-type ExtensionDesc struct {
- ExtendedType Message // nil pointer to the type that is being extended
- ExtensionType interface{} // nil pointer to the extension type
- Field int32 // field number
- Name string // fully-qualified name of extension, for text formatting
- Tag string // protobuf tag style
- Filename string // name of the file in which the extension is defined
-}
-
-func (ed *ExtensionDesc) repeated() bool {
- t := reflect.TypeOf(ed.ExtensionType)
- return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
-}
-
-// Extension represents an extension in a message.
-type Extension struct {
- // When an extension is stored in a message using SetExtension
- // only desc and value are set. When the message is marshaled
- // enc will be set to the encoded form of the message.
- //
- // When a message is unmarshaled and contains extensions, each
- // extension will have only enc set. When such an extension is
- // accessed using GetExtension (or GetExtensions) desc and value
- // will be set.
- desc *ExtensionDesc
- value interface{}
- enc []byte
+ return has
}
-// SetRawExtension is for testing only.
-func SetRawExtension(base Message, id int32, b []byte) {
- epb, err := extendable(base)
- if err != nil {
+// ClearExtension removes the extension field from m
+// either as an explicitly populated field or as an unknown field.
+func ClearExtension(m Message, xt *ExtensionDesc) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() {
return
}
- extmap := epb.extensionsWrite()
- extmap[id] = Extension{enc: b}
-}
-// isExtensionField returns true iff the given field number is in an extension range.
-func isExtensionField(pb extendableProto, field int32) bool {
- for _, er := range pb.ExtensionRangeArray() {
- if er.Start <= field && field <= er.End {
+ xtd := xt.TypeDescriptor()
+ if isValidExtension(mr.Descriptor(), xtd) {
+ mr.Clear(xtd)
+ } else {
+ mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
+ if int32(fd.Number()) == xt.Field {
+ mr.Clear(fd)
+ return false
+ }
return true
- }
- }
- return false
-}
-
-// checkExtensionTypes checks that the given extension is valid for pb.
-func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
- var pbi interface{} = pb
- // Check the extended type.
- if ea, ok := pbi.(extensionAdapter); ok {
- pbi = ea.extendableProtoV1
- }
- if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
- return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
- }
- // Check the range.
- if !isExtensionField(pb, extension.Field) {
- return errors.New("proto: bad extension number; not in declared ranges")
- }
- return nil
-}
-
-// extPropKey is sufficient to uniquely identify an extension.
-type extPropKey struct {
- base reflect.Type
- field int32
-}
-
-var extProp = struct {
- sync.RWMutex
- m map[extPropKey]*Properties
-}{
- m: make(map[extPropKey]*Properties),
-}
-
-func extensionProperties(ed *ExtensionDesc) *Properties {
- key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
-
- extProp.RLock()
- if prop, ok := extProp.m[key]; ok {
- extProp.RUnlock()
- return prop
- }
- extProp.RUnlock()
-
- extProp.Lock()
- defer extProp.Unlock()
- // Check again.
- if prop, ok := extProp.m[key]; ok {
- return prop
- }
-
- prop := new(Properties)
- prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
- extProp.m[key] = prop
- return prop
-}
-
-// HasExtension returns whether the given extension is present in pb.
-func HasExtension(pb Message, extension *ExtensionDesc) bool {
- // TODO: Check types, field numbers, etc.?
- epb, err := extendable(pb)
- if err != nil {
- return false
- }
- extmap, mu := epb.extensionsRead()
- if extmap == nil {
- return false
+ })
}
- mu.Lock()
- _, ok := extmap[extension.Field]
- mu.Unlock()
- return ok
+ clearUnknown(mr, fieldNum(xt.Field))
}
-// ClearExtension removes the given extension from pb.
-func ClearExtension(pb Message, extension *ExtensionDesc) {
- epb, err := extendable(pb)
- if err != nil {
+// ClearAllExtensions clears all extensions from m.
+// This includes populated fields and unknown fields in the extension range.
+func ClearAllExtensions(m Message) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() {
return
}
- // TODO: Check types, field numbers, etc.?
- extmap := epb.extensionsWrite()
- delete(extmap, extension.Field)
+
+ mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
+ if fd.IsExtension() {
+ mr.Clear(fd)
+ }
+ return true
+ })
+ clearUnknown(mr, mr.Descriptor().ExtensionRanges())
}
-// GetExtension retrieves a proto2 extended field from pb.
+// GetExtension retrieves a proto2 extended field from m.
//
// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
// then GetExtension parses the encoded field and returns a Go value of the specified type.
// If the field is not present, then the default value is returned (if one is specified),
// otherwise ErrMissingExtension is reported.
//
-// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
-// then GetExtension returns the raw encoded bytes of the field extension.
-func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
-
- if extension.ExtendedType != nil {
- // can only check type if this is a complete descriptor
- if err := checkExtensionTypes(epb, extension); err != nil {
- return nil, err
+// If the descriptor is type incomplete (i.e., ExtensionDesc.ExtensionType is nil),
+// then GetExtension returns the raw encoded bytes for the extension field.
+func GetExtension(m Message, xt *ExtensionDesc) (interface{}, error) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 {
+ return nil, errNotExtendable
+ }
+
+ // Retrieve the unknown fields for this extension field.
+ var bo protoreflect.RawFields
+ for bi := mr.GetUnknown(); len(bi) > 0; {
+ num, _, n := protowire.ConsumeField(bi)
+ if int32(num) == xt.Field {
+ bo = append(bo, bi[:n]...)
}
+ bi = bi[n:]
}
- emap, mu := epb.extensionsRead()
- if emap == nil {
- return defaultExtensionValue(extension)
- }
- mu.Lock()
- defer mu.Unlock()
- e, ok := emap[extension.Field]
- if !ok {
- // defaultExtensionValue returns the default value or
- // ErrMissingExtension if there is no default.
- return defaultExtensionValue(extension)
+ // For type incomplete descriptors, only retrieve the unknown fields.
+ if xt.ExtensionType == nil {
+ return []byte(bo), nil
}
- if e.value != nil {
- // Already decoded. Check the descriptor, though.
- if e.desc != extension {
- // This shouldn't happen. If it does, it means that
- // GetExtension was called twice with two different
- // descriptors with the same field number.
- return nil, errors.New("proto: descriptor conflict")
+ // If the extension field only exists as unknown fields, unmarshal it.
+ // This is rarely done since proto.Unmarshal eagerly unmarshals extensions.
+ xtd := xt.TypeDescriptor()
+ if !isValidExtension(mr.Descriptor(), xtd) {
+ return nil, fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m)
+ }
+ if !mr.Has(xtd) && len(bo) > 0 {
+ m2 := mr.New()
+ if err := (proto.UnmarshalOptions{
+ Resolver: extensionResolver{xt},
+ }.Unmarshal(bo, m2.Interface())); err != nil {
+ return nil, err
+ }
+ if m2.Has(xtd) {
+ mr.Set(xtd, m2.Get(xtd))
+ clearUnknown(mr, fieldNum(xt.Field))
}
- return e.value, nil
}
- if extension.ExtensionType == nil {
- // incomplete descriptor
- return e.enc, nil
+ // Check whether the message has the extension field set or a default.
+ var pv protoreflect.Value
+ switch {
+ case mr.Has(xtd):
+ pv = mr.Get(xtd)
+ case xtd.HasDefault():
+ pv = xtd.Default()
+ default:
+ return nil, ErrMissingExtension
}
- v, err := decodeExtension(e.enc, extension)
- if err != nil {
- return nil, err
+ v := xt.InterfaceOf(pv)
+ rv := reflect.ValueOf(v)
+ if isScalarKind(rv.Kind()) {
+ rv2 := reflect.New(rv.Type())
+ rv2.Elem().Set(rv)
+ v = rv2.Interface()
}
-
- // Remember the decoded version and drop the encoded version.
- // That way it is safe to mutate what we return.
- e.value = v
- e.desc = extension
- e.enc = nil
- emap[extension.Field] = e
- return e.value, nil
+ return v, nil
}
-// defaultExtensionValue returns the default value for extension.
-// If no default for an extension is defined ErrMissingExtension is returned.
-func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
- if extension.ExtensionType == nil {
- // incomplete descriptor, so no default
- return nil, ErrMissingExtension
- }
-
- t := reflect.TypeOf(extension.ExtensionType)
- props := extensionProperties(extension)
+// extensionResolver is a custom extension resolver that stores a single
+// extension type that takes precedence over the global registry.
+type extensionResolver struct{ xt protoreflect.ExtensionType }
- sf, _, err := fieldDefault(t, props)
- if err != nil {
- return nil, err
+func (r extensionResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
+ if xtd := r.xt.TypeDescriptor(); xtd.FullName() == field {
+ return r.xt, nil
}
+ return protoregistry.GlobalTypes.FindExtensionByName(field)
+}
- if sf == nil || sf.value == nil {
- // There is no default value.
- return nil, ErrMissingExtension
+func (r extensionResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
+ if xtd := r.xt.TypeDescriptor(); xtd.ContainingMessage().FullName() == message && xtd.Number() == field {
+ return r.xt, nil
}
+ return protoregistry.GlobalTypes.FindExtensionByNumber(message, field)
+}
- if t.Kind() != reflect.Ptr {
- // We do not need to return a Ptr, we can directly return sf.value.
- return sf.value, nil
+// GetExtensions returns a list of the extensions values present in m,
+// corresponding with the provided list of extension descriptors, xts.
+// If an extension is missing in m, the corresponding value is nil.
+func GetExtensions(m Message, xts []*ExtensionDesc) ([]interface{}, error) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() {
+ return nil, errNotExtendable
}
- // We need to return an interface{} that is a pointer to sf.value.
- value := reflect.New(t).Elem()
- value.Set(reflect.New(value.Type().Elem()))
- if sf.kind == reflect.Int32 {
- // We may have an int32 or an enum, but the underlying data is int32.
- // Since we can't set an int32 into a non int32 reflect.value directly
- // set it as a int32.
- value.Elem().SetInt(int64(sf.value.(int32)))
- } else {
- value.Elem().Set(reflect.ValueOf(sf.value))
+ vs := make([]interface{}, len(xts))
+ for i, xt := range xts {
+ v, err := GetExtension(m, xt)
+ if err != nil {
+ if err == ErrMissingExtension {
+ continue
+ }
+ return vs, err
+ }
+ vs[i] = v
}
- return value.Interface(), nil
+ return vs, nil
}
-// decodeExtension decodes an extension encoded in b.
-func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
- t := reflect.TypeOf(extension.ExtensionType)
- unmarshal := typeUnmarshaler(t, extension.Tag)
-
- // t is a pointer to a struct, pointer to basic type or a slice.
- // Allocate space to store the pointer/slice.
- value := reflect.New(t).Elem()
+// SetExtension sets an extension field in m to the provided value.
+func SetExtension(m Message, xt *ExtensionDesc, v interface{}) error {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 {
+ return errNotExtendable
+ }
- var err error
- for {
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
+ rv := reflect.ValueOf(v)
+ if reflect.TypeOf(v) != reflect.TypeOf(xt.ExtensionType) {
+ return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", v, xt.ExtensionType)
+ }
+ if rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ return fmt.Errorf("proto: SetExtension called with nil value of type %T", v)
}
- b = b[n:]
- wire := int(x) & 7
-
- b, err = unmarshal(b, valToPointer(value.Addr()), wire)
- if err != nil {
- return nil, err
+ if isScalarKind(rv.Elem().Kind()) {
+ v = rv.Elem().Interface()
}
+ }
- if len(b) == 0 {
- break
- }
+ xtd := xt.TypeDescriptor()
+ if !isValidExtension(mr.Descriptor(), xtd) {
+ return fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m)
}
- return value.Interface(), nil
+ mr.Set(xtd, xt.ValueOf(v))
+ clearUnknown(mr, fieldNum(xt.Field))
+ return nil
}
-// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
-// The returned slice has the same length as es; missing extensions will appear as nil elements.
-func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
+// SetRawExtension inserts b into the unknown fields of m.
+//
+// Deprecated: Use Message.ProtoReflect.SetUnknown instead.
+func SetRawExtension(m Message, fnum int32, b []byte) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() {
+ return
}
- extensions = make([]interface{}, len(es))
- for i, e := range es {
- extensions[i], err = GetExtension(epb, e)
- if err == ErrMissingExtension {
- err = nil
- }
- if err != nil {
- return
+
+ // Verify that the raw field is valid.
+ for b0 := b; len(b0) > 0; {
+ num, _, n := protowire.ConsumeField(b0)
+ if int32(num) != fnum {
+ panic(fmt.Sprintf("mismatching field number: got %d, want %d", num, fnum))
}
+ b0 = b0[n:]
}
- return
-}
-// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
-// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
-// just the Field field, which defines the extension's field number.
-func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
- registeredExtensions := RegisteredExtensions(pb)
+ ClearExtension(m, &ExtensionDesc{Field: fnum})
+ mr.SetUnknown(append(mr.GetUnknown(), b...))
+}
- emap, mu := epb.extensionsRead()
- if emap == nil {
- return nil, nil
- }
- mu.Lock()
- defer mu.Unlock()
- extensions := make([]*ExtensionDesc, 0, len(emap))
- for extid, e := range emap {
- desc := e.desc
- if desc == nil {
- desc = registeredExtensions[extid]
- if desc == nil {
- desc = &ExtensionDesc{Field: extid}
+// ExtensionDescs returns a list of extension descriptors found in m,
+// containing descriptors for both populated extension fields in m and
+// also unknown fields of m that are in the extension range.
+// For the later case, an type incomplete descriptor is provided where only
+// the ExtensionDesc.Field field is populated.
+// The order of the extension descriptors is undefined.
+func ExtensionDescs(m Message) ([]*ExtensionDesc, error) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 {
+ return nil, errNotExtendable
+ }
+
+ // Collect a set of known extension descriptors.
+ extDescs := make(map[protoreflect.FieldNumber]*ExtensionDesc)
+ mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
+ if fd.IsExtension() {
+ xt := fd.(protoreflect.ExtensionTypeDescriptor)
+ if xd, ok := xt.Type().(*ExtensionDesc); ok {
+ extDescs[fd.Number()] = xd
}
}
-
- extensions = append(extensions, desc)
+ return true
+ })
+
+ // Collect a set of unknown extension descriptors.
+ extRanges := mr.Descriptor().ExtensionRanges()
+ for b := mr.GetUnknown(); len(b) > 0; {
+ num, _, n := protowire.ConsumeField(b)
+ if extRanges.Has(num) && extDescs[num] == nil {
+ extDescs[num] = nil
+ }
+ b = b[n:]
}
- return extensions, nil
-}
-// SetExtension sets the specified extension of pb to the specified value.
-func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
- epb, err := extendable(pb)
- if err != nil {
- return err
- }
- if err := checkExtensionTypes(epb, extension); err != nil {
- return err
- }
- typ := reflect.TypeOf(extension.ExtensionType)
- if typ != reflect.TypeOf(value) {
- return errors.New("proto: bad extension value type")
- }
- // nil extension values need to be caught early, because the
- // encoder can't distinguish an ErrNil due to a nil extension
- // from an ErrNil due to a missing field. Extensions are
- // always optional, so the encoder would just swallow the error
- // and drop all the extensions from the encoded message.
- if reflect.ValueOf(value).IsNil() {
- return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
+ // Transpose the set of descriptors into a list.
+ var xts []*ExtensionDesc
+ for num, xt := range extDescs {
+ if xt == nil {
+ xt = &ExtensionDesc{Field: int32(num)}
+ }
+ xts = append(xts, xt)
}
+ return xts, nil
+}
- extmap := epb.extensionsWrite()
- extmap[extension.Field] = Extension{desc: extension, value: value}
- return nil
+// isValidExtension reports whether xtd is a valid extension descriptor for md.
+func isValidExtension(md protoreflect.MessageDescriptor, xtd protoreflect.ExtensionTypeDescriptor) bool {
+ return xtd.ContainingMessage() == md && md.ExtensionRanges().Has(xtd.Number())
}
-// ClearAllExtensions clears all extensions from pb.
-func ClearAllExtensions(pb Message) {
- epb, err := extendable(pb)
- if err != nil {
- return
- }
- m := epb.extensionsWrite()
- for k := range m {
- delete(m, k)
+// isScalarKind reports whether k is a protobuf scalar kind (except bytes).
+// This function exists for historical reasons since the representation of
+// scalars differs between v1 and v2, where v1 uses *T and v2 uses T.
+func isScalarKind(k reflect.Kind) bool {
+ switch k {
+ case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
+ return true
+ default:
+ return false
}
}
-// A global registry of extensions.
-// The generated code will register the generated descriptors by calling RegisterExtension.
-
-var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
-
-// RegisterExtension is called from the generated code.
-func RegisterExtension(desc *ExtensionDesc) {
- st := reflect.TypeOf(desc.ExtendedType).Elem()
- m := extensionMaps[st]
- if m == nil {
- m = make(map[int32]*ExtensionDesc)
- extensionMaps[st] = m
+// clearUnknown removes unknown fields from m where remover.Has reports true.
+func clearUnknown(m protoreflect.Message, remover interface {
+ Has(protoreflect.FieldNumber) bool
+}) {
+ var bo protoreflect.RawFields
+ for bi := m.GetUnknown(); len(bi) > 0; {
+ num, _, n := protowire.ConsumeField(bi)
+ if !remover.Has(num) {
+ bo = append(bo, bi[:n]...)
+ }
+ bi = bi[n:]
}
- if _, ok := m[desc.Field]; ok {
- panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
+ if bi := m.GetUnknown(); len(bi) != len(bo) {
+ m.SetUnknown(bo)
}
- m[desc.Field] = desc
}
-// RegisteredExtensions returns a map of the registered extensions of a
-// protocol buffer struct, indexed by the extension number.
-// The argument pb should be a nil pointer to the struct type.
-func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
- return extensionMaps[reflect.TypeOf(pb).Elem()]
+type fieldNum protoreflect.FieldNumber
+
+func (n1 fieldNum) Has(n2 protoreflect.FieldNumber) bool {
+ return protoreflect.FieldNumber(n1) == n2
}
diff --git a/vendor/github.com/golang/protobuf/proto/extensions_test.go b/vendor/github.com/golang/protobuf/proto/extensions_test.go
index dc69fe971..597815942 100644
--- a/vendor/github.com/golang/protobuf/proto/extensions_test.go
+++ b/vendor/github.com/golang/protobuf/proto/extensions_test.go
@@ -1,59 +1,32 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package proto_test
import (
"bytes"
"fmt"
- "io"
"reflect"
"sort"
"strings"
+ "sync"
"testing"
"github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/proto/test_proto"
- "golang.org/x/sync/errgroup"
+
+ pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
)
func TestGetExtensionsWithMissingExtensions(t *testing.T) {
- msg := &pb.MyMessage{}
- ext1 := &pb.Ext{}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil {
+ msg := &pb2.MyMessage{}
+ ext1 := &pb2.Ext{}
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, ext1); err != nil {
t.Fatalf("Could not set ext1: %s", err)
}
exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{
- pb.E_Ext_More,
- pb.E_Ext_Text,
+ pb2.E_Ext_More,
+ pb2.E_Ext_Text,
})
if err != nil {
t.Fatalf("GetExtensions() failed: %s", err)
@@ -66,21 +39,10 @@ func TestGetExtensionsWithMissingExtensions(t *testing.T) {
}
}
-func TestGetExtensionWithEmptyBuffer(t *testing.T) {
- // Make sure that GetExtension returns an error if its
- // undecoded buffer is empty.
- msg := &pb.MyMessage{}
- proto.SetRawExtension(msg, pb.E_Ext_More.Field, []byte{})
- _, err := proto.GetExtension(msg, pb.E_Ext_More)
- if want := io.ErrUnexpectedEOF; err != want {
- t.Errorf("unexpected error in GetExtension from empty buffer: got %v, want %v", err, want)
- }
-}
-
func TestGetExtensionForIncompleteDesc(t *testing.T) {
- msg := &pb.MyMessage{Count: proto.Int32(0)}
+ msg := &pb2.MyMessage{Count: proto.Int32(0)}
extdesc1 := &proto.ExtensionDesc{
- ExtendedType: (*pb.MyMessage)(nil),
+ ExtendedType: (*pb2.MyMessage)(nil),
ExtensionType: (*bool)(nil),
Field: 123456789,
Name: "a.b",
@@ -91,7 +53,7 @@ func TestGetExtensionForIncompleteDesc(t *testing.T) {
t.Fatalf("Could not set ext1: %s", err)
}
extdesc2 := &proto.ExtensionDesc{
- ExtendedType: (*pb.MyMessage)(nil),
+ ExtendedType: (*pb2.MyMessage)(nil),
ExtensionType: ([]byte)(nil),
Field: 123456790,
Name: "a.c",
@@ -102,13 +64,13 @@ func TestGetExtensionForIncompleteDesc(t *testing.T) {
t.Fatalf("Could not set ext2: %s", err)
}
extdesc3 := &proto.ExtensionDesc{
- ExtendedType: (*pb.MyMessage)(nil),
- ExtensionType: (*pb.Ext)(nil),
+ ExtendedType: (*pb2.MyMessage)(nil),
+ ExtensionType: (*pb2.Ext)(nil),
Field: 123456791,
Name: "a.d",
Tag: "bytes,123456791,opt",
}
- ext3 := &pb.Ext{Data: proto.String("foo")}
+ ext3 := &pb2.Ext{Data: proto.String("foo")}
if err := proto.SetExtension(msg, extdesc3, ext3); err != nil {
t.Fatalf("Could not set ext3: %s", err)
}
@@ -167,18 +129,18 @@ func TestGetExtensionForIncompleteDesc(t *testing.T) {
}
func TestExtensionDescsWithUnregisteredExtensions(t *testing.T) {
- msg := &pb.MyMessage{Count: proto.Int32(0)}
- extdesc1 := pb.E_Ext_More
+ msg := &pb2.MyMessage{Count: proto.Int32(0)}
+ extdesc1 := pb2.E_Ext_More
if descs, err := proto.ExtensionDescs(msg); len(descs) != 0 || err != nil {
t.Errorf("proto.ExtensionDescs: got %d descs, error %v; want 0, nil", len(descs), err)
}
- ext1 := &pb.Ext{}
+ ext1 := &pb2.Ext{}
if err := proto.SetExtension(msg, extdesc1, ext1); err != nil {
t.Fatalf("Could not set ext1: %s", err)
}
extdesc2 := &proto.ExtensionDesc{
- ExtendedType: (*pb.MyMessage)(nil),
+ ExtendedType: (*pb2.MyMessage)(nil),
ExtensionType: (*bool)(nil),
Field: 123456789,
Name: "a.b",
@@ -219,20 +181,20 @@ func sortExtDescs(s []*proto.ExtensionDesc) {
}
func TestGetExtensionStability(t *testing.T) {
- check := func(m *pb.MyMessage) bool {
- ext1, err := proto.GetExtension(m, pb.E_Ext_More)
+ check := func(m *pb2.MyMessage) bool {
+ ext1, err := proto.GetExtension(m, pb2.E_Ext_More)
if err != nil {
t.Fatalf("GetExtension() failed: %s", err)
}
- ext2, err := proto.GetExtension(m, pb.E_Ext_More)
+ ext2, err := proto.GetExtension(m, pb2.E_Ext_More)
if err != nil {
t.Fatalf("GetExtension() failed: %s", err)
}
return ext1 == ext2
}
- msg := &pb.MyMessage{Count: proto.Int32(4)}
- ext0 := &pb.Ext{}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil {
+ msg := &pb2.MyMessage{Count: proto.Int32(4)}
+ ext0 := &pb2.Ext{}
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, ext0); err != nil {
t.Fatalf("Could not set ext1: %s", ext0)
}
if !check(msg) {
@@ -242,7 +204,7 @@ func TestGetExtensionStability(t *testing.T) {
if err != nil {
t.Fatalf("Marshal() failed: %s", err)
}
- msg1 := &pb.MyMessage{}
+ msg1 := &pb2.MyMessage{}
err = proto.Unmarshal(bb, msg1)
if err != nil {
t.Fatalf("Unmarshal() failed: %s", err)
@@ -263,7 +225,7 @@ func TestGetExtensionDefaults(t *testing.T) {
var setBool2 = false
var setString = "Goodnight string"
var setBytes = []byte("Goodnight bytes")
- var setEnum = pb.DefaultsMessage_TWO
+ var setEnum = pb2.DefaultsMessage_TWO
type testcase struct {
ext *proto.ExtensionDesc // Extension we are testing.
@@ -271,83 +233,89 @@ func TestGetExtensionDefaults(t *testing.T) {
def interface{} // Expected value of extension after ClearExtension().
}
tests := []testcase{
- {pb.E_NoDefaultDouble, setFloat64, nil},
- {pb.E_NoDefaultFloat, setFloat32, nil},
- {pb.E_NoDefaultInt32, setInt32, nil},
- {pb.E_NoDefaultInt64, setInt64, nil},
- {pb.E_NoDefaultUint32, setUint32, nil},
- {pb.E_NoDefaultUint64, setUint64, nil},
- {pb.E_NoDefaultSint32, setInt32, nil},
- {pb.E_NoDefaultSint64, setInt64, nil},
- {pb.E_NoDefaultFixed32, setUint32, nil},
- {pb.E_NoDefaultFixed64, setUint64, nil},
- {pb.E_NoDefaultSfixed32, setInt32, nil},
- {pb.E_NoDefaultSfixed64, setInt64, nil},
- {pb.E_NoDefaultBool, setBool, nil},
- {pb.E_NoDefaultBool, setBool2, nil},
- {pb.E_NoDefaultString, setString, nil},
- {pb.E_NoDefaultBytes, setBytes, nil},
- {pb.E_NoDefaultEnum, setEnum, nil},
- {pb.E_DefaultDouble, setFloat64, float64(3.1415)},
- {pb.E_DefaultFloat, setFloat32, float32(3.14)},
- {pb.E_DefaultInt32, setInt32, int32(42)},
- {pb.E_DefaultInt64, setInt64, int64(43)},
- {pb.E_DefaultUint32, setUint32, uint32(44)},
- {pb.E_DefaultUint64, setUint64, uint64(45)},
- {pb.E_DefaultSint32, setInt32, int32(46)},
- {pb.E_DefaultSint64, setInt64, int64(47)},
- {pb.E_DefaultFixed32, setUint32, uint32(48)},
- {pb.E_DefaultFixed64, setUint64, uint64(49)},
- {pb.E_DefaultSfixed32, setInt32, int32(50)},
- {pb.E_DefaultSfixed64, setInt64, int64(51)},
- {pb.E_DefaultBool, setBool, true},
- {pb.E_DefaultBool, setBool2, true},
- {pb.E_DefaultString, setString, "Hello, string,def=foo"},
- {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")},
- {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE},
- }
-
- checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error {
- val, err := proto.GetExtension(msg, test.ext)
- if err != nil {
- if valWant != nil {
- return fmt.Errorf("GetExtension(): %s", err)
- }
- if want := proto.ErrMissingExtension; err != want {
- return fmt.Errorf("Unexpected error: got %v, want %v", err, want)
+ {pb2.E_NoDefaultDouble, setFloat64, nil},
+ {pb2.E_NoDefaultFloat, setFloat32, nil},
+ {pb2.E_NoDefaultInt32, setInt32, nil},
+ {pb2.E_NoDefaultInt64, setInt64, nil},
+ {pb2.E_NoDefaultUint32, setUint32, nil},
+ {pb2.E_NoDefaultUint64, setUint64, nil},
+ {pb2.E_NoDefaultSint32, setInt32, nil},
+ {pb2.E_NoDefaultSint64, setInt64, nil},
+ {pb2.E_NoDefaultFixed32, setUint32, nil},
+ {pb2.E_NoDefaultFixed64, setUint64, nil},
+ {pb2.E_NoDefaultSfixed32, setInt32, nil},
+ {pb2.E_NoDefaultSfixed64, setInt64, nil},
+ {pb2.E_NoDefaultBool, setBool, nil},
+ {pb2.E_NoDefaultBool, setBool2, nil},
+ {pb2.E_NoDefaultString, setString, nil},
+ {pb2.E_NoDefaultBytes, setBytes, nil},
+ {pb2.E_NoDefaultEnum, setEnum, nil},
+ {pb2.E_DefaultDouble, setFloat64, float64(3.1415)},
+ {pb2.E_DefaultFloat, setFloat32, float32(3.14)},
+ {pb2.E_DefaultInt32, setInt32, int32(42)},
+ {pb2.E_DefaultInt64, setInt64, int64(43)},
+ {pb2.E_DefaultUint32, setUint32, uint32(44)},
+ {pb2.E_DefaultUint64, setUint64, uint64(45)},
+ {pb2.E_DefaultSint32, setInt32, int32(46)},
+ {pb2.E_DefaultSint64, setInt64, int64(47)},
+ {pb2.E_DefaultFixed32, setUint32, uint32(48)},
+ {pb2.E_DefaultFixed64, setUint64, uint64(49)},
+ {pb2.E_DefaultSfixed32, setInt32, int32(50)},
+ {pb2.E_DefaultSfixed64, setInt64, int64(51)},
+ {pb2.E_DefaultBool, setBool, true},
+ {pb2.E_DefaultBool, setBool2, true},
+ {pb2.E_DefaultString, setString, "Hello, string,def=foo"},
+ {pb2.E_DefaultBytes, setBytes, []byte("Hello, bytes")},
+ {pb2.E_DefaultEnum, setEnum, pb2.DefaultsMessage_ONE},
+ }
+
+ checkVal := func(t *testing.T, name string, test testcase, msg *pb2.DefaultsMessage, valWant interface{}) {
+ t.Run(name, func(t *testing.T) {
+ val, err := proto.GetExtension(msg, test.ext)
+ if err != nil {
+ if valWant != nil {
+ t.Errorf("GetExtension(): %s", err)
+ return
+ }
+ if want := proto.ErrMissingExtension; err != want {
+ t.Errorf("Unexpected error: got %v, want %v", err, want)
+ return
+ }
+ return
}
- return nil
- }
- // All proto2 extension values are either a pointer to a value or a slice of values.
- ty := reflect.TypeOf(val)
- tyWant := reflect.TypeOf(test.ext.ExtensionType)
- if got, want := ty, tyWant; got != want {
- return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want)
- }
- tye := ty.Elem()
- tyeWant := tyWant.Elem()
- if got, want := tye, tyeWant; got != want {
- return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want)
- }
-
- // Check the name of the type of the value.
- // If it is an enum it will be type int32 with the name of the enum.
- if got, want := tye.Name(), tye.Name(); got != want {
- return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want)
- }
+ // All proto2 extension values are either a pointer to a value or a slice of values.
+ ty := reflect.TypeOf(val)
+ tyWant := reflect.TypeOf(test.ext.ExtensionType)
+ if got, want := ty, tyWant; got != want {
+ t.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want)
+ return
+ }
+ tye := ty.Elem()
+ tyeWant := tyWant.Elem()
+ if got, want := tye, tyeWant; got != want {
+ t.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want)
+ return
+ }
- // Check that value is what we expect.
- // If we have a pointer in val, get the value it points to.
- valExp := val
- if ty.Kind() == reflect.Ptr {
- valExp = reflect.ValueOf(val).Elem().Interface()
- }
- if got, want := valExp, valWant; !reflect.DeepEqual(got, want) {
- return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want)
- }
+ // Check the name of the type of the value.
+ // If it is an enum it will be type int32 with the name of the enum.
+ if got, want := tye.Name(), tye.Name(); got != want {
+ t.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want)
+ return
+ }
- return nil
+ // Check that value is what we expect.
+ // If we have a pointer in val, get the value it points to.
+ valExp := val
+ if ty.Kind() == reflect.Ptr {
+ valExp = reflect.ValueOf(val).Elem().Interface()
+ }
+ if got, want := valExp, valWant; !reflect.DeepEqual(got, want) {
+ t.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want)
+ return
+ }
+ })
}
setTo := func(test testcase) interface{} {
@@ -361,37 +329,28 @@ func TestGetExtensionDefaults(t *testing.T) {
}
for _, test := range tests {
- msg := &pb.DefaultsMessage{}
+ msg := &pb2.DefaultsMessage{}
name := test.ext.Name
// Check the initial value.
- if err := checkVal(test, msg, test.def); err != nil {
- t.Errorf("%s: %v", name, err)
- }
+ checkVal(t, name+"/initial", test, msg, test.def)
// Set the per-type value and check value.
- name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want)
if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil {
t.Errorf("%s: SetExtension(): %v", name, err)
continue
}
- if err := checkVal(test, msg, test.want); err != nil {
- t.Errorf("%s: %v", name, err)
- continue
- }
+ checkVal(t, name+"/set", test, msg, test.want)
// Set and check the value.
- name += " (cleared)"
proto.ClearExtension(msg, test.ext)
- if err := checkVal(test, msg, test.def); err != nil {
- t.Errorf("%s: %v", name, err)
- }
+ checkVal(t, name+"/cleared", test, msg, test.def)
}
}
func TestNilMessage(t *testing.T) {
name := "nil interface"
- if got, err := proto.GetExtension(nil, pb.E_Ext_More); err == nil {
+ if got, err := proto.GetExtension(nil, pb2.E_Ext_More); err == nil {
t.Errorf("%s: got %T %v, expected to fail", name, got, got)
} else if !strings.Contains(err.Error(), "extendable") {
t.Errorf("%s: got error %v, expected not-extendable error", name, err)
@@ -400,11 +359,11 @@ func TestNilMessage(t *testing.T) {
// Regression tests: all functions of the Extension API
// used to panic when passed (*M)(nil), where M is a concrete message
// type. Now they handle this gracefully as a no-op or reported error.
- var nilMsg *pb.MyMessage
- desc := pb.E_Ext_More
+ var nilMsg *pb2.MyMessage
+ desc := pb2.E_Ext_More
isNotExtendable := func(err error) bool {
- return strings.Contains(fmt.Sprint(err), "not extendable")
+ return strings.Contains(fmt.Sprint(err), "not an extendable")
}
if proto.HasExtension(nilMsg, desc) {
@@ -428,58 +387,52 @@ func TestNilMessage(t *testing.T) {
}
func TestExtensionsRoundTrip(t *testing.T) {
- msg := &pb.MyMessage{}
- ext1 := &pb.Ext{
+ msg := &pb2.MyMessage{}
+ ext1 := &pb2.Ext{
Data: proto.String("hi"),
}
- ext2 := &pb.Ext{
+ ext2 := &pb2.Ext{
Data: proto.String("there"),
}
- exists := proto.HasExtension(msg, pb.E_Ext_More)
+ exists := proto.HasExtension(msg, pb2.E_Ext_More)
if exists {
t.Error("Extension More present unexpectedly")
}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil {
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, ext1); err != nil {
t.Error(err)
}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil {
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, ext2); err != nil {
t.Error(err)
}
- e, err := proto.GetExtension(msg, pb.E_Ext_More)
+ e, err := proto.GetExtension(msg, pb2.E_Ext_More)
if err != nil {
t.Error(err)
}
- x, ok := e.(*pb.Ext)
+ x, ok := e.(*pb2.Ext)
if !ok {
t.Errorf("e has type %T, expected test_proto.Ext", e)
} else if *x.Data != "there" {
t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x)
}
- proto.ClearExtension(msg, pb.E_Ext_More)
- if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension {
+ proto.ClearExtension(msg, pb2.E_Ext_More)
+ if _, err = proto.GetExtension(msg, pb2.E_Ext_More); err != proto.ErrMissingExtension {
t.Errorf("got %v, expected ErrMissingExtension", e)
}
- if _, err := proto.GetExtension(msg, pb.E_X215); err == nil {
- t.Error("expected bad extension error, got nil")
- }
- if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil {
- t.Error("expected extension err")
- }
- if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil {
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, 12); err == nil {
t.Error("expected some sort of type mismatch error, got nil")
}
}
func TestNilExtension(t *testing.T) {
- msg := &pb.MyMessage{
+ msg := &pb2.MyMessage{
Count: proto.Int32(1),
}
- if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil {
+ if err := proto.SetExtension(msg, pb2.E_Ext_Text, proto.String("hello")); err != nil {
t.Fatal(err)
}
- if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil {
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, (*pb2.Ext)(nil)); err == nil {
t.Error("expected SetExtension to fail due to a nil extension")
- } else if want := fmt.Sprintf("proto: SetExtension called with nil value of type %T", new(pb.Ext)); err.Error() != want {
+ } else if want := fmt.Sprintf("proto: SetExtension called with nil value of type %T", new(pb2.Ext)); err.Error() != want {
t.Errorf("expected error %v, got %v", want, err)
}
// Note: if the behavior of Marshal is ever changed to ignore nil extensions, update
@@ -490,25 +443,25 @@ func TestMarshalUnmarshalRepeatedExtension(t *testing.T) {
// Add a repeated extension to the result.
tests := []struct {
name string
- ext []*pb.ComplexExtension
+ ext []*pb2.ComplexExtension
}{
{
"two fields",
- []*pb.ComplexExtension{
+ []*pb2.ComplexExtension{
{First: proto.Int32(7)},
{Second: proto.Int32(11)},
},
},
{
"repeated field",
- []*pb.ComplexExtension{
+ []*pb2.ComplexExtension{
{Third: []int32{1000}},
{Third: []int32{2000}},
},
},
{
"two fields and repeated field",
- []*pb.ComplexExtension{
+ []*pb2.ComplexExtension{
{Third: []int32{1000}},
{First: proto.Int32(9)},
{Second: proto.Int32(21)},
@@ -518,8 +471,8 @@ func TestMarshalUnmarshalRepeatedExtension(t *testing.T) {
}
for _, test := range tests {
// Marshal message with a repeated extension.
- msg1 := new(pb.OtherMessage)
- err := proto.SetExtension(msg1, pb.E_RComplex, test.ext)
+ msg1 := new(pb2.OtherMessage)
+ err := proto.SetExtension(msg1, pb2.E_RComplex, test.ext)
if err != nil {
t.Fatalf("[%s] Error setting extension: %v", test.name, err)
}
@@ -529,16 +482,16 @@ func TestMarshalUnmarshalRepeatedExtension(t *testing.T) {
}
// Unmarshal and read the merged proto.
- msg2 := new(pb.OtherMessage)
+ msg2 := new(pb2.OtherMessage)
err = proto.Unmarshal(b, msg2)
if err != nil {
t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err)
}
- e, err := proto.GetExtension(msg2, pb.E_RComplex)
+ e, err := proto.GetExtension(msg2, pb2.E_RComplex)
if err != nil {
t.Fatalf("[%s] Error getting extension: %v", test.name, err)
}
- ext := e.([]*pb.ComplexExtension)
+ ext := e.([]*pb2.ComplexExtension)
if ext == nil {
t.Fatalf("[%s] Invalid extension", test.name)
}
@@ -559,25 +512,25 @@ func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) {
// this way. Here, we verify that we merge the extensions together.
tests := []struct {
name string
- ext []*pb.ComplexExtension
+ ext []*pb2.ComplexExtension
}{
{
"two fields",
- []*pb.ComplexExtension{
+ []*pb2.ComplexExtension{
{First: proto.Int32(7)},
{Second: proto.Int32(11)},
},
},
{
"repeated field",
- []*pb.ComplexExtension{
+ []*pb2.ComplexExtension{
{Third: []int32{1000}},
{Third: []int32{2000}},
},
},
{
"two fields and repeated field",
- []*pb.ComplexExtension{
+ []*pb2.ComplexExtension{
{Third: []int32{1000}},
{First: proto.Int32(9)},
{Second: proto.Int32(21)},
@@ -587,7 +540,7 @@ func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) {
}
for _, test := range tests {
var buf bytes.Buffer
- var want pb.ComplexExtension
+ var want pb2.ComplexExtension
// Generate a serialized representation of a repeated extension
// by catenating bytes together.
@@ -596,8 +549,8 @@ func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) {
proto.Merge(&want, e)
// serialize the message
- msg := new(pb.OtherMessage)
- err := proto.SetExtension(msg, pb.E_Complex, e)
+ msg := new(pb2.OtherMessage)
+ err := proto.SetExtension(msg, pb2.E_Complex, e)
if err != nil {
t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err)
}
@@ -609,16 +562,16 @@ func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) {
}
// Unmarshal and read the merged proto.
- msg2 := new(pb.OtherMessage)
+ msg2 := new(pb2.OtherMessage)
err := proto.Unmarshal(buf.Bytes(), msg2)
if err != nil {
t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err)
}
- e, err := proto.GetExtension(msg2, pb.E_Complex)
+ e, err := proto.GetExtension(msg2, pb2.E_Complex)
if err != nil {
t.Fatalf("[%s] Error getting extension: %v", test.name, err)
}
- ext := e.(*pb.ComplexExtension)
+ ext := e.(*pb2.ComplexExtension)
if ext == nil {
t.Fatalf("[%s] Invalid extension", test.name)
}
@@ -631,13 +584,13 @@ func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) {
func TestClearAllExtensions(t *testing.T) {
// unregistered extension
desc := &proto.ExtensionDesc{
- ExtendedType: (*pb.MyMessage)(nil),
+ ExtendedType: (*pb2.MyMessage)(nil),
ExtensionType: (*bool)(nil),
Field: 101010100,
Name: "emptyextension",
Tag: "varint,0,opt",
}
- m := &pb.MyMessage{}
+ m := &pb2.MyMessage{}
if proto.HasExtension(m, desc) {
t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m))
}
@@ -654,9 +607,9 @@ func TestClearAllExtensions(t *testing.T) {
}
func TestMarshalRace(t *testing.T) {
- ext := &pb.Ext{}
- m := &pb.MyMessage{Count: proto.Int32(4)}
- if err := proto.SetExtension(m, pb.E_Ext_More, ext); err != nil {
+ ext := &pb2.Ext{}
+ m := &pb2.MyMessage{Count: proto.Int32(4)}
+ if err := proto.SetExtension(m, pb2.E_Ext_More, ext); err != nil {
t.Fatalf("proto.SetExtension(m, desc, true): got error %q, want nil", err)
}
@@ -671,18 +624,22 @@ func TestMarshalRace(t *testing.T) {
// GetExtension will decode it lazily. Make sure this does
// not race against Marshal.
- var g errgroup.Group
+ wg := sync.WaitGroup{}
+ errs := make(chan error, 3)
for n := 3; n > 0; n-- {
- g.Go(func() error {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
_, err := proto.Marshal(m)
- return err
- })
- g.Go(func() error {
- _, err := proto.GetExtension(m, pb.E_Ext_More)
- return err
- })
+ errs <- err
+ }()
}
- if err := g.Wait(); err != nil {
- t.Fatal(err)
+ wg.Wait()
+ close(errs)
+
+ for err = range errs {
+ if err != nil {
+ t.Fatal(err)
+ }
}
}
diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go
deleted file mode 100644
index 0e2191b8a..000000000
--- a/vendor/github.com/golang/protobuf/proto/lib.go
+++ /dev/null
@@ -1,921 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
-Package proto converts data structures to and from the wire format of
-protocol buffers. It works in concert with the Go source code generated
-for .proto files by the protocol compiler.
-
-A summary of the properties of the protocol buffer interface
-for a protocol buffer variable v:
-
- - Names are turned from camel_case to CamelCase for export.
- - There are no methods on v to set fields; just treat
- them as structure fields.
- - There are getters that return a field's value if set,
- and return the field's default value if unset.
- The getters work even if the receiver is a nil message.
- - The zero value for a struct is its correct initialization state.
- All desired fields must be set before marshaling.
- - A Reset() method will restore a protobuf struct to its zero state.
- - Non-repeated fields are pointers to the values; nil means unset.
- That is, optional or required field int32 f becomes F *int32.
- - Repeated fields are slices.
- - Helper functions are available to aid the setting of fields.
- msg.Foo = proto.String("hello") // set field
- - Constants are defined to hold the default values of all fields that
- have them. They have the form Default_StructName_FieldName.
- Because the getter methods handle defaulted values,
- direct use of these constants should be rare.
- - Enums are given type names and maps from names to values.
- Enum values are prefixed by the enclosing message's name, or by the
- enum's type name if it is a top-level enum. Enum types have a String
- method, and a Enum method to assist in message construction.
- - Nested messages, groups and enums have type names prefixed with the name of
- the surrounding message type.
- - Extensions are given descriptor names that start with E_,
- followed by an underscore-delimited list of the nested messages
- that contain it (if any) followed by the CamelCased name of the
- extension field itself. HasExtension, ClearExtension, GetExtension
- and SetExtension are functions for manipulating extensions.
- - Oneof field sets are given a single field in their message,
- with distinguished wrapper types for each possible field value.
- - Marshal and Unmarshal are functions to encode and decode the wire format.
-
-When the .proto file specifies `syntax="proto3"`, there are some differences:
-
- - Non-repeated fields of non-message type are values instead of pointers.
- - Enum types do not get an Enum method.
-
-The simplest way to describe this is to see an example.
-Given file test.proto, containing
-
- package example;
-
- enum FOO { X = 17; }
-
- message Test {
- required string label = 1;
- optional int32 type = 2 [default=77];
- repeated int64 reps = 3;
- optional group OptionalGroup = 4 {
- required string RequiredField = 5;
- }
- oneof union {
- int32 number = 6;
- string name = 7;
- }
- }
-
-The resulting file, test.pb.go, is:
-
- package example
-
- import proto "github.com/golang/protobuf/proto"
- import math "math"
-
- type FOO int32
- const (
- FOO_X FOO = 17
- )
- var FOO_name = map[int32]string{
- 17: "X",
- }
- var FOO_value = map[string]int32{
- "X": 17,
- }
-
- func (x FOO) Enum() *FOO {
- p := new(FOO)
- *p = x
- return p
- }
- func (x FOO) String() string {
- return proto.EnumName(FOO_name, int32(x))
- }
- func (x *FOO) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FOO_value, data)
- if err != nil {
- return err
- }
- *x = FOO(value)
- return nil
- }
-
- type Test struct {
- Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
- Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
- Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
- Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
- // Types that are valid to be assigned to Union:
- // *Test_Number
- // *Test_Name
- Union isTest_Union `protobuf_oneof:"union"`
- XXX_unrecognized []byte `json:"-"`
- }
- func (m *Test) Reset() { *m = Test{} }
- func (m *Test) String() string { return proto.CompactTextString(m) }
- func (*Test) ProtoMessage() {}
-
- type isTest_Union interface {
- isTest_Union()
- }
-
- type Test_Number struct {
- Number int32 `protobuf:"varint,6,opt,name=number"`
- }
- type Test_Name struct {
- Name string `protobuf:"bytes,7,opt,name=name"`
- }
-
- func (*Test_Number) isTest_Union() {}
- func (*Test_Name) isTest_Union() {}
-
- func (m *Test) GetUnion() isTest_Union {
- if m != nil {
- return m.Union
- }
- return nil
- }
- const Default_Test_Type int32 = 77
-
- func (m *Test) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
- }
-
- func (m *Test) GetType() int32 {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return Default_Test_Type
- }
-
- func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
- if m != nil {
- return m.Optionalgroup
- }
- return nil
- }
-
- type Test_OptionalGroup struct {
- RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
- }
- func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
- func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
-
- func (m *Test_OptionalGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
- }
-
- func (m *Test) GetNumber() int32 {
- if x, ok := m.GetUnion().(*Test_Number); ok {
- return x.Number
- }
- return 0
- }
-
- func (m *Test) GetName() string {
- if x, ok := m.GetUnion().(*Test_Name); ok {
- return x.Name
- }
- return ""
- }
-
- func init() {
- proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
- }
-
-To create and play with a Test object:
-
- package main
-
- import (
- "log"
-
- "github.com/golang/protobuf/proto"
- pb "./example.pb"
- )
-
- func main() {
- test := &pb.Test{
- Label: proto.String("hello"),
- Type: proto.Int32(17),
- Reps: []int64{1, 2, 3},
- Optionalgroup: &pb.Test_OptionalGroup{
- RequiredField: proto.String("good bye"),
- },
- Union: &pb.Test_Name{"fred"},
- }
- data, err := proto.Marshal(test)
- if err != nil {
- log.Fatal("marshaling error: ", err)
- }
- newTest := &pb.Test{}
- err = proto.Unmarshal(data, newTest)
- if err != nil {
- log.Fatal("unmarshaling error: ", err)
- }
- // Now test and newTest contain the same data.
- if test.GetLabel() != newTest.GetLabel() {
- log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
- }
- // Use a type switch to determine which oneof was set.
- switch u := test.Union.(type) {
- case *pb.Test_Number: // u.Number contains the number.
- case *pb.Test_Name: // u.Name contains the string.
- }
- // etc.
- }
-*/
-package proto
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "log"
- "reflect"
- "sort"
- "strconv"
- "sync"
-)
-
-var errInvalidUTF8 = errors.New("proto: invalid UTF-8 string")
-
-// Message is implemented by generated protocol buffer messages.
-type Message interface {
- Reset()
- String() string
- ProtoMessage()
-}
-
-// Stats records allocation details about the protocol buffer encoders
-// and decoders. Useful for tuning the library itself.
-type Stats struct {
- Emalloc uint64 // mallocs in encode
- Dmalloc uint64 // mallocs in decode
- Encode uint64 // number of encodes
- Decode uint64 // number of decodes
- Chit uint64 // number of cache hits
- Cmiss uint64 // number of cache misses
- Size uint64 // number of sizes
-}
-
-// Set to true to enable stats collection.
-const collectStats = false
-
-var stats Stats
-
-// GetStats returns a copy of the global Stats structure.
-func GetStats() Stats { return stats }
-
-// A Buffer is a buffer manager for marshaling and unmarshaling
-// protocol buffers. It may be reused between invocations to
-// reduce memory usage. It is not necessary to use a Buffer;
-// the global functions Marshal and Unmarshal create a
-// temporary Buffer and are fine for most applications.
-type Buffer struct {
- buf []byte // encode/decode byte stream
- index int // read point
-
- deterministic bool
-}
-
-// NewBuffer allocates a new Buffer and initializes its internal data to
-// the contents of the argument slice.
-func NewBuffer(e []byte) *Buffer {
- return &Buffer{buf: e}
-}
-
-// Reset resets the Buffer, ready for marshaling a new protocol buffer.
-func (p *Buffer) Reset() {
- p.buf = p.buf[0:0] // for reading/writing
- p.index = 0 // for reading
-}
-
-// SetBuf replaces the internal buffer with the slice,
-// ready for unmarshaling the contents of the slice.
-func (p *Buffer) SetBuf(s []byte) {
- p.buf = s
- p.index = 0
-}
-
-// Bytes returns the contents of the Buffer.
-func (p *Buffer) Bytes() []byte { return p.buf }
-
-// SetDeterministic sets whether to use deterministic serialization.
-//
-// Deterministic serialization guarantees that for a given binary, equal
-// messages will always be serialized to the same bytes. This implies:
-//
-// - Repeated serialization of a message will return the same bytes.
-// - Different processes of the same binary (which may be executing on
-// different machines) will serialize equal messages to the same bytes.
-//
-// Note that the deterministic serialization is NOT canonical across
-// languages. It is not guaranteed to remain stable over time. It is unstable
-// across different builds with schema changes due to unknown fields.
-// Users who need canonical serialization (e.g., persistent storage in a
-// canonical form, fingerprinting, etc.) should define their own
-// canonicalization specification and implement their own serializer rather
-// than relying on this API.
-//
-// If deterministic serialization is requested, map entries will be sorted
-// by keys in lexographical order. This is an implementation detail and
-// subject to change.
-func (p *Buffer) SetDeterministic(deterministic bool) {
- p.deterministic = deterministic
-}
-
-/*
- * Helper routines for simplifying the creation of optional fields of basic type.
- */
-
-// Bool is a helper routine that allocates a new bool value
-// to store v and returns a pointer to it.
-func Bool(v bool) *bool {
- return &v
-}
-
-// Int32 is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it.
-func Int32(v int32) *int32 {
- return &v
-}
-
-// Int is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it, but unlike Int32
-// its argument value is an int.
-func Int(v int) *int32 {
- p := new(int32)
- *p = int32(v)
- return p
-}
-
-// Int64 is a helper routine that allocates a new int64 value
-// to store v and returns a pointer to it.
-func Int64(v int64) *int64 {
- return &v
-}
-
-// Float32 is a helper routine that allocates a new float32 value
-// to store v and returns a pointer to it.
-func Float32(v float32) *float32 {
- return &v
-}
-
-// Float64 is a helper routine that allocates a new float64 value
-// to store v and returns a pointer to it.
-func Float64(v float64) *float64 {
- return &v
-}
-
-// Uint32 is a helper routine that allocates a new uint32 value
-// to store v and returns a pointer to it.
-func Uint32(v uint32) *uint32 {
- return &v
-}
-
-// Uint64 is a helper routine that allocates a new uint64 value
-// to store v and returns a pointer to it.
-func Uint64(v uint64) *uint64 {
- return &v
-}
-
-// String is a helper routine that allocates a new string value
-// to store v and returns a pointer to it.
-func String(v string) *string {
- return &v
-}
-
-// EnumName is a helper function to simplify printing protocol buffer enums
-// by name. Given an enum map and a value, it returns a useful string.
-func EnumName(m map[int32]string, v int32) string {
- s, ok := m[v]
- if ok {
- return s
- }
- return strconv.Itoa(int(v))
-}
-
-// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
-// from their JSON-encoded representation. Given a map from the enum's symbolic
-// names to its int values, and a byte buffer containing the JSON-encoded
-// value, it returns an int32 that can be cast to the enum type by the caller.
-//
-// The function can deal with both JSON representations, numeric and symbolic.
-func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
- if data[0] == '"' {
- // New style: enums are strings.
- var repr string
- if err := json.Unmarshal(data, &repr); err != nil {
- return -1, err
- }
- val, ok := m[repr]
- if !ok {
- return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
- }
- return val, nil
- }
- // Old style: enums are ints.
- var val int32
- if err := json.Unmarshal(data, &val); err != nil {
- return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
- }
- return val, nil
-}
-
-// DebugPrint dumps the encoded data in b in a debugging format with a header
-// including the string s. Used in testing but made available for general debugging.
-func (p *Buffer) DebugPrint(s string, b []byte) {
- var u uint64
-
- obuf := p.buf
- index := p.index
- p.buf = b
- p.index = 0
- depth := 0
-
- fmt.Printf("\n--- %s ---\n", s)
-
-out:
- for {
- for i := 0; i < depth; i++ {
- fmt.Print(" ")
- }
-
- index := p.index
- if index == len(p.buf) {
- break
- }
-
- op, err := p.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: fetching op err %v\n", index, err)
- break out
- }
- tag := op >> 3
- wire := op & 7
-
- switch wire {
- default:
- fmt.Printf("%3d: t=%3d unknown wire=%d\n",
- index, tag, wire)
- break out
-
- case WireBytes:
- var r []byte
-
- r, err = p.DecodeRawBytes(false)
- if err != nil {
- break out
- }
- fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
- if len(r) <= 6 {
- for i := 0; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- } else {
- for i := 0; i < 3; i++ {
- fmt.Printf(" %.2x", r[i])
- }
- fmt.Printf(" ..")
- for i := len(r) - 3; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- }
- fmt.Printf("\n")
-
- case WireFixed32:
- u, err = p.DecodeFixed32()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
-
- case WireFixed64:
- u, err = p.DecodeFixed64()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
-
- case WireVarint:
- u, err = p.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
-
- case WireStartGroup:
- fmt.Printf("%3d: t=%3d start\n", index, tag)
- depth++
-
- case WireEndGroup:
- depth--
- fmt.Printf("%3d: t=%3d end\n", index, tag)
- }
- }
-
- if depth != 0 {
- fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
- }
- fmt.Printf("\n")
-
- p.buf = obuf
- p.index = index
-}
-
-// SetDefaults sets unset protocol buffer fields to their default values.
-// It only modifies fields that are both unset and have defined defaults.
-// It recursively sets default values in any non-nil sub-messages.
-func SetDefaults(pb Message) {
- setDefaults(reflect.ValueOf(pb), true, false)
-}
-
-// v is a pointer to a struct.
-func setDefaults(v reflect.Value, recur, zeros bool) {
- v = v.Elem()
-
- defaultMu.RLock()
- dm, ok := defaults[v.Type()]
- defaultMu.RUnlock()
- if !ok {
- dm = buildDefaultMessage(v.Type())
- defaultMu.Lock()
- defaults[v.Type()] = dm
- defaultMu.Unlock()
- }
-
- for _, sf := range dm.scalars {
- f := v.Field(sf.index)
- if !f.IsNil() {
- // field already set
- continue
- }
- dv := sf.value
- if dv == nil && !zeros {
- // no explicit default, and don't want to set zeros
- continue
- }
- fptr := f.Addr().Interface() // **T
- // TODO: Consider batching the allocations we do here.
- switch sf.kind {
- case reflect.Bool:
- b := new(bool)
- if dv != nil {
- *b = dv.(bool)
- }
- *(fptr.(**bool)) = b
- case reflect.Float32:
- f := new(float32)
- if dv != nil {
- *f = dv.(float32)
- }
- *(fptr.(**float32)) = f
- case reflect.Float64:
- f := new(float64)
- if dv != nil {
- *f = dv.(float64)
- }
- *(fptr.(**float64)) = f
- case reflect.Int32:
- // might be an enum
- if ft := f.Type(); ft != int32PtrType {
- // enum
- f.Set(reflect.New(ft.Elem()))
- if dv != nil {
- f.Elem().SetInt(int64(dv.(int32)))
- }
- } else {
- // int32 field
- i := new(int32)
- if dv != nil {
- *i = dv.(int32)
- }
- *(fptr.(**int32)) = i
- }
- case reflect.Int64:
- i := new(int64)
- if dv != nil {
- *i = dv.(int64)
- }
- *(fptr.(**int64)) = i
- case reflect.String:
- s := new(string)
- if dv != nil {
- *s = dv.(string)
- }
- *(fptr.(**string)) = s
- case reflect.Uint8:
- // exceptional case: []byte
- var b []byte
- if dv != nil {
- db := dv.([]byte)
- b = make([]byte, len(db))
- copy(b, db)
- } else {
- b = []byte{}
- }
- *(fptr.(*[]byte)) = b
- case reflect.Uint32:
- u := new(uint32)
- if dv != nil {
- *u = dv.(uint32)
- }
- *(fptr.(**uint32)) = u
- case reflect.Uint64:
- u := new(uint64)
- if dv != nil {
- *u = dv.(uint64)
- }
- *(fptr.(**uint64)) = u
- default:
- log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
- }
- }
-
- for _, ni := range dm.nested {
- f := v.Field(ni)
- // f is *T or []*T or map[T]*T
- switch f.Kind() {
- case reflect.Ptr:
- if f.IsNil() {
- continue
- }
- setDefaults(f, recur, zeros)
-
- case reflect.Slice:
- for i := 0; i < f.Len(); i++ {
- e := f.Index(i)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
-
- case reflect.Map:
- for _, k := range f.MapKeys() {
- e := f.MapIndex(k)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
- }
- }
-}
-
-var (
- // defaults maps a protocol buffer struct type to a slice of the fields,
- // with its scalar fields set to their proto-declared non-zero default values.
- defaultMu sync.RWMutex
- defaults = make(map[reflect.Type]defaultMessage)
-
- int32PtrType = reflect.TypeOf((*int32)(nil))
-)
-
-// defaultMessage represents information about the default values of a message.
-type defaultMessage struct {
- scalars []scalarField
- nested []int // struct field index of nested messages
-}
-
-type scalarField struct {
- index int // struct field index
- kind reflect.Kind // element type (the T in *T or []T)
- value interface{} // the proto-declared default value, or nil
-}
-
-// t is a struct type.
-func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
- sprop := GetProperties(t)
- for _, prop := range sprop.Prop {
- fi, ok := sprop.decoderTags.get(prop.Tag)
- if !ok {
- // XXX_unrecognized
- continue
- }
- ft := t.Field(fi).Type
-
- sf, nested, err := fieldDefault(ft, prop)
- switch {
- case err != nil:
- log.Print(err)
- case nested:
- dm.nested = append(dm.nested, fi)
- case sf != nil:
- sf.index = fi
- dm.scalars = append(dm.scalars, *sf)
- }
- }
-
- return dm
-}
-
-// fieldDefault returns the scalarField for field type ft.
-// sf will be nil if the field can not have a default.
-// nestedMessage will be true if this is a nested message.
-// Note that sf.index is not set on return.
-func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
- var canHaveDefault bool
- switch ft.Kind() {
- case reflect.Ptr:
- if ft.Elem().Kind() == reflect.Struct {
- nestedMessage = true
- } else {
- canHaveDefault = true // proto2 scalar field
- }
-
- case reflect.Slice:
- switch ft.Elem().Kind() {
- case reflect.Ptr:
- nestedMessage = true // repeated message
- case reflect.Uint8:
- canHaveDefault = true // bytes field
- }
-
- case reflect.Map:
- if ft.Elem().Kind() == reflect.Ptr {
- nestedMessage = true // map with message values
- }
- }
-
- if !canHaveDefault {
- if nestedMessage {
- return nil, true, nil
- }
- return nil, false, nil
- }
-
- // We now know that ft is a pointer or slice.
- sf = &scalarField{kind: ft.Elem().Kind()}
-
- // scalar fields without defaults
- if !prop.HasDefault {
- return sf, false, nil
- }
-
- // a scalar field: either *T or []byte
- switch ft.Elem().Kind() {
- case reflect.Bool:
- x, err := strconv.ParseBool(prop.Default)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.Float32:
- x, err := strconv.ParseFloat(prop.Default, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
- }
- sf.value = float32(x)
- case reflect.Float64:
- x, err := strconv.ParseFloat(prop.Default, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.Int32:
- x, err := strconv.ParseInt(prop.Default, 10, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
- }
- sf.value = int32(x)
- case reflect.Int64:
- x, err := strconv.ParseInt(prop.Default, 10, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.String:
- sf.value = prop.Default
- case reflect.Uint8:
- // []byte (not *uint8)
- sf.value = []byte(prop.Default)
- case reflect.Uint32:
- x, err := strconv.ParseUint(prop.Default, 10, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
- }
- sf.value = uint32(x)
- case reflect.Uint64:
- x, err := strconv.ParseUint(prop.Default, 10, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
- }
- sf.value = x
- default:
- return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
- }
-
- return sf, false, nil
-}
-
-// mapKeys returns a sort.Interface to be used for sorting the map keys.
-// Map fields may have key types of non-float scalars, strings and enums.
-func mapKeys(vs []reflect.Value) sort.Interface {
- s := mapKeySorter{vs: vs}
-
- // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
- if len(vs) == 0 {
- return s
- }
- switch vs[0].Kind() {
- case reflect.Int32, reflect.Int64:
- s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
- case reflect.Uint32, reflect.Uint64:
- s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
- case reflect.Bool:
- s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
- case reflect.String:
- s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
- default:
- panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
- }
-
- return s
-}
-
-type mapKeySorter struct {
- vs []reflect.Value
- less func(a, b reflect.Value) bool
-}
-
-func (s mapKeySorter) Len() int { return len(s.vs) }
-func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
-func (s mapKeySorter) Less(i, j int) bool {
- return s.less(s.vs[i], s.vs[j])
-}
-
-// isProto3Zero reports whether v is a zero proto3 value.
-func isProto3Zero(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint32, reflect.Uint64:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.String:
- return v.String() == ""
- }
- return false
-}
-
-// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
-// to assert that that code is compatible with this version of the proto package.
-const ProtoPackageIsVersion2 = true
-
-// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
-// to assert that that code is compatible with this version of the proto package.
-const ProtoPackageIsVersion1 = true
-
-// InternalMessageInfo is a type used internally by generated .pb.go files.
-// This type is not intended to be used by non-generated code.
-// This type is not subject to any compatibility guarantee.
-type InternalMessageInfo struct {
- marshal *marshalInfo
- unmarshal *unmarshalInfo
- merge *mergeInfo
- discard *discardInfo
-}
diff --git a/vendor/github.com/golang/protobuf/proto/map_test.go b/vendor/github.com/golang/protobuf/proto/map_test.go
deleted file mode 100644
index b1e1529ee..000000000
--- a/vendor/github.com/golang/protobuf/proto/map_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package proto_test
-
-import (
- "fmt"
- "reflect"
- "testing"
-
- "github.com/golang/protobuf/proto"
- ppb "github.com/golang/protobuf/proto/proto3_proto"
-)
-
-func TestMap(t *testing.T) {
- var b []byte
- fmt.Sscanf("a2010c0a044b657931120456616c31a201130a044b657932120556616c3261120456616c32a201240a044b6579330d05000000120556616c33621a0556616c3361120456616c331505000000a20100a201260a044b657934130a07536f6d6555524c1209536f6d655469746c651a08536e69707065743114", "%x", &b)
-
- var m ppb.Message
- if err := proto.Unmarshal(b, &m); err != nil {
- t.Fatalf("proto.Unmarshal error: %v", err)
- }
-
- got := m.StringMap
- want := map[string]string{
- "": "",
- "Key1": "Val1",
- "Key2": "Val2",
- "Key3": "Val3",
- "Key4": "",
- }
-
- if !reflect.DeepEqual(got, want) {
- t.Errorf("maps differ:\ngot %#v\nwant %#v", got, want)
- }
-}
-
-func marshalled() []byte {
- m := &ppb.IntMaps{}
- for i := 0; i < 1000; i++ {
- m.Maps = append(m.Maps, &ppb.IntMap{
- Rtt: map[int32]int32{1: 2},
- })
- }
- b, err := proto.Marshal(m)
- if err != nil {
- panic(fmt.Sprintf("Can't marshal %+v: %v", m, err))
- }
- return b
-}
-
-func BenchmarkConcurrentMapUnmarshal(b *testing.B) {
- in := marshalled()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var out ppb.IntMaps
- if err := proto.Unmarshal(in, &out); err != nil {
- b.Errorf("Can't unmarshal ppb.IntMaps: %v", err)
- }
- }
- })
-}
-
-func BenchmarkSequentialMapUnmarshal(b *testing.B) {
- in := marshalled()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- var out ppb.IntMaps
- if err := proto.Unmarshal(in, &out); err != nil {
- b.Errorf("Can't unmarshal ppb.IntMaps: %v", err)
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go
deleted file mode 100644
index 3b6ca41d5..000000000
--- a/vendor/github.com/golang/protobuf/proto/message_set.go
+++ /dev/null
@@ -1,314 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-/*
- * Support for message sets.
- */
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "reflect"
- "sort"
- "sync"
-)
-
-// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
-// A message type ID is required for storing a protocol buffer in a message set.
-var errNoMessageTypeID = errors.New("proto does not have a message type ID")
-
-// The first two types (_MessageSet_Item and messageSet)
-// model what the protocol compiler produces for the following protocol message:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-// That is the MessageSet wire format. We can't use a proto to generate these
-// because that would introduce a circular dependency between it and this package.
-
-type _MessageSet_Item struct {
- TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
- Message []byte `protobuf:"bytes,3,req,name=message"`
-}
-
-type messageSet struct {
- Item []*_MessageSet_Item `protobuf:"group,1,rep"`
- XXX_unrecognized []byte
- // TODO: caching?
-}
-
-// Make sure messageSet is a Message.
-var _ Message = (*messageSet)(nil)
-
-// messageTypeIder is an interface satisfied by a protocol buffer type
-// that may be stored in a MessageSet.
-type messageTypeIder interface {
- MessageTypeId() int32
-}
-
-func (ms *messageSet) find(pb Message) *_MessageSet_Item {
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return nil
- }
- id := mti.MessageTypeId()
- for _, item := range ms.Item {
- if *item.TypeId == id {
- return item
- }
- }
- return nil
-}
-
-func (ms *messageSet) Has(pb Message) bool {
- return ms.find(pb) != nil
-}
-
-func (ms *messageSet) Unmarshal(pb Message) error {
- if item := ms.find(pb); item != nil {
- return Unmarshal(item.Message, pb)
- }
- if _, ok := pb.(messageTypeIder); !ok {
- return errNoMessageTypeID
- }
- return nil // TODO: return error instead?
-}
-
-func (ms *messageSet) Marshal(pb Message) error {
- msg, err := Marshal(pb)
- if err != nil {
- return err
- }
- if item := ms.find(pb); item != nil {
- // reuse existing item
- item.Message = msg
- return nil
- }
-
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return errNoMessageTypeID
- }
-
- mtid := mti.MessageTypeId()
- ms.Item = append(ms.Item, &_MessageSet_Item{
- TypeId: &mtid,
- Message: msg,
- })
- return nil
-}
-
-func (ms *messageSet) Reset() { *ms = messageSet{} }
-func (ms *messageSet) String() string { return CompactTextString(ms) }
-func (*messageSet) ProtoMessage() {}
-
-// Support for the message_set_wire_format message option.
-
-func skipVarint(buf []byte) []byte {
- i := 0
- for ; buf[i]&0x80 != 0; i++ {
- }
- return buf[i+1:]
-}
-
-// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
-// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
-func MarshalMessageSet(exts interface{}) ([]byte, error) {
- return marshalMessageSet(exts, false)
-}
-
-// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal.
-func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) {
- switch exts := exts.(type) {
- case *XXX_InternalExtensions:
- var u marshalInfo
- siz := u.sizeMessageSet(exts)
- b := make([]byte, 0, siz)
- return u.appendMessageSet(b, exts, deterministic)
-
- case map[int32]Extension:
- // This is an old-style extension map.
- // Wrap it in a new-style XXX_InternalExtensions.
- ie := XXX_InternalExtensions{
- p: &struct {
- mu sync.Mutex
- extensionMap map[int32]Extension
- }{
- extensionMap: exts,
- },
- }
-
- var u marshalInfo
- siz := u.sizeMessageSet(&ie)
- b := make([]byte, 0, siz)
- return u.appendMessageSet(b, &ie, deterministic)
-
- default:
- return nil, errors.New("proto: not an extension map")
- }
-}
-
-// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
-// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
-func UnmarshalMessageSet(buf []byte, exts interface{}) error {
- var m map[int32]Extension
- switch exts := exts.(type) {
- case *XXX_InternalExtensions:
- m = exts.extensionsWrite()
- case map[int32]Extension:
- m = exts
- default:
- return errors.New("proto: not an extension map")
- }
-
- ms := new(messageSet)
- if err := Unmarshal(buf, ms); err != nil {
- return err
- }
- for _, item := range ms.Item {
- id := *item.TypeId
- msg := item.Message
-
- // Restore wire type and field number varint, plus length varint.
- // Be careful to preserve duplicate items.
- b := EncodeVarint(uint64(id)<<3 | WireBytes)
- if ext, ok := m[id]; ok {
- // Existing data; rip off the tag and length varint
- // so we join the new data correctly.
- // We can assume that ext.enc is set because we are unmarshaling.
- o := ext.enc[len(b):] // skip wire type and field number
- _, n := DecodeVarint(o) // calculate length of length varint
- o = o[n:] // skip length varint
- msg = append(o, msg...) // join old data and new data
- }
- b = append(b, EncodeVarint(uint64(len(msg)))...)
- b = append(b, msg...)
-
- m[id] = Extension{enc: b}
- }
- return nil
-}
-
-// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
-// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
-func MarshalMessageSetJSON(exts interface{}) ([]byte, error) {
- var m map[int32]Extension
- switch exts := exts.(type) {
- case *XXX_InternalExtensions:
- var mu sync.Locker
- m, mu = exts.extensionsRead()
- if m != nil {
- // Keep the extensions map locked until we're done marshaling to prevent
- // races between marshaling and unmarshaling the lazily-{en,de}coded
- // values.
- mu.Lock()
- defer mu.Unlock()
- }
- case map[int32]Extension:
- m = exts
- default:
- return nil, errors.New("proto: not an extension map")
- }
- var b bytes.Buffer
- b.WriteByte('{')
-
- // Process the map in key order for deterministic output.
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
-
- for i, id := range ids {
- ext := m[id]
- msd, ok := messageSetMap[id]
- if !ok {
- // Unknown type; we can't render it, so skip it.
- continue
- }
-
- if i > 0 && b.Len() > 1 {
- b.WriteByte(',')
- }
-
- fmt.Fprintf(&b, `"[%s]":`, msd.name)
-
- x := ext.value
- if x == nil {
- x = reflect.New(msd.t.Elem()).Interface()
- if err := Unmarshal(ext.enc, x.(Message)); err != nil {
- return nil, err
- }
- }
- d, err := json.Marshal(x)
- if err != nil {
- return nil, err
- }
- b.Write(d)
- }
- b.WriteByte('}')
- return b.Bytes(), nil
-}
-
-// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
-// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
-func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error {
- // Common-case fast path.
- if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
- return nil
- }
-
- // This is fairly tricky, and it's not clear that it is needed.
- return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
-}
-
-// A global registry of types that can be used in a MessageSet.
-
-var messageSetMap = make(map[int32]messageSetDesc)
-
-type messageSetDesc struct {
- t reflect.Type // pointer to struct
- name string
-}
-
-// RegisterMessageSetType is called from the generated code.
-func RegisterMessageSetType(m Message, fieldNum int32, name string) {
- messageSetMap[fieldNum] = messageSetDesc{
- t: reflect.TypeOf(m),
- name: name,
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/message_set_test.go b/vendor/github.com/golang/protobuf/proto/message_set_test.go
deleted file mode 100644
index 2c170c5f2..000000000
--- a/vendor/github.com/golang/protobuf/proto/message_set_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "bytes"
- "testing"
-)
-
-func TestUnmarshalMessageSetWithDuplicate(t *testing.T) {
- // Check that a repeated message set entry will be concatenated.
- in := &messageSet{
- Item: []*_MessageSet_Item{
- {TypeId: Int32(12345), Message: []byte("hoo")},
- {TypeId: Int32(12345), Message: []byte("hah")},
- },
- }
- b, err := Marshal(in)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- t.Logf("Marshaled bytes: %q", b)
-
- var extensions XXX_InternalExtensions
- if err := UnmarshalMessageSet(b, &extensions); err != nil {
- t.Fatalf("UnmarshalMessageSet: %v", err)
- }
- ext, ok := extensions.p.extensionMap[12345]
- if !ok {
- t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap)
- }
- // Skip wire type/field number and length varints.
- got := skipVarint(skipVarint(ext.enc))
- if want := []byte("hoohah"); !bytes.Equal(got, want) {
- t.Errorf("Combined extension is %q, want %q", got, want)
- }
-}
-
-func TestMarshalMessageSetJSON_UnknownType(t *testing.T) {
- extMap := map[int32]Extension{12345: Extension{}}
- got, err := MarshalMessageSetJSON(extMap)
- if err != nil {
- t.Fatalf("MarshalMessageSetJSON: %v", err)
- }
- if want := []byte("{}"); !bytes.Equal(got, want) {
- t.Errorf("MarshalMessageSetJSON(%v) = %q, want %q", extMap, got, want)
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
deleted file mode 100644
index b6cad9083..000000000
--- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
+++ /dev/null
@@ -1,357 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// +build purego appengine js
-
-// This file contains an implementation of proto field accesses using package reflect.
-// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
-// be used on App Engine.
-
-package proto
-
-import (
- "reflect"
- "sync"
-)
-
-const unsafeAllowed = false
-
-// A field identifies a field in a struct, accessible from a pointer.
-// In this implementation, a field is identified by the sequence of field indices
-// passed to reflect's FieldByIndex.
-type field []int
-
-// toField returns a field equivalent to the given reflect field.
-func toField(f *reflect.StructField) field {
- return f.Index
-}
-
-// invalidField is an invalid field identifier.
-var invalidField = field(nil)
-
-// zeroField is a noop when calling pointer.offset.
-var zeroField = field([]int{})
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool { return f != nil }
-
-// The pointer type is for the table-driven decoder.
-// The implementation here uses a reflect.Value of pointer type to
-// create a generic pointer. In pointer_unsafe.go we use unsafe
-// instead of reflect to implement the same (but faster) interface.
-type pointer struct {
- v reflect.Value
-}
-
-// toPointer converts an interface of pointer type to a pointer
-// that points to the same target.
-func toPointer(i *Message) pointer {
- return pointer{v: reflect.ValueOf(*i)}
-}
-
-// toAddrPointer converts an interface to a pointer that points to
-// the interface data.
-func toAddrPointer(i *interface{}, isptr bool) pointer {
- v := reflect.ValueOf(*i)
- u := reflect.New(v.Type())
- u.Elem().Set(v)
- return pointer{v: u}
-}
-
-// valToPointer converts v to a pointer. v must be of pointer type.
-func valToPointer(v reflect.Value) pointer {
- return pointer{v: v}
-}
-
-// offset converts from a pointer to a structure to a pointer to
-// one of its fields.
-func (p pointer) offset(f field) pointer {
- return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
-}
-
-func (p pointer) isNil() bool {
- return p.v.IsNil()
-}
-
-// grow updates the slice s in place to make it one element longer.
-// s must be addressable.
-// Returns the (addressable) new element.
-func grow(s reflect.Value) reflect.Value {
- n, m := s.Len(), s.Cap()
- if n < m {
- s.SetLen(n + 1)
- } else {
- s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem())))
- }
- return s.Index(n)
-}
-
-func (p pointer) toInt64() *int64 {
- return p.v.Interface().(*int64)
-}
-func (p pointer) toInt64Ptr() **int64 {
- return p.v.Interface().(**int64)
-}
-func (p pointer) toInt64Slice() *[]int64 {
- return p.v.Interface().(*[]int64)
-}
-
-var int32ptr = reflect.TypeOf((*int32)(nil))
-
-func (p pointer) toInt32() *int32 {
- return p.v.Convert(int32ptr).Interface().(*int32)
-}
-
-// The toInt32Ptr/Slice methods don't work because of enums.
-// Instead, we must use set/get methods for the int32ptr/slice case.
-/*
- func (p pointer) toInt32Ptr() **int32 {
- return p.v.Interface().(**int32)
-}
- func (p pointer) toInt32Slice() *[]int32 {
- return p.v.Interface().(*[]int32)
-}
-*/
-func (p pointer) getInt32Ptr() *int32 {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- return p.v.Elem().Interface().(*int32)
- }
- // an enum
- return p.v.Elem().Convert(int32PtrType).Interface().(*int32)
-}
-func (p pointer) setInt32Ptr(v int32) {
- // Allocate value in a *int32. Possibly convert that to a *enum.
- // Then assign it to a **int32 or **enum.
- // Note: we can convert *int32 to *enum, but we can't convert
- // **int32 to **enum!
- p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem()))
-}
-
-// getInt32Slice copies []int32 from p as a new slice.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) getInt32Slice() []int32 {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- return p.v.Elem().Interface().([]int32)
- }
- // an enum
- // Allocate a []int32, then assign []enum's values into it.
- // Note: we can't convert []enum to []int32.
- slice := p.v.Elem()
- s := make([]int32, slice.Len())
- for i := 0; i < slice.Len(); i++ {
- s[i] = int32(slice.Index(i).Int())
- }
- return s
-}
-
-// setInt32Slice copies []int32 into p as a new slice.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) setInt32Slice(v []int32) {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- p.v.Elem().Set(reflect.ValueOf(v))
- return
- }
- // an enum
- // Allocate a []enum, then assign []int32's values into it.
- // Note: we can't convert []enum to []int32.
- slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v))
- for i, x := range v {
- slice.Index(i).SetInt(int64(x))
- }
- p.v.Elem().Set(slice)
-}
-func (p pointer) appendInt32Slice(v int32) {
- grow(p.v.Elem()).SetInt(int64(v))
-}
-
-func (p pointer) toUint64() *uint64 {
- return p.v.Interface().(*uint64)
-}
-func (p pointer) toUint64Ptr() **uint64 {
- return p.v.Interface().(**uint64)
-}
-func (p pointer) toUint64Slice() *[]uint64 {
- return p.v.Interface().(*[]uint64)
-}
-func (p pointer) toUint32() *uint32 {
- return p.v.Interface().(*uint32)
-}
-func (p pointer) toUint32Ptr() **uint32 {
- return p.v.Interface().(**uint32)
-}
-func (p pointer) toUint32Slice() *[]uint32 {
- return p.v.Interface().(*[]uint32)
-}
-func (p pointer) toBool() *bool {
- return p.v.Interface().(*bool)
-}
-func (p pointer) toBoolPtr() **bool {
- return p.v.Interface().(**bool)
-}
-func (p pointer) toBoolSlice() *[]bool {
- return p.v.Interface().(*[]bool)
-}
-func (p pointer) toFloat64() *float64 {
- return p.v.Interface().(*float64)
-}
-func (p pointer) toFloat64Ptr() **float64 {
- return p.v.Interface().(**float64)
-}
-func (p pointer) toFloat64Slice() *[]float64 {
- return p.v.Interface().(*[]float64)
-}
-func (p pointer) toFloat32() *float32 {
- return p.v.Interface().(*float32)
-}
-func (p pointer) toFloat32Ptr() **float32 {
- return p.v.Interface().(**float32)
-}
-func (p pointer) toFloat32Slice() *[]float32 {
- return p.v.Interface().(*[]float32)
-}
-func (p pointer) toString() *string {
- return p.v.Interface().(*string)
-}
-func (p pointer) toStringPtr() **string {
- return p.v.Interface().(**string)
-}
-func (p pointer) toStringSlice() *[]string {
- return p.v.Interface().(*[]string)
-}
-func (p pointer) toBytes() *[]byte {
- return p.v.Interface().(*[]byte)
-}
-func (p pointer) toBytesSlice() *[][]byte {
- return p.v.Interface().(*[][]byte)
-}
-func (p pointer) toExtensions() *XXX_InternalExtensions {
- return p.v.Interface().(*XXX_InternalExtensions)
-}
-func (p pointer) toOldExtensions() *map[int32]Extension {
- return p.v.Interface().(*map[int32]Extension)
-}
-func (p pointer) getPointer() pointer {
- return pointer{v: p.v.Elem()}
-}
-func (p pointer) setPointer(q pointer) {
- p.v.Elem().Set(q.v)
-}
-func (p pointer) appendPointer(q pointer) {
- grow(p.v.Elem()).Set(q.v)
-}
-
-// getPointerSlice copies []*T from p as a new []pointer.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) getPointerSlice() []pointer {
- if p.v.IsNil() {
- return nil
- }
- n := p.v.Elem().Len()
- s := make([]pointer, n)
- for i := 0; i < n; i++ {
- s[i] = pointer{v: p.v.Elem().Index(i)}
- }
- return s
-}
-
-// setPointerSlice copies []pointer into p as a new []*T.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) setPointerSlice(v []pointer) {
- if v == nil {
- p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem())
- return
- }
- s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v))
- for _, p := range v {
- s = reflect.Append(s, p.v)
- }
- p.v.Elem().Set(s)
-}
-
-// getInterfacePointer returns a pointer that points to the
-// interface data of the interface pointed by p.
-func (p pointer) getInterfacePointer() pointer {
- if p.v.Elem().IsNil() {
- return pointer{v: p.v.Elem()}
- }
- return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct
-}
-
-func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
- // TODO: check that p.v.Type().Elem() == t?
- return p.v
-}
-
-func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-
-var atomicLock sync.Mutex
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
deleted file mode 100644
index d55a335d9..000000000
--- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
+++ /dev/null
@@ -1,308 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// +build !purego,!appengine,!js
-
-// This file contains the implementation of the proto field accesses using package unsafe.
-
-package proto
-
-import (
- "reflect"
- "sync/atomic"
- "unsafe"
-)
-
-const unsafeAllowed = true
-
-// A field identifies a field in a struct, accessible from a pointer.
-// In this implementation, a field is identified by its byte offset from the start of the struct.
-type field uintptr
-
-// toField returns a field equivalent to the given reflect field.
-func toField(f *reflect.StructField) field {
- return field(f.Offset)
-}
-
-// invalidField is an invalid field identifier.
-const invalidField = ^field(0)
-
-// zeroField is a noop when calling pointer.offset.
-const zeroField = field(0)
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool {
- return f != invalidField
-}
-
-// The pointer type below is for the new table-driven encoder/decoder.
-// The implementation here uses unsafe.Pointer to create a generic pointer.
-// In pointer_reflect.go we use reflect instead of unsafe to implement
-// the same (but slower) interface.
-type pointer struct {
- p unsafe.Pointer
-}
-
-// size of pointer
-var ptrSize = unsafe.Sizeof(uintptr(0))
-
-// toPointer converts an interface of pointer type to a pointer
-// that points to the same target.
-func toPointer(i *Message) pointer {
- // Super-tricky - read pointer out of data word of interface value.
- // Saves ~25ns over the equivalent:
- // return valToPointer(reflect.ValueOf(*i))
- return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
-}
-
-// toAddrPointer converts an interface to a pointer that points to
-// the interface data.
-func toAddrPointer(i *interface{}, isptr bool) pointer {
- // Super-tricky - read or get the address of data word of interface value.
- if isptr {
- // The interface is of pointer type, thus it is a direct interface.
- // The data word is the pointer data itself. We take its address.
- return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)}
- }
- // The interface is not of pointer type. The data word is the pointer
- // to the data.
- return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
-}
-
-// valToPointer converts v to a pointer. v must be of pointer type.
-func valToPointer(v reflect.Value) pointer {
- return pointer{p: unsafe.Pointer(v.Pointer())}
-}
-
-// offset converts from a pointer to a structure to a pointer to
-// one of its fields.
-func (p pointer) offset(f field) pointer {
- // For safety, we should panic if !f.IsValid, however calling panic causes
- // this to no longer be inlineable, which is a serious performance cost.
- /*
- if !f.IsValid() {
- panic("invalid field")
- }
- */
- return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))}
-}
-
-func (p pointer) isNil() bool {
- return p.p == nil
-}
-
-func (p pointer) toInt64() *int64 {
- return (*int64)(p.p)
-}
-func (p pointer) toInt64Ptr() **int64 {
- return (**int64)(p.p)
-}
-func (p pointer) toInt64Slice() *[]int64 {
- return (*[]int64)(p.p)
-}
-func (p pointer) toInt32() *int32 {
- return (*int32)(p.p)
-}
-
-// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist.
-/*
- func (p pointer) toInt32Ptr() **int32 {
- return (**int32)(p.p)
- }
- func (p pointer) toInt32Slice() *[]int32 {
- return (*[]int32)(p.p)
- }
-*/
-func (p pointer) getInt32Ptr() *int32 {
- return *(**int32)(p.p)
-}
-func (p pointer) setInt32Ptr(v int32) {
- *(**int32)(p.p) = &v
-}
-
-// getInt32Slice loads a []int32 from p.
-// The value returned is aliased with the original slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) getInt32Slice() []int32 {
- return *(*[]int32)(p.p)
-}
-
-// setInt32Slice stores a []int32 to p.
-// The value set is aliased with the input slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) setInt32Slice(v []int32) {
- *(*[]int32)(p.p) = v
-}
-
-// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead?
-func (p pointer) appendInt32Slice(v int32) {
- s := (*[]int32)(p.p)
- *s = append(*s, v)
-}
-
-func (p pointer) toUint64() *uint64 {
- return (*uint64)(p.p)
-}
-func (p pointer) toUint64Ptr() **uint64 {
- return (**uint64)(p.p)
-}
-func (p pointer) toUint64Slice() *[]uint64 {
- return (*[]uint64)(p.p)
-}
-func (p pointer) toUint32() *uint32 {
- return (*uint32)(p.p)
-}
-func (p pointer) toUint32Ptr() **uint32 {
- return (**uint32)(p.p)
-}
-func (p pointer) toUint32Slice() *[]uint32 {
- return (*[]uint32)(p.p)
-}
-func (p pointer) toBool() *bool {
- return (*bool)(p.p)
-}
-func (p pointer) toBoolPtr() **bool {
- return (**bool)(p.p)
-}
-func (p pointer) toBoolSlice() *[]bool {
- return (*[]bool)(p.p)
-}
-func (p pointer) toFloat64() *float64 {
- return (*float64)(p.p)
-}
-func (p pointer) toFloat64Ptr() **float64 {
- return (**float64)(p.p)
-}
-func (p pointer) toFloat64Slice() *[]float64 {
- return (*[]float64)(p.p)
-}
-func (p pointer) toFloat32() *float32 {
- return (*float32)(p.p)
-}
-func (p pointer) toFloat32Ptr() **float32 {
- return (**float32)(p.p)
-}
-func (p pointer) toFloat32Slice() *[]float32 {
- return (*[]float32)(p.p)
-}
-func (p pointer) toString() *string {
- return (*string)(p.p)
-}
-func (p pointer) toStringPtr() **string {
- return (**string)(p.p)
-}
-func (p pointer) toStringSlice() *[]string {
- return (*[]string)(p.p)
-}
-func (p pointer) toBytes() *[]byte {
- return (*[]byte)(p.p)
-}
-func (p pointer) toBytesSlice() *[][]byte {
- return (*[][]byte)(p.p)
-}
-func (p pointer) toExtensions() *XXX_InternalExtensions {
- return (*XXX_InternalExtensions)(p.p)
-}
-func (p pointer) toOldExtensions() *map[int32]Extension {
- return (*map[int32]Extension)(p.p)
-}
-
-// getPointerSlice loads []*T from p as a []pointer.
-// The value returned is aliased with the original slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) getPointerSlice() []pointer {
- // Super-tricky - p should point to a []*T where T is a
- // message type. We load it as []pointer.
- return *(*[]pointer)(p.p)
-}
-
-// setPointerSlice stores []pointer into p as a []*T.
-// The value set is aliased with the input slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) setPointerSlice(v []pointer) {
- // Super-tricky - p should point to a []*T where T is a
- // message type. We store it as []pointer.
- *(*[]pointer)(p.p) = v
-}
-
-// getPointer loads the pointer at p and returns it.
-func (p pointer) getPointer() pointer {
- return pointer{p: *(*unsafe.Pointer)(p.p)}
-}
-
-// setPointer stores the pointer q at p.
-func (p pointer) setPointer(q pointer) {
- *(*unsafe.Pointer)(p.p) = q.p
-}
-
-// append q to the slice pointed to by p.
-func (p pointer) appendPointer(q pointer) {
- s := (*[]unsafe.Pointer)(p.p)
- *s = append(*s, q.p)
-}
-
-// getInterfacePointer returns a pointer that points to the
-// interface data of the interface pointed by p.
-func (p pointer) getInterfacePointer() pointer {
- // Super-tricky - read pointer out of data word of interface value.
- return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]}
-}
-
-// asPointerTo returns a reflect.Value that is a pointer to an
-// object of type t stored at p.
-func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
- return reflect.NewAt(t, p.p)
-}
-
-func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
- return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
- return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
- return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
- return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go
index f710adab0..dcdc2202f 100644
--- a/vendor/github.com/golang/protobuf/proto/properties.go
+++ b/vendor/github.com/golang/protobuf/proto/properties.go
@@ -1,163 +1,104 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package proto
-/*
- * Routines for encoding data into the wire format for protocol buffers.
- */
-
import (
"fmt"
- "log"
- "os"
"reflect"
- "sort"
"strconv"
"strings"
"sync"
-)
-
-const debug bool = false
-// Constants that identify the encoding of a value on the wire.
-const (
- WireVarint = 0
- WireFixed64 = 1
- WireBytes = 2
- WireStartGroup = 3
- WireEndGroup = 4
- WireFixed32 = 5
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/runtime/protoimpl"
)
-// tagMap is an optimization over map[int]int for typical protocol buffer
-// use-cases. Encoded protocol buffers are often in tag order with small tag
-// numbers.
-type tagMap struct {
- fastTags []int
- slowTags map[int]int
-}
-
-// tagMapFastLimit is the upper bound on the tag number that will be stored in
-// the tagMap slice rather than its map.
-const tagMapFastLimit = 1024
-
-func (p *tagMap) get(t int) (int, bool) {
- if t > 0 && t < tagMapFastLimit {
- if t >= len(p.fastTags) {
- return 0, false
- }
- fi := p.fastTags[t]
- return fi, fi >= 0
- }
- fi, ok := p.slowTags[t]
- return fi, ok
-}
-
-func (p *tagMap) put(t int, fi int) {
- if t > 0 && t < tagMapFastLimit {
- for len(p.fastTags) < t+1 {
- p.fastTags = append(p.fastTags, -1)
- }
- p.fastTags[t] = fi
- return
- }
- if p.slowTags == nil {
- p.slowTags = make(map[int]int)
- }
- p.slowTags[t] = fi
-}
-
-// StructProperties represents properties for all the fields of a struct.
-// decoderTags and decoderOrigNames should only be used by the decoder.
+// StructProperties represents protocol buffer type information for a
+// generated protobuf message in the open-struct API.
+//
+// Deprecated: Do not use.
type StructProperties struct {
- Prop []*Properties // properties for each field
- reqCount int // required count
- decoderTags tagMap // map from proto tag to struct field number
- decoderOrigNames map[string]int // map from original name to struct field number
- order []int // list of struct field numbers in tag order
+ // Prop are the properties for each field.
+ //
+ // Fields belonging to a oneof are stored in OneofTypes instead, with a
+ // single Properties representing the parent oneof held here.
+ //
+ // The order of Prop matches the order of fields in the Go struct.
+ // Struct fields that are not related to protobufs have a "XXX_" prefix
+ // in the Properties.Name and must be ignored by the user.
+ Prop []*Properties
// OneofTypes contains information about the oneof fields in this message.
- // It is keyed by the original name of a field.
+ // It is keyed by the protobuf field name.
OneofTypes map[string]*OneofProperties
}
-// OneofProperties represents information about a specific field in a oneof.
-type OneofProperties struct {
- Type reflect.Type // pointer to generated struct type for this oneof field
- Field int // struct field number of the containing oneof in the message
- Prop *Properties
-}
-
-// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
-// See encode.go, (*Buffer).enc_struct.
-
-func (sp *StructProperties) Len() int { return len(sp.order) }
-func (sp *StructProperties) Less(i, j int) bool {
- return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
-}
-func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
-
-// Properties represents the protocol-specific behavior of a single struct field.
+// Properties represents the type information for a protobuf message field.
+//
+// Deprecated: Do not use.
type Properties struct {
- Name string // name of the field, for error messages
- OrigName string // original name before protocol compiler (always set)
- JSONName string // name to use for JSON; determined by protoc
- Wire string
+ // Name is a placeholder name with little meaningful semantic value.
+ // If the name has an "XXX_" prefix, the entire Properties must be ignored.
+ Name string
+ // OrigName is the protobuf field name or oneof name.
+ OrigName string
+ // JSONName is the JSON name for the protobuf field.
+ JSONName string
+ // Enum is a placeholder name for enums.
+ // For historical reasons, this is neither the Go name for the enum,
+ // nor the protobuf name for the enum.
+ Enum string // Deprecated: Do not use.
+ // Weak contains the full name of the weakly referenced message.
+ Weak string
+ // Wire is a string representation of the wire type.
+ Wire string
+ // WireType is the protobuf wire type for the field.
WireType int
- Tag int
+ // Tag is the protobuf field number.
+ Tag int
+ // Required reports whether this is a required field.
Required bool
+ // Optional reports whether this is a optional field.
Optional bool
+ // Repeated reports whether this is a repeated field.
Repeated bool
- Packed bool // relevant for repeated primitives only
- Enum string // set for enum types only
- proto3 bool // whether this is known to be a proto3 field; set for []byte only
- oneof bool // whether this is a oneof field
-
- Default string // default value
- HasDefault bool // whether an explicit default was provided
-
- stype reflect.Type // set for struct types only
- sprop *StructProperties // set for struct types only
+ // Packed reports whether this is a packed repeated field of scalars.
+ Packed bool
+ // Proto3 reports whether this field operates under the proto3 syntax.
+ Proto3 bool
+ // Oneof reports whether this field belongs within a oneof.
+ Oneof bool
+
+ // Default is the default value in string form.
+ Default string
+ // HasDefault reports whether the field has a default value.
+ HasDefault bool
+
+ // MapKeyProp is the properties for the key field for a map field.
+ MapKeyProp *Properties
+ // MapValProp is the properties for the value field for a map field.
+ MapValProp *Properties
+}
- mtype reflect.Type // set for map types only
- mkeyprop *Properties // set for map types only
- mvalprop *Properties // set for map types only
+// OneofProperties represents the type information for a protobuf oneof.
+//
+// Deprecated: Do not use.
+type OneofProperties struct {
+ // Type is a pointer to the generated wrapper type for the field value.
+ // This is nil for messages that are not in the open-struct API.
+ Type reflect.Type
+ // Field is the index into StructProperties.Prop for the containing oneof.
+ Field int
+ // Prop is the properties for the field.
+ Prop *Properties
}
// String formats the properties in the protobuf struct field tag style.
func (p *Properties) String() string {
s := p.Wire
- s += ","
- s += strconv.Itoa(p.Tag)
+ s += "," + strconv.Itoa(p.Tag)
if p.Required {
s += ",req"
}
@@ -171,18 +112,21 @@ func (p *Properties) String() string {
s += ",packed"
}
s += ",name=" + p.OrigName
- if p.JSONName != p.OrigName {
+ if p.JSONName != "" {
s += ",json=" + p.JSONName
}
- if p.proto3 {
+ if len(p.Enum) > 0 {
+ s += ",enum=" + p.Enum
+ }
+ if len(p.Weak) > 0 {
+ s += ",weak=" + p.Weak
+ }
+ if p.Proto3 {
s += ",proto3"
}
- if p.oneof {
+ if p.Oneof {
s += ",oneof"
}
- if len(p.Enum) > 0 {
- s += ",enum=" + p.Enum
- }
if p.HasDefault {
s += ",def=" + p.Default
}
@@ -190,355 +134,173 @@ func (p *Properties) String() string {
}
// Parse populates p by parsing a string in the protobuf struct field tag style.
-func (p *Properties) Parse(s string) {
- // "bytes,49,opt,name=foo,def=hello!"
- fields := strings.Split(s, ",") // breaks def=, but handled below.
- if len(fields) < 2 {
- fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
- return
- }
-
- p.Wire = fields[0]
- switch p.Wire {
- case "varint":
- p.WireType = WireVarint
- case "fixed32":
- p.WireType = WireFixed32
- case "fixed64":
- p.WireType = WireFixed64
- case "zigzag32":
- p.WireType = WireVarint
- case "zigzag64":
- p.WireType = WireVarint
- case "bytes", "group":
- p.WireType = WireBytes
- // no numeric converter for non-numeric types
- default:
- fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
- return
- }
-
- var err error
- p.Tag, err = strconv.Atoi(fields[1])
- if err != nil {
- return
- }
-
-outer:
- for i := 2; i < len(fields); i++ {
- f := fields[i]
- switch {
- case f == "req":
- p.Required = true
- case f == "opt":
+func (p *Properties) Parse(tag string) {
+ // For example: "bytes,49,opt,name=foo,def=hello!"
+ for len(tag) > 0 {
+ i := strings.IndexByte(tag, ',')
+ if i < 0 {
+ i = len(tag)
+ }
+ switch s := tag[:i]; {
+ case strings.HasPrefix(s, "name="):
+ p.OrigName = s[len("name="):]
+ case strings.HasPrefix(s, "json="):
+ p.JSONName = s[len("json="):]
+ case strings.HasPrefix(s, "enum="):
+ p.Enum = s[len("enum="):]
+ case strings.HasPrefix(s, "weak="):
+ p.Weak = s[len("weak="):]
+ case strings.Trim(s, "0123456789") == "":
+ n, _ := strconv.ParseUint(s, 10, 32)
+ p.Tag = int(n)
+ case s == "opt":
p.Optional = true
- case f == "rep":
+ case s == "req":
+ p.Required = true
+ case s == "rep":
p.Repeated = true
- case f == "packed":
+ case s == "varint" || s == "zigzag32" || s == "zigzag64":
+ p.Wire = s
+ p.WireType = WireVarint
+ case s == "fixed32":
+ p.Wire = s
+ p.WireType = WireFixed32
+ case s == "fixed64":
+ p.Wire = s
+ p.WireType = WireFixed64
+ case s == "bytes":
+ p.Wire = s
+ p.WireType = WireBytes
+ case s == "group":
+ p.Wire = s
+ p.WireType = WireStartGroup
+ case s == "packed":
p.Packed = true
- case strings.HasPrefix(f, "name="):
- p.OrigName = f[5:]
- case strings.HasPrefix(f, "json="):
- p.JSONName = f[5:]
- case strings.HasPrefix(f, "enum="):
- p.Enum = f[5:]
- case f == "proto3":
- p.proto3 = true
- case f == "oneof":
- p.oneof = true
- case strings.HasPrefix(f, "def="):
+ case s == "proto3":
+ p.Proto3 = true
+ case s == "oneof":
+ p.Oneof = true
+ case strings.HasPrefix(s, "def="):
+ // The default tag is special in that everything afterwards is the
+ // default regardless of the presence of commas.
p.HasDefault = true
- p.Default = f[4:] // rest of string
- if i+1 < len(fields) {
- // Commas aren't escaped, and def is always last.
- p.Default += "," + strings.Join(fields[i+1:], ",")
- break outer
- }
- }
- }
-}
-
-var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
-
-// setFieldProps initializes the field properties for submessages and maps.
-func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
- switch t1 := typ; t1.Kind() {
- case reflect.Ptr:
- if t1.Elem().Kind() == reflect.Struct {
- p.stype = t1.Elem()
- }
-
- case reflect.Slice:
- if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct {
- p.stype = t2.Elem()
- }
-
- case reflect.Map:
- p.mtype = t1
- p.mkeyprop = &Properties{}
- p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
- p.mvalprop = &Properties{}
- vtype := p.mtype.Elem()
- if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
- // The value type is not a message (*T) or bytes ([]byte),
- // so we need encoders for the pointer to this type.
- vtype = reflect.PtrTo(vtype)
- }
- p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
- }
-
- if p.stype != nil {
- if lockGetProp {
- p.sprop = GetProperties(p.stype)
- } else {
- p.sprop = getPropertiesLocked(p.stype)
+ p.Default, i = tag[len("def="):], len(tag)
}
+ tag = strings.TrimPrefix(tag[i:], ",")
}
}
-var (
- marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
-)
-
// Init populates the properties from a protocol buffer struct tag.
+//
+// Deprecated: Do not use.
func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
- p.init(typ, name, tag, f, true)
-}
-
-func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
- // "bytes,49,opt,def=hello!"
p.Name = name
p.OrigName = name
if tag == "" {
return
}
p.Parse(tag)
- p.setFieldProps(typ, f, lockGetProp)
+
+ if typ != nil && typ.Kind() == reflect.Map {
+ p.MapKeyProp = new(Properties)
+ p.MapKeyProp.Init(nil, "Key", f.Tag.Get("protobuf_key"), nil)
+ p.MapValProp = new(Properties)
+ p.MapValProp.Init(nil, "Value", f.Tag.Get("protobuf_val"), nil)
+ }
}
-var (
- propertiesMu sync.RWMutex
- propertiesMap = make(map[reflect.Type]*StructProperties)
-)
+var propertiesCache sync.Map // map[reflect.Type]*StructProperties
-// GetProperties returns the list of properties for the type represented by t.
-// t must represent a generated struct type of a protocol message.
+// GetProperties returns the list of properties for the type represented by t,
+// which must be a generated protocol buffer message in the open-struct API,
+// where protobuf message fields are represented by exported Go struct fields.
+//
+// Deprecated: Use protobuf reflection instead.
func GetProperties(t reflect.Type) *StructProperties {
- if t.Kind() != reflect.Struct {
- panic("proto: type must have kind struct")
- }
-
- // Most calls to GetProperties in a long-running program will be
- // retrieving details for types we have seen before.
- propertiesMu.RLock()
- sprop, ok := propertiesMap[t]
- propertiesMu.RUnlock()
- if ok {
- if collectStats {
- stats.Chit++
- }
- return sprop
+ if p, ok := propertiesCache.Load(t); ok {
+ return p.(*StructProperties)
}
-
- propertiesMu.Lock()
- sprop = getPropertiesLocked(t)
- propertiesMu.Unlock()
- return sprop
+ p, _ := propertiesCache.LoadOrStore(t, newProperties(t))
+ return p.(*StructProperties)
}
-// getPropertiesLocked requires that propertiesMu is held.
-func getPropertiesLocked(t reflect.Type) *StructProperties {
- if prop, ok := propertiesMap[t]; ok {
- if collectStats {
- stats.Chit++
- }
- return prop
- }
- if collectStats {
- stats.Cmiss++
+func newProperties(t reflect.Type) *StructProperties {
+ if t.Kind() != reflect.Struct {
+ panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t))
}
+ var hasOneof bool
prop := new(StructProperties)
- // in case of recursive protos, fill this in now.
- propertiesMap[t] = prop
-
- // build properties
- prop.Prop = make([]*Properties, t.NumField())
- prop.order = make([]int, t.NumField())
+ // Construct a list of properties for each field in the struct.
for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
p := new(Properties)
- name := f.Name
- p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
+ f := t.Field(i)
+ tagField := f.Tag.Get("protobuf")
+ p.Init(f.Type, f.Name, tagField, &f)
- oneof := f.Tag.Get("protobuf_oneof") // special case
- if oneof != "" {
- // Oneof fields don't use the traditional protobuf tag.
- p.OrigName = oneof
- }
- prop.Prop[i] = p
- prop.order[i] = i
- if debug {
- print(i, " ", f.Name, " ", t.String(), " ")
- if p.Tag > 0 {
- print(p.String())
- }
- print("\n")
+ tagOneof := f.Tag.Get("protobuf_oneof")
+ if tagOneof != "" {
+ hasOneof = true
+ p.OrigName = tagOneof
}
- }
- // Re-order prop.order.
- sort.Sort(prop)
+ // Rename unrelated struct fields with the "XXX_" prefix since so much
+ // user code simply checks for this to exclude special fields.
+ if tagField == "" && tagOneof == "" && !strings.HasPrefix(p.Name, "XXX_") {
+ p.Name = "XXX_" + p.Name
+ p.OrigName = "XXX_" + p.OrigName
+ } else if p.Weak != "" {
+ p.Name = p.OrigName // avoid possible "XXX_" prefix on weak field
+ }
- type oneofMessage interface {
- XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
+ prop.Prop = append(prop.Prop, p)
}
- if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok {
- var oots []interface{}
- _, _, _, oots = om.XXX_OneofFuncs()
- // Interpret oneof metadata.
+ // Construct a mapping of oneof field names to properties.
+ if hasOneof {
+ var oneofWrappers []interface{}
+ if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
+ oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
+ }
+ if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
+ oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
+ }
+ if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(protoreflect.ProtoMessage); ok {
+ if m, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *protoimpl.MessageInfo }); ok {
+ oneofWrappers = m.ProtoMessageInfo().OneofWrappers
+ }
+ }
+
prop.OneofTypes = make(map[string]*OneofProperties)
- for _, oot := range oots {
- oop := &OneofProperties{
- Type: reflect.ValueOf(oot).Type(), // *T
+ for _, wrapper := range oneofWrappers {
+ p := &OneofProperties{
+ Type: reflect.ValueOf(wrapper).Type(), // *T
Prop: new(Properties),
}
- sft := oop.Type.Elem().Field(0)
- oop.Prop.Name = sft.Name
- oop.Prop.Parse(sft.Tag.Get("protobuf"))
- // There will be exactly one interface field that
- // this new value is assignable to.
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- if f.Type.Kind() != reflect.Interface {
- continue
+ f := p.Type.Elem().Field(0)
+ p.Prop.Name = f.Name
+ p.Prop.Parse(f.Tag.Get("protobuf"))
+
+ // Determine the struct field that contains this oneof.
+ // Each wrapper is assignable to exactly one parent field.
+ var foundOneof bool
+ for i := 0; i < t.NumField() && !foundOneof; i++ {
+ if p.Type.AssignableTo(t.Field(i).Type) {
+ p.Field = i
+ foundOneof = true
}
- if !oop.Type.AssignableTo(f.Type) {
- continue
- }
- oop.Field = i
- break
}
- prop.OneofTypes[oop.Prop.OrigName] = oop
- }
- }
-
- // build required counts
- // build tags
- reqCount := 0
- prop.decoderOrigNames = make(map[string]int)
- for i, p := range prop.Prop {
- if strings.HasPrefix(p.Name, "XXX_") {
- // Internal fields should not appear in tags/origNames maps.
- // They are handled specially when encoding and decoding.
- continue
- }
- if p.Required {
- reqCount++
+ if !foundOneof {
+ panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t))
+ }
+ prop.OneofTypes[p.Prop.OrigName] = p
}
- prop.decoderTags.put(p.Tag, i)
- prop.decoderOrigNames[p.OrigName] = i
}
- prop.reqCount = reqCount
return prop
}
-// A global registry of enum types.
-// The generated code will register the generated maps by calling RegisterEnum.
-
-var enumValueMaps = make(map[string]map[string]int32)
-
-// RegisterEnum is called from the generated code to install the enum descriptor
-// maps into the global table to aid parsing text format protocol buffers.
-func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
- if _, ok := enumValueMaps[typeName]; ok {
- panic("proto: duplicate enum registered: " + typeName)
- }
- enumValueMaps[typeName] = valueMap
-}
-
-// EnumValueMap returns the mapping from names to integers of the
-// enum type enumType, or a nil if not found.
-func EnumValueMap(enumType string) map[string]int32 {
- return enumValueMaps[enumType]
-}
-
-// A registry of all linked message types.
-// The string is a fully-qualified proto name ("pkg.Message").
-var (
- protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers
- protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types
- revProtoTypes = make(map[reflect.Type]string)
-)
-
-// RegisterType is called from generated code and maps from the fully qualified
-// proto name to the type (pointer to struct) of the protocol buffer.
-func RegisterType(x Message, name string) {
- if _, ok := protoTypedNils[name]; ok {
- // TODO: Some day, make this a panic.
- log.Printf("proto: duplicate proto type registered: %s", name)
- return
- }
- t := reflect.TypeOf(x)
- if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
- // Generated code always calls RegisterType with nil x.
- // This check is just for extra safety.
- protoTypedNils[name] = x
- } else {
- protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
- }
- revProtoTypes[t] = name
-}
-
-// RegisterMapType is called from generated code and maps from the fully qualified
-// proto name to the native map type of the proto map definition.
-func RegisterMapType(x interface{}, name string) {
- if reflect.TypeOf(x).Kind() != reflect.Map {
- panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
- }
- if _, ok := protoMapTypes[name]; ok {
- log.Printf("proto: duplicate proto type registered: %s", name)
- return
- }
- t := reflect.TypeOf(x)
- protoMapTypes[name] = t
- revProtoTypes[t] = name
-}
-
-// MessageName returns the fully-qualified proto name for the given message type.
-func MessageName(x Message) string {
- type xname interface {
- XXX_MessageName() string
- }
- if m, ok := x.(xname); ok {
- return m.XXX_MessageName()
- }
- return revProtoTypes[reflect.TypeOf(x)]
-}
-
-// MessageType returns the message type (pointer to struct) for a named message.
-// The type is not guaranteed to implement proto.Message if the name refers to a
-// map entry.
-func MessageType(name string) reflect.Type {
- if t, ok := protoTypedNils[name]; ok {
- return reflect.TypeOf(t)
- }
- return protoMapTypes[name]
-}
-
-// A registry of all linked proto files.
-var (
- protoFiles = make(map[string][]byte) // file name => fileDescriptor
-)
-
-// RegisterFile is called from generated code and maps from the
-// full file name of a .proto file to its compressed FileDescriptorProto.
-func RegisterFile(filename string, fileDescriptor []byte) {
- protoFiles[filename] = fileDescriptor
-}
-
-// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
-func FileDescriptor(filename string) []byte { return protoFiles[filename] }
+func (sp *StructProperties) Len() int { return len(sp.Prop) }
+func (sp *StructProperties) Less(i, j int) bool { return false }
+func (sp *StructProperties) Swap(i, j int) { return }
diff --git a/vendor/github.com/golang/protobuf/proto/proto.go b/vendor/github.com/golang/protobuf/proto/proto.go
new file mode 100644
index 000000000..5aee89c32
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/proto.go
@@ -0,0 +1,167 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package proto provides functionality for handling protocol buffer messages.
+// In particular, it provides marshaling and unmarshaling between a protobuf
+// message and the binary wire format.
+//
+// See https://developers.google.com/protocol-buffers/docs/gotutorial for
+// more information.
+//
+// Deprecated: Use the "google.golang.org/protobuf/proto" package instead.
+package proto
+
+import (
+ protoV2 "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/runtime/protoiface"
+ "google.golang.org/protobuf/runtime/protoimpl"
+)
+
+const (
+ ProtoPackageIsVersion1 = true
+ ProtoPackageIsVersion2 = true
+ ProtoPackageIsVersion3 = true
+ ProtoPackageIsVersion4 = true
+)
+
+// GeneratedEnum is any enum type generated by protoc-gen-go
+// which is a named int32 kind.
+// This type exists for documentation purposes.
+type GeneratedEnum interface{}
+
+// GeneratedMessage is any message type generated by protoc-gen-go
+// which is a pointer to a named struct kind.
+// This type exists for documentation purposes.
+type GeneratedMessage interface{}
+
+// Message is a protocol buffer message.
+//
+// This is the v1 version of the message interface and is marginally better
+// than an empty interface as it lacks any method to programatically interact
+// with the contents of the message.
+//
+// A v2 message is declared in "google.golang.org/protobuf/proto".Message and
+// exposes protobuf reflection as a first-class feature of the interface.
+//
+// To convert a v1 message to a v2 message, use the MessageV2 function.
+// To convert a v2 message to a v1 message, use the MessageV1 function.
+type Message = protoiface.MessageV1
+
+// MessageV1 converts either a v1 or v2 message to a v1 message.
+// It returns nil if m is nil.
+func MessageV1(m GeneratedMessage) protoiface.MessageV1 {
+ return protoimpl.X.ProtoMessageV1Of(m)
+}
+
+// MessageV2 converts either a v1 or v2 message to a v2 message.
+// It returns nil if m is nil.
+func MessageV2(m GeneratedMessage) protoV2.Message {
+ return protoimpl.X.ProtoMessageV2Of(m)
+}
+
+// MessageReflect returns a reflective view for a message.
+// It returns nil if m is nil.
+func MessageReflect(m Message) protoreflect.Message {
+ return protoimpl.X.MessageOf(m)
+}
+
+// Marshaler is implemented by messages that can marshal themselves.
+// This interface is used by the following functions: Size, Marshal,
+// Buffer.Marshal, and Buffer.EncodeMessage.
+//
+// Deprecated: Do not implement.
+type Marshaler interface {
+ // Marshal formats the encoded bytes of the message.
+ // It should be deterministic and emit valid protobuf wire data.
+ // The caller takes ownership of the returned buffer.
+ Marshal() ([]byte, error)
+}
+
+// Unmarshaler is implemented by messages that can unmarshal themselves.
+// This interface is used by the following functions: Unmarshal, UnmarshalMerge,
+// Buffer.Unmarshal, Buffer.DecodeMessage, and Buffer.DecodeGroup.
+//
+// Deprecated: Do not implement.
+type Unmarshaler interface {
+ // Unmarshal parses the encoded bytes of the protobuf wire input.
+ // The provided buffer is only valid for during method call.
+ // It should not reset the receiver message.
+ Unmarshal([]byte) error
+}
+
+// Merger is implemented by messages that can merge themselves.
+// This interface is used by the following functions: Clone and Merge.
+//
+// Deprecated: Do not implement.
+type Merger interface {
+ // Merge merges the contents of src into the receiver message.
+ // It clones all data structures in src such that it aliases no mutable
+ // memory referenced by src.
+ Merge(src Message)
+}
+
+// RequiredNotSetError is an error type returned when
+// marshaling or unmarshaling a message with missing required fields.
+type RequiredNotSetError struct {
+ err error
+}
+
+func (e *RequiredNotSetError) Error() string {
+ if e.err != nil {
+ return e.err.Error()
+ }
+ return "proto: required field not set"
+}
+func (e *RequiredNotSetError) RequiredNotSet() bool {
+ return true
+}
+
+func checkRequiredNotSet(m protoV2.Message) error {
+ if err := protoV2.CheckInitialized(m); err != nil {
+ return &RequiredNotSetError{err: err}
+ }
+ return nil
+}
+
+// Clone returns a deep copy of src.
+func Clone(src Message) Message {
+ return MessageV1(protoV2.Clone(MessageV2(src)))
+}
+
+// Merge merges src into dst, which must be messages of the same type.
+//
+// Populated scalar fields in src are copied to dst, while populated
+// singular messages in src are merged into dst by recursively calling Merge.
+// The elements of every list field in src is appended to the corresponded
+// list fields in dst. The entries of every map field in src is copied into
+// the corresponding map field in dst, possibly replacing existing entries.
+// The unknown fields of src are appended to the unknown fields of dst.
+func Merge(dst, src Message) {
+ protoV2.Merge(MessageV2(dst), MessageV2(src))
+}
+
+// Equal reports whether two messages are equal.
+// If two messages marshal to the same bytes under deterministic serialization,
+// then Equal is guaranteed to report true.
+//
+// Two messages are equal if they are the same protobuf message type,
+// have the same set of populated known and extension field values,
+// and the same set of unknown fields values.
+//
+// Scalar values are compared with the equivalent of the == operator in Go,
+// except bytes values which are compared using bytes.Equal and
+// floating point values which specially treat NaNs as equal.
+// Message values are compared by recursively calling Equal.
+// Lists are equal if each element value is also equal.
+// Maps are equal if they have the same set of keys, where the pair of values
+// for each key is also equal.
+func Equal(x, y Message) bool {
+ return protoV2.Equal(MessageV2(x), MessageV2(y))
+}
+
+func isMessageSet(md protoreflect.MessageDescriptor) bool {
+ ms, ok := md.(interface{ IsMessageSet() bool })
+ return ok && ms.IsMessageSet()
+}
diff --git a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
deleted file mode 100644
index a80f08930..000000000
--- a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
+++ /dev/null
@@ -1,461 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: proto3_proto/proto3.proto
-
-package proto3_proto
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import test_proto "github.com/golang/protobuf/proto/test_proto"
-import any "github.com/golang/protobuf/ptypes/any"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type Message_Humour int32
-
-const (
- Message_UNKNOWN Message_Humour = 0
- Message_PUNS Message_Humour = 1
- Message_SLAPSTICK Message_Humour = 2
- Message_BILL_BAILEY Message_Humour = 3
-)
-
-var Message_Humour_name = map[int32]string{
- 0: "UNKNOWN",
- 1: "PUNS",
- 2: "SLAPSTICK",
- 3: "BILL_BAILEY",
-}
-var Message_Humour_value = map[string]int32{
- "UNKNOWN": 0,
- "PUNS": 1,
- "SLAPSTICK": 2,
- "BILL_BAILEY": 3,
-}
-
-func (x Message_Humour) String() string {
- return proto.EnumName(Message_Humour_name, int32(x))
-}
-func (Message_Humour) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_proto3_e706e4ff19a5dbea, []int{0, 0}
-}
-
-type Message struct {
- Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"`
- HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"`
- Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
- ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"`
- TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"`
- Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"`
- Key []uint64 `protobuf:"varint,5,rep,packed,name=key" json:"key,omitempty"`
- ShortKey []int32 `protobuf:"varint,19,rep,packed,name=short_key,json=shortKey" json:"short_key,omitempty"`
- Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"`
- RFunny []Message_Humour `protobuf:"varint,16,rep,packed,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"`
- Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Proto2Field *test_proto.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"`
- Proto2Value map[string]*test_proto.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Anything *any.Any `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"`
- ManyThings []*any.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"`
- Submessage *Message `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"`
- Children []*Message `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"`
- StringMap map[string]string `protobuf:"bytes,20,rep,name=string_map,json=stringMap" json:"string_map,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Message) Reset() { *m = Message{} }
-func (m *Message) String() string { return proto.CompactTextString(m) }
-func (*Message) ProtoMessage() {}
-func (*Message) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_e706e4ff19a5dbea, []int{0}
-}
-func (m *Message) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Message.Unmarshal(m, b)
-}
-func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Message.Marshal(b, m, deterministic)
-}
-func (dst *Message) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Message.Merge(dst, src)
-}
-func (m *Message) XXX_Size() int {
- return xxx_messageInfo_Message.Size(m)
-}
-func (m *Message) XXX_DiscardUnknown() {
- xxx_messageInfo_Message.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Message proto.InternalMessageInfo
-
-func (m *Message) GetName() string {
- if m != nil {
- return m.Name
- }
- return ""
-}
-
-func (m *Message) GetHilarity() Message_Humour {
- if m != nil {
- return m.Hilarity
- }
- return Message_UNKNOWN
-}
-
-func (m *Message) GetHeightInCm() uint32 {
- if m != nil {
- return m.HeightInCm
- }
- return 0
-}
-
-func (m *Message) GetData() []byte {
- if m != nil {
- return m.Data
- }
- return nil
-}
-
-func (m *Message) GetResultCount() int64 {
- if m != nil {
- return m.ResultCount
- }
- return 0
-}
-
-func (m *Message) GetTrueScotsman() bool {
- if m != nil {
- return m.TrueScotsman
- }
- return false
-}
-
-func (m *Message) GetScore() float32 {
- if m != nil {
- return m.Score
- }
- return 0
-}
-
-func (m *Message) GetKey() []uint64 {
- if m != nil {
- return m.Key
- }
- return nil
-}
-
-func (m *Message) GetShortKey() []int32 {
- if m != nil {
- return m.ShortKey
- }
- return nil
-}
-
-func (m *Message) GetNested() *Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *Message) GetRFunny() []Message_Humour {
- if m != nil {
- return m.RFunny
- }
- return nil
-}
-
-func (m *Message) GetTerrain() map[string]*Nested {
- if m != nil {
- return m.Terrain
- }
- return nil
-}
-
-func (m *Message) GetProto2Field() *test_proto.SubDefaults {
- if m != nil {
- return m.Proto2Field
- }
- return nil
-}
-
-func (m *Message) GetProto2Value() map[string]*test_proto.SubDefaults {
- if m != nil {
- return m.Proto2Value
- }
- return nil
-}
-
-func (m *Message) GetAnything() *any.Any {
- if m != nil {
- return m.Anything
- }
- return nil
-}
-
-func (m *Message) GetManyThings() []*any.Any {
- if m != nil {
- return m.ManyThings
- }
- return nil
-}
-
-func (m *Message) GetSubmessage() *Message {
- if m != nil {
- return m.Submessage
- }
- return nil
-}
-
-func (m *Message) GetChildren() []*Message {
- if m != nil {
- return m.Children
- }
- return nil
-}
-
-func (m *Message) GetStringMap() map[string]string {
- if m != nil {
- return m.StringMap
- }
- return nil
-}
-
-type Nested struct {
- Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"`
- Cute bool `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Nested) Reset() { *m = Nested{} }
-func (m *Nested) String() string { return proto.CompactTextString(m) }
-func (*Nested) ProtoMessage() {}
-func (*Nested) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_e706e4ff19a5dbea, []int{1}
-}
-func (m *Nested) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Nested.Unmarshal(m, b)
-}
-func (m *Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Nested.Marshal(b, m, deterministic)
-}
-func (dst *Nested) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Nested.Merge(dst, src)
-}
-func (m *Nested) XXX_Size() int {
- return xxx_messageInfo_Nested.Size(m)
-}
-func (m *Nested) XXX_DiscardUnknown() {
- xxx_messageInfo_Nested.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Nested proto.InternalMessageInfo
-
-func (m *Nested) GetBunny() string {
- if m != nil {
- return m.Bunny
- }
- return ""
-}
-
-func (m *Nested) GetCute() bool {
- if m != nil {
- return m.Cute
- }
- return false
-}
-
-type MessageWithMap struct {
- ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
-func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
-func (*MessageWithMap) ProtoMessage() {}
-func (*MessageWithMap) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_e706e4ff19a5dbea, []int{2}
-}
-func (m *MessageWithMap) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MessageWithMap.Unmarshal(m, b)
-}
-func (m *MessageWithMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MessageWithMap.Marshal(b, m, deterministic)
-}
-func (dst *MessageWithMap) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageWithMap.Merge(dst, src)
-}
-func (m *MessageWithMap) XXX_Size() int {
- return xxx_messageInfo_MessageWithMap.Size(m)
-}
-func (m *MessageWithMap) XXX_DiscardUnknown() {
- xxx_messageInfo_MessageWithMap.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MessageWithMap proto.InternalMessageInfo
-
-func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
- if m != nil {
- return m.ByteMapping
- }
- return nil
-}
-
-type IntMap struct {
- Rtt map[int32]int32 `protobuf:"bytes,1,rep,name=rtt" json:"rtt,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *IntMap) Reset() { *m = IntMap{} }
-func (m *IntMap) String() string { return proto.CompactTextString(m) }
-func (*IntMap) ProtoMessage() {}
-func (*IntMap) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_e706e4ff19a5dbea, []int{3}
-}
-func (m *IntMap) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_IntMap.Unmarshal(m, b)
-}
-func (m *IntMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_IntMap.Marshal(b, m, deterministic)
-}
-func (dst *IntMap) XXX_Merge(src proto.Message) {
- xxx_messageInfo_IntMap.Merge(dst, src)
-}
-func (m *IntMap) XXX_Size() int {
- return xxx_messageInfo_IntMap.Size(m)
-}
-func (m *IntMap) XXX_DiscardUnknown() {
- xxx_messageInfo_IntMap.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_IntMap proto.InternalMessageInfo
-
-func (m *IntMap) GetRtt() map[int32]int32 {
- if m != nil {
- return m.Rtt
- }
- return nil
-}
-
-type IntMaps struct {
- Maps []*IntMap `protobuf:"bytes,1,rep,name=maps" json:"maps,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *IntMaps) Reset() { *m = IntMaps{} }
-func (m *IntMaps) String() string { return proto.CompactTextString(m) }
-func (*IntMaps) ProtoMessage() {}
-func (*IntMaps) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_e706e4ff19a5dbea, []int{4}
-}
-func (m *IntMaps) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_IntMaps.Unmarshal(m, b)
-}
-func (m *IntMaps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_IntMaps.Marshal(b, m, deterministic)
-}
-func (dst *IntMaps) XXX_Merge(src proto.Message) {
- xxx_messageInfo_IntMaps.Merge(dst, src)
-}
-func (m *IntMaps) XXX_Size() int {
- return xxx_messageInfo_IntMaps.Size(m)
-}
-func (m *IntMaps) XXX_DiscardUnknown() {
- xxx_messageInfo_IntMaps.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_IntMaps proto.InternalMessageInfo
-
-func (m *IntMaps) GetMaps() []*IntMap {
- if m != nil {
- return m.Maps
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*Message)(nil), "proto3_proto.Message")
- proto.RegisterMapType((map[string]*test_proto.SubDefaults)(nil), "proto3_proto.Message.Proto2ValueEntry")
- proto.RegisterMapType((map[string]string)(nil), "proto3_proto.Message.StringMapEntry")
- proto.RegisterMapType((map[string]*Nested)(nil), "proto3_proto.Message.TerrainEntry")
- proto.RegisterType((*Nested)(nil), "proto3_proto.Nested")
- proto.RegisterType((*MessageWithMap)(nil), "proto3_proto.MessageWithMap")
- proto.RegisterMapType((map[bool][]byte)(nil), "proto3_proto.MessageWithMap.ByteMappingEntry")
- proto.RegisterType((*IntMap)(nil), "proto3_proto.IntMap")
- proto.RegisterMapType((map[int32]int32)(nil), "proto3_proto.IntMap.RttEntry")
- proto.RegisterType((*IntMaps)(nil), "proto3_proto.IntMaps")
- proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value)
-}
-
-func init() { proto.RegisterFile("proto3_proto/proto3.proto", fileDescriptor_proto3_e706e4ff19a5dbea) }
-
-var fileDescriptor_proto3_e706e4ff19a5dbea = []byte{
- // 774 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x94, 0x6f, 0x8f, 0xdb, 0x44,
- 0x10, 0xc6, 0x71, 0x9c, 0x3f, 0xce, 0xd8, 0x77, 0x35, 0x4b, 0x2a, 0xb6, 0x01, 0x24, 0x13, 0x10,
- 0xb2, 0x10, 0xf5, 0x41, 0xaa, 0x43, 0x55, 0x55, 0x81, 0xee, 0x8e, 0x56, 0x44, 0x77, 0x17, 0xa2,
- 0xcd, 0x95, 0x13, 0xaf, 0xac, 0x4d, 0x6e, 0x93, 0x58, 0xc4, 0xeb, 0xe0, 0x5d, 0x23, 0xf9, 0x0b,
- 0xf0, 0x41, 0xf8, 0xa4, 0x68, 0x77, 0x9d, 0xd4, 0xa9, 0x5c, 0xfa, 0x2a, 0xbb, 0x8f, 0x7f, 0x33,
- 0xcf, 0x78, 0x66, 0x1c, 0x78, 0xb2, 0xcb, 0x33, 0x99, 0x3d, 0x8b, 0xf5, 0xcf, 0x99, 0xb9, 0x44,
- 0xfa, 0x07, 0x79, 0xf5, 0x47, 0xc3, 0x27, 0xeb, 0x2c, 0x5b, 0x6f, 0x99, 0x41, 0x16, 0xc5, 0xea,
- 0x8c, 0xf2, 0xd2, 0x80, 0xc3, 0xc7, 0x92, 0x09, 0x59, 0x65, 0x50, 0x47, 0x23, 0x8f, 0xfe, 0xe9,
- 0x43, 0xef, 0x96, 0x09, 0x41, 0xd7, 0x0c, 0x21, 0x68, 0x73, 0x9a, 0x32, 0x6c, 0x05, 0x56, 0xd8,
- 0x27, 0xfa, 0x8c, 0x9e, 0x83, 0xb3, 0x49, 0xb6, 0x34, 0x4f, 0x64, 0x89, 0x5b, 0x81, 0x15, 0x9e,
- 0x8e, 0x3f, 0x8f, 0xea, 0x96, 0x51, 0x15, 0x1c, 0xfd, 0x5a, 0xa4, 0x59, 0x91, 0x93, 0x03, 0x8d,
- 0x02, 0xf0, 0x36, 0x2c, 0x59, 0x6f, 0x64, 0x9c, 0xf0, 0x78, 0x99, 0x62, 0x3b, 0xb0, 0xc2, 0x13,
- 0x02, 0x46, 0x9b, 0xf0, 0xab, 0x54, 0xf9, 0x3d, 0x50, 0x49, 0x71, 0x3b, 0xb0, 0x42, 0x8f, 0xe8,
- 0x33, 0xfa, 0x12, 0xbc, 0x9c, 0x89, 0x62, 0x2b, 0xe3, 0x65, 0x56, 0x70, 0x89, 0x7b, 0x81, 0x15,
- 0xda, 0xc4, 0x35, 0xda, 0x95, 0x92, 0xd0, 0x57, 0x70, 0x22, 0xf3, 0x82, 0xc5, 0x62, 0x99, 0x49,
- 0x91, 0x52, 0x8e, 0x9d, 0xc0, 0x0a, 0x1d, 0xe2, 0x29, 0x71, 0x5e, 0x69, 0x68, 0x00, 0x1d, 0xb1,
- 0xcc, 0x72, 0x86, 0xfb, 0x81, 0x15, 0xb6, 0x88, 0xb9, 0x20, 0x1f, 0xec, 0x3f, 0x59, 0x89, 0x3b,
- 0x81, 0x1d, 0xb6, 0x89, 0x3a, 0xa2, 0xcf, 0xa0, 0x2f, 0x36, 0x59, 0x2e, 0x63, 0xa5, 0x7f, 0x12,
- 0xd8, 0x61, 0x87, 0x38, 0x5a, 0xb8, 0x66, 0x25, 0xfa, 0x0e, 0xba, 0x9c, 0x09, 0xc9, 0x1e, 0x70,
- 0x37, 0xb0, 0x42, 0x77, 0x3c, 0x38, 0x7e, 0xf5, 0xa9, 0x7e, 0x46, 0x2a, 0x06, 0x9d, 0x43, 0x2f,
- 0x8f, 0x57, 0x05, 0xe7, 0x25, 0xf6, 0x03, 0xfb, 0x83, 0x9d, 0xea, 0xe6, 0xaf, 0x15, 0x8b, 0x5e,
- 0x42, 0x4f, 0xb2, 0x3c, 0xa7, 0x09, 0xc7, 0x10, 0xd8, 0xa1, 0x3b, 0x1e, 0x35, 0x87, 0xdd, 0x19,
- 0xe8, 0x15, 0x97, 0x79, 0x49, 0xf6, 0x21, 0xe8, 0x05, 0x98, 0x0d, 0x18, 0xc7, 0xab, 0x84, 0x6d,
- 0x1f, 0xb0, 0xab, 0x0b, 0xfd, 0x34, 0x7a, 0x3b, 0xed, 0x68, 0x5e, 0x2c, 0x7e, 0x61, 0x2b, 0x5a,
- 0x6c, 0xa5, 0x20, 0xae, 0x81, 0x5f, 0x2b, 0x16, 0x4d, 0x0e, 0xb1, 0x7f, 0xd3, 0x6d, 0xc1, 0xf0,
- 0x89, 0xb6, 0xff, 0xa6, 0xd9, 0x7e, 0xa6, 0xc9, 0xdf, 0x15, 0x68, 0x4a, 0xa8, 0x52, 0x69, 0x05,
- 0x7d, 0x0f, 0x0e, 0xe5, 0xa5, 0xdc, 0x24, 0x7c, 0x8d, 0x4f, 0xab, 0x5e, 0x99, 0x5d, 0x8c, 0xf6,
- 0xbb, 0x18, 0x5d, 0xf0, 0x92, 0x1c, 0x28, 0x74, 0x0e, 0x6e, 0x4a, 0x79, 0x19, 0xeb, 0x9b, 0xc0,
- 0x8f, 0xb4, 0x77, 0x73, 0x10, 0x28, 0xf0, 0x4e, 0x73, 0xe8, 0x1c, 0x40, 0x14, 0x8b, 0xd4, 0x14,
- 0x85, 0x3f, 0xd6, 0x56, 0x8f, 0x1b, 0x2b, 0x26, 0x35, 0x10, 0xfd, 0x00, 0xce, 0x72, 0x93, 0x6c,
- 0x1f, 0x72, 0xc6, 0x31, 0xd2, 0x56, 0xef, 0x09, 0x3a, 0x60, 0xe8, 0x0a, 0x40, 0xc8, 0x3c, 0xe1,
- 0xeb, 0x38, 0xa5, 0x3b, 0x3c, 0xd0, 0x41, 0x5f, 0x37, 0xf7, 0x66, 0xae, 0xb9, 0x5b, 0xba, 0x33,
- 0x9d, 0xe9, 0x8b, 0xfd, 0x7d, 0x38, 0x03, 0xaf, 0x3e, 0xb7, 0xfd, 0x02, 0x9a, 0x2f, 0x4c, 0x2f,
- 0xe0, 0xb7, 0xd0, 0x31, 0xdd, 0x6f, 0xfd, 0xcf, 0x8a, 0x19, 0xe4, 0x45, 0xeb, 0xb9, 0x35, 0xbc,
- 0x07, 0xff, 0xdd, 0x51, 0x34, 0x64, 0x7d, 0x7a, 0x9c, 0xf5, 0xbd, 0xfb, 0x50, 0x4b, 0xfc, 0x12,
- 0x4e, 0x8f, 0xdf, 0xa3, 0x21, 0xed, 0xa0, 0x9e, 0xb6, 0x5f, 0x8b, 0x1e, 0xfd, 0x0c, 0x5d, 0xb3,
- 0xd7, 0xc8, 0x85, 0xde, 0x9b, 0xe9, 0xf5, 0xf4, 0xb7, 0xfb, 0xa9, 0xff, 0x11, 0x72, 0xa0, 0x3d,
- 0x7b, 0x33, 0x9d, 0xfb, 0x16, 0x3a, 0x81, 0xfe, 0xfc, 0xe6, 0x62, 0x36, 0xbf, 0x9b, 0x5c, 0x5d,
- 0xfb, 0x2d, 0xf4, 0x08, 0xdc, 0xcb, 0xc9, 0xcd, 0x4d, 0x7c, 0x79, 0x31, 0xb9, 0x79, 0xf5, 0x87,
- 0x6f, 0x8f, 0xc6, 0xd0, 0x35, 0x2f, 0xab, 0x4c, 0x16, 0xfa, 0x2b, 0x32, 0xc6, 0xe6, 0xa2, 0xfe,
- 0x2c, 0x96, 0x85, 0x34, 0xce, 0x0e, 0xd1, 0xe7, 0xd1, 0xbf, 0x16, 0x9c, 0x56, 0x33, 0xb8, 0x4f,
- 0xe4, 0xe6, 0x96, 0xee, 0xd0, 0x0c, 0xbc, 0x45, 0x29, 0x99, 0x9a, 0xd9, 0x4e, 0x2d, 0xa3, 0xa5,
- 0xe7, 0xf6, 0xb4, 0x71, 0x6e, 0x55, 0x4c, 0x74, 0x59, 0x4a, 0x76, 0x6b, 0xf8, 0x6a, 0xb5, 0x17,
- 0x6f, 0x95, 0xe1, 0x4f, 0xe0, 0xbf, 0x0b, 0xd4, 0x3b, 0xe3, 0x34, 0x74, 0xc6, 0xab, 0x77, 0xe6,
- 0x2f, 0xe8, 0x4e, 0xb8, 0x54, 0xb5, 0x9d, 0x81, 0x9d, 0x4b, 0x59, 0x95, 0xf4, 0xc5, 0x71, 0x49,
- 0x06, 0x89, 0x88, 0x94, 0xa6, 0x04, 0x45, 0x0e, 0x7f, 0x04, 0x67, 0x2f, 0xd4, 0x2d, 0x3b, 0x0d,
- 0x96, 0x9d, 0xba, 0xe5, 0x33, 0xe8, 0x99, 0x7c, 0x02, 0x85, 0xd0, 0x4e, 0xe9, 0x4e, 0x54, 0xa6,
- 0x83, 0x26, 0x53, 0xa2, 0x89, 0x45, 0xd7, 0x3c, 0xfa, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x99, 0x24,
- 0x6b, 0x12, 0x6d, 0x06, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
deleted file mode 100644
index c81fe1e5e..000000000
--- a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
+++ /dev/null
@@ -1,89 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-import "google/protobuf/any.proto";
-import "test_proto/test.proto";
-
-package proto3_proto;
-
-message Message {
- enum Humour {
- UNKNOWN = 0;
- PUNS = 1;
- SLAPSTICK = 2;
- BILL_BAILEY = 3;
- }
-
- string name = 1;
- Humour hilarity = 2;
- uint32 height_in_cm = 3;
- bytes data = 4;
- int64 result_count = 7;
- bool true_scotsman = 8;
- float score = 9;
-
- repeated uint64 key = 5;
- repeated int32 short_key = 19;
- Nested nested = 6;
- repeated Humour r_funny = 16;
-
- map terrain = 10;
- test_proto.SubDefaults proto2_field = 11;
- map proto2_value = 13;
-
- google.protobuf.Any anything = 14;
- repeated google.protobuf.Any many_things = 15;
-
- Message submessage = 17;
- repeated Message children = 18;
-
- map string_map = 20;
-}
-
-message Nested {
- string bunny = 1;
- bool cute = 2;
-}
-
-message MessageWithMap {
- map byte_mapping = 1;
-}
-
-
-message IntMap {
- map rtt = 1;
-}
-
-message IntMaps {
- repeated IntMap maps = 1;
-}
diff --git a/vendor/github.com/golang/protobuf/proto/proto3_test.go b/vendor/github.com/golang/protobuf/proto/proto3_test.go
deleted file mode 100644
index 73eed6c0b..000000000
--- a/vendor/github.com/golang/protobuf/proto/proto3_test.go
+++ /dev/null
@@ -1,151 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto_test
-
-import (
- "bytes"
- "testing"
-
- "github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/proto/proto3_proto"
- tpb "github.com/golang/protobuf/proto/test_proto"
-)
-
-func TestProto3ZeroValues(t *testing.T) {
- tests := []struct {
- desc string
- m proto.Message
- }{
- {"zero message", &pb.Message{}},
- {"empty bytes field", &pb.Message{Data: []byte{}}},
- }
- for _, test := range tests {
- b, err := proto.Marshal(test.m)
- if err != nil {
- t.Errorf("%s: proto.Marshal: %v", test.desc, err)
- continue
- }
- if len(b) > 0 {
- t.Errorf("%s: Encoding is non-empty: %q", test.desc, b)
- }
- }
-}
-
-func TestRoundTripProto3(t *testing.T) {
- m := &pb.Message{
- Name: "David", // (2 | 1<<3): 0x0a 0x05 "David"
- Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01
- HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01
- Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto"
- ResultCount: 47, // (0 | 7<<3): 0x38 0x2f
- TrueScotsman: true, // (0 | 8<<3): 0x40 0x01
- Score: 8.1, // (5 | 9<<3): 0x4d <8.1>
-
- Key: []uint64{1, 0xdeadbeef},
- Nested: &pb.Nested{
- Bunny: "Monty",
- },
- }
- t.Logf(" m: %v", m)
-
- b, err := proto.Marshal(m)
- if err != nil {
- t.Fatalf("proto.Marshal: %v", err)
- }
- t.Logf(" b: %q", b)
-
- m2 := new(pb.Message)
- if err := proto.Unmarshal(b, m2); err != nil {
- t.Fatalf("proto.Unmarshal: %v", err)
- }
- t.Logf("m2: %v", m2)
-
- if !proto.Equal(m, m2) {
- t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2)
- }
-}
-
-func TestGettersForBasicTypesExist(t *testing.T) {
- var m pb.Message
- if got := m.GetNested().GetBunny(); got != "" {
- t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got)
- }
- if got := m.GetNested().GetCute(); got {
- t.Errorf("m.GetNested().GetCute() = %t, want false", got)
- }
-}
-
-func TestProto3SetDefaults(t *testing.T) {
- in := &pb.Message{
- Terrain: map[string]*pb.Nested{
- "meadow": new(pb.Nested),
- },
- Proto2Field: new(tpb.SubDefaults),
- Proto2Value: map[string]*tpb.SubDefaults{
- "badlands": new(tpb.SubDefaults),
- },
- }
-
- got := proto.Clone(in).(*pb.Message)
- proto.SetDefaults(got)
-
- // There are no defaults in proto3. Everything should be the zero value, but
- // we need to remember to set defaults for nested proto2 messages.
- want := &pb.Message{
- Terrain: map[string]*pb.Nested{
- "meadow": new(pb.Nested),
- },
- Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)},
- Proto2Value: map[string]*tpb.SubDefaults{
- "badlands": &tpb.SubDefaults{N: proto.Int64(7)},
- },
- }
-
- if !proto.Equal(got, want) {
- t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want)
- }
-}
-
-func TestUnknownFieldPreservation(t *testing.T) {
- b1 := "\x0a\x05David" // Known tag 1
- b2 := "\xc2\x0c\x06Google" // Unknown tag 200
- b := []byte(b1 + b2)
-
- m := new(pb.Message)
- if err := proto.Unmarshal(b, m); err != nil {
- t.Fatalf("proto.Unmarshal: %v", err)
- }
-
- if !bytes.Equal(m.XXX_unrecognized, []byte(b2)) {
- t.Fatalf("mismatching unknown fields:\ngot %q\nwant %q", m.XXX_unrecognized, b2)
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/proto_clone_test.go b/vendor/github.com/golang/protobuf/proto/proto_clone_test.go
new file mode 100644
index 000000000..d9ae24f1b
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/proto_clone_test.go
@@ -0,0 +1,379 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto_test
+
+import (
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+
+ pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
+ pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
+)
+
+var cloneTestMessage = &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("Dave"),
+ Pet: []string{"bunny", "kitty", "horsey"},
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("niles"),
+ Port: proto.Int32(9099),
+ Connected: proto.Bool(true),
+ },
+ Others: []*pb2.OtherMessage{
+ {
+ Value: []byte("some bytes"),
+ },
+ },
+ Somegroup: &pb2.MyMessage_SomeGroup{
+ GroupField: proto.Int32(6),
+ },
+ RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
+}
+
+func init() {
+ ext := &pb2.Ext{
+ Data: proto.String("extension"),
+ }
+ if err := proto.SetExtension(cloneTestMessage, pb2.E_Ext_More, ext); err != nil {
+ panic("SetExtension: " + err.Error())
+ }
+ if err := proto.SetExtension(cloneTestMessage, pb2.E_Ext_Text, proto.String("hello")); err != nil {
+ panic("SetExtension: " + err.Error())
+ }
+ if err := proto.SetExtension(cloneTestMessage, pb2.E_Greeting, []string{"one", "two"}); err != nil {
+ panic("SetExtension: " + err.Error())
+ }
+}
+
+func TestClone(t *testing.T) {
+ // Create a clone using a marshal/unmarshal roundtrip.
+ vanilla := new(pb2.MyMessage)
+ b, err := proto.Marshal(cloneTestMessage)
+ if err != nil {
+ t.Errorf("unexpected Marshal error: %v", err)
+ }
+ if err := proto.Unmarshal(b, vanilla); err != nil {
+ t.Errorf("unexpected Unarshal error: %v", err)
+ }
+
+ // Create a clone using Clone and verify that it is equal to the original.
+ m := proto.Clone(cloneTestMessage).(*pb2.MyMessage)
+ if !proto.Equal(m, cloneTestMessage) {
+ t.Fatalf("Clone(%v) = %v", cloneTestMessage, m)
+ }
+
+ // Mutate the clone, which should not affect the original.
+ x1, err := proto.GetExtension(m, pb2.E_Ext_More)
+ if err != nil {
+ t.Errorf("unexpected GetExtension(%v) error: %v", pb2.E_Ext_More.Name, err)
+ }
+ x2, err := proto.GetExtension(m, pb2.E_Ext_Text)
+ if err != nil {
+ t.Errorf("unexpected GetExtension(%v) error: %v", pb2.E_Ext_Text.Name, err)
+ }
+ x3, err := proto.GetExtension(m, pb2.E_Greeting)
+ if err != nil {
+ t.Errorf("unexpected GetExtension(%v) error: %v", pb2.E_Greeting.Name, err)
+ }
+ *m.Inner.Port++
+ *(x1.(*pb2.Ext)).Data = "blah blah"
+ *(x2.(*string)) = "goodbye"
+ x3.([]string)[0] = "zero"
+ if !proto.Equal(cloneTestMessage, vanilla) {
+ t.Fatalf("mutation on original detected:\ngot %v\nwant %v", cloneTestMessage, vanilla)
+ }
+}
+
+func TestCloneNil(t *testing.T) {
+ var m *pb2.MyMessage
+ if c := proto.Clone(m); !proto.Equal(m, c) {
+ t.Errorf("Clone(%v) = %v", m, c)
+ }
+}
+
+var mergeTests = []struct {
+ src, dst, want proto.Message
+}{
+ {
+ src: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ },
+ dst: &pb2.MyMessage{
+ Name: proto.String("Dave"),
+ },
+ want: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("Dave"),
+ },
+ },
+ {
+ src: &pb2.MyMessage{
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("hey"),
+ Connected: proto.Bool(true),
+ },
+ Pet: []string{"horsey"},
+ Others: []*pb2.OtherMessage{
+ {
+ Value: []byte("some bytes"),
+ },
+ },
+ },
+ dst: &pb2.MyMessage{
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("niles"),
+ Port: proto.Int32(9099),
+ },
+ Pet: []string{"bunny", "kitty"},
+ Others: []*pb2.OtherMessage{
+ {
+ Key: proto.Int64(31415926535),
+ },
+ {
+ // Explicitly test a src=nil field
+ Inner: nil,
+ },
+ },
+ },
+ want: &pb2.MyMessage{
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("hey"),
+ Connected: proto.Bool(true),
+ Port: proto.Int32(9099),
+ },
+ Pet: []string{"bunny", "kitty", "horsey"},
+ Others: []*pb2.OtherMessage{
+ {
+ Key: proto.Int64(31415926535),
+ },
+ {},
+ {
+ Value: []byte("some bytes"),
+ },
+ },
+ },
+ },
+ {
+ src: &pb2.MyMessage{
+ RepBytes: [][]byte{[]byte("wow")},
+ },
+ dst: &pb2.MyMessage{
+ Somegroup: &pb2.MyMessage_SomeGroup{
+ GroupField: proto.Int32(6),
+ },
+ RepBytes: [][]byte{[]byte("sham")},
+ },
+ want: &pb2.MyMessage{
+ Somegroup: &pb2.MyMessage_SomeGroup{
+ GroupField: proto.Int32(6),
+ },
+ RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
+ },
+ },
+ // Check that a scalar bytes field replaces rather than appends.
+ {
+ src: &pb2.OtherMessage{Value: []byte("foo")},
+ dst: &pb2.OtherMessage{Value: []byte("bar")},
+ want: &pb2.OtherMessage{Value: []byte("foo")},
+ },
+ {
+ src: &pb2.MessageWithMap{
+ NameMapping: map[int32]string{6: "Nigel"},
+ MsgMapping: map[int64]*pb2.FloatingPoint{
+ 0x4001: &pb2.FloatingPoint{F: proto.Float64(2.0)},
+ 0x4002: &pb2.FloatingPoint{
+ F: proto.Float64(2.0),
+ },
+ },
+ ByteMapping: map[bool][]byte{true: []byte("wowsa")},
+ },
+ dst: &pb2.MessageWithMap{
+ NameMapping: map[int32]string{
+ 6: "Bruce", // should be overwritten
+ 7: "Andrew",
+ },
+ MsgMapping: map[int64]*pb2.FloatingPoint{
+ 0x4002: &pb2.FloatingPoint{
+ F: proto.Float64(3.0),
+ Exact: proto.Bool(true),
+ }, // the entire message should be overwritten
+ },
+ },
+ want: &pb2.MessageWithMap{
+ NameMapping: map[int32]string{
+ 6: "Nigel",
+ 7: "Andrew",
+ },
+ MsgMapping: map[int64]*pb2.FloatingPoint{
+ 0x4001: &pb2.FloatingPoint{F: proto.Float64(2.0)},
+ 0x4002: &pb2.FloatingPoint{
+ F: proto.Float64(2.0),
+ },
+ },
+ ByteMapping: map[bool][]byte{true: []byte("wowsa")},
+ },
+ },
+ // proto3 shouldn't merge zero values,
+ // in the same way that proto2 shouldn't merge nils.
+ {
+ src: &pb3.Message{
+ Name: "Aaron",
+ Data: []byte(""), // zero value, but not nil
+ },
+ dst: &pb3.Message{
+ HeightInCm: 176,
+ Data: []byte("texas!"),
+ },
+ want: &pb3.Message{
+ Name: "Aaron",
+ HeightInCm: 176,
+ Data: []byte("texas!"),
+ },
+ },
+ { // Oneof fields should merge by assignment.
+ src: &pb2.Communique{Union: &pb2.Communique_Number{41}},
+ dst: &pb2.Communique{Union: &pb2.Communique_Name{"Bobby Tables"}},
+ want: &pb2.Communique{Union: &pb2.Communique_Number{41}},
+ },
+ { // Oneof nil is the same as not set.
+ src: &pb2.Communique{},
+ dst: &pb2.Communique{Union: &pb2.Communique_Name{"Bobby Tables"}},
+ want: &pb2.Communique{Union: &pb2.Communique_Name{"Bobby Tables"}},
+ },
+ {
+ src: &pb2.Communique{Union: &pb2.Communique_Number{1337}},
+ dst: &pb2.Communique{},
+ want: &pb2.Communique{Union: &pb2.Communique_Number{1337}},
+ },
+ {
+ src: &pb2.Communique{Union: &pb2.Communique_Col{pb2.MyMessage_RED}},
+ dst: &pb2.Communique{},
+ want: &pb2.Communique{Union: &pb2.Communique_Col{pb2.MyMessage_RED}},
+ },
+ {
+ src: &pb2.Communique{Union: &pb2.Communique_Data{[]byte("hello")}},
+ dst: &pb2.Communique{},
+ want: &pb2.Communique{Union: &pb2.Communique_Data{[]byte("hello")}},
+ },
+ {
+ src: &pb2.Communique{Union: &pb2.Communique_Msg{&pb2.Strings{BytesField: []byte{1, 2, 3}}}},
+ dst: &pb2.Communique{},
+ want: &pb2.Communique{Union: &pb2.Communique_Msg{&pb2.Strings{BytesField: []byte{1, 2, 3}}}},
+ },
+ {
+ src: &pb2.Communique{Union: &pb2.Communique_Msg{}},
+ dst: &pb2.Communique{},
+ want: &pb2.Communique{Union: &pb2.Communique_Msg{}},
+ },
+ {
+ src: &pb2.Communique{Union: &pb2.Communique_Msg{&pb2.Strings{StringField: proto.String("123")}}},
+ dst: &pb2.Communique{Union: &pb2.Communique_Msg{&pb2.Strings{BytesField: []byte{1, 2, 3}}}},
+ want: &pb2.Communique{Union: &pb2.Communique_Msg{&pb2.Strings{StringField: proto.String("123"), BytesField: []byte{1, 2, 3}}}},
+ },
+ {
+ src: &pb3.Message{
+ Terrain: map[string]*pb3.Nested{
+ "kay_a": &pb3.Nested{Cute: true}, // replace
+ "kay_b": &pb3.Nested{Bunny: "rabbit"}, // insert
+ },
+ },
+ dst: &pb3.Message{
+ Terrain: map[string]*pb3.Nested{
+ "kay_a": &pb3.Nested{Bunny: "lost"}, // replaced
+ "kay_c": &pb3.Nested{Bunny: "bunny"}, // keep
+ },
+ },
+ want: &pb3.Message{
+ Terrain: map[string]*pb3.Nested{
+ "kay_a": &pb3.Nested{Cute: true},
+ "kay_b": &pb3.Nested{Bunny: "rabbit"},
+ "kay_c": &pb3.Nested{Bunny: "bunny"},
+ },
+ },
+ },
+ {
+ src: &pb2.GoTest{
+ F_BoolRepeated: []bool{},
+ F_Int32Repeated: []int32{},
+ F_Int64Repeated: []int64{},
+ F_Uint32Repeated: []uint32{},
+ F_Uint64Repeated: []uint64{},
+ F_FloatRepeated: []float32{},
+ F_DoubleRepeated: []float64{},
+ F_StringRepeated: []string{},
+ F_BytesRepeated: [][]byte{},
+ },
+ dst: &pb2.GoTest{},
+ want: &pb2.GoTest{
+ F_BoolRepeated: []bool{},
+ F_Int32Repeated: []int32{},
+ F_Int64Repeated: []int64{},
+ F_Uint32Repeated: []uint32{},
+ F_Uint64Repeated: []uint64{},
+ F_FloatRepeated: []float32{},
+ F_DoubleRepeated: []float64{},
+ F_StringRepeated: []string{},
+ F_BytesRepeated: [][]byte{},
+ },
+ },
+ {
+ src: &pb2.GoTest{},
+ dst: &pb2.GoTest{
+ F_BoolRepeated: []bool{},
+ F_Int32Repeated: []int32{},
+ F_Int64Repeated: []int64{},
+ F_Uint32Repeated: []uint32{},
+ F_Uint64Repeated: []uint64{},
+ F_FloatRepeated: []float32{},
+ F_DoubleRepeated: []float64{},
+ F_StringRepeated: []string{},
+ F_BytesRepeated: [][]byte{},
+ },
+ want: &pb2.GoTest{
+ F_BoolRepeated: []bool{},
+ F_Int32Repeated: []int32{},
+ F_Int64Repeated: []int64{},
+ F_Uint32Repeated: []uint32{},
+ F_Uint64Repeated: []uint64{},
+ F_FloatRepeated: []float32{},
+ F_DoubleRepeated: []float64{},
+ F_StringRepeated: []string{},
+ F_BytesRepeated: [][]byte{},
+ },
+ },
+ {
+ src: &pb2.GoTest{
+ F_BytesRepeated: [][]byte{nil, []byte{}, []byte{0}},
+ },
+ dst: &pb2.GoTest{},
+ want: &pb2.GoTest{
+ F_BytesRepeated: [][]byte{nil, []byte{}, []byte{0}},
+ },
+ },
+ {
+ src: &pb2.MyMessage{
+ Others: []*pb2.OtherMessage{},
+ },
+ dst: &pb2.MyMessage{},
+ want: &pb2.MyMessage{
+ Others: []*pb2.OtherMessage{},
+ },
+ },
+}
+
+func TestMerge(t *testing.T) {
+ for _, m := range mergeTests {
+ got := proto.Clone(m.dst)
+ if !proto.Equal(got, m.dst) {
+ t.Errorf("Clone()\ngot %v\nwant %v", got, m.dst)
+ continue
+ }
+ proto.Merge(got, m.src)
+ if !proto.Equal(got, m.want) {
+ t.Errorf("Merge(%v, %v)\ngot %v\nwant %v", m.dst, m.src, got, m.want)
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/proto_equal_test.go b/vendor/github.com/golang/protobuf/proto/proto_equal_test.go
new file mode 100644
index 000000000..d5b2541a0
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/proto_equal_test.go
@@ -0,0 +1,218 @@
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto_test
+
+import (
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+
+ pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
+ pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
+)
+
+// Four identical base messages.
+// The init function adds extensions to some of them.
+var messageWithoutExtension = &pb2.MyMessage{Count: proto.Int32(7)}
+var messageWithExtension1a = &pb2.MyMessage{Count: proto.Int32(7)}
+var messageWithExtension1b = &pb2.MyMessage{Count: proto.Int32(7)}
+var messageWithExtension2 = &pb2.MyMessage{Count: proto.Int32(7)}
+var messageWithExtension3a = &pb2.MyMessage{Count: proto.Int32(7)}
+var messageWithExtension3b = &pb2.MyMessage{Count: proto.Int32(7)}
+var messageWithExtension3c = &pb2.MyMessage{Count: proto.Int32(7)}
+
+// Two messages with non-message extensions.
+var messageWithInt32Extension1 = &pb2.MyMessage{Count: proto.Int32(8)}
+var messageWithInt32Extension2 = &pb2.MyMessage{Count: proto.Int32(8)}
+
+func init() {
+ ext1 := &pb2.Ext{Data: proto.String("Kirk")}
+ ext2 := &pb2.Ext{Data: proto.String("Picard")}
+
+ // messageWithExtension1a has ext1, but never marshals it.
+ if err := proto.SetExtension(messageWithExtension1a, pb2.E_Ext_More, ext1); err != nil {
+ panic("proto.SetExtension on 1a failed: " + err.Error())
+ }
+
+ // messageWithExtension1b is the unmarshaled form of messageWithExtension1a.
+ if err := proto.SetExtension(messageWithExtension1b, pb2.E_Ext_More, ext1); err != nil {
+ panic("proto.SetExtension on 1b failed: " + err.Error())
+ }
+ buf, err := proto.Marshal(messageWithExtension1b)
+ if err != nil {
+ panic("proto.Marshal of 1b failed: " + err.Error())
+ }
+ messageWithExtension1b.Reset()
+ if err := proto.Unmarshal(buf, messageWithExtension1b); err != nil {
+ panic("proto.Unmarshal of 1b failed: " + err.Error())
+ }
+
+ // messageWithExtension2 has ext2.
+ if err := proto.SetExtension(messageWithExtension2, pb2.E_Ext_More, ext2); err != nil {
+ panic("proto.SetExtension on 2 failed: " + err.Error())
+ }
+
+ if err := proto.SetExtension(messageWithInt32Extension1, pb2.E_Ext_Number, proto.Int32(23)); err != nil {
+ panic("proto.SetExtension on Int32-1 failed: " + err.Error())
+ }
+ if err := proto.SetExtension(messageWithInt32Extension1, pb2.E_Ext_Number, proto.Int32(24)); err != nil {
+ panic("proto.SetExtension on Int32-2 failed: " + err.Error())
+ }
+
+ // messageWithExtension3{a,b,c} has unregistered extension.
+ if proto.RegisteredExtensions(messageWithExtension3a)[200] != nil {
+ panic("expect extension 200 unregistered")
+ }
+ bytes := []byte{
+ 0xc0, 0x0c, 0x01, // id=200, wiretype=0 (varint), data=1
+ }
+ bytes2 := []byte{
+ 0xc0, 0x0c, 0x02, // id=200, wiretype=0 (varint), data=2
+ }
+ proto.SetRawExtension(messageWithExtension3a, 200, bytes)
+ proto.SetRawExtension(messageWithExtension3b, 200, bytes)
+ proto.SetRawExtension(messageWithExtension3c, 200, bytes2)
+}
+
+var EqualTests = []struct {
+ desc string
+ a, b proto.Message
+ exp bool
+}{
+ {"different types", &pb2.GoEnum{}, &pb2.GoTestField{}, false},
+ {"equal empty", &pb2.GoEnum{}, &pb2.GoEnum{}, true},
+ {"nil vs nil", nil, nil, true},
+ {"typed nil vs typed nil", (*pb2.GoEnum)(nil), (*pb2.GoEnum)(nil), true},
+ {"typed nil vs empty", (*pb2.GoEnum)(nil), &pb2.GoEnum{}, false},
+ {"different typed nil", (*pb2.GoEnum)(nil), (*pb2.GoTestField)(nil), false},
+
+ {"one set field, one unset field", &pb2.GoTestField{Label: proto.String("foo")}, &pb2.GoTestField{}, false},
+ {"one set field zero, one unset field", &pb2.GoTest{Param: proto.Int32(0)}, &pb2.GoTest{}, false},
+ {"different set fields", &pb2.GoTestField{Label: proto.String("foo")}, &pb2.GoTestField{Label: proto.String("bar")}, false},
+ {"equal set", &pb2.GoTestField{Label: proto.String("foo")}, &pb2.GoTestField{Label: proto.String("foo")}, true},
+
+ {"repeated, one set", &pb2.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb2.GoTest{}, false},
+ {"repeated, different length", &pb2.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb2.GoTest{F_Int32Repeated: []int32{2}}, false},
+ {"repeated, different value", &pb2.GoTest{F_Int32Repeated: []int32{2}}, &pb2.GoTest{F_Int32Repeated: []int32{3}}, false},
+ {"repeated, equal", &pb2.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb2.GoTest{F_Int32Repeated: []int32{2, 4}}, true},
+ {"repeated, nil equal nil", &pb2.GoTest{F_Int32Repeated: nil}, &pb2.GoTest{F_Int32Repeated: nil}, true},
+ {"repeated, nil equal empty", &pb2.GoTest{F_Int32Repeated: nil}, &pb2.GoTest{F_Int32Repeated: []int32{}}, true},
+ {"repeated, empty equal nil", &pb2.GoTest{F_Int32Repeated: []int32{}}, &pb2.GoTest{F_Int32Repeated: nil}, true},
+
+ {
+ "nested, different",
+ &pb2.GoTest{RequiredField: &pb2.GoTestField{Label: proto.String("foo")}},
+ &pb2.GoTest{RequiredField: &pb2.GoTestField{Label: proto.String("bar")}},
+ false,
+ },
+ {
+ "nested, equal",
+ &pb2.GoTest{RequiredField: &pb2.GoTestField{Label: proto.String("wow")}},
+ &pb2.GoTest{RequiredField: &pb2.GoTestField{Label: proto.String("wow")}},
+ true,
+ },
+
+ {"bytes", &pb2.OtherMessage{Value: []byte("foo")}, &pb2.OtherMessage{Value: []byte("foo")}, true},
+ {"bytes, empty", &pb2.OtherMessage{Value: []byte{}}, &pb2.OtherMessage{Value: []byte{}}, true},
+ {"bytes, empty vs nil", &pb2.OtherMessage{Value: []byte{}}, &pb2.OtherMessage{Value: nil}, false},
+ {
+ "repeated bytes",
+ &pb2.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}},
+ &pb2.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}},
+ true,
+ },
+ // In proto3, []byte{} and []byte(nil) are equal.
+ {"proto3 bytes, empty vs nil", &pb3.Message{Data: []byte{}}, &pb3.Message{Data: nil}, true},
+
+ {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false},
+ {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true},
+ {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false},
+
+ {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true},
+ {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false},
+
+ {"unregistered extension same", messageWithExtension3a, messageWithExtension3b, true},
+ {"unregistered extension different", messageWithExtension3a, messageWithExtension3c, false},
+
+ {
+ "message with group",
+ &pb2.MyMessage{
+ Count: proto.Int32(1),
+ Somegroup: &pb2.MyMessage_SomeGroup{
+ GroupField: proto.Int32(5),
+ },
+ },
+ &pb2.MyMessage{
+ Count: proto.Int32(1),
+ Somegroup: &pb2.MyMessage_SomeGroup{
+ GroupField: proto.Int32(5),
+ },
+ },
+ true,
+ },
+
+ {
+ "map same",
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
+ true,
+ },
+ {
+ "map different entry",
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
+ &pb2.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}},
+ false,
+ },
+ {
+ "map different key only",
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
+ &pb2.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}},
+ false,
+ },
+ {
+ "map different value only",
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}},
+ false,
+ },
+ {
+ "zero-length maps same",
+ &pb2.MessageWithMap{NameMapping: map[int32]string{}},
+ &pb2.MessageWithMap{NameMapping: nil},
+ true,
+ },
+ {
+ "orders in map don't matter",
+ &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Ken", 2: "Rob"}},
+ &pb2.MessageWithMap{NameMapping: map[int32]string{2: "Rob", 1: "Ken"}},
+ true,
+ },
+ {
+ "oneof same",
+ &pb2.Communique{Union: &pb2.Communique_Number{41}},
+ &pb2.Communique{Union: &pb2.Communique_Number{41}},
+ true,
+ },
+ {
+ "oneof one nil",
+ &pb2.Communique{Union: &pb2.Communique_Number{41}},
+ &pb2.Communique{},
+ false,
+ },
+ {
+ "oneof different",
+ &pb2.Communique{Union: &pb2.Communique_Number{41}},
+ &pb2.Communique{Union: &pb2.Communique_Name{"Bobby Tables"}},
+ false,
+ },
+}
+
+func TestEqual(t *testing.T) {
+ for _, tc := range EqualTests {
+ if res := proto.Equal(tc.a, tc.b); res != tc.exp {
+ t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp)
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/proto_test.go b/vendor/github.com/golang/protobuf/proto/proto_test.go
new file mode 100644
index 000000000..61c8f8a02
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/proto_test.go
@@ -0,0 +1,2593 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "math"
+ "math/rand"
+ "reflect"
+ "runtime/debug"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ "google.golang.org/protobuf/testing/protopack"
+
+ pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
+ pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
+ tspb "github.com/golang/protobuf/ptypes/timestamp"
+)
+
+func initGoTestField() *pb2.GoTestField {
+ f := new(pb2.GoTestField)
+ f.Label = proto.String("label")
+ f.Type = proto.String("type")
+ return f
+}
+
+// These are all structurally equivalent but the tag numbers differ.
+// (It's remarkable that required, optional, and repeated all have
+// 8 letters.)
+func initGoTest_RequiredGroup() *pb2.GoTest_RequiredGroup {
+ return &pb2.GoTest_RequiredGroup{
+ RequiredField: proto.String("required"),
+ }
+}
+
+func initGoTest_OptionalGroup() *pb2.GoTest_OptionalGroup {
+ return &pb2.GoTest_OptionalGroup{
+ RequiredField: proto.String("optional"),
+ }
+}
+
+func initGoTest_RepeatedGroup() *pb2.GoTest_RepeatedGroup {
+ return &pb2.GoTest_RepeatedGroup{
+ RequiredField: proto.String("repeated"),
+ }
+}
+
+func initGoTest(setdefaults bool) *pb2.GoTest {
+ pb := new(pb2.GoTest)
+ if setdefaults {
+ pb.F_BoolDefaulted = proto.Bool(pb2.Default_GoTest_F_BoolDefaulted)
+ pb.F_Int32Defaulted = proto.Int32(pb2.Default_GoTest_F_Int32Defaulted)
+ pb.F_Int64Defaulted = proto.Int64(pb2.Default_GoTest_F_Int64Defaulted)
+ pb.F_Fixed32Defaulted = proto.Uint32(pb2.Default_GoTest_F_Fixed32Defaulted)
+ pb.F_Fixed64Defaulted = proto.Uint64(pb2.Default_GoTest_F_Fixed64Defaulted)
+ pb.F_Uint32Defaulted = proto.Uint32(pb2.Default_GoTest_F_Uint32Defaulted)
+ pb.F_Uint64Defaulted = proto.Uint64(pb2.Default_GoTest_F_Uint64Defaulted)
+ pb.F_FloatDefaulted = proto.Float32(pb2.Default_GoTest_F_FloatDefaulted)
+ pb.F_DoubleDefaulted = proto.Float64(pb2.Default_GoTest_F_DoubleDefaulted)
+ pb.F_StringDefaulted = proto.String(pb2.Default_GoTest_F_StringDefaulted)
+ pb.F_BytesDefaulted = pb2.Default_GoTest_F_BytesDefaulted
+ pb.F_Sint32Defaulted = proto.Int32(pb2.Default_GoTest_F_Sint32Defaulted)
+ pb.F_Sint64Defaulted = proto.Int64(pb2.Default_GoTest_F_Sint64Defaulted)
+ pb.F_Sfixed32Defaulted = proto.Int32(pb2.Default_GoTest_F_Sfixed32Defaulted)
+ pb.F_Sfixed64Defaulted = proto.Int64(pb2.Default_GoTest_F_Sfixed64Defaulted)
+ }
+
+ pb.Kind = pb2.GoTest_TIME.Enum()
+ pb.RequiredField = initGoTestField()
+ pb.F_BoolRequired = proto.Bool(true)
+ pb.F_Int32Required = proto.Int32(3)
+ pb.F_Int64Required = proto.Int64(6)
+ pb.F_Fixed32Required = proto.Uint32(32)
+ pb.F_Fixed64Required = proto.Uint64(64)
+ pb.F_Uint32Required = proto.Uint32(3232)
+ pb.F_Uint64Required = proto.Uint64(6464)
+ pb.F_FloatRequired = proto.Float32(3232)
+ pb.F_DoubleRequired = proto.Float64(6464)
+ pb.F_StringRequired = proto.String("string")
+ pb.F_BytesRequired = []byte("bytes")
+ pb.F_Sint32Required = proto.Int32(-32)
+ pb.F_Sint64Required = proto.Int64(-64)
+ pb.F_Sfixed32Required = proto.Int32(-32)
+ pb.F_Sfixed64Required = proto.Int64(-64)
+ pb.Requiredgroup = initGoTest_RequiredGroup()
+
+ return pb
+}
+
+func overify(t *testing.T, pb *pb2.GoTest, want []byte) {
+ bb := new(proto.Buffer)
+ err := bb.Marshal(pb)
+ got := bb.Bytes()
+ if err != nil {
+ t.Logf("overify marshal-1 err = %v", err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+
+ // Now test Unmarshal by recreating the original buffer.
+ pbd := new(pb2.GoTest)
+ err = bb.Unmarshal(pbd)
+ if err != nil {
+ t.Fatalf("overify unmarshal err = %v", err)
+ }
+ bb.Reset()
+ err = bb.Marshal(pbd)
+ got = bb.Bytes()
+ if err != nil {
+ t.Fatalf("overify marshal-2 err = %v", err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+}
+
+// When hooks are enabled, RequiredNotSetError is typed alias to internal/proto
+// package. Binary serialization has not been wrapped yet and hence produces
+// requiredNotSetError instead. This function is a work-around to identify both
+// aliased and non-aliased types.
+func isRequiredNotSetError(err error) bool {
+ e, ok := err.(interface{ RequiredNotSet() bool })
+ return ok && e.RequiredNotSet()
+}
+
+// Simple tests for numeric encode/decode primitives (varint, etc.)
+func TestNumericPrimitives(t *testing.T) {
+ for i := uint64(0); i < 1e6; i += 111 {
+ o := new(proto.Buffer)
+ if o.EncodeVarint(i) != nil {
+ t.Error("EncodeVarint")
+ break
+ }
+ x, e := o.DecodeVarint()
+ if e != nil {
+ t.Fatal("DecodeVarint")
+ }
+ if x != i {
+ t.Fatal("varint decode fail:", i, x)
+ }
+
+ o.Reset()
+ if o.EncodeFixed32(i) != nil {
+ t.Fatal("encFixed32")
+ }
+ x, e = o.DecodeFixed32()
+ if e != nil {
+ t.Fatal("decFixed32")
+ }
+ if x != i {
+ t.Fatal("fixed32 decode fail:", i, x)
+ }
+
+ o.Reset()
+ if o.EncodeFixed64(i*1234567) != nil {
+ t.Error("encFixed64")
+ break
+ }
+ x, e = o.DecodeFixed64()
+ if e != nil {
+ t.Error("decFixed64")
+ break
+ }
+ if x != i*1234567 {
+ t.Error("fixed64 decode fail:", i*1234567, x)
+ break
+ }
+
+ o.Reset()
+ i32 := int32(i - 12345)
+ if o.EncodeZigzag32(uint64(i32)) != nil {
+ t.Fatal("EncodeZigzag32")
+ }
+ x, e = o.DecodeZigzag32()
+ if e != nil {
+ t.Fatal("DecodeZigzag32")
+ }
+ if x != uint64(uint32(i32)) {
+ t.Fatal("zigzag32 decode fail:", i32, x)
+ }
+
+ o.Reset()
+ i64 := int64(i - 12345)
+ if o.EncodeZigzag64(uint64(i64)) != nil {
+ t.Fatal("EncodeZigzag64")
+ }
+ x, e = o.DecodeZigzag64()
+ if e != nil {
+ t.Fatal("DecodeZigzag64")
+ }
+ if x != uint64(i64) {
+ t.Fatal("zigzag64 decode fail:", i64, x)
+ }
+ }
+}
+
+// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces.
+type fakeMarshaler struct {
+ b []byte
+ err error
+}
+
+func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err }
+func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) }
+func (f *fakeMarshaler) ProtoMessage() {}
+func (f *fakeMarshaler) Reset() {}
+
+type msgWithFakeMarshaler struct {
+ M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"`
+}
+
+func (m *msgWithFakeMarshaler) String() string { return proto.CompactTextString(m) }
+func (m *msgWithFakeMarshaler) ProtoMessage() {}
+func (m *msgWithFakeMarshaler) Reset() {}
+
+// Simple tests for proto messages that implement the Marshaler interface.
+func TestMarshalerEncoding(t *testing.T) {
+ tests := []struct {
+ name string
+ m proto.Message
+ want []byte
+ errType reflect.Type
+ }{
+ {
+ name: "Marshaler that fails",
+ m: &fakeMarshaler{
+ err: errors.New("some marshal err"),
+ b: []byte{5, 6, 7},
+ },
+ errType: reflect.TypeOf(errors.New("some marshal err")),
+ },
+ {
+ name: "Marshaler that fails with RequiredNotSetError",
+ m: &msgWithFakeMarshaler{
+ M: &fakeMarshaler{
+ err: &proto.RequiredNotSetError{},
+ b: []byte{5, 6, 7},
+ },
+ },
+ errType: reflect.TypeOf(&proto.RequiredNotSetError{}),
+ },
+ {
+ name: "Marshaler that succeeds",
+ m: &fakeMarshaler{
+ b: []byte{0, 1, 2, 3, 4, 127, 255},
+ },
+ want: []byte{0, 1, 2, 3, 4, 127, 255},
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ b := proto.NewBuffer(nil)
+ err := b.Marshal(test.m)
+ if reflect.TypeOf(err) != test.errType {
+ t.Errorf("got err %T(%v) wanted %T", err, err, test.errType)
+ }
+ if err != nil {
+ return // skip comparing output when marshal fails.
+ }
+ if !reflect.DeepEqual(test.want, b.Bytes()) {
+ t.Errorf("got bytes %v wanted %v", b.Bytes(), test.want)
+ }
+ if size := proto.Size(test.m); size != len(b.Bytes()) {
+ t.Errorf("Size(_) = %v, but marshaled to %v bytes", size, len(b.Bytes()))
+ }
+
+ m, mErr := proto.Marshal(test.m)
+ if !bytes.Equal(b.Bytes(), m) {
+ t.Errorf("Marshal returned %v, but (*Buffer).Marshal wrote %v", m, b.Bytes())
+ }
+ if !reflect.DeepEqual(err, mErr) {
+ t.Errorf("Marshal err = %v, but (*Buffer).Marshal returned %v", mErr, err)
+ }
+ })
+ }
+}
+
+// Ensure that Buffer.Marshal uses O(N) memory for N messages
+func TestBufferMarshalAllocs(t *testing.T) {
+ value := &pb2.OtherMessage{Key: proto.Int64(1)}
+ msg := &pb2.MyMessage{Count: proto.Int32(1), Others: []*pb2.OtherMessage{value}}
+
+ for _, prealloc := range []int{0, 100, 10000} {
+ const count = 1000
+ var b proto.Buffer
+ s := make([]byte, 0, proto.Size(msg))
+ marshalAllocs := testing.AllocsPerRun(count, func() {
+ b.SetBuf(s)
+ err := b.Marshal(msg)
+ if err != nil {
+ t.Errorf("Marshal err = %q", err)
+ }
+ })
+
+ b.SetBuf(make([]byte, 0, prealloc))
+ bufferAllocs := testing.AllocsPerRun(count, func() {
+ err := b.Marshal(msg)
+ if err != nil {
+ t.Errorf("Marshal err = %q", err)
+ }
+ })
+
+ if marshalAllocs != bufferAllocs {
+ t.Errorf("%v allocs/op when writing to a preallocated buffer", marshalAllocs)
+ t.Errorf("%v allocs/op when repeatedly appending to a buffer", bufferAllocs)
+ t.Errorf("expect amortized allocs/op to be identical")
+ }
+ }
+}
+
+// Simple tests for bytes
+func TestBytesPrimitives(t *testing.T) {
+ bb := new(proto.Buffer)
+ want := []byte("now is the time")
+ if err := bb.EncodeRawBytes(want); err != nil {
+ t.Errorf("EncodeRawBytes error: %v", err)
+ }
+ got, err := bb.DecodeRawBytes(false)
+ if err != nil {
+ t.Errorf("DecodeRawBytes error: %v", err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Errorf("got %q\nwant %q", got, want)
+ }
+}
+
+// Simple tests for strings
+func TestStringPrimitives(t *testing.T) {
+ bb := new(proto.Buffer)
+ want := "now is the time"
+ if err := bb.EncodeStringBytes(want); err != nil {
+ t.Errorf("EncodeStringBytes error: %v", err)
+ }
+ got, err := bb.DecodeStringBytes()
+ if err != nil {
+ t.Errorf("DecodeStringBytes error: %v", err)
+ }
+ if got != want {
+ t.Errorf("got %q\nwant %q", got, want)
+ }
+}
+
+// Do we catch the "required bit not set" case?
+func TestRequiredBit(t *testing.T) {
+ o := new(proto.Buffer)
+ pb := new(pb2.GoTest)
+ err := o.Marshal(pb)
+ if err == nil {
+ t.Error("did not catch missing required fields")
+ } else if !strings.Contains(err.Error(), "Kind") {
+ t.Error("wrong error type:", err)
+ }
+}
+
+// Check that all fields are nil.
+// Clearly silly, and a residue from a more interesting test with an earlier,
+// different initialization property, but it once caught a compiler bug so
+// it lives.
+func checkInitialized(pb *pb2.GoTest, t *testing.T) {
+ switch {
+ case pb.F_BoolDefaulted != nil:
+ t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
+ case pb.F_Int32Defaulted != nil:
+ t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
+ case pb.F_Int64Defaulted != nil:
+ t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
+ case pb.F_Fixed32Defaulted != nil:
+ t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
+ case pb.F_Fixed64Defaulted != nil:
+ t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
+ case pb.F_Uint32Defaulted != nil:
+ t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
+ case pb.F_Uint64Defaulted != nil:
+ t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
+ case pb.F_FloatDefaulted != nil:
+ t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
+ case pb.F_DoubleDefaulted != nil:
+ t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
+ case pb.F_StringDefaulted != nil:
+ t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
+ case pb.F_BytesDefaulted != nil:
+ t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
+ case pb.F_Sint32Defaulted != nil:
+ t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
+ case pb.F_Sint64Defaulted != nil:
+ t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
+ }
+}
+
+// Does Reset() reset?
+func TestReset(t *testing.T) {
+ pb := initGoTest(true)
+ // muck with some values
+ pb.F_BoolDefaulted = proto.Bool(false)
+ pb.F_Int32Defaulted = proto.Int32(237)
+ pb.F_Int64Defaulted = proto.Int64(12346)
+ pb.F_Fixed32Defaulted = proto.Uint32(32000)
+ pb.F_Fixed64Defaulted = proto.Uint64(666)
+ pb.F_Uint32Defaulted = proto.Uint32(323232)
+ pb.F_Uint64Defaulted = nil
+ pb.F_FloatDefaulted = nil
+ pb.F_DoubleDefaulted = proto.Float64(0)
+ pb.F_StringDefaulted = proto.String("gotcha")
+ pb.F_BytesDefaulted = []byte("asdfasdf")
+ pb.F_Sint32Defaulted = proto.Int32(123)
+ pb.F_Sint64Defaulted = proto.Int64(789)
+ pb.Reset()
+ checkInitialized(pb, t)
+}
+
+// All required fields set, no defaults provided.
+func TestEncodeDecode1(t *testing.T) {
+ pb := initGoTest(false)
+ overify(t, pb,
+ protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{11, protopack.VarintType}, protopack.Varint(3),
+ protopack.Tag{12, protopack.VarintType}, protopack.Varint(6),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ }.Marshal())
+}
+
+// All required fields set, defaults provided.
+func TestEncodeDecode2(t *testing.T) {
+ pb := initGoTest(true)
+ overify(t, pb,
+ protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{11, protopack.VarintType}, protopack.Varint(3),
+ protopack.Tag{12, protopack.VarintType}, protopack.Varint(6),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{40, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{41, protopack.VarintType}, protopack.Varint(32),
+ protopack.Tag{42, protopack.VarintType}, protopack.Varint(64),
+ protopack.Tag{43, protopack.Fixed32Type}, protopack.Uint32(320),
+ protopack.Tag{44, protopack.Fixed64Type}, protopack.Uint64(640),
+ protopack.Tag{45, protopack.VarintType}, protopack.Uvarint(3200),
+ protopack.Tag{46, protopack.VarintType}, protopack.Uvarint(6400),
+ protopack.Tag{47, protopack.Fixed32Type}, protopack.Float32(314159),
+ protopack.Tag{48, protopack.Fixed64Type}, protopack.Float64(271828),
+ protopack.Tag{49, protopack.BytesType}, protopack.String("hello, \"world!\"\n"),
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{401, protopack.BytesType}, protopack.Bytes("Bignose"),
+ protopack.Tag{402, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{403, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{404, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{405, protopack.Fixed64Type}, protopack.Int64(-64),
+ }.Marshal())
+}
+
+// All default fields set to their default value by hand
+func TestEncodeDecode3(t *testing.T) {
+ pb := initGoTest(false)
+ pb.F_BoolDefaulted = proto.Bool(true)
+ pb.F_Int32Defaulted = proto.Int32(32)
+ pb.F_Int64Defaulted = proto.Int64(64)
+ pb.F_Fixed32Defaulted = proto.Uint32(320)
+ pb.F_Fixed64Defaulted = proto.Uint64(640)
+ pb.F_Uint32Defaulted = proto.Uint32(3200)
+ pb.F_Uint64Defaulted = proto.Uint64(6400)
+ pb.F_FloatDefaulted = proto.Float32(314159)
+ pb.F_DoubleDefaulted = proto.Float64(271828)
+ pb.F_StringDefaulted = proto.String("hello, \"world!\"\n")
+ pb.F_BytesDefaulted = []byte("Bignose")
+ pb.F_Sint32Defaulted = proto.Int32(-32)
+ pb.F_Sint64Defaulted = proto.Int64(-64)
+ pb.F_Sfixed32Defaulted = proto.Int32(-32)
+ pb.F_Sfixed64Defaulted = proto.Int64(-64)
+
+ overify(t, pb,
+ protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{11, protopack.VarintType}, protopack.Varint(3),
+ protopack.Tag{12, protopack.VarintType}, protopack.Varint(6),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{40, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{41, protopack.VarintType}, protopack.Varint(32),
+ protopack.Tag{42, protopack.VarintType}, protopack.Varint(64),
+ protopack.Tag{43, protopack.Fixed32Type}, protopack.Uint32(320),
+ protopack.Tag{44, protopack.Fixed64Type}, protopack.Uint64(640),
+ protopack.Tag{45, protopack.VarintType}, protopack.Uvarint(3200),
+ protopack.Tag{46, protopack.VarintType}, protopack.Uvarint(6400),
+ protopack.Tag{47, protopack.Fixed32Type}, protopack.Float32(314159),
+ protopack.Tag{48, protopack.Fixed64Type}, protopack.Float64(271828),
+ protopack.Tag{49, protopack.BytesType}, protopack.String("hello, \"world!\"\n"),
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{401, protopack.BytesType}, protopack.Bytes("Bignose"),
+ protopack.Tag{402, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{403, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{404, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{405, protopack.Fixed64Type}, protopack.Int64(-64),
+ }.Marshal())
+}
+
+// All required fields set, defaults provided, all non-defaulted optional fields have values.
+func TestEncodeDecode4(t *testing.T) {
+ pb := initGoTest(true)
+ pb.Table = proto.String("hello")
+ pb.Param = proto.Int32(7)
+ pb.OptionalField = initGoTestField()
+ pb.F_BoolOptional = proto.Bool(true)
+ pb.F_Int32Optional = proto.Int32(32)
+ pb.F_Int64Optional = proto.Int64(64)
+ pb.F_Fixed32Optional = proto.Uint32(3232)
+ pb.F_Fixed64Optional = proto.Uint64(6464)
+ pb.F_Uint32Optional = proto.Uint32(323232)
+ pb.F_Uint64Optional = proto.Uint64(646464)
+ pb.F_FloatOptional = proto.Float32(32.)
+ pb.F_DoubleOptional = proto.Float64(64.)
+ pb.F_StringOptional = proto.String("hello")
+ pb.F_BytesOptional = []byte("Bignose")
+ pb.F_Sint32Optional = proto.Int32(-32)
+ pb.F_Sint64Optional = proto.Int64(-64)
+ pb.F_Sfixed32Optional = proto.Int32(-32)
+ pb.F_Sfixed64Optional = proto.Int64(-64)
+ pb.Optionalgroup = initGoTest_OptionalGroup()
+
+ overify(t, pb,
+ protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("hello"),
+ protopack.Tag{3, protopack.VarintType}, protopack.Varint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{6, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{11, protopack.VarintType}, protopack.Varint(3),
+ protopack.Tag{12, protopack.VarintType}, protopack.Varint(6),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{30, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{31, protopack.VarintType}, protopack.Varint(32),
+ protopack.Tag{32, protopack.VarintType}, protopack.Varint(64),
+ protopack.Tag{33, protopack.Fixed32Type}, protopack.Uint32(3232),
+ protopack.Tag{34, protopack.Fixed64Type}, protopack.Uint64(6464),
+ protopack.Tag{35, protopack.VarintType}, protopack.Uvarint(323232),
+ protopack.Tag{36, protopack.VarintType}, protopack.Uvarint(646464),
+ protopack.Tag{37, protopack.Fixed32Type}, protopack.Float32(32),
+ protopack.Tag{38, protopack.Fixed64Type}, protopack.Float64(64),
+ protopack.Tag{39, protopack.BytesType}, protopack.String("hello"),
+ protopack.Tag{40, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{41, protopack.VarintType}, protopack.Varint(32),
+ protopack.Tag{42, protopack.VarintType}, protopack.Varint(64),
+ protopack.Tag{43, protopack.Fixed32Type}, protopack.Uint32(320),
+ protopack.Tag{44, protopack.Fixed64Type}, protopack.Uint64(640),
+ protopack.Tag{45, protopack.VarintType}, protopack.Uvarint(3200),
+ protopack.Tag{46, protopack.VarintType}, protopack.Uvarint(6400),
+ protopack.Tag{47, protopack.Fixed32Type}, protopack.Float32(314159),
+ protopack.Tag{48, protopack.Fixed64Type}, protopack.Float64(271828),
+ protopack.Tag{49, protopack.BytesType}, protopack.String("hello, \"world!\"\n"),
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{90, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{91, protopack.BytesType}, protopack.String("optional"),
+ },
+ protopack.Tag{90, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{301, protopack.BytesType}, protopack.Bytes("Bignose"),
+ protopack.Tag{302, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{303, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{304, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{305, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{401, protopack.BytesType}, protopack.Bytes("Bignose"),
+ protopack.Tag{402, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{403, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{404, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{405, protopack.Fixed64Type}, protopack.Int64(-64),
+ }.Marshal())
+}
+
+// All required fields set, defaults provided, all repeated fields given two values.
+func TestEncodeDecode5(t *testing.T) {
+ pb := initGoTest(true)
+ pb.RepeatedField = []*pb2.GoTestField{initGoTestField(), initGoTestField()}
+ pb.F_BoolRepeated = []bool{false, true}
+ pb.F_Int32Repeated = []int32{32, 33}
+ pb.F_Int64Repeated = []int64{64, 65}
+ pb.F_Fixed32Repeated = []uint32{3232, 3333}
+ pb.F_Fixed64Repeated = []uint64{6464, 6565}
+ pb.F_Uint32Repeated = []uint32{323232, 333333}
+ pb.F_Uint64Repeated = []uint64{646464, 656565}
+ pb.F_FloatRepeated = []float32{32., 33.}
+ pb.F_DoubleRepeated = []float64{64., 65.}
+ pb.F_StringRepeated = []string{"hello", "sailor"}
+ pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
+ pb.F_Sint32Repeated = []int32{32, -32}
+ pb.F_Sint64Repeated = []int64{64, -64}
+ pb.F_Sfixed32Repeated = []int32{32, -32}
+ pb.F_Sfixed64Repeated = []int64{64, -64}
+ pb.Repeatedgroup = []*pb2.GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
+
+ overify(t, pb,
+ protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{5, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{5, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{11, protopack.VarintType}, protopack.Varint(3),
+ protopack.Tag{12, protopack.VarintType}, protopack.Varint(6),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{20, protopack.VarintType}, protopack.Bool(false),
+ protopack.Tag{20, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{21, protopack.VarintType}, protopack.Varint(32),
+ protopack.Tag{21, protopack.VarintType}, protopack.Varint(33),
+ protopack.Tag{22, protopack.VarintType}, protopack.Varint(64),
+ protopack.Tag{22, protopack.VarintType}, protopack.Varint(65),
+ protopack.Tag{23, protopack.Fixed32Type}, protopack.Uint32(3232),
+ protopack.Tag{23, protopack.Fixed32Type}, protopack.Uint32(3333),
+ protopack.Tag{24, protopack.Fixed64Type}, protopack.Uint64(6464),
+ protopack.Tag{24, protopack.Fixed64Type}, protopack.Uint64(6565),
+ protopack.Tag{25, protopack.VarintType}, protopack.Uvarint(323232),
+ protopack.Tag{25, protopack.VarintType}, protopack.Uvarint(333333),
+ protopack.Tag{26, protopack.VarintType}, protopack.Uvarint(646464),
+ protopack.Tag{26, protopack.VarintType}, protopack.Uvarint(656565),
+ protopack.Tag{27, protopack.Fixed32Type}, protopack.Float32(32),
+ protopack.Tag{27, protopack.Fixed32Type}, protopack.Float32(33),
+ protopack.Tag{28, protopack.Fixed64Type}, protopack.Float64(64),
+ protopack.Tag{28, protopack.Fixed64Type}, protopack.Float64(65),
+ protopack.Tag{29, protopack.BytesType}, protopack.String("hello"),
+ protopack.Tag{29, protopack.BytesType}, protopack.String("sailor"),
+ protopack.Tag{40, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{41, protopack.VarintType}, protopack.Varint(32),
+ protopack.Tag{42, protopack.VarintType}, protopack.Varint(64),
+ protopack.Tag{43, protopack.Fixed32Type}, protopack.Uint32(320),
+ protopack.Tag{44, protopack.Fixed64Type}, protopack.Uint64(640),
+ protopack.Tag{45, protopack.VarintType}, protopack.Uvarint(3200),
+ protopack.Tag{46, protopack.VarintType}, protopack.Uvarint(6400),
+ protopack.Tag{47, protopack.Fixed32Type}, protopack.Float32(314159),
+ protopack.Tag{48, protopack.Fixed64Type}, protopack.Float64(271828),
+ protopack.Tag{49, protopack.BytesType}, protopack.String("hello, \"world!\"\n"),
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{80, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{81, protopack.BytesType}, protopack.String("repeated"),
+ },
+ protopack.Tag{80, protopack.EndGroupType},
+ protopack.Tag{80, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{81, protopack.BytesType}, protopack.String("repeated"),
+ },
+ protopack.Tag{80, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{201, protopack.BytesType}, protopack.Bytes("big"),
+ protopack.Tag{201, protopack.BytesType}, protopack.Bytes("nose"),
+ protopack.Tag{202, protopack.VarintType}, protopack.Svarint(32),
+ protopack.Tag{202, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{203, protopack.VarintType}, protopack.Svarint(64),
+ protopack.Tag{203, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{204, protopack.Fixed32Type}, protopack.Int32(32),
+ protopack.Tag{204, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{205, protopack.Fixed64Type}, protopack.Int64(64),
+ protopack.Tag{205, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{401, protopack.BytesType}, protopack.Bytes("Bignose"),
+ protopack.Tag{402, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{403, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{404, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{405, protopack.Fixed64Type}, protopack.Int64(-64),
+ }.Marshal())
+}
+
+// All required fields set, all packed repeated fields given two values.
+func TestEncodeDecode6(t *testing.T) {
+ pb := initGoTest(false)
+ pb.F_BoolRepeatedPacked = []bool{false, true}
+ pb.F_Int32RepeatedPacked = []int32{32, 33}
+ pb.F_Int64RepeatedPacked = []int64{64, 65}
+ pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
+ pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
+ pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
+ pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
+ pb.F_FloatRepeatedPacked = []float32{32., 33.}
+ pb.F_DoubleRepeatedPacked = []float64{64., 65.}
+ pb.F_Sint32RepeatedPacked = []int32{32, -32}
+ pb.F_Sint64RepeatedPacked = []int64{64, -64}
+ pb.F_Sfixed32RepeatedPacked = []int32{32, -32}
+ pb.F_Sfixed64RepeatedPacked = []int64{64, -64}
+
+ overify(t, pb,
+ protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("label"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{11, protopack.VarintType}, protopack.Varint(3),
+ protopack.Tag{12, protopack.VarintType}, protopack.Varint(6),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{50, protopack.BytesType}, protopack.LengthPrefix{protopack.Bool(false), protopack.Bool(true)},
+ protopack.Tag{51, protopack.BytesType}, protopack.LengthPrefix{protopack.Varint(32), protopack.Varint(33)},
+ protopack.Tag{52, protopack.BytesType}, protopack.LengthPrefix{protopack.Varint(64), protopack.Varint(65)},
+ protopack.Tag{53, protopack.BytesType}, protopack.LengthPrefix{protopack.Uint32(3232), protopack.Uint32(3333)},
+ protopack.Tag{54, protopack.BytesType}, protopack.LengthPrefix{protopack.Uint64(6464), protopack.Uint64(6565)},
+ protopack.Tag{55, protopack.BytesType}, protopack.LengthPrefix{protopack.Uvarint(323232), protopack.Uvarint(333333)},
+ protopack.Tag{56, protopack.BytesType}, protopack.LengthPrefix{protopack.Uvarint(646464), protopack.Uvarint(656565)},
+ protopack.Tag{57, protopack.BytesType}, protopack.LengthPrefix{protopack.Float32(32), protopack.Float32(33)},
+ protopack.Tag{58, protopack.BytesType}, protopack.LengthPrefix{protopack.Float64(64), protopack.Float64(65)},
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ protopack.Tag{502, protopack.BytesType}, protopack.LengthPrefix{protopack.Svarint(32), protopack.Svarint(-32)},
+ protopack.Tag{503, protopack.BytesType}, protopack.LengthPrefix{protopack.Svarint(64), protopack.Svarint(-64)},
+ protopack.Tag{504, protopack.BytesType}, protopack.LengthPrefix{protopack.Int32(32), protopack.Int32(-32)},
+ protopack.Tag{505, protopack.BytesType}, protopack.LengthPrefix{protopack.Int64(64), protopack.Int64(-64)},
+ }.Marshal())
+}
+
+// Test that we can encode empty bytes fields.
+func TestEncodeDecodeBytes1(t *testing.T) {
+ pb := initGoTest(false)
+
+ // Create our bytes
+ pb.F_BytesRequired = []byte{}
+ pb.F_BytesRepeated = [][]byte{{}}
+ pb.F_BytesOptional = []byte{}
+
+ d, err := proto.Marshal(pb)
+ if err != nil {
+ t.Error(err)
+ }
+
+ pbd := new(pb2.GoTest)
+ if err := proto.Unmarshal(d, pbd); err != nil {
+ t.Error(err)
+ }
+
+ if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
+ t.Error("required empty bytes field is incorrect")
+ }
+ if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
+ t.Error("repeated empty bytes field is incorrect")
+ }
+ if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
+ t.Error("optional empty bytes field is incorrect")
+ }
+}
+
+// Test that we encode nil-valued fields of a repeated bytes field correctly.
+// Since entries in a repeated field cannot be nil, nil must mean empty value.
+func TestEncodeDecodeBytes2(t *testing.T) {
+ pb := initGoTest(false)
+
+ // Create our bytes
+ pb.F_BytesRepeated = [][]byte{nil}
+
+ d, err := proto.Marshal(pb)
+ if err != nil {
+ t.Error(err)
+ }
+
+ pbd := new(pb2.GoTest)
+ if err := proto.Unmarshal(d, pbd); err != nil {
+ t.Error(err)
+ }
+
+ if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
+ t.Error("Unexpected value for repeated bytes field")
+ }
+}
+
+// All required fields set, defaults provided, all repeated fields given two values.
+func TestSkippingUnrecognizedFields(t *testing.T) {
+ o := new(proto.Buffer)
+ pb := initGoTestField()
+
+ // Marshal it normally.
+ o.Marshal(pb)
+
+ // Now new a GoSkipTest record.
+ skip := &pb2.GoSkipTest{
+ SkipInt32: proto.Int32(32),
+ SkipFixed32: proto.Uint32(3232),
+ SkipFixed64: proto.Uint64(6464),
+ SkipString: proto.String("skipper"),
+ Skipgroup: &pb2.GoSkipTest_SkipGroup{
+ GroupInt32: proto.Int32(75),
+ GroupString: proto.String("wxyz"),
+ },
+ }
+
+ // Marshal it into same buffer.
+ o.Marshal(skip)
+
+ pbd := new(pb2.GoTestField)
+ o.Unmarshal(pbd)
+
+ // The __unrecognized field should be a marshaling of GoSkipTest
+ skipd := new(pb2.GoSkipTest)
+
+ o.SetBuf(pbd.XXX_unrecognized)
+ o.Unmarshal(skipd)
+
+ switch {
+ case *skipd.SkipInt32 != *skip.SkipInt32:
+ t.Error("skip int32", skipd.SkipInt32)
+ case *skipd.SkipFixed32 != *skip.SkipFixed32:
+ t.Error("skip fixed32", skipd.SkipFixed32)
+ case *skipd.SkipFixed64 != *skip.SkipFixed64:
+ t.Error("skip fixed64", skipd.SkipFixed64)
+ case *skipd.SkipString != *skip.SkipString:
+ t.Error("skip string", *skipd.SkipString)
+ case *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32:
+ t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
+ case *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString:
+ t.Error("skip group string", *skipd.Skipgroup.GroupString)
+ }
+}
+
+// Check that unrecognized fields of a submessage are preserved.
+func TestSubmessageUnrecognizedFields(t *testing.T) {
+ nm := &pb2.NewMessage{
+ Nested: &pb2.NewMessage_Nested{
+ Name: proto.String("Nigel"),
+ FoodGroup: proto.String("carbs"),
+ },
+ }
+ b, err := proto.Marshal(nm)
+ if err != nil {
+ t.Fatalf("Marshal of NewMessage: %v", err)
+ }
+
+ // Unmarshal into an OldMessage.
+ om := new(pb2.OldMessage)
+ if err := proto.Unmarshal(b, om); err != nil {
+ t.Fatalf("Unmarshal to OldMessage: %v", err)
+ }
+ exp := &pb2.OldMessage{
+ Nested: &pb2.OldMessage_Nested{
+ Name: proto.String("Nigel"),
+ // normal protocol buffer users should not do this
+ XXX_unrecognized: []byte("\x12\x05carbs"),
+ },
+ }
+ if !proto.Equal(om, exp) {
+ t.Errorf("om = %v, want %v", om, exp)
+ }
+
+ // Clone the OldMessage.
+ om = proto.Clone(om).(*pb2.OldMessage)
+ if !proto.Equal(om, exp) {
+ t.Errorf("Clone(om) = %v, want %v", om, exp)
+ }
+
+ // Marshal the OldMessage, then unmarshal it into an empty NewMessage.
+ if b, err = proto.Marshal(om); err != nil {
+ t.Fatalf("Marshal of OldMessage: %v", err)
+ }
+ t.Logf("Marshal(%v) -> %q", om, b)
+ nm2 := new(pb2.NewMessage)
+ if err := proto.Unmarshal(b, nm2); err != nil {
+ t.Fatalf("Unmarshal to NewMessage: %v", err)
+ }
+ if !proto.Equal(nm, nm2) {
+ t.Errorf("NewMessage round-trip: %v => %v", nm, nm2)
+ }
+}
+
+// Check that an int32 field can be upgraded to an int64 field.
+func TestNegativeInt32(t *testing.T) {
+ om := &pb2.OldMessage{
+ Num: proto.Int32(-1),
+ }
+ b, err := proto.Marshal(om)
+ if err != nil {
+ t.Fatalf("Marshal of OldMessage: %v", err)
+ }
+
+ // Check the size. It should be 11 bytes;
+ // 1 for the field/wire type, and 10 for the negative number.
+ if len(b) != 11 {
+ t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b)
+ }
+
+ // Unmarshal into a NewMessage.
+ nm := new(pb2.NewMessage)
+ if err := proto.Unmarshal(b, nm); err != nil {
+ t.Fatalf("Unmarshal to NewMessage: %v", err)
+ }
+ want := &pb2.NewMessage{
+ Num: proto.Int64(-1),
+ }
+ if !proto.Equal(nm, want) {
+ t.Errorf("nm = %v, want %v", nm, want)
+ }
+}
+
+// Check that we can grow an array (repeated field) to have many elements.
+// This test doesn't depend only on our encoding; for variety, it makes sure
+// we create, encode, and decode the correct contents explicitly. It's therefore
+// a bit messier.
+// This test also uses (and hence tests) the Marshal/Unmarshal functions
+// instead of the methods.
+func TestBigRepeated(t *testing.T) {
+ pb := initGoTest(true)
+
+ // Create the arrays
+ const N = 50 // Internally the library starts much smaller.
+ pb.Repeatedgroup = make([]*pb2.GoTest_RepeatedGroup, N)
+ pb.F_Sint64Repeated = make([]int64, N)
+ pb.F_Sint32Repeated = make([]int32, N)
+ pb.F_BytesRepeated = make([][]byte, N)
+ pb.F_StringRepeated = make([]string, N)
+ pb.F_DoubleRepeated = make([]float64, N)
+ pb.F_FloatRepeated = make([]float32, N)
+ pb.F_Uint64Repeated = make([]uint64, N)
+ pb.F_Uint32Repeated = make([]uint32, N)
+ pb.F_Fixed64Repeated = make([]uint64, N)
+ pb.F_Fixed32Repeated = make([]uint32, N)
+ pb.F_Int64Repeated = make([]int64, N)
+ pb.F_Int32Repeated = make([]int32, N)
+ pb.F_BoolRepeated = make([]bool, N)
+ pb.RepeatedField = make([]*pb2.GoTestField, N)
+
+ // Fill in the arrays with checkable values.
+ igtf := initGoTestField()
+ igtrg := initGoTest_RepeatedGroup()
+ for i := 0; i < N; i++ {
+ pb.Repeatedgroup[i] = igtrg
+ pb.F_Sint64Repeated[i] = int64(i)
+ pb.F_Sint32Repeated[i] = int32(i)
+ s := fmt.Sprint(i)
+ pb.F_BytesRepeated[i] = []byte(s)
+ pb.F_StringRepeated[i] = s
+ pb.F_DoubleRepeated[i] = float64(i)
+ pb.F_FloatRepeated[i] = float32(i)
+ pb.F_Uint64Repeated[i] = uint64(i)
+ pb.F_Uint32Repeated[i] = uint32(i)
+ pb.F_Fixed64Repeated[i] = uint64(i)
+ pb.F_Fixed32Repeated[i] = uint32(i)
+ pb.F_Int64Repeated[i] = int64(i)
+ pb.F_Int32Repeated[i] = int32(i)
+ pb.F_BoolRepeated[i] = i%2 == 0
+ pb.RepeatedField[i] = igtf
+ }
+
+ // Marshal.
+ buf, _ := proto.Marshal(pb)
+
+ // Now test Unmarshal by recreating the original buffer.
+ pbd := new(pb2.GoTest)
+ proto.Unmarshal(buf, pbd)
+
+ // Check the checkable values
+ for i := uint64(0); i < N; i++ {
+ switch {
+ case pbd.Repeatedgroup[i] == nil:
+ t.Error("pbd.Repeatedgroup bad")
+ case uint64(pbd.F_Sint64Repeated[i]) != i:
+ t.Error("pbd.F_Sint64Repeated bad", uint64(pbd.F_Sint64Repeated[i]), i)
+ case uint64(pbd.F_Sint32Repeated[i]) != i:
+ t.Error("pbd.F_Sint32Repeated bad", uint64(pbd.F_Sint32Repeated[i]), i)
+ case !bytes.Equal(pbd.F_BytesRepeated[i], []byte(fmt.Sprint(i))):
+ t.Error("pbd.F_BytesRepeated bad", pbd.F_BytesRepeated[i], i)
+ case pbd.F_StringRepeated[i] != string(fmt.Sprint(i)):
+ t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
+ case uint64(pbd.F_DoubleRepeated[i]) != i:
+ t.Error("pbd.F_DoubleRepeated bad", uint64(pbd.F_DoubleRepeated[i]), i)
+ case uint64(pbd.F_FloatRepeated[i]) != i:
+ t.Error("pbd.F_FloatRepeated bad", uint64(pbd.F_FloatRepeated[i]), i)
+ case pbd.F_Uint64Repeated[i] != i:
+ t.Error("pbd.F_Uint64Repeated bad", pbd.F_Uint64Repeated[i], i)
+ case uint64(pbd.F_Uint32Repeated[i]) != i:
+ t.Error("pbd.F_Uint32Repeated bad", uint64(pbd.F_Uint32Repeated[i]), i)
+ case pbd.F_Fixed64Repeated[i] != i:
+ t.Error("pbd.F_Fixed64Repeated bad", pbd.F_Fixed64Repeated[i], i)
+ case uint64(pbd.F_Fixed32Repeated[i]) != i:
+ t.Error("pbd.F_Fixed32Repeated bad", uint64(pbd.F_Fixed32Repeated[i]), i)
+ case uint64(pbd.F_Int64Repeated[i]) != i:
+ t.Error("pbd.F_Int64Repeated bad", uint64(pbd.F_Int64Repeated[i]), i)
+ case uint64(pbd.F_Int32Repeated[i]) != i:
+ t.Error("pbd.F_Int32Repeated bad", uint64(pbd.F_Int32Repeated[i]), i)
+ case pbd.F_BoolRepeated[i] != (i%2 == 0):
+ t.Error("pbd.F_BoolRepeated bad", pbd.F_BoolRepeated[i], i)
+ case pbd.RepeatedField[i] == nil:
+ t.Error("pbd.RepeatedField bad")
+ }
+ }
+}
+
+func TestBadWireTypeUnknown(t *testing.T) {
+ b := protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.Bytes("x"),
+ protopack.Tag{1, protopack.Fixed32Type}, protopack.Uint32(0),
+ protopack.Tag{1, protopack.VarintType}, protopack.Varint(11),
+ protopack.Tag{2, protopack.VarintType}, protopack.Uvarint(22),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("aaa"),
+ protopack.Tag{2, protopack.Fixed32Type}, protopack.Uint32(33),
+ protopack.Tag{4, protopack.VarintType}, protopack.Uvarint(44),
+ protopack.Tag{4, protopack.BytesType}, protopack.String("bbb"),
+ protopack.Tag{4, protopack.Fixed32Type}, protopack.Uint32(55),
+ protopack.Tag{4, protopack.BytesType}, protopack.String("ccc"),
+ protopack.Tag{4, protopack.Fixed64Type}, protopack.Uint64(66),
+ protopack.Tag{11, protopack.VarintType}, protopack.Uvarint(77),
+ protopack.Tag{11, protopack.BytesType}, protopack.Bytes("ddd"),
+ protopack.Tag{11, protopack.Fixed64Type}, protopack.Float64(88),
+ protopack.Tag{11, protopack.Fixed32Type}, protopack.Uint32(99),
+ }.Marshal()
+
+ m := new(pb2.MyMessage)
+ if err := proto.Unmarshal(b, m); err != nil {
+ t.Errorf("unexpected Unmarshal error: %v", err)
+ }
+
+ unknown := protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.Bytes("x"),
+ protopack.Tag{1, protopack.Fixed32Type}, protopack.Uint32(0),
+ protopack.Tag{2, protopack.VarintType}, protopack.Uvarint(22),
+ protopack.Tag{2, protopack.Fixed32Type}, protopack.Uint32(33),
+ protopack.Tag{4, protopack.VarintType}, protopack.Uvarint(44),
+ protopack.Tag{4, protopack.Fixed32Type}, protopack.Uint32(55),
+ protopack.Tag{4, protopack.Fixed64Type}, protopack.Uint64(66),
+ protopack.Tag{11, protopack.VarintType}, protopack.Uvarint(77),
+ protopack.Tag{11, protopack.BytesType}, protopack.Bytes("ddd"),
+ protopack.Tag{11, protopack.Fixed32Type}, protopack.Uint32(99),
+ }.Marshal()
+ if !bytes.Equal(m.XXX_unrecognized, unknown) {
+ t.Errorf("unknown bytes mismatch:\ngot %x\nwant %x", m.XXX_unrecognized, unknown)
+ }
+ proto.DiscardUnknown(m)
+
+ want := &pb2.MyMessage{Count: proto.Int32(11), Name: proto.String("aaa"), Pet: []string{"bbb", "ccc"}, Bigfloat: proto.Float64(88)}
+ if !proto.Equal(m, want) {
+ t.Errorf("message mismatch:\ngot %v\nwant %v", m, want)
+ }
+}
+
+func encodeDecode(t *testing.T, in, out proto.Message, msg string) {
+ buf, err := proto.Marshal(in)
+ if err != nil {
+ t.Fatalf("failed marshaling %v: %v", msg, err)
+ }
+ if err := proto.Unmarshal(buf, out); err != nil {
+ t.Fatalf("failed unmarshaling %v: %v", msg, err)
+ }
+}
+
+func TestPackedNonPackedDecoderSwitching(t *testing.T) {
+ np, p := new(pb2.NonPackedTest), new(pb2.PackedTest)
+
+ // non-packed -> packed
+ np.A = []int32{0, 1, 1, 2, 3, 5}
+ encodeDecode(t, np, p, "non-packed -> packed")
+ if !reflect.DeepEqual(np.A, p.B) {
+ t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
+ }
+
+ // packed -> non-packed
+ np.Reset()
+ p.B = []int32{3, 1, 4, 1, 5, 9}
+ encodeDecode(t, p, np, "packed -> non-packed")
+ if !reflect.DeepEqual(p.B, np.A) {
+ t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
+ }
+}
+
+func TestProto1RepeatedGroup(t *testing.T) {
+ pb := &pb2.MessageList{
+ Message: []*pb2.MessageList_Message{
+ {
+ Name: proto.String("blah"),
+ Count: proto.Int32(7),
+ },
+ // NOTE: pb.Message[1] is a nil
+ nil,
+ },
+ }
+
+ o := new(proto.Buffer)
+ err := o.Marshal(pb)
+ if err == nil {
+ t.Fatalf("expected error when marshaling repeted nil MessageList.Message")
+ }
+ if _, ok := err.(*proto.RequiredNotSetError); !ok {
+ t.Fatalf("unexpected error when marshaling: %v", err)
+ }
+}
+
+// Test that enums work. Checks for a bug introduced by making enums
+// named types instead of int32: newInt32FromUint64 would crash with
+// a type mismatch in reflect.PointTo.
+func TestEnum(t *testing.T) {
+ pb := new(pb2.GoEnum)
+ pb.Foo = pb2.FOO_FOO1.Enum()
+ o := new(proto.Buffer)
+ if err := o.Marshal(pb); err != nil {
+ t.Fatal("error encoding enum:", err)
+ }
+ pb1 := new(pb2.GoEnum)
+ if err := o.Unmarshal(pb1); err != nil {
+ t.Fatal("error decoding enum:", err)
+ }
+ if *pb1.Foo != pb2.FOO_FOO1 {
+ t.Error("expected 7 but got ", *pb1.Foo)
+ }
+}
+
+// Enum types have String methods. Check that enum fields can be printed.
+// We don't care what the value actually is, just as long as it doesn't crash.
+func TestPrintingNilEnumFields(t *testing.T) {
+ pb := new(pb2.GoEnum)
+ _ = fmt.Sprintf("%+v", pb)
+}
+
+// Verify that absent required fields cause Marshal/Unmarshal to return errors.
+func TestRequiredFieldEnforcement(t *testing.T) {
+ pb := new(pb2.GoTestField)
+ _, err := proto.Marshal(pb)
+ if err == nil {
+ t.Error("marshal: expected error, got nil")
+ } else if !isRequiredNotSetError(err) {
+ t.Errorf("marshal: bad error type: %v", err)
+ }
+
+ // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
+ // so simply counting the required fields is insufficient.
+ // field 1, encoding 2, value "hi"
+ buf := []byte("\x0A\x02hi\x0A\x02hi")
+ err = proto.Unmarshal(buf, pb)
+ if err == nil {
+ t.Error("unmarshal: expected error, got nil")
+ } else if !isRequiredNotSetError(err) {
+ t.Errorf("unmarshal: bad error type: %v", err)
+ }
+}
+
+// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors.
+func TestRequiredFieldEnforcementGroups(t *testing.T) {
+ pb := &pb2.GoTestRequiredGroupField{Group: &pb2.GoTestRequiredGroupField_Group{}}
+ if _, err := proto.Marshal(pb); err == nil {
+ t.Error("marshal: expected error, got nil")
+ } else if !isRequiredNotSetError(err) {
+ t.Errorf("marshal: bad error type: %v", err)
+ }
+
+ buf := []byte{11, 12}
+ if err := proto.Unmarshal(buf, pb); err == nil {
+ t.Error("unmarshal: expected error, got nil")
+ } else if !isRequiredNotSetError(err) {
+ t.Errorf("unmarshal: bad error type: %v", err)
+ }
+}
+
+func TestTypedNilMarshal(t *testing.T) {
+ // A typed nil should return ErrNil and not crash.
+ var m *pb2.GoEnum
+ if _, err := proto.Marshal(m); err != proto.ErrNil {
+ t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err)
+ }
+}
+
+func TestTypedNilMarshalInOneof(t *testing.T) {
+ // It should not panic.
+ m := &pb2.Communique{Union: &pb2.Communique_Msg{nil}}
+ if _, err := proto.Marshal(m); err == proto.ErrNil {
+ t.Errorf("Marshal(%#v): got %v, want nil or errOneofHasNil", m, err)
+ }
+}
+
+// A type that implements the Marshaler interface, but is not nillable.
+type nonNillableInt uint64
+
+func (nni nonNillableInt) Marshal() ([]byte, error) {
+ return proto.EncodeVarint(uint64(nni)), nil
+}
+
+type NNIMessage struct {
+ nni nonNillableInt
+}
+
+func (*NNIMessage) Reset() {}
+func (*NNIMessage) String() string { return "" }
+func (*NNIMessage) ProtoMessage() {}
+
+type NMMessage struct{}
+
+func (*NMMessage) Reset() {}
+func (*NMMessage) String() string { return "" }
+func (*NMMessage) ProtoMessage() {}
+
+// Verify a type that uses the Marshaler interface, but has a nil pointer.
+func TestNilMarshaler(t *testing.T) {
+ // Try a struct with a Marshaler field that is nil.
+ // It should be directly marshable.
+ nmm := new(NMMessage)
+ if _, err := proto.Marshal(nmm); err != nil {
+ t.Error("unexpected error marshaling nmm: ", err)
+ }
+
+ // Try a struct with a Marshaler field that is not nillable.
+ nnim := new(NNIMessage)
+ nnim.nni = 7
+ var _ proto.Marshaler = nnim.nni // verify it is truly a Marshaler
+ if _, err := proto.Marshal(nnim); err != nil {
+ t.Error("unexpected error marshaling nnim: ", err)
+ }
+}
+
+func TestAllSetDefaults(t *testing.T) {
+ // Exercise SetDefaults with all scalar field types.
+ got := &pb2.Defaults{
+ // NaN != NaN, so override that here.
+ F_Nan: proto.Float32(1.7),
+ }
+ want := &pb2.Defaults{
+ F_Bool: proto.Bool(true),
+ F_Int32: proto.Int32(32),
+ F_Int64: proto.Int64(64),
+ F_Fixed32: proto.Uint32(320),
+ F_Fixed64: proto.Uint64(640),
+ F_Uint32: proto.Uint32(3200),
+ F_Uint64: proto.Uint64(6400),
+ F_Float: proto.Float32(314159),
+ F_Double: proto.Float64(271828),
+ F_String: proto.String(`hello, "world!"` + "\n"),
+ F_Bytes: []byte("Bignose"),
+ F_Sint32: proto.Int32(-32),
+ F_Sint64: proto.Int64(-64),
+ F_Enum: pb2.Defaults_GREEN.Enum(),
+ F_Pinf: proto.Float32(float32(math.Inf(1))),
+ F_Ninf: proto.Float32(float32(math.Inf(-1))),
+ F_Nan: proto.Float32(1.7),
+ StrZero: proto.String(""),
+ }
+ proto.SetDefaults(got)
+ if !proto.Equal(got, want) {
+ t.Errorf("SetDefaults failed\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestSetDefaultsWithSetField(t *testing.T) {
+ // Check that a set value is not overridden.
+ m := &pb2.Defaults{
+ F_Int32: proto.Int32(12),
+ }
+ proto.SetDefaults(m)
+ if v := m.GetF_Int32(); v != 12 {
+ t.Errorf("m.FInt32 = %v, want 12", v)
+ }
+}
+
+func TestSetDefaultsWithSubMessage(t *testing.T) {
+ got := &pb2.OtherMessage{
+ Key: proto.Int64(123),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("gopher"),
+ },
+ }
+ want := &pb2.OtherMessage{
+ Key: proto.Int64(123),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("gopher"),
+ Port: proto.Int32(4000),
+ },
+ }
+ proto.SetDefaults(got)
+ if !proto.Equal(got, want) {
+ t.Errorf("\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) {
+ got := &pb2.MyMessage{
+ RepInner: []*pb2.InnerMessage{{}},
+ }
+ want := &pb2.MyMessage{
+ RepInner: []*pb2.InnerMessage{{
+ Port: proto.Int32(4000),
+ }},
+ }
+ proto.SetDefaults(got)
+ if !proto.Equal(got, want) {
+ t.Errorf("\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestSetDefaultWithRepeatedNonMessage(t *testing.T) {
+ got := &pb2.MyMessage{
+ Pet: []string{"turtle", "wombat"},
+ }
+ want := proto.Clone(got)
+ proto.SetDefaults(got)
+ if !proto.Equal(got, want) {
+ t.Errorf("\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestMaximumTagNumber(t *testing.T) {
+ m := &pb2.MaxTag{
+ LastField: proto.String("natural goat essence"),
+ }
+ buf, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("proto.Marshal failed: %v", err)
+ }
+ m2 := new(pb2.MaxTag)
+ if err := proto.Unmarshal(buf, m2); err != nil {
+ t.Fatalf("proto.Unmarshal failed: %v", err)
+ }
+ if got, want := m2.GetLastField(), *m.LastField; got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
+
+func TestJSON(t *testing.T) {
+ m := &pb2.MyMessage{
+ Count: proto.Int32(4),
+ Pet: []string{"bunny", "kitty"},
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("cauchy"),
+ },
+ Bikeshed: pb2.MyMessage_GREEN.Enum(),
+ }
+ const want = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}`
+
+ b, err := json.Marshal(m)
+ if err != nil {
+ t.Fatalf("json.Marshal failed: %v", err)
+ }
+ s := string(b)
+ if s != want {
+ t.Errorf("got %s\nwant %s", s, want)
+ }
+
+ received := new(pb2.MyMessage)
+ if err := json.Unmarshal(b, received); err != nil {
+ t.Fatalf("json.Unmarshal failed: %v", err)
+ }
+ if !proto.Equal(received, m) {
+ t.Fatalf("got %s, want %s", received, m)
+ }
+
+ // Test unmarshaling of JSON with symbolic enum name.
+ const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}`
+ received.Reset()
+ if err := json.Unmarshal([]byte(old), received); err != nil {
+ t.Fatalf("json.Unmarshal failed: %v", err)
+ }
+ if !proto.Equal(received, m) {
+ t.Fatalf("got %s, want %s", received, m)
+ }
+}
+
+func TestBadWireType(t *testing.T) {
+ b := []byte{7<<3 | 6} // field 7, wire type 6
+ pb := new(pb2.OtherMessage)
+ if err := proto.Unmarshal(b, pb); err == nil {
+ t.Errorf("Unmarshal did not fail")
+ }
+}
+
+func TestBytesWithInvalidLength(t *testing.T) {
+ // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
+ b := protopack.Message{
+ protopack.Tag{2, protopack.BytesType}, protopack.Denormalized{+1, protopack.Uvarint(34359738367)},
+ }.Marshal()
+ proto.Unmarshal(b, new(pb2.MyMessage))
+}
+
+func TestLengthOverflow(t *testing.T) {
+ // Overflowing a length should not panic.
+ b := protopack.Message{
+ protopack.Tag{2, protopack.BytesType}, protopack.String("\x01"),
+ protopack.Tag{3, protopack.BytesType}, protopack.Uvarint(9223372036854775807),
+ protopack.Raw("\x01"),
+ }.Marshal()
+ proto.Unmarshal(b, new(pb2.MyMessage))
+}
+
+func TestVarintOverflow(t *testing.T) {
+ // Overflowing a 64-bit length should not be allowed.
+ b := protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Varint(1),
+ protopack.Tag{3, protopack.BytesType},
+ protopack.Raw("\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01"),
+ }.Marshal()
+ if err := proto.Unmarshal(b, new(pb2.MyMessage)); err == nil {
+ t.Fatalf("Overflowed uint64 length without error")
+ }
+}
+
+func TestBytesWithInvalidLengthInGroup(t *testing.T) {
+ // Overflowing a 64-bit length should not be allowed.
+ b := protopack.Message{
+ protopack.Tag{775, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{774, protopack.BytesType}, protopack.Uvarint(13654841034505509168),
+ protopack.Raw(""),
+ },
+ }.Marshal()
+ if err := proto.Unmarshal(b, new(pb2.MyMessage)); err == nil {
+ t.Fatalf("Overflowed uint64 length without error")
+ }
+}
+
+func TestUnmarshalFuzz(t *testing.T) {
+ const N = 1000
+ seed := time.Now().UnixNano()
+ t.Logf("RNG seed is %d", seed)
+ rng := rand.New(rand.NewSource(seed))
+ buf := make([]byte, 20)
+ for i := 0; i < N; i++ {
+ for j := range buf {
+ buf[j] = byte(rng.Intn(256))
+ }
+ fuzzUnmarshal(t, buf)
+ }
+}
+
+func TestMergeMessages(t *testing.T) {
+ pb := &pb2.MessageList{Message: []*pb2.MessageList_Message{{Name: proto.String("x"), Count: proto.Int32(1)}}}
+ data, err := proto.Marshal(pb)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+
+ pb1 := new(pb2.MessageList)
+ if err := proto.Unmarshal(data, pb1); err != nil {
+ t.Fatalf("first Unmarshal: %v", err)
+ }
+ if err := proto.Unmarshal(data, pb1); err != nil {
+ t.Fatalf("second Unmarshal: %v", err)
+ }
+ if len(pb1.Message) != 1 {
+ t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message))
+ }
+
+ pb2 := new(pb2.MessageList)
+ if err := proto.UnmarshalMerge(data, pb2); err != nil {
+ t.Fatalf("first UnmarshalMerge: %v", err)
+ }
+ if err := proto.UnmarshalMerge(data, pb2); err != nil {
+ t.Fatalf("second UnmarshalMerge: %v", err)
+ }
+ if len(pb2.Message) != 2 {
+ t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message))
+ }
+}
+
+func TestExtensionMarshalOrder(t *testing.T) {
+ m := &pb2.MyMessage{Count: proto.Int(123)}
+ if err := proto.SetExtension(m, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("alpha")}); err != nil {
+ t.Fatalf("SetExtension: %v", err)
+ }
+ if err := proto.SetExtension(m, pb2.E_Ext_Text, proto.String("aleph")); err != nil {
+ t.Fatalf("SetExtension: %v", err)
+ }
+ if err := proto.SetExtension(m, pb2.E_Ext_Number, proto.Int32(1)); err != nil {
+ t.Fatalf("SetExtension: %v", err)
+ }
+
+ // Serialize m several times, and check we get the same bytes each time.
+ var orig []byte
+ for i := 0; i < 100; i++ {
+ b, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ if i == 0 {
+ orig = b
+ continue
+ }
+ if !bytes.Equal(b, orig) {
+ t.Errorf("Bytes differ on attempt #%d", i)
+ }
+ }
+}
+
+func TestExtensionMapFieldMarshalDeterministic(t *testing.T) {
+ m := &pb2.MyMessage{Count: proto.Int(123)}
+ if err := proto.SetExtension(m, pb2.E_Ext_More, &pb2.Ext{MapField: map[int32]int32{1: 1, 2: 2, 3: 3, 4: 4}}); err != nil {
+ t.Fatalf("SetExtension: %v", err)
+ }
+ marshal := func(m proto.Message) []byte {
+ var b proto.Buffer
+ b.SetDeterministic(true)
+ if err := b.Marshal(m); err != nil {
+ t.Fatalf("Marshal failed: %v", err)
+ }
+ return b.Bytes()
+ }
+
+ want := marshal(m)
+ for i := 0; i < 100; i++ {
+ if got := marshal(m); !bytes.Equal(got, want) {
+ t.Errorf("Marshal produced inconsistent output with determinism enabled (pass %d).\n got %v\nwant %v", i, got, want)
+ }
+ }
+}
+
+func TestUnmarshalMergesMessages(t *testing.T) {
+ // If a nested message occurs twice in the input,
+ // the fields should be merged when decoding.
+ a := &pb2.OtherMessage{
+ Key: proto.Int64(123),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("polhode"),
+ Port: proto.Int32(1234),
+ },
+ }
+ aData, err := proto.Marshal(a)
+ if err != nil {
+ t.Fatalf("Marshal(a): %v", err)
+ }
+ b := &pb2.OtherMessage{
+ Weight: proto.Float32(1.2),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("herpolhode"),
+ Connected: proto.Bool(true),
+ },
+ }
+ bData, err := proto.Marshal(b)
+ if err != nil {
+ t.Fatalf("Marshal(b): %v", err)
+ }
+ want := &pb2.OtherMessage{
+ Key: proto.Int64(123),
+ Weight: proto.Float32(1.2),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("herpolhode"),
+ Port: proto.Int32(1234),
+ Connected: proto.Bool(true),
+ },
+ }
+ got := new(pb2.OtherMessage)
+ if err := proto.Unmarshal(append(aData, bData...), got); err != nil {
+ t.Fatalf("Unmarshal: %v", err)
+ }
+ if !proto.Equal(got, want) {
+ t.Errorf("\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestUnmarshalMergesGroups(t *testing.T) {
+ // If a nested group occurs twice in the input,
+ // the fields should be merged when decoding.
+ a := &pb2.GroupNew{
+ G: &pb2.GroupNew_G{
+ X: proto.Int32(7),
+ Y: proto.Int32(8),
+ },
+ }
+ aData, err := proto.Marshal(a)
+ if err != nil {
+ t.Fatalf("Marshal(a): %v", err)
+ }
+ b := &pb2.GroupNew{
+ G: &pb2.GroupNew_G{
+ X: proto.Int32(9),
+ },
+ }
+ bData, err := proto.Marshal(b)
+ if err != nil {
+ t.Fatalf("Marshal(b): %v", err)
+ }
+ want := &pb2.GroupNew{
+ G: &pb2.GroupNew_G{
+ X: proto.Int32(9),
+ Y: proto.Int32(8),
+ },
+ }
+ got := new(pb2.GroupNew)
+ if err := proto.Unmarshal(append(aData, bData...), got); err != nil {
+ t.Fatalf("Unmarshal: %v", err)
+ }
+ if !proto.Equal(got, want) {
+ t.Errorf("\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestEncodingSizes(t *testing.T) {
+ tests := []struct {
+ m proto.Message
+ n int
+ }{
+ {&pb2.Defaults{F_Int32: proto.Int32(math.MaxInt32)}, 6},
+ {&pb2.Defaults{F_Int32: proto.Int32(math.MinInt32)}, 11},
+ {&pb2.Defaults{F_Uint32: proto.Uint32(uint32(math.MaxInt32) + 1)}, 6},
+ {&pb2.Defaults{F_Uint32: proto.Uint32(math.MaxUint32)}, 6},
+ }
+ for _, test := range tests {
+ b, err := proto.Marshal(test.m)
+ if err != nil {
+ t.Errorf("Marshal(%v): %v", test.m, err)
+ continue
+ }
+ if len(b) != test.n {
+ t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n)
+ }
+ }
+}
+
+func TestRequiredNotSetError(t *testing.T) {
+ pb := initGoTest(false)
+ pb.RequiredField.Label = nil
+ pb.F_Int32Required = nil
+ pb.F_Int64Required = nil
+
+ want := protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(7),
+ protopack.Tag{4, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{2, protopack.BytesType}, protopack.String("type"),
+ }),
+ protopack.Tag{10, protopack.VarintType}, protopack.Bool(true),
+ protopack.Tag{13, protopack.Fixed32Type}, protopack.Uint32(32),
+ protopack.Tag{14, protopack.Fixed64Type}, protopack.Uint64(64),
+ protopack.Tag{15, protopack.VarintType}, protopack.Uvarint(3232),
+ protopack.Tag{16, protopack.VarintType}, protopack.Uvarint(6464),
+ protopack.Tag{17, protopack.Fixed32Type}, protopack.Float32(3232),
+ protopack.Tag{18, protopack.Fixed64Type}, protopack.Float64(6464),
+ protopack.Tag{19, protopack.BytesType}, protopack.String("string"),
+ protopack.Tag{70, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{71, protopack.BytesType}, protopack.String("required"),
+ },
+ protopack.Tag{70, protopack.EndGroupType},
+ protopack.Tag{101, protopack.BytesType}, protopack.Bytes("bytes"),
+ protopack.Tag{102, protopack.VarintType}, protopack.Svarint(-32),
+ protopack.Tag{103, protopack.VarintType}, protopack.Svarint(-64),
+ protopack.Tag{104, protopack.Fixed32Type}, protopack.Int32(-32),
+ protopack.Tag{105, protopack.Fixed64Type}, protopack.Int64(-64),
+ }.Marshal()
+
+ got, err := proto.Marshal(pb)
+ if !isRequiredNotSetError(err) {
+ t.Logf("marshal-1 err = %v, want *RequiredNotSetError", err)
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+
+ // Now test Unmarshal by recreating the original buffer.
+ pbd := new(pb2.GoTest)
+ err = proto.Unmarshal(got, pbd)
+ if !isRequiredNotSetError(err) {
+ t.Errorf("unmarshal err = %v, want *RequiredNotSetError", err)
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+ got, err = proto.Marshal(pbd)
+ if !isRequiredNotSetError(err) {
+ t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err)
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+}
+
+func TestRequiredNotSetErrorWithBadWireTypes(t *testing.T) {
+ // Required field expects a varint, and properly found a varint.
+ if err := proto.Unmarshal([]byte{0x08, 0x00}, new(pb2.GoEnum)); err != nil {
+ t.Errorf("Unmarshal = %v, want nil", err)
+ }
+ // Required field expects a varint, but found a fixed32 instead.
+ if err := proto.Unmarshal([]byte{0x0d, 0x00, 0x00, 0x00, 0x00}, new(pb2.GoEnum)); err == nil {
+ t.Errorf("Unmarshal = nil, want RequiredNotSetError")
+ }
+ // Required field expects a varint, and found both a varint and fixed32 (ignored).
+ m := new(pb2.GoEnum)
+ if err := proto.Unmarshal([]byte{0x08, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00}, m); err != nil {
+ t.Errorf("Unmarshal = %v, want nil", err)
+ }
+ if !bytes.Equal(m.XXX_unrecognized, []byte{0x0d, 0x00, 0x00, 0x00, 0x00}) {
+ t.Errorf("expected fixed32 to appear as unknown bytes: %x", m.XXX_unrecognized)
+ }
+}
+
+func fuzzUnmarshal(t *testing.T, data []byte) {
+ defer func() {
+ if e := recover(); e != nil {
+ t.Errorf("These bytes caused a panic: %+v", data)
+ t.Logf("Stack:\n%s", debug.Stack())
+ t.FailNow()
+ }
+ }()
+
+ pb := new(pb2.MyMessage)
+ proto.Unmarshal(data, pb)
+}
+
+func TestMapFieldMarshal(t *testing.T) {
+ m := &pb2.MessageWithMap{
+ NameMapping: map[int32]string{
+ 1: "Rob",
+ 4: "Ian",
+ 8: "Dave",
+ },
+ }
+ b, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+
+ // b should be the concatenation of these three byte sequences in some order.
+ parts := []string{
+ "\n\a\b\x01\x12\x03Rob",
+ "\n\a\b\x04\x12\x03Ian",
+ "\n\b\b\x08\x12\x04Dave",
+ }
+ ok := false
+ for i := range parts {
+ for j := range parts {
+ if j == i {
+ continue
+ }
+ for k := range parts {
+ if k == i || k == j {
+ continue
+ }
+ try := parts[i] + parts[j] + parts[k]
+ if bytes.Equal(b, []byte(try)) {
+ ok = true
+ break
+ }
+ }
+ }
+ }
+ if !ok {
+ t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2])
+ }
+ t.Logf("FYI b: %q", b)
+}
+
+func TestMapFieldDeterministicMarshal(t *testing.T) {
+ m := &pb2.MessageWithMap{
+ NameMapping: map[int32]string{
+ 1: "Rob",
+ 4: "Ian",
+ 8: "Dave",
+ },
+ }
+
+ marshal := func(m proto.Message) []byte {
+ var b proto.Buffer
+ b.SetDeterministic(true)
+ if err := b.Marshal(m); err != nil {
+ t.Fatalf("Marshal failed: %v", err)
+ }
+ return b.Bytes()
+ }
+
+ want := marshal(m)
+ for i := 0; i < 10; i++ {
+ if got := marshal(m); !bytes.Equal(got, want) {
+ t.Errorf("Marshal produced inconsistent output with determinism enabled (pass %d).\n got %v\nwant %v", i, got, want)
+ }
+ }
+}
+
+func TestMapFieldRoundTrips(t *testing.T) {
+ m := &pb2.MessageWithMap{
+ NameMapping: map[int32]string{
+ 1: "Rob",
+ 4: "Ian",
+ 8: "Dave",
+ },
+ MsgMapping: map[int64]*pb2.FloatingPoint{
+ 0x7001: {F: proto.Float64(2.0)},
+ },
+ ByteMapping: map[bool][]byte{
+ false: []byte("that's not right!"),
+ true: []byte("aye, 'tis true!"),
+ },
+ }
+ b, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ t.Logf("FYI b: %q", b)
+ m2 := new(pb2.MessageWithMap)
+ if err := proto.Unmarshal(b, m2); err != nil {
+ t.Fatalf("Unmarshal: %v", err)
+ }
+ if !proto.Equal(m, m2) {
+ t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", m, m2)
+ }
+}
+
+func TestMapFieldWithNil(t *testing.T) {
+ m1 := &pb2.MessageWithMap{
+ MsgMapping: map[int64]*pb2.FloatingPoint{
+ 1: nil,
+ },
+ }
+ b, err := proto.Marshal(m1)
+ if _, ok := err.(*proto.RequiredNotSetError); !ok {
+ t.Fatalf("Marshal(%v): err=%v, want RequiredNotSet", m1, err)
+ }
+ m2 := new(pb2.MessageWithMap)
+ err = proto.Unmarshal(b, m2)
+ if _, ok := err.(*proto.RequiredNotSetError); !ok {
+ t.Fatalf("Unmarshal(%v): err=%v, want RequiredNotSet", m1, err)
+ }
+ if !proto.Equal(m1, m2) {
+ t.Fatalf("roundtrip marshal/unmarshal changed message; got:\n%v\nwant:\n%v", m2, m1)
+ }
+}
+
+func TestMapFieldWithNilBytes(t *testing.T) {
+ m1 := &pb2.MessageWithMap{
+ ByteMapping: map[bool][]byte{
+ false: {},
+ true: nil,
+ },
+ }
+ n := proto.Size(m1)
+ b, err := proto.Marshal(m1)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ if n != len(b) {
+ t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b))
+ }
+ m2 := new(pb2.MessageWithMap)
+ if err := proto.Unmarshal(b, m2); err != nil {
+ t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
+ }
+ if v, ok := m2.ByteMapping[false]; !ok {
+ t.Error("byte_mapping[false] not present")
+ } else if len(v) != 0 {
+ t.Errorf("byte_mapping[false] not empty: %#v", v)
+ }
+ if v, ok := m2.ByteMapping[true]; !ok {
+ t.Error("byte_mapping[true] not present")
+ } else if len(v) != 0 {
+ t.Errorf("byte_mapping[true] not empty: %#v", v)
+ }
+}
+
+func TestDecodeMapFieldMissingKey(t *testing.T) {
+ b := []byte{
+ 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes
+ // no key
+ 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m"
+ }
+ got := &pb2.MessageWithMap{}
+ err := proto.Unmarshal(b, got)
+ if err != nil {
+ t.Fatalf("failed to marshal map with missing key: %v", err)
+ }
+ want := &pb2.MessageWithMap{NameMapping: map[int32]string{0: "m"}}
+ if !proto.Equal(got, want) {
+ t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want)
+ }
+}
+
+func TestDecodeMapFieldMissingValue(t *testing.T) {
+ b := protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.VarintType}, protopack.Uvarint(1),
+ }),
+ }.Marshal()
+ got := &pb2.MessageWithMap{}
+ err := proto.Unmarshal(b, got)
+ if err != nil {
+ t.Fatalf("failed to marshal map with missing value: %v", err)
+ }
+ want := &pb2.MessageWithMap{NameMapping: map[int32]string{1: ""}}
+ if !proto.Equal(got, want) {
+ t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want)
+ }
+}
+
+func TestOneof(t *testing.T) {
+ m := &pb2.Communique{}
+ b, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal of empty message with oneof: %v", err)
+ }
+ if len(b) != 0 {
+ t.Errorf("Marshal of empty message yielded too many bytes: %v", b)
+ }
+
+ m = &pb2.Communique{
+ Union: &pb2.Communique_Name{"Barry"},
+ }
+
+ // Round-trip.
+ b, err = proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal of message with oneof: %v", err)
+ }
+ if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5)
+ t.Errorf("Incorrect marshal of message with oneof: %v", b)
+ }
+ m.Reset()
+ if err := proto.Unmarshal(b, m); err != nil {
+ t.Fatalf("Unmarshal of message with oneof: %v", err)
+ }
+ if x, ok := m.Union.(*pb2.Communique_Name); !ok || x.Name != "Barry" {
+ t.Errorf("After round trip, Union = %+v", m.Union)
+ }
+ if name := m.GetName(); name != "Barry" {
+ t.Errorf("After round trip, GetName = %q, want %q", name, "Barry")
+ }
+
+ // Let's try with a message in the oneof.
+ m.Union = &pb2.Communique_Msg{&pb2.Strings{StringField: proto.String("deep deep string")}}
+ b, err = proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal of message with oneof set to message: %v", err)
+ }
+ if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16)
+ t.Errorf("Incorrect marshal of message with oneof set to message: %v", b)
+ }
+ m.Reset()
+ if err := proto.Unmarshal(b, m); err != nil {
+ t.Fatalf("Unmarshal of message with oneof set to message: %v", err)
+ }
+ ss, ok := m.Union.(*pb2.Communique_Msg)
+ if !ok || ss.Msg.GetStringField() != "deep deep string" {
+ t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union)
+ }
+}
+
+func TestOneofNilBytes(t *testing.T) {
+ // A oneof with nil byte slice should marshal to tag + 0 (size), with no error.
+ m := &pb2.Communique{Union: &pb2.Communique_Data{Data: nil}}
+ b, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal failed: %v", err)
+ }
+ want := protopack.Message{
+ protopack.Tag{7, protopack.BytesType}, protopack.Bytes(""),
+ }.Marshal()
+ if !bytes.Equal(b, want) {
+ t.Errorf("Wrong result of Marshal: got %x, want %x", b, want)
+ }
+}
+
+func TestInefficientPackedBool(t *testing.T) {
+ // https://github.com/golang/protobuf/issues/76
+ inp := protopack.Message{
+ protopack.Tag{2, protopack.BytesType}, protopack.Bytes("\xb90"),
+ }.Marshal()
+ if err := proto.Unmarshal(inp, new(pb2.MoreRepeated)); err != nil {
+ t.Error(err)
+ }
+}
+
+// Make sure pure-reflect-based implementation handles
+// []int32-[]enum conversion correctly.
+func TestRepeatedEnum2(t *testing.T) {
+ pb := &pb2.RepeatedEnum{
+ Color: []pb2.RepeatedEnum_Color{pb2.RepeatedEnum_RED},
+ }
+ b, err := proto.Marshal(pb)
+ if err != nil {
+ t.Fatalf("Marshal failed: %v", err)
+ }
+ x := new(pb2.RepeatedEnum)
+ err = proto.Unmarshal(b, x)
+ if err != nil {
+ t.Fatalf("Unmarshal failed: %v", err)
+ }
+ if !proto.Equal(pb, x) {
+ t.Errorf("Incorrect result: want: %v got: %v", pb, x)
+ }
+}
+
+// TestConcurrentMarshal makes sure that it is safe to marshal
+// same message in multiple goroutines concurrently.
+func TestConcurrentMarshal(t *testing.T) {
+ pb := initGoTest(true)
+ const N = 100
+ b := make([][]byte, N)
+
+ var wg sync.WaitGroup
+ for i := 0; i < N; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ var err error
+ b[i], err = proto.Marshal(pb)
+ if err != nil {
+ t.Errorf("marshal error: %v", err)
+ }
+ }(i)
+ }
+
+ wg.Wait()
+ for i := 1; i < N; i++ {
+ if !bytes.Equal(b[0], b[i]) {
+ t.Errorf("concurrent marshal result not same: b[0] = %v, b[%d] = %v", b[0], i, b[i])
+ }
+ }
+}
+
+func TestInvalidUTF8(t *testing.T) {
+ const invalidUTF8 = "\xde\xad\xbe\xef\x80\x00\xff"
+ tests := []struct {
+ label string
+ proto2 proto.Message
+ proto3 proto.Message
+ want []byte
+ }{{
+ label: "Scalar",
+ proto2: &pb2.TestUTF8{Scalar: proto.String(invalidUTF8)},
+ proto3: &pb3.TestUTF8{Scalar: invalidUTF8},
+ want: []byte{0x0a, 0x07, 0xde, 0xad, 0xbe, 0xef, 0x80, 0x00, 0xff},
+ }, {
+ label: "Vector",
+ proto2: &pb2.TestUTF8{Vector: []string{invalidUTF8}},
+ proto3: &pb3.TestUTF8{Vector: []string{invalidUTF8}},
+ want: []byte{0x12, 0x07, 0xde, 0xad, 0xbe, 0xef, 0x80, 0x00, 0xff},
+ }, {
+ label: "Oneof",
+ proto2: &pb2.TestUTF8{Oneof: &pb2.TestUTF8_Field{invalidUTF8}},
+ proto3: &pb3.TestUTF8{Oneof: &pb3.TestUTF8_Field{invalidUTF8}},
+ want: []byte{0x1a, 0x07, 0xde, 0xad, 0xbe, 0xef, 0x80, 0x00, 0xff},
+ }, {
+ label: "MapKey",
+ proto2: &pb2.TestUTF8{MapKey: map[string]int64{invalidUTF8: 0}},
+ proto3: &pb3.TestUTF8{MapKey: map[string]int64{invalidUTF8: 0}},
+ want: []byte{0x22, 0x0b, 0x0a, 0x07, 0xde, 0xad, 0xbe, 0xef, 0x80, 0x00, 0xff, 0x10, 0x00},
+ }, {
+ label: "MapValue",
+ proto2: &pb2.TestUTF8{MapValue: map[int64]string{0: invalidUTF8}},
+ proto3: &pb3.TestUTF8{MapValue: map[int64]string{0: invalidUTF8}},
+ want: []byte{0x2a, 0x0b, 0x08, 0x00, 0x12, 0x07, 0xde, 0xad, 0xbe, 0xef, 0x80, 0x00, 0xff},
+ }}
+
+ for _, tt := range tests {
+ // Proto2 should not validate UTF-8.
+ b, err := proto.Marshal(tt.proto2)
+ if err != nil {
+ t.Errorf("Marshal(proto2.%s) = %v, want nil", tt.label, err)
+ }
+ if !bytes.Equal(b, tt.want) {
+ t.Errorf("Marshal(proto2.%s) = %x, want %x", tt.label, b, tt.want)
+ }
+
+ m := proto.Clone(tt.proto2)
+ m.Reset()
+ if err = proto.Unmarshal(tt.want, m); err != nil {
+ t.Errorf("Unmarshal(proto2.%s) = %v, want nil", tt.label, err)
+ }
+ if !proto.Equal(m, tt.proto2) {
+ t.Errorf("proto2.%s: output mismatch:\ngot %v\nwant %v", tt.label, m, tt.proto2)
+ }
+
+ // Proto3 should validate UTF-8.
+ if _, err := proto.Marshal(tt.proto3); err == nil {
+ t.Errorf("Marshal(proto3.%s) = %v, want non-nil", tt.label, err)
+ }
+
+ m = proto.Clone(tt.proto3)
+ m.Reset()
+ if err := proto.Unmarshal(tt.want, m); err == nil {
+ t.Errorf("Unmarshal(proto3.%s) = %v, want non-nil", tt.label, err)
+ }
+ }
+}
+
+func TestRequired(t *testing.T) {
+ // The F_BoolRequired field appears after all of the required fields.
+ // It should still be handled even after multiple required field violations.
+ m := &pb2.GoTest{F_BoolRequired: proto.Bool(true)}
+ got, err := proto.Marshal(m)
+ if !isRequiredNotSetError(err) {
+ t.Errorf("Marshal() = %v, want RequiredNotSetError error", err)
+ }
+ if want := []byte{0x50, 0x01}; !bytes.Equal(got, want) {
+ t.Errorf("Marshal() = %x, want %x", got, want)
+ }
+
+ m = new(pb2.GoTest)
+ err = proto.Unmarshal(got, m)
+ if !isRequiredNotSetError(err) {
+ t.Errorf("Marshal() = %v, want RequiredNotSetError error", err)
+ }
+ if !m.GetF_BoolRequired() {
+ t.Error("m.F_BoolRequired = false, want true")
+ }
+}
+
+func TestUnknownV2(t *testing.T) {
+ m := new(tspb.Timestamp)
+ m.ProtoReflect().SetUnknown([]byte("\x92\x4d\x12unknown field 1234"))
+ got := proto.CompactTextString(m)
+ if !strings.Contains(got, "unknown field 1234") {
+ t.Errorf("got %q, want contains %q", got, "unknown field 1234")
+ }
+}
+
+func testMsg() *pb2.GoTest {
+ pb := initGoTest(true)
+ const N = 1000 // Internally the library starts much smaller.
+ pb.F_Int32Repeated = make([]int32, N)
+ pb.F_DoubleRepeated = make([]float64, N)
+ for i := 0; i < N; i++ {
+ pb.F_Int32Repeated[i] = int32(i)
+ pb.F_DoubleRepeated[i] = float64(i)
+ }
+ return pb
+}
+
+func bytesMsg() *pb2.GoTest {
+ pb := initGoTest(true)
+ buf := make([]byte, 4000)
+ for i := range buf {
+ buf[i] = byte(i)
+ }
+ pb.F_BytesDefaulted = buf
+ return pb
+}
+
+func benchmarkMarshal(b *testing.B, pb proto.Message, marshal func(proto.Message) ([]byte, error)) {
+ d, _ := marshal(pb)
+ b.SetBytes(int64(len(d)))
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ marshal(pb)
+ }
+}
+
+func benchmarkBufferMarshal(b *testing.B, pb proto.Message) {
+ p := proto.NewBuffer(nil)
+ benchmarkMarshal(b, pb, func(pb0 proto.Message) ([]byte, error) {
+ p.Reset()
+ err := p.Marshal(pb0)
+ return p.Bytes(), err
+ })
+}
+
+func benchmarkSize(b *testing.B, pb proto.Message) {
+ benchmarkMarshal(b, pb, func(pb0 proto.Message) ([]byte, error) {
+ proto.Size(pb)
+ return nil, nil
+ })
+}
+
+func TestProto3ZeroValues(t *testing.T) {
+ tests := []struct {
+ desc string
+ m proto.Message
+ }{
+ {"zero message", &pb3.Message{}},
+ {"empty bytes field", &pb3.Message{Data: []byte{}}},
+ }
+ for _, test := range tests {
+ b, err := proto.Marshal(test.m)
+ if err != nil {
+ t.Errorf("%s: proto.Marshal: %v", test.desc, err)
+ continue
+ }
+ if len(b) > 0 {
+ t.Errorf("%s: Encoding is non-empty: %q", test.desc, b)
+ }
+ }
+}
+
+func TestRoundTripProto3(t *testing.T) {
+ m := &pb3.Message{
+ Name: "David", // (2 | 1<<3): 0x0a 0x05 "David"
+ Hilarity: pb3.Message_PUNS, // (0 | 2<<3): 0x10 0x01
+ HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01
+ Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto"
+ ResultCount: 47, // (0 | 7<<3): 0x38 0x2f
+ TrueScotsman: true, // (0 | 8<<3): 0x40 0x01
+ Score: 8.1, // (5 | 9<<3): 0x4d <8.1>
+
+ Key: []uint64{1, 0xdeadbeef},
+ Nested: &pb3.Nested{
+ Bunny: "Monty",
+ },
+ }
+ t.Logf(" m: %v", m)
+
+ b, err := proto.Marshal(m)
+ if err != nil {
+ t.Fatalf("proto.Marshal: %v", err)
+ }
+ t.Logf(" b: %q", b)
+
+ m2 := new(pb3.Message)
+ if err := proto.Unmarshal(b, m2); err != nil {
+ t.Fatalf("proto.Unmarshal: %v", err)
+ }
+ t.Logf("m2: %v", m2)
+
+ if !proto.Equal(m, m2) {
+ t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2)
+ }
+}
+
+func TestGettersForBasicTypesExist(t *testing.T) {
+ var m pb3.Message
+ if got := m.GetNested().GetBunny(); got != "" {
+ t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got)
+ }
+ if got := m.GetNested().GetCute(); got {
+ t.Errorf("m.GetNested().GetCute() = %t, want false", got)
+ }
+}
+
+func TestProto3SetDefaults(t *testing.T) {
+ in := &pb3.Message{
+ Terrain: map[string]*pb3.Nested{
+ "meadow": new(pb3.Nested),
+ },
+ Proto2Field: new(pb2.SubDefaults),
+ Proto2Value: map[string]*pb2.SubDefaults{
+ "badlands": new(pb2.SubDefaults),
+ },
+ }
+
+ got := proto.Clone(in).(*pb3.Message)
+ proto.SetDefaults(got)
+
+ // There are no defaults in proto3. Everything should be the zero value, but
+ // we need to remember to set defaults for nested proto2 messages.
+ want := &pb3.Message{
+ Terrain: map[string]*pb3.Nested{
+ "meadow": new(pb3.Nested),
+ },
+ Proto2Field: &pb2.SubDefaults{N: proto.Int64(7)},
+ Proto2Value: map[string]*pb2.SubDefaults{
+ "badlands": &pb2.SubDefaults{N: proto.Int64(7)},
+ },
+ }
+
+ if !proto.Equal(got, want) {
+ t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want)
+ }
+}
+
+func TestUnknownFieldPreservation(t *testing.T) {
+ b1 := "\x0a\x05David" // Known tag 1
+ b2 := "\xc2\x0c\x06Google" // Unknown tag 200
+ b := []byte(b1 + b2)
+
+ m := new(pb3.Message)
+ if err := proto.Unmarshal(b, m); err != nil {
+ t.Fatalf("proto.Unmarshal: %v", err)
+ }
+
+ if !bytes.Equal(m.XXX_unrecognized, []byte(b2)) {
+ t.Fatalf("mismatching unknown fields:\ngot %q\nwant %q", m.XXX_unrecognized, b2)
+ }
+}
+
+func TestMap(t *testing.T) {
+ b := protopack.Message{
+ protopack.Tag{20, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("Key1"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("Val1"),
+ }),
+ protopack.Tag{20, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("Key2"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("Val2a"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("Val2"),
+ }),
+ protopack.Tag{20, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("Key3"),
+ protopack.Tag{1, protopack.Fixed32Type}, protopack.Uint32(5),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("Val3b"),
+ protopack.Tag{3, protopack.BytesType}, protopack.Bytes("Val3a"),
+ protopack.Tag{2, protopack.BytesType}, protopack.String("Val3"),
+ protopack.Tag{2, protopack.Fixed32Type}, protopack.Uint32(5),
+ }),
+ protopack.Tag{20, protopack.BytesType}, protopack.LengthPrefix{},
+ protopack.Tag{20, protopack.BytesType}, protopack.LengthPrefix(protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.String("Key4"),
+ protopack.Tag{2, protopack.StartGroupType},
+ protopack.Message{
+ protopack.Tag{1, protopack.BytesType}, protopack.Bytes("SomeURL"),
+ protopack.Tag{2, protopack.BytesType}, protopack.Bytes("SomeTitle"),
+ protopack.Tag{3, protopack.BytesType}, protopack.Bytes("Snippet1"),
+ },
+ protopack.Tag{2, protopack.EndGroupType},
+ }),
+ }.Marshal()
+
+ var m pb3.Message
+ if err := proto.Unmarshal(b, &m); err != nil {
+ t.Fatalf("proto.Unmarshal error: %v", err)
+ }
+
+ got := m.StringMap
+ want := map[string]string{
+ "": "",
+ "Key1": "Val1",
+ "Key2": "Val2",
+ "Key3": "Val3",
+ "Key4": "",
+ }
+
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("maps differ:\ngot %#v\nwant %#v", got, want)
+ }
+}
+
+func marshalled() []byte {
+ m := &pb3.IntMaps{}
+ for i := 0; i < 1000; i++ {
+ m.Maps = append(m.Maps, &pb3.IntMap{
+ Rtt: map[int32]int32{1: 2},
+ })
+ }
+ b, err := proto.Marshal(m)
+ if err != nil {
+ panic(fmt.Sprintf("Can't marshal %+v: %v", m, err))
+ }
+ return b
+}
+
+var messageWithExtension1 = &pb2.MyMessage{Count: proto.Int32(7)}
+
+// messageWithExtension2 is in equal_test.go.
+var messageWithExtension3 = &pb2.MyMessage{Count: proto.Int32(8)}
+
+func init() {
+ if err := proto.SetExtension(messageWithExtension1, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("Abbott")}); err != nil {
+ log.Panicf("proto.SetExtension: %v", err)
+ }
+ if err := proto.SetExtension(messageWithExtension3, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("Costello")}); err != nil {
+ log.Panicf("proto.SetExtension: %v", err)
+ }
+
+ // Force messageWithExtension3 to have the extension encoded.
+ proto.Marshal(messageWithExtension3)
+
+}
+
+// non-pointer custom message
+type nonptrMessage struct{}
+
+func (m nonptrMessage) ProtoMessage() {}
+func (m nonptrMessage) Reset() {}
+func (m nonptrMessage) String() string { return "" }
+
+func (m nonptrMessage) Marshal() ([]byte, error) {
+ return []byte{42}, nil
+}
+
+var SizeTests = []struct {
+ desc string
+ pb proto.Message
+}{
+ {"empty", &pb2.OtherMessage{}},
+ // Basic types.
+ {"bool", &pb2.Defaults{F_Bool: proto.Bool(true)}},
+ {"int32", &pb2.Defaults{F_Int32: proto.Int32(12)}},
+ {"negative int32", &pb2.Defaults{F_Int32: proto.Int32(-1)}},
+ {"small int64", &pb2.Defaults{F_Int64: proto.Int64(1)}},
+ {"big int64", &pb2.Defaults{F_Int64: proto.Int64(1 << 20)}},
+ {"negative int64", &pb2.Defaults{F_Int64: proto.Int64(-1)}},
+ {"fixed32", &pb2.Defaults{F_Fixed32: proto.Uint32(71)}},
+ {"fixed64", &pb2.Defaults{F_Fixed64: proto.Uint64(72)}},
+ {"uint32", &pb2.Defaults{F_Uint32: proto.Uint32(123)}},
+ {"uint64", &pb2.Defaults{F_Uint64: proto.Uint64(124)}},
+ {"float", &pb2.Defaults{F_Float: proto.Float32(12.6)}},
+ {"double", &pb2.Defaults{F_Double: proto.Float64(13.9)}},
+ {"string", &pb2.Defaults{F_String: proto.String("niles")}},
+ {"bytes", &pb2.Defaults{F_Bytes: []byte("wowsa")}},
+ {"bytes, empty", &pb2.Defaults{F_Bytes: []byte{}}},
+ {"sint32", &pb2.Defaults{F_Sint32: proto.Int32(65)}},
+ {"sint64", &pb2.Defaults{F_Sint64: proto.Int64(67)}},
+ {"enum", &pb2.Defaults{F_Enum: pb2.Defaults_BLUE.Enum()}},
+ // Repeated.
+ {"empty repeated bool", &pb2.MoreRepeated{Bools: []bool{}}},
+ {"repeated bool", &pb2.MoreRepeated{Bools: []bool{false, true, true, false}}},
+ {"packed repeated bool", &pb2.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}},
+ {"repeated int32", &pb2.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}},
+ {"repeated int32 packed", &pb2.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}},
+ {"repeated int64 packed", &pb2.MoreRepeated{Int64SPacked: []int64{
+ // Need enough large numbers to verify that the header is counting the number of bytes
+ // for the field, not the number of elements.
+ 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62,
+ 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62,
+ }}},
+ {"repeated string", &pb2.MoreRepeated{Strings: []string{"r", "ken", "gri"}}},
+ {"repeated fixed", &pb2.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}},
+ // Nested.
+ {"nested", &pb2.OldMessage{Nested: &pb2.OldMessage_Nested{Name: proto.String("whatever")}}},
+ {"group", &pb2.GroupOld{G: &pb2.GroupOld_G{X: proto.Int32(12345)}}},
+ // Other things.
+ {"unrecognized", &pb2.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}},
+ {"extension (unencoded)", messageWithExtension1},
+ {"extension (encoded)", messageWithExtension3},
+ // proto3 message
+ {"proto3 empty", &pb3.Message{}},
+ {"proto3 bool", &pb3.Message{TrueScotsman: true}},
+ {"proto3 int64", &pb3.Message{ResultCount: 1}},
+ {"proto3 uint32", &pb3.Message{HeightInCm: 123}},
+ {"proto3 float", &pb3.Message{Score: 12.6}},
+ {"proto3 string", &pb3.Message{Name: "Snezana"}},
+ {"proto3 bytes", &pb3.Message{Data: []byte("wowsa")}},
+ {"proto3 bytes, empty", &pb3.Message{Data: []byte{}}},
+ {"proto3 enum", &pb3.Message{Hilarity: pb3.Message_PUNS}},
+ {"proto3 map field with empty bytes", &pb3.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}},
+
+ {"map field", &pb2.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}},
+ {"map field with message", &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{0x7001: &pb2.FloatingPoint{F: proto.Float64(2.0)}}}},
+ {"map field with bytes", &pb2.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}},
+ {"map field with empty bytes", &pb2.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}},
+
+ {"map field with big entry", &pb2.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}},
+ {"map field with big key and val", &pb2.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}},
+ {"map field with big numeric key", &pb2.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}},
+
+ {"oneof not set", &pb2.Oneof{}},
+ {"oneof bool", &pb2.Oneof{Union: &pb2.Oneof_F_Bool{true}}},
+ {"oneof zero int32", &pb2.Oneof{Union: &pb2.Oneof_F_Int32{0}}},
+ {"oneof big int32", &pb2.Oneof{Union: &pb2.Oneof_F_Int32{1 << 20}}},
+ {"oneof int64", &pb2.Oneof{Union: &pb2.Oneof_F_Int64{42}}},
+ {"oneof fixed32", &pb2.Oneof{Union: &pb2.Oneof_F_Fixed32{43}}},
+ {"oneof fixed64", &pb2.Oneof{Union: &pb2.Oneof_F_Fixed64{44}}},
+ {"oneof uint32", &pb2.Oneof{Union: &pb2.Oneof_F_Uint32{45}}},
+ {"oneof uint64", &pb2.Oneof{Union: &pb2.Oneof_F_Uint64{46}}},
+ {"oneof float", &pb2.Oneof{Union: &pb2.Oneof_F_Float{47.1}}},
+ {"oneof double", &pb2.Oneof{Union: &pb2.Oneof_F_Double{48.9}}},
+ {"oneof string", &pb2.Oneof{Union: &pb2.Oneof_F_String{"Rhythmic Fman"}}},
+ {"oneof bytes", &pb2.Oneof{Union: &pb2.Oneof_F_Bytes{[]byte("let go")}}},
+ {"oneof sint32", &pb2.Oneof{Union: &pb2.Oneof_F_Sint32{50}}},
+ {"oneof sint64", &pb2.Oneof{Union: &pb2.Oneof_F_Sint64{51}}},
+ {"oneof enum", &pb2.Oneof{Union: &pb2.Oneof_F_Enum{pb2.MyMessage_BLUE}}},
+ {"message for oneof", &pb2.GoTestField{Label: proto.String("k"), Type: proto.String("v")}},
+ {"oneof message", &pb2.Oneof{Union: &pb2.Oneof_F_Message{&pb2.GoTestField{Label: proto.String("k"), Type: proto.String("v")}}}},
+ {"oneof group", &pb2.Oneof{Union: &pb2.Oneof_FGroup{&pb2.Oneof_F_Group{X: proto.Int32(52)}}}},
+ {"oneof largest tag", &pb2.Oneof{Union: &pb2.Oneof_F_Largest_Tag{1}}},
+ {"multiple oneofs", &pb2.Oneof{Union: &pb2.Oneof_F_Int32{1}, Tormato: &pb2.Oneof_Value{2}}},
+
+ {"non-pointer message", nonptrMessage{}},
+}
+
+func TestSize(t *testing.T) {
+ for _, tc := range SizeTests {
+ t.Run(tc.desc, func(t *testing.T) {
+ size := proto.Size(tc.pb)
+ b, err := proto.Marshal(tc.pb)
+ if err != nil {
+ t.Errorf("%v: Marshal failed: %v", tc.desc, err)
+ return
+ }
+ if size != len(b) {
+ t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b))
+ t.Logf("%v: bytes: %#v", tc.desc, b)
+ }
+ })
+ }
+}
+
+func TestVarintSize(t *testing.T) {
+ // Check the edge cases carefully.
+ testCases := []struct {
+ n uint64
+ size int
+ }{
+ {0, 1},
+ {1, 1},
+ {127, 1},
+ {128, 2},
+ {16383, 2},
+ {16384, 3},
+ {math.MaxInt64, 9},
+ {math.MaxInt64 + 1, 10},
+ }
+ for _, tc := range testCases {
+ size := proto.SizeVarint(tc.n)
+ if size != tc.size {
+ t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size)
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/registry.go b/vendor/github.com/golang/protobuf/proto/registry.go
new file mode 100644
index 000000000..1e7ff6420
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/registry.go
@@ -0,0 +1,323 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io/ioutil"
+ "reflect"
+ "strings"
+ "sync"
+
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+ "google.golang.org/protobuf/runtime/protoimpl"
+)
+
+// filePath is the path to the proto source file.
+type filePath = string // e.g., "google/protobuf/descriptor.proto"
+
+// fileDescGZIP is the compressed contents of the encoded FileDescriptorProto.
+type fileDescGZIP = []byte
+
+var fileCache sync.Map // map[filePath]fileDescGZIP
+
+// RegisterFile is called from generated code to register the compressed
+// FileDescriptorProto with the file path for a proto source file.
+//
+// Deprecated: Use protoregistry.GlobalFiles.RegisterFile instead.
+func RegisterFile(s filePath, d fileDescGZIP) {
+ // Decompress the descriptor.
+ zr, err := gzip.NewReader(bytes.NewReader(d))
+ if err != nil {
+ panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err))
+ }
+ b, err := ioutil.ReadAll(zr)
+ if err != nil {
+ panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err))
+ }
+
+ // Construct a protoreflect.FileDescriptor from the raw descriptor.
+ // Note that DescBuilder.Build automatically registers the constructed
+ // file descriptor with the v2 registry.
+ protoimpl.DescBuilder{RawDescriptor: b}.Build()
+
+ // Locally cache the raw descriptor form for the file.
+ fileCache.Store(s, d)
+}
+
+// FileDescriptor returns the compressed FileDescriptorProto given the file path
+// for a proto source file. It returns nil if not found.
+//
+// Deprecated: Use protoregistry.GlobalFiles.FindFileByPath instead.
+func FileDescriptor(s filePath) fileDescGZIP {
+ if v, ok := fileCache.Load(s); ok {
+ return v.(fileDescGZIP)
+ }
+
+ // Find the descriptor in the v2 registry.
+ var b []byte
+ if fd, _ := protoregistry.GlobalFiles.FindFileByPath(s); fd != nil {
+ if fd, ok := fd.(interface{ ProtoLegacyRawDesc() []byte }); ok {
+ b = fd.ProtoLegacyRawDesc()
+ } else {
+ // TODO: Use protodesc.ToFileDescriptorProto to construct
+ // a descriptorpb.FileDescriptorProto and marshal it.
+ // However, doing so causes the proto package to have a dependency
+ // on descriptorpb, leading to cyclic dependency issues.
+ }
+ }
+
+ // Locally cache the raw descriptor form for the file.
+ if len(b) > 0 {
+ v, _ := fileCache.LoadOrStore(s, protoimpl.X.CompressGZIP(b))
+ return v.(fileDescGZIP)
+ }
+ return nil
+}
+
+// enumName is the name of an enum. For historical reasons, the enum name is
+// neither the full Go name nor the full protobuf name of the enum.
+// The name is the dot-separated combination of just the proto package that the
+// enum is declared within followed by the Go type name of the generated enum.
+type enumName = string // e.g., "my.proto.package.GoMessage_GoEnum"
+
+// enumsByName maps enum values by name to their numeric counterpart.
+type enumsByName = map[string]int32
+
+// enumsByNumber maps enum values by number to their name counterpart.
+type enumsByNumber = map[int32]string
+
+var enumCache sync.Map // map[enumName]enumsByName
+var numFilesCache sync.Map // map[protoreflect.FullName]int
+
+// RegisterEnum is called from the generated code to register the mapping of
+// enum value names to enum numbers for the enum identified by s.
+//
+// Deprecated: Use protoregistry.GlobalTypes.RegisterEnum instead.
+func RegisterEnum(s enumName, _ enumsByNumber, m enumsByName) {
+ if _, ok := enumCache.Load(s); ok {
+ panic("proto: duplicate enum registered: " + s)
+ }
+ enumCache.Store(s, m)
+
+ // This does not forward registration to the v2 registry since this API
+ // lacks sufficient information to construct a complete v2 enum descriptor.
+}
+
+// EnumValueMap returns the mapping from enum value names to enum numbers for
+// the enum of the given name. It returns nil if not found.
+//
+// Deprecated: Use protoregistry.GlobalTypes.FindEnumByName instead.
+func EnumValueMap(s enumName) enumsByName {
+ if v, ok := enumCache.Load(s); ok {
+ return v.(enumsByName)
+ }
+
+ // Check whether the cache is stale. If the number of files in the current
+ // package differs, then it means that some enums may have been recently
+ // registered upstream that we do not know about.
+ var protoPkg protoreflect.FullName
+ if i := strings.LastIndexByte(s, '.'); i >= 0 {
+ protoPkg = protoreflect.FullName(s[:i])
+ }
+ v, _ := numFilesCache.Load(protoPkg)
+ numFiles, _ := v.(int)
+ if protoregistry.GlobalFiles.NumFilesByPackage(protoPkg) == numFiles {
+ return nil // cache is up-to-date; was not found earlier
+ }
+
+ // Update the enum cache for all enums declared in the given proto package.
+ numFiles = 0
+ protoregistry.GlobalFiles.RangeFilesByPackage(protoPkg, func(fd protoreflect.FileDescriptor) bool {
+ walkEnums(fd, func(ed protoreflect.EnumDescriptor) {
+ name := protoimpl.X.LegacyEnumName(ed)
+ if _, ok := enumCache.Load(name); !ok {
+ m := make(enumsByName)
+ evs := ed.Values()
+ for i := evs.Len() - 1; i >= 0; i-- {
+ ev := evs.Get(i)
+ m[string(ev.Name())] = int32(ev.Number())
+ }
+ enumCache.LoadOrStore(name, m)
+ }
+ })
+ numFiles++
+ return true
+ })
+ numFilesCache.Store(protoPkg, numFiles)
+
+ // Check cache again for enum map.
+ if v, ok := enumCache.Load(s); ok {
+ return v.(enumsByName)
+ }
+ return nil
+}
+
+// walkEnums recursively walks all enums declared in d.
+func walkEnums(d interface {
+ Enums() protoreflect.EnumDescriptors
+ Messages() protoreflect.MessageDescriptors
+}, f func(protoreflect.EnumDescriptor)) {
+ eds := d.Enums()
+ for i := eds.Len() - 1; i >= 0; i-- {
+ f(eds.Get(i))
+ }
+ mds := d.Messages()
+ for i := mds.Len() - 1; i >= 0; i-- {
+ walkEnums(mds.Get(i), f)
+ }
+}
+
+// messageName is the full name of protobuf message.
+type messageName = string
+
+var messageTypeCache sync.Map // map[messageName]reflect.Type
+
+// RegisterType is called from generated code to register the message Go type
+// for a message of the given name.
+//
+// Deprecated: Use protoregistry.GlobalTypes.RegisterMessage instead.
+func RegisterType(m Message, s messageName) {
+ mt := protoimpl.X.LegacyMessageTypeOf(m, protoreflect.FullName(s))
+ if err := protoregistry.GlobalTypes.RegisterMessage(mt); err != nil {
+ panic(err)
+ }
+ messageTypeCache.Store(s, reflect.TypeOf(m))
+}
+
+// RegisterMapType is called from generated code to register the Go map type
+// for a protobuf message representing a map entry.
+//
+// Deprecated: Do not use.
+func RegisterMapType(m interface{}, s messageName) {
+ t := reflect.TypeOf(m)
+ if t.Kind() != reflect.Map {
+ panic(fmt.Sprintf("invalid map kind: %v", t))
+ }
+ if _, ok := messageTypeCache.Load(s); ok {
+ panic(fmt.Errorf("proto: duplicate proto message registered: %s", s))
+ }
+ messageTypeCache.Store(s, t)
+}
+
+// MessageType returns the message type for a named message.
+// It returns nil if not found.
+//
+// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead.
+func MessageType(s messageName) reflect.Type {
+ if v, ok := messageTypeCache.Load(s); ok {
+ return v.(reflect.Type)
+ }
+
+ // Derive the message type from the v2 registry.
+ var t reflect.Type
+ if mt, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(s)); mt != nil {
+ t = messageGoType(mt)
+ }
+
+ // If we could not get a concrete type, it is possible that it is a
+ // pseudo-message for a map entry.
+ if t == nil {
+ d, _ := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(s))
+ if md, _ := d.(protoreflect.MessageDescriptor); md != nil && md.IsMapEntry() {
+ kt := goTypeForField(md.Fields().ByNumber(1))
+ vt := goTypeForField(md.Fields().ByNumber(2))
+ t = reflect.MapOf(kt, vt)
+ }
+ }
+
+ // Locally cache the message type for the given name.
+ if t != nil {
+ v, _ := messageTypeCache.LoadOrStore(s, t)
+ return v.(reflect.Type)
+ }
+ return nil
+}
+
+func goTypeForField(fd protoreflect.FieldDescriptor) reflect.Type {
+ switch k := fd.Kind(); k {
+ case protoreflect.EnumKind:
+ if et, _ := protoregistry.GlobalTypes.FindEnumByName(fd.Enum().FullName()); et != nil {
+ return enumGoType(et)
+ }
+ return reflect.TypeOf(protoreflect.EnumNumber(0))
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ if mt, _ := protoregistry.GlobalTypes.FindMessageByName(fd.Message().FullName()); mt != nil {
+ return messageGoType(mt)
+ }
+ return reflect.TypeOf((*protoreflect.Message)(nil)).Elem()
+ default:
+ return reflect.TypeOf(fd.Default().Interface())
+ }
+}
+
+func enumGoType(et protoreflect.EnumType) reflect.Type {
+ return reflect.TypeOf(et.New(0))
+}
+
+func messageGoType(mt protoreflect.MessageType) reflect.Type {
+ return reflect.TypeOf(MessageV1(mt.Zero().Interface()))
+}
+
+// MessageName returns the full protobuf name for the given message type.
+//
+// Deprecated: Use protoreflect.MessageDescriptor.FullName instead.
+func MessageName(m Message) messageName {
+ if m == nil {
+ return ""
+ }
+ if m, ok := m.(interface{ XXX_MessageName() messageName }); ok {
+ return m.XXX_MessageName()
+ }
+ return messageName(protoimpl.X.MessageDescriptorOf(m).FullName())
+}
+
+// RegisterExtension is called from the generated code to register
+// the extension descriptor.
+//
+// Deprecated: Use protoregistry.GlobalTypes.RegisterExtension instead.
+func RegisterExtension(d *ExtensionDesc) {
+ if err := protoregistry.GlobalTypes.RegisterExtension(d); err != nil {
+ panic(err)
+ }
+}
+
+type extensionsByNumber = map[int32]*ExtensionDesc
+
+var extensionCache sync.Map // map[messageName]extensionsByNumber
+
+// RegisteredExtensions returns a map of the registered extensions for the
+// provided protobuf message, indexed by the extension field number.
+//
+// Deprecated: Use protoregistry.GlobalTypes.RangeExtensionsByMessage instead.
+func RegisteredExtensions(m Message) extensionsByNumber {
+ // Check whether the cache is stale. If the number of extensions for
+ // the given message differs, then it means that some extensions were
+ // recently registered upstream that we do not know about.
+ s := MessageName(m)
+ v, _ := extensionCache.Load(s)
+ xs, _ := v.(extensionsByNumber)
+ if protoregistry.GlobalTypes.NumExtensionsByMessage(protoreflect.FullName(s)) == len(xs) {
+ return xs // cache is up-to-date
+ }
+
+ // Cache is stale, re-compute the extensions map.
+ xs = make(extensionsByNumber)
+ protoregistry.GlobalTypes.RangeExtensionsByMessage(protoreflect.FullName(s), func(xt protoreflect.ExtensionType) bool {
+ if xd, ok := xt.(*ExtensionDesc); ok {
+ xs[int32(xt.TypeDescriptor().Number())] = xd
+ } else {
+ // TODO: This implies that the protoreflect.ExtensionType is a
+ // custom type not generated by protoc-gen-go. We could try and
+ // convert the type to an ExtensionDesc.
+ }
+ return true
+ })
+ extensionCache.Store(s, xs)
+ return xs
+}
diff --git a/vendor/github.com/golang/protobuf/proto/registry_test.go b/vendor/github.com/golang/protobuf/proto/registry_test.go
new file mode 100644
index 000000000..89c4f783c
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/registry_test.go
@@ -0,0 +1,37 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto_test
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+
+ descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
+)
+
+func TestRegistry(t *testing.T) {
+ file := new(descpb.DescriptorProto).ProtoReflect().Descriptor().ParentFile()
+ path := file.Path()
+ pkg := file.Package()
+ if got := proto.FileDescriptor(path); len(got) == 0 {
+ t.Errorf("FileDescriptor(%q) = empty, want non-empty", path)
+ }
+
+ name := protoreflect.FullName(pkg + ".FieldDescriptorProto_Label")
+ if got := proto.EnumValueMap(string(name)); len(got) == 0 {
+ t.Errorf("EnumValueMap(%q) = empty, want non-empty", name)
+ }
+
+ msg := new(descpb.EnumDescriptorProto_EnumReservedRange)
+ name = msg.ProtoReflect().Descriptor().FullName()
+ wantType := reflect.TypeOf(msg)
+ gotType := proto.MessageType(string(name))
+ if gotType != wantType {
+ t.Errorf("MessageType(%q) = %v, want %v", name, gotType, wantType)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/size2_test.go b/vendor/github.com/golang/protobuf/proto/size2_test.go
deleted file mode 100644
index 7846b0617..000000000
--- a/vendor/github.com/golang/protobuf/proto/size2_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "testing"
-)
-
-// This is a separate file and package from size_test.go because that one uses
-// generated messages and thus may not be in package proto without having a circular
-// dependency, whereas this file tests unexported details of size.go.
-
-func TestVarintSize(t *testing.T) {
- // Check the edge cases carefully.
- testCases := []struct {
- n uint64
- size int
- }{
- {0, 1},
- {1, 1},
- {127, 1},
- {128, 2},
- {16383, 2},
- {16384, 3},
- {1<<63 - 1, 9},
- {1 << 63, 10},
- }
- for _, tc := range testCases {
- size := SizeVarint(tc.n)
- if size != tc.size {
- t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size)
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/size_test.go b/vendor/github.com/golang/protobuf/proto/size_test.go
deleted file mode 100644
index 3abac418a..000000000
--- a/vendor/github.com/golang/protobuf/proto/size_test.go
+++ /dev/null
@@ -1,191 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto_test
-
-import (
- "log"
- "strings"
- "testing"
-
- . "github.com/golang/protobuf/proto"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/test_proto"
-)
-
-var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)}
-
-// messageWithExtension2 is in equal_test.go.
-var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)}
-
-func init() {
- if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil {
- log.Panicf("SetExtension: %v", err)
- }
- if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil {
- log.Panicf("SetExtension: %v", err)
- }
-
- // Force messageWithExtension3 to have the extension encoded.
- Marshal(messageWithExtension3)
-
-}
-
-// non-pointer custom message
-type nonptrMessage struct{}
-
-func (m nonptrMessage) ProtoMessage() {}
-func (m nonptrMessage) Reset() {}
-func (m nonptrMessage) String() string { return "" }
-
-func (m nonptrMessage) Marshal() ([]byte, error) {
- return []byte{42}, nil
-}
-
-// custom message embedding a proto.Message
-type messageWithEmbedding struct {
- *pb.OtherMessage
-}
-
-func (m *messageWithEmbedding) ProtoMessage() {}
-func (m *messageWithEmbedding) Reset() {}
-func (m *messageWithEmbedding) String() string { return "" }
-
-func (m *messageWithEmbedding) Marshal() ([]byte, error) {
- return []byte{42}, nil
-}
-
-var SizeTests = []struct {
- desc string
- pb Message
-}{
- {"empty", &pb.OtherMessage{}},
- // Basic types.
- {"bool", &pb.Defaults{F_Bool: Bool(true)}},
- {"int32", &pb.Defaults{F_Int32: Int32(12)}},
- {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}},
- {"small int64", &pb.Defaults{F_Int64: Int64(1)}},
- {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}},
- {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}},
- {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}},
- {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}},
- {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}},
- {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}},
- {"float", &pb.Defaults{F_Float: Float32(12.6)}},
- {"double", &pb.Defaults{F_Double: Float64(13.9)}},
- {"string", &pb.Defaults{F_String: String("niles")}},
- {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}},
- {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}},
- {"sint32", &pb.Defaults{F_Sint32: Int32(65)}},
- {"sint64", &pb.Defaults{F_Sint64: Int64(67)}},
- {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}},
- // Repeated.
- {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}},
- {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}},
- {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}},
- {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}},
- {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}},
- {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{
- // Need enough large numbers to verify that the header is counting the number of bytes
- // for the field, not the number of elements.
- 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62,
- 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62,
- }}},
- {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}},
- {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}},
- // Nested.
- {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}},
- {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}},
- // Other things.
- {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}},
- {"extension (unencoded)", messageWithExtension1},
- {"extension (encoded)", messageWithExtension3},
- // proto3 message
- {"proto3 empty", &proto3pb.Message{}},
- {"proto3 bool", &proto3pb.Message{TrueScotsman: true}},
- {"proto3 int64", &proto3pb.Message{ResultCount: 1}},
- {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}},
- {"proto3 float", &proto3pb.Message{Score: 12.6}},
- {"proto3 string", &proto3pb.Message{Name: "Snezana"}},
- {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}},
- {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}},
- {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
- {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}},
-
- {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}},
- {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}},
- {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}},
- {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}},
-
- {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}},
- {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}},
- {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}},
-
- {"oneof not set", &pb.Oneof{}},
- {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}},
- {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}},
- {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}},
- {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}},
- {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}},
- {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}},
- {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}},
- {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}},
- {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}},
- {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}},
- {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}},
- {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}},
- {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}},
- {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}},
- {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}},
- {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}},
- {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}},
- {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}},
- {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}},
- {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}},
-
- {"non-pointer message", nonptrMessage{}},
- {"custom message with embedding", &messageWithEmbedding{&pb.OtherMessage{}}},
-}
-
-func TestSize(t *testing.T) {
- for _, tc := range SizeTests {
- size := Size(tc.pb)
- b, err := Marshal(tc.pb)
- if err != nil {
- t.Errorf("%v: Marshal failed: %v", tc.desc, err)
- continue
- }
- if size != len(b) {
- t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b))
- t.Logf("%v: bytes: %#v", tc.desc, b)
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go
deleted file mode 100644
index be7b2428c..000000000
--- a/vendor/github.com/golang/protobuf/proto/table_marshal.go
+++ /dev/null
@@ -1,2685 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "errors"
- "fmt"
- "math"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "unicode/utf8"
-)
-
-// a sizer takes a pointer to a field and the size of its tag, computes the size of
-// the encoded data.
-type sizer func(pointer, int) int
-
-// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format),
-// marshals the field to the end of the slice, returns the slice and error (if any).
-type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error)
-
-// marshalInfo is the information used for marshaling a message.
-type marshalInfo struct {
- typ reflect.Type
- fields []*marshalFieldInfo
- unrecognized field // offset of XXX_unrecognized
- extensions field // offset of XXX_InternalExtensions
- v1extensions field // offset of XXX_extensions
- sizecache field // offset of XXX_sizecache
- initialized int32 // 0 -- only typ is set, 1 -- fully initialized
- messageset bool // uses message set wire format
- hasmarshaler bool // has custom marshaler
- sync.RWMutex // protect extElems map, also for initialization
- extElems map[int32]*marshalElemInfo // info of extension elements
-}
-
-// marshalFieldInfo is the information used for marshaling a field of a message.
-type marshalFieldInfo struct {
- field field
- wiretag uint64 // tag in wire format
- tagsize int // size of tag in wire format
- sizer sizer
- marshaler marshaler
- isPointer bool
- required bool // field is required
- name string // name of the field, for error reporting
- oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements
-}
-
-// marshalElemInfo is the information used for marshaling an extension or oneof element.
-type marshalElemInfo struct {
- wiretag uint64 // tag in wire format
- tagsize int // size of tag in wire format
- sizer sizer
- marshaler marshaler
- isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only)
-}
-
-var (
- marshalInfoMap = map[reflect.Type]*marshalInfo{}
- marshalInfoLock sync.Mutex
-)
-
-// getMarshalInfo returns the information to marshal a given type of message.
-// The info it returns may not necessarily initialized.
-// t is the type of the message (NOT the pointer to it).
-func getMarshalInfo(t reflect.Type) *marshalInfo {
- marshalInfoLock.Lock()
- u, ok := marshalInfoMap[t]
- if !ok {
- u = &marshalInfo{typ: t}
- marshalInfoMap[t] = u
- }
- marshalInfoLock.Unlock()
- return u
-}
-
-// Size is the entry point from generated code,
-// and should be ONLY called by generated code.
-// It computes the size of encoded data of msg.
-// a is a pointer to a place to store cached marshal info.
-func (a *InternalMessageInfo) Size(msg Message) int {
- u := getMessageMarshalInfo(msg, a)
- ptr := toPointer(&msg)
- if ptr.isNil() {
- // We get here if msg is a typed nil ((*SomeMessage)(nil)),
- // so it satisfies the interface, and msg == nil wouldn't
- // catch it. We don't want crash in this case.
- return 0
- }
- return u.size(ptr)
-}
-
-// Marshal is the entry point from generated code,
-// and should be ONLY called by generated code.
-// It marshals msg to the end of b.
-// a is a pointer to a place to store cached marshal info.
-func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
- u := getMessageMarshalInfo(msg, a)
- ptr := toPointer(&msg)
- if ptr.isNil() {
- // We get here if msg is a typed nil ((*SomeMessage)(nil)),
- // so it satisfies the interface, and msg == nil wouldn't
- // catch it. We don't want crash in this case.
- return b, ErrNil
- }
- return u.marshal(b, ptr, deterministic)
-}
-
-func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo {
- // u := a.marshal, but atomically.
- // We use an atomic here to ensure memory consistency.
- u := atomicLoadMarshalInfo(&a.marshal)
- if u == nil {
- // Get marshal information from type of message.
- t := reflect.ValueOf(msg).Type()
- if t.Kind() != reflect.Ptr {
- panic(fmt.Sprintf("cannot handle non-pointer message type %v", t))
- }
- u = getMarshalInfo(t.Elem())
- // Store it in the cache for later users.
- // a.marshal = u, but atomically.
- atomicStoreMarshalInfo(&a.marshal, u)
- }
- return u
-}
-
-// size is the main function to compute the size of the encoded data of a message.
-// ptr is the pointer to the message.
-func (u *marshalInfo) size(ptr pointer) int {
- if atomic.LoadInt32(&u.initialized) == 0 {
- u.computeMarshalInfo()
- }
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if u.hasmarshaler {
- m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
- b, _ := m.Marshal()
- return len(b)
- }
-
- n := 0
- for _, f := range u.fields {
- if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
- // nil pointer always marshals to nothing
- continue
- }
- n += f.sizer(ptr.offset(f.field), f.tagsize)
- }
- if u.extensions.IsValid() {
- e := ptr.offset(u.extensions).toExtensions()
- if u.messageset {
- n += u.sizeMessageSet(e)
- } else {
- n += u.sizeExtensions(e)
- }
- }
- if u.v1extensions.IsValid() {
- m := *ptr.offset(u.v1extensions).toOldExtensions()
- n += u.sizeV1Extensions(m)
- }
- if u.unrecognized.IsValid() {
- s := *ptr.offset(u.unrecognized).toBytes()
- n += len(s)
- }
- // cache the result for use in marshal
- if u.sizecache.IsValid() {
- atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n))
- }
- return n
-}
-
-// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated),
-// fall back to compute the size.
-func (u *marshalInfo) cachedsize(ptr pointer) int {
- if u.sizecache.IsValid() {
- return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32()))
- }
- return u.size(ptr)
-}
-
-// marshal is the main function to marshal a message. It takes a byte slice and appends
-// the encoded data to the end of the slice, returns the slice and error (if any).
-// ptr is the pointer to the message.
-// If deterministic is true, map is marshaled in deterministic order.
-func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) {
- if atomic.LoadInt32(&u.initialized) == 0 {
- u.computeMarshalInfo()
- }
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if u.hasmarshaler {
- m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
- b1, err := m.Marshal()
- b = append(b, b1...)
- return b, err
- }
-
- var err, errreq error
- // The old marshaler encodes extensions at beginning.
- if u.extensions.IsValid() {
- e := ptr.offset(u.extensions).toExtensions()
- if u.messageset {
- b, err = u.appendMessageSet(b, e, deterministic)
- } else {
- b, err = u.appendExtensions(b, e, deterministic)
- }
- if err != nil {
- return b, err
- }
- }
- if u.v1extensions.IsValid() {
- m := *ptr.offset(u.v1extensions).toOldExtensions()
- b, err = u.appendV1Extensions(b, m, deterministic)
- if err != nil {
- return b, err
- }
- }
- for _, f := range u.fields {
- if f.required && errreq == nil {
- if ptr.offset(f.field).getPointer().isNil() {
- // Required field is not set.
- // We record the error but keep going, to give a complete marshaling.
- errreq = &RequiredNotSetError{f.name}
- continue
- }
- }
- if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
- // nil pointer always marshals to nothing
- continue
- }
- b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic)
- if err != nil {
- if err1, ok := err.(*RequiredNotSetError); ok {
- // Required field in submessage is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errreq == nil {
- errreq = &RequiredNotSetError{f.name + "." + err1.field}
- }
- continue
- }
- if err == errRepeatedHasNil {
- err = errors.New("proto: repeated field " + f.name + " has nil element")
- }
- if err == errInvalidUTF8 {
- fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
- err = fmt.Errorf("proto: string field %q contains invalid UTF-8", fullName)
- }
- return b, err
- }
- }
- if u.unrecognized.IsValid() {
- s := *ptr.offset(u.unrecognized).toBytes()
- b = append(b, s...)
- }
- return b, errreq
-}
-
-// computeMarshalInfo initializes the marshal info.
-func (u *marshalInfo) computeMarshalInfo() {
- u.Lock()
- defer u.Unlock()
- if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock
- return
- }
-
- t := u.typ
- u.unrecognized = invalidField
- u.extensions = invalidField
- u.v1extensions = invalidField
- u.sizecache = invalidField
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if reflect.PtrTo(t).Implements(marshalerType) {
- u.hasmarshaler = true
- atomic.StoreInt32(&u.initialized, 1)
- return
- }
-
- // get oneof implementers
- var oneofImplementers []interface{}
- if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok {
- _, _, _, oneofImplementers = m.XXX_OneofFuncs()
- }
-
- n := t.NumField()
-
- // deal with XXX fields first
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- if !strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- switch f.Name {
- case "XXX_sizecache":
- u.sizecache = toField(&f)
- case "XXX_unrecognized":
- u.unrecognized = toField(&f)
- case "XXX_InternalExtensions":
- u.extensions = toField(&f)
- u.messageset = f.Tag.Get("protobuf_messageset") == "1"
- case "XXX_extensions":
- u.v1extensions = toField(&f)
- case "XXX_NoUnkeyedLiteral":
- // nothing to do
- default:
- panic("unknown XXX field: " + f.Name)
- }
- n--
- }
-
- // normal fields
- fields := make([]marshalFieldInfo, n) // batch allocation
- u.fields = make([]*marshalFieldInfo, 0, n)
- for i, j := 0, 0; i < t.NumField(); i++ {
- f := t.Field(i)
-
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- field := &fields[j]
- j++
- field.name = f.Name
- u.fields = append(u.fields, field)
- if f.Tag.Get("protobuf_oneof") != "" {
- field.computeOneofFieldInfo(&f, oneofImplementers)
- continue
- }
- if f.Tag.Get("protobuf") == "" {
- // field has no tag (not in generated message), ignore it
- u.fields = u.fields[:len(u.fields)-1]
- j--
- continue
- }
- field.computeMarshalFieldInfo(&f)
- }
-
- // fields are marshaled in tag order on the wire.
- sort.Sort(byTag(u.fields))
-
- atomic.StoreInt32(&u.initialized, 1)
-}
-
-// helper for sorting fields by tag
-type byTag []*marshalFieldInfo
-
-func (a byTag) Len() int { return len(a) }
-func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag }
-
-// getExtElemInfo returns the information to marshal an extension element.
-// The info it returns is initialized.
-func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo {
- // get from cache first
- u.RLock()
- e, ok := u.extElems[desc.Field]
- u.RUnlock()
- if ok {
- return e
- }
-
- t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct
- tags := strings.Split(desc.Tag, ",")
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- sizer, marshaler := typeMarshaler(t, tags, false, false)
- e = &marshalElemInfo{
- wiretag: uint64(tag)<<3 | wt,
- tagsize: SizeVarint(uint64(tag) << 3),
- sizer: sizer,
- marshaler: marshaler,
- isptr: t.Kind() == reflect.Ptr,
- }
-
- // update cache
- u.Lock()
- if u.extElems == nil {
- u.extElems = make(map[int32]*marshalElemInfo)
- }
- u.extElems[desc.Field] = e
- u.Unlock()
- return e
-}
-
-// computeMarshalFieldInfo fills up the information to marshal a field.
-func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) {
- // parse protobuf tag of the field.
- // tag has format of "bytes,49,opt,name=foo,def=hello!"
- tags := strings.Split(f.Tag.Get("protobuf"), ",")
- if tags[0] == "" {
- return
- }
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- if tags[2] == "req" {
- fi.required = true
- }
- fi.setTag(f, tag, wt)
- fi.setMarshaler(f, tags)
-}
-
-func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) {
- fi.field = toField(f)
- fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire.
- fi.isPointer = true
- fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f)
- fi.oneofElems = make(map[reflect.Type]*marshalElemInfo)
-
- ityp := f.Type // interface type
- for _, o := range oneofImplementers {
- t := reflect.TypeOf(o)
- if !t.Implements(ityp) {
- continue
- }
- sf := t.Elem().Field(0) // oneof implementer is a struct with a single field
- tags := strings.Split(sf.Tag.Get("protobuf"), ",")
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value
- fi.oneofElems[t.Elem()] = &marshalElemInfo{
- wiretag: uint64(tag)<<3 | wt,
- tagsize: SizeVarint(uint64(tag) << 3),
- sizer: sizer,
- marshaler: marshaler,
- }
- }
-}
-
-type oneofMessage interface {
- XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
-}
-
-// wiretype returns the wire encoding of the type.
-func wiretype(encoding string) uint64 {
- switch encoding {
- case "fixed32":
- return WireFixed32
- case "fixed64":
- return WireFixed64
- case "varint", "zigzag32", "zigzag64":
- return WireVarint
- case "bytes":
- return WireBytes
- case "group":
- return WireStartGroup
- }
- panic("unknown wire type " + encoding)
-}
-
-// setTag fills up the tag (in wire format) and its size in the info of a field.
-func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) {
- fi.field = toField(f)
- fi.wiretag = uint64(tag)<<3 | wt
- fi.tagsize = SizeVarint(uint64(tag) << 3)
-}
-
-// setMarshaler fills up the sizer and marshaler in the info of a field.
-func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) {
- switch f.Type.Kind() {
- case reflect.Map:
- // map field
- fi.isPointer = true
- fi.sizer, fi.marshaler = makeMapMarshaler(f)
- return
- case reflect.Ptr, reflect.Slice:
- fi.isPointer = true
- }
- fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false)
-}
-
-// typeMarshaler returns the sizer and marshaler of a given field.
-// t is the type of the field.
-// tags is the generated "protobuf" tag of the field.
-// If nozero is true, zero value is not marshaled to the wire.
-// If oneof is true, it is a oneof field.
-func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) {
- encoding := tags[0]
-
- pointer := false
- slice := false
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- slice = true
- t = t.Elem()
- }
- if t.Kind() == reflect.Ptr {
- pointer = true
- t = t.Elem()
- }
-
- packed := false
- proto3 := false
- for i := 2; i < len(tags); i++ {
- if tags[i] == "packed" {
- packed = true
- }
- if tags[i] == "proto3" {
- proto3 = true
- }
- }
-
- switch t.Kind() {
- case reflect.Bool:
- if pointer {
- return sizeBoolPtr, appendBoolPtr
- }
- if slice {
- if packed {
- return sizeBoolPackedSlice, appendBoolPackedSlice
- }
- return sizeBoolSlice, appendBoolSlice
- }
- if nozero {
- return sizeBoolValueNoZero, appendBoolValueNoZero
- }
- return sizeBoolValue, appendBoolValue
- case reflect.Uint32:
- switch encoding {
- case "fixed32":
- if pointer {
- return sizeFixed32Ptr, appendFixed32Ptr
- }
- if slice {
- if packed {
- return sizeFixed32PackedSlice, appendFixed32PackedSlice
- }
- return sizeFixed32Slice, appendFixed32Slice
- }
- if nozero {
- return sizeFixed32ValueNoZero, appendFixed32ValueNoZero
- }
- return sizeFixed32Value, appendFixed32Value
- case "varint":
- if pointer {
- return sizeVarint32Ptr, appendVarint32Ptr
- }
- if slice {
- if packed {
- return sizeVarint32PackedSlice, appendVarint32PackedSlice
- }
- return sizeVarint32Slice, appendVarint32Slice
- }
- if nozero {
- return sizeVarint32ValueNoZero, appendVarint32ValueNoZero
- }
- return sizeVarint32Value, appendVarint32Value
- }
- case reflect.Int32:
- switch encoding {
- case "fixed32":
- if pointer {
- return sizeFixedS32Ptr, appendFixedS32Ptr
- }
- if slice {
- if packed {
- return sizeFixedS32PackedSlice, appendFixedS32PackedSlice
- }
- return sizeFixedS32Slice, appendFixedS32Slice
- }
- if nozero {
- return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero
- }
- return sizeFixedS32Value, appendFixedS32Value
- case "varint":
- if pointer {
- return sizeVarintS32Ptr, appendVarintS32Ptr
- }
- if slice {
- if packed {
- return sizeVarintS32PackedSlice, appendVarintS32PackedSlice
- }
- return sizeVarintS32Slice, appendVarintS32Slice
- }
- if nozero {
- return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero
- }
- return sizeVarintS32Value, appendVarintS32Value
- case "zigzag32":
- if pointer {
- return sizeZigzag32Ptr, appendZigzag32Ptr
- }
- if slice {
- if packed {
- return sizeZigzag32PackedSlice, appendZigzag32PackedSlice
- }
- return sizeZigzag32Slice, appendZigzag32Slice
- }
- if nozero {
- return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero
- }
- return sizeZigzag32Value, appendZigzag32Value
- }
- case reflect.Uint64:
- switch encoding {
- case "fixed64":
- if pointer {
- return sizeFixed64Ptr, appendFixed64Ptr
- }
- if slice {
- if packed {
- return sizeFixed64PackedSlice, appendFixed64PackedSlice
- }
- return sizeFixed64Slice, appendFixed64Slice
- }
- if nozero {
- return sizeFixed64ValueNoZero, appendFixed64ValueNoZero
- }
- return sizeFixed64Value, appendFixed64Value
- case "varint":
- if pointer {
- return sizeVarint64Ptr, appendVarint64Ptr
- }
- if slice {
- if packed {
- return sizeVarint64PackedSlice, appendVarint64PackedSlice
- }
- return sizeVarint64Slice, appendVarint64Slice
- }
- if nozero {
- return sizeVarint64ValueNoZero, appendVarint64ValueNoZero
- }
- return sizeVarint64Value, appendVarint64Value
- }
- case reflect.Int64:
- switch encoding {
- case "fixed64":
- if pointer {
- return sizeFixedS64Ptr, appendFixedS64Ptr
- }
- if slice {
- if packed {
- return sizeFixedS64PackedSlice, appendFixedS64PackedSlice
- }
- return sizeFixedS64Slice, appendFixedS64Slice
- }
- if nozero {
- return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero
- }
- return sizeFixedS64Value, appendFixedS64Value
- case "varint":
- if pointer {
- return sizeVarintS64Ptr, appendVarintS64Ptr
- }
- if slice {
- if packed {
- return sizeVarintS64PackedSlice, appendVarintS64PackedSlice
- }
- return sizeVarintS64Slice, appendVarintS64Slice
- }
- if nozero {
- return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero
- }
- return sizeVarintS64Value, appendVarintS64Value
- case "zigzag64":
- if pointer {
- return sizeZigzag64Ptr, appendZigzag64Ptr
- }
- if slice {
- if packed {
- return sizeZigzag64PackedSlice, appendZigzag64PackedSlice
- }
- return sizeZigzag64Slice, appendZigzag64Slice
- }
- if nozero {
- return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero
- }
- return sizeZigzag64Value, appendZigzag64Value
- }
- case reflect.Float32:
- if pointer {
- return sizeFloat32Ptr, appendFloat32Ptr
- }
- if slice {
- if packed {
- return sizeFloat32PackedSlice, appendFloat32PackedSlice
- }
- return sizeFloat32Slice, appendFloat32Slice
- }
- if nozero {
- return sizeFloat32ValueNoZero, appendFloat32ValueNoZero
- }
- return sizeFloat32Value, appendFloat32Value
- case reflect.Float64:
- if pointer {
- return sizeFloat64Ptr, appendFloat64Ptr
- }
- if slice {
- if packed {
- return sizeFloat64PackedSlice, appendFloat64PackedSlice
- }
- return sizeFloat64Slice, appendFloat64Slice
- }
- if nozero {
- return sizeFloat64ValueNoZero, appendFloat64ValueNoZero
- }
- return sizeFloat64Value, appendFloat64Value
- case reflect.String:
- if pointer {
- return sizeStringPtr, appendStringPtr
- }
- if slice {
- return sizeStringSlice, appendStringSlice
- }
- if nozero {
- return sizeStringValueNoZero, appendStringValueNoZero
- }
- return sizeStringValue, appendStringValue
- case reflect.Slice:
- if slice {
- return sizeBytesSlice, appendBytesSlice
- }
- if oneof {
- // Oneof bytes field may also have "proto3" tag.
- // We want to marshal it as a oneof field. Do this
- // check before the proto3 check.
- return sizeBytesOneof, appendBytesOneof
- }
- if proto3 {
- return sizeBytes3, appendBytes3
- }
- return sizeBytes, appendBytes
- case reflect.Struct:
- switch encoding {
- case "group":
- if slice {
- return makeGroupSliceMarshaler(getMarshalInfo(t))
- }
- return makeGroupMarshaler(getMarshalInfo(t))
- case "bytes":
- if slice {
- return makeMessageSliceMarshaler(getMarshalInfo(t))
- }
- return makeMessageMarshaler(getMarshalInfo(t))
- }
- }
- panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding))
-}
-
-// Below are functions to size/marshal a specific type of a field.
-// They are stored in the field's info, and called by function pointers.
-// They have type sizer or marshaler.
-
-func sizeFixed32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixed32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixed32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFixed32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFixedS32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixedS32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixedS32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFloat32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int {
- v := math.Float32bits(*ptr.toFloat32())
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFloat32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toFloat32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFloat32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFloat32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFixed64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixed64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixed64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFixed64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeFixedS64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixedS64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixedS64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeFloat64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int {
- v := math.Float64bits(*ptr.toFloat64())
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFloat64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toFloat64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFloat64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFloat64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeVarint32Value(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarint32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarint32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarint32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarintS32Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarintS32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarint64Value(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- return SizeVarint(v) + tagsize
-}
-func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- if v == 0 {
- return 0
- }
- return SizeVarint(v) + tagsize
-}
-func sizeVarint64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(*p) + tagsize
-}
-func sizeVarint64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(v) + tagsize
- }
- return n
-}
-func sizeVarint64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(v)
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarintS64Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarintS64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeZigzag32Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- v := *p
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
- }
- return n
-}
-func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeZigzag64Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- v := *p
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
- }
- return n
-}
-func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeBoolValue(_ pointer, tagsize int) int {
- return 1 + tagsize
-}
-func sizeBoolValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toBool()
- if !v {
- return 0
- }
- return 1 + tagsize
-}
-func sizeBoolPtr(ptr pointer, tagsize int) int {
- p := *ptr.toBoolPtr()
- if p == nil {
- return 0
- }
- return 1 + tagsize
-}
-func sizeBoolSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBoolSlice()
- return (1 + tagsize) * len(s)
-}
-func sizeBoolPackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBoolSlice()
- if len(s) == 0 {
- return 0
- }
- return len(s) + SizeVarint(uint64(len(s))) + tagsize
-}
-func sizeStringValue(ptr pointer, tagsize int) int {
- v := *ptr.toString()
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toString()
- if v == "" {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringPtr(ptr pointer, tagsize int) int {
- p := *ptr.toStringPtr()
- if p == nil {
- return 0
- }
- v := *p
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringSlice(ptr pointer, tagsize int) int {
- s := *ptr.toStringSlice()
- n := 0
- for _, v := range s {
- n += len(v) + SizeVarint(uint64(len(v))) + tagsize
- }
- return n
-}
-func sizeBytes(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- if v == nil {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytes3(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- if len(v) == 0 {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytesOneof(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytesSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBytesSlice()
- n := 0
- for _, v := range s {
- n += len(v) + SizeVarint(uint64(len(v))) + tagsize
- }
- return n
-}
-
-// appendFixed32 appends an encoded fixed32 to b.
-func appendFixed32(b []byte, v uint32) []byte {
- b = append(b,
- byte(v),
- byte(v>>8),
- byte(v>>16),
- byte(v>>24))
- return b
-}
-
-// appendFixed64 appends an encoded fixed64 to b.
-func appendFixed64(b []byte, v uint64) []byte {
- b = append(b,
- byte(v),
- byte(v>>8),
- byte(v>>16),
- byte(v>>24),
- byte(v>>32),
- byte(v>>40),
- byte(v>>48),
- byte(v>>56))
- return b
-}
-
-// appendVarint appends an encoded varint to b.
-func appendVarint(b []byte, v uint64) []byte {
- // TODO: make 1-byte (maybe 2-byte) case inline-able, once we
- // have non-leaf inliner.
- switch {
- case v < 1<<7:
- b = append(b, byte(v))
- case v < 1<<14:
- b = append(b,
- byte(v&0x7f|0x80),
- byte(v>>7))
- case v < 1<<21:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte(v>>14))
- case v < 1<<28:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte(v>>21))
- case v < 1<<35:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte(v>>28))
- case v < 1<<42:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte(v>>35))
- case v < 1<<49:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte(v>>42))
- case v < 1<<56:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte(v>>49))
- case v < 1<<63:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte((v>>49)&0x7f|0x80),
- byte(v>>56))
- default:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte((v>>49)&0x7f|0x80),
- byte((v>>56)&0x7f|0x80),
- 1)
- }
- return b
-}
-
-func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, *p)
- return b, nil
-}
-func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- }
- return b, nil
-}
-func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, v)
- }
- return b, nil
-}
-func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- return b, nil
-}
-func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- return b, nil
-}
-func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(*p))
- return b, nil
-}
-func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- }
- return b, nil
-}
-func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, uint32(v))
- }
- return b, nil
-}
-func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float32bits(*ptr.toFloat32())
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float32bits(*ptr.toFloat32())
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toFloat32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, math.Float32bits(*p))
- return b, nil
-}
-func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, math.Float32bits(v))
- }
- return b, nil
-}
-func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, math.Float32bits(v))
- }
- return b, nil
-}
-func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, *p)
- return b, nil
-}
-func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- }
- return b, nil
-}
-func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, v)
- }
- return b, nil
-}
-func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- return b, nil
-}
-func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- return b, nil
-}
-func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(*p))
- return b, nil
-}
-func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- }
- return b, nil
-}
-func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, uint64(v))
- }
- return b, nil
-}
-func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float64bits(*ptr.toFloat64())
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float64bits(*ptr.toFloat64())
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toFloat64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, math.Float64bits(*p))
- return b, nil
-}
-func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, math.Float64bits(v))
- }
- return b, nil
-}
-func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, math.Float64bits(v))
- }
- return b, nil
-}
-func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- return b, nil
-}
-func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- return b, nil
-}
-func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, *p)
- return b, nil
-}
-func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- }
- return b, nil
-}
-func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(v)
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, v)
- }
- return b, nil
-}
-func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- v := *p
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- }
- return b, nil
-}
-func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- }
- return b, nil
-}
-func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- v := *p
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- }
- return b, nil
-}
-func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- }
- return b, nil
-}
-func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBool()
- b = appendVarint(b, wiretag)
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- return b, nil
-}
-func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBool()
- if !v {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = append(b, 1)
- return b, nil
-}
-
-func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toBoolPtr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- if *p {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- return b, nil
-}
-func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBoolSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- }
- return b, nil
-}
-func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBoolSlice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(len(s)))
- for _, v := range s {
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- }
- return b, nil
-}
-func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toString()
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toString()
- if v == "" {
- return b, nil
- }
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toStringPtr()
- if p == nil {
- return b, nil
- }
- v := *p
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toStringSlice()
- for _, v := range s {
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- return b, nil
-}
-func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- if v == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- if len(v) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBytesSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- return b, nil
-}
-
-// makeGroupMarshaler returns the sizer and marshaler for a group.
-// u is the marshal info of the underlying message.
-func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- return u.size(p) + 2*tagsize
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- p := ptr.getPointer()
- if p.isNil() {
- return b, nil
- }
- var err error
- b = appendVarint(b, wiretag) // start group
- b, err = u.marshal(b, p, deterministic)
- b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
- return b, err
- }
-}
-
-// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice.
-// u is the marshal info of the underlying message.
-func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- s := ptr.getPointerSlice()
- n := 0
- for _, v := range s {
- if v.isNil() {
- continue
- }
- n += u.size(v) + 2*tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- s := ptr.getPointerSlice()
- var err, errreq error
- for _, v := range s {
- if v.isNil() {
- return b, errRepeatedHasNil
- }
- b = appendVarint(b, wiretag) // start group
- b, err = u.marshal(b, v, deterministic)
- b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
- if err != nil {
- if _, ok := err.(*RequiredNotSetError); ok {
- // Required field in submessage is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errreq == nil {
- errreq = err
- }
- continue
- }
- if err == ErrNil {
- err = errRepeatedHasNil
- }
- return b, err
- }
- }
- return b, errreq
- }
-}
-
-// makeMessageMarshaler returns the sizer and marshaler for a message field.
-// u is the marshal info of the message.
-func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- siz := u.size(p)
- return siz + SizeVarint(uint64(siz)) + tagsize
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- p := ptr.getPointer()
- if p.isNil() {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- siz := u.cachedsize(p)
- b = appendVarint(b, uint64(siz))
- return u.marshal(b, p, deterministic)
- }
-}
-
-// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice.
-// u is the marshal info of the message.
-func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- s := ptr.getPointerSlice()
- n := 0
- for _, v := range s {
- if v.isNil() {
- continue
- }
- siz := u.size(v)
- n += siz + SizeVarint(uint64(siz)) + tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- s := ptr.getPointerSlice()
- var err, errreq error
- for _, v := range s {
- if v.isNil() {
- return b, errRepeatedHasNil
- }
- b = appendVarint(b, wiretag)
- siz := u.cachedsize(v)
- b = appendVarint(b, uint64(siz))
- b, err = u.marshal(b, v, deterministic)
-
- if err != nil {
- if _, ok := err.(*RequiredNotSetError); ok {
- // Required field in submessage is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errreq == nil {
- errreq = err
- }
- continue
- }
- if err == ErrNil {
- err = errRepeatedHasNil
- }
- return b, err
- }
- }
- return b, errreq
- }
-}
-
-// makeMapMarshaler returns the sizer and marshaler for a map field.
-// f is the pointer to the reflect data structure of the field.
-func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) {
- // figure out key and value type
- t := f.Type
- keyType := t.Key()
- valType := t.Elem()
- keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",")
- valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
- keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map
- valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map
- keyWireTag := 1<<3 | wiretype(keyTags[0])
- valWireTag := 2<<3 | wiretype(valTags[0])
-
- // We create an interface to get the addresses of the map key and value.
- // If value is pointer-typed, the interface is a direct interface, the
- // idata itself is the value. Otherwise, the idata is the pointer to the
- // value.
- // Key cannot be pointer-typed.
- valIsPtr := valType.Kind() == reflect.Ptr
- return func(ptr pointer, tagsize int) int {
- m := ptr.asPointerTo(t).Elem() // the map
- n := 0
- for _, k := range m.MapKeys() {
- ki := k.Interface()
- vi := m.MapIndex(k).Interface()
- kaddr := toAddrPointer(&ki, false) // pointer to key
- vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
- siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
- n += siz + SizeVarint(uint64(siz)) + tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) {
- m := ptr.asPointerTo(t).Elem() // the map
- var err error
- keys := m.MapKeys()
- if len(keys) > 1 && deterministic {
- sort.Sort(mapKeys(keys))
- }
- for _, k := range keys {
- ki := k.Interface()
- vi := m.MapIndex(k).Interface()
- kaddr := toAddrPointer(&ki, false) // pointer to key
- vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
- b = appendVarint(b, tag)
- siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
- b = appendVarint(b, uint64(siz))
- b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic)
- if err != nil {
- return b, err
- }
- b, err = valMarshaler(b, vaddr, valWireTag, deterministic)
- if err != nil && err != ErrNil { // allow nil value in map
- return b, err
- }
- }
- return b, nil
- }
-}
-
-// makeOneOfMarshaler returns the sizer and marshaler for a oneof field.
-// fi is the marshal info of the field.
-// f is the pointer to the reflect data structure of the field.
-func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) {
- // Oneof field is an interface. We need to get the actual data type on the fly.
- t := f.Type
- return func(ptr pointer, _ int) int {
- p := ptr.getInterfacePointer()
- if p.isNil() {
- return 0
- }
- v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
- telem := v.Type()
- e := fi.oneofElems[telem]
- return e.sizer(p, e.tagsize)
- },
- func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) {
- p := ptr.getInterfacePointer()
- if p.isNil() {
- return b, nil
- }
- v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
- telem := v.Type()
- if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() {
- return b, errOneofHasNil
- }
- e := fi.oneofElems[telem]
- return e.marshaler(b, p, e.wiretag, deterministic)
- }
-}
-
-// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field.
-func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int {
- m, mu := ext.extensionsRead()
- if m == nil {
- return 0
- }
- mu.Lock()
-
- n := 0
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- n += len(e.enc)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- n += ei.sizer(p, ei.tagsize)
- }
- mu.Unlock()
- return n
-}
-
-// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b.
-func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
- m, mu := ext.extensionsRead()
- if m == nil {
- return b, nil
- }
- mu.Lock()
- defer mu.Unlock()
-
- var err error
-
- // Fast-path for common cases: zero or one extensions.
- // Don't bother sorting the keys.
- if len(m) <= 1 {
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, e.enc...)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if err != nil {
- return b, err
- }
- }
- return b, nil
- }
-
- // Sort the keys to provide a deterministic encoding.
- // Not sure this is required, but the old code does it.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, k := range keys {
- e := m[int32(k)]
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, e.enc...)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if err != nil {
- return b, err
- }
- }
- return b, nil
-}
-
-// message set format is:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-
-// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field
-// in message set format (above).
-func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int {
- m, mu := ext.extensionsRead()
- if m == nil {
- return 0
- }
- mu.Lock()
-
- n := 0
- for id, e := range m {
- n += 2 // start group, end group. tag = 1 (size=1)
- n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1)
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- siz := len(msgWithLen)
- n += siz + 1 // message, tag = 3 (size=1)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- n += ei.sizer(p, 1) // message, tag = 3 (size=1)
- }
- mu.Unlock()
- return n
-}
-
-// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above)
-// to the end of byte slice b.
-func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
- m, mu := ext.extensionsRead()
- if m == nil {
- return b, nil
- }
- mu.Lock()
- defer mu.Unlock()
-
- var err error
-
- // Fast-path for common cases: zero or one extensions.
- // Don't bother sorting the keys.
- if len(m) <= 1 {
- for id, e := range m {
- b = append(b, 1<<3|WireStartGroup)
- b = append(b, 2<<3|WireVarint)
- b = appendVarint(b, uint64(id))
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- b = append(b, 3<<3|WireBytes)
- b = append(b, msgWithLen...)
- b = append(b, 1<<3|WireEndGroup)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
- if err != nil {
- return b, err
- }
- b = append(b, 1<<3|WireEndGroup)
- }
- return b, nil
- }
-
- // Sort the keys to provide a deterministic encoding.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, id := range keys {
- e := m[int32(id)]
- b = append(b, 1<<3|WireStartGroup)
- b = append(b, 2<<3|WireVarint)
- b = appendVarint(b, uint64(id))
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- b = append(b, 3<<3|WireBytes)
- b = append(b, msgWithLen...)
- b = append(b, 1<<3|WireEndGroup)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
- b = append(b, 1<<3|WireEndGroup)
- if err != nil {
- return b, err
- }
- }
- return b, nil
-}
-
-// sizeV1Extensions computes the size of encoded data for a V1-API extension field.
-func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int {
- if m == nil {
- return 0
- }
-
- n := 0
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- n += len(e.enc)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- n += ei.sizer(p, ei.tagsize)
- }
- return n
-}
-
-// appendV1Extensions marshals a V1-API extension field to the end of byte slice b.
-func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) {
- if m == nil {
- return b, nil
- }
-
- // Sort the keys to provide a deterministic encoding.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- var err error
- for _, k := range keys {
- e := m[int32(k)]
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, e.enc...)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if err != nil {
- return b, err
- }
- }
- return b, nil
-}
-
-// newMarshaler is the interface representing objects that can marshal themselves.
-//
-// This exists to support protoc-gen-go generated messages.
-// The proto package will stop type-asserting to this interface in the future.
-//
-// DO NOT DEPEND ON THIS.
-type newMarshaler interface {
- XXX_Size() int
- XXX_Marshal(b []byte, deterministic bool) ([]byte, error)
-}
-
-// Size returns the encoded size of a protocol buffer message.
-// This is the main entry point.
-func Size(pb Message) int {
- if m, ok := pb.(newMarshaler); ok {
- return m.XXX_Size()
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- b, _ := m.Marshal()
- return len(b)
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return 0
- }
- var info InternalMessageInfo
- return info.Size(pb)
-}
-
-// Marshal takes a protocol buffer message
-// and encodes it into the wire format, returning the data.
-// This is the main entry point.
-func Marshal(pb Message) ([]byte, error) {
- if m, ok := pb.(newMarshaler); ok {
- siz := m.XXX_Size()
- b := make([]byte, 0, siz)
- return m.XXX_Marshal(b, false)
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- return m.Marshal()
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return nil, ErrNil
- }
- var info InternalMessageInfo
- siz := info.Size(pb)
- b := make([]byte, 0, siz)
- return info.Marshal(b, pb, false)
-}
-
-// Marshal takes a protocol buffer message
-// and encodes it into the wire format, writing the result to the
-// Buffer.
-// This is an alternative entry point. It is not necessary to use
-// a Buffer for most applications.
-func (p *Buffer) Marshal(pb Message) error {
- var err error
- if m, ok := pb.(newMarshaler); ok {
- siz := m.XXX_Size()
- p.grow(siz) // make sure buf has enough capacity
- p.buf, err = m.XXX_Marshal(p.buf, p.deterministic)
- return err
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- b, err := m.Marshal()
- p.buf = append(p.buf, b...)
- return err
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return ErrNil
- }
- var info InternalMessageInfo
- siz := info.Size(pb)
- p.grow(siz) // make sure buf has enough capacity
- p.buf, err = info.Marshal(p.buf, pb, p.deterministic)
- return err
-}
-
-// grow grows the buffer's capacity, if necessary, to guarantee space for
-// another n bytes. After grow(n), at least n bytes can be written to the
-// buffer without another allocation.
-func (p *Buffer) grow(n int) {
- need := len(p.buf) + n
- if need <= cap(p.buf) {
- return
- }
- newCap := len(p.buf) * 2
- if newCap < need {
- newCap = need
- }
- p.buf = append(make([]byte, 0, newCap), p.buf...)
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go
deleted file mode 100644
index 5525def6a..000000000
--- a/vendor/github.com/golang/protobuf/proto/table_merge.go
+++ /dev/null
@@ -1,654 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "fmt"
- "reflect"
- "strings"
- "sync"
- "sync/atomic"
-)
-
-// Merge merges the src message into dst.
-// This assumes that dst and src of the same type and are non-nil.
-func (a *InternalMessageInfo) Merge(dst, src Message) {
- mi := atomicLoadMergeInfo(&a.merge)
- if mi == nil {
- mi = getMergeInfo(reflect.TypeOf(dst).Elem())
- atomicStoreMergeInfo(&a.merge, mi)
- }
- mi.merge(toPointer(&dst), toPointer(&src))
-}
-
-type mergeInfo struct {
- typ reflect.Type
-
- initialized int32 // 0: only typ is valid, 1: everything is valid
- lock sync.Mutex
-
- fields []mergeFieldInfo
- unrecognized field // Offset of XXX_unrecognized
-}
-
-type mergeFieldInfo struct {
- field field // Offset of field, guaranteed to be valid
-
- // isPointer reports whether the value in the field is a pointer.
- // This is true for the following situations:
- // * Pointer to struct
- // * Pointer to basic type (proto2 only)
- // * Slice (first value in slice header is a pointer)
- // * String (first value in string header is a pointer)
- isPointer bool
-
- // basicWidth reports the width of the field assuming that it is directly
- // embedded in the struct (as is the case for basic types in proto3).
- // The possible values are:
- // 0: invalid
- // 1: bool
- // 4: int32, uint32, float32
- // 8: int64, uint64, float64
- basicWidth int
-
- // Where dst and src are pointers to the types being merged.
- merge func(dst, src pointer)
-}
-
-var (
- mergeInfoMap = map[reflect.Type]*mergeInfo{}
- mergeInfoLock sync.Mutex
-)
-
-func getMergeInfo(t reflect.Type) *mergeInfo {
- mergeInfoLock.Lock()
- defer mergeInfoLock.Unlock()
- mi := mergeInfoMap[t]
- if mi == nil {
- mi = &mergeInfo{typ: t}
- mergeInfoMap[t] = mi
- }
- return mi
-}
-
-// merge merges src into dst assuming they are both of type *mi.typ.
-func (mi *mergeInfo) merge(dst, src pointer) {
- if dst.isNil() {
- panic("proto: nil destination")
- }
- if src.isNil() {
- return // Nothing to do.
- }
-
- if atomic.LoadInt32(&mi.initialized) == 0 {
- mi.computeMergeInfo()
- }
-
- for _, fi := range mi.fields {
- sfp := src.offset(fi.field)
-
- // As an optimization, we can avoid the merge function call cost
- // if we know for sure that the source will have no effect
- // by checking if it is the zero value.
- if unsafeAllowed {
- if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string
- continue
- }
- if fi.basicWidth > 0 {
- switch {
- case fi.basicWidth == 1 && !*sfp.toBool():
- continue
- case fi.basicWidth == 4 && *sfp.toUint32() == 0:
- continue
- case fi.basicWidth == 8 && *sfp.toUint64() == 0:
- continue
- }
- }
- }
-
- dfp := dst.offset(fi.field)
- fi.merge(dfp, sfp)
- }
-
- // TODO: Make this faster?
- out := dst.asPointerTo(mi.typ).Elem()
- in := src.asPointerTo(mi.typ).Elem()
- if emIn, err := extendable(in.Addr().Interface()); err == nil {
- emOut, _ := extendable(out.Addr().Interface())
- mIn, muIn := emIn.extensionsRead()
- if mIn != nil {
- mOut := emOut.extensionsWrite()
- muIn.Lock()
- mergeExtension(mOut, mIn)
- muIn.Unlock()
- }
- }
-
- if mi.unrecognized.IsValid() {
- if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 {
- *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...)
- }
- }
-}
-
-func (mi *mergeInfo) computeMergeInfo() {
- mi.lock.Lock()
- defer mi.lock.Unlock()
- if mi.initialized != 0 {
- return
- }
- t := mi.typ
- n := t.NumField()
-
- props := GetProperties(t)
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
-
- mfi := mergeFieldInfo{field: toField(&f)}
- tf := f.Type
-
- // As an optimization, we can avoid the merge function call cost
- // if we know for sure that the source will have no effect
- // by checking if it is the zero value.
- if unsafeAllowed {
- switch tf.Kind() {
- case reflect.Ptr, reflect.Slice, reflect.String:
- // As a special case, we assume slices and strings are pointers
- // since we know that the first field in the SliceSlice or
- // StringHeader is a data pointer.
- mfi.isPointer = true
- case reflect.Bool:
- mfi.basicWidth = 1
- case reflect.Int32, reflect.Uint32, reflect.Float32:
- mfi.basicWidth = 4
- case reflect.Int64, reflect.Uint64, reflect.Float64:
- mfi.basicWidth = 8
- }
- }
-
- // Unwrap tf to get at its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic("both pointer and slice for basic type in " + tf.Name())
- }
-
- switch tf.Kind() {
- case reflect.Int32:
- switch {
- case isSlice: // E.g., []int32
- mfi.merge = func(dst, src pointer) {
- // NOTE: toInt32Slice is not defined (see pointer_reflect.go).
- /*
- sfsp := src.toInt32Slice()
- if *sfsp != nil {
- dfsp := dst.toInt32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []int64{}
- }
- }
- */
- sfs := src.getInt32Slice()
- if sfs != nil {
- dfs := dst.getInt32Slice()
- dfs = append(dfs, sfs...)
- if dfs == nil {
- dfs = []int32{}
- }
- dst.setInt32Slice(dfs)
- }
- }
- case isPointer: // E.g., *int32
- mfi.merge = func(dst, src pointer) {
- // NOTE: toInt32Ptr is not defined (see pointer_reflect.go).
- /*
- sfpp := src.toInt32Ptr()
- if *sfpp != nil {
- dfpp := dst.toInt32Ptr()
- if *dfpp == nil {
- *dfpp = Int32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- */
- sfp := src.getInt32Ptr()
- if sfp != nil {
- dfp := dst.getInt32Ptr()
- if dfp == nil {
- dst.setInt32Ptr(*sfp)
- } else {
- *dfp = *sfp
- }
- }
- }
- default: // E.g., int32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toInt32(); v != 0 {
- *dst.toInt32() = v
- }
- }
- }
- case reflect.Int64:
- switch {
- case isSlice: // E.g., []int64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toInt64Slice()
- if *sfsp != nil {
- dfsp := dst.toInt64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []int64{}
- }
- }
- }
- case isPointer: // E.g., *int64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toInt64Ptr()
- if *sfpp != nil {
- dfpp := dst.toInt64Ptr()
- if *dfpp == nil {
- *dfpp = Int64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., int64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toInt64(); v != 0 {
- *dst.toInt64() = v
- }
- }
- }
- case reflect.Uint32:
- switch {
- case isSlice: // E.g., []uint32
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toUint32Slice()
- if *sfsp != nil {
- dfsp := dst.toUint32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []uint32{}
- }
- }
- }
- case isPointer: // E.g., *uint32
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toUint32Ptr()
- if *sfpp != nil {
- dfpp := dst.toUint32Ptr()
- if *dfpp == nil {
- *dfpp = Uint32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., uint32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toUint32(); v != 0 {
- *dst.toUint32() = v
- }
- }
- }
- case reflect.Uint64:
- switch {
- case isSlice: // E.g., []uint64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toUint64Slice()
- if *sfsp != nil {
- dfsp := dst.toUint64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []uint64{}
- }
- }
- }
- case isPointer: // E.g., *uint64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toUint64Ptr()
- if *sfpp != nil {
- dfpp := dst.toUint64Ptr()
- if *dfpp == nil {
- *dfpp = Uint64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., uint64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toUint64(); v != 0 {
- *dst.toUint64() = v
- }
- }
- }
- case reflect.Float32:
- switch {
- case isSlice: // E.g., []float32
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toFloat32Slice()
- if *sfsp != nil {
- dfsp := dst.toFloat32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []float32{}
- }
- }
- }
- case isPointer: // E.g., *float32
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toFloat32Ptr()
- if *sfpp != nil {
- dfpp := dst.toFloat32Ptr()
- if *dfpp == nil {
- *dfpp = Float32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., float32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toFloat32(); v != 0 {
- *dst.toFloat32() = v
- }
- }
- }
- case reflect.Float64:
- switch {
- case isSlice: // E.g., []float64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toFloat64Slice()
- if *sfsp != nil {
- dfsp := dst.toFloat64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []float64{}
- }
- }
- }
- case isPointer: // E.g., *float64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toFloat64Ptr()
- if *sfpp != nil {
- dfpp := dst.toFloat64Ptr()
- if *dfpp == nil {
- *dfpp = Float64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., float64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toFloat64(); v != 0 {
- *dst.toFloat64() = v
- }
- }
- }
- case reflect.Bool:
- switch {
- case isSlice: // E.g., []bool
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toBoolSlice()
- if *sfsp != nil {
- dfsp := dst.toBoolSlice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []bool{}
- }
- }
- }
- case isPointer: // E.g., *bool
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toBoolPtr()
- if *sfpp != nil {
- dfpp := dst.toBoolPtr()
- if *dfpp == nil {
- *dfpp = Bool(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., bool
- mfi.merge = func(dst, src pointer) {
- if v := *src.toBool(); v {
- *dst.toBool() = v
- }
- }
- }
- case reflect.String:
- switch {
- case isSlice: // E.g., []string
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toStringSlice()
- if *sfsp != nil {
- dfsp := dst.toStringSlice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []string{}
- }
- }
- }
- case isPointer: // E.g., *string
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toStringPtr()
- if *sfpp != nil {
- dfpp := dst.toStringPtr()
- if *dfpp == nil {
- *dfpp = String(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., string
- mfi.merge = func(dst, src pointer) {
- if v := *src.toString(); v != "" {
- *dst.toString() = v
- }
- }
- }
- case reflect.Slice:
- isProto3 := props.Prop[i].proto3
- switch {
- case isPointer:
- panic("bad pointer in byte slice case in " + tf.Name())
- case tf.Elem().Kind() != reflect.Uint8:
- panic("bad element kind in byte slice case in " + tf.Name())
- case isSlice: // E.g., [][]byte
- mfi.merge = func(dst, src pointer) {
- sbsp := src.toBytesSlice()
- if *sbsp != nil {
- dbsp := dst.toBytesSlice()
- for _, sb := range *sbsp {
- if sb == nil {
- *dbsp = append(*dbsp, nil)
- } else {
- *dbsp = append(*dbsp, append([]byte{}, sb...))
- }
- }
- if *dbsp == nil {
- *dbsp = [][]byte{}
- }
- }
- }
- default: // E.g., []byte
- mfi.merge = func(dst, src pointer) {
- sbp := src.toBytes()
- if *sbp != nil {
- dbp := dst.toBytes()
- if !isProto3 || len(*sbp) > 0 {
- *dbp = append([]byte{}, *sbp...)
- }
- }
- }
- }
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("message field %s without pointer", tf))
- case isSlice: // E.g., []*pb.T
- mi := getMergeInfo(tf)
- mfi.merge = func(dst, src pointer) {
- sps := src.getPointerSlice()
- if sps != nil {
- dps := dst.getPointerSlice()
- for _, sp := range sps {
- var dp pointer
- if !sp.isNil() {
- dp = valToPointer(reflect.New(tf))
- mi.merge(dp, sp)
- }
- dps = append(dps, dp)
- }
- if dps == nil {
- dps = []pointer{}
- }
- dst.setPointerSlice(dps)
- }
- }
- default: // E.g., *pb.T
- mi := getMergeInfo(tf)
- mfi.merge = func(dst, src pointer) {
- sp := src.getPointer()
- if !sp.isNil() {
- dp := dst.getPointer()
- if dp.isNil() {
- dp = valToPointer(reflect.New(tf))
- dst.setPointer(dp)
- }
- mi.merge(dp, sp)
- }
- }
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic("bad pointer or slice in map case in " + tf.Name())
- default: // E.g., map[K]V
- mfi.merge = func(dst, src pointer) {
- sm := src.asPointerTo(tf).Elem()
- if sm.Len() == 0 {
- return
- }
- dm := dst.asPointerTo(tf).Elem()
- if dm.IsNil() {
- dm.Set(reflect.MakeMap(tf))
- }
-
- switch tf.Elem().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- val = reflect.ValueOf(Clone(val.Interface().(Message)))
- dm.SetMapIndex(key, val)
- }
- case reflect.Slice: // E.g. Bytes type (e.g., []byte)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- dm.SetMapIndex(key, val)
- }
- default: // Basic type (e.g., string)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- dm.SetMapIndex(key, val)
- }
- }
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic("bad pointer or slice in interface case in " + tf.Name())
- default: // E.g., interface{}
- // TODO: Make this faster?
- mfi.merge = func(dst, src pointer) {
- su := src.asPointerTo(tf).Elem()
- if !su.IsNil() {
- du := dst.asPointerTo(tf).Elem()
- typ := su.Elem().Type()
- if du.IsNil() || du.Elem().Type() != typ {
- du.Set(reflect.New(typ.Elem())) // Initialize interface if empty
- }
- sv := su.Elem().Elem().Field(0)
- if sv.Kind() == reflect.Ptr && sv.IsNil() {
- return
- }
- dv := du.Elem().Elem().Field(0)
- if dv.Kind() == reflect.Ptr && dv.IsNil() {
- dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty
- }
- switch sv.Type().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- Merge(dv.Interface().(Message), sv.Interface().(Message))
- case reflect.Slice: // E.g. Bytes type (e.g., []byte)
- dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...)))
- default: // Basic type (e.g., string)
- dv.Set(sv)
- }
- }
- }
- }
- default:
- panic(fmt.Sprintf("merger not found for type:%s", tf))
- }
- mi.fields = append(mi.fields, mfi)
- }
-
- mi.unrecognized = invalidField
- if f, ok := t.FieldByName("XXX_unrecognized"); ok {
- if f.Type != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- mi.unrecognized = toField(&f)
- }
-
- atomic.StoreInt32(&mi.initialized, 1)
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
deleted file mode 100644
index 96764347a..000000000
--- a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
+++ /dev/null
@@ -1,1981 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "errors"
- "fmt"
- "io"
- "math"
- "reflect"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "unicode/utf8"
-)
-
-// Unmarshal is the entry point from the generated .pb.go files.
-// This function is not intended to be used by non-generated code.
-// This function is not subject to any compatibility guarantee.
-// msg contains a pointer to a protocol buffer struct.
-// b is the data to be unmarshaled into the protocol buffer.
-// a is a pointer to a place to store cached unmarshal information.
-func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error {
- // Load the unmarshal information for this message type.
- // The atomic load ensures memory consistency.
- u := atomicLoadUnmarshalInfo(&a.unmarshal)
- if u == nil {
- // Slow path: find unmarshal info for msg, update a with it.
- u = getUnmarshalInfo(reflect.TypeOf(msg).Elem())
- atomicStoreUnmarshalInfo(&a.unmarshal, u)
- }
- // Then do the unmarshaling.
- err := u.unmarshal(toPointer(&msg), b)
- return err
-}
-
-type unmarshalInfo struct {
- typ reflect.Type // type of the protobuf struct
-
- // 0 = only typ field is initialized
- // 1 = completely initialized
- initialized int32
- lock sync.Mutex // prevents double initialization
- dense []unmarshalFieldInfo // fields indexed by tag #
- sparse map[uint64]unmarshalFieldInfo // fields indexed by tag #
- reqFields []string // names of required fields
- reqMask uint64 // 1< 0 {
- // Read tag and wire type.
- // Special case 1 and 2 byte varints.
- var x uint64
- if b[0] < 128 {
- x = uint64(b[0])
- b = b[1:]
- } else if len(b) >= 2 && b[1] < 128 {
- x = uint64(b[0]&0x7f) + uint64(b[1])<<7
- b = b[2:]
- } else {
- var n int
- x, n = decodeVarint(b)
- if n == 0 {
- return io.ErrUnexpectedEOF
- }
- b = b[n:]
- }
- tag := x >> 3
- wire := int(x) & 7
-
- // Dispatch on the tag to one of the unmarshal* functions below.
- var f unmarshalFieldInfo
- if tag < uint64(len(u.dense)) {
- f = u.dense[tag]
- } else {
- f = u.sparse[tag]
- }
- if fn := f.unmarshal; fn != nil {
- var err error
- b, err = fn(b, m.offset(f.field), wire)
- if err == nil {
- reqMask |= f.reqMask
- continue
- }
- if r, ok := err.(*RequiredNotSetError); ok {
- // Remember this error, but keep parsing. We need to produce
- // a full parse even if a required field is missing.
- rnse = r
- reqMask |= f.reqMask
- continue
- }
- if err != errInternalBadWireType {
- if err == errInvalidUTF8 {
- fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
- err = fmt.Errorf("proto: string field %q contains invalid UTF-8", fullName)
- }
- return err
- }
- // Fragments with bad wire type are treated as unknown fields.
- }
-
- // Unknown tag.
- if !u.unrecognized.IsValid() {
- // Don't keep unrecognized data; just skip it.
- var err error
- b, err = skipField(b, wire)
- if err != nil {
- return err
- }
- continue
- }
- // Keep unrecognized data around.
- // maybe in extensions, maybe in the unrecognized field.
- z := m.offset(u.unrecognized).toBytes()
- var emap map[int32]Extension
- var e Extension
- for _, r := range u.extensionRanges {
- if uint64(r.Start) <= tag && tag <= uint64(r.End) {
- if u.extensions.IsValid() {
- mp := m.offset(u.extensions).toExtensions()
- emap = mp.extensionsWrite()
- e = emap[int32(tag)]
- z = &e.enc
- break
- }
- if u.oldExtensions.IsValid() {
- p := m.offset(u.oldExtensions).toOldExtensions()
- emap = *p
- if emap == nil {
- emap = map[int32]Extension{}
- *p = emap
- }
- e = emap[int32(tag)]
- z = &e.enc
- break
- }
- panic("no extensions field available")
- }
- }
-
- // Use wire type to skip data.
- var err error
- b0 := b
- b, err = skipField(b, wire)
- if err != nil {
- return err
- }
- *z = encodeVarint(*z, tag<<3|uint64(wire))
- *z = append(*z, b0[:len(b0)-len(b)]...)
-
- if emap != nil {
- emap[int32(tag)] = e
- }
- }
- if rnse != nil {
- // A required field of a submessage/group is missing. Return that error.
- return rnse
- }
- if reqMask != u.reqMask {
- // A required field of this message is missing.
- for _, n := range u.reqFields {
- if reqMask&1 == 0 {
- return &RequiredNotSetError{n}
- }
- reqMask >>= 1
- }
- }
- return nil
-}
-
-// computeUnmarshalInfo fills in u with information for use
-// in unmarshaling protocol buffers of type u.typ.
-func (u *unmarshalInfo) computeUnmarshalInfo() {
- u.lock.Lock()
- defer u.lock.Unlock()
- if u.initialized != 0 {
- return
- }
- t := u.typ
- n := t.NumField()
-
- // Set up the "not found" value for the unrecognized byte buffer.
- // This is the default for proto3.
- u.unrecognized = invalidField
- u.extensions = invalidField
- u.oldExtensions = invalidField
-
- // List of the generated type and offset for each oneof field.
- type oneofField struct {
- ityp reflect.Type // interface type of oneof field
- field field // offset in containing message
- }
- var oneofFields []oneofField
-
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if f.Name == "XXX_unrecognized" {
- // The byte slice used to hold unrecognized input is special.
- if f.Type != reflect.TypeOf(([]byte)(nil)) {
- panic("bad type for XXX_unrecognized field: " + f.Type.Name())
- }
- u.unrecognized = toField(&f)
- continue
- }
- if f.Name == "XXX_InternalExtensions" {
- // Ditto here.
- if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) {
- panic("bad type for XXX_InternalExtensions field: " + f.Type.Name())
- }
- u.extensions = toField(&f)
- if f.Tag.Get("protobuf_messageset") == "1" {
- u.isMessageSet = true
- }
- continue
- }
- if f.Name == "XXX_extensions" {
- // An older form of the extensions field.
- if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) {
- panic("bad type for XXX_extensions field: " + f.Type.Name())
- }
- u.oldExtensions = toField(&f)
- continue
- }
- if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" {
- continue
- }
-
- oneof := f.Tag.Get("protobuf_oneof")
- if oneof != "" {
- oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)})
- // The rest of oneof processing happens below.
- continue
- }
-
- tags := f.Tag.Get("protobuf")
- tagArray := strings.Split(tags, ",")
- if len(tagArray) < 2 {
- panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags)
- }
- tag, err := strconv.Atoi(tagArray[1])
- if err != nil {
- panic("protobuf tag field not an integer: " + tagArray[1])
- }
-
- name := ""
- for _, tag := range tagArray[3:] {
- if strings.HasPrefix(tag, "name=") {
- name = tag[5:]
- }
- }
-
- // Extract unmarshaling function from the field (its type and tags).
- unmarshal := fieldUnmarshaler(&f)
-
- // Required field?
- var reqMask uint64
- if tagArray[2] == "req" {
- bit := len(u.reqFields)
- u.reqFields = append(u.reqFields, name)
- reqMask = uint64(1) << uint(bit)
- // TODO: if we have more than 64 required fields, we end up
- // not verifying that all required fields are present.
- // Fix this, perhaps using a count of required fields?
- }
-
- // Store the info in the correct slot in the message.
- u.setTag(tag, toField(&f), unmarshal, reqMask, name)
- }
-
- // Find any types associated with oneof fields.
- // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it?
- fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs")
- if fn.IsValid() {
- res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{}
- for i := res.Len() - 1; i >= 0; i-- {
- v := res.Index(i) // interface{}
- tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X
- typ := tptr.Elem() // Msg_X
-
- f := typ.Field(0) // oneof implementers have one field
- baseUnmarshal := fieldUnmarshaler(&f)
- tags := strings.Split(f.Tag.Get("protobuf"), ",")
- fieldNum, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("protobuf tag field not an integer: " + tags[1])
- }
- var name string
- for _, tag := range tags {
- if strings.HasPrefix(tag, "name=") {
- name = strings.TrimPrefix(tag, "name=")
- break
- }
- }
-
- // Find the oneof field that this struct implements.
- // Might take O(n^2) to process all of the oneofs, but who cares.
- for _, of := range oneofFields {
- if tptr.Implements(of.ityp) {
- // We have found the corresponding interface for this struct.
- // That lets us know where this struct should be stored
- // when we encounter it during unmarshaling.
- unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal)
- u.setTag(fieldNum, of.field, unmarshal, 0, name)
- }
- }
- }
- }
-
- // Get extension ranges, if any.
- fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray")
- if fn.IsValid() {
- if !u.extensions.IsValid() && !u.oldExtensions.IsValid() {
- panic("a message with extensions, but no extensions field in " + t.Name())
- }
- u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange)
- }
-
- // Explicitly disallow tag 0. This will ensure we flag an error
- // when decoding a buffer of all zeros. Without this code, we
- // would decode and skip an all-zero buffer of even length.
- // [0 0] is [tag=0/wiretype=varint varint-encoded-0].
- u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) {
- return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w)
- }, 0, "")
-
- // Set mask for required field check.
- u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here?
- for len(u.dense) <= tag {
- u.dense = append(u.dense, unmarshalFieldInfo{})
- }
- u.dense[tag] = i
- return
- }
- if u.sparse == nil {
- u.sparse = map[uint64]unmarshalFieldInfo{}
- }
- u.sparse[uint64(tag)] = i
-}
-
-// fieldUnmarshaler returns an unmarshaler for the given field.
-func fieldUnmarshaler(f *reflect.StructField) unmarshaler {
- if f.Type.Kind() == reflect.Map {
- return makeUnmarshalMap(f)
- }
- return typeUnmarshaler(f.Type, f.Tag.Get("protobuf"))
-}
-
-// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair.
-func typeUnmarshaler(t reflect.Type, tags string) unmarshaler {
- tagArray := strings.Split(tags, ",")
- encoding := tagArray[0]
- name := "unknown"
- for _, tag := range tagArray[3:] {
- if strings.HasPrefix(tag, "name=") {
- name = tag[5:]
- }
- }
-
- // Figure out packaging (pointer, slice, or both)
- slice := false
- pointer := false
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- slice = true
- t = t.Elem()
- }
- if t.Kind() == reflect.Ptr {
- pointer = true
- t = t.Elem()
- }
-
- // We'll never have both pointer and slice for basic types.
- if pointer && slice && t.Kind() != reflect.Struct {
- panic("both pointer and slice for basic type in " + t.Name())
- }
-
- switch t.Kind() {
- case reflect.Bool:
- if pointer {
- return unmarshalBoolPtr
- }
- if slice {
- return unmarshalBoolSlice
- }
- return unmarshalBoolValue
- case reflect.Int32:
- switch encoding {
- case "fixed32":
- if pointer {
- return unmarshalFixedS32Ptr
- }
- if slice {
- return unmarshalFixedS32Slice
- }
- return unmarshalFixedS32Value
- case "varint":
- // this could be int32 or enum
- if pointer {
- return unmarshalInt32Ptr
- }
- if slice {
- return unmarshalInt32Slice
- }
- return unmarshalInt32Value
- case "zigzag32":
- if pointer {
- return unmarshalSint32Ptr
- }
- if slice {
- return unmarshalSint32Slice
- }
- return unmarshalSint32Value
- }
- case reflect.Int64:
- switch encoding {
- case "fixed64":
- if pointer {
- return unmarshalFixedS64Ptr
- }
- if slice {
- return unmarshalFixedS64Slice
- }
- return unmarshalFixedS64Value
- case "varint":
- if pointer {
- return unmarshalInt64Ptr
- }
- if slice {
- return unmarshalInt64Slice
- }
- return unmarshalInt64Value
- case "zigzag64":
- if pointer {
- return unmarshalSint64Ptr
- }
- if slice {
- return unmarshalSint64Slice
- }
- return unmarshalSint64Value
- }
- case reflect.Uint32:
- switch encoding {
- case "fixed32":
- if pointer {
- return unmarshalFixed32Ptr
- }
- if slice {
- return unmarshalFixed32Slice
- }
- return unmarshalFixed32Value
- case "varint":
- if pointer {
- return unmarshalUint32Ptr
- }
- if slice {
- return unmarshalUint32Slice
- }
- return unmarshalUint32Value
- }
- case reflect.Uint64:
- switch encoding {
- case "fixed64":
- if pointer {
- return unmarshalFixed64Ptr
- }
- if slice {
- return unmarshalFixed64Slice
- }
- return unmarshalFixed64Value
- case "varint":
- if pointer {
- return unmarshalUint64Ptr
- }
- if slice {
- return unmarshalUint64Slice
- }
- return unmarshalUint64Value
- }
- case reflect.Float32:
- if pointer {
- return unmarshalFloat32Ptr
- }
- if slice {
- return unmarshalFloat32Slice
- }
- return unmarshalFloat32Value
- case reflect.Float64:
- if pointer {
- return unmarshalFloat64Ptr
- }
- if slice {
- return unmarshalFloat64Slice
- }
- return unmarshalFloat64Value
- case reflect.Map:
- panic("map type in typeUnmarshaler in " + t.Name())
- case reflect.Slice:
- if pointer {
- panic("bad pointer in slice case in " + t.Name())
- }
- if slice {
- return unmarshalBytesSlice
- }
- return unmarshalBytesValue
- case reflect.String:
- if pointer {
- return unmarshalStringPtr
- }
- if slice {
- return unmarshalStringSlice
- }
- return unmarshalStringValue
- case reflect.Struct:
- // message or group field
- if !pointer {
- panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding))
- }
- switch encoding {
- case "bytes":
- if slice {
- return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name)
- }
- return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name)
- case "group":
- if slice {
- return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name)
- }
- return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name)
- }
- }
- panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding))
-}
-
-// Below are all the unmarshalers for individual fields of various types.
-
-func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- *f.toInt64() = v
- return b, nil
-}
-
-func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- *f.toInt64Ptr() = &v
- return b, nil
-}
-
-func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- s := f.toInt64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- *f.toInt64() = v
- return b, nil
-}
-
-func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- *f.toInt64Ptr() = &v
- return b, nil
-}
-
-func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- s := f.toInt64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- *f.toUint64() = v
- return b, nil
-}
-
-func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- *f.toUint64Ptr() = &v
- return b, nil
-}
-
-func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- s := f.toUint64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- s := f.toUint64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- *f.toInt32() = v
- return b, nil
-}
-
-func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.setInt32Ptr(v)
- return b, nil
-}
-
-func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.appendInt32Slice(v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.appendInt32Slice(v)
- return b, nil
-}
-
-func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- *f.toInt32() = v
- return b, nil
-}
-
-func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.setInt32Ptr(v)
- return b, nil
-}
-
-func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.appendInt32Slice(v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.appendInt32Slice(v)
- return b, nil
-}
-
-func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- *f.toUint32() = v
- return b, nil
-}
-
-func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- *f.toUint32Ptr() = &v
- return b, nil
-}
-
-func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- s := f.toUint32Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- s := f.toUint32Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- *f.toUint64() = v
- return b[8:], nil
-}
-
-func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- *f.toUint64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- s := f.toUint64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- s := f.toUint64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- *f.toInt64() = v
- return b[8:], nil
-}
-
-func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- *f.toInt64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- s := f.toInt64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- *f.toUint32() = v
- return b[4:], nil
-}
-
-func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- *f.toUint32Ptr() = &v
- return b[4:], nil
-}
-
-func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- s := f.toUint32Slice()
- *s = append(*s, v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- s := f.toUint32Slice()
- *s = append(*s, v)
- return b[4:], nil
-}
-
-func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- *f.toInt32() = v
- return b[4:], nil
-}
-
-func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.setInt32Ptr(v)
- return b[4:], nil
-}
-
-func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.appendInt32Slice(v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.appendInt32Slice(v)
- return b[4:], nil
-}
-
-func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- // Note: any length varint is allowed, even though any sane
- // encoder will use one byte.
- // See https://github.com/golang/protobuf/issues/76
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- // TODO: check if x>1? Tests seem to indicate no.
- v := x != 0
- *f.toBool() = v
- return b[n:], nil
-}
-
-func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- *f.toBoolPtr() = &v
- return b[n:], nil
-}
-
-func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- s := f.toBoolSlice()
- *s = append(*s, v)
- b = b[n:]
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- s := f.toBoolSlice()
- *s = append(*s, v)
- return b[n:], nil
-}
-
-func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- *f.toFloat64() = v
- return b[8:], nil
-}
-
-func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- *f.toFloat64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- s := f.toFloat64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- s := f.toFloat64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- *f.toFloat32() = v
- return b[4:], nil
-}
-
-func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- *f.toFloat32Ptr() = &v
- return b[4:], nil
-}
-
-func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- s := f.toFloat32Slice()
- *s = append(*s, v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- s := f.toFloat32Slice()
- *s = append(*s, v)
- return b[4:], nil
-}
-
-func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- *f.toString() = v
- return b[x:], nil
-}
-
-func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- *f.toStringPtr() = &v
- return b[x:], nil
-}
-
-func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- if !utf8.ValidString(v) {
- return nil, errInvalidUTF8
- }
- s := f.toStringSlice()
- *s = append(*s, v)
- return b[x:], nil
-}
-
-var emptyBuf [0]byte
-
-func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- // The use of append here is a trick which avoids the zeroing
- // that would be required if we used a make/copy pair.
- // We append to emptyBuf instead of nil because we want
- // a non-nil result even when the length is 0.
- v := append(emptyBuf[:], b[:x]...)
- *f.toBytes() = v
- return b[x:], nil
-}
-
-func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := append(emptyBuf[:], b[:x]...)
- s := f.toBytesSlice()
- *s = append(*s, v)
- return b[x:], nil
-}
-
-func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- // First read the message field to see if something is there.
- // The semantics of multiple submessages are weird. Instead of
- // the last one winning (as it is for all other fields), multiple
- // submessages are merged.
- v := f.getPointer()
- if v.isNil() {
- v = valToPointer(reflect.New(sub.typ))
- f.setPointer(v)
- }
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- return b[x:], err
- }
-}
-
-func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := valToPointer(reflect.New(sub.typ))
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- f.appendPointer(v)
- return b[x:], err
- }
-}
-
-func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireStartGroup {
- return b, errInternalBadWireType
- }
- x, y := findEndGroup(b)
- if x < 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := f.getPointer()
- if v.isNil() {
- v = valToPointer(reflect.New(sub.typ))
- f.setPointer(v)
- }
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- return b[y:], err
- }
-}
-
-func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireStartGroup {
- return b, errInternalBadWireType
- }
- x, y := findEndGroup(b)
- if x < 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := valToPointer(reflect.New(sub.typ))
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- f.appendPointer(v)
- return b[y:], err
- }
-}
-
-func makeUnmarshalMap(f *reflect.StructField) unmarshaler {
- t := f.Type
- kt := t.Key()
- vt := t.Elem()
- unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key"))
- unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val"))
- return func(b []byte, f pointer, w int) ([]byte, error) {
- // The map entry is a submessage. Figure out how big it is.
- if w != WireBytes {
- return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes)
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- r := b[x:] // unused data to return
- b = b[:x] // data for map entry
-
- // Note: we could use #keys * #values ~= 200 functions
- // to do map decoding without reflection. Probably not worth it.
- // Maps will be somewhat slow. Oh well.
-
- // Read key and value from data.
- k := reflect.New(kt)
- v := reflect.New(vt)
- for len(b) > 0 {
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- wire := int(x) & 7
- b = b[n:]
-
- var err error
- switch x >> 3 {
- case 1:
- b, err = unmarshalKey(b, valToPointer(k), wire)
- case 2:
- b, err = unmarshalVal(b, valToPointer(v), wire)
- default:
- err = errInternalBadWireType // skip unknown tag
- }
-
- if err == nil {
- continue
- }
- if err != errInternalBadWireType {
- return nil, err
- }
-
- // Skip past unknown fields.
- b, err = skipField(b, wire)
- if err != nil {
- return nil, err
- }
- }
-
- // Get map, allocate if needed.
- m := f.asPointerTo(t).Elem() // an addressable map[K]T
- if m.IsNil() {
- m.Set(reflect.MakeMap(t))
- }
-
- // Insert into map.
- m.SetMapIndex(k.Elem(), v.Elem())
-
- return r, nil
- }
-}
-
-// makeUnmarshalOneof makes an unmarshaler for oneof fields.
-// for:
-// message Msg {
-// oneof F {
-// int64 X = 1;
-// float64 Y = 2;
-// }
-// }
-// typ is the type of the concrete entry for a oneof case (e.g. Msg_X).
-// ityp is the interface type of the oneof field (e.g. isMsg_F).
-// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64).
-// Note that this function will be called once for each case in the oneof.
-func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler {
- sf := typ.Field(0)
- field0 := toField(&sf)
- return func(b []byte, f pointer, w int) ([]byte, error) {
- // Allocate holder for value.
- v := reflect.New(typ)
-
- // Unmarshal data into holder.
- // We unmarshal into the first field of the holder object.
- var err error
- b, err = unmarshal(b, valToPointer(v).offset(field0), w)
- if err != nil {
- return nil, err
- }
-
- // Write pointer to holder into target field.
- f.asPointerTo(ityp).Elem().Set(v)
-
- return b, nil
- }
-}
-
-// Error used by decode internally.
-var errInternalBadWireType = errors.New("proto: internal error: bad wiretype")
-
-// skipField skips past a field of type wire and returns the remaining bytes.
-func skipField(b []byte, wire int) ([]byte, error) {
- switch wire {
- case WireVarint:
- _, k := decodeVarint(b)
- if k == 0 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[k:]
- case WireFixed32:
- if len(b) < 4 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[4:]
- case WireFixed64:
- if len(b) < 8 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[8:]
- case WireBytes:
- m, k := decodeVarint(b)
- if k == 0 || uint64(len(b)-k) < m {
- return b, io.ErrUnexpectedEOF
- }
- b = b[uint64(k)+m:]
- case WireStartGroup:
- _, i := findEndGroup(b)
- if i == -1 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[i:]
- default:
- return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire)
- }
- return b, nil
-}
-
-// findEndGroup finds the index of the next EndGroup tag.
-// Groups may be nested, so the "next" EndGroup tag is the first
-// unpaired EndGroup.
-// findEndGroup returns the indexes of the start and end of the EndGroup tag.
-// Returns (-1,-1) if it can't find one.
-func findEndGroup(b []byte) (int, int) {
- depth := 1
- i := 0
- for {
- x, n := decodeVarint(b[i:])
- if n == 0 {
- return -1, -1
- }
- j := i
- i += n
- switch x & 7 {
- case WireVarint:
- _, k := decodeVarint(b[i:])
- if k == 0 {
- return -1, -1
- }
- i += k
- case WireFixed32:
- if len(b)-4 < i {
- return -1, -1
- }
- i += 4
- case WireFixed64:
- if len(b)-8 < i {
- return -1, -1
- }
- i += 8
- case WireBytes:
- m, k := decodeVarint(b[i:])
- if k == 0 {
- return -1, -1
- }
- i += k
- if uint64(len(b)-i) < m {
- return -1, -1
- }
- i += int(m)
- case WireStartGroup:
- depth++
- case WireEndGroup:
- depth--
- if depth == 0 {
- return j, i
- }
- default:
- return -1, -1
- }
- }
-}
-
-// encodeVarint appends a varint-encoded integer to b and returns the result.
-func encodeVarint(b []byte, x uint64) []byte {
- for x >= 1<<7 {
- b = append(b, byte(x&0x7f|0x80))
- x >>= 7
- }
- return append(b, byte(x))
-}
-
-// decodeVarint reads a varint-encoded integer from b.
-// Returns the decoded integer and the number of bytes read.
-// If there is an error, it returns 0,0.
-func decodeVarint(b []byte) (uint64, int) {
- var x, y uint64
- if len(b) <= 0 {
- goto bad
- }
- x = uint64(b[0])
- if x < 0x80 {
- return x, 1
- }
- x -= 0x80
-
- if len(b) <= 1 {
- goto bad
- }
- y = uint64(b[1])
- x += y << 7
- if y < 0x80 {
- return x, 2
- }
- x -= 0x80 << 7
-
- if len(b) <= 2 {
- goto bad
- }
- y = uint64(b[2])
- x += y << 14
- if y < 0x80 {
- return x, 3
- }
- x -= 0x80 << 14
-
- if len(b) <= 3 {
- goto bad
- }
- y = uint64(b[3])
- x += y << 21
- if y < 0x80 {
- return x, 4
- }
- x -= 0x80 << 21
-
- if len(b) <= 4 {
- goto bad
- }
- y = uint64(b[4])
- x += y << 28
- if y < 0x80 {
- return x, 5
- }
- x -= 0x80 << 28
-
- if len(b) <= 5 {
- goto bad
- }
- y = uint64(b[5])
- x += y << 35
- if y < 0x80 {
- return x, 6
- }
- x -= 0x80 << 35
-
- if len(b) <= 6 {
- goto bad
- }
- y = uint64(b[6])
- x += y << 42
- if y < 0x80 {
- return x, 7
- }
- x -= 0x80 << 42
-
- if len(b) <= 7 {
- goto bad
- }
- y = uint64(b[7])
- x += y << 49
- if y < 0x80 {
- return x, 8
- }
- x -= 0x80 << 49
-
- if len(b) <= 8 {
- goto bad
- }
- y = uint64(b[8])
- x += y << 56
- if y < 0x80 {
- return x, 9
- }
- x -= 0x80 << 56
-
- if len(b) <= 9 {
- goto bad
- }
- y = uint64(b[9])
- x += y << 63
- if y < 2 {
- return x, 10
- }
-
-bad:
- return 0, 0
-}
diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go
deleted file mode 100644
index 2205fdaad..000000000
--- a/vendor/github.com/golang/protobuf/proto/text.go
+++ /dev/null
@@ -1,843 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-// Functions for writing the text protocol buffer format.
-
-import (
- "bufio"
- "bytes"
- "encoding"
- "errors"
- "fmt"
- "io"
- "log"
- "math"
- "reflect"
- "sort"
- "strings"
-)
-
-var (
- newline = []byte("\n")
- spaces = []byte(" ")
- endBraceNewline = []byte("}\n")
- backslashN = []byte{'\\', 'n'}
- backslashR = []byte{'\\', 'r'}
- backslashT = []byte{'\\', 't'}
- backslashDQ = []byte{'\\', '"'}
- backslashBS = []byte{'\\', '\\'}
- posInf = []byte("inf")
- negInf = []byte("-inf")
- nan = []byte("nan")
-)
-
-type writer interface {
- io.Writer
- WriteByte(byte) error
-}
-
-// textWriter is an io.Writer that tracks its indentation level.
-type textWriter struct {
- ind int
- complete bool // if the current position is a complete line
- compact bool // whether to write out as a one-liner
- w writer
-}
-
-func (w *textWriter) WriteString(s string) (n int, err error) {
- if !strings.Contains(s, "\n") {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- w.complete = false
- return io.WriteString(w.w, s)
- }
- // WriteString is typically called without newlines, so this
- // codepath and its copy are rare. We copy to avoid
- // duplicating all of Write's logic here.
- return w.Write([]byte(s))
-}
-
-func (w *textWriter) Write(p []byte) (n int, err error) {
- newlines := bytes.Count(p, newline)
- if newlines == 0 {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- n, err = w.w.Write(p)
- w.complete = false
- return n, err
- }
-
- frags := bytes.SplitN(p, newline, newlines+1)
- if w.compact {
- for i, frag := range frags {
- if i > 0 {
- if err := w.w.WriteByte(' '); err != nil {
- return n, err
- }
- n++
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- }
- return n, nil
- }
-
- for i, frag := range frags {
- if w.complete {
- w.writeIndent()
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- if i+1 < len(frags) {
- if err := w.w.WriteByte('\n'); err != nil {
- return n, err
- }
- n++
- }
- }
- w.complete = len(frags[len(frags)-1]) == 0
- return n, nil
-}
-
-func (w *textWriter) WriteByte(c byte) error {
- if w.compact && c == '\n' {
- c = ' '
- }
- if !w.compact && w.complete {
- w.writeIndent()
- }
- err := w.w.WriteByte(c)
- w.complete = c == '\n'
- return err
-}
-
-func (w *textWriter) indent() { w.ind++ }
-
-func (w *textWriter) unindent() {
- if w.ind == 0 {
- log.Print("proto: textWriter unindented too far")
- return
- }
- w.ind--
-}
-
-func writeName(w *textWriter, props *Properties) error {
- if _, err := w.WriteString(props.OrigName); err != nil {
- return err
- }
- if props.Wire != "group" {
- return w.WriteByte(':')
- }
- return nil
-}
-
-func requiresQuotes(u string) bool {
- // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
- for _, ch := range u {
- switch {
- case ch == '.' || ch == '/' || ch == '_':
- continue
- case '0' <= ch && ch <= '9':
- continue
- case 'A' <= ch && ch <= 'Z':
- continue
- case 'a' <= ch && ch <= 'z':
- continue
- default:
- return true
- }
- }
- return false
-}
-
-// isAny reports whether sv is a google.protobuf.Any message
-func isAny(sv reflect.Value) bool {
- type wkt interface {
- XXX_WellKnownType() string
- }
- t, ok := sv.Addr().Interface().(wkt)
- return ok && t.XXX_WellKnownType() == "Any"
-}
-
-// writeProto3Any writes an expanded google.protobuf.Any message.
-//
-// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
-// required messages are not linked in).
-//
-// It returns (true, error) when sv was written in expanded format or an error
-// was encountered.
-func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
- turl := sv.FieldByName("TypeUrl")
- val := sv.FieldByName("Value")
- if !turl.IsValid() || !val.IsValid() {
- return true, errors.New("proto: invalid google.protobuf.Any message")
- }
-
- b, ok := val.Interface().([]byte)
- if !ok {
- return true, errors.New("proto: invalid google.protobuf.Any message")
- }
-
- parts := strings.Split(turl.String(), "/")
- mt := MessageType(parts[len(parts)-1])
- if mt == nil {
- return false, nil
- }
- m := reflect.New(mt.Elem())
- if err := Unmarshal(b, m.Interface().(Message)); err != nil {
- return false, nil
- }
- w.Write([]byte("["))
- u := turl.String()
- if requiresQuotes(u) {
- writeString(w, u)
- } else {
- w.Write([]byte(u))
- }
- if w.compact {
- w.Write([]byte("]:<"))
- } else {
- w.Write([]byte("]: <\n"))
- w.ind++
- }
- if err := tm.writeStruct(w, m.Elem()); err != nil {
- return true, err
- }
- if w.compact {
- w.Write([]byte("> "))
- } else {
- w.ind--
- w.Write([]byte(">\n"))
- }
- return true, nil
-}
-
-func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
- if tm.ExpandAny && isAny(sv) {
- if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
- return err
- }
- }
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < sv.NumField(); i++ {
- fv := sv.Field(i)
- props := sprops.Prop[i]
- name := st.Field(i).Name
-
- if name == "XXX_NoUnkeyedLiteral" {
- continue
- }
-
- if strings.HasPrefix(name, "XXX_") {
- // There are two XXX_ fields:
- // XXX_unrecognized []byte
- // XXX_extensions map[int32]proto.Extension
- // The first is handled here;
- // the second is handled at the bottom of this function.
- if name == "XXX_unrecognized" && !fv.IsNil() {
- if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Ptr && fv.IsNil() {
- // Field not filled in. This could be an optional field or
- // a required field that wasn't filled in. Either way, there
- // isn't anything we can show for it.
- continue
- }
- if fv.Kind() == reflect.Slice && fv.IsNil() {
- // Repeated field that is empty, or a bytes field that is unused.
- continue
- }
-
- if props.Repeated && fv.Kind() == reflect.Slice {
- // Repeated field.
- for j := 0; j < fv.Len(); j++ {
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- v := fv.Index(j)
- if v.Kind() == reflect.Ptr && v.IsNil() {
- // A nil message in a repeated field is not valid,
- // but we can handle that more gracefully than panicking.
- if _, err := w.Write([]byte("\n")); err != nil {
- return err
- }
- continue
- }
- if err := tm.writeAny(w, v, props); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Map {
- // Map fields are rendered as a repeated struct with key/value fields.
- keys := fv.MapKeys()
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
- val := fv.MapIndex(key)
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- // open struct
- if err := w.WriteByte('<'); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- // key
- if _, err := w.WriteString("key:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- // nil values aren't legal, but we can avoid panicking because of them.
- if val.Kind() != reflect.Ptr || !val.IsNil() {
- // value
- if _, err := w.WriteString("value:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, val, props.mvalprop); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- // close struct
- w.unindent()
- if err := w.WriteByte('>'); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
- // empty bytes field
- continue
- }
- if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
- // proto3 non-repeated scalar field; skip if zero value
- if isProto3Zero(fv) {
- continue
- }
- }
-
- if fv.Kind() == reflect.Interface {
- // Check if it is a oneof.
- if st.Field(i).Tag.Get("protobuf_oneof") != "" {
- // fv is nil, or holds a pointer to generated struct.
- // That generated struct has exactly one field,
- // which has a protobuf struct tag.
- if fv.IsNil() {
- continue
- }
- inner := fv.Elem().Elem() // interface -> *T -> T
- tag := inner.Type().Field(0).Tag.Get("protobuf")
- props = new(Properties) // Overwrite the outer props var, but not its pointee.
- props.Parse(tag)
- // Write the value in the oneof, not the oneof itself.
- fv = inner.Field(0)
-
- // Special case to cope with malformed messages gracefully:
- // If the value in the oneof is a nil pointer, don't panic
- // in writeAny.
- if fv.Kind() == reflect.Ptr && fv.IsNil() {
- // Use errors.New so writeAny won't render quotes.
- msg := errors.New("/* nil */")
- fv = reflect.ValueOf(&msg).Elem()
- }
- }
- }
-
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
-
- // Enums have a String method, so writeAny will work fine.
- if err := tm.writeAny(w, fv, props); err != nil {
- return err
- }
-
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
-
- // Extensions (the XXX_extensions field).
- pv := sv.Addr()
- if _, err := extendable(pv.Interface()); err == nil {
- if err := tm.writeExtensions(w, pv); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// writeAny writes an arbitrary field.
-func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
- v = reflect.Indirect(v)
-
- // Floats have special cases.
- if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
- x := v.Float()
- var b []byte
- switch {
- case math.IsInf(x, 1):
- b = posInf
- case math.IsInf(x, -1):
- b = negInf
- case math.IsNaN(x):
- b = nan
- }
- if b != nil {
- _, err := w.Write(b)
- return err
- }
- // Other values are handled below.
- }
-
- // We don't attempt to serialise every possible value type; only those
- // that can occur in protocol buffers.
- switch v.Kind() {
- case reflect.Slice:
- // Should only be a []byte; repeated fields are handled in writeStruct.
- if err := writeString(w, string(v.Bytes())); err != nil {
- return err
- }
- case reflect.String:
- if err := writeString(w, v.String()); err != nil {
- return err
- }
- case reflect.Struct:
- // Required/optional group/message.
- var bra, ket byte = '<', '>'
- if props != nil && props.Wire == "group" {
- bra, ket = '{', '}'
- }
- if err := w.WriteByte(bra); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- if v.CanAddr() {
- // Calling v.Interface on a struct causes the reflect package to
- // copy the entire struct. This is racy with the new Marshaler
- // since we atomically update the XXX_sizecache.
- //
- // Thus, we retrieve a pointer to the struct if possible to avoid
- // a race since v.Interface on the pointer doesn't copy the struct.
- //
- // If v is not addressable, then we are not worried about a race
- // since it implies that the binary Marshaler cannot possibly be
- // mutating this value.
- v = v.Addr()
- }
- if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
- text, err := etm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = w.Write(text); err != nil {
- return err
- }
- } else {
- if v.Kind() == reflect.Ptr {
- v = v.Elem()
- }
- if err := tm.writeStruct(w, v); err != nil {
- return err
- }
- }
- w.unindent()
- if err := w.WriteByte(ket); err != nil {
- return err
- }
- default:
- _, err := fmt.Fprint(w, v.Interface())
- return err
- }
- return nil
-}
-
-// equivalent to C's isprint.
-func isprint(c byte) bool {
- return c >= 0x20 && c < 0x7f
-}
-
-// writeString writes a string in the protocol buffer text format.
-// It is similar to strconv.Quote except we don't use Go escape sequences,
-// we treat the string as a byte sequence, and we use octal escapes.
-// These differences are to maintain interoperability with the other
-// languages' implementations of the text format.
-func writeString(w *textWriter, s string) error {
- // use WriteByte here to get any needed indent
- if err := w.WriteByte('"'); err != nil {
- return err
- }
- // Loop over the bytes, not the runes.
- for i := 0; i < len(s); i++ {
- var err error
- // Divergence from C++: we don't escape apostrophes.
- // There's no need to escape them, and the C++ parser
- // copes with a naked apostrophe.
- switch c := s[i]; c {
- case '\n':
- _, err = w.w.Write(backslashN)
- case '\r':
- _, err = w.w.Write(backslashR)
- case '\t':
- _, err = w.w.Write(backslashT)
- case '"':
- _, err = w.w.Write(backslashDQ)
- case '\\':
- _, err = w.w.Write(backslashBS)
- default:
- if isprint(c) {
- err = w.w.WriteByte(c)
- } else {
- _, err = fmt.Fprintf(w.w, "\\%03o", c)
- }
- }
- if err != nil {
- return err
- }
- }
- return w.WriteByte('"')
-}
-
-func writeUnknownStruct(w *textWriter, data []byte) (err error) {
- if !w.compact {
- if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
- return err
- }
- }
- b := NewBuffer(data)
- for b.index < len(b.buf) {
- x, err := b.DecodeVarint()
- if err != nil {
- _, err := fmt.Fprintf(w, "/* %v */\n", err)
- return err
- }
- wire, tag := x&7, x>>3
- if wire == WireEndGroup {
- w.unindent()
- if _, err := w.Write(endBraceNewline); err != nil {
- return err
- }
- continue
- }
- if _, err := fmt.Fprint(w, tag); err != nil {
- return err
- }
- if wire != WireStartGroup {
- if err := w.WriteByte(':'); err != nil {
- return err
- }
- }
- if !w.compact || wire == WireStartGroup {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- switch wire {
- case WireBytes:
- buf, e := b.DecodeRawBytes(false)
- if e == nil {
- _, err = fmt.Fprintf(w, "%q", buf)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", e)
- }
- case WireFixed32:
- x, err = b.DecodeFixed32()
- err = writeUnknownInt(w, x, err)
- case WireFixed64:
- x, err = b.DecodeFixed64()
- err = writeUnknownInt(w, x, err)
- case WireStartGroup:
- err = w.WriteByte('{')
- w.indent()
- case WireVarint:
- x, err = b.DecodeVarint()
- err = writeUnknownInt(w, x, err)
- default:
- _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
- }
- if err != nil {
- return err
- }
- if err = w.WriteByte('\n'); err != nil {
- return err
- }
- }
- return nil
-}
-
-func writeUnknownInt(w *textWriter, x uint64, err error) error {
- if err == nil {
- _, err = fmt.Fprint(w, x)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", err)
- }
- return err
-}
-
-type int32Slice []int32
-
-func (s int32Slice) Len() int { return len(s) }
-func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
-func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-
-// writeExtensions writes all the extensions in pv.
-// pv is assumed to be a pointer to a protocol message struct that is extendable.
-func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
- emap := extensionMaps[pv.Type().Elem()]
- ep, _ := extendable(pv.Interface())
-
- // Order the extensions by ID.
- // This isn't strictly necessary, but it will give us
- // canonical output, which will also make testing easier.
- m, mu := ep.extensionsRead()
- if m == nil {
- return nil
- }
- mu.Lock()
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids))
- mu.Unlock()
-
- for _, extNum := range ids {
- ext := m[extNum]
- var desc *ExtensionDesc
- if emap != nil {
- desc = emap[extNum]
- }
- if desc == nil {
- // Unknown extension.
- if err := writeUnknownStruct(w, ext.enc); err != nil {
- return err
- }
- continue
- }
-
- pb, err := GetExtension(ep, desc)
- if err != nil {
- return fmt.Errorf("failed getting extension: %v", err)
- }
-
- // Repeated extensions will appear as a slice.
- if !desc.repeated() {
- if err := tm.writeExtension(w, desc.Name, pb); err != nil {
- return err
- }
- } else {
- v := reflect.ValueOf(pb)
- for i := 0; i < v.Len(); i++ {
- if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
- return err
- }
- }
- }
- }
- return nil
-}
-
-func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
- if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- return nil
-}
-
-func (w *textWriter) writeIndent() {
- if !w.complete {
- return
- }
- remain := w.ind * 2
- for remain > 0 {
- n := remain
- if n > len(spaces) {
- n = len(spaces)
- }
- w.w.Write(spaces[:n])
- remain -= n
- }
- w.complete = false
-}
-
-// TextMarshaler is a configurable text format marshaler.
-type TextMarshaler struct {
- Compact bool // use compact text format (one line).
- ExpandAny bool // expand google.protobuf.Any messages of known types
-}
-
-// Marshal writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
- val := reflect.ValueOf(pb)
- if pb == nil || val.IsNil() {
- w.Write([]byte(""))
- return nil
- }
- var bw *bufio.Writer
- ww, ok := w.(writer)
- if !ok {
- bw = bufio.NewWriter(w)
- ww = bw
- }
- aw := &textWriter{
- w: ww,
- complete: true,
- compact: tm.Compact,
- }
-
- if etm, ok := pb.(encoding.TextMarshaler); ok {
- text, err := etm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = aw.Write(text); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
- }
- // Dereference the received pointer so we don't have outer < and >.
- v := reflect.Indirect(val)
- if err := tm.writeStruct(aw, v); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
-}
-
-// Text is the same as Marshal, but returns the string directly.
-func (tm *TextMarshaler) Text(pb Message) string {
- var buf bytes.Buffer
- tm.Marshal(&buf, pb)
- return buf.String()
-}
-
-var (
- defaultTextMarshaler = TextMarshaler{}
- compactTextMarshaler = TextMarshaler{Compact: true}
-)
-
-// TODO: consider removing some of the Marshal functions below.
-
-// MarshalText writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
-
-// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
-
-// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
-
-// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/golang/protobuf/proto/text_decode.go b/vendor/github.com/golang/protobuf/proto/text_decode.go
new file mode 100644
index 000000000..47eb3e445
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/text_decode.go
@@ -0,0 +1,801 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto
+
+import (
+ "encoding"
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "google.golang.org/protobuf/encoding/prototext"
+ protoV2 "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+)
+
+const wrapTextUnmarshalV2 = false
+
+// ParseError is returned by UnmarshalText.
+type ParseError struct {
+ Message string
+
+ // Deprecated: Do not use.
+ Line, Offset int
+}
+
+func (e *ParseError) Error() string {
+ if wrapTextUnmarshalV2 {
+ return e.Message
+ }
+ if e.Line == 1 {
+ return fmt.Sprintf("line 1.%d: %v", e.Offset, e.Message)
+ }
+ return fmt.Sprintf("line %d: %v", e.Line, e.Message)
+}
+
+// UnmarshalText parses a proto text formatted string into m.
+func UnmarshalText(s string, m Message) error {
+ if u, ok := m.(encoding.TextUnmarshaler); ok {
+ return u.UnmarshalText([]byte(s))
+ }
+
+ m.Reset()
+ mi := MessageV2(m)
+
+ if wrapTextUnmarshalV2 {
+ err := prototext.UnmarshalOptions{
+ AllowPartial: true,
+ }.Unmarshal([]byte(s), mi)
+ if err != nil {
+ return &ParseError{Message: err.Error()}
+ }
+ return checkRequiredNotSet(mi)
+ } else {
+ if err := newTextParser(s).unmarshalMessage(mi.ProtoReflect(), ""); err != nil {
+ return err
+ }
+ return checkRequiredNotSet(mi)
+ }
+}
+
+type textParser struct {
+ s string // remaining input
+ done bool // whether the parsing is finished (success or error)
+ backed bool // whether back() was called
+ offset, line int
+ cur token
+}
+
+type token struct {
+ value string
+ err *ParseError
+ line int // line number
+ offset int // byte number from start of input, not start of line
+ unquoted string // the unquoted version of value, if it was a quoted string
+}
+
+func newTextParser(s string) *textParser {
+ p := new(textParser)
+ p.s = s
+ p.line = 1
+ p.cur.line = 1
+ return p
+}
+
+func (p *textParser) unmarshalMessage(m protoreflect.Message, terminator string) (err error) {
+ md := m.Descriptor()
+ fds := md.Fields()
+
+ // A struct is a sequence of "name: value", terminated by one of
+ // '>' or '}', or the end of the input. A name may also be
+ // "[extension]" or "[type/url]".
+ //
+ // The whole struct can also be an expanded Any message, like:
+ // [type/url] < ... struct contents ... >
+ seen := make(map[protoreflect.FieldNumber]bool)
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ if tok.value == "[" {
+ if err := p.unmarshalExtensionOrAny(m, seen); err != nil {
+ return err
+ }
+ continue
+ }
+
+ // This is a normal, non-extension field.
+ name := protoreflect.Name(tok.value)
+ fd := fds.ByName(name)
+ switch {
+ case fd == nil:
+ gd := fds.ByName(protoreflect.Name(strings.ToLower(string(name))))
+ if gd != nil && gd.Kind() == protoreflect.GroupKind && gd.Message().Name() == name {
+ fd = gd
+ }
+ case fd.Kind() == protoreflect.GroupKind && fd.Message().Name() != name:
+ fd = nil
+ case fd.IsWeak() && fd.Message().IsPlaceholder():
+ fd = nil
+ }
+ if fd == nil {
+ typeName := string(md.FullName())
+ if m, ok := m.Interface().(Message); ok {
+ t := reflect.TypeOf(m)
+ if t.Kind() == reflect.Ptr {
+ typeName = t.Elem().String()
+ }
+ }
+ return p.errorf("unknown field name %q in %v", name, typeName)
+ }
+ if od := fd.ContainingOneof(); od != nil && m.WhichOneof(od) != nil {
+ return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, od.Name())
+ }
+ if fd.Cardinality() != protoreflect.Repeated && seen[fd.Number()] {
+ return p.errorf("non-repeated field %q was repeated", fd.Name())
+ }
+ seen[fd.Number()] = true
+
+ // Consume any colon.
+ if err := p.checkForColon(fd); err != nil {
+ return err
+ }
+
+ // Parse into the field.
+ v := m.Get(fd)
+ if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) {
+ v = m.Mutable(fd)
+ }
+ if v, err = p.unmarshalValue(v, fd); err != nil {
+ return err
+ }
+ m.Set(fd, v)
+
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (p *textParser) unmarshalExtensionOrAny(m protoreflect.Message, seen map[protoreflect.FieldNumber]bool) error {
+ name, err := p.consumeExtensionOrAnyName()
+ if err != nil {
+ return err
+ }
+
+ // If it contains a slash, it's an Any type URL.
+ if slashIdx := strings.LastIndex(name, "/"); slashIdx >= 0 {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ // consume an optional colon
+ if tok.value == ":" {
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ }
+
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+
+ mt, err := protoregistry.GlobalTypes.FindMessageByURL(name)
+ if err != nil {
+ return p.errorf("unrecognized message %q in google.protobuf.Any", name[slashIdx+len("/"):])
+ }
+ m2 := mt.New()
+ if err := p.unmarshalMessage(m2, terminator); err != nil {
+ return err
+ }
+ b, err := protoV2.Marshal(m2.Interface())
+ if err != nil {
+ return p.errorf("failed to marshal message of type %q: %v", name[slashIdx+len("/"):], err)
+ }
+
+ urlFD := m.Descriptor().Fields().ByName("type_url")
+ valFD := m.Descriptor().Fields().ByName("value")
+ if seen[urlFD.Number()] {
+ return p.errorf("Any message unpacked multiple times, or %q already set", urlFD.Name())
+ }
+ if seen[valFD.Number()] {
+ return p.errorf("Any message unpacked multiple times, or %q already set", valFD.Name())
+ }
+ m.Set(urlFD, protoreflect.ValueOfString(name))
+ m.Set(valFD, protoreflect.ValueOfBytes(b))
+ seen[urlFD.Number()] = true
+ seen[valFD.Number()] = true
+ return nil
+ }
+
+ xname := protoreflect.FullName(name)
+ xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname)
+ if xt == nil && isMessageSet(m.Descriptor()) {
+ xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension"))
+ }
+ if xt == nil {
+ return p.errorf("unrecognized extension %q", name)
+ }
+ fd := xt.TypeDescriptor()
+ if fd.ContainingMessage().FullName() != m.Descriptor().FullName() {
+ return p.errorf("extension field %q does not extend message %q", name, m.Descriptor().FullName())
+ }
+
+ if err := p.checkForColon(fd); err != nil {
+ return err
+ }
+
+ v := m.Get(fd)
+ if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) {
+ v = m.Mutable(fd)
+ }
+ v, err = p.unmarshalValue(v, fd)
+ if err != nil {
+ return err
+ }
+ m.Set(fd, v)
+ return p.consumeOptionalSeparator()
+}
+
+func (p *textParser) unmarshalValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return v, tok.err
+ }
+ if tok.value == "" {
+ return v, p.errorf("unexpected EOF")
+ }
+
+ switch {
+ case fd.IsList():
+ lv := v.List()
+ var err error
+ if tok.value == "[" {
+ // Repeated field with list notation, like [1,2,3].
+ for {
+ vv := lv.NewElement()
+ vv, err = p.unmarshalSingularValue(vv, fd)
+ if err != nil {
+ return v, err
+ }
+ lv.Append(vv)
+
+ tok := p.next()
+ if tok.err != nil {
+ return v, tok.err
+ }
+ if tok.value == "]" {
+ break
+ }
+ if tok.value != "," {
+ return v, p.errorf("Expected ']' or ',' found %q", tok.value)
+ }
+ }
+ return v, nil
+ }
+
+ // One value of the repeated field.
+ p.back()
+ vv := lv.NewElement()
+ vv, err = p.unmarshalSingularValue(vv, fd)
+ if err != nil {
+ return v, err
+ }
+ lv.Append(vv)
+ return v, nil
+ case fd.IsMap():
+ // The map entry should be this sequence of tokens:
+ // < key : KEY value : VALUE >
+ // However, implementations may omit key or value, and technically
+ // we should support them in any order.
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return v, p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+
+ keyFD := fd.MapKey()
+ valFD := fd.MapValue()
+
+ mv := v.Map()
+ kv := keyFD.Default()
+ vv := mv.NewValue()
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return v, tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ var err error
+ switch tok.value {
+ case "key":
+ if err := p.consumeToken(":"); err != nil {
+ return v, err
+ }
+ if kv, err = p.unmarshalSingularValue(kv, keyFD); err != nil {
+ return v, err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return v, err
+ }
+ case "value":
+ if err := p.checkForColon(valFD); err != nil {
+ return v, err
+ }
+ if vv, err = p.unmarshalSingularValue(vv, valFD); err != nil {
+ return v, err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return v, err
+ }
+ default:
+ p.back()
+ return v, p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
+ }
+ }
+ mv.Set(kv.MapKey(), vv)
+ return v, nil
+ default:
+ p.back()
+ return p.unmarshalSingularValue(v, fd)
+ }
+}
+
+func (p *textParser) unmarshalSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return v, tok.err
+ }
+ if tok.value == "" {
+ return v, p.errorf("unexpected EOF")
+ }
+
+ switch fd.Kind() {
+ case protoreflect.BoolKind:
+ switch tok.value {
+ case "true", "1", "t", "True":
+ return protoreflect.ValueOfBool(true), nil
+ case "false", "0", "f", "False":
+ return protoreflect.ValueOfBool(false), nil
+ }
+ case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
+ if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
+ return protoreflect.ValueOfInt32(int32(x)), nil
+ }
+
+ // The C++ parser accepts large positive hex numbers that uses
+ // two's complement arithmetic to represent negative numbers.
+ // This feature is here for backwards compatibility with C++.
+ if strings.HasPrefix(tok.value, "0x") {
+ if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
+ return protoreflect.ValueOfInt32(int32(-(int64(^x) + 1))), nil
+ }
+ }
+ case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
+ if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
+ return protoreflect.ValueOfInt64(int64(x)), nil
+ }
+
+ // The C++ parser accepts large positive hex numbers that uses
+ // two's complement arithmetic to represent negative numbers.
+ // This feature is here for backwards compatibility with C++.
+ if strings.HasPrefix(tok.value, "0x") {
+ if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
+ return protoreflect.ValueOfInt64(int64(-(int64(^x) + 1))), nil
+ }
+ }
+ case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
+ if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
+ return protoreflect.ValueOfUint32(uint32(x)), nil
+ }
+ case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
+ if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
+ return protoreflect.ValueOfUint64(uint64(x)), nil
+ }
+ case protoreflect.FloatKind:
+ // Ignore 'f' for compatibility with output generated by C++,
+ // but don't remove 'f' when the value is "-inf" or "inf".
+ v := tok.value
+ if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" {
+ v = v[:len(v)-len("f")]
+ }
+ if x, err := strconv.ParseFloat(v, 32); err == nil {
+ return protoreflect.ValueOfFloat32(float32(x)), nil
+ }
+ case protoreflect.DoubleKind:
+ // Ignore 'f' for compatibility with output generated by C++,
+ // but don't remove 'f' when the value is "-inf" or "inf".
+ v := tok.value
+ if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" {
+ v = v[:len(v)-len("f")]
+ }
+ if x, err := strconv.ParseFloat(v, 64); err == nil {
+ return protoreflect.ValueOfFloat64(float64(x)), nil
+ }
+ case protoreflect.StringKind:
+ if isQuote(tok.value[0]) {
+ return protoreflect.ValueOfString(tok.unquoted), nil
+ }
+ case protoreflect.BytesKind:
+ if isQuote(tok.value[0]) {
+ return protoreflect.ValueOfBytes([]byte(tok.unquoted)), nil
+ }
+ case protoreflect.EnumKind:
+ if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
+ return protoreflect.ValueOfEnum(protoreflect.EnumNumber(x)), nil
+ }
+ vd := fd.Enum().Values().ByName(protoreflect.Name(tok.value))
+ if vd != nil {
+ return protoreflect.ValueOfEnum(vd.Number()), nil
+ }
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ var terminator string
+ switch tok.value {
+ case "{":
+ terminator = "}"
+ case "<":
+ terminator = ">"
+ default:
+ return v, p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ err := p.unmarshalMessage(v.Message(), terminator)
+ return v, err
+ default:
+ panic(fmt.Sprintf("invalid kind %v", fd.Kind()))
+ }
+ return v, p.errorf("invalid %v: %v", fd.Kind(), tok.value)
+}
+
+// Consume a ':' from the input stream (if the next token is a colon),
+// returning an error if a colon is needed but not present.
+func (p *textParser) checkForColon(fd protoreflect.FieldDescriptor) *ParseError {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ":" {
+ if fd.Message() == nil {
+ return p.errorf("expected ':', found %q", tok.value)
+ }
+ p.back()
+ }
+ return nil
+}
+
+// consumeExtensionOrAnyName consumes an extension name or an Any type URL and
+// the following ']'. It returns the name or URL consumed.
+func (p *textParser) consumeExtensionOrAnyName() (string, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return "", tok.err
+ }
+
+ // If extension name or type url is quoted, it's a single token.
+ if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
+ name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
+ if err != nil {
+ return "", err
+ }
+ return name, p.consumeToken("]")
+ }
+
+ // Consume everything up to "]"
+ var parts []string
+ for tok.value != "]" {
+ parts = append(parts, tok.value)
+ tok = p.next()
+ if tok.err != nil {
+ return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
+ }
+ if p.done && tok.value != "]" {
+ return "", p.errorf("unclosed type_url or extension name")
+ }
+ }
+ return strings.Join(parts, ""), nil
+}
+
+// consumeOptionalSeparator consumes an optional semicolon or comma.
+// It is used in unmarshalMessage to provide backward compatibility.
+func (p *textParser) consumeOptionalSeparator() error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ";" && tok.value != "," {
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
+ pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
+ p.cur.err = pe
+ p.done = true
+ return pe
+}
+
+func (p *textParser) skipWhitespace() {
+ i := 0
+ for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
+ if p.s[i] == '#' {
+ // comment; skip to end of line or input
+ for i < len(p.s) && p.s[i] != '\n' {
+ i++
+ }
+ if i == len(p.s) {
+ break
+ }
+ }
+ if p.s[i] == '\n' {
+ p.line++
+ }
+ i++
+ }
+ p.offset += i
+ p.s = p.s[i:len(p.s)]
+ if len(p.s) == 0 {
+ p.done = true
+ }
+}
+
+func (p *textParser) advance() {
+ // Skip whitespace
+ p.skipWhitespace()
+ if p.done {
+ return
+ }
+
+ // Start of non-whitespace
+ p.cur.err = nil
+ p.cur.offset, p.cur.line = p.offset, p.line
+ p.cur.unquoted = ""
+ switch p.s[0] {
+ case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
+ // Single symbol
+ p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
+ case '"', '\'':
+ // Quoted string
+ i := 1
+ for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
+ if p.s[i] == '\\' && i+1 < len(p.s) {
+ // skip escaped char
+ i++
+ }
+ i++
+ }
+ if i >= len(p.s) || p.s[i] != p.s[0] {
+ p.errorf("unmatched quote")
+ return
+ }
+ unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
+ if err != nil {
+ p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
+ return
+ }
+ p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
+ p.cur.unquoted = unq
+ default:
+ i := 0
+ for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
+ i++
+ }
+ if i == 0 {
+ p.errorf("unexpected byte %#x", p.s[0])
+ return
+ }
+ p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
+ }
+ p.offset += len(p.cur.value)
+}
+
+// Back off the parser by one token. Can only be done between calls to next().
+// It makes the next advance() a no-op.
+func (p *textParser) back() { p.backed = true }
+
+// Advances the parser and returns the new current token.
+func (p *textParser) next() *token {
+ if p.backed || p.done {
+ p.backed = false
+ return &p.cur
+ }
+ p.advance()
+ if p.done {
+ p.cur.value = ""
+ } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
+ // Look for multiple quoted strings separated by whitespace,
+ // and concatenate them.
+ cat := p.cur
+ for {
+ p.skipWhitespace()
+ if p.done || !isQuote(p.s[0]) {
+ break
+ }
+ p.advance()
+ if p.cur.err != nil {
+ return &p.cur
+ }
+ cat.value += " " + p.cur.value
+ cat.unquoted += p.cur.unquoted
+ }
+ p.done = false // parser may have seen EOF, but we want to return cat
+ p.cur = cat
+ }
+ return &p.cur
+}
+
+func (p *textParser) consumeToken(s string) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != s {
+ p.back()
+ return p.errorf("expected %q, found %q", s, tok.value)
+ }
+ return nil
+}
+
+var errBadUTF8 = errors.New("proto: bad UTF-8")
+
+func unquoteC(s string, quote rune) (string, error) {
+ // This is based on C++'s tokenizer.cc.
+ // Despite its name, this is *not* parsing C syntax.
+ // For instance, "\0" is an invalid quoted string.
+
+ // Avoid allocation in trivial cases.
+ simple := true
+ for _, r := range s {
+ if r == '\\' || r == quote {
+ simple = false
+ break
+ }
+ }
+ if simple {
+ return s, nil
+ }
+
+ buf := make([]byte, 0, 3*len(s)/2)
+ for len(s) > 0 {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", errBadUTF8
+ }
+ s = s[n:]
+ if r != '\\' {
+ if r < utf8.RuneSelf {
+ buf = append(buf, byte(r))
+ } else {
+ buf = append(buf, string(r)...)
+ }
+ continue
+ }
+
+ ch, tail, err := unescape(s)
+ if err != nil {
+ return "", err
+ }
+ buf = append(buf, ch...)
+ s = tail
+ }
+ return string(buf), nil
+}
+
+func unescape(s string) (ch string, tail string, err error) {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", "", errBadUTF8
+ }
+ s = s[n:]
+ switch r {
+ case 'a':
+ return "\a", s, nil
+ case 'b':
+ return "\b", s, nil
+ case 'f':
+ return "\f", s, nil
+ case 'n':
+ return "\n", s, nil
+ case 'r':
+ return "\r", s, nil
+ case 't':
+ return "\t", s, nil
+ case 'v':
+ return "\v", s, nil
+ case '?':
+ return "?", s, nil // trigraph workaround
+ case '\'', '"', '\\':
+ return string(r), s, nil
+ case '0', '1', '2', '3', '4', '5', '6', '7':
+ if len(s) < 2 {
+ return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
+ }
+ ss := string(r) + s[:2]
+ s = s[2:]
+ i, err := strconv.ParseUint(ss, 8, 8)
+ if err != nil {
+ return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
+ }
+ return string([]byte{byte(i)}), s, nil
+ case 'x', 'X', 'u', 'U':
+ var n int
+ switch r {
+ case 'x', 'X':
+ n = 2
+ case 'u':
+ n = 4
+ case 'U':
+ n = 8
+ }
+ if len(s) < n {
+ return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
+ }
+ ss := s[:n]
+ s = s[n:]
+ i, err := strconv.ParseUint(ss, 16, 64)
+ if err != nil {
+ return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
+ }
+ if r == 'x' || r == 'X' {
+ return string([]byte{byte(i)}), s, nil
+ }
+ if i > utf8.MaxRune {
+ return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
+ }
+ return string(rune(i)), s, nil
+ }
+ return "", "", fmt.Errorf(`unknown escape \%c`, r)
+}
+
+func isIdentOrNumberChar(c byte) bool {
+ switch {
+ case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
+ return true
+ case '0' <= c && c <= '9':
+ return true
+ }
+ switch c {
+ case '-', '+', '.', '_':
+ return true
+ }
+ return false
+}
+
+func isWhitespace(c byte) bool {
+ switch c {
+ case ' ', '\t', '\n', '\r':
+ return true
+ }
+ return false
+}
+
+func isQuote(c byte) bool {
+ switch c {
+ case '"', '\'':
+ return true
+ }
+ return false
+}
diff --git a/vendor/github.com/golang/protobuf/proto/text_encode.go b/vendor/github.com/golang/protobuf/proto/text_encode.go
new file mode 100644
index 000000000..a31134eeb
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/text_encode.go
@@ -0,0 +1,560 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto
+
+import (
+ "bytes"
+ "encoding"
+ "fmt"
+ "io"
+ "math"
+ "sort"
+ "strings"
+
+ "google.golang.org/protobuf/encoding/prototext"
+ "google.golang.org/protobuf/encoding/protowire"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+)
+
+const wrapTextMarshalV2 = false
+
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+ Compact bool // use compact text format (one line)
+ ExpandAny bool // expand google.protobuf.Any messages of known types
+}
+
+// Marshal writes the proto text format of m to w.
+func (tm *TextMarshaler) Marshal(w io.Writer, m Message) error {
+ b, err := tm.marshal(m)
+ if len(b) > 0 {
+ if _, err := w.Write(b); err != nil {
+ return err
+ }
+ }
+ return err
+}
+
+// Text returns a proto text formatted string of m.
+func (tm *TextMarshaler) Text(m Message) string {
+ b, _ := tm.marshal(m)
+ return string(b)
+}
+
+func (tm *TextMarshaler) marshal(m Message) ([]byte, error) {
+ mr := MessageReflect(m)
+ if mr == nil || !mr.IsValid() {
+ return []byte(""), nil
+ }
+
+ if wrapTextMarshalV2 {
+ if m, ok := m.(encoding.TextMarshaler); ok {
+ return m.MarshalText()
+ }
+
+ opts := prototext.MarshalOptions{
+ AllowPartial: true,
+ EmitUnknown: true,
+ }
+ if !tm.Compact {
+ opts.Indent = " "
+ }
+ if !tm.ExpandAny {
+ opts.Resolver = (*protoregistry.Types)(nil)
+ }
+ return opts.Marshal(mr.Interface())
+ } else {
+ w := &textWriter{
+ compact: tm.Compact,
+ expandAny: tm.ExpandAny,
+ complete: true,
+ }
+
+ if m, ok := m.(encoding.TextMarshaler); ok {
+ b, err := m.MarshalText()
+ if err != nil {
+ return nil, err
+ }
+ w.Write(b)
+ return w.buf, nil
+ }
+
+ err := w.writeMessage(mr)
+ return w.buf, err
+ }
+}
+
+var (
+ defaultTextMarshaler = TextMarshaler{}
+ compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// MarshalText writes the proto text format of m to w.
+func MarshalText(w io.Writer, m Message) error { return defaultTextMarshaler.Marshal(w, m) }
+
+// MarshalTextString returns a proto text formatted string of m.
+func MarshalTextString(m Message) string { return defaultTextMarshaler.Text(m) }
+
+// CompactText writes the compact proto text format of m to w.
+func CompactText(w io.Writer, m Message) error { return compactTextMarshaler.Marshal(w, m) }
+
+// CompactTextString returns a compact proto text formatted string of m.
+func CompactTextString(m Message) string { return compactTextMarshaler.Text(m) }
+
+var (
+ newline = []byte("\n")
+ endBraceNewline = []byte("}\n")
+ posInf = []byte("inf")
+ negInf = []byte("-inf")
+ nan = []byte("nan")
+)
+
+// textWriter is an io.Writer that tracks its indentation level.
+type textWriter struct {
+ compact bool // same as TextMarshaler.Compact
+ expandAny bool // same as TextMarshaler.ExpandAny
+ complete bool // whether the current position is a complete line
+ indent int // indentation level; never negative
+ buf []byte
+}
+
+func (w *textWriter) Write(p []byte) (n int, _ error) {
+ newlines := bytes.Count(p, newline)
+ if newlines == 0 {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ w.buf = append(w.buf, p...)
+ w.complete = false
+ return len(p), nil
+ }
+
+ frags := bytes.SplitN(p, newline, newlines+1)
+ if w.compact {
+ for i, frag := range frags {
+ if i > 0 {
+ w.buf = append(w.buf, ' ')
+ n++
+ }
+ w.buf = append(w.buf, frag...)
+ n += len(frag)
+ }
+ return n, nil
+ }
+
+ for i, frag := range frags {
+ if w.complete {
+ w.writeIndent()
+ }
+ w.buf = append(w.buf, frag...)
+ n += len(frag)
+ if i+1 < len(frags) {
+ w.buf = append(w.buf, '\n')
+ n++
+ }
+ }
+ w.complete = len(frags[len(frags)-1]) == 0
+ return n, nil
+}
+
+func (w *textWriter) WriteByte(c byte) error {
+ if w.compact && c == '\n' {
+ c = ' '
+ }
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ w.buf = append(w.buf, c)
+ w.complete = c == '\n'
+ return nil
+}
+
+func (w *textWriter) writeName(fd protoreflect.FieldDescriptor) {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ w.complete = false
+
+ if fd.Kind() != protoreflect.GroupKind {
+ w.buf = append(w.buf, fd.Name()...)
+ w.WriteByte(':')
+ } else {
+ // Use message type name for group field name.
+ w.buf = append(w.buf, fd.Message().Name()...)
+ }
+
+ if !w.compact {
+ w.WriteByte(' ')
+ }
+}
+
+func requiresQuotes(u string) bool {
+ // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
+ for _, ch := range u {
+ switch {
+ case ch == '.' || ch == '/' || ch == '_':
+ continue
+ case '0' <= ch && ch <= '9':
+ continue
+ case 'A' <= ch && ch <= 'Z':
+ continue
+ case 'a' <= ch && ch <= 'z':
+ continue
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// writeProto3Any writes an expanded google.protobuf.Any message.
+//
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
+// required messages are not linked in).
+//
+// It returns (true, error) when sv was written in expanded format or an error
+// was encountered.
+func (w *textWriter) writeProto3Any(m protoreflect.Message) (bool, error) {
+ md := m.Descriptor()
+ fdURL := md.Fields().ByName("type_url")
+ fdVal := md.Fields().ByName("value")
+
+ url := m.Get(fdURL).String()
+ mt, err := protoregistry.GlobalTypes.FindMessageByURL(url)
+ if err != nil {
+ return false, nil
+ }
+
+ b := m.Get(fdVal).Bytes()
+ m2 := mt.New()
+ if err := proto.Unmarshal(b, m2.Interface()); err != nil {
+ return false, nil
+ }
+ w.Write([]byte("["))
+ if requiresQuotes(url) {
+ w.writeQuotedString(url)
+ } else {
+ w.Write([]byte(url))
+ }
+ if w.compact {
+ w.Write([]byte("]:<"))
+ } else {
+ w.Write([]byte("]: <\n"))
+ w.indent++
+ }
+ if err := w.writeMessage(m2); err != nil {
+ return true, err
+ }
+ if w.compact {
+ w.Write([]byte("> "))
+ } else {
+ w.indent--
+ w.Write([]byte(">\n"))
+ }
+ return true, nil
+}
+
+func (w *textWriter) writeMessage(m protoreflect.Message) error {
+ md := m.Descriptor()
+ if w.expandAny && md.FullName() == "google.protobuf.Any" {
+ if canExpand, err := w.writeProto3Any(m); canExpand {
+ return err
+ }
+ }
+
+ fds := md.Fields()
+ for i := 0; i < fds.Len(); {
+ fd := fds.Get(i)
+ if od := fd.ContainingOneof(); od != nil {
+ fd = m.WhichOneof(od)
+ i += od.Fields().Len()
+ } else {
+ i++
+ }
+ if fd == nil || !m.Has(fd) {
+ continue
+ }
+
+ switch {
+ case fd.IsList():
+ lv := m.Get(fd).List()
+ for j := 0; j < lv.Len(); j++ {
+ w.writeName(fd)
+ v := lv.Get(j)
+ if err := w.writeSingularValue(v, fd); err != nil {
+ return err
+ }
+ w.WriteByte('\n')
+ }
+ case fd.IsMap():
+ kfd := fd.MapKey()
+ vfd := fd.MapValue()
+ mv := m.Get(fd).Map()
+
+ type entry struct{ key, val protoreflect.Value }
+ var entries []entry
+ mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
+ entries = append(entries, entry{k.Value(), v})
+ return true
+ })
+ sort.Slice(entries, func(i, j int) bool {
+ switch kfd.Kind() {
+ case protoreflect.BoolKind:
+ return !entries[i].key.Bool() && entries[j].key.Bool()
+ case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
+ return entries[i].key.Int() < entries[j].key.Int()
+ case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
+ return entries[i].key.Uint() < entries[j].key.Uint()
+ case protoreflect.StringKind:
+ return entries[i].key.String() < entries[j].key.String()
+ default:
+ panic("invalid kind")
+ }
+ })
+ for _, entry := range entries {
+ w.writeName(fd)
+ w.WriteByte('<')
+ if !w.compact {
+ w.WriteByte('\n')
+ }
+ w.indent++
+ w.writeName(kfd)
+ if err := w.writeSingularValue(entry.key, kfd); err != nil {
+ return err
+ }
+ w.WriteByte('\n')
+ w.writeName(vfd)
+ if err := w.writeSingularValue(entry.val, vfd); err != nil {
+ return err
+ }
+ w.WriteByte('\n')
+ w.indent--
+ w.WriteByte('>')
+ w.WriteByte('\n')
+ }
+ default:
+ w.writeName(fd)
+ if err := w.writeSingularValue(m.Get(fd), fd); err != nil {
+ return err
+ }
+ w.WriteByte('\n')
+ }
+ }
+
+ if b := m.GetUnknown(); len(b) > 0 {
+ w.writeUnknownFields(b)
+ }
+ return w.writeExtensions(m)
+}
+
+func (w *textWriter) writeSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) error {
+ switch fd.Kind() {
+ case protoreflect.FloatKind, protoreflect.DoubleKind:
+ switch vf := v.Float(); {
+ case math.IsInf(vf, +1):
+ w.Write(posInf)
+ case math.IsInf(vf, -1):
+ w.Write(negInf)
+ case math.IsNaN(vf):
+ w.Write(nan)
+ default:
+ fmt.Fprint(w, v.Interface())
+ }
+ case protoreflect.StringKind:
+ // NOTE: This does not validate UTF-8 for historical reasons.
+ w.writeQuotedString(string(v.String()))
+ case protoreflect.BytesKind:
+ w.writeQuotedString(string(v.Bytes()))
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ var bra, ket byte = '<', '>'
+ if fd.Kind() == protoreflect.GroupKind {
+ bra, ket = '{', '}'
+ }
+ w.WriteByte(bra)
+ if !w.compact {
+ w.WriteByte('\n')
+ }
+ w.indent++
+ m := v.Message()
+ if m2, ok := m.Interface().(encoding.TextMarshaler); ok {
+ b, err := m2.MarshalText()
+ if err != nil {
+ return err
+ }
+ w.Write(b)
+ } else {
+ w.writeMessage(m)
+ }
+ w.indent--
+ w.WriteByte(ket)
+ case protoreflect.EnumKind:
+ if ev := fd.Enum().Values().ByNumber(v.Enum()); ev != nil {
+ fmt.Fprint(w, ev.Name())
+ } else {
+ fmt.Fprint(w, v.Enum())
+ }
+ default:
+ fmt.Fprint(w, v.Interface())
+ }
+ return nil
+}
+
+// writeQuotedString writes a quoted string in the protocol buffer text format.
+func (w *textWriter) writeQuotedString(s string) {
+ w.WriteByte('"')
+ for i := 0; i < len(s); i++ {
+ switch c := s[i]; c {
+ case '\n':
+ w.buf = append(w.buf, `\n`...)
+ case '\r':
+ w.buf = append(w.buf, `\r`...)
+ case '\t':
+ w.buf = append(w.buf, `\t`...)
+ case '"':
+ w.buf = append(w.buf, `\"`...)
+ case '\\':
+ w.buf = append(w.buf, `\\`...)
+ default:
+ if isPrint := c >= 0x20 && c < 0x7f; isPrint {
+ w.buf = append(w.buf, c)
+ } else {
+ w.buf = append(w.buf, fmt.Sprintf(`\%03o`, c)...)
+ }
+ }
+ }
+ w.WriteByte('"')
+}
+
+func (w *textWriter) writeUnknownFields(b []byte) {
+ if !w.compact {
+ fmt.Fprintf(w, "/* %d unknown bytes */\n", len(b))
+ }
+
+ for len(b) > 0 {
+ num, wtyp, n := protowire.ConsumeTag(b)
+ if n < 0 {
+ return
+ }
+ b = b[n:]
+
+ if wtyp == protowire.EndGroupType {
+ w.indent--
+ w.Write(endBraceNewline)
+ continue
+ }
+ fmt.Fprint(w, num)
+ if wtyp != protowire.StartGroupType {
+ w.WriteByte(':')
+ }
+ if !w.compact || wtyp == protowire.StartGroupType {
+ w.WriteByte(' ')
+ }
+ switch wtyp {
+ case protowire.VarintType:
+ v, n := protowire.ConsumeVarint(b)
+ if n < 0 {
+ return
+ }
+ b = b[n:]
+ fmt.Fprint(w, v)
+ case protowire.Fixed32Type:
+ v, n := protowire.ConsumeFixed32(b)
+ if n < 0 {
+ return
+ }
+ b = b[n:]
+ fmt.Fprint(w, v)
+ case protowire.Fixed64Type:
+ v, n := protowire.ConsumeFixed64(b)
+ if n < 0 {
+ return
+ }
+ b = b[n:]
+ fmt.Fprint(w, v)
+ case protowire.BytesType:
+ v, n := protowire.ConsumeBytes(b)
+ if n < 0 {
+ return
+ }
+ b = b[n:]
+ fmt.Fprintf(w, "%q", v)
+ case protowire.StartGroupType:
+ w.WriteByte('{')
+ w.indent++
+ default:
+ fmt.Fprintf(w, "/* unknown wire type %d */", wtyp)
+ }
+ w.WriteByte('\n')
+ }
+}
+
+// writeExtensions writes all the extensions in m.
+func (w *textWriter) writeExtensions(m protoreflect.Message) error {
+ md := m.Descriptor()
+ if md.ExtensionRanges().Len() == 0 {
+ return nil
+ }
+
+ type ext struct {
+ desc protoreflect.FieldDescriptor
+ val protoreflect.Value
+ }
+ var exts []ext
+ m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
+ if fd.IsExtension() {
+ exts = append(exts, ext{fd, v})
+ }
+ return true
+ })
+ sort.Slice(exts, func(i, j int) bool {
+ return exts[i].desc.Number() < exts[j].desc.Number()
+ })
+
+ for _, ext := range exts {
+ // For message set, use the name of the message as the extension name.
+ name := string(ext.desc.FullName())
+ if isMessageSet(ext.desc.ContainingMessage()) {
+ name = strings.TrimSuffix(name, ".message_set_extension")
+ }
+
+ if !ext.desc.IsList() {
+ if err := w.writeSingularExtension(name, ext.val, ext.desc); err != nil {
+ return err
+ }
+ } else {
+ lv := ext.val.List()
+ for i := 0; i < lv.Len(); i++ {
+ if err := w.writeSingularExtension(name, lv.Get(i), ext.desc); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (w *textWriter) writeSingularExtension(name string, v protoreflect.Value, fd protoreflect.FieldDescriptor) error {
+ fmt.Fprintf(w, "[%s]:", name)
+ if !w.compact {
+ w.WriteByte(' ')
+ }
+ if err := w.writeSingularValue(v, fd); err != nil {
+ return err
+ }
+ w.WriteByte('\n')
+ return nil
+}
+
+func (w *textWriter) writeIndent() {
+ if !w.complete {
+ return
+ }
+ for i := 0; i < w.indent*2; i++ {
+ w.buf = append(w.buf, ' ')
+ }
+ w.complete = false
+}
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go
deleted file mode 100644
index 0685bae36..000000000
--- a/vendor/github.com/golang/protobuf/proto/text_parser.go
+++ /dev/null
@@ -1,880 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-// Functions for parsing the Text protocol buffer format.
-// TODO: message sets.
-
-import (
- "encoding"
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "unicode/utf8"
-)
-
-// Error string emitted when deserializing Any and fields are already set
-const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
-
-type ParseError struct {
- Message string
- Line int // 1-based line number
- Offset int // 0-based byte offset from start of input
-}
-
-func (p *ParseError) Error() string {
- if p.Line == 1 {
- // show offset only for first line
- return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
- }
- return fmt.Sprintf("line %d: %v", p.Line, p.Message)
-}
-
-type token struct {
- value string
- err *ParseError
- line int // line number
- offset int // byte number from start of input, not start of line
- unquoted string // the unquoted version of value, if it was a quoted string
-}
-
-func (t *token) String() string {
- if t.err == nil {
- return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
- }
- return fmt.Sprintf("parse error: %v", t.err)
-}
-
-type textParser struct {
- s string // remaining input
- done bool // whether the parsing is finished (success or error)
- backed bool // whether back() was called
- offset, line int
- cur token
-}
-
-func newTextParser(s string) *textParser {
- p := new(textParser)
- p.s = s
- p.line = 1
- p.cur.line = 1
- return p
-}
-
-func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
- pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
- p.cur.err = pe
- p.done = true
- return pe
-}
-
-// Numbers and identifiers are matched by [-+._A-Za-z0-9]
-func isIdentOrNumberChar(c byte) bool {
- switch {
- case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
- return true
- case '0' <= c && c <= '9':
- return true
- }
- switch c {
- case '-', '+', '.', '_':
- return true
- }
- return false
-}
-
-func isWhitespace(c byte) bool {
- switch c {
- case ' ', '\t', '\n', '\r':
- return true
- }
- return false
-}
-
-func isQuote(c byte) bool {
- switch c {
- case '"', '\'':
- return true
- }
- return false
-}
-
-func (p *textParser) skipWhitespace() {
- i := 0
- for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
- if p.s[i] == '#' {
- // comment; skip to end of line or input
- for i < len(p.s) && p.s[i] != '\n' {
- i++
- }
- if i == len(p.s) {
- break
- }
- }
- if p.s[i] == '\n' {
- p.line++
- }
- i++
- }
- p.offset += i
- p.s = p.s[i:len(p.s)]
- if len(p.s) == 0 {
- p.done = true
- }
-}
-
-func (p *textParser) advance() {
- // Skip whitespace
- p.skipWhitespace()
- if p.done {
- return
- }
-
- // Start of non-whitespace
- p.cur.err = nil
- p.cur.offset, p.cur.line = p.offset, p.line
- p.cur.unquoted = ""
- switch p.s[0] {
- case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
- // Single symbol
- p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
- case '"', '\'':
- // Quoted string
- i := 1
- for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
- if p.s[i] == '\\' && i+1 < len(p.s) {
- // skip escaped char
- i++
- }
- i++
- }
- if i >= len(p.s) || p.s[i] != p.s[0] {
- p.errorf("unmatched quote")
- return
- }
- unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
- if err != nil {
- p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
- return
- }
- p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
- p.cur.unquoted = unq
- default:
- i := 0
- for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
- i++
- }
- if i == 0 {
- p.errorf("unexpected byte %#x", p.s[0])
- return
- }
- p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
- }
- p.offset += len(p.cur.value)
-}
-
-var (
- errBadUTF8 = errors.New("proto: bad UTF-8")
-)
-
-func unquoteC(s string, quote rune) (string, error) {
- // This is based on C++'s tokenizer.cc.
- // Despite its name, this is *not* parsing C syntax.
- // For instance, "\0" is an invalid quoted string.
-
- // Avoid allocation in trivial cases.
- simple := true
- for _, r := range s {
- if r == '\\' || r == quote {
- simple = false
- break
- }
- }
- if simple {
- return s, nil
- }
-
- buf := make([]byte, 0, 3*len(s)/2)
- for len(s) > 0 {
- r, n := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && n == 1 {
- return "", errBadUTF8
- }
- s = s[n:]
- if r != '\\' {
- if r < utf8.RuneSelf {
- buf = append(buf, byte(r))
- } else {
- buf = append(buf, string(r)...)
- }
- continue
- }
-
- ch, tail, err := unescape(s)
- if err != nil {
- return "", err
- }
- buf = append(buf, ch...)
- s = tail
- }
- return string(buf), nil
-}
-
-func unescape(s string) (ch string, tail string, err error) {
- r, n := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && n == 1 {
- return "", "", errBadUTF8
- }
- s = s[n:]
- switch r {
- case 'a':
- return "\a", s, nil
- case 'b':
- return "\b", s, nil
- case 'f':
- return "\f", s, nil
- case 'n':
- return "\n", s, nil
- case 'r':
- return "\r", s, nil
- case 't':
- return "\t", s, nil
- case 'v':
- return "\v", s, nil
- case '?':
- return "?", s, nil // trigraph workaround
- case '\'', '"', '\\':
- return string(r), s, nil
- case '0', '1', '2', '3', '4', '5', '6', '7':
- if len(s) < 2 {
- return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
- }
- ss := string(r) + s[:2]
- s = s[2:]
- i, err := strconv.ParseUint(ss, 8, 8)
- if err != nil {
- return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
- }
- return string([]byte{byte(i)}), s, nil
- case 'x', 'X', 'u', 'U':
- var n int
- switch r {
- case 'x', 'X':
- n = 2
- case 'u':
- n = 4
- case 'U':
- n = 8
- }
- if len(s) < n {
- return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
- }
- ss := s[:n]
- s = s[n:]
- i, err := strconv.ParseUint(ss, 16, 64)
- if err != nil {
- return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
- }
- if r == 'x' || r == 'X' {
- return string([]byte{byte(i)}), s, nil
- }
- if i > utf8.MaxRune {
- return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
- }
- return string(i), s, nil
- }
- return "", "", fmt.Errorf(`unknown escape \%c`, r)
-}
-
-// Back off the parser by one token. Can only be done between calls to next().
-// It makes the next advance() a no-op.
-func (p *textParser) back() { p.backed = true }
-
-// Advances the parser and returns the new current token.
-func (p *textParser) next() *token {
- if p.backed || p.done {
- p.backed = false
- return &p.cur
- }
- p.advance()
- if p.done {
- p.cur.value = ""
- } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
- // Look for multiple quoted strings separated by whitespace,
- // and concatenate them.
- cat := p.cur
- for {
- p.skipWhitespace()
- if p.done || !isQuote(p.s[0]) {
- break
- }
- p.advance()
- if p.cur.err != nil {
- return &p.cur
- }
- cat.value += " " + p.cur.value
- cat.unquoted += p.cur.unquoted
- }
- p.done = false // parser may have seen EOF, but we want to return cat
- p.cur = cat
- }
- return &p.cur
-}
-
-func (p *textParser) consumeToken(s string) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != s {
- p.back()
- return p.errorf("expected %q, found %q", s, tok.value)
- }
- return nil
-}
-
-// Return a RequiredNotSetError indicating which required field was not set.
-func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < st.NumField(); i++ {
- if !isNil(sv.Field(i)) {
- continue
- }
-
- props := sprops.Prop[i]
- if props.Required {
- return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
- }
- }
- return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen
-}
-
-// Returns the index in the struct for the named field, as well as the parsed tag properties.
-func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
- i, ok := sprops.decoderOrigNames[name]
- if ok {
- return i, sprops.Prop[i], true
- }
- return -1, nil, false
-}
-
-// Consume a ':' from the input stream (if the next token is a colon),
-// returning an error if a colon is needed but not present.
-func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ":" {
- // Colon is optional when the field is a group or message.
- needColon := true
- switch props.Wire {
- case "group":
- needColon = false
- case "bytes":
- // A "bytes" field is either a message, a string, or a repeated field;
- // those three become *T, *string and []T respectively, so we can check for
- // this field being a pointer to a non-string.
- if typ.Kind() == reflect.Ptr {
- // *T or *string
- if typ.Elem().Kind() == reflect.String {
- break
- }
- } else if typ.Kind() == reflect.Slice {
- // []T or []*T
- if typ.Elem().Kind() != reflect.Ptr {
- break
- }
- } else if typ.Kind() == reflect.String {
- // The proto3 exception is for a string field,
- // which requires a colon.
- break
- }
- needColon = false
- }
- if needColon {
- return p.errorf("expected ':', found %q", tok.value)
- }
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
- st := sv.Type()
- sprops := GetProperties(st)
- reqCount := sprops.reqCount
- var reqFieldErr error
- fieldSet := make(map[string]bool)
- // A struct is a sequence of "name: value", terminated by one of
- // '>' or '}', or the end of the input. A name may also be
- // "[extension]" or "[type/url]".
- //
- // The whole struct can also be an expanded Any message, like:
- // [type/url] < ... struct contents ... >
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- if tok.value == "[" {
- // Looks like an extension or an Any.
- //
- // TODO: Check whether we need to handle
- // namespace rooted names (e.g. ".something.Foo").
- extName, err := p.consumeExtName()
- if err != nil {
- return err
- }
-
- if s := strings.LastIndex(extName, "/"); s >= 0 {
- // If it contains a slash, it's an Any type URL.
- messageName := extName[s+1:]
- mt := MessageType(messageName)
- if mt == nil {
- return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
- }
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- // consume an optional colon
- if tok.value == ":" {
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- }
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- v := reflect.New(mt.Elem())
- if pe := p.readStruct(v.Elem(), terminator); pe != nil {
- return pe
- }
- b, err := Marshal(v.Interface().(Message))
- if err != nil {
- return p.errorf("failed to marshal message of type %q: %v", messageName, err)
- }
- if fieldSet["type_url"] {
- return p.errorf(anyRepeatedlyUnpacked, "type_url")
- }
- if fieldSet["value"] {
- return p.errorf(anyRepeatedlyUnpacked, "value")
- }
- sv.FieldByName("TypeUrl").SetString(extName)
- sv.FieldByName("Value").SetBytes(b)
- fieldSet["type_url"] = true
- fieldSet["value"] = true
- continue
- }
-
- var desc *ExtensionDesc
- // This could be faster, but it's functional.
- // TODO: Do something smarter than a linear scan.
- for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
- if d.Name == extName {
- desc = d
- break
- }
- }
- if desc == nil {
- return p.errorf("unrecognized extension %q", extName)
- }
-
- props := &Properties{}
- props.Parse(desc.Tag)
-
- typ := reflect.TypeOf(desc.ExtensionType)
- if err := p.checkForColon(props, typ); err != nil {
- return err
- }
-
- rep := desc.repeated()
-
- // Read the extension structure, and set it in
- // the value we're constructing.
- var ext reflect.Value
- if !rep {
- ext = reflect.New(typ).Elem()
- } else {
- ext = reflect.New(typ.Elem()).Elem()
- }
- if err := p.readAny(ext, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- ep := sv.Addr().Interface().(Message)
- if !rep {
- SetExtension(ep, desc, ext.Interface())
- } else {
- old, err := GetExtension(ep, desc)
- var sl reflect.Value
- if err == nil {
- sl = reflect.ValueOf(old) // existing slice
- } else {
- sl = reflect.MakeSlice(typ, 0, 1)
- }
- sl = reflect.Append(sl, ext)
- SetExtension(ep, desc, sl.Interface())
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- continue
- }
-
- // This is a normal, non-extension field.
- name := tok.value
- var dst reflect.Value
- fi, props, ok := structFieldByName(sprops, name)
- if ok {
- dst = sv.Field(fi)
- } else if oop, ok := sprops.OneofTypes[name]; ok {
- // It is a oneof.
- props = oop.Prop
- nv := reflect.New(oop.Type.Elem())
- dst = nv.Elem().Field(0)
- field := sv.Field(oop.Field)
- if !field.IsNil() {
- return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
- }
- field.Set(nv)
- }
- if !dst.IsValid() {
- return p.errorf("unknown field name %q in %v", name, st)
- }
-
- if dst.Kind() == reflect.Map {
- // Consume any colon.
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Construct the map if it doesn't already exist.
- if dst.IsNil() {
- dst.Set(reflect.MakeMap(dst.Type()))
- }
- key := reflect.New(dst.Type().Key()).Elem()
- val := reflect.New(dst.Type().Elem()).Elem()
-
- // The map entry should be this sequence of tokens:
- // < key : KEY value : VALUE >
- // However, implementations may omit key or value, and technically
- // we should support them in any order. See b/28924776 for a time
- // this went wrong.
-
- tok := p.next()
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- switch tok.value {
- case "key":
- if err := p.consumeToken(":"); err != nil {
- return err
- }
- if err := p.readAny(key, props.mkeyprop); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- case "value":
- if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
- return err
- }
- if err := p.readAny(val, props.mvalprop); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- default:
- p.back()
- return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
- }
- }
-
- dst.SetMapIndex(key, val)
- continue
- }
-
- // Check that it's not already set if it's not a repeated field.
- if !props.Repeated && fieldSet[name] {
- return p.errorf("non-repeated field %q was repeated", name)
- }
-
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Parse into the field.
- fieldSet[name] = true
- if err := p.readAny(dst, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- if props.Required {
- reqCount--
- }
-
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
-
- }
-
- if reqCount > 0 {
- return p.missingRequiredFieldError(sv)
- }
- return reqFieldErr
-}
-
-// consumeExtName consumes extension name or expanded Any type URL and the
-// following ']'. It returns the name or URL consumed.
-func (p *textParser) consumeExtName() (string, error) {
- tok := p.next()
- if tok.err != nil {
- return "", tok.err
- }
-
- // If extension name or type url is quoted, it's a single token.
- if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
- name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
- if err != nil {
- return "", err
- }
- return name, p.consumeToken("]")
- }
-
- // Consume everything up to "]"
- var parts []string
- for tok.value != "]" {
- parts = append(parts, tok.value)
- tok = p.next()
- if tok.err != nil {
- return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
- }
- if p.done && tok.value != "]" {
- return "", p.errorf("unclosed type_url or extension name")
- }
- }
- return strings.Join(parts, ""), nil
-}
-
-// consumeOptionalSeparator consumes an optional semicolon or comma.
-// It is used in readStruct to provide backward compatibility.
-func (p *textParser) consumeOptionalSeparator() error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ";" && tok.value != "," {
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readAny(v reflect.Value, props *Properties) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "" {
- return p.errorf("unexpected EOF")
- }
-
- switch fv := v; fv.Kind() {
- case reflect.Slice:
- at := v.Type()
- if at.Elem().Kind() == reflect.Uint8 {
- // Special case for []byte
- if tok.value[0] != '"' && tok.value[0] != '\'' {
- // Deliberately written out here, as the error after
- // this switch statement would write "invalid []byte: ...",
- // which is not as user-friendly.
- return p.errorf("invalid string: %v", tok.value)
- }
- bytes := []byte(tok.unquoted)
- fv.Set(reflect.ValueOf(bytes))
- return nil
- }
- // Repeated field.
- if tok.value == "[" {
- // Repeated field with list notation, like [1,2,3].
- for {
- fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
- err := p.readAny(fv.Index(fv.Len()-1), props)
- if err != nil {
- return err
- }
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "]" {
- break
- }
- if tok.value != "," {
- return p.errorf("Expected ']' or ',' found %q", tok.value)
- }
- }
- return nil
- }
- // One value of the repeated field.
- p.back()
- fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
- return p.readAny(fv.Index(fv.Len()-1), props)
- case reflect.Bool:
- // true/1/t/True or false/f/0/False.
- switch tok.value {
- case "true", "1", "t", "True":
- fv.SetBool(true)
- return nil
- case "false", "0", "f", "False":
- fv.SetBool(false)
- return nil
- }
- case reflect.Float32, reflect.Float64:
- v := tok.value
- // Ignore 'f' for compatibility with output generated by C++, but don't
- // remove 'f' when the value is "-inf" or "inf".
- if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
- v = v[:len(v)-1]
- }
- if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
- fv.SetFloat(f)
- return nil
- }
- case reflect.Int32:
- if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- if len(props.Enum) == 0 {
- break
- }
- m, ok := enumValueMaps[props.Enum]
- if !ok {
- break
- }
- x, ok := m[tok.value]
- if !ok {
- break
- }
- fv.SetInt(int64(x))
- return nil
- case reflect.Int64:
- if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- case reflect.Ptr:
- // A basic field (indirected through pointer), or a repeated message/group
- p.back()
- fv.Set(reflect.New(fv.Type().Elem()))
- return p.readAny(fv.Elem(), props)
- case reflect.String:
- if tok.value[0] == '"' || tok.value[0] == '\'' {
- fv.SetString(tok.unquoted)
- return nil
- }
- case reflect.Struct:
- var terminator string
- switch tok.value {
- case "{":
- terminator = "}"
- case "<":
- terminator = ">"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
- return p.readStruct(fv, terminator)
- case reflect.Uint32:
- if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
- fv.SetUint(uint64(x))
- return nil
- }
- case reflect.Uint64:
- if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
- fv.SetUint(x)
- return nil
- }
- }
- return p.errorf("invalid %v: %v", v.Type(), tok.value)
-}
-
-// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
-// before starting to unmarshal, so any existing data in pb is always removed.
-// If a required field is not set and no other error occurs,
-// UnmarshalText returns *RequiredNotSetError.
-func UnmarshalText(s string, pb Message) error {
- if um, ok := pb.(encoding.TextUnmarshaler); ok {
- return um.UnmarshalText([]byte(s))
- }
- pb.Reset()
- v := reflect.ValueOf(pb)
- return newTextParser(s).readStruct(v.Elem(), "")
-}
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser_test.go b/vendor/github.com/golang/protobuf/proto/text_parser_test.go
deleted file mode 100644
index a81980879..000000000
--- a/vendor/github.com/golang/protobuf/proto/text_parser_test.go
+++ /dev/null
@@ -1,706 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto_test
-
-import (
- "fmt"
- "math"
- "testing"
-
- . "github.com/golang/protobuf/proto"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- . "github.com/golang/protobuf/proto/test_proto"
-)
-
-type UnmarshalTextTest struct {
- in string
- err string // if "", no error expected
- out *MyMessage
-}
-
-func buildExtStructTest(text string) UnmarshalTextTest {
- msg := &MyMessage{
- Count: Int32(42),
- }
- SetExtension(msg, E_Ext_More, &Ext{
- Data: String("Hello, world!"),
- })
- return UnmarshalTextTest{in: text, out: msg}
-}
-
-func buildExtDataTest(text string) UnmarshalTextTest {
- msg := &MyMessage{
- Count: Int32(42),
- }
- SetExtension(msg, E_Ext_Text, String("Hello, world!"))
- SetExtension(msg, E_Ext_Number, Int32(1729))
- return UnmarshalTextTest{in: text, out: msg}
-}
-
-func buildExtRepStringTest(text string) UnmarshalTextTest {
- msg := &MyMessage{
- Count: Int32(42),
- }
- if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil {
- panic(err)
- }
- return UnmarshalTextTest{in: text, out: msg}
-}
-
-var unMarshalTextTests = []UnmarshalTextTest{
- // Basic
- {
- in: " count:42\n name:\"Dave\" ",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("Dave"),
- },
- },
-
- // Empty quoted string
- {
- in: `count:42 name:""`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String(""),
- },
- },
-
- // Quoted string concatenation with double quotes
- {
- in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("My name is elsewhere"),
- },
- },
-
- // Quoted string concatenation with single quotes
- {
- in: "count:42 name: 'My name is '\n'elsewhere'",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("My name is elsewhere"),
- },
- },
-
- // Quoted string concatenations with mixed quotes
- {
- in: "count:42 name: 'My name is '\n\"elsewhere\"",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("My name is elsewhere"),
- },
- },
- {
- in: "count:42 name: \"My name is \"\n'elsewhere'",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("My name is elsewhere"),
- },
- },
-
- // Quoted string with escaped apostrophe
- {
- in: `count:42 name: "HOLIDAY - New Year\'s Day"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("HOLIDAY - New Year's Day"),
- },
- },
-
- // Quoted string with single quote
- {
- in: `count:42 name: 'Roger "The Ramster" Ramjet'`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String(`Roger "The Ramster" Ramjet`),
- },
- },
-
- // Quoted string with all the accepted special characters from the C++ test
- {
- in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"),
- },
- },
-
- // Quoted string with quoted backslash
- {
- in: `count:42 name: "\\'xyz"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String(`\'xyz`),
- },
- },
-
- // Quoted string with UTF-8 bytes.
- {
- in: "count:42 name: '\303\277\302\201\x00\xAB\xCD\xEF'",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("\303\277\302\201\x00\xAB\xCD\xEF"),
- },
- },
-
- // Quoted string with unicode escapes.
- {
- in: `count: 42 name: "\u0047\U00000047\uffff\U0010ffff"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("GG\uffff\U0010ffff"),
- },
- },
-
- // Bad quoted string
- {
- in: `inner: < host: "\0" >` + "\n",
- err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`,
- },
-
- // Bad \u escape
- {
- in: `count: 42 name: "\u000"`,
- err: `line 1.16: invalid quoted string "\u000": \u requires 4 following digits`,
- },
-
- // Bad \U escape
- {
- in: `count: 42 name: "\U0000000"`,
- err: `line 1.16: invalid quoted string "\U0000000": \U requires 8 following digits`,
- },
-
- // Bad \U escape
- {
- in: `count: 42 name: "\xxx"`,
- err: `line 1.16: invalid quoted string "\xxx": \xxx contains non-hexadecimal digits`,
- },
-
- // Number too large for int64
- {
- in: "count: 1 others { key: 123456789012345678901 }",
- err: "line 1.23: invalid int64: 123456789012345678901",
- },
-
- // Number too large for int32
- {
- in: "count: 1234567890123",
- err: "line 1.7: invalid int32: 1234567890123",
- },
-
- // Number in hexadecimal
- {
- in: "count: 0x2beef",
- out: &MyMessage{
- Count: Int32(0x2beef),
- },
- },
-
- // Number in octal
- {
- in: "count: 024601",
- out: &MyMessage{
- Count: Int32(024601),
- },
- },
-
- // Floating point number with "f" suffix
- {
- in: "count: 4 others:< weight: 17.0f >",
- out: &MyMessage{
- Count: Int32(4),
- Others: []*OtherMessage{
- {
- Weight: Float32(17),
- },
- },
- },
- },
-
- // Floating point positive infinity
- {
- in: "count: 4 bigfloat: inf",
- out: &MyMessage{
- Count: Int32(4),
- Bigfloat: Float64(math.Inf(1)),
- },
- },
-
- // Floating point negative infinity
- {
- in: "count: 4 bigfloat: -inf",
- out: &MyMessage{
- Count: Int32(4),
- Bigfloat: Float64(math.Inf(-1)),
- },
- },
-
- // Number too large for float32
- {
- in: "others:< weight: 12345678901234567890123456789012345678901234567890 >",
- err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890",
- },
-
- // Number posing as a quoted string
- {
- in: `inner: < host: 12 >` + "\n",
- err: `line 1.15: invalid string: 12`,
- },
-
- // Quoted string posing as int32
- {
- in: `count: "12"`,
- err: `line 1.7: invalid int32: "12"`,
- },
-
- // Quoted string posing a float32
- {
- in: `others:< weight: "17.4" >`,
- err: `line 1.17: invalid float32: "17.4"`,
- },
-
- // unclosed bracket doesn't cause infinite loop
- {
- in: `[`,
- err: `line 1.0: unclosed type_url or extension name`,
- },
-
- // Enum
- {
- in: `count:42 bikeshed: BLUE`,
- out: &MyMessage{
- Count: Int32(42),
- Bikeshed: MyMessage_BLUE.Enum(),
- },
- },
-
- // Repeated field
- {
- in: `count:42 pet: "horsey" pet:"bunny"`,
- out: &MyMessage{
- Count: Int32(42),
- Pet: []string{"horsey", "bunny"},
- },
- },
-
- // Repeated field with list notation
- {
- in: `count:42 pet: ["horsey", "bunny"]`,
- out: &MyMessage{
- Count: Int32(42),
- Pet: []string{"horsey", "bunny"},
- },
- },
-
- // Repeated message with/without colon and <>/{}
- {
- in: `count:42 others:{} others{} others:<> others:{}`,
- out: &MyMessage{
- Count: Int32(42),
- Others: []*OtherMessage{
- {},
- {},
- {},
- {},
- },
- },
- },
-
- // Missing colon for inner message
- {
- in: `count:42 inner < host: "cauchy.syd" >`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("cauchy.syd"),
- },
- },
- },
-
- // Missing colon for string field
- {
- in: `name "Dave"`,
- err: `line 1.5: expected ':', found "\"Dave\""`,
- },
-
- // Missing colon for int32 field
- {
- in: `count 42`,
- err: `line 1.6: expected ':', found "42"`,
- },
-
- // Missing required field
- {
- in: `name: "Pawel"`,
- err: fmt.Sprintf(`proto: required field "%T.count" not set`, MyMessage{}),
- out: &MyMessage{
- Name: String("Pawel"),
- },
- },
-
- // Missing required field in a required submessage
- {
- in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`,
- err: fmt.Sprintf(`proto: required field "%T.host" not set`, InnerMessage{}),
- out: &MyMessage{
- Count: Int32(42),
- WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}},
- },
- },
-
- // Repeated non-repeated field
- {
- in: `name: "Rob" name: "Russ"`,
- err: `line 1.12: non-repeated field "name" was repeated`,
- },
-
- // Group
- {
- in: `count: 17 SomeGroup { group_field: 12 }`,
- out: &MyMessage{
- Count: Int32(17),
- Somegroup: &MyMessage_SomeGroup{
- GroupField: Int32(12),
- },
- },
- },
-
- // Semicolon between fields
- {
- in: `count:3;name:"Calvin"`,
- out: &MyMessage{
- Count: Int32(3),
- Name: String("Calvin"),
- },
- },
- // Comma between fields
- {
- in: `count:4,name:"Ezekiel"`,
- out: &MyMessage{
- Count: Int32(4),
- Name: String("Ezekiel"),
- },
- },
-
- // Boolean false
- {
- in: `count:42 inner { host: "example.com" connected: false }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(false),
- },
- },
- },
- // Boolean true
- {
- in: `count:42 inner { host: "example.com" connected: true }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(true),
- },
- },
- },
- // Boolean 0
- {
- in: `count:42 inner { host: "example.com" connected: 0 }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(false),
- },
- },
- },
- // Boolean 1
- {
- in: `count:42 inner { host: "example.com" connected: 1 }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(true),
- },
- },
- },
- // Boolean f
- {
- in: `count:42 inner { host: "example.com" connected: f }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(false),
- },
- },
- },
- // Boolean t
- {
- in: `count:42 inner { host: "example.com" connected: t }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(true),
- },
- },
- },
- // Boolean False
- {
- in: `count:42 inner { host: "example.com" connected: False }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(false),
- },
- },
- },
- // Boolean True
- {
- in: `count:42 inner { host: "example.com" connected: True }`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("example.com"),
- Connected: Bool(true),
- },
- },
- },
-
- // Extension
- buildExtStructTest(`count: 42 [test_proto.Ext.more]:`),
- buildExtStructTest(`count: 42 [test_proto.Ext.more] {data:"Hello, world!"}`),
- buildExtDataTest(`count: 42 [test_proto.Ext.text]:"Hello, world!" [test_proto.Ext.number]:1729`),
- buildExtRepStringTest(`count: 42 [test_proto.greeting]:"bula" [test_proto.greeting]:"hola"`),
-
- // Big all-in-one
- {
- in: "count:42 # Meaning\n" +
- `name:"Dave" ` +
- `quote:"\"I didn't want to go.\"" ` +
- `pet:"bunny" ` +
- `pet:"kitty" ` +
- `pet:"horsey" ` +
- `inner:<` +
- ` host:"footrest.syd" ` +
- ` port:7001 ` +
- ` connected:true ` +
- `> ` +
- `others:<` +
- ` key:3735928559 ` +
- ` value:"\x01A\a\f" ` +
- `> ` +
- `others:<` +
- " weight:58.9 # Atomic weight of Co\n" +
- ` inner:<` +
- ` host:"lesha.mtv" ` +
- ` port:8002 ` +
- ` >` +
- `>`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("Dave"),
- Quote: String(`"I didn't want to go."`),
- Pet: []string{"bunny", "kitty", "horsey"},
- Inner: &InnerMessage{
- Host: String("footrest.syd"),
- Port: Int32(7001),
- Connected: Bool(true),
- },
- Others: []*OtherMessage{
- {
- Key: Int64(3735928559),
- Value: []byte{0x1, 'A', '\a', '\f'},
- },
- {
- Weight: Float32(58.9),
- Inner: &InnerMessage{
- Host: String("lesha.mtv"),
- Port: Int32(8002),
- },
- },
- },
- },
- },
-}
-
-func TestUnmarshalText(t *testing.T) {
- for i, test := range unMarshalTextTests {
- pb := new(MyMessage)
- err := UnmarshalText(test.in, pb)
- if test.err == "" {
- // We don't expect failure.
- if err != nil {
- t.Errorf("Test %d: Unexpected error: %v", i, err)
- } else if !Equal(pb, test.out) {
- t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v",
- i, pb, test.out)
- }
- } else {
- // We do expect failure.
- if err == nil {
- t.Errorf("Test %d: Didn't get expected error: %v", i, test.err)
- } else if err.Error() != test.err {
- t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v",
- i, err.Error(), test.err)
- } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !Equal(pb, test.out) {
- t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v",
- i, pb, test.out)
- }
- }
- }
-}
-
-func TestUnmarshalTextCustomMessage(t *testing.T) {
- msg := &textMessage{}
- if err := UnmarshalText("custom", msg); err != nil {
- t.Errorf("Unexpected error from custom unmarshal: %v", err)
- }
- if UnmarshalText("not custom", msg) == nil {
- t.Errorf("Didn't get expected error from custom unmarshal")
- }
-}
-
-// Regression test; this caused a panic.
-func TestRepeatedEnum(t *testing.T) {
- pb := new(RepeatedEnum)
- if err := UnmarshalText("color: RED", pb); err != nil {
- t.Fatal(err)
- }
- exp := &RepeatedEnum{
- Color: []RepeatedEnum_Color{RepeatedEnum_RED},
- }
- if !Equal(pb, exp) {
- t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp)
- }
-}
-
-func TestProto3TextParsing(t *testing.T) {
- m := new(proto3pb.Message)
- const in = `name: "Wallace" true_scotsman: true`
- want := &proto3pb.Message{
- Name: "Wallace",
- TrueScotsman: true,
- }
- if err := UnmarshalText(in, m); err != nil {
- t.Fatal(err)
- }
- if !Equal(m, want) {
- t.Errorf("\n got %v\nwant %v", m, want)
- }
-}
-
-func TestMapParsing(t *testing.T) {
- m := new(MessageWithMap)
- const in = `name_mapping: name_mapping:` +
- `msg_mapping:,>` + // separating commas are okay
- `msg_mapping>` + // no colon after "value"
- `msg_mapping:>` + // omitted key
- `msg_mapping:` + // omitted value
- `byte_mapping:` +
- `byte_mapping:<>` // omitted key and value
- want := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Beatles",
- 1234: "Feist",
- },
- MsgMapping: map[int64]*FloatingPoint{
- -4: {F: Float64(2.0)},
- -2: {F: Float64(4.0)},
- 0: {F: Float64(5.0)},
- 1: nil,
- },
- ByteMapping: map[bool][]byte{
- false: nil,
- true: []byte("so be it"),
- },
- }
- if err := UnmarshalText(in, m); err != nil {
- t.Fatal(err)
- }
- if !Equal(m, want) {
- t.Errorf("\n got %v\nwant %v", m, want)
- }
-}
-
-func TestOneofParsing(t *testing.T) {
- const in = `name:"Shrek"`
- m := new(Communique)
- want := &Communique{Union: &Communique_Name{"Shrek"}}
- if err := UnmarshalText(in, m); err != nil {
- t.Fatal(err)
- }
- if !Equal(m, want) {
- t.Errorf("\n got %v\nwant %v", m, want)
- }
-
- const inOverwrite = `name:"Shrek" number:42`
- m = new(Communique)
- testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'"
- if err := UnmarshalText(inOverwrite, m); err == nil {
- t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr)
- } else if err.Error() != testErr {
- t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v",
- err.Error(), testErr)
- }
-
-}
-
-var benchInput string
-
-func init() {
- benchInput = "count: 4\n"
- for i := 0; i < 1000; i++ {
- benchInput += "pet: \"fido\"\n"
- }
-
- // Check it is valid input.
- pb := new(MyMessage)
- err := UnmarshalText(benchInput, pb)
- if err != nil {
- panic("Bad benchmark input: " + err.Error())
- }
-}
-
-func BenchmarkUnmarshalText(b *testing.B) {
- pb := new(MyMessage)
- for i := 0; i < b.N; i++ {
- UnmarshalText(benchInput, pb)
- }
- b.SetBytes(int64(len(benchInput)))
-}
diff --git a/vendor/github.com/golang/protobuf/proto/text_test.go b/vendor/github.com/golang/protobuf/proto/text_test.go
index 3c8b033c0..3f6edc5a6 100644
--- a/vendor/github.com/golang/protobuf/proto/text_test.go
+++ b/vendor/github.com/golang/protobuf/proto/text_test.go
@@ -1,52 +1,285 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package proto_test
import (
"bytes"
"errors"
- "io/ioutil"
"math"
"strings"
"sync"
"testing"
"github.com/golang/protobuf/proto"
+ "github.com/google/go-cmp/cmp"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/test_proto"
+ pb2 "github.com/golang/protobuf/internal/testprotos/proto2_proto"
+ pb3 "github.com/golang/protobuf/internal/testprotos/proto3_proto"
anypb "github.com/golang/protobuf/ptypes/any"
)
+var (
+ expandedMarshaler = proto.TextMarshaler{ExpandAny: true}
+ expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true}
+)
+
+// anyEqual reports whether two messages which may be google.protobuf.Any or may
+// contain google.protobuf.Any fields are equal. We can't use proto.Equal for
+// comparison, because semantically equivalent messages may be marshaled to
+// binary in different tag order. Instead, trust that TextMarshaler with
+// ExpandAny option works and compare the text marshaling results.
+func anyEqual(got, want proto.Message) bool {
+ // if messages are proto.Equal, no need to marshal.
+ if proto.Equal(got, want) {
+ return true
+ }
+ g := expandedMarshaler.Text(got)
+ w := expandedMarshaler.Text(want)
+ return g == w
+}
+
+type golden struct {
+ m proto.Message
+ t, c string
+}
+
+var goldenMessages = makeGolden()
+
+func makeGolden() []golden {
+ nested := &pb3.Nested{Bunny: "Monty"}
+ nb, err := proto.Marshal(nested)
+ if err != nil {
+ panic(err)
+ }
+ m1 := &pb3.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb},
+ }
+ m2 := &pb3.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb},
+ }
+ m3 := &pb3.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb},
+ }
+ m4 := &pb3.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb},
+ }
+ m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}
+
+ any1 := &pb2.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}
+ proto.SetExtension(any1, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("foo")})
+ proto.SetExtension(any1, pb2.E_Ext_Text, proto.String("bar"))
+ any1b, err := proto.Marshal(any1)
+ if err != nil {
+ panic(err)
+ }
+ any2 := &pb2.MyMessage{Count: proto.Int32(42), Bikeshed: pb2.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}}
+ proto.SetExtension(any2, pb2.E_Ext_More, &pb2.Ext{Data: proto.String("baz")})
+ any2b, err := proto.Marshal(any2)
+ if err != nil {
+ panic(err)
+ }
+ m6 := &pb3.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
+ ManyThings: []*anypb.Any{
+ &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b},
+ &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
+ },
+ }
+
+ const (
+ m1Golden = `
+name: "David"
+result_count: 47
+anything: <
+ [type.googleapis.com/proto3_test.Nested]: <
+ bunny: "Monty"
+ >
+>
+`
+ m2Golden = `
+name: "David"
+result_count: 47
+anything: <
+ ["http://[::1]/type.googleapis.com/proto3_test.Nested"]: <
+ bunny: "Monty"
+ >
+>
+`
+ m3Golden = `
+name: "David"
+result_count: 47
+anything: <
+ ["type.googleapis.com/\"/proto3_test.Nested"]: <
+ bunny: "Monty"
+ >
+>
+`
+ m4Golden = `
+name: "David"
+result_count: 47
+anything: <
+ [type.googleapis.com/a/path/proto3_test.Nested]: <
+ bunny: "Monty"
+ >
+>
+`
+ m5Golden = `
+[type.googleapis.com/proto3_test.Nested]: <
+ bunny: "Monty"
+>
+`
+ m6Golden = `
+name: "David"
+result_count: 47
+anything: <
+ [type.googleapis.com/proto2_test.MyMessage]: <
+ count: 47
+ name: "David"
+ [proto2_test.Ext.more]: <
+ data: "foo"
+ >
+ [proto2_test.Ext.text]: "bar"
+ >
+>
+many_things: <
+ [type.googleapis.com/proto2_test.MyMessage]: <
+ count: 42
+ bikeshed: GREEN
+ rep_bytes: "roboto"
+ [proto2_test.Ext.more]: <
+ data: "baz"
+ >
+ >
+>
+many_things: <
+ [type.googleapis.com/proto2_test.MyMessage]: <
+ count: 47
+ name: "David"
+ [proto2_test.Ext.more]: <
+ data: "foo"
+ >
+ [proto2_test.Ext.text]: "bar"
+ >
+>
+`
+ )
+ return []golden{
+ {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "},
+ {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "},
+ {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "},
+ {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "},
+ {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "},
+ {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "},
+ }
+}
+
+func TestMarshalGolden(t *testing.T) {
+ for _, tt := range goldenMessages {
+ t.Run("", func(t *testing.T) {
+ if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want {
+ t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want)
+ }
+ if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want {
+ t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want)
+ }
+ })
+ }
+}
+
+func TestUnmarshalGolden(t *testing.T) {
+ for _, tt := range goldenMessages {
+ t.Run("", func(t *testing.T) {
+ want := tt.m
+ got := proto.Clone(tt.m)
+ got.Reset()
+ if err := proto.UnmarshalText(tt.t, got); err != nil {
+ t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err)
+ }
+ if !anyEqual(got, want) {
+ t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want)
+ }
+ got.Reset()
+ if err := proto.UnmarshalText(tt.c, got); err != nil {
+ t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err)
+ }
+ if !anyEqual(got, want) {
+ t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want)
+ }
+ })
+ }
+}
+
+func TestMarshalUnknownAny(t *testing.T) {
+ m := &pb3.Message{
+ Anything: &anypb.Any{
+ TypeUrl: "foo",
+ Value: []byte("bar"),
+ },
+ }
+ want := `anything: <
+ type_url: "foo"
+ value: "bar"
+>
+`
+ got := expandedMarshaler.Text(m)
+ if got != want {
+ t.Errorf("got:\n%s\nwant:\n%s", got, want)
+ }
+}
+
+func TestAmbiguousAny(t *testing.T) {
+ pb := &anypb.Any{}
+ err := proto.UnmarshalText(`
+ type_url: "ttt/proto3_test.Nested"
+ value: "\n\x05Monty"
+ `, pb)
+ if err != nil {
+ t.Errorf("unexpected proto.UnmarshalText error: %v", err)
+ }
+}
+
+func TestUnmarshalOverwriteAny(t *testing.T) {
+ pb := &anypb.Any{}
+ err := proto.UnmarshalText(`
+ [type.googleapis.com/a/path/proto3_test.Nested]: <
+ bunny: "Monty"
+ >
+ [type.googleapis.com/a/path/proto3_test.Nested]: <
+ bunny: "Rabbit of Caerbannog"
+ >
+ `, pb)
+ want := `line 7: Any message unpacked multiple times, or "type_url" already set`
+ if err.Error() != want {
+ t.Errorf("incorrect error:\ngot: %v\nwant: %v", err.Error(), want)
+ }
+}
+
+func TestUnmarshalAnyMixAndMatch(t *testing.T) {
+ pb := &anypb.Any{}
+ err := proto.UnmarshalText(`
+ value: "\n\x05Monty"
+ [type.googleapis.com/a/path/proto3_test.Nested]: <
+ bunny: "Rabbit of Caerbannog"
+ >
+ `, pb)
+ want := `line 5: Any message unpacked multiple times, or "value" already set`
+ if err.Error() != want {
+ t.Errorf("incorrect error:\ngot: %v\nwant: %v", err.Error(), want)
+ }
+}
+
// textMessage implements the methods that allow it to marshal and unmarshal
// itself as text.
type textMessage struct {
@@ -67,51 +300,51 @@ func (*textMessage) Reset() {}
func (*textMessage) String() string { return "" }
func (*textMessage) ProtoMessage() {}
-func newTestMessage() *pb.MyMessage {
- msg := &pb.MyMessage{
+func newTestMessage() *pb2.MyMessage {
+ msg := &pb2.MyMessage{
Count: proto.Int32(42),
Name: proto.String("Dave"),
Quote: proto.String(`"I didn't want to go."`),
Pet: []string{"bunny", "kitty", "horsey"},
- Inner: &pb.InnerMessage{
+ Inner: &pb2.InnerMessage{
Host: proto.String("footrest.syd"),
Port: proto.Int32(7001),
Connected: proto.Bool(true),
},
- Others: []*pb.OtherMessage{
+ Others: []*pb2.OtherMessage{
{
Key: proto.Int64(0xdeadbeef),
Value: []byte{1, 65, 7, 12},
},
{
Weight: proto.Float32(6.022),
- Inner: &pb.InnerMessage{
+ Inner: &pb2.InnerMessage{
Host: proto.String("lesha.mtv"),
Port: proto.Int32(8002),
},
},
},
- Bikeshed: pb.MyMessage_BLUE.Enum(),
- Somegroup: &pb.MyMessage_SomeGroup{
+ Bikeshed: pb2.MyMessage_BLUE.Enum(),
+ Somegroup: &pb2.MyMessage_SomeGroup{
GroupField: proto.Int32(8),
},
// One normally wouldn't do this.
// This is an undeclared tag 13, as a varint (wire type 0) with value 4.
XXX_unrecognized: []byte{13<<3 | 0, 4},
}
- ext := &pb.Ext{
+ ext := &pb2.Ext{
Data: proto.String("Big gobs for big rats"),
}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil {
+ if err := proto.SetExtension(msg, pb2.E_Ext_More, ext); err != nil {
panic(err)
}
greetings := []string{"adg", "easy", "cow"}
- if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil {
+ if err := proto.SetExtension(msg, pb2.E_Greeting, greetings); err != nil {
panic(err)
}
- // Add an unknown extension. We marshal a pb.Ext, and fake the ID.
- b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")})
+ // Add an unknown extension. We marshal a pb2.Ext, and fake the ID.
+ b, err := proto.Marshal(&pb2.Ext{Data: proto.String("3G skiing")})
if err != nil {
panic(err)
}
@@ -151,18 +384,16 @@ bikeshed: BLUE
SomeGroup {
group_field: 8
}
-/* 2 unknown bytes */
+/* 18 unknown bytes */
13: 4
-[test_proto.Ext.more]: <
- data: "Big gobs for big rats"
->
-[test_proto.greeting]: "adg"
-[test_proto.greeting]: "easy"
-[test_proto.greeting]: "cow"
-/* 13 unknown bytes */
201: "\t3G skiing"
-/* 3 unknown bytes */
202: 19
+[proto2_test.Ext.more]: <
+ data: "Big gobs for big rats"
+>
+[proto2_test.greeting]: "adg"
+[proto2_test.greeting]: "easy"
+[proto2_test.greeting]: "cow"
`
func TestMarshalText(t *testing.T) {
@@ -170,9 +401,9 @@ func TestMarshalText(t *testing.T) {
if err := proto.MarshalText(buf, newTestMessage()); err != nil {
t.Fatalf("proto.MarshalText: %v", err)
}
- s := buf.String()
- if s != text {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text)
+ got := buf.String()
+ if diff := cmp.Diff(text, got); got != text {
+ t.Errorf("diff (-want +got):\n%v\n\ngot:\n%v\n\nwant:\n%v", diff, got, text)
}
}
@@ -181,14 +412,14 @@ func TestMarshalTextCustomMessage(t *testing.T) {
if err := proto.MarshalText(buf, &textMessage{}); err != nil {
t.Fatalf("proto.MarshalText: %v", err)
}
- s := buf.String()
- if s != "custom" {
- t.Errorf("Got %q, expected %q", s, "custom")
+ got := buf.String()
+ if got != "custom" {
+ t.Errorf("got:\n%v\n\nwant:\n%v", got, "custom")
}
}
func TestMarshalTextNil(t *testing.T) {
want := ""
- tests := []proto.Message{nil, (*pb.MyMessage)(nil)}
+ tests := []proto.Message{nil, (*pb2.MyMessage)(nil)}
for i, test := range tests {
buf := new(bytes.Buffer)
if err := proto.MarshalText(buf, test); err != nil {
@@ -202,7 +433,7 @@ func TestMarshalTextNil(t *testing.T) {
func TestMarshalTextUnknownEnum(t *testing.T) {
// The Color enum only specifies values 0-2.
- m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()}
+ m := &pb2.MyMessage{Bikeshed: pb2.MyMessage_Color(3).Enum()}
got := m.String()
const want = `bikeshed:3 `
if got != want {
@@ -216,41 +447,24 @@ func TestTextOneof(t *testing.T) {
want string
}{
// zero message
- {&pb.Communique{}, ``},
+ {&pb2.Communique{}, ``},
// scalar field
- {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`},
+ {&pb2.Communique{Union: &pb2.Communique_Number{4}}, `number:4`},
// message field
- {&pb.Communique{Union: &pb.Communique_Msg{
- &pb.Strings{StringField: proto.String("why hello!")},
+ {&pb2.Communique{Union: &pb2.Communique_Msg{
+ &pb2.Strings{StringField: proto.String("why hello!")},
}}, `msg:`},
// bad oneof (should not panic)
- {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`},
+ {&pb2.Communique{Union: &pb2.Communique_Msg{nil}}, `msg:<>`},
}
for _, test := range tests {
got := strings.TrimSpace(test.m.String())
if got != test.want {
- t.Errorf("\n got %s\nwant %s", got, test.want)
+ t.Errorf("got:\n%s\n\nwant:\n%s", got, test.want)
}
}
}
-func BenchmarkMarshalTextBuffered(b *testing.B) {
- buf := new(bytes.Buffer)
- m := newTestMessage()
- for i := 0; i < b.N; i++ {
- buf.Reset()
- proto.MarshalText(buf, m)
- }
-}
-
-func BenchmarkMarshalTextUnbuffered(b *testing.B) {
- w := ioutil.Discard
- m := newTestMessage()
- for i := 0; i < b.N; i++ {
- proto.MarshalText(w, m)
- }
-}
-
func compact(src string) string {
// s/[ \n]+/ /g; s/ $//;
dst := make([]byte, len(src))
@@ -296,59 +510,56 @@ func compact(src string) string {
return string(dst[0:j])
}
-var compactText = compact(text)
-
func TestCompactText(t *testing.T) {
- s := proto.CompactTextString(newTestMessage())
- if s != compactText {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText)
+ got := proto.CompactTextString(newTestMessage())
+ if got != compact(text) {
+ t.Errorf("got:\n%v\n\nwant:\n%v", got, compact(text))
}
}
func TestStringEscaping(t *testing.T) {
testCases := []struct {
- in *pb.Strings
+ in *pb2.Strings
out string
}{
{
// Test data from C++ test (TextFormatTest.StringEscape).
// Single divergence: we don't escape apostrophes.
- &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")},
+ &pb2.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")},
"string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n",
},
{
// Test data from the same C++ test.
- &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")},
+ &pb2.Strings{StringField: proto.String("\350\260\267\346\255\214")},
"string_field: \"\\350\\260\\267\\346\\255\\214\"\n",
},
{
// Some UTF-8.
- &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")},
+ &pb2.Strings{StringField: proto.String("\x00\x01\xff\x81")},
`string_field: "\000\001\377\201"` + "\n",
},
}
- for i, tc := range testCases {
- var buf bytes.Buffer
- if err := proto.MarshalText(&buf, tc.in); err != nil {
- t.Errorf("proto.MarsalText: %v", err)
- continue
- }
- s := buf.String()
- if s != tc.out {
- t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out)
- continue
- }
+ for _, tc := range testCases {
+ t.Run("", func(t *testing.T) {
+ var buf bytes.Buffer
+ if err := proto.MarshalText(&buf, tc.in); err != nil {
+ t.Fatalf("proto.MarsalText error: %v", err)
+ }
+ got := buf.String()
+ if got != tc.out {
+ t.Fatalf("want:\n%s\n\nwant:\n%s", got, tc.out)
+ }
- // Check round-trip.
- pb := new(pb.Strings)
- if err := proto.UnmarshalText(s, pb); err != nil {
- t.Errorf("#%d: UnmarshalText: %v", i, err)
- continue
- }
- if !proto.Equal(pb, tc.in) {
- t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb)
- }
+ // Check round-trip.
+ pb := new(pb2.Strings)
+ if err := proto.UnmarshalText(got, pb); err != nil {
+ t.Fatalf("proto.UnmarshalText error: %v", err)
+ }
+ if !proto.Equal(pb, tc.in) {
+ t.Fatalf("proto.Equal mismatch:\ngot:\n%v\n\nwant:\n%v", pb, tc.in)
+ }
+ })
}
}
@@ -382,12 +593,12 @@ func TestMarshalTextFailing(t *testing.T) {
err := proto.MarshalText(buf, newTestMessage())
// We expect a certain error, but also some partial results in the buffer.
if err != outOfSpace {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace)
+ t.Errorf("error mismatch: got %v, want %v", err, outOfSpace)
}
- s := buf.b.String()
- x := text[:buf.limit]
- if s != x {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x)
+ got := buf.b.String()
+ want := text[:buf.limit]
+ if got != want {
+ t.Errorf("text mismatch:\n\ngot:\n%v\n\nwant:\n%v", got, want)
}
}
}
@@ -404,7 +615,7 @@ func TestFloats(t *testing.T) {
{math.NaN(), "nan"},
}
for _, test := range tests {
- msg := &pb.FloatingPoint{F: &test.f}
+ msg := &pb2.FloatingPoint{F: &test.f}
got := strings.TrimSpace(msg.String())
want := `f:` + test.want
if got != want {
@@ -414,23 +625,25 @@ func TestFloats(t *testing.T) {
}
func TestRepeatedNilText(t *testing.T) {
- m := &pb.MessageList{
- Message: []*pb.MessageList_Message{
+ m := &pb2.MessageList{
+ Message: []*pb2.MessageList_Message{
nil,
- &pb.MessageList_Message{
+ &pb2.MessageList_Message{
Name: proto.String("Horse"),
},
nil,
},
}
- want := `Message
+ want := `Message {
+}
Message {
name: "Horse"
}
-Message
+Message {
+}
`
- if s := proto.MarshalTextString(m); s != want {
- t.Errorf(" got: %s\nwant: %s", s, want)
+ if got := proto.MarshalTextString(m); got != want {
+ t.Errorf("got:\n%s\n\nwant:\n%s", got, want)
}
}
@@ -440,17 +653,17 @@ func TestProto3Text(t *testing.T) {
want string
}{
// zero message
- {&proto3pb.Message{}, ``},
+ {&pb3.Message{}, ``},
// zero message except for an empty byte slice
- {&proto3pb.Message{Data: []byte{}}, ``},
+ {&pb3.Message{Data: []byte{}}, ``},
// trivial case
- {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`},
+ {&pb3.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`},
// empty map
- {&pb.MessageWithMap{}, ``},
+ {&pb2.MessageWithMap{}, ``},
// non-empty map; map format is the same as a repeated struct,
// and they are sorted by key (numerically for numeric keys).
{
- &pb.MessageWithMap{NameMapping: map[int32]string{
+ &pb2.MessageWithMap{NameMapping: map[int32]string{
-1: "Negatory",
7: "Lucky",
1234: "Feist",
@@ -463,14 +676,14 @@ func TestProto3Text(t *testing.T) {
},
// map with nil value; not well-defined, but we shouldn't crash
{
- &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}},
- `msg_mapping:`,
+ &pb2.MessageWithMap{MsgMapping: map[int64]*pb2.FloatingPoint{7: nil}},
+ `msg_mapping: >`,
},
}
for _, test := range tests {
got := strings.TrimSpace(test.m.String())
if got != test.want {
- t.Errorf("\n got %s\nwant %s", got, test.want)
+ t.Errorf("got:\n%s\n\nwant:\n%s", got, test.want)
}
}
}
@@ -478,13 +691,13 @@ func TestProto3Text(t *testing.T) {
func TestRacyMarshal(t *testing.T) {
// This test should be run with the race detector.
- any := &pb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}
- proto.SetExtension(any, pb.E_Ext_Text, proto.String("bar"))
+ any := &pb2.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}
+ proto.SetExtension(any, pb2.E_Ext_Text, proto.String("bar"))
b, err := proto.Marshal(any)
if err != nil {
panic(err)
}
- m := &proto3pb.Message{
+ m := &pb3.Message{
Name: "David",
ResultCount: 47,
Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any), Value: b},
@@ -516,3 +729,642 @@ func TestRacyMarshal(t *testing.T) {
}()
}
}
+
+type UnmarshalTextTest struct {
+ in string
+ err string // if "", no error expected
+ out *pb2.MyMessage
+}
+
+func buildExtStructTest(text string) UnmarshalTextTest {
+ msg := &pb2.MyMessage{
+ Count: proto.Int32(42),
+ }
+ proto.SetExtension(msg, pb2.E_Ext_More, &pb2.Ext{
+ Data: proto.String("Hello, world!"),
+ })
+ return UnmarshalTextTest{in: text, out: msg}
+}
+
+func buildExtDataTest(text string) UnmarshalTextTest {
+ msg := &pb2.MyMessage{
+ Count: proto.Int32(42),
+ }
+ proto.SetExtension(msg, pb2.E_Ext_Text, proto.String("Hello, world!"))
+ proto.SetExtension(msg, pb2.E_Ext_Number, proto.Int32(1729))
+ return UnmarshalTextTest{in: text, out: msg}
+}
+
+func buildExtRepStringTest(text string) UnmarshalTextTest {
+ msg := &pb2.MyMessage{
+ Count: proto.Int32(42),
+ }
+ if err := proto.SetExtension(msg, pb2.E_Greeting, []string{"bula", "hola"}); err != nil {
+ panic(err)
+ }
+ return UnmarshalTextTest{in: text, out: msg}
+}
+
+var unmarshalTextTests = []UnmarshalTextTest{
+ // Basic
+ {
+ in: " count:42\n name:\"Dave\" ",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("Dave"),
+ },
+ },
+
+ // Empty quoted string
+ {
+ in: `count:42 name:""`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String(""),
+ },
+ },
+
+ // Quoted string concatenation with double quotes
+ {
+ in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("My name is elsewhere"),
+ },
+ },
+
+ // Quoted string concatenation with single quotes
+ {
+ in: "count:42 name: 'My name is '\n'elsewhere'",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("My name is elsewhere"),
+ },
+ },
+
+ // Quoted string concatenations with mixed quotes
+ {
+ in: "count:42 name: 'My name is '\n\"elsewhere\"",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("My name is elsewhere"),
+ },
+ },
+ {
+ in: "count:42 name: \"My name is \"\n'elsewhere'",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("My name is elsewhere"),
+ },
+ },
+
+ // Quoted string with escaped apostrophe
+ {
+ in: `count:42 name: "HOLIDAY - New Year\'s Day"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("HOLIDAY - New Year's Day"),
+ },
+ },
+
+ // Quoted string with single quote
+ {
+ in: `count:42 name: 'Roger "The Ramster" Ramjet'`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String(`Roger "The Ramster" Ramjet`),
+ },
+ },
+
+ // Quoted string with all the accepted special characters from the C++ test
+ {
+ in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"),
+ },
+ },
+
+ // Quoted string with quoted backslash
+ {
+ in: `count:42 name: "\\'xyz"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String(`\'xyz`),
+ },
+ },
+
+ // Quoted string with UTF-8 bytes.
+ {
+ in: "count:42 name: '\303\277\302\201\x00\xAB\xCD\xEF'",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("\303\277\302\201\x00\xAB\xCD\xEF"),
+ },
+ },
+
+ // Quoted string with unicode escapes.
+ {
+ in: `count: 42 name: "\u0047\U00000047\uffff\U0010ffff"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("GG\uffff\U0010ffff"),
+ },
+ },
+
+ // Bad quoted string
+ {
+ in: `inner: < host: "\0" >` + "\n",
+ err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`,
+ },
+
+ // Bad \u escape
+ {
+ in: `count: 42 name: "\u000"`,
+ err: `line 1.16: invalid quoted string "\u000": \u requires 4 following digits`,
+ },
+
+ // Bad \U escape
+ {
+ in: `count: 42 name: "\U0000000"`,
+ err: `line 1.16: invalid quoted string "\U0000000": \U requires 8 following digits`,
+ },
+
+ // Bad \U escape
+ {
+ in: `count: 42 name: "\xxx"`,
+ err: `line 1.16: invalid quoted string "\xxx": \xxx contains non-hexadecimal digits`,
+ },
+
+ // Number too large for int64
+ {
+ in: "count: 1 others { key: 123456789012345678901 }",
+ err: "line 1.23: invalid int64: 123456789012345678901",
+ },
+
+ // Number too large for int32
+ {
+ in: "count: 1234567890123",
+ err: "line 1.7: invalid int32: 1234567890123",
+ },
+
+ // Number in hexadecimal
+ {
+ in: "count: 0x2beef",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(0x2beef),
+ },
+ },
+
+ // Number in octal
+ {
+ in: "count: 024601",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(024601),
+ },
+ },
+
+ // Floating point number with "f" suffix
+ {
+ in: "count: 4 others:< weight: 17.0f >",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(4),
+ Others: []*pb2.OtherMessage{
+ {
+ Weight: proto.Float32(17),
+ },
+ },
+ },
+ },
+
+ // Floating point positive infinity
+ {
+ in: "count: 4 bigfloat: inf",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(4),
+ Bigfloat: proto.Float64(math.Inf(1)),
+ },
+ },
+
+ // Floating point negative infinity
+ {
+ in: "count: 4 bigfloat: -inf",
+ out: &pb2.MyMessage{
+ Count: proto.Int32(4),
+ Bigfloat: proto.Float64(math.Inf(-1)),
+ },
+ },
+
+ // Number too large for float32
+ {
+ in: "others:< weight: 12345678901234567890123456789012345678901234567890 >",
+ err: "line 1.17: invalid float: 12345678901234567890123456789012345678901234567890",
+ },
+
+ // Number posing as a quoted string
+ {
+ in: `inner: < host: 12 >` + "\n",
+ err: `line 1.15: invalid string: 12`,
+ },
+
+ // Quoted string posing as int32
+ {
+ in: `count: "12"`,
+ err: `line 1.7: invalid int32: "12"`,
+ },
+
+ // Quoted string posing a float32
+ {
+ in: `others:< weight: "17.4" >`,
+ err: `line 1.17: invalid float: "17.4"`,
+ },
+
+ // unclosed bracket doesn't cause infinite loop
+ {
+ in: `[`,
+ err: `line 1.0: unclosed type_url or extension name`,
+ },
+
+ // Enum
+ {
+ in: `count:42 bikeshed: BLUE`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Bikeshed: pb2.MyMessage_BLUE.Enum(),
+ },
+ },
+
+ // Repeated field
+ {
+ in: `count:42 pet: "horsey" pet:"bunny"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Pet: []string{"horsey", "bunny"},
+ },
+ },
+
+ // Repeated field with list notation
+ {
+ in: `count:42 pet: ["horsey", "bunny"]`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Pet: []string{"horsey", "bunny"},
+ },
+ },
+
+ // Repeated message with/without colon and <>/{}
+ {
+ in: `count:42 others:{} others{} others:<> others:{}`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Others: []*pb2.OtherMessage{
+ {},
+ {},
+ {},
+ {},
+ },
+ },
+ },
+
+ // Missing colon for inner message
+ {
+ in: `count:42 inner < host: "cauchy.syd" >`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("cauchy.syd"),
+ },
+ },
+ },
+
+ // Missing colon for string field
+ {
+ in: `name "Dave"`,
+ err: `line 1.5: expected ':', found "\"Dave\""`,
+ },
+
+ // Missing colon for int32 field
+ {
+ in: `count 42`,
+ err: `line 1.6: expected ':', found "42"`,
+ },
+
+ // Missing required field
+ {
+ in: `name: "Pawel"`,
+ err: `required field proto2_test.MyMessage.count not set`,
+ out: &pb2.MyMessage{
+ Name: proto.String("Pawel"),
+ },
+ },
+
+ // Missing required field in a required submessage
+ {
+ in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`,
+ err: `required field proto2_test.InnerMessage.host not set`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ WeMustGoDeeper: &pb2.RequiredInnerMessage{LeoFinallyWonAnOscar: &pb2.InnerMessage{}},
+ },
+ },
+
+ // Repeated non-repeated field
+ {
+ in: `name: "Rob" name: "Russ"`,
+ err: `line 1.12: non-repeated field "name" was repeated`,
+ },
+
+ // Group
+ {
+ in: `count: 17 SomeGroup { group_field: 12 }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(17),
+ Somegroup: &pb2.MyMessage_SomeGroup{
+ GroupField: proto.Int32(12),
+ },
+ },
+ },
+
+ // Semicolon between fields
+ {
+ in: `count:3;name:"Calvin"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(3),
+ Name: proto.String("Calvin"),
+ },
+ },
+ // Comma between fields
+ {
+ in: `count:4,name:"Ezekiel"`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(4),
+ Name: proto.String("Ezekiel"),
+ },
+ },
+
+ // Boolean false
+ {
+ in: `count:42 inner { host: "example.com" connected: false }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(false),
+ },
+ },
+ },
+ // Boolean true
+ {
+ in: `count:42 inner { host: "example.com" connected: true }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(true),
+ },
+ },
+ },
+ // Boolean 0
+ {
+ in: `count:42 inner { host: "example.com" connected: 0 }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(false),
+ },
+ },
+ },
+ // Boolean 1
+ {
+ in: `count:42 inner { host: "example.com" connected: 1 }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(true),
+ },
+ },
+ },
+ // Boolean f
+ {
+ in: `count:42 inner { host: "example.com" connected: f }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(false),
+ },
+ },
+ },
+ // Boolean t
+ {
+ in: `count:42 inner { host: "example.com" connected: t }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(true),
+ },
+ },
+ },
+ // Boolean False
+ {
+ in: `count:42 inner { host: "example.com" connected: False }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(false),
+ },
+ },
+ },
+ // Boolean True
+ {
+ in: `count:42 inner { host: "example.com" connected: True }`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("example.com"),
+ Connected: proto.Bool(true),
+ },
+ },
+ },
+
+ // Extension
+ buildExtStructTest(`count: 42 [proto2_test.Ext.more]:`),
+ buildExtStructTest(`count: 42 [proto2_test.Ext.more] {data:"Hello, world!"}`),
+ buildExtDataTest(`count: 42 [proto2_test.Ext.text]:"Hello, world!" [proto2_test.Ext.number]:1729`),
+ buildExtRepStringTest(`count: 42 [proto2_test.greeting]:"bula" [proto2_test.greeting]:"hola"`),
+ {
+ in: `[proto2_test.complex]:<>`,
+ err: `line 1.20: extension field "proto2_test.complex" does not extend message "proto2_test.MyMessage"`,
+ },
+
+ // Big all-in-one
+ {
+ in: "count:42 # Meaning\n" +
+ `name:"Dave" ` +
+ `quote:"\"I didn't want to go.\"" ` +
+ `pet:"bunny" ` +
+ `pet:"kitty" ` +
+ `pet:"horsey" ` +
+ `inner:<` +
+ ` host:"footrest.syd" ` +
+ ` port:7001 ` +
+ ` connected:true ` +
+ `> ` +
+ `others:<` +
+ ` key:3735928559 ` +
+ ` value:"\x01A\a\f" ` +
+ `> ` +
+ `others:<` +
+ " weight:58.9 # Atomic weight of Co\n" +
+ ` inner:<` +
+ ` host:"lesha.mtv" ` +
+ ` port:8002 ` +
+ ` >` +
+ `>`,
+ out: &pb2.MyMessage{
+ Count: proto.Int32(42),
+ Name: proto.String("Dave"),
+ Quote: proto.String(`"I didn't want to go."`),
+ Pet: []string{"bunny", "kitty", "horsey"},
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("footrest.syd"),
+ Port: proto.Int32(7001),
+ Connected: proto.Bool(true),
+ },
+ Others: []*pb2.OtherMessage{
+ {
+ Key: proto.Int64(3735928559),
+ Value: []byte{0x1, 'A', '\a', '\f'},
+ },
+ {
+ Weight: proto.Float32(58.9),
+ Inner: &pb2.InnerMessage{
+ Host: proto.String("lesha.mtv"),
+ Port: proto.Int32(8002),
+ },
+ },
+ },
+ },
+ },
+}
+
+func TestUnmarshalText(t *testing.T) {
+ for _, test := range unmarshalTextTests {
+ t.Run("", func(t *testing.T) {
+ pb := new(pb2.MyMessage)
+ err := proto.UnmarshalText(test.in, pb)
+ if test.err == "" {
+ // We don't expect failure.
+ if err != nil {
+ t.Errorf("proto.UnmarshalText error: %v", err)
+ } else if !proto.Equal(pb, test.out) {
+ t.Errorf("proto.Equal mismatch:\ngot: %v\nwant: %v", pb, test.out)
+ }
+ } else {
+ // We do expect failure.
+ if err == nil {
+ t.Errorf("proto.UnmarshalText: got nil error, want %v", test.err)
+ } else if !strings.Contains(err.Error(), test.err) {
+ t.Errorf("proto.UnmarshalText error mismatch:\ngot: %v\nwant: %v", err.Error(), test.err)
+ } else if _, ok := err.(*proto.RequiredNotSetError); ok && test.out != nil && !proto.Equal(pb, test.out) {
+ t.Errorf("proto.Equal mismatch:\ngot %v\nwant: %v", pb, test.out)
+ }
+ }
+ })
+ }
+}
+
+func TestUnmarshalTextCustomMessage(t *testing.T) {
+ msg := &textMessage{}
+ if err := proto.UnmarshalText("custom", msg); err != nil {
+ t.Errorf("proto.UnmarshalText error: %v", err)
+ }
+ if err := proto.UnmarshalText("not custom", msg); err == nil {
+ t.Errorf("proto.UnmarshalText: got nil error, want non-nil")
+ }
+}
+
+// Regression test; this caused a panic.
+func TestRepeatedEnum(t *testing.T) {
+ pb := new(pb2.RepeatedEnum)
+ if err := proto.UnmarshalText("color: RED", pb); err != nil {
+ t.Fatal(err)
+ }
+ exp := &pb2.RepeatedEnum{
+ Color: []pb2.RepeatedEnum_Color{pb2.RepeatedEnum_RED},
+ }
+ if !proto.Equal(pb, exp) {
+ t.Errorf("proto.Equal mismatch:\ngot: %v\nwant %v", pb, exp)
+ }
+}
+
+func TestProto3TextParsing(t *testing.T) {
+ m := new(pb3.Message)
+ const in = `name: "Wallace" true_scotsman: true`
+ want := &pb3.Message{
+ Name: "Wallace",
+ TrueScotsman: true,
+ }
+ if err := proto.UnmarshalText(in, m); err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(m, want) {
+ t.Errorf("proto.Equal mismatch:\ngot: %v\nwant %v", m, want)
+ }
+}
+
+func TestMapParsing(t *testing.T) {
+ m := new(pb2.MessageWithMap)
+ const in = `name_mapping: name_mapping:` +
+ `msg_mapping:,>` + // separating commas are okay
+ `msg_mapping>` + // no colon after "value"
+ `msg_mapping:>` + // omitted key
+ `byte_mapping:` +
+ `byte_mapping:<>` // omitted key and value
+ want := &pb2.MessageWithMap{
+ NameMapping: map[int32]string{
+ 1: "Beatles",
+ 1234: "Feist",
+ },
+ MsgMapping: map[int64]*pb2.FloatingPoint{
+ -4: {F: proto.Float64(2.0)},
+ -2: {F: proto.Float64(4.0)},
+ 0: {F: proto.Float64(5.0)},
+ },
+ ByteMapping: map[bool][]byte{
+ false: nil,
+ true: []byte("so be it"),
+ },
+ }
+ if err := proto.UnmarshalText(in, m); err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(m, want) {
+ t.Errorf("proto.Equal mismatch:\ngot: %v\nwant %v", m, want)
+ }
+}
+
+func TestOneofParsing(t *testing.T) {
+ const in = `name:"Shrek"`
+ m := new(pb2.Communique)
+ want := &pb2.Communique{Union: &pb2.Communique_Name{"Shrek"}}
+ if err := proto.UnmarshalText(in, m); err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(m, want) {
+ t.Errorf("\n got %v\nwant %v", m, want)
+ }
+
+ const inOverwrite = `name:"Shrek" number:42`
+ m = new(pb2.Communique)
+ testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'union'"
+ if err := proto.UnmarshalText(inOverwrite, m); err == nil {
+ t.Errorf("proto.UnmarshalText: got nil error, want %v", testErr)
+ } else if err.Error() != testErr {
+ t.Errorf("error mismatch:\ngot: %v\nwant: %v", err.Error(), testErr)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/wire.go b/vendor/github.com/golang/protobuf/proto/wire.go
new file mode 100644
index 000000000..d7c28da5a
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/wire.go
@@ -0,0 +1,78 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto
+
+import (
+ protoV2 "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/runtime/protoiface"
+)
+
+// Size returns the size in bytes of the wire-format encoding of m.
+func Size(m Message) int {
+ if m == nil {
+ return 0
+ }
+ mi := MessageV2(m)
+ return protoV2.Size(mi)
+}
+
+// Marshal returns the wire-format encoding of m.
+func Marshal(m Message) ([]byte, error) {
+ b, err := marshalAppend(nil, m, false)
+ if b == nil {
+ b = zeroBytes
+ }
+ return b, err
+}
+
+var zeroBytes = make([]byte, 0, 0)
+
+func marshalAppend(buf []byte, m Message, deterministic bool) ([]byte, error) {
+ if m == nil {
+ return nil, ErrNil
+ }
+ mi := MessageV2(m)
+ nbuf, err := protoV2.MarshalOptions{
+ Deterministic: deterministic,
+ AllowPartial: true,
+ }.MarshalAppend(buf, mi)
+ if err != nil {
+ return buf, err
+ }
+ if len(buf) == len(nbuf) {
+ if !mi.ProtoReflect().IsValid() {
+ return buf, ErrNil
+ }
+ }
+ return nbuf, checkRequiredNotSet(mi)
+}
+
+// Unmarshal parses a wire-format message in b and places the decoded results in m.
+//
+// Unmarshal resets m before starting to unmarshal, so any existing data in m is always
+// removed. Use UnmarshalMerge to preserve and append to existing data.
+func Unmarshal(b []byte, m Message) error {
+ m.Reset()
+ return UnmarshalMerge(b, m)
+}
+
+// UnmarshalMerge parses a wire-format message in b and places the decoded results in m.
+func UnmarshalMerge(b []byte, m Message) error {
+ mi := MessageV2(m)
+ out, err := protoV2.UnmarshalOptions{
+ AllowPartial: true,
+ Merge: true,
+ }.UnmarshalState(protoiface.UnmarshalInput{
+ Buf: b,
+ Message: mi.ProtoReflect(),
+ })
+ if err != nil {
+ return err
+ }
+ if out.Flags&protoiface.UnmarshalInitialized > 0 {
+ return nil
+ }
+ return checkRequiredNotSet(mi)
+}
diff --git a/vendor/github.com/golang/protobuf/proto/wrappers.go b/vendor/github.com/golang/protobuf/proto/wrappers.go
new file mode 100644
index 000000000..398e34859
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/wrappers.go
@@ -0,0 +1,34 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package proto
+
+// Bool stores v in a new bool value and returns a pointer to it.
+func Bool(v bool) *bool { return &v }
+
+// Int stores v in a new int32 value and returns a pointer to it.
+//
+// Deprecated: Use Int32 instead.
+func Int(v int) *int32 { return Int32(int32(v)) }
+
+// Int32 stores v in a new int32 value and returns a pointer to it.
+func Int32(v int32) *int32 { return &v }
+
+// Int64 stores v in a new int64 value and returns a pointer to it.
+func Int64(v int64) *int64 { return &v }
+
+// Uint32 stores v in a new uint32 value and returns a pointer to it.
+func Uint32(v uint32) *uint32 { return &v }
+
+// Uint64 stores v in a new uint64 value and returns a pointer to it.
+func Uint64(v uint64) *uint64 { return &v }
+
+// Float32 stores v in a new float32 value and returns a pointer to it.
+func Float32(v float32) *float32 { return &v }
+
+// Float64 stores v in a new float64 value and returns a pointer to it.
+func Float64(v float64) *float64 { return &v }
+
+// String stores v in a new string value and returns a pointer to it.
+func String(v string) *string { return &v }
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile
deleted file mode 100644
index 41a2d04d0..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile
+++ /dev/null
@@ -1,36 +0,0 @@
-# Go support for Protocol Buffers - Google's data interchange format
-#
-# Copyright 2010 The Go Authors. All rights reserved.
-# https://github.com/golang/protobuf
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-# Not stored here, but descriptor.proto is in https://github.com/google/protobuf/
-# at src/google/protobuf/descriptor.proto
-regenerate:
- @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
- protoc --go_out=../../../../.. -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
index e855b1f5c..63dc05785 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
@@ -1,2812 +1,200 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/descriptor.proto
+// source: github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
-package descriptor // import "github.com/golang/protobuf/protoc-gen-go/descriptor"
+package descriptor
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type FieldDescriptorProto_Type int32
-
-const (
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
- FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
- FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
- FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
- FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
- FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
- FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
- FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
- // New in version 2.
- FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
- FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
- FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
- FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
- FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
- FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
- FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
-)
-
-var FieldDescriptorProto_Type_name = map[int32]string{
- 1: "TYPE_DOUBLE",
- 2: "TYPE_FLOAT",
- 3: "TYPE_INT64",
- 4: "TYPE_UINT64",
- 5: "TYPE_INT32",
- 6: "TYPE_FIXED64",
- 7: "TYPE_FIXED32",
- 8: "TYPE_BOOL",
- 9: "TYPE_STRING",
- 10: "TYPE_GROUP",
- 11: "TYPE_MESSAGE",
- 12: "TYPE_BYTES",
- 13: "TYPE_UINT32",
- 14: "TYPE_ENUM",
- 15: "TYPE_SFIXED32",
- 16: "TYPE_SFIXED64",
- 17: "TYPE_SINT32",
- 18: "TYPE_SINT64",
-}
-var FieldDescriptorProto_Type_value = map[string]int32{
- "TYPE_DOUBLE": 1,
- "TYPE_FLOAT": 2,
- "TYPE_INT64": 3,
- "TYPE_UINT64": 4,
- "TYPE_INT32": 5,
- "TYPE_FIXED64": 6,
- "TYPE_FIXED32": 7,
- "TYPE_BOOL": 8,
- "TYPE_STRING": 9,
- "TYPE_GROUP": 10,
- "TYPE_MESSAGE": 11,
- "TYPE_BYTES": 12,
- "TYPE_UINT32": 13,
- "TYPE_ENUM": 14,
- "TYPE_SFIXED32": 15,
- "TYPE_SFIXED64": 16,
- "TYPE_SINT32": 17,
- "TYPE_SINT64": 18,
-}
-
-func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
- p := new(FieldDescriptorProto_Type)
- *p = x
- return p
-}
-func (x FieldDescriptorProto_Type) String() string {
- return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
-}
-func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
- if err != nil {
- return err
- }
- *x = FieldDescriptorProto_Type(value)
- return nil
-}
-func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 0}
-}
-
-type FieldDescriptorProto_Label int32
-
-const (
- // 0 is reserved for errors
- FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
- FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
- FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
-)
-
-var FieldDescriptorProto_Label_name = map[int32]string{
- 1: "LABEL_OPTIONAL",
- 2: "LABEL_REQUIRED",
- 3: "LABEL_REPEATED",
-}
-var FieldDescriptorProto_Label_value = map[string]int32{
- "LABEL_OPTIONAL": 1,
- "LABEL_REQUIRED": 2,
- "LABEL_REPEATED": 3,
-}
-
-func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
- p := new(FieldDescriptorProto_Label)
- *p = x
- return p
-}
-func (x FieldDescriptorProto_Label) String() string {
- return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
-}
-func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
- if err != nil {
- return err
- }
- *x = FieldDescriptorProto_Label(value)
- return nil
-}
-func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 1}
-}
-
-// Generated classes can be optimized for speed or code size.
-type FileOptions_OptimizeMode int32
-
-const (
- FileOptions_SPEED FileOptions_OptimizeMode = 1
- // etc.
- FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
- FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
-)
-
-var FileOptions_OptimizeMode_name = map[int32]string{
- 1: "SPEED",
- 2: "CODE_SIZE",
- 3: "LITE_RUNTIME",
-}
-var FileOptions_OptimizeMode_value = map[string]int32{
- "SPEED": 1,
- "CODE_SIZE": 2,
- "LITE_RUNTIME": 3,
-}
-
-func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
- p := new(FileOptions_OptimizeMode)
- *p = x
- return p
-}
-func (x FileOptions_OptimizeMode) String() string {
- return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
-}
-func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
- if err != nil {
- return err
- }
- *x = FileOptions_OptimizeMode(value)
- return nil
-}
-func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10, 0}
-}
-
-type FieldOptions_CType int32
-
-const (
- // Default mode.
- FieldOptions_STRING FieldOptions_CType = 0
- FieldOptions_CORD FieldOptions_CType = 1
- FieldOptions_STRING_PIECE FieldOptions_CType = 2
-)
-
-var FieldOptions_CType_name = map[int32]string{
- 0: "STRING",
- 1: "CORD",
- 2: "STRING_PIECE",
-}
-var FieldOptions_CType_value = map[string]int32{
- "STRING": 0,
- "CORD": 1,
- "STRING_PIECE": 2,
-}
-
-func (x FieldOptions_CType) Enum() *FieldOptions_CType {
- p := new(FieldOptions_CType)
- *p = x
- return p
-}
-func (x FieldOptions_CType) String() string {
- return proto.EnumName(FieldOptions_CType_name, int32(x))
-}
-func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
- if err != nil {
- return err
- }
- *x = FieldOptions_CType(value)
- return nil
-}
-func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 0}
-}
-
-type FieldOptions_JSType int32
-
-const (
- // Use the default type.
- FieldOptions_JS_NORMAL FieldOptions_JSType = 0
- // Use JavaScript strings.
- FieldOptions_JS_STRING FieldOptions_JSType = 1
- // Use JavaScript numbers.
- FieldOptions_JS_NUMBER FieldOptions_JSType = 2
-)
-
-var FieldOptions_JSType_name = map[int32]string{
- 0: "JS_NORMAL",
- 1: "JS_STRING",
- 2: "JS_NUMBER",
-}
-var FieldOptions_JSType_value = map[string]int32{
- "JS_NORMAL": 0,
- "JS_STRING": 1,
- "JS_NUMBER": 2,
-}
-
-func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
- p := new(FieldOptions_JSType)
- *p = x
- return p
-}
-func (x FieldOptions_JSType) String() string {
- return proto.EnumName(FieldOptions_JSType_name, int32(x))
-}
-func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
- if err != nil {
- return err
- }
- *x = FieldOptions_JSType(value)
- return nil
-}
-func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 1}
-}
-
-// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
-// or neither? HTTP based RPC implementation may choose GET verb for safe
-// methods, and PUT verb for idempotent methods instead of the default POST.
-type MethodOptions_IdempotencyLevel int32
-
-const (
- MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0
- MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1
- MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ descriptorpb "google.golang.org/protobuf/types/descriptorpb"
+ reflect "reflect"
)
-var MethodOptions_IdempotencyLevel_name = map[int32]string{
- 0: "IDEMPOTENCY_UNKNOWN",
- 1: "NO_SIDE_EFFECTS",
- 2: "IDEMPOTENT",
-}
-var MethodOptions_IdempotencyLevel_value = map[string]int32{
- "IDEMPOTENCY_UNKNOWN": 0,
- "NO_SIDE_EFFECTS": 1,
- "IDEMPOTENT": 2,
-}
-
-func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel {
- p := new(MethodOptions_IdempotencyLevel)
- *p = x
- return p
-}
-func (x MethodOptions_IdempotencyLevel) String() string {
- return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x))
-}
-func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel")
- if err != nil {
- return err
- }
- *x = MethodOptions_IdempotencyLevel(value)
- return nil
-}
-func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17, 0}
-}
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-type FileDescriptorSet struct {
- File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
-func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
-func (*FileDescriptorSet) ProtoMessage() {}
-func (*FileDescriptorSet) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{0}
-}
-func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b)
-}
-func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic)
-}
-func (dst *FileDescriptorSet) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileDescriptorSet.Merge(dst, src)
-}
-func (m *FileDescriptorSet) XXX_Size() int {
- return xxx_messageInfo_FileDescriptorSet.Size(m)
-}
-func (m *FileDescriptorSet) XXX_DiscardUnknown() {
- xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo
-
-func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
- if m != nil {
- return m.File
- }
- return nil
-}
-
-// Describes a complete .proto file.
-type FileDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
- // Names of files imported by this file.
- Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
- // Indexes of the public imported files in the dependency list above.
- PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
- // All top-level definitions in this file.
- MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
- EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
- Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
- Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
- Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
-func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*FileDescriptorProto) ProtoMessage() {}
-func (*FileDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{1}
-}
-func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b)
-}
-func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *FileDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileDescriptorProto.Merge(dst, src)
-}
-func (m *FileDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_FileDescriptorProto.Size(m)
-}
-func (m *FileDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo
-
-func (m *FileDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *FileDescriptorProto) GetPackage() string {
- if m != nil && m.Package != nil {
- return *m.Package
- }
- return ""
-}
-
-func (m *FileDescriptorProto) GetDependency() []string {
- if m != nil {
- return m.Dependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetPublicDependency() []int32 {
- if m != nil {
- return m.PublicDependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetWeakDependency() []int32 {
- if m != nil {
- return m.WeakDependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
- if m != nil {
- return m.MessageType
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
- if m != nil {
- return m.EnumType
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
- if m != nil {
- return m.Service
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
- if m != nil {
- return m.Extension
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetOptions() *FileOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
- if m != nil {
- return m.SourceCodeInfo
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetSyntax() string {
- if m != nil && m.Syntax != nil {
- return *m.Syntax
- }
- return ""
-}
-
-// Describes a message type.
-type DescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
- Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
- NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
- EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
- ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
- OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
- Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
- ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
-func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto) ProtoMessage() {}
-func (*DescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2}
-}
-func (m *DescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto.Unmarshal(m, b)
-}
-func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *DescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto.Merge(dst, src)
-}
-func (m *DescriptorProto) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto.Size(m)
-}
-func (m *DescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo
-
-func (m *DescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
- if m != nil {
- return m.Field
- }
- return nil
-}
-
-func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
- if m != nil {
- return m.Extension
- }
- return nil
-}
-
-func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
- if m != nil {
- return m.NestedType
- }
- return nil
-}
-
-func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
- if m != nil {
- return m.EnumType
- }
- return nil
-}
-
-func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
- if m != nil {
- return m.ExtensionRange
- }
- return nil
-}
-
-func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
- if m != nil {
- return m.OneofDecl
- }
- return nil
-}
-
-func (m *DescriptorProto) GetOptions() *MessageOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
- if m != nil {
- return m.ReservedRange
- }
- return nil
-}
-
-func (m *DescriptorProto) GetReservedName() []string {
- if m != nil {
- return m.ReservedName
- }
- return nil
-}
-
-type DescriptorProto_ExtensionRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
-func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
-func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 0}
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic)
-}
-func (dst *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(dst, src)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo
-
-func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Range of reserved tag numbers. Reserved tag numbers may not be used by
-// fields or extension ranges in the same message. Reserved ranges may
-// not overlap.
-type DescriptorProto_ReservedRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
-func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto_ReservedRange) ProtoMessage() {}
-func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 1}
-}
-func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic)
-}
-func (dst *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto_ReservedRange.Merge(dst, src)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m)
-}
-func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo
-
-func (m *DescriptorProto_ReservedRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-type ExtensionRangeOptions struct {
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} }
-func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) }
-func (*ExtensionRangeOptions) ProtoMessage() {}
-func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{3}
-}
-
-var extRange_ExtensionRangeOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_ExtensionRangeOptions
-}
-func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b)
-}
-func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic)
-}
-func (dst *ExtensionRangeOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ExtensionRangeOptions.Merge(dst, src)
-}
-func (m *ExtensionRangeOptions) XXX_Size() int {
- return xxx_messageInfo_ExtensionRangeOptions.Size(m)
-}
-func (m *ExtensionRangeOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo
+// Symbols defined in public import of google/protobuf/descriptor.proto.
-func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
+type FieldDescriptorProto_Type = descriptorpb.FieldDescriptorProto_Type
-// Describes a field within a message.
-type FieldDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
- Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- // TODO(kenton): Base-64 encode?
- DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
- Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
+const FieldDescriptorProto_TYPE_DOUBLE = descriptorpb.FieldDescriptorProto_TYPE_DOUBLE
+const FieldDescriptorProto_TYPE_FLOAT = descriptorpb.FieldDescriptorProto_TYPE_FLOAT
+const FieldDescriptorProto_TYPE_INT64 = descriptorpb.FieldDescriptorProto_TYPE_INT64
+const FieldDescriptorProto_TYPE_UINT64 = descriptorpb.FieldDescriptorProto_TYPE_UINT64
+const FieldDescriptorProto_TYPE_INT32 = descriptorpb.FieldDescriptorProto_TYPE_INT32
+const FieldDescriptorProto_TYPE_FIXED64 = descriptorpb.FieldDescriptorProto_TYPE_FIXED64
+const FieldDescriptorProto_TYPE_FIXED32 = descriptorpb.FieldDescriptorProto_TYPE_FIXED32
+const FieldDescriptorProto_TYPE_BOOL = descriptorpb.FieldDescriptorProto_TYPE_BOOL
+const FieldDescriptorProto_TYPE_STRING = descriptorpb.FieldDescriptorProto_TYPE_STRING
+const FieldDescriptorProto_TYPE_GROUP = descriptorpb.FieldDescriptorProto_TYPE_GROUP
+const FieldDescriptorProto_TYPE_MESSAGE = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE
+const FieldDescriptorProto_TYPE_BYTES = descriptorpb.FieldDescriptorProto_TYPE_BYTES
+const FieldDescriptorProto_TYPE_UINT32 = descriptorpb.FieldDescriptorProto_TYPE_UINT32
+const FieldDescriptorProto_TYPE_ENUM = descriptorpb.FieldDescriptorProto_TYPE_ENUM
+const FieldDescriptorProto_TYPE_SFIXED32 = descriptorpb.FieldDescriptorProto_TYPE_SFIXED32
+const FieldDescriptorProto_TYPE_SFIXED64 = descriptorpb.FieldDescriptorProto_TYPE_SFIXED64
+const FieldDescriptorProto_TYPE_SINT32 = descriptorpb.FieldDescriptorProto_TYPE_SINT32
+const FieldDescriptorProto_TYPE_SINT64 = descriptorpb.FieldDescriptorProto_TYPE_SINT64
-func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
-func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*FieldDescriptorProto) ProtoMessage() {}
-func (*FieldDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4}
-}
-func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b)
-}
-func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *FieldDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FieldDescriptorProto.Merge(dst, src)
-}
-func (m *FieldDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_FieldDescriptorProto.Size(m)
-}
-func (m *FieldDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m)
-}
+var FieldDescriptorProto_Type_name = descriptorpb.FieldDescriptorProto_Type_name
+var FieldDescriptorProto_Type_value = descriptorpb.FieldDescriptorProto_Type_value
-var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo
+type FieldDescriptorProto_Label = descriptorpb.FieldDescriptorProto_Label
-func (m *FieldDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
+const FieldDescriptorProto_LABEL_OPTIONAL = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL
+const FieldDescriptorProto_LABEL_REQUIRED = descriptorpb.FieldDescriptorProto_LABEL_REQUIRED
+const FieldDescriptorProto_LABEL_REPEATED = descriptorpb.FieldDescriptorProto_LABEL_REPEATED
-func (m *FieldDescriptorProto) GetNumber() int32 {
- if m != nil && m.Number != nil {
- return *m.Number
- }
- return 0
-}
+var FieldDescriptorProto_Label_name = descriptorpb.FieldDescriptorProto_Label_name
+var FieldDescriptorProto_Label_value = descriptorpb.FieldDescriptorProto_Label_value
-func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return FieldDescriptorProto_LABEL_OPTIONAL
-}
+type FileOptions_OptimizeMode = descriptorpb.FileOptions_OptimizeMode
-func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return FieldDescriptorProto_TYPE_DOUBLE
-}
+const FileOptions_SPEED = descriptorpb.FileOptions_SPEED
+const FileOptions_CODE_SIZE = descriptorpb.FileOptions_CODE_SIZE
+const FileOptions_LITE_RUNTIME = descriptorpb.FileOptions_LITE_RUNTIME
-func (m *FieldDescriptorProto) GetTypeName() string {
- if m != nil && m.TypeName != nil {
- return *m.TypeName
- }
- return ""
-}
+var FileOptions_OptimizeMode_name = descriptorpb.FileOptions_OptimizeMode_name
+var FileOptions_OptimizeMode_value = descriptorpb.FileOptions_OptimizeMode_value
-func (m *FieldDescriptorProto) GetExtendee() string {
- if m != nil && m.Extendee != nil {
- return *m.Extendee
- }
- return ""
-}
+type FieldOptions_CType = descriptorpb.FieldOptions_CType
-func (m *FieldDescriptorProto) GetDefaultValue() string {
- if m != nil && m.DefaultValue != nil {
- return *m.DefaultValue
- }
- return ""
-}
+const FieldOptions_STRING = descriptorpb.FieldOptions_STRING
+const FieldOptions_CORD = descriptorpb.FieldOptions_CORD
+const FieldOptions_STRING_PIECE = descriptorpb.FieldOptions_STRING_PIECE
-func (m *FieldDescriptorProto) GetOneofIndex() int32 {
- if m != nil && m.OneofIndex != nil {
- return *m.OneofIndex
- }
- return 0
-}
+var FieldOptions_CType_name = descriptorpb.FieldOptions_CType_name
+var FieldOptions_CType_value = descriptorpb.FieldOptions_CType_value
-func (m *FieldDescriptorProto) GetJsonName() string {
- if m != nil && m.JsonName != nil {
- return *m.JsonName
- }
- return ""
-}
+type FieldOptions_JSType = descriptorpb.FieldOptions_JSType
-func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
+const FieldOptions_JS_NORMAL = descriptorpb.FieldOptions_JS_NORMAL
+const FieldOptions_JS_STRING = descriptorpb.FieldOptions_JS_STRING
+const FieldOptions_JS_NUMBER = descriptorpb.FieldOptions_JS_NUMBER
-// Describes a oneof.
-type OneofDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
+var FieldOptions_JSType_name = descriptorpb.FieldOptions_JSType_name
+var FieldOptions_JSType_value = descriptorpb.FieldOptions_JSType_value
-func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
-func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*OneofDescriptorProto) ProtoMessage() {}
-func (*OneofDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{5}
-}
-func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b)
-}
-func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *OneofDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OneofDescriptorProto.Merge(dst, src)
-}
-func (m *OneofDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_OneofDescriptorProto.Size(m)
-}
-func (m *OneofDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m)
-}
+type MethodOptions_IdempotencyLevel = descriptorpb.MethodOptions_IdempotencyLevel
-var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo
+const MethodOptions_IDEMPOTENCY_UNKNOWN = descriptorpb.MethodOptions_IDEMPOTENCY_UNKNOWN
+const MethodOptions_NO_SIDE_EFFECTS = descriptorpb.MethodOptions_NO_SIDE_EFFECTS
+const MethodOptions_IDEMPOTENT = descriptorpb.MethodOptions_IDEMPOTENT
-func (m *OneofDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes an enum type.
-type EnumDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
- Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
-func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*EnumDescriptorProto) ProtoMessage() {}
-func (*EnumDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6}
-}
-func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b)
-}
-func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *EnumDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumDescriptorProto.Merge(dst, src)
-}
-func (m *EnumDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_EnumDescriptorProto.Size(m)
-}
-func (m *EnumDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo
-
-func (m *EnumDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange {
- if m != nil {
- return m.ReservedRange
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetReservedName() []string {
- if m != nil {
- return m.ReservedName
- }
- return nil
-}
-
-// Range of reserved numeric values. Reserved values may not be used by
-// entries in the same enum. Reserved ranges may not overlap.
-//
-// Note that this is distinct from DescriptorProto.ReservedRange in that it
-// is inclusive such that it can appropriately represent the entire int32
-// domain.
-type EnumDescriptorProto_EnumReservedRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} }
-func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) }
-func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {}
-func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6, 0}
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic)
-}
-func (dst *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(dst, src)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo
-
-func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-// Describes a value within an enum.
-type EnumValueDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
- Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
-func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*EnumValueDescriptorProto) ProtoMessage() {}
-func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{7}
-}
-func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b)
-}
-func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *EnumValueDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumValueDescriptorProto.Merge(dst, src)
-}
-func (m *EnumValueDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_EnumValueDescriptorProto.Size(m)
-}
-func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo
-
-func (m *EnumValueDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *EnumValueDescriptorProto) GetNumber() int32 {
- if m != nil && m.Number != nil {
- return *m.Number
- }
- return 0
-}
-
-func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a service.
-type ServiceDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
- Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
-func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*ServiceDescriptorProto) ProtoMessage() {}
-func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{8}
-}
-func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b)
-}
-func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *ServiceDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ServiceDescriptorProto.Merge(dst, src)
-}
-func (m *ServiceDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_ServiceDescriptorProto.Size(m)
-}
-func (m *ServiceDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo
-
-func (m *ServiceDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
- if m != nil {
- return m.Method
- }
- return nil
-}
-
-func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a method of a service.
-type MethodDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
- OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
- Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
- // Identifies if client streams multiple client messages
- ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
- // Identifies if server streams multiple server messages
- ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
-func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*MethodDescriptorProto) ProtoMessage() {}
-func (*MethodDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{9}
-}
-func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b)
-}
-func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic)
-}
-func (dst *MethodDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MethodDescriptorProto.Merge(dst, src)
-}
-func (m *MethodDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_MethodDescriptorProto.Size(m)
-}
-func (m *MethodDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo
-
-const Default_MethodDescriptorProto_ClientStreaming bool = false
-const Default_MethodDescriptorProto_ServerStreaming bool = false
-
-func (m *MethodDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetInputType() string {
- if m != nil && m.InputType != nil {
- return *m.InputType
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetOutputType() string {
- if m != nil && m.OutputType != nil {
- return *m.OutputType
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *MethodDescriptorProto) GetClientStreaming() bool {
- if m != nil && m.ClientStreaming != nil {
- return *m.ClientStreaming
- }
- return Default_MethodDescriptorProto_ClientStreaming
-}
-
-func (m *MethodDescriptorProto) GetServerStreaming() bool {
- if m != nil && m.ServerStreaming != nil {
- return *m.ServerStreaming
- }
- return Default_MethodDescriptorProto_ServerStreaming
-}
-
-type FileOptions struct {
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
- // If set, all the classes from the .proto file are wrapped in a single
- // outer class with the given name. This applies to both Proto1
- // (equivalent to the old "--one_java_file" option) and Proto2 (where
- // a .proto always translates to a single class, but you may want to
- // explicitly choose the class name).
- JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
- // If set true, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the outer class
- // named by java_outer_classname. However, the outer class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
- // This option does nothing.
- JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use.
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
- OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
- JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
- PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
- PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"`
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
- // Namespace for generated classes; defaults to the package.
- CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"`
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"`
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"`
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileOptions) Reset() { *m = FileOptions{} }
-func (m *FileOptions) String() string { return proto.CompactTextString(m) }
-func (*FileOptions) ProtoMessage() {}
-func (*FileOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10}
-}
-
-var extRange_FileOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_FileOptions
-}
-func (m *FileOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileOptions.Unmarshal(m, b)
-}
-func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic)
-}
-func (dst *FileOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileOptions.Merge(dst, src)
-}
-func (m *FileOptions) XXX_Size() int {
- return xxx_messageInfo_FileOptions.Size(m)
-}
-func (m *FileOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_FileOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileOptions proto.InternalMessageInfo
-
-const Default_FileOptions_JavaMultipleFiles bool = false
-const Default_FileOptions_JavaStringCheckUtf8 bool = false
-const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
-const Default_FileOptions_CcGenericServices bool = false
-const Default_FileOptions_JavaGenericServices bool = false
-const Default_FileOptions_PyGenericServices bool = false
-const Default_FileOptions_PhpGenericServices bool = false
-const Default_FileOptions_Deprecated bool = false
-const Default_FileOptions_CcEnableArenas bool = false
-
-func (m *FileOptions) GetJavaPackage() string {
- if m != nil && m.JavaPackage != nil {
- return *m.JavaPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetJavaOuterClassname() string {
- if m != nil && m.JavaOuterClassname != nil {
- return *m.JavaOuterClassname
- }
- return ""
-}
-
-func (m *FileOptions) GetJavaMultipleFiles() bool {
- if m != nil && m.JavaMultipleFiles != nil {
- return *m.JavaMultipleFiles
- }
- return Default_FileOptions_JavaMultipleFiles
-}
-
-// Deprecated: Do not use.
-func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
- if m != nil && m.JavaGenerateEqualsAndHash != nil {
- return *m.JavaGenerateEqualsAndHash
- }
- return false
-}
-
-func (m *FileOptions) GetJavaStringCheckUtf8() bool {
- if m != nil && m.JavaStringCheckUtf8 != nil {
- return *m.JavaStringCheckUtf8
- }
- return Default_FileOptions_JavaStringCheckUtf8
-}
-
-func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
- if m != nil && m.OptimizeFor != nil {
- return *m.OptimizeFor
- }
- return Default_FileOptions_OptimizeFor
-}
-
-func (m *FileOptions) GetGoPackage() string {
- if m != nil && m.GoPackage != nil {
- return *m.GoPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetCcGenericServices() bool {
- if m != nil && m.CcGenericServices != nil {
- return *m.CcGenericServices
- }
- return Default_FileOptions_CcGenericServices
-}
-
-func (m *FileOptions) GetJavaGenericServices() bool {
- if m != nil && m.JavaGenericServices != nil {
- return *m.JavaGenericServices
- }
- return Default_FileOptions_JavaGenericServices
-}
-
-func (m *FileOptions) GetPyGenericServices() bool {
- if m != nil && m.PyGenericServices != nil {
- return *m.PyGenericServices
- }
- return Default_FileOptions_PyGenericServices
-}
-
-func (m *FileOptions) GetPhpGenericServices() bool {
- if m != nil && m.PhpGenericServices != nil {
- return *m.PhpGenericServices
- }
- return Default_FileOptions_PhpGenericServices
-}
-
-func (m *FileOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_FileOptions_Deprecated
-}
-
-func (m *FileOptions) GetCcEnableArenas() bool {
- if m != nil && m.CcEnableArenas != nil {
- return *m.CcEnableArenas
- }
- return Default_FileOptions_CcEnableArenas
-}
-
-func (m *FileOptions) GetObjcClassPrefix() string {
- if m != nil && m.ObjcClassPrefix != nil {
- return *m.ObjcClassPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetCsharpNamespace() string {
- if m != nil && m.CsharpNamespace != nil {
- return *m.CsharpNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetSwiftPrefix() string {
- if m != nil && m.SwiftPrefix != nil {
- return *m.SwiftPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpClassPrefix() string {
- if m != nil && m.PhpClassPrefix != nil {
- return *m.PhpClassPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpNamespace() string {
- if m != nil && m.PhpNamespace != nil {
- return *m.PhpNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type MessageOptions struct {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementions still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MessageOptions) Reset() { *m = MessageOptions{} }
-func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
-func (*MessageOptions) ProtoMessage() {}
-func (*MessageOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{11}
-}
-
-var extRange_MessageOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MessageOptions
-}
-func (m *MessageOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MessageOptions.Unmarshal(m, b)
-}
-func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic)
-}
-func (dst *MessageOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageOptions.Merge(dst, src)
-}
-func (m *MessageOptions) XXX_Size() int {
- return xxx_messageInfo_MessageOptions.Size(m)
-}
-func (m *MessageOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_MessageOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MessageOptions proto.InternalMessageInfo
-
-const Default_MessageOptions_MessageSetWireFormat bool = false
-const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
-const Default_MessageOptions_Deprecated bool = false
-
-func (m *MessageOptions) GetMessageSetWireFormat() bool {
- if m != nil && m.MessageSetWireFormat != nil {
- return *m.MessageSetWireFormat
- }
- return Default_MessageOptions_MessageSetWireFormat
-}
-
-func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
- if m != nil && m.NoStandardDescriptorAccessor != nil {
- return *m.NoStandardDescriptorAccessor
- }
- return Default_MessageOptions_NoStandardDescriptorAccessor
-}
-
-func (m *MessageOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_MessageOptions_Deprecated
-}
-
-func (m *MessageOptions) GetMapEntry() bool {
- if m != nil && m.MapEntry != nil {
- return *m.MapEntry
- }
- return false
-}
-
-func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type FieldOptions struct {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // For Google-internal migration only. Do not use.
- Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FieldOptions) Reset() { *m = FieldOptions{} }
-func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
-func (*FieldOptions) ProtoMessage() {}
-func (*FieldOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12}
-}
-
-var extRange_FieldOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_FieldOptions
-}
-func (m *FieldOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FieldOptions.Unmarshal(m, b)
-}
-func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic)
-}
-func (dst *FieldOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FieldOptions.Merge(dst, src)
-}
-func (m *FieldOptions) XXX_Size() int {
- return xxx_messageInfo_FieldOptions.Size(m)
-}
-func (m *FieldOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_FieldOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FieldOptions proto.InternalMessageInfo
-
-const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
-const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
-const Default_FieldOptions_Lazy bool = false
-const Default_FieldOptions_Deprecated bool = false
-const Default_FieldOptions_Weak bool = false
-
-func (m *FieldOptions) GetCtype() FieldOptions_CType {
- if m != nil && m.Ctype != nil {
- return *m.Ctype
- }
- return Default_FieldOptions_Ctype
-}
-
-func (m *FieldOptions) GetPacked() bool {
- if m != nil && m.Packed != nil {
- return *m.Packed
- }
- return false
-}
-
-func (m *FieldOptions) GetJstype() FieldOptions_JSType {
- if m != nil && m.Jstype != nil {
- return *m.Jstype
- }
- return Default_FieldOptions_Jstype
-}
-
-func (m *FieldOptions) GetLazy() bool {
- if m != nil && m.Lazy != nil {
- return *m.Lazy
- }
- return Default_FieldOptions_Lazy
-}
-
-func (m *FieldOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_FieldOptions_Deprecated
-}
-
-func (m *FieldOptions) GetWeak() bool {
- if m != nil && m.Weak != nil {
- return *m.Weak
- }
- return Default_FieldOptions_Weak
-}
-
-func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type OneofOptions struct {
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OneofOptions) Reset() { *m = OneofOptions{} }
-func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
-func (*OneofOptions) ProtoMessage() {}
-func (*OneofOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{13}
-}
-
-var extRange_OneofOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OneofOptions
-}
-func (m *OneofOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OneofOptions.Unmarshal(m, b)
-}
-func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic)
-}
-func (dst *OneofOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OneofOptions.Merge(dst, src)
-}
-func (m *OneofOptions) XXX_Size() int {
- return xxx_messageInfo_OneofOptions.Size(m)
-}
-func (m *OneofOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_OneofOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OneofOptions proto.InternalMessageInfo
-
-func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type EnumOptions struct {
- // Set this option to true to allow mapping different tag names to the same
- // value.
- AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumOptions) Reset() { *m = EnumOptions{} }
-func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
-func (*EnumOptions) ProtoMessage() {}
-func (*EnumOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{14}
-}
-
-var extRange_EnumOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_EnumOptions
-}
-func (m *EnumOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumOptions.Unmarshal(m, b)
-}
-func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic)
-}
-func (dst *EnumOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumOptions.Merge(dst, src)
-}
-func (m *EnumOptions) XXX_Size() int {
- return xxx_messageInfo_EnumOptions.Size(m)
-}
-func (m *EnumOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumOptions proto.InternalMessageInfo
-
-const Default_EnumOptions_Deprecated bool = false
-
-func (m *EnumOptions) GetAllowAlias() bool {
- if m != nil && m.AllowAlias != nil {
- return *m.AllowAlias
- }
- return false
-}
-
-func (m *EnumOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_EnumOptions_Deprecated
-}
-
-func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type EnumValueOptions struct {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
-func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
-func (*EnumValueOptions) ProtoMessage() {}
-func (*EnumValueOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{15}
-}
-
-var extRange_EnumValueOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_EnumValueOptions
-}
-func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b)
-}
-func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic)
-}
-func (dst *EnumValueOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumValueOptions.Merge(dst, src)
-}
-func (m *EnumValueOptions) XXX_Size() int {
- return xxx_messageInfo_EnumValueOptions.Size(m)
-}
-func (m *EnumValueOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumValueOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo
-
-const Default_EnumValueOptions_Deprecated bool = false
-
-func (m *EnumValueOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_EnumValueOptions_Deprecated
-}
-
-func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type ServiceOptions struct {
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
-func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
-func (*ServiceOptions) ProtoMessage() {}
-func (*ServiceOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{16}
-}
-
-var extRange_ServiceOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_ServiceOptions
-}
-func (m *ServiceOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ServiceOptions.Unmarshal(m, b)
-}
-func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic)
-}
-func (dst *ServiceOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ServiceOptions.Merge(dst, src)
-}
-func (m *ServiceOptions) XXX_Size() int {
- return xxx_messageInfo_ServiceOptions.Size(m)
-}
-func (m *ServiceOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_ServiceOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo
-
-const Default_ServiceOptions_Deprecated bool = false
-
-func (m *ServiceOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_ServiceOptions_Deprecated
-}
-
-func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type MethodOptions struct {
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MethodOptions) Reset() { *m = MethodOptions{} }
-func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
-func (*MethodOptions) ProtoMessage() {}
-func (*MethodOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17}
-}
-
-var extRange_MethodOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MethodOptions
-}
-func (m *MethodOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MethodOptions.Unmarshal(m, b)
-}
-func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic)
-}
-func (dst *MethodOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MethodOptions.Merge(dst, src)
-}
-func (m *MethodOptions) XXX_Size() int {
- return xxx_messageInfo_MethodOptions.Size(m)
-}
-func (m *MethodOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_MethodOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MethodOptions proto.InternalMessageInfo
-
-const Default_MethodOptions_Deprecated bool = false
-const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN
-
-func (m *MethodOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_MethodOptions_Deprecated
-}
-
-func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel {
- if m != nil && m.IdempotencyLevel != nil {
- return *m.IdempotencyLevel
- }
- return Default_MethodOptions_IdempotencyLevel
-}
-
-func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-type UninterpretedOption struct {
- Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
- PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
- NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
- DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
- StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
- AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
-func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
-func (*UninterpretedOption) ProtoMessage() {}
-func (*UninterpretedOption) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18}
-}
-func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b)
-}
-func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic)
-}
-func (dst *UninterpretedOption) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UninterpretedOption.Merge(dst, src)
-}
-func (m *UninterpretedOption) XXX_Size() int {
- return xxx_messageInfo_UninterpretedOption.Size(m)
-}
-func (m *UninterpretedOption) XXX_DiscardUnknown() {
- xxx_messageInfo_UninterpretedOption.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo
-
-func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
- if m != nil {
- return m.Name
- }
- return nil
-}
-
-func (m *UninterpretedOption) GetIdentifierValue() string {
- if m != nil && m.IdentifierValue != nil {
- return *m.IdentifierValue
- }
- return ""
-}
-
-func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
- if m != nil && m.PositiveIntValue != nil {
- return *m.PositiveIntValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetNegativeIntValue() int64 {
- if m != nil && m.NegativeIntValue != nil {
- return *m.NegativeIntValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetDoubleValue() float64 {
- if m != nil && m.DoubleValue != nil {
- return *m.DoubleValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetStringValue() []byte {
- if m != nil {
- return m.StringValue
- }
- return nil
-}
-
-func (m *UninterpretedOption) GetAggregateValue() string {
- if m != nil && m.AggregateValue != nil {
- return *m.AggregateValue
- }
- return ""
-}
-
-// The name of the uninterpreted option. Each string represents a segment in
-// a dot-separated name. is_extension is true iff a segment represents an
-// extension (denoted with parentheses in options specs in .proto files).
-// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
-// "foo.(bar.baz).qux".
-type UninterpretedOption_NamePart struct {
- NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
- IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
-func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
-func (*UninterpretedOption_NamePart) ProtoMessage() {}
-func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18, 0}
-}
-func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b)
-}
-func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic)
-}
-func (dst *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UninterpretedOption_NamePart.Merge(dst, src)
-}
-func (m *UninterpretedOption_NamePart) XXX_Size() int {
- return xxx_messageInfo_UninterpretedOption_NamePart.Size(m)
-}
-func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() {
- xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo
-
-func (m *UninterpretedOption_NamePart) GetNamePart() string {
- if m != nil && m.NamePart != nil {
- return *m.NamePart
- }
- return ""
-}
-
-func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
- if m != nil && m.IsExtension != nil {
- return *m.IsExtension
- }
- return false
-}
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-type SourceCodeInfo struct {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendent. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
-func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
-func (*SourceCodeInfo) ProtoMessage() {}
-func (*SourceCodeInfo) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19}
-}
-func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b)
-}
-func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic)
-}
-func (dst *SourceCodeInfo) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SourceCodeInfo.Merge(dst, src)
-}
-func (m *SourceCodeInfo) XXX_Size() int {
- return xxx_messageInfo_SourceCodeInfo.Size(m)
-}
-func (m *SourceCodeInfo) XXX_DiscardUnknown() {
- xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo
-
-func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
- if m != nil {
- return m.Location
- }
- return nil
-}
-
-type SourceCodeInfo_Location struct {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
- // Always has exactly three or four elements: start line, start column,
- // end line (optional, otherwise assumed same as start line), end column.
- // These are packed into a single field for efficiency. Note that line
- // and column numbers are zero-based -- typically you will want to add
- // 1 to each before displaying to a user.
- Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
- // If this SourceCodeInfo represents a complete declaration, these are any
- // comments appearing before and after the declaration which appear to be
- // attached to the declaration.
- //
- // A series of line comments appearing on consecutive lines, with no other
- // tokens appearing on those lines, will be treated as a single comment.
- //
- // leading_detached_comments will keep paragraphs of comments that appear
- // before (but not connected to) the current element. Each paragraph,
- // separated by empty lines, will be one comment element in the repeated
- // field.
- //
- // Only the comment content is provided; comment markers (e.g. //) are
- // stripped out. For block comments, leading whitespace and an asterisk
- // will be stripped from the beginning of each line other than the first.
- // Newlines are included in the output.
- //
- // Examples:
- //
- // optional int32 foo = 1; // Comment attached to foo.
- // // Comment attached to bar.
- // optional int32 bar = 2;
- //
- // optional string baz = 3;
- // // Comment attached to baz.
- // // Another line attached to baz.
- //
- // // Comment attached to qux.
- // //
- // // Another line attached to qux.
- // optional double qux = 4;
- //
- // // Detached comment for corge. This is not leading or trailing comments
- // // to qux or corge because there are blank lines separating it from
- // // both.
- //
- // // Detached comment for corge paragraph 2.
- //
- // optional string corge = 5;
- // /* Block comment attached
- // * to corge. Leading asterisks
- // * will be removed. */
- // /* Block comment attached to
- // * grault. */
- // optional int32 grault = 6;
- //
- // // ignored detached comments.
- LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
- TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
- LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
-func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
-func (*SourceCodeInfo_Location) ProtoMessage() {}
-func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19, 0}
-}
-func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b)
-}
-func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic)
-}
-func (dst *SourceCodeInfo_Location) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SourceCodeInfo_Location.Merge(dst, src)
-}
-func (m *SourceCodeInfo_Location) XXX_Size() int {
- return xxx_messageInfo_SourceCodeInfo_Location.Size(m)
-}
-func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() {
- xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo
-
-func (m *SourceCodeInfo_Location) GetPath() []int32 {
- if m != nil {
- return m.Path
- }
- return nil
-}
-
-func (m *SourceCodeInfo_Location) GetSpan() []int32 {
- if m != nil {
- return m.Span
- }
- return nil
-}
-
-func (m *SourceCodeInfo_Location) GetLeadingComments() string {
- if m != nil && m.LeadingComments != nil {
- return *m.LeadingComments
- }
- return ""
-}
-
-func (m *SourceCodeInfo_Location) GetTrailingComments() string {
- if m != nil && m.TrailingComments != nil {
- return *m.TrailingComments
- }
- return ""
-}
-
-func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
- if m != nil {
- return m.LeadingDetachedComments
- }
- return nil
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-type GeneratedCodeInfo struct {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
-func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
-func (*GeneratedCodeInfo) ProtoMessage() {}
-func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20}
-}
-func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b)
-}
-func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic)
-}
-func (dst *GeneratedCodeInfo) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GeneratedCodeInfo.Merge(dst, src)
-}
-func (m *GeneratedCodeInfo) XXX_Size() int {
- return xxx_messageInfo_GeneratedCodeInfo.Size(m)
-}
-func (m *GeneratedCodeInfo) XXX_DiscardUnknown() {
- xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo
-
-func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
- if m != nil {
- return m.Annotation
- }
- return nil
-}
-
-type GeneratedCodeInfo_Annotation struct {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
- // Identifies the filesystem path to the original source .proto.
- SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
- // Identifies the starting offset in bytes in the generated code
- // that relates to the identified object.
- Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
- // Identifies the ending offset in bytes in the generated code that
- // relates to the identified offset. The end offset should be one past
- // the last relevant byte (so the length of the text = end - begin).
- End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
-func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
-func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
-func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
- return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20, 0}
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic)
-}
-func (dst *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(dst, src)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Size() int {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() {
- xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo
-
-func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
- if m != nil {
- return m.Path
- }
- return nil
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
- if m != nil && m.SourceFile != nil {
- return *m.SourceFile
- }
- return ""
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
- if m != nil && m.Begin != nil {
- return *m.Begin
- }
- return 0
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-func init() {
- proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
- proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
- proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
- proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
- proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
- proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions")
- proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
- proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
- proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
- proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange")
- proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
- proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
- proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
- proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
- proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
- proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
- proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
- proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
- proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
- proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
- proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
- proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
- proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
- proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
- proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
- proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
- proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
- proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
- proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
- proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
- proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
- proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
- proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value)
-}
-
-func init() {
- proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_descriptor_4df4cb5f42392df6)
-}
+var MethodOptions_IdempotencyLevel_name = descriptorpb.MethodOptions_IdempotencyLevel_name
+var MethodOptions_IdempotencyLevel_value = descriptorpb.MethodOptions_IdempotencyLevel_value
-var fileDescriptor_descriptor_4df4cb5f42392df6 = []byte{
- // 2555 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7,
- 0xf5, 0xcf, 0xf2, 0x4b, 0xe4, 0x21, 0x45, 0x8d, 0x46, 0x8a, 0xbd, 0x56, 0x3e, 0x2c, 0x33, 0x1f,
- 0x96, 0x9d, 0x7f, 0xa8, 0xc0, 0xb1, 0x1d, 0x47, 0xfe, 0x23, 0x2d, 0x45, 0xae, 0x15, 0xaa, 0x12,
- 0xc9, 0x2e, 0xa9, 0xe6, 0x03, 0x28, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb,
- 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0xd5, 0xab, 0xde, 0x16, 0x45, 0xd1, 0x8b, 0xde, 0x04, 0xe8,
- 0x03, 0x14, 0xc8, 0x5d, 0x9f, 0xa0, 0x40, 0xde, 0xa0, 0x68, 0x0b, 0xb4, 0x8f, 0xd0, 0xcb, 0x62,
- 0x66, 0x76, 0x97, 0xbb, 0x24, 0x15, 0x2b, 0x01, 0xe2, 0x5c, 0x91, 0xf3, 0x9b, 0xdf, 0x39, 0x73,
- 0xe6, 0xcc, 0x99, 0x33, 0x67, 0x66, 0x61, 0x7b, 0xe4, 0x38, 0x23, 0x8b, 0xee, 0xba, 0x9e, 0x13,
- 0x38, 0xa7, 0xd3, 0xe1, 0xae, 0x41, 0x7d, 0xdd, 0x33, 0xdd, 0xc0, 0xf1, 0xea, 0x1c, 0xc3, 0x6b,
- 0x82, 0x51, 0x8f, 0x18, 0xb5, 0x63, 0x58, 0x7f, 0x60, 0x5a, 0xb4, 0x15, 0x13, 0xfb, 0x34, 0xc0,
- 0xf7, 0x20, 0x37, 0x34, 0x2d, 0x2a, 0x4b, 0xdb, 0xd9, 0x9d, 0xf2, 0xad, 0x37, 0xeb, 0x73, 0x42,
- 0xf5, 0xb4, 0x44, 0x8f, 0xc1, 0x2a, 0x97, 0xa8, 0xfd, 0x2b, 0x07, 0x1b, 0x4b, 0x7a, 0x31, 0x86,
- 0x9c, 0x4d, 0x26, 0x4c, 0xa3, 0xb4, 0x53, 0x52, 0xf9, 0x7f, 0x2c, 0xc3, 0x8a, 0x4b, 0xf4, 0x47,
- 0x64, 0x44, 0xe5, 0x0c, 0x87, 0xa3, 0x26, 0x7e, 0x1d, 0xc0, 0xa0, 0x2e, 0xb5, 0x0d, 0x6a, 0xeb,
- 0x67, 0x72, 0x76, 0x3b, 0xbb, 0x53, 0x52, 0x13, 0x08, 0x7e, 0x07, 0xd6, 0xdd, 0xe9, 0xa9, 0x65,
- 0xea, 0x5a, 0x82, 0x06, 0xdb, 0xd9, 0x9d, 0xbc, 0x8a, 0x44, 0x47, 0x6b, 0x46, 0xbe, 0x0e, 0x6b,
- 0x4f, 0x28, 0x79, 0x94, 0xa4, 0x96, 0x39, 0xb5, 0xca, 0xe0, 0x04, 0xb1, 0x09, 0x95, 0x09, 0xf5,
- 0x7d, 0x32, 0xa2, 0x5a, 0x70, 0xe6, 0x52, 0x39, 0xc7, 0x67, 0xbf, 0xbd, 0x30, 0xfb, 0xf9, 0x99,
- 0x97, 0x43, 0xa9, 0xc1, 0x99, 0x4b, 0x71, 0x03, 0x4a, 0xd4, 0x9e, 0x4e, 0x84, 0x86, 0xfc, 0x39,
- 0xfe, 0x53, 0xec, 0xe9, 0x64, 0x5e, 0x4b, 0x91, 0x89, 0x85, 0x2a, 0x56, 0x7c, 0xea, 0x3d, 0x36,
- 0x75, 0x2a, 0x17, 0xb8, 0x82, 0xeb, 0x0b, 0x0a, 0xfa, 0xa2, 0x7f, 0x5e, 0x47, 0x24, 0x87, 0x9b,
- 0x50, 0xa2, 0x4f, 0x03, 0x6a, 0xfb, 0xa6, 0x63, 0xcb, 0x2b, 0x5c, 0xc9, 0x5b, 0x4b, 0x56, 0x91,
- 0x5a, 0xc6, 0xbc, 0x8a, 0x99, 0x1c, 0xbe, 0x0b, 0x2b, 0x8e, 0x1b, 0x98, 0x8e, 0xed, 0xcb, 0xc5,
- 0x6d, 0x69, 0xa7, 0x7c, 0xeb, 0xd5, 0xa5, 0x81, 0xd0, 0x15, 0x1c, 0x35, 0x22, 0xe3, 0x36, 0x20,
- 0xdf, 0x99, 0x7a, 0x3a, 0xd5, 0x74, 0xc7, 0xa0, 0x9a, 0x69, 0x0f, 0x1d, 0xb9, 0xc4, 0x15, 0x5c,
- 0x5d, 0x9c, 0x08, 0x27, 0x36, 0x1d, 0x83, 0xb6, 0xed, 0xa1, 0xa3, 0x56, 0xfd, 0x54, 0x1b, 0x5f,
- 0x82, 0x82, 0x7f, 0x66, 0x07, 0xe4, 0xa9, 0x5c, 0xe1, 0x11, 0x12, 0xb6, 0x6a, 0x5f, 0x17, 0x60,
- 0xed, 0x22, 0x21, 0x76, 0x1f, 0xf2, 0x43, 0x36, 0x4b, 0x39, 0xf3, 0x5d, 0x7c, 0x20, 0x64, 0xd2,
- 0x4e, 0x2c, 0x7c, 0x4f, 0x27, 0x36, 0xa0, 0x6c, 0x53, 0x3f, 0xa0, 0x86, 0x88, 0x88, 0xec, 0x05,
- 0x63, 0x0a, 0x84, 0xd0, 0x62, 0x48, 0xe5, 0xbe, 0x57, 0x48, 0x7d, 0x0a, 0x6b, 0xb1, 0x49, 0x9a,
- 0x47, 0xec, 0x51, 0x14, 0x9b, 0xbb, 0xcf, 0xb3, 0xa4, 0xae, 0x44, 0x72, 0x2a, 0x13, 0x53, 0xab,
- 0x34, 0xd5, 0xc6, 0x2d, 0x00, 0xc7, 0xa6, 0xce, 0x50, 0x33, 0xa8, 0x6e, 0xc9, 0xc5, 0x73, 0xbc,
- 0xd4, 0x65, 0x94, 0x05, 0x2f, 0x39, 0x02, 0xd5, 0x2d, 0xfc, 0xe1, 0x2c, 0xd4, 0x56, 0xce, 0x89,
- 0x94, 0x63, 0xb1, 0xc9, 0x16, 0xa2, 0xed, 0x04, 0xaa, 0x1e, 0x65, 0x71, 0x4f, 0x8d, 0x70, 0x66,
- 0x25, 0x6e, 0x44, 0xfd, 0xb9, 0x33, 0x53, 0x43, 0x31, 0x31, 0xb1, 0x55, 0x2f, 0xd9, 0xc4, 0x6f,
- 0x40, 0x0c, 0x68, 0x3c, 0xac, 0x80, 0x67, 0xa1, 0x4a, 0x04, 0x76, 0xc8, 0x84, 0x6e, 0x7d, 0x09,
- 0xd5, 0xb4, 0x7b, 0xf0, 0x26, 0xe4, 0xfd, 0x80, 0x78, 0x01, 0x8f, 0xc2, 0xbc, 0x2a, 0x1a, 0x18,
- 0x41, 0x96, 0xda, 0x06, 0xcf, 0x72, 0x79, 0x95, 0xfd, 0xc5, 0x3f, 0x9d, 0x4d, 0x38, 0xcb, 0x27,
- 0xfc, 0xf6, 0xe2, 0x8a, 0xa6, 0x34, 0xcf, 0xcf, 0x7b, 0xeb, 0x03, 0x58, 0x4d, 0x4d, 0xe0, 0xa2,
- 0x43, 0xd7, 0x7e, 0x05, 0x2f, 0x2f, 0x55, 0x8d, 0x3f, 0x85, 0xcd, 0xa9, 0x6d, 0xda, 0x01, 0xf5,
- 0x5c, 0x8f, 0xb2, 0x88, 0x15, 0x43, 0xc9, 0xff, 0x5e, 0x39, 0x27, 0xe6, 0x4e, 0x92, 0x6c, 0xa1,
- 0x45, 0xdd, 0x98, 0x2e, 0x82, 0x37, 0x4b, 0xc5, 0xff, 0xac, 0xa0, 0x67, 0xcf, 0x9e, 0x3d, 0xcb,
- 0xd4, 0x7e, 0x57, 0x80, 0xcd, 0x65, 0x7b, 0x66, 0xe9, 0xf6, 0xbd, 0x04, 0x05, 0x7b, 0x3a, 0x39,
- 0xa5, 0x1e, 0x77, 0x52, 0x5e, 0x0d, 0x5b, 0xb8, 0x01, 0x79, 0x8b, 0x9c, 0x52, 0x4b, 0xce, 0x6d,
- 0x4b, 0x3b, 0xd5, 0x5b, 0xef, 0x5c, 0x68, 0x57, 0xd6, 0x8f, 0x98, 0x88, 0x2a, 0x24, 0xf1, 0x47,
- 0x90, 0x0b, 0x53, 0x34, 0xd3, 0x70, 0xf3, 0x62, 0x1a, 0xd8, 0x5e, 0x52, 0xb9, 0x1c, 0x7e, 0x05,
- 0x4a, 0xec, 0x57, 0xc4, 0x46, 0x81, 0xdb, 0x5c, 0x64, 0x00, 0x8b, 0x0b, 0xbc, 0x05, 0x45, 0xbe,
- 0x4d, 0x0c, 0x1a, 0x1d, 0x6d, 0x71, 0x9b, 0x05, 0x96, 0x41, 0x87, 0x64, 0x6a, 0x05, 0xda, 0x63,
- 0x62, 0x4d, 0x29, 0x0f, 0xf8, 0x92, 0x5a, 0x09, 0xc1, 0x5f, 0x30, 0x0c, 0x5f, 0x85, 0xb2, 0xd8,
- 0x55, 0xa6, 0x6d, 0xd0, 0xa7, 0x3c, 0x7b, 0xe6, 0x55, 0xb1, 0xd1, 0xda, 0x0c, 0x61, 0xc3, 0x3f,
- 0xf4, 0x1d, 0x3b, 0x0a, 0x4d, 0x3e, 0x04, 0x03, 0xf8, 0xf0, 0x1f, 0xcc, 0x27, 0xee, 0xd7, 0x96,
- 0x4f, 0x6f, 0x3e, 0xa6, 0x6a, 0x7f, 0xc9, 0x40, 0x8e, 0xe7, 0x8b, 0x35, 0x28, 0x0f, 0x3e, 0xeb,
- 0x29, 0x5a, 0xab, 0x7b, 0xb2, 0x7f, 0xa4, 0x20, 0x09, 0x57, 0x01, 0x38, 0xf0, 0xe0, 0xa8, 0xdb,
- 0x18, 0xa0, 0x4c, 0xdc, 0x6e, 0x77, 0x06, 0x77, 0x6f, 0xa3, 0x6c, 0x2c, 0x70, 0x22, 0x80, 0x5c,
- 0x92, 0xf0, 0xfe, 0x2d, 0x94, 0xc7, 0x08, 0x2a, 0x42, 0x41, 0xfb, 0x53, 0xa5, 0x75, 0xf7, 0x36,
- 0x2a, 0xa4, 0x91, 0xf7, 0x6f, 0xa1, 0x15, 0xbc, 0x0a, 0x25, 0x8e, 0xec, 0x77, 0xbb, 0x47, 0xa8,
- 0x18, 0xeb, 0xec, 0x0f, 0xd4, 0x76, 0xe7, 0x00, 0x95, 0x62, 0x9d, 0x07, 0x6a, 0xf7, 0xa4, 0x87,
- 0x20, 0xd6, 0x70, 0xac, 0xf4, 0xfb, 0x8d, 0x03, 0x05, 0x95, 0x63, 0xc6, 0xfe, 0x67, 0x03, 0xa5,
- 0x8f, 0x2a, 0x29, 0xb3, 0xde, 0xbf, 0x85, 0x56, 0xe3, 0x21, 0x94, 0xce, 0xc9, 0x31, 0xaa, 0xe2,
- 0x75, 0x58, 0x15, 0x43, 0x44, 0x46, 0xac, 0xcd, 0x41, 0x77, 0x6f, 0x23, 0x34, 0x33, 0x44, 0x68,
- 0x59, 0x4f, 0x01, 0x77, 0x6f, 0x23, 0x5c, 0x6b, 0x42, 0x9e, 0x47, 0x17, 0xc6, 0x50, 0x3d, 0x6a,
- 0xec, 0x2b, 0x47, 0x5a, 0xb7, 0x37, 0x68, 0x77, 0x3b, 0x8d, 0x23, 0x24, 0xcd, 0x30, 0x55, 0xf9,
- 0xf9, 0x49, 0x5b, 0x55, 0x5a, 0x28, 0x93, 0xc4, 0x7a, 0x4a, 0x63, 0xa0, 0xb4, 0x50, 0xb6, 0xa6,
- 0xc3, 0xe6, 0xb2, 0x3c, 0xb9, 0x74, 0x67, 0x24, 0x96, 0x38, 0x73, 0xce, 0x12, 0x73, 0x5d, 0x0b,
- 0x4b, 0xfc, 0xcf, 0x0c, 0x6c, 0x2c, 0x39, 0x2b, 0x96, 0x0e, 0xf2, 0x13, 0xc8, 0x8b, 0x10, 0x15,
- 0xa7, 0xe7, 0x8d, 0xa5, 0x87, 0x0e, 0x0f, 0xd8, 0x85, 0x13, 0x94, 0xcb, 0x25, 0x2b, 0x88, 0xec,
- 0x39, 0x15, 0x04, 0x53, 0xb1, 0x90, 0xd3, 0x7f, 0xb9, 0x90, 0xd3, 0xc5, 0xb1, 0x77, 0xf7, 0x22,
- 0xc7, 0x1e, 0xc7, 0xbe, 0x5b, 0x6e, 0xcf, 0x2f, 0xc9, 0xed, 0xf7, 0x61, 0x7d, 0x41, 0xd1, 0x85,
- 0x73, 0xec, 0xaf, 0x25, 0x90, 0xcf, 0x73, 0xce, 0x73, 0x32, 0x5d, 0x26, 0x95, 0xe9, 0xee, 0xcf,
- 0x7b, 0xf0, 0xda, 0xf9, 0x8b, 0xb0, 0xb0, 0xd6, 0x5f, 0x49, 0x70, 0x69, 0x79, 0xa5, 0xb8, 0xd4,
- 0x86, 0x8f, 0xa0, 0x30, 0xa1, 0xc1, 0xd8, 0x89, 0xaa, 0xa5, 0xb7, 0x97, 0x9c, 0xc1, 0xac, 0x7b,
- 0x7e, 0xb1, 0x43, 0xa9, 0xe4, 0x21, 0x9e, 0x3d, 0xaf, 0xdc, 0x13, 0xd6, 0x2c, 0x58, 0xfa, 0x9b,
- 0x0c, 0xbc, 0xbc, 0x54, 0xf9, 0x52, 0x43, 0x5f, 0x03, 0x30, 0x6d, 0x77, 0x1a, 0x88, 0x8a, 0x48,
- 0x24, 0xd8, 0x12, 0x47, 0x78, 0xf2, 0x62, 0xc9, 0x73, 0x1a, 0xc4, 0xfd, 0x59, 0xde, 0x0f, 0x02,
- 0xe2, 0x84, 0x7b, 0x33, 0x43, 0x73, 0xdc, 0xd0, 0xd7, 0xcf, 0x99, 0xe9, 0x42, 0x60, 0xbe, 0x07,
- 0x48, 0xb7, 0x4c, 0x6a, 0x07, 0x9a, 0x1f, 0x78, 0x94, 0x4c, 0x4c, 0x7b, 0xc4, 0x4f, 0x90, 0xe2,
- 0x5e, 0x7e, 0x48, 0x2c, 0x9f, 0xaa, 0x6b, 0xa2, 0xbb, 0x1f, 0xf5, 0x32, 0x09, 0x1e, 0x40, 0x5e,
- 0x42, 0xa2, 0x90, 0x92, 0x10, 0xdd, 0xb1, 0x44, 0xed, 0xeb, 0x22, 0x94, 0x13, 0x75, 0x35, 0xbe,
- 0x06, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0xf0, 0x44, 0x99, 0x61, 0xbd, 0xf0, 0xbe,
- 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0xee, 0xb4, 0x22,
- 0xa7, 0x62, 0xd6, 0xd7, 0x65, 0x5d, 0xcd, 0xa8, 0x07, 0xdf, 0x81, 0x0d, 0x2e, 0x31, 0x99, 0x5a,
- 0x81, 0xe9, 0x5a, 0x54, 0x63, 0xb7, 0x37, 0x9f, 0x9f, 0x24, 0xb1, 0x65, 0xeb, 0x8c, 0x71, 0x1c,
- 0x12, 0x98, 0x45, 0x3e, 0x6e, 0xc1, 0x6b, 0x5c, 0x6c, 0x44, 0x6d, 0xea, 0x91, 0x80, 0x6a, 0xf4,
- 0x8b, 0x29, 0xb1, 0x7c, 0x8d, 0xd8, 0x86, 0x36, 0x26, 0xfe, 0x58, 0xde, 0x64, 0x0a, 0xf6, 0x33,
- 0xb2, 0xa4, 0x5e, 0x61, 0xc4, 0x83, 0x90, 0xa7, 0x70, 0x5a, 0xc3, 0x36, 0x3e, 0x26, 0xfe, 0x18,
- 0xef, 0xc1, 0x25, 0xae, 0xc5, 0x0f, 0x3c, 0xd3, 0x1e, 0x69, 0xfa, 0x98, 0xea, 0x8f, 0xb4, 0x69,
- 0x30, 0xbc, 0x27, 0xbf, 0x92, 0x1c, 0x9f, 0x5b, 0xd8, 0xe7, 0x9c, 0x26, 0xa3, 0x9c, 0x04, 0xc3,
- 0x7b, 0xb8, 0x0f, 0x15, 0xb6, 0x18, 0x13, 0xf3, 0x4b, 0xaa, 0x0d, 0x1d, 0x8f, 0x1f, 0x8d, 0xd5,
- 0x25, 0xa9, 0x29, 0xe1, 0xc1, 0x7a, 0x37, 0x14, 0x38, 0x76, 0x0c, 0xba, 0x97, 0xef, 0xf7, 0x14,
- 0xa5, 0xa5, 0x96, 0x23, 0x2d, 0x0f, 0x1c, 0x8f, 0x05, 0xd4, 0xc8, 0x89, 0x1d, 0x5c, 0x16, 0x01,
- 0x35, 0x72, 0x22, 0xf7, 0xde, 0x81, 0x0d, 0x5d, 0x17, 0x73, 0x36, 0x75, 0x2d, 0xbc, 0x63, 0xf9,
- 0x32, 0x4a, 0x39, 0x4b, 0xd7, 0x0f, 0x04, 0x21, 0x8c, 0x71, 0x1f, 0x7f, 0x08, 0x2f, 0xcf, 0x9c,
- 0x95, 0x14, 0x5c, 0x5f, 0x98, 0xe5, 0xbc, 0xe8, 0x1d, 0xd8, 0x70, 0xcf, 0x16, 0x05, 0x71, 0x6a,
- 0x44, 0xf7, 0x6c, 0x5e, 0xec, 0x03, 0xd8, 0x74, 0xc7, 0xee, 0xa2, 0xdc, 0xcd, 0xa4, 0x1c, 0x76,
- 0xc7, 0xee, 0xbc, 0xe0, 0x5b, 0xfc, 0xc2, 0xed, 0x51, 0x9d, 0x04, 0xd4, 0x90, 0x2f, 0x27, 0xe9,
- 0x89, 0x0e, 0xbc, 0x0b, 0x48, 0xd7, 0x35, 0x6a, 0x93, 0x53, 0x8b, 0x6a, 0xc4, 0xa3, 0x36, 0xf1,
- 0xe5, 0xab, 0x49, 0x72, 0x55, 0xd7, 0x15, 0xde, 0xdb, 0xe0, 0x9d, 0xf8, 0x26, 0xac, 0x3b, 0xa7,
- 0x0f, 0x75, 0x11, 0x92, 0x9a, 0xeb, 0xd1, 0xa1, 0xf9, 0x54, 0x7e, 0x93, 0xfb, 0x77, 0x8d, 0x75,
- 0xf0, 0x80, 0xec, 0x71, 0x18, 0xdf, 0x00, 0xa4, 0xfb, 0x63, 0xe2, 0xb9, 0x3c, 0x27, 0xfb, 0x2e,
- 0xd1, 0xa9, 0xfc, 0x96, 0xa0, 0x0a, 0xbc, 0x13, 0xc1, 0x6c, 0x4b, 0xf8, 0x4f, 0xcc, 0x61, 0x10,
- 0x69, 0xbc, 0x2e, 0xb6, 0x04, 0xc7, 0x42, 0x6d, 0x3b, 0x80, 0x98, 0x2b, 0x52, 0x03, 0xef, 0x70,
- 0x5a, 0xd5, 0x1d, 0xbb, 0xc9, 0x71, 0xdf, 0x80, 0x55, 0xc6, 0x9c, 0x0d, 0x7a, 0x43, 0x14, 0x64,
- 0xee, 0x38, 0x31, 0xe2, 0x0f, 0x56, 0x1b, 0xd7, 0xf6, 0xa0, 0x92, 0x8c, 0x4f, 0x5c, 0x02, 0x11,
- 0xa1, 0x48, 0x62, 0xc5, 0x4a, 0xb3, 0xdb, 0x62, 0x65, 0xc6, 0xe7, 0x0a, 0xca, 0xb0, 0x72, 0xe7,
- 0xa8, 0x3d, 0x50, 0x34, 0xf5, 0xa4, 0x33, 0x68, 0x1f, 0x2b, 0x28, 0x9b, 0xa8, 0xab, 0x0f, 0x73,
- 0xc5, 0xb7, 0xd1, 0xf5, 0xda, 0x37, 0x19, 0xa8, 0xa6, 0x2f, 0x4a, 0xf8, 0xff, 0xe1, 0x72, 0xf4,
- 0xaa, 0xe1, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0xe3, 0x4c, 0x88, 0x38, 0xc4, 0xe2, 0xa5, 0xdb,
- 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0x5b, 0x4c, 0x48, 0x80, 0x8f, 0xe0, 0xaa, 0xed,
- 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0x4f, 0xd2, 0x88, 0xae, 0x53, 0xdf, 0x77,
- 0xc4, 0x81, 0x15, 0x6b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x96, 0xc9, 0x1b, 0x21, 0x75, 0x2e,
- 0xcc, 0xb2, 0xe7, 0x85, 0xd9, 0x2b, 0x50, 0x9a, 0x10, 0x57, 0xa3, 0x76, 0xe0, 0x9d, 0xf1, 0xf2,
- 0xb8, 0xa8, 0x16, 0x27, 0xc4, 0x55, 0x58, 0xfb, 0x85, 0xdc, 0x52, 0x0e, 0x73, 0xc5, 0x22, 0x2a,
- 0x1d, 0xe6, 0x8a, 0x25, 0x04, 0xb5, 0x7f, 0x64, 0xa1, 0x92, 0x2c, 0x97, 0xd9, 0xed, 0x43, 0xe7,
- 0x27, 0x8b, 0xc4, 0x73, 0xcf, 0x1b, 0xdf, 0x5a, 0x5c, 0xd7, 0x9b, 0xec, 0xc8, 0xd9, 0x2b, 0x88,
- 0x22, 0x56, 0x15, 0x92, 0xec, 0xb8, 0x67, 0xd9, 0x86, 0x8a, 0xa2, 0xa1, 0xa8, 0x86, 0x2d, 0x7c,
- 0x00, 0x85, 0x87, 0x3e, 0xd7, 0x5d, 0xe0, 0xba, 0xdf, 0xfc, 0x76, 0xdd, 0x87, 0x7d, 0xae, 0xbc,
- 0x74, 0xd8, 0xd7, 0x3a, 0x5d, 0xf5, 0xb8, 0x71, 0xa4, 0x86, 0xe2, 0xf8, 0x0a, 0xe4, 0x2c, 0xf2,
- 0xe5, 0x59, 0xfa, 0x70, 0xe2, 0xd0, 0x45, 0x17, 0xe1, 0x0a, 0xe4, 0x9e, 0x50, 0xf2, 0x28, 0x7d,
- 0x24, 0x70, 0xe8, 0x07, 0xdc, 0x0c, 0xbb, 0x90, 0xe7, 0xfe, 0xc2, 0x00, 0xa1, 0xc7, 0xd0, 0x4b,
- 0xb8, 0x08, 0xb9, 0x66, 0x57, 0x65, 0x1b, 0x02, 0x41, 0x45, 0xa0, 0x5a, 0xaf, 0xad, 0x34, 0x15,
- 0x94, 0xa9, 0xdd, 0x81, 0x82, 0x70, 0x02, 0xdb, 0x2c, 0xb1, 0x1b, 0xd0, 0x4b, 0x61, 0x33, 0xd4,
- 0x21, 0x45, 0xbd, 0x27, 0xc7, 0xfb, 0x8a, 0x8a, 0x32, 0xe9, 0xa5, 0xce, 0xa1, 0x7c, 0xcd, 0x87,
- 0x4a, 0xb2, 0x5e, 0x7e, 0x31, 0x77, 0xe1, 0xbf, 0x4a, 0x50, 0x4e, 0xd4, 0xbf, 0xac, 0x70, 0x21,
- 0x96, 0xe5, 0x3c, 0xd1, 0x88, 0x65, 0x12, 0x3f, 0x0c, 0x0d, 0xe0, 0x50, 0x83, 0x21, 0x17, 0x5d,
- 0xba, 0x17, 0xb4, 0x45, 0xf2, 0xa8, 0x50, 0xfb, 0xa3, 0x04, 0x68, 0xbe, 0x00, 0x9d, 0x33, 0x53,
- 0xfa, 0x31, 0xcd, 0xac, 0xfd, 0x41, 0x82, 0x6a, 0xba, 0xea, 0x9c, 0x33, 0xef, 0xda, 0x8f, 0x6a,
- 0xde, 0xdf, 0x33, 0xb0, 0x9a, 0xaa, 0x35, 0x2f, 0x6a, 0xdd, 0x17, 0xb0, 0x6e, 0x1a, 0x74, 0xe2,
- 0x3a, 0x01, 0xb5, 0xf5, 0x33, 0xcd, 0xa2, 0x8f, 0xa9, 0x25, 0xd7, 0x78, 0xd2, 0xd8, 0xfd, 0xf6,
- 0x6a, 0xb6, 0xde, 0x9e, 0xc9, 0x1d, 0x31, 0xb1, 0xbd, 0x8d, 0x76, 0x4b, 0x39, 0xee, 0x75, 0x07,
- 0x4a, 0xa7, 0xf9, 0x99, 0x76, 0xd2, 0xf9, 0x59, 0xa7, 0xfb, 0x49, 0x47, 0x45, 0xe6, 0x1c, 0xed,
- 0x07, 0xdc, 0xf6, 0x3d, 0x40, 0xf3, 0x46, 0xe1, 0xcb, 0xb0, 0xcc, 0x2c, 0xf4, 0x12, 0xde, 0x80,
- 0xb5, 0x4e, 0x57, 0xeb, 0xb7, 0x5b, 0x8a, 0xa6, 0x3c, 0x78, 0xa0, 0x34, 0x07, 0x7d, 0xf1, 0x3e,
- 0x11, 0xb3, 0x07, 0xa9, 0x0d, 0x5e, 0xfb, 0x7d, 0x16, 0x36, 0x96, 0x58, 0x82, 0x1b, 0xe1, 0xcd,
- 0x42, 0x5c, 0x76, 0xde, 0xbd, 0x88, 0xf5, 0x75, 0x56, 0x10, 0xf4, 0x88, 0x17, 0x84, 0x17, 0x91,
- 0x1b, 0xc0, 0xbc, 0x64, 0x07, 0xe6, 0xd0, 0xa4, 0x5e, 0xf8, 0x9c, 0x23, 0xae, 0x1b, 0x6b, 0x33,
- 0x5c, 0xbc, 0xe8, 0xfc, 0x1f, 0x60, 0xd7, 0xf1, 0xcd, 0xc0, 0x7c, 0x4c, 0x35, 0xd3, 0x8e, 0xde,
- 0x7e, 0xd8, 0xf5, 0x23, 0xa7, 0xa2, 0xa8, 0xa7, 0x6d, 0x07, 0x31, 0xdb, 0xa6, 0x23, 0x32, 0xc7,
- 0x66, 0xc9, 0x3c, 0xab, 0xa2, 0xa8, 0x27, 0x66, 0x5f, 0x83, 0x8a, 0xe1, 0x4c, 0x59, 0x4d, 0x26,
- 0x78, 0xec, 0xec, 0x90, 0xd4, 0xb2, 0xc0, 0x62, 0x4a, 0x58, 0x6d, 0xcf, 0x1e, 0x9d, 0x2a, 0x6a,
- 0x59, 0x60, 0x82, 0x72, 0x1d, 0xd6, 0xc8, 0x68, 0xe4, 0x31, 0xe5, 0x91, 0x22, 0x71, 0x7f, 0xa8,
- 0xc6, 0x30, 0x27, 0x6e, 0x1d, 0x42, 0x31, 0xf2, 0x03, 0x3b, 0xaa, 0x99, 0x27, 0x34, 0x57, 0x5c,
- 0x8a, 0x33, 0x3b, 0x25, 0xb5, 0x68, 0x47, 0x9d, 0xd7, 0xa0, 0x62, 0xfa, 0xda, 0xec, 0x0d, 0x3d,
- 0xb3, 0x9d, 0xd9, 0x29, 0xaa, 0x65, 0xd3, 0x8f, 0xdf, 0x1f, 0x6b, 0x5f, 0x65, 0xa0, 0x9a, 0xfe,
- 0x06, 0x80, 0x5b, 0x50, 0xb4, 0x1c, 0x9d, 0xf0, 0xd0, 0x12, 0x1f, 0xa0, 0x76, 0x9e, 0xf3, 0xd9,
- 0xa0, 0x7e, 0x14, 0xf2, 0xd5, 0x58, 0x72, 0xeb, 0x6f, 0x12, 0x14, 0x23, 0x18, 0x5f, 0x82, 0x9c,
- 0x4b, 0x82, 0x31, 0x57, 0x97, 0xdf, 0xcf, 0x20, 0x49, 0xe5, 0x6d, 0x86, 0xfb, 0x2e, 0xb1, 0x79,
- 0x08, 0x84, 0x38, 0x6b, 0xb3, 0x75, 0xb5, 0x28, 0x31, 0xf8, 0xe5, 0xc4, 0x99, 0x4c, 0xa8, 0x1d,
- 0xf8, 0xd1, 0xba, 0x86, 0x78, 0x33, 0x84, 0xf1, 0x3b, 0xb0, 0x1e, 0x78, 0xc4, 0xb4, 0x52, 0xdc,
- 0x1c, 0xe7, 0xa2, 0xa8, 0x23, 0x26, 0xef, 0xc1, 0x95, 0x48, 0xaf, 0x41, 0x03, 0xa2, 0x8f, 0xa9,
- 0x31, 0x13, 0x2a, 0xf0, 0x47, 0x88, 0xcb, 0x21, 0xa1, 0x15, 0xf6, 0x47, 0xb2, 0xb5, 0x6f, 0x24,
- 0x58, 0x8f, 0xae, 0x53, 0x46, 0xec, 0xac, 0x63, 0x00, 0x62, 0xdb, 0x4e, 0x90, 0x74, 0xd7, 0x62,
- 0x28, 0x2f, 0xc8, 0xd5, 0x1b, 0xb1, 0x90, 0x9a, 0x50, 0xb0, 0x35, 0x01, 0x98, 0xf5, 0x9c, 0xeb,
- 0xb6, 0xab, 0x50, 0x0e, 0x3f, 0xf0, 0xf0, 0xaf, 0x84, 0xe2, 0x02, 0x0e, 0x02, 0x62, 0xf7, 0x2e,
- 0xbc, 0x09, 0xf9, 0x53, 0x3a, 0x32, 0xed, 0xf0, 0xd9, 0x56, 0x34, 0xa2, 0x67, 0x92, 0x5c, 0xfc,
- 0x4c, 0xb2, 0xff, 0x5b, 0x09, 0x36, 0x74, 0x67, 0x32, 0x6f, 0xef, 0x3e, 0x9a, 0x7b, 0x05, 0xf0,
- 0x3f, 0x96, 0x3e, 0xff, 0x68, 0x64, 0x06, 0xe3, 0xe9, 0x69, 0x5d, 0x77, 0x26, 0xbb, 0x23, 0xc7,
- 0x22, 0xf6, 0x68, 0xf6, 0x99, 0x93, 0xff, 0xd1, 0xdf, 0x1d, 0x51, 0xfb, 0xdd, 0x91, 0x93, 0xf8,
- 0xe8, 0x79, 0x7f, 0xf6, 0xf7, 0xbf, 0x92, 0xf4, 0xa7, 0x4c, 0xf6, 0xa0, 0xb7, 0xff, 0xe7, 0xcc,
- 0xd6, 0x81, 0x18, 0xae, 0x17, 0xb9, 0x47, 0xa5, 0x43, 0x8b, 0xea, 0x6c, 0xca, 0xff, 0x0b, 0x00,
- 0x00, 0xff, 0xff, 0x1a, 0x28, 0x25, 0x79, 0x42, 0x1d, 0x00, 0x00,
+type FileDescriptorSet = descriptorpb.FileDescriptorSet
+type FileDescriptorProto = descriptorpb.FileDescriptorProto
+type DescriptorProto = descriptorpb.DescriptorProto
+type ExtensionRangeOptions = descriptorpb.ExtensionRangeOptions
+type FieldDescriptorProto = descriptorpb.FieldDescriptorProto
+type OneofDescriptorProto = descriptorpb.OneofDescriptorProto
+type EnumDescriptorProto = descriptorpb.EnumDescriptorProto
+type EnumValueDescriptorProto = descriptorpb.EnumValueDescriptorProto
+type ServiceDescriptorProto = descriptorpb.ServiceDescriptorProto
+type MethodDescriptorProto = descriptorpb.MethodDescriptorProto
+
+const Default_MethodDescriptorProto_ClientStreaming = descriptorpb.Default_MethodDescriptorProto_ClientStreaming
+const Default_MethodDescriptorProto_ServerStreaming = descriptorpb.Default_MethodDescriptorProto_ServerStreaming
+
+type FileOptions = descriptorpb.FileOptions
+
+const Default_FileOptions_JavaMultipleFiles = descriptorpb.Default_FileOptions_JavaMultipleFiles
+const Default_FileOptions_JavaStringCheckUtf8 = descriptorpb.Default_FileOptions_JavaStringCheckUtf8
+const Default_FileOptions_OptimizeFor = descriptorpb.Default_FileOptions_OptimizeFor
+const Default_FileOptions_CcGenericServices = descriptorpb.Default_FileOptions_CcGenericServices
+const Default_FileOptions_JavaGenericServices = descriptorpb.Default_FileOptions_JavaGenericServices
+const Default_FileOptions_PyGenericServices = descriptorpb.Default_FileOptions_PyGenericServices
+const Default_FileOptions_PhpGenericServices = descriptorpb.Default_FileOptions_PhpGenericServices
+const Default_FileOptions_Deprecated = descriptorpb.Default_FileOptions_Deprecated
+const Default_FileOptions_CcEnableArenas = descriptorpb.Default_FileOptions_CcEnableArenas
+
+type MessageOptions = descriptorpb.MessageOptions
+
+const Default_MessageOptions_MessageSetWireFormat = descriptorpb.Default_MessageOptions_MessageSetWireFormat
+const Default_MessageOptions_NoStandardDescriptorAccessor = descriptorpb.Default_MessageOptions_NoStandardDescriptorAccessor
+const Default_MessageOptions_Deprecated = descriptorpb.Default_MessageOptions_Deprecated
+
+type FieldOptions = descriptorpb.FieldOptions
+
+const Default_FieldOptions_Ctype = descriptorpb.Default_FieldOptions_Ctype
+const Default_FieldOptions_Jstype = descriptorpb.Default_FieldOptions_Jstype
+const Default_FieldOptions_Lazy = descriptorpb.Default_FieldOptions_Lazy
+const Default_FieldOptions_Deprecated = descriptorpb.Default_FieldOptions_Deprecated
+const Default_FieldOptions_Weak = descriptorpb.Default_FieldOptions_Weak
+
+type OneofOptions = descriptorpb.OneofOptions
+type EnumOptions = descriptorpb.EnumOptions
+
+const Default_EnumOptions_Deprecated = descriptorpb.Default_EnumOptions_Deprecated
+
+type EnumValueOptions = descriptorpb.EnumValueOptions
+
+const Default_EnumValueOptions_Deprecated = descriptorpb.Default_EnumValueOptions_Deprecated
+
+type ServiceOptions = descriptorpb.ServiceOptions
+
+const Default_ServiceOptions_Deprecated = descriptorpb.Default_ServiceOptions_Deprecated
+
+type MethodOptions = descriptorpb.MethodOptions
+
+const Default_MethodOptions_Deprecated = descriptorpb.Default_MethodOptions_Deprecated
+const Default_MethodOptions_IdempotencyLevel = descriptorpb.Default_MethodOptions_IdempotencyLevel
+
+type UninterpretedOption = descriptorpb.UninterpretedOption
+type SourceCodeInfo = descriptorpb.SourceCodeInfo
+type GeneratedCodeInfo = descriptorpb.GeneratedCodeInfo
+type DescriptorProto_ExtensionRange = descriptorpb.DescriptorProto_ExtensionRange
+type DescriptorProto_ReservedRange = descriptorpb.DescriptorProto_ReservedRange
+type EnumDescriptorProto_EnumReservedRange = descriptorpb.EnumDescriptorProto_EnumReservedRange
+type UninterpretedOption_NamePart = descriptorpb.UninterpretedOption_NamePart
+type SourceCodeInfo_Location = descriptorpb.SourceCodeInfo_Location
+type GeneratedCodeInfo_Annotation = descriptorpb.GeneratedCodeInfo_Annotation
+
+var File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto protoreflect.FileDescriptor
+
+var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc = []byte{
+ 0x0a, 0x44, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72,
+ 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72,
+ 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70,
+ 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74,
+ 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x40, 0x5a, 0x3e, 0x67, 0x69, 0x74, 0x68,
+ 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65,
+ 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x3b,
+ 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x32,
+}
+
+var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_init() }
+func file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_init() {
+ if File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto != nil {
+ return
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto = out.File
+ file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc = nil
+ file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes = nil
+ file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
deleted file mode 100644
index 8697a50de..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
+++ /dev/null
@@ -1,872 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// The messages in this file describe the definitions found in .proto files.
-// A valid .proto file can be translated directly to a FileDescriptorProto
-// without any other information (e.g. without reading its imports).
-
-
-syntax = "proto2";
-
-package google.protobuf;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "DescriptorProtos";
-option csharp_namespace = "Google.Protobuf.Reflection";
-option objc_class_prefix = "GPB";
-option cc_enable_arenas = true;
-
-// descriptor.proto must be optimized for speed because reflection-based
-// algorithms don't work during bootstrapping.
-option optimize_for = SPEED;
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-message FileDescriptorSet {
- repeated FileDescriptorProto file = 1;
-}
-
-// Describes a complete .proto file.
-message FileDescriptorProto {
- optional string name = 1; // file name, relative to root of source tree
- optional string package = 2; // e.g. "foo", "foo.bar", etc.
-
- // Names of files imported by this file.
- repeated string dependency = 3;
- // Indexes of the public imported files in the dependency list above.
- repeated int32 public_dependency = 10;
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- repeated int32 weak_dependency = 11;
-
- // All top-level definitions in this file.
- repeated DescriptorProto message_type = 4;
- repeated EnumDescriptorProto enum_type = 5;
- repeated ServiceDescriptorProto service = 6;
- repeated FieldDescriptorProto extension = 7;
-
- optional FileOptions options = 8;
-
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- optional SourceCodeInfo source_code_info = 9;
-
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- optional string syntax = 12;
-}
-
-// Describes a message type.
-message DescriptorProto {
- optional string name = 1;
-
- repeated FieldDescriptorProto field = 2;
- repeated FieldDescriptorProto extension = 6;
-
- repeated DescriptorProto nested_type = 3;
- repeated EnumDescriptorProto enum_type = 4;
-
- message ExtensionRange {
- optional int32 start = 1;
- optional int32 end = 2;
-
- optional ExtensionRangeOptions options = 3;
- }
- repeated ExtensionRange extension_range = 5;
-
- repeated OneofDescriptorProto oneof_decl = 8;
-
- optional MessageOptions options = 7;
-
- // Range of reserved tag numbers. Reserved tag numbers may not be used by
- // fields or extension ranges in the same message. Reserved ranges may
- // not overlap.
- message ReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Exclusive.
- }
- repeated ReservedRange reserved_range = 9;
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- repeated string reserved_name = 10;
-}
-
-message ExtensionRangeOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-// Describes a field within a message.
-message FieldDescriptorProto {
- enum Type {
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- TYPE_DOUBLE = 1;
- TYPE_FLOAT = 2;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- TYPE_INT64 = 3;
- TYPE_UINT64 = 4;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- TYPE_INT32 = 5;
- TYPE_FIXED64 = 6;
- TYPE_FIXED32 = 7;
- TYPE_BOOL = 8;
- TYPE_STRING = 9;
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- TYPE_GROUP = 10;
- TYPE_MESSAGE = 11; // Length-delimited aggregate.
-
- // New in version 2.
- TYPE_BYTES = 12;
- TYPE_UINT32 = 13;
- TYPE_ENUM = 14;
- TYPE_SFIXED32 = 15;
- TYPE_SFIXED64 = 16;
- TYPE_SINT32 = 17; // Uses ZigZag encoding.
- TYPE_SINT64 = 18; // Uses ZigZag encoding.
- };
-
- enum Label {
- // 0 is reserved for errors
- LABEL_OPTIONAL = 1;
- LABEL_REQUIRED = 2;
- LABEL_REPEATED = 3;
- };
-
- optional string name = 1;
- optional int32 number = 3;
- optional Label label = 4;
-
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- optional Type type = 5;
-
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- optional string type_name = 6;
-
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- optional string extendee = 2;
-
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- // TODO(kenton): Base-64 encode?
- optional string default_value = 7;
-
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- optional int32 oneof_index = 9;
-
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- optional string json_name = 10;
-
- optional FieldOptions options = 8;
-}
-
-// Describes a oneof.
-message OneofDescriptorProto {
- optional string name = 1;
- optional OneofOptions options = 2;
-}
-
-// Describes an enum type.
-message EnumDescriptorProto {
- optional string name = 1;
-
- repeated EnumValueDescriptorProto value = 2;
-
- optional EnumOptions options = 3;
-
- // Range of reserved numeric values. Reserved values may not be used by
- // entries in the same enum. Reserved ranges may not overlap.
- //
- // Note that this is distinct from DescriptorProto.ReservedRange in that it
- // is inclusive such that it can appropriately represent the entire int32
- // domain.
- message EnumReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Inclusive.
- }
-
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- repeated EnumReservedRange reserved_range = 4;
-
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- repeated string reserved_name = 5;
-}
-
-// Describes a value within an enum.
-message EnumValueDescriptorProto {
- optional string name = 1;
- optional int32 number = 2;
-
- optional EnumValueOptions options = 3;
-}
-
-// Describes a service.
-message ServiceDescriptorProto {
- optional string name = 1;
- repeated MethodDescriptorProto method = 2;
-
- optional ServiceOptions options = 3;
-}
-
-// Describes a method of a service.
-message MethodDescriptorProto {
- optional string name = 1;
-
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- optional string input_type = 2;
- optional string output_type = 3;
-
- optional MethodOptions options = 4;
-
- // Identifies if client streams multiple client messages
- optional bool client_streaming = 5 [default=false];
- // Identifies if server streams multiple server messages
- optional bool server_streaming = 6 [default=false];
-}
-
-
-// ===================================================================
-// Options
-
-// Each of the definitions above may have "options" attached. These are
-// just annotations which may cause code to be generated slightly differently
-// or may contain hints for code that manipulates protocol messages.
-//
-// Clients may define custom options as extensions of the *Options messages.
-// These extensions may not yet be known at parsing time, so the parser cannot
-// store the values in them. Instead it stores them in a field in the *Options
-// message called uninterpreted_option. This field must have the same name
-// across all *Options messages. We then use this field to populate the
-// extensions when we build a descriptor, at which point all protos have been
-// parsed and so all extensions are known.
-//
-// Extension numbers for custom options may be chosen as follows:
-// * For options which will only be used within a single application or
-// organization, or for experimental options, use field numbers 50000
-// through 99999. It is up to you to ensure that you do not use the
-// same number for multiple options.
-// * For options which will be published and used publicly by multiple
-// independent entities, e-mail protobuf-global-extension-registry@google.com
-// to reserve extension numbers. Simply provide your project name (e.g.
-// Objective-C plugin) and your project website (if available) -- there's no
-// need to explain how you intend to use them. Usually you only need one
-// extension number. You can declare multiple options with only one extension
-// number by putting them in a sub-message. See the Custom Options section of
-// the docs for examples:
-// https://developers.google.com/protocol-buffers/docs/proto#options
-// If this turns out to be popular, a web service will be set up
-// to automatically assign option numbers.
-
-
-message FileOptions {
-
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- optional string java_package = 1;
-
-
- // If set, all the classes from the .proto file are wrapped in a single
- // outer class with the given name. This applies to both Proto1
- // (equivalent to the old "--one_java_file" option) and Proto2 (where
- // a .proto always translates to a single class, but you may want to
- // explicitly choose the class name).
- optional string java_outer_classname = 8;
-
- // If set true, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the outer class
- // named by java_outer_classname. However, the outer class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- optional bool java_multiple_files = 10 [default=false];
-
- // This option does nothing.
- optional bool java_generate_equals_and_hash = 20 [deprecated=true];
-
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- optional bool java_string_check_utf8 = 27 [default=false];
-
-
- // Generated classes can be optimized for speed or code size.
- enum OptimizeMode {
- SPEED = 1; // Generate complete code for parsing, serialization,
- // etc.
- CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
- LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
- }
- optional OptimizeMode optimize_for = 9 [default=SPEED];
-
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- optional string go_package = 11;
-
-
-
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- optional bool cc_generic_services = 16 [default=false];
- optional bool java_generic_services = 17 [default=false];
- optional bool py_generic_services = 18 [default=false];
- optional bool php_generic_services = 42 [default=false];
-
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- optional bool deprecated = 23 [default=false];
-
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- optional bool cc_enable_arenas = 31 [default=false];
-
-
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- optional string objc_class_prefix = 36;
-
- // Namespace for generated classes; defaults to the package.
- optional string csharp_namespace = 37;
-
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- optional string swift_prefix = 39;
-
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- optional string php_class_prefix = 40;
-
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- optional string php_namespace = 41;
-
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message.
- // See the documentation for the "Options" section above.
- extensions 1000 to max;
-
- reserved 38;
-}
-
-message MessageOptions {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- optional bool message_set_wire_format = 1 [default=false];
-
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- optional bool no_standard_descriptor_accessor = 2 [default=false];
-
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- optional bool deprecated = 3 [default=false];
-
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementions still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- optional bool map_entry = 7;
-
- reserved 8; // javalite_serializable
- reserved 9; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message FieldOptions {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- optional CType ctype = 1 [default = STRING];
- enum CType {
- // Default mode.
- STRING = 0;
-
- CORD = 1;
-
- STRING_PIECE = 2;
- }
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- optional bool packed = 2;
-
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- optional JSType jstype = 6 [default = JS_NORMAL];
- enum JSType {
- // Use the default type.
- JS_NORMAL = 0;
-
- // Use JavaScript strings.
- JS_STRING = 1;
-
- // Use JavaScript numbers.
- JS_NUMBER = 2;
- }
-
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- optional bool lazy = 5 [default=false];
-
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- optional bool deprecated = 3 [default=false];
-
- // For Google-internal migration only. Do not use.
- optional bool weak = 10 [default=false];
-
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-
- reserved 4; // removed jtype
-}
-
-message OneofOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumOptions {
-
- // Set this option to true to allow mapping different tag names to the same
- // value.
- optional bool allow_alias = 2;
-
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- optional bool deprecated = 3 [default=false];
-
- reserved 5; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumValueOptions {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- optional bool deprecated = 1 [default=false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message ServiceOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- optional bool deprecated = 33 [default=false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message MethodOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- optional bool deprecated = 33 [default=false];
-
- // Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
- // or neither? HTTP based RPC implementation may choose GET verb for safe
- // methods, and PUT verb for idempotent methods instead of the default POST.
- enum IdempotencyLevel {
- IDEMPOTENCY_UNKNOWN = 0;
- NO_SIDE_EFFECTS = 1; // implies idempotent
- IDEMPOTENT = 2; // idempotent, but may have side effects
- }
- optional IdempotencyLevel idempotency_level =
- 34 [default=IDEMPOTENCY_UNKNOWN];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-message UninterpretedOption {
- // The name of the uninterpreted option. Each string represents a segment in
- // a dot-separated name. is_extension is true iff a segment represents an
- // extension (denoted with parentheses in options specs in .proto files).
- // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
- // "foo.(bar.baz).qux".
- message NamePart {
- required string name_part = 1;
- required bool is_extension = 2;
- }
- repeated NamePart name = 2;
-
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- optional string identifier_value = 3;
- optional uint64 positive_int_value = 4;
- optional int64 negative_int_value = 5;
- optional double double_value = 6;
- optional bytes string_value = 7;
- optional string aggregate_value = 8;
-}
-
-// ===================================================================
-// Optional source code info
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-message SourceCodeInfo {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendent. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- repeated Location location = 1;
- message Location {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- repeated int32 path = 1 [packed=true];
-
- // Always has exactly three or four elements: start line, start column,
- // end line (optional, otherwise assumed same as start line), end column.
- // These are packed into a single field for efficiency. Note that line
- // and column numbers are zero-based -- typically you will want to add
- // 1 to each before displaying to a user.
- repeated int32 span = 2 [packed=true];
-
- // If this SourceCodeInfo represents a complete declaration, these are any
- // comments appearing before and after the declaration which appear to be
- // attached to the declaration.
- //
- // A series of line comments appearing on consecutive lines, with no other
- // tokens appearing on those lines, will be treated as a single comment.
- //
- // leading_detached_comments will keep paragraphs of comments that appear
- // before (but not connected to) the current element. Each paragraph,
- // separated by empty lines, will be one comment element in the repeated
- // field.
- //
- // Only the comment content is provided; comment markers (e.g. //) are
- // stripped out. For block comments, leading whitespace and an asterisk
- // will be stripped from the beginning of each line other than the first.
- // Newlines are included in the output.
- //
- // Examples:
- //
- // optional int32 foo = 1; // Comment attached to foo.
- // // Comment attached to bar.
- // optional int32 bar = 2;
- //
- // optional string baz = 3;
- // // Comment attached to baz.
- // // Another line attached to baz.
- //
- // // Comment attached to qux.
- // //
- // // Another line attached to qux.
- // optional double qux = 4;
- //
- // // Detached comment for corge. This is not leading or trailing comments
- // // to qux or corge because there are blank lines separating it from
- // // both.
- //
- // // Detached comment for corge paragraph 2.
- //
- // optional string corge = 5;
- // /* Block comment attached
- // * to corge. Leading asterisks
- // * will be removed. */
- // /* Block comment attached to
- // * grault. */
- // optional int32 grault = 6;
- //
- // // ignored detached comments.
- optional string leading_comments = 3;
- optional string trailing_comments = 4;
- repeated string leading_detached_comments = 6;
- }
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-message GeneratedCodeInfo {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- repeated Annotation annotation = 1;
- message Annotation {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- repeated int32 path = 1 [packed=true];
-
- // Identifies the filesystem path to the original source .proto.
- optional string source_file = 2;
-
- // Identifies the starting offset in bytes in the generated code
- // that relates to the identified object.
- optional int32 begin = 3;
-
- // Identifies the ending offset in bytes in the generated code that
- // relates to the identified offset. The end offset should be one past
- // the last relevant byte (so the length of the text = end - begin).
- optional int32 end = 4;
- }
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go
deleted file mode 100644
index 0d6055d61..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
- A plugin for the Google protocol buffer compiler to generate Go code.
- Run it by building this program and putting it in your path with the name
- protoc-gen-go
- That word 'go' at the end becomes part of the option string set for the
- protocol compiler, so once the protocol compiler (protoc) is installed
- you can run
- protoc --go_out=output_directory input_directory/file.proto
- to generate Go bindings for the protocol defined by file.proto.
- With that input, the output will be written to
- output_directory/file.pb.go
-
- The generated code is documented in the package comment for
- the library.
-
- See the README and documentation for protocol buffers to learn more:
- https://developers.google.com/protocol-buffers/
-
-*/
-package documentation
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go
index e0aba85f3..12ff35b94 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go
@@ -1,39 +1,14 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package generator is deprecated.
//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
+// This package is excluded from the Go protocol buffer compatibility guarantee
+// and may be deleted at some point in the future.
//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
- The code generator for the plugin for the Google protocol buffer compiler.
- It generates Go code from the protocol buffer description files read by the
- main routine.
-*/
+// Deprecated: Use the "google.golang.org/protobuf/compiler/protogen" package
+// instead to write protoc plugins in Go.
package generator
import (
@@ -43,6 +18,7 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
+ "go/ast"
"go/build"
"go/parser"
"go/printer"
@@ -63,11 +39,18 @@ import (
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
+func init() {
+ fmt.Fprint(os.Stderr,
+ "WARNING: Package \"github.com/golang/protobuf/protoc-gen-go/generator\" is deprecated.\n"+
+ "\tA future release of golang/protobuf will delete this package,\n"+
+ "\twhich has long been excluded from the compatibility promise.\n\n")
+}
+
// generatedCodeVersion indicates a version of the generated code.
// It is incremented whenever an incompatibility between the generated code and
// proto package is introduced; the generated code references
// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
-const generatedCodeVersion = 2
+const generatedCodeVersion = 3
// A Plugin provides functionality to add to the output during Go code generation,
// such as to produce RPC stubs.
@@ -271,7 +254,6 @@ type FileDescriptor struct {
// This is used for supporting public imports.
exported map[Object][]symbol
- fingerprint string // Fingerprint of this file's contents.
importPath GoImportPath // Import path of this file's package.
packageName GoPackageName // Name of this file's Go package.
@@ -282,8 +264,8 @@ type FileDescriptor struct {
// to the compressed bytes of this descriptor. It is not exported, so
// it is only valid inside the generated package.
func (d *FileDescriptor) VarName() string {
- name := strings.Map(badToUnderscore, baseName(d.GetName()))
- return fmt.Sprintf("fileDescriptor_%s_%s", name, d.fingerprint)
+ h := sha256.Sum256([]byte(d.GetName()))
+ return fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(h[:8]))
}
// goPackageOption interprets the file's go_package option.
@@ -340,7 +322,7 @@ func (d *FileDescriptor) addExport(obj Object, sym symbol) {
type symbol interface {
// GenerateAlias should generate an appropriate alias
// for the symbol from the named package.
- GenerateAlias(g *Generator, pkg GoPackageName)
+ GenerateAlias(g *Generator, filename string, pkg GoPackageName)
}
type messageSymbol struct {
@@ -356,7 +338,8 @@ type getterSymbol struct {
genType bool // whether typ contains a generated type (message/group/enum)
}
-func (ms *messageSymbol) GenerateAlias(g *Generator, pkg GoPackageName) {
+func (ms *messageSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
+ g.P("// ", ms.sym, " from public import ", filename)
g.P("type ", ms.sym, " = ", pkg, ".", ms.sym)
for _, name := range ms.oneofTypes {
g.P("type ", name, " = ", pkg, ".", name)
@@ -368,8 +351,9 @@ type enumSymbol struct {
proto3 bool // Whether this came from a proto3 file.
}
-func (es enumSymbol) GenerateAlias(g *Generator, pkg GoPackageName) {
+func (es enumSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
s := es.name
+ g.P("// ", s, " from public import ", filename)
g.P("type ", s, " = ", pkg, ".", s)
g.P("var ", s, "_name = ", pkg, ".", s, "_name")
g.P("var ", s, "_value = ", pkg, ".", s, "_value")
@@ -381,7 +365,7 @@ type constOrVarSymbol struct {
cast string // if non-empty, a type cast is required (used for enums)
}
-func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg GoPackageName) {
+func (cs constOrVarSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
v := string(pkg) + "." + cs.sym
if cs.cast != "" {
v = cs.cast + "(" + v + ")"
@@ -418,6 +402,7 @@ type Generator struct {
packageNames map[GoImportPath]GoPackageName // Imported package names in the current file.
usedPackages map[GoImportPath]bool // Packages used in current file.
usedPackageNames map[GoPackageName]bool // Package names used in the current file.
+ addedImports map[GoImportPath]bool // Additional imports to emit.
typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
init []string // Lines to emit in the init function.
indent string
@@ -532,7 +517,7 @@ func (g *Generator) GoPackageName(importPath GoImportPath) GoPackageName {
return name
}
name := cleanPackageName(baseName(string(importPath)))
- for i, orig := 1, name; g.usedPackageNames[name]; i++ {
+ for i, orig := 1, name; g.usedPackageNames[name] || isGoPredeclaredIdentifier[string(name)]; i++ {
name = orig + GoPackageName(strconv.Itoa(i))
}
g.packageNames[importPath] = name
@@ -540,6 +525,13 @@ func (g *Generator) GoPackageName(importPath GoImportPath) GoPackageName {
return name
}
+// AddImport adds a package to the generated file's import section.
+// It returns the name used for the package.
+func (g *Generator) AddImport(importPath GoImportPath) GoPackageName {
+ g.addedImports[importPath] = true
+ return g.GoPackageName(importPath)
+}
+
var globalPackageNames = map[GoPackageName]bool{
"fmt": true,
"math": true,
@@ -585,9 +577,51 @@ var isGoKeyword = map[string]bool{
"var": true,
}
+var isGoPredeclaredIdentifier = map[string]bool{
+ "append": true,
+ "bool": true,
+ "byte": true,
+ "cap": true,
+ "close": true,
+ "complex": true,
+ "complex128": true,
+ "complex64": true,
+ "copy": true,
+ "delete": true,
+ "error": true,
+ "false": true,
+ "float32": true,
+ "float64": true,
+ "imag": true,
+ "int": true,
+ "int16": true,
+ "int32": true,
+ "int64": true,
+ "int8": true,
+ "iota": true,
+ "len": true,
+ "make": true,
+ "new": true,
+ "nil": true,
+ "panic": true,
+ "print": true,
+ "println": true,
+ "real": true,
+ "recover": true,
+ "rune": true,
+ "string": true,
+ "true": true,
+ "uint": true,
+ "uint16": true,
+ "uint32": true,
+ "uint64": true,
+ "uint8": true,
+ "uintptr": true,
+}
+
func cleanPackageName(name string) GoPackageName {
name = strings.Map(badToUnderscore, name)
- // Identifier must not be keyword: insert _.
+ // Identifier must not be keyword or predeclared identifier: insert _.
if isGoKeyword[name] {
name = "_" + name
}
@@ -724,27 +758,10 @@ func (g *Generator) WrapTypes() {
if fd == nil {
g.Fail("could not find file named", fileName)
}
- fingerprint, err := fingerprintProto(fd.FileDescriptorProto)
- if err != nil {
- g.Error(err)
- }
- fd.fingerprint = fingerprint
g.genFiles = append(g.genFiles, fd)
}
}
-// fingerprintProto returns a fingerprint for a message.
-// The fingerprint is intended to prevent conflicts between generated fileds,
-// not to provide cryptographic security.
-func fingerprintProto(m proto.Message) (string, error) {
- b, err := proto.Marshal(m)
- if err != nil {
- return "", err
- }
- h := sha256.Sum256(b)
- return hex.EncodeToString(h[:8]), nil
-}
-
// Scan the descriptors in this file. For each one, build the slice of nested descriptors
func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
for _, desc := range descs {
@@ -938,39 +955,6 @@ func (g *Generator) ObjectNamed(typeName string) Object {
if !ok {
g.Fail("can't find object with type", typeName)
}
-
- // If the file of this object isn't a direct dependency of the current file,
- // or in the current file, then this object has been publicly imported into
- // a dependency of the current file.
- // We should return the ImportedDescriptor object for it instead.
- direct := *o.File().Name == *g.file.Name
- if !direct {
- for _, dep := range g.file.Dependency {
- if *g.fileByName(dep).Name == *o.File().Name {
- direct = true
- break
- }
- }
- }
- if !direct {
- found := false
- Loop:
- for _, dep := range g.file.Dependency {
- df := g.fileByName(*g.fileByName(dep).Name)
- for _, td := range df.imp {
- if td.o == o {
- // Found it!
- o = td
- found = true
- break Loop
- }
- }
- }
- if !found {
- log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name)
- }
- }
-
return o
}
@@ -1124,6 +1108,7 @@ func (g *Generator) generate(file *FileDescriptor) {
g.usedPackages = make(map[GoImportPath]bool)
g.packageNames = make(map[GoImportPath]GoPackageName)
g.usedPackageNames = make(map[GoPackageName]bool)
+ g.addedImports = make(map[GoImportPath]bool)
for name := range globalPackageNames {
g.usedPackageNames[name] = true
}
@@ -1152,12 +1137,11 @@ func (g *Generator) generate(file *FileDescriptor) {
g.generateExtension(ext)
}
g.generateInitFunction()
+ g.generateFileDescriptor(file)
// Run the plugins before the imports so we know which imports are necessary.
g.runPlugins(file)
- g.generateFileDescriptor(file)
-
// Generate header and imports last, though they appear first in the output.
rem := g.Buffer
remAnno := g.annotations
@@ -1183,7 +1167,7 @@ func (g *Generator) generate(file *FileDescriptor) {
// make a copy independent of g; we'll need it after Reset.
original = append([]byte(nil), original...)
}
- ast, err := parser.ParseFile(fset, "", original, parser.ParseComments)
+ fileAST, err := parser.ParseFile(fset, "", original, parser.ParseComments)
if err != nil {
// Print out the bad code with line numbers.
// This should never happen in practice, but it can while changing generated code,
@@ -1195,8 +1179,9 @@ func (g *Generator) generate(file *FileDescriptor) {
}
g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String())
}
+ ast.SortImports(fset, fileAST)
g.Reset()
- err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)
+ err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, fileAST)
if err != nil {
g.Fail("generated Go source code could not be reformatted:", err.Error())
}
@@ -1225,28 +1210,10 @@ func (g *Generator) generateHeader() {
g.P("// source: ", g.file.Name)
}
g.P()
-
- importPath, _, _ := g.file.goPackageOption()
- if importPath == "" {
- g.P("package ", g.file.packageName)
- } else {
- g.P("package ", g.file.packageName, " // import ", GoImportPath(g.ImportPrefix)+importPath)
- }
+ g.PrintComments(strconv.Itoa(packagePath))
+ g.P()
+ g.P("package ", g.file.packageName)
g.P()
-
- if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok {
- g.P("/*")
- // not using g.PrintComments because this is a /* */ comment block.
- text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
- for _, line := range strings.Split(text, "\n") {
- line = strings.TrimPrefix(line, " ")
- // ensure we don't escape from the block comment
- line = strings.Replace(line, "*/", "* /", -1)
- g.P(line)
- }
- g.P("*/")
- g.P()
- }
}
// deprecationComment is the standard comment added to deprecated
@@ -1261,16 +1228,28 @@ func (g *Generator) PrintComments(path string) bool {
if !g.writeOutput {
return false
}
- if loc, ok := g.file.comments[path]; ok {
- text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
- for _, line := range strings.Split(text, "\n") {
- g.P("// ", strings.TrimPrefix(line, " "))
- }
+ if c, ok := g.makeComments(path); ok {
+ g.P(c)
return true
}
return false
}
+// makeComments generates the comment string for the field, no "\n" at the end
+func (g *Generator) makeComments(path string) (string, bool) {
+ loc, ok := g.file.comments[path]
+ if !ok {
+ return "", false
+ }
+ w := new(bytes.Buffer)
+ nl := ""
+ for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
+ fmt.Fprintf(w, "%s//%s", nl, line)
+ nl = "\n"
+ }
+ return w.String(), true
+}
+
func (g *Generator) fileByName(filename string) *FileDescriptor {
return g.allFilesByName[filename]
}
@@ -1287,17 +1266,7 @@ func (g *Generator) weak(i int32) bool {
// Generate the imports
func (g *Generator) generateImports() {
- // We almost always need a proto import. Rather than computing when we
- // do, which is tricky when there's a plugin, just import it and
- // reference it later. The same argument applies to the fmt and math packages.
- g.P("import "+g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto")
- g.P("import " + g.Pkg["fmt"] + ` "fmt"`)
- g.P("import " + g.Pkg["math"] + ` "math"`)
- var (
- imports = make(map[GoImportPath]bool)
- strongImports = make(map[GoImportPath]bool)
- importPaths []string
- )
+ imports := make(map[GoImportPath]GoPackageName)
for i, s := range g.file.Dependency {
fd := g.fileByName(s)
importPath := fd.importPath
@@ -1305,32 +1274,37 @@ func (g *Generator) generateImports() {
if importPath == g.file.importPath {
continue
}
- if !imports[importPath] {
- importPaths = append(importPaths, string(importPath))
- }
- imports[importPath] = true
- if !g.weak(int32(i)) {
- strongImports[importPath] = true
+ // Do not import weak imports.
+ if g.weak(int32(i)) {
+ continue
}
- }
- sort.Strings(importPaths)
- for i := range importPaths {
- importPath := GoImportPath(importPaths[i])
- packageName := g.GoPackageName(importPath)
- fullPath := GoImportPath(g.ImportPrefix) + importPath
- // Skip weak imports.
- if !strongImports[importPath] {
- g.P("// skipping weak import ", packageName, " ", fullPath)
+ // Do not import a package twice.
+ if _, ok := imports[importPath]; ok {
continue
}
// We need to import all the dependencies, even if we don't reference them,
// because other code and tools depend on having the full transitive closure
// of protocol buffer types in the binary.
+ packageName := g.GoPackageName(importPath)
if _, ok := g.usedPackages[importPath]; !ok {
packageName = "_"
}
- g.P("import ", packageName, " ", fullPath)
+ imports[importPath] = packageName
+ }
+ for importPath := range g.addedImports {
+ imports[importPath] = g.GoPackageName(importPath)
+ }
+ // We almost always need a proto import. Rather than computing when we
+ // do, which is tricky when there's a plugin, just import it and
+ // reference it later. The same argument applies to the fmt and math packages.
+ g.P("import (")
+ g.P(g.Pkg["fmt"] + ` "fmt"`)
+ g.P(g.Pkg["math"] + ` "math"`)
+ g.P(g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto")
+ for importPath, packageName := range imports {
+ g.P(packageName, " ", GoImportPath(g.ImportPrefix)+importPath)
}
+ g.P(")")
g.P()
// TODO: may need to worry about uniqueness across plugins
for _, p := range plugins {
@@ -1345,24 +1319,19 @@ func (g *Generator) generateImports() {
}
func (g *Generator) generateImported(id *ImportedDescriptor) {
- tn := id.TypeName()
- sn := tn[len(tn)-1]
df := id.o.File()
filename := *df.Name
if df.importPath == g.file.importPath {
// Don't generate type aliases for files in the same Go package as this one.
- g.P("// Ignoring public import of ", sn, " from ", filename)
- g.P()
return
}
if !supportTypeAliases {
g.Fail(fmt.Sprintf("%s: public imports require at least go1.9", filename))
}
- g.P("// ", sn, " from public import ", filename)
g.usedPackages[df.importPath] = true
for _, sym := range df.exported[id.o] {
- sym.GenerateAlias(g, g.GoPackageName(df.importPath))
+ sym.GenerateAlias(g, filename, g.GoPackageName(df.importPath))
}
g.P()
@@ -1384,7 +1353,6 @@ func (g *Generator) generateEnum(enum *EnumDescriptor) {
g.P("type ", Annotate(enum.file, enum.path, ccTypeName), " int32", deprecatedEnum)
g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()})
g.P("const (")
- g.In()
for i, e := range enum.Value {
etorPath := fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)
g.PrintComments(etorPath)
@@ -1398,10 +1366,9 @@ func (g *Generator) generateEnum(enum *EnumDescriptor) {
g.P(Annotate(enum.file, etorPath, name), " ", ccTypeName, " = ", e.Number, " ", deprecatedValue)
g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
}
- g.Out()
g.P(")")
+ g.P()
g.P("var ", ccTypeName, "_name = map[int32]string{")
- g.In()
generated := make(map[int32]bool) // avoid duplicate values
for _, e := range enum.Value {
duplicate := ""
@@ -1411,45 +1378,39 @@ func (g *Generator) generateEnum(enum *EnumDescriptor) {
g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
generated[*e.Number] = true
}
- g.Out()
g.P("}")
+ g.P()
g.P("var ", ccTypeName, "_value = map[string]int32{")
- g.In()
for _, e := range enum.Value {
g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
}
- g.Out()
g.P("}")
+ g.P()
if !enum.proto3() {
g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
- g.In()
g.P("p := new(", ccTypeName, ")")
g.P("*p = x")
g.P("return p")
- g.Out()
g.P("}")
+ g.P()
}
g.P("func (x ", ccTypeName, ") String() string {")
- g.In()
g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
- g.Out()
g.P("}")
+ g.P()
if !enum.proto3() {
g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
- g.In()
g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
g.P("if err != nil {")
- g.In()
g.P("return err")
- g.Out()
g.P("}")
g.P("*x = ", ccTypeName, "(value)")
g.P("return nil")
- g.Out()
g.P("}")
+ g.P()
}
var indexes []string
@@ -1459,15 +1420,15 @@ func (g *Generator) generateEnum(enum *EnumDescriptor) {
}
indexes = append(indexes, strconv.Itoa(enum.index))
g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) {")
- g.In()
g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
- g.Out()
g.P("}")
+ g.P()
if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" {
g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`)
+ g.P()
}
- g.P()
+ g.generateEnumRegistration(enum)
}
// The tag is a string like "varint,2,opt,name=fieldname,def=7" that
@@ -1524,6 +1485,18 @@ func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptor
g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName()))
}
defaultValue = enum.integerValueAsString(defaultValue)
+ case descriptor.FieldDescriptorProto_TYPE_FLOAT:
+ if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
+ if f, err := strconv.ParseFloat(defaultValue, 32); err == nil {
+ defaultValue = fmt.Sprint(float32(f))
+ }
+ }
+ case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
+ if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
+ if f, err := strconv.ParseFloat(defaultValue, 64); err == nil {
+ defaultValue = fmt.Sprint(f)
+ }
+ }
}
defaultValue = ",def=" + defaultValue
}
@@ -1561,19 +1534,14 @@ func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptor
name = name[i+1:]
}
}
- if json := field.GetJsonName(); json != "" && json != name {
+ if json := field.GetJsonName(); field.Extendee == nil && json != "" && json != name {
// TODO: escaping might be needed, in which case
// perhaps this should be in its own "json" tag.
name += ",json=" + json
}
name = ",name=" + name
if message.proto3() {
- // We only need the extra tag for []byte fields;
- // no need to add noise for the others.
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES {
- name += ",proto3"
- }
-
+ name += ",proto3"
}
oneof := ""
if field.OneofIndex != nil {
@@ -1670,11 +1638,16 @@ func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescripto
}
func (g *Generator) RecordTypeUse(t string) {
- if _, ok := g.typeNameToObject[t]; ok {
- // Call ObjectNamed to get the true object to record the use.
- obj := g.ObjectNamed(t)
- g.usedPackages[obj.GoImportPath()] = true
+ if _, ok := g.typeNameToObject[t]; !ok {
+ return
+ }
+ importPath := g.ObjectNamed(t).GoImportPath()
+ if importPath == g.outputImportPath {
+ // Don't record use of objects in our package.
+ return
}
+ g.AddImport(importPath)
+ g.usedPackages[importPath] = true
}
// Method names that may be generated. Fields with these names get an
@@ -1713,321 +1686,294 @@ var wellKnownTypes = map[string]bool{
"BytesValue": true,
}
-// Generate the type and default constant definitions for this Descriptor.
-func (g *Generator) generateMessage(message *Descriptor) {
- // The full type name
- typeName := message.TypeName()
- // The full type name, CamelCased.
- ccTypeName := CamelCaseSlice(typeName)
-
- usedNames := make(map[string]bool)
- for _, n := range methodNames {
- usedNames[n] = true
+// getterDefault finds the default value for the field to return from a getter,
+// regardless of if it's a built in default or explicit from the source. Returns e.g. "nil", `""`, "Default_MessageType_FieldName"
+func (g *Generator) getterDefault(field *descriptor.FieldDescriptorProto, goMessageType string) string {
+ if isRepeated(field) {
+ return "nil"
+ }
+ if def := field.GetDefaultValue(); def != "" {
+ defaultConstant := g.defaultConstantName(goMessageType, field.GetName())
+ if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
+ return defaultConstant
+ }
+ return "append([]byte(nil), " + defaultConstant + "...)"
+ }
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_BOOL:
+ return "false"
+ case descriptor.FieldDescriptorProto_TYPE_STRING:
+ return `""`
+ case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_BYTES:
+ return "nil"
+ case descriptor.FieldDescriptorProto_TYPE_ENUM:
+ obj := g.ObjectNamed(field.GetTypeName())
+ var enum *EnumDescriptor
+ if id, ok := obj.(*ImportedDescriptor); ok {
+ // The enum type has been publicly imported.
+ enum, _ = id.o.(*EnumDescriptor)
+ } else {
+ enum, _ = obj.(*EnumDescriptor)
+ }
+ if enum == nil {
+ log.Printf("don't know how to generate getter for %s", field.GetName())
+ return "nil"
+ }
+ if len(enum.Value) == 0 {
+ return "0 // empty enum"
+ }
+ first := enum.Value[0].GetName()
+ return g.DefaultPackageName(obj) + enum.prefix() + first
+ default:
+ return "0"
}
- fieldNames := make(map[*descriptor.FieldDescriptorProto]string)
- fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string)
- fieldTypes := make(map[*descriptor.FieldDescriptorProto]string)
- mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string)
+}
- oneofFieldName := make(map[int32]string) // indexed by oneof_index field of FieldDescriptorProto
- oneofDisc := make(map[int32]string) // name of discriminator method
- oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star
- oneofInsertPoints := make(map[int32]int) // oneof_index => offset of g.Buffer
+// defaultConstantName builds the name of the default constant from the message
+// type name and the untouched field name, e.g. "Default_MessageType_FieldName"
+func (g *Generator) defaultConstantName(goMessageType, protoFieldName string) string {
+ return "Default_" + goMessageType + "_" + CamelCase(protoFieldName)
+}
- comments := g.PrintComments(message.path)
+// The different types of fields in a message and how to actually print them
+// Most of the logic for generateMessage is in the methods of these types.
+//
+// Note that the content of the field is irrelevant, a simpleField can contain
+// anything from a scalar to a group (which is just a message).
+//
+// Extension fields (and message sets) are however handled separately.
+//
+// simpleField - a field that is neiter weak nor oneof, possibly repeated
+// oneofField - field containing list of subfields:
+// - oneofSubField - a field within the oneof
- // Guarantee deprecation comments appear after user-provided comments.
- if message.GetOptions().GetDeprecated() {
- if comments {
- // Convention: Separate deprecation comments from original
- // comments with an empty line.
- g.P("//")
- }
- g.P(deprecationComment)
- }
+// msgCtx contains the context for the generator functions.
+type msgCtx struct {
+ goName string // Go struct name of the message, e.g. MessageName
+ message *Descriptor // The descriptor for the message
+}
- g.P("type ", Annotate(message.file, message.path, ccTypeName), " struct {")
- g.In()
+// fieldCommon contains data common to all types of fields.
+type fieldCommon struct {
+ goName string // Go name of field, e.g. "FieldName" or "Descriptor_"
+ protoName string // Name of field in proto language, e.g. "field_name" or "descriptor"
+ getterName string // Name of the getter, e.g. "GetFieldName" or "GetDescriptor_"
+ goType string // The Go type as a string, e.g. "*int32" or "*OtherMessage"
+ tags string // The tag string/annotation for the type, e.g. `protobuf:"varint,8,opt,name=region_id,json=regionId"`
+ fullPath string // The full path of the field as used by Annotate etc, e.g. "4,0,2,0"
+}
- // allocNames finds a conflict-free variation of the given strings,
- // consistently mutating their suffixes.
- // It returns the same number of strings.
- allocNames := func(ns ...string) []string {
- Loop:
- for {
- for _, n := range ns {
- if usedNames[n] {
- for i := range ns {
- ns[i] += "_"
- }
- continue Loop
- }
- }
- for _, n := range ns {
- usedNames[n] = true
- }
- return ns
- }
- }
+// getProtoName gets the proto name of a field, e.g. "field_name" or "descriptor".
+func (f *fieldCommon) getProtoName() string {
+ return f.protoName
+}
- for i, field := range message.Field {
- // Allocate the getter and the field at the same time so name
- // collisions create field/method consistent names.
- // TODO: This allocation occurs based on the order of the fields
- // in the proto file, meaning that a change in the field
- // ordering can change generated Method/Field names.
- base := CamelCase(*field.Name)
- ns := allocNames(base, "Get"+base)
- fieldName, fieldGetterName := ns[0], ns[1]
- typename, wiretype := g.GoType(message, field)
- jsonName := *field.Name
- tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty")
+// getGoType returns the go type of the field as a string, e.g. "*int32".
+func (f *fieldCommon) getGoType() string {
+ return f.goType
+}
- fieldNames[field] = fieldName
- fieldGetterNames[field] = fieldGetterName
+// simpleField is not weak, not a oneof, not an extension. Can be required, optional or repeated.
+type simpleField struct {
+ fieldCommon
+ protoTypeName string // Proto type name, empty if primitive, e.g. ".google.protobuf.Duration"
+ protoType descriptor.FieldDescriptorProto_Type // Actual type enum value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
+ deprecated string // Deprecation comment, if any, e.g. "// Deprecated: Do not use."
+ getterDef string // Default for getters, e.g. "nil", `""` or "Default_MessageType_FieldName"
+ protoDef string // Default value as defined in the proto file, e.g "yoshi" or "5"
+ comment string // The full comment for the field, e.g. "// Useful information"
+}
- oneof := field.OneofIndex != nil
- if oneof && oneofFieldName[*field.OneofIndex] == "" {
- odp := message.OneofDecl[int(*field.OneofIndex)]
- fname := allocNames(CamelCase(odp.GetName()))[0]
+// decl prints the declaration of the field in the struct (if any).
+func (f *simpleField) decl(g *Generator, mc *msgCtx) {
+ g.P(f.comment, Annotate(mc.message.file, f.fullPath, f.goName), "\t", f.goType, "\t`", f.tags, "`", f.deprecated)
+}
- // This is the first field of a oneof we haven't seen before.
- // Generate the union field.
- oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)
- com := g.PrintComments(oneofFullPath)
- if com {
- g.P("//")
- }
- g.P("// Types that are valid to be assigned to ", fname, ":")
- // Generate the rest of this comment later,
- // when we've computed any disambiguation.
- oneofInsertPoints[*field.OneofIndex] = g.Buffer.Len()
+// getter prints the getter for the field.
+func (f *simpleField) getter(g *Generator, mc *msgCtx) {
+ star := ""
+ tname := f.goType
+ if needsStar(f.protoType) && tname[0] == '*' {
+ tname = tname[1:]
+ star = "*"
+ }
+ if f.deprecated != "" {
+ g.P(f.deprecated)
+ }
+ g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, f.fullPath, f.getterName), "() "+tname+" {")
+ if f.getterDef == "nil" { // Simpler getter
+ g.P("if m != nil {")
+ g.P("return m." + f.goName)
+ g.P("}")
+ g.P("return nil")
+ g.P("}")
+ g.P()
+ return
+ }
+ if mc.message.proto3() {
+ g.P("if m != nil {")
+ } else {
+ g.P("if m != nil && m." + f.goName + " != nil {")
+ }
+ g.P("return " + star + "m." + f.goName)
+ g.P("}")
+ g.P("return ", f.getterDef)
+ g.P("}")
+ g.P()
+}
- dname := "is" + ccTypeName + "_" + fname
- oneofFieldName[*field.OneofIndex] = fname
- oneofDisc[*field.OneofIndex] = dname
- tag := `protobuf_oneof:"` + odp.GetName() + `"`
- g.P(Annotate(message.file, oneofFullPath, fname), " ", dname, " `", tag, "`")
- }
+// setter prints the setter method of the field.
+func (f *simpleField) setter(g *Generator, mc *msgCtx) {
+ // No setter for regular fields yet
+}
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
- desc := g.ObjectNamed(field.GetTypeName())
- if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() {
- // Figure out the Go types and tags for the key and value types.
- keyField, valField := d.Field[0], d.Field[1]
- keyType, keyWire := g.GoType(d, keyField)
- valType, valWire := g.GoType(d, valField)
- keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire)
+// getProtoDef returns the default value explicitly stated in the proto file, e.g "yoshi" or "5".
+func (f *simpleField) getProtoDef() string {
+ return f.protoDef
+}
- // We don't use stars, except for message-typed values.
- // Message and enum types are the only two possibly foreign types used in maps,
- // so record their use. They are not permitted as map keys.
- keyType = strings.TrimPrefix(keyType, "*")
- switch *valField.Type {
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- valType = strings.TrimPrefix(valType, "*")
- g.RecordTypeUse(valField.GetTypeName())
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- g.RecordTypeUse(valField.GetTypeName())
- default:
- valType = strings.TrimPrefix(valType, "*")
- }
+// getProtoTypeName returns the protobuf type name for the field as returned by field.GetTypeName(), e.g. ".google.protobuf.Duration".
+func (f *simpleField) getProtoTypeName() string {
+ return f.protoTypeName
+}
- typename = fmt.Sprintf("map[%s]%s", keyType, valType)
- mapFieldTypes[field] = typename // record for the getter generation
+// getProtoType returns the *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64.
+func (f *simpleField) getProtoType() descriptor.FieldDescriptorProto_Type {
+ return f.protoType
+}
- tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag)
- }
- }
+// oneofSubFields are kept slize held by each oneofField. They do not appear in the top level slize of fields for the message.
+type oneofSubField struct {
+ fieldCommon
+ protoTypeName string // Proto type name, empty if primitive, e.g. ".google.protobuf.Duration"
+ protoType descriptor.FieldDescriptorProto_Type // Actual type enum value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
+ oneofTypeName string // Type name of the enclosing struct, e.g. "MessageName_FieldName"
+ fieldNumber int // Actual field number, as defined in proto, e.g. 12
+ getterDef string // Default for getters, e.g. "nil", `""` or "Default_MessageType_FieldName"
+ protoDef string // Default value as defined in the proto file, e.g "yoshi" or "5"
+ deprecated string // Deprecation comment, if any.
+}
- fieldTypes[field] = typename
+// typedNil prints a nil casted to the pointer to this field.
+// - for XXX_OneofWrappers
+func (f *oneofSubField) typedNil(g *Generator) {
+ g.P("(*", f.oneofTypeName, ")(nil),")
+}
- if oneof {
- tname := ccTypeName + "_" + fieldName
- // It is possible for this to collide with a message or enum
- // nested in this message. Check for collisions.
- for {
- ok := true
- for _, desc := range message.nested {
- if CamelCaseSlice(desc.TypeName()) == tname {
- ok = false
- break
- }
- }
- for _, enum := range message.enums {
- if CamelCaseSlice(enum.TypeName()) == tname {
- ok = false
- break
- }
- }
- if !ok {
- tname += "_"
- continue
- }
- break
- }
+// getProtoDef returns the default value explicitly stated in the proto file, e.g "yoshi" or "5".
+func (f *oneofSubField) getProtoDef() string {
+ return f.protoDef
+}
- oneofTypeName[field] = tname
- continue
- }
+// getProtoTypeName returns the protobuf type name for the field as returned by field.GetTypeName(), e.g. ".google.protobuf.Duration".
+func (f *oneofSubField) getProtoTypeName() string {
+ return f.protoTypeName
+}
- fieldDeprecated := ""
- if field.GetOptions().GetDeprecated() {
- fieldDeprecated = deprecationComment
- }
+// getProtoType returns the *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64.
+func (f *oneofSubField) getProtoType() descriptor.FieldDescriptorProto_Type {
+ return f.protoType
+}
- fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)
- g.PrintComments(fieldFullPath)
- g.P(Annotate(message.file, fieldFullPath, fieldName), "\t", typename, "\t`", tag, "`", fieldDeprecated)
- g.RecordTypeUse(field.GetTypeName())
- }
- g.P("XXX_NoUnkeyedLiteral\tstruct{} `json:\"-\"`") // prevent unkeyed struct literals
- if len(message.ExtensionRange) > 0 {
- messageset := ""
- if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() {
- messageset = "protobuf_messageset:\"1\" "
- }
- g.P(g.Pkg["proto"], ".XXX_InternalExtensions `", messageset, "json:\"-\"`")
+// oneofField represents the oneof on top level.
+// The alternative fields within the oneof are represented by oneofSubField.
+type oneofField struct {
+ fieldCommon
+ subFields []*oneofSubField // All the possible oneof fields
+ comment string // The full comment for the field, e.g. "// Types that are valid to be assigned to MyOneof:\n\\"
+}
+
+// decl prints the declaration of the field in the struct (if any).
+func (f *oneofField) decl(g *Generator, mc *msgCtx) {
+ comment := f.comment
+ for _, sf := range f.subFields {
+ comment += "//\t*" + sf.oneofTypeName + "\n"
}
- g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
- g.P("XXX_sizecache\tint32 `json:\"-\"`")
- g.Out()
- g.P("}")
+ g.P(comment, Annotate(mc.message.file, f.fullPath, f.goName), " ", f.goType, " `", f.tags, "`")
+}
- // Update g.Buffer to list valid oneof types.
- // We do this down here, after we've disambiguated the oneof type names.
- // We go in reverse order of insertion point to avoid invalidating offsets.
- for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- {
- ip := oneofInsertPoints[oi]
- all := g.Buffer.Bytes()
- rem := all[ip:]
- g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem
- oldLen := g.Buffer.Len()
- for _, field := range message.Field {
- if field.OneofIndex == nil || *field.OneofIndex != oi {
- continue
- }
- g.P("//\t*", oneofTypeName[field])
- }
- // If we've inserted text, we also need to fix up affected annotations (as
- // they contain offsets that may need to be changed).
- offset := int32(g.Buffer.Len() - oldLen)
- ip32 := int32(ip)
- for _, anno := range g.annotations {
- if *anno.Begin >= ip32 {
- *anno.Begin += offset
- }
- if *anno.End >= ip32 {
- *anno.End += offset
- }
- }
- g.Buffer.Write(rem)
- }
-
- // Reset, String and ProtoMessage methods.
- g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }")
- g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
- g.P("func (*", ccTypeName, ") ProtoMessage() {}")
- var indexes []string
- for m := message; m != nil; m = m.parent {
- indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
- }
- g.P("func (*", ccTypeName, ") Descriptor() ([]byte, []int) {")
- g.In()
- g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
- g.Out()
+// getter for a oneof field will print additional discriminators and interfaces for the oneof,
+// also it prints all the getters for the sub fields.
+func (f *oneofField) getter(g *Generator, mc *msgCtx) {
+ // The discriminator type
+ g.P("type ", f.goType, " interface {")
+ g.P(f.goType, "()")
g.P("}")
- // TODO: Revisit the decision to use a XXX_WellKnownType method
- // if we change proto.MessageName to work with multiple equivalents.
- if message.file.GetPackage() == "google.protobuf" && wellKnownTypes[message.GetName()] {
- g.P("func (*", ccTypeName, `) XXX_WellKnownType() string { return "`, message.GetName(), `" }`)
+ g.P()
+ // The subField types, fulfilling the discriminator type contract
+ for _, sf := range f.subFields {
+ g.P("type ", Annotate(mc.message.file, sf.fullPath, sf.oneofTypeName), " struct {")
+ g.P(Annotate(mc.message.file, sf.fullPath, sf.goName), " ", sf.goType, " `", sf.tags, "`")
+ g.P("}")
+ g.P()
}
-
- // Extension support methods
- var hasExtensions, isMessageSet bool
- if len(message.ExtensionRange) > 0 {
- hasExtensions = true
- // message_set_wire_format only makes sense when extensions are defined.
- if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() {
- isMessageSet = true
- g.P()
- g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {")
- g.In()
- g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(&m.XXX_InternalExtensions)")
- g.Out()
- g.P("}")
- g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {")
- g.In()
- g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)")
- g.Out()
- g.P("}")
- }
-
+ for _, sf := range f.subFields {
+ g.P("func (*", sf.oneofTypeName, ") ", f.goType, "() {}")
g.P()
- g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{")
- g.In()
- for _, r := range message.ExtensionRange {
- end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
- g.P("{Start: ", r.Start, ", End: ", end, "},")
- }
- g.Out()
+ }
+ // Getter for the oneof field
+ g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, f.fullPath, f.getterName), "() ", f.goType, " {")
+ g.P("if m != nil { return m.", f.goName, " }")
+ g.P("return nil")
+ g.P("}")
+ g.P()
+ // Getters for each oneof
+ for _, sf := range f.subFields {
+ if sf.deprecated != "" {
+ g.P(sf.deprecated)
+ }
+ g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, sf.fullPath, sf.getterName), "() "+sf.goType+" {")
+ g.P("if x, ok := m.", f.getterName, "().(*", sf.oneofTypeName, "); ok {")
+ g.P("return x.", sf.goName)
g.P("}")
- g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
- g.In()
- g.P("return extRange_", ccTypeName)
- g.Out()
+ g.P("return ", sf.getterDef)
g.P("}")
+ g.P()
}
+}
- // TODO: It does not scale to keep adding another method for every
- // operation on protos that we want to switch over to using the
- // table-driven approach. Instead, we should only add a single method
- // that allows getting access to the *InternalMessageInfo struct and then
- // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
-
- // Wrapper for table-driven marshaling and unmarshaling.
- g.P("func (m *", ccTypeName, ") XXX_Unmarshal(b []byte) error {")
- g.In()
- g.P("return xxx_messageInfo_", ccTypeName, ".Unmarshal(m, b)")
- g.Out()
- g.P("}")
-
- g.P("func (m *", ccTypeName, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
- g.In()
- g.P("return xxx_messageInfo_", ccTypeName, ".Marshal(b, m, deterministic)")
- g.Out()
- g.P("}")
-
- g.P("func (dst *", ccTypeName, ") XXX_Merge(src ", g.Pkg["proto"], ".Message) {")
- g.In()
- g.P("xxx_messageInfo_", ccTypeName, ".Merge(dst, src)")
- g.Out()
- g.P("}")
-
- g.P("func (m *", ccTypeName, ") XXX_Size() int {") // avoid name clash with "Size" field in some message
- g.In()
- g.P("return xxx_messageInfo_", ccTypeName, ".Size(m)")
- g.Out()
- g.P("}")
+// setter prints the setter method of the field.
+func (f *oneofField) setter(g *Generator, mc *msgCtx) {
+ // No setters for oneof yet
+}
- g.P("func (m *", ccTypeName, ") XXX_DiscardUnknown() {")
- g.In()
- g.P("xxx_messageInfo_", ccTypeName, ".DiscardUnknown(m)")
- g.Out()
- g.P("}")
+// topLevelField interface implemented by all types of fields on the top level (not oneofSubField).
+type topLevelField interface {
+ decl(g *Generator, mc *msgCtx) // print declaration within the struct
+ getter(g *Generator, mc *msgCtx) // print getter
+ setter(g *Generator, mc *msgCtx) // print setter if applicable
+}
- g.P("var xxx_messageInfo_", ccTypeName, " ", g.Pkg["proto"], ".InternalMessageInfo")
+// defField interface implemented by all types of fields that can have defaults (not oneofField, but instead oneofSubField).
+type defField interface {
+ getProtoDef() string // default value explicitly stated in the proto file, e.g "yoshi" or "5"
+ getProtoName() string // proto name of a field, e.g. "field_name" or "descriptor"
+ getGoType() string // go type of the field as a string, e.g. "*int32"
+ getProtoTypeName() string // protobuf type name for the field, e.g. ".google.protobuf.Duration"
+ getProtoType() descriptor.FieldDescriptorProto_Type // *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
+}
- // Default constants
- defNames := make(map[*descriptor.FieldDescriptorProto]string)
- for _, field := range message.Field {
- def := field.GetDefaultValue()
+// generateDefaultConstants adds constants for default values if needed, which is only if the default value is.
+// explicit in the proto.
+func (g *Generator) generateDefaultConstants(mc *msgCtx, topLevelFields []topLevelField) {
+ // Collect fields that can have defaults
+ dFields := []defField{}
+ for _, pf := range topLevelFields {
+ if f, ok := pf.(*oneofField); ok {
+ for _, osf := range f.subFields {
+ dFields = append(dFields, osf)
+ }
+ continue
+ }
+ dFields = append(dFields, pf.(defField))
+ }
+ for _, df := range dFields {
+ def := df.getProtoDef()
if def == "" {
continue
}
- fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
- defNames[field] = fieldname
- typename, _ := g.GoType(message, field)
+ fieldname := g.defaultConstantName(mc.goName, df.getProtoName())
+ typename := df.getGoType()
if typename[0] == '*' {
typename = typename[1:]
}
@@ -2049,13 +1995,21 @@ func (g *Generator) generateMessage(message *Descriptor) {
case "nan":
def = "math.NaN()"
}
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT {
+ if df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT {
def = "float32(" + def + ")"
}
kind = "var "
- case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
+ case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT:
+ if f, err := strconv.ParseFloat(def, 32); err == nil {
+ def = fmt.Sprint(float32(f))
+ }
+ case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_DOUBLE:
+ if f, err := strconv.ParseFloat(def, 64); err == nil {
+ def = fmt.Sprint(f)
+ }
+ case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_ENUM:
// Must be an enum. Need to construct the prefixed name.
- obj := g.ObjectNamed(field.GetTypeName())
+ obj := g.ObjectNamed(df.getProtoTypeName())
var enum *EnumDescriptor
if id, ok := obj.(*ImportedDescriptor); ok {
// The enum type has been publicly imported.
@@ -2070,456 +2024,388 @@ func (g *Generator) generateMessage(message *Descriptor) {
def = g.DefaultPackageName(obj) + enum.prefix() + def
}
g.P(kind, fieldname, " ", typename, " = ", def)
- g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""})
+ g.file.addExport(mc.message, constOrVarSymbol{fieldname, kind, ""})
}
g.P()
+}
- // Oneof per-field types, discriminants and getters.
- //
- // Generate unexported named types for the discriminant interfaces.
- // We shouldn't have to do this, but there was (~19 Aug 2015) a compiler/linker bug
- // that was triggered by using anonymous interfaces here.
- // TODO: Revisit this and consider reverting back to anonymous interfaces.
- for oi := range message.OneofDecl {
- dname := oneofDisc[int32(oi)]
- g.P("type ", dname, " interface {")
- g.In()
- g.P(dname, "()")
- g.Out()
- g.P("}")
- }
- g.P()
- var oneofTypes []string
- for i, field := range message.Field {
- if field.OneofIndex == nil {
- continue
+// generateInternalStructFields just adds the XXX_ fields to the message struct.
+func (g *Generator) generateInternalStructFields(mc *msgCtx, topLevelFields []topLevelField) {
+ g.P("XXX_NoUnkeyedLiteral\tstruct{} `json:\"-\"`") // prevent unkeyed struct literals
+ if len(mc.message.ExtensionRange) > 0 {
+ messageset := ""
+ if opts := mc.message.Options; opts != nil && opts.GetMessageSetWireFormat() {
+ messageset = "protobuf_messageset:\"1\" "
}
- _, wiretype := g.GoType(message, field)
- tag := "protobuf:" + g.goTag(message, field, wiretype)
- fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)
- g.P("type ", Annotate(message.file, fieldFullPath, oneofTypeName[field]), " struct{ ", Annotate(message.file, fieldFullPath, fieldNames[field]), " ", fieldTypes[field], " `", tag, "` }")
- g.RecordTypeUse(field.GetTypeName())
- oneofTypes = append(oneofTypes, oneofTypeName[field])
+ g.P(g.Pkg["proto"], ".XXX_InternalExtensions `", messageset, "json:\"-\"`")
}
- g.P()
- for _, field := range message.Field {
- if field.OneofIndex == nil {
- continue
+ g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
+ g.P("XXX_sizecache\tint32 `json:\"-\"`")
+
+}
+
+// generateOneofFuncs adds all the utility functions for oneof, including marshalling, unmarshalling and sizer.
+func (g *Generator) generateOneofFuncs(mc *msgCtx, topLevelFields []topLevelField) {
+ ofields := []*oneofField{}
+ for _, f := range topLevelFields {
+ if o, ok := f.(*oneofField); ok {
+ ofields = append(ofields, o)
}
- g.P("func (*", oneofTypeName[field], ") ", oneofDisc[*field.OneofIndex], "() {}")
}
- g.P()
- for oi := range message.OneofDecl {
- fname := oneofFieldName[int32(oi)]
- oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, oi)
- g.P("func (m *", ccTypeName, ") ", Annotate(message.file, oneofFullPath, "Get"+fname), "() ", oneofDisc[int32(oi)], " {")
- g.P("if m != nil { return m.", fname, " }")
- g.P("return nil")
- g.P("}")
+ if len(ofields) == 0 {
+ return
}
- g.P()
- // Field getters
- for i, field := range message.Field {
- oneof := field.OneofIndex != nil
-
- fname := fieldNames[field]
- typename, _ := g.GoType(message, field)
- if t, ok := mapFieldTypes[field]; ok {
- typename = t
- }
- mname := fieldGetterNames[field]
- star := ""
- if needsStar(*field.Type) && typename[0] == '*' {
- typename = typename[1:]
- star = "*"
+ // OneofFuncs
+ g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
+ g.P("func (*", mc.goName, ") XXX_OneofWrappers() []interface{} {")
+ g.P("return []interface{}{")
+ for _, of := range ofields {
+ for _, sf := range of.subFields {
+ sf.typedNil(g)
}
- fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)
+ }
+ g.P("}")
+ g.P("}")
+ g.P()
+}
- if field.GetOptions().GetDeprecated() {
- g.P(deprecationComment)
- }
+// generateMessageStruct adds the actual struct with it's members (but not methods) to the output.
+func (g *Generator) generateMessageStruct(mc *msgCtx, topLevelFields []topLevelField) {
+ comments := g.PrintComments(mc.message.path)
- g.P("func (m *", ccTypeName, ") ", Annotate(message.file, fieldFullPath, mname), "() "+typename+" {")
- g.In()
- def, hasDef := defNames[field]
- typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_BYTES:
- typeDefaultIsNil = !hasDef
- case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- typeDefaultIsNil = true
- }
- if isRepeated(field) {
- typeDefaultIsNil = true
- }
- if typeDefaultIsNil && !oneof {
- // A bytes field with no explicit default needs less generated code,
- // as does a message or group field, or a repeated field.
- g.P("if m != nil {")
- g.In()
- g.P("return m." + fname)
- g.Out()
- g.P("}")
- g.P("return nil")
- g.Out()
- g.P("}")
- g.P()
- continue
- }
- if !oneof {
- if message.proto3() {
- g.P("if m != nil {")
- } else {
- g.P("if m != nil && m." + fname + " != nil {")
- }
- g.In()
- g.P("return " + star + "m." + fname)
- g.Out()
- g.P("}")
- } else {
- uname := oneofFieldName[*field.OneofIndex]
- tname := oneofTypeName[field]
- g.P("if x, ok := m.Get", uname, "().(*", tname, "); ok {")
- g.P("return x.", fname)
- g.P("}")
- }
- if hasDef {
- if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
- g.P("return " + def)
- } else {
- // The default is a []byte var.
- // Make a copy when returning it to be safe.
- g.P("return append([]byte(nil), ", def, "...)")
- }
- } else {
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- g.P("return false")
- case descriptor.FieldDescriptorProto_TYPE_STRING:
- g.P(`return ""`)
- case descriptor.FieldDescriptorProto_TYPE_GROUP,
- descriptor.FieldDescriptorProto_TYPE_MESSAGE,
- descriptor.FieldDescriptorProto_TYPE_BYTES:
- // This is only possible for oneof fields.
- g.P("return nil")
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- // The default default for an enum is the first value in the enum,
- // not zero.
- obj := g.ObjectNamed(field.GetTypeName())
- var enum *EnumDescriptor
- if id, ok := obj.(*ImportedDescriptor); ok {
- // The enum type has been publicly imported.
- enum, _ = id.o.(*EnumDescriptor)
- } else {
- enum, _ = obj.(*EnumDescriptor)
- }
- if enum == nil {
- log.Printf("don't know how to generate getter for %s", field.GetName())
- continue
- }
- if len(enum.Value) == 0 {
- g.P("return 0 // empty enum")
- } else {
- first := enum.Value[0].GetName()
- g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first)
- }
- default:
- g.P("return 0")
- }
+ // Guarantee deprecation comments appear after user-provided comments.
+ if mc.message.GetOptions().GetDeprecated() {
+ if comments {
+ // Convention: Separate deprecation comments from original
+ // comments with an empty line.
+ g.P("//")
}
- g.Out()
- g.P("}")
- g.P()
+ g.P(deprecationComment)
}
- if !message.group {
- ms := &messageSymbol{
- sym: ccTypeName,
- hasExtensions: hasExtensions,
- isMessageSet: isMessageSet,
- oneofTypes: oneofTypes,
- }
- g.file.addExport(message, ms)
+ g.P("type ", Annotate(mc.message.file, mc.message.path, mc.goName), " struct {")
+ for _, pf := range topLevelFields {
+ pf.decl(g, mc)
+ }
+ g.generateInternalStructFields(mc, topLevelFields)
+ g.P("}")
+}
+
+// generateGetters adds getters for all fields, including oneofs and weak fields when applicable.
+func (g *Generator) generateGetters(mc *msgCtx, topLevelFields []topLevelField) {
+ for _, pf := range topLevelFields {
+ pf.getter(g, mc)
}
+}
- // Oneof functions
- if len(message.OneofDecl) > 0 {
- fieldWire := make(map[*descriptor.FieldDescriptorProto]string)
+// generateSetters add setters for all fields, including oneofs and weak fields when applicable.
+func (g *Generator) generateSetters(mc *msgCtx, topLevelFields []topLevelField) {
+ for _, pf := range topLevelFields {
+ pf.setter(g, mc)
+ }
+}
- // method
- enc := "_" + ccTypeName + "_OneofMarshaler"
- dec := "_" + ccTypeName + "_OneofUnmarshaler"
- size := "_" + ccTypeName + "_OneofSizer"
- encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error"
- decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)"
- sizeSig := "(msg " + g.Pkg["proto"] + ".Message) (n int)"
+// generateCommonMethods adds methods to the message that are not on a per field basis.
+func (g *Generator) generateCommonMethods(mc *msgCtx) {
+ // Reset, String and ProtoMessage methods.
+ g.P("func (m *", mc.goName, ") Reset() { *m = ", mc.goName, "{} }")
+ g.P("func (m *", mc.goName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
+ g.P("func (*", mc.goName, ") ProtoMessage() {}")
+ var indexes []string
+ for m := mc.message; m != nil; m = m.parent {
+ indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
+ }
+ g.P("func (*", mc.goName, ") Descriptor() ([]byte, []int) {")
+ g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
+ g.P("}")
+ g.P()
+ // TODO: Revisit the decision to use a XXX_WellKnownType method
+ // if we change proto.MessageName to work with multiple equivalents.
+ if mc.message.file.GetPackage() == "google.protobuf" && wellKnownTypes[mc.message.GetName()] {
+ g.P("func (*", mc.goName, `) XXX_WellKnownType() string { return "`, mc.message.GetName(), `" }`)
+ g.P()
+ }
- g.P("// XXX_OneofFuncs is for the internal use of the proto package.")
- g.P("func (*", ccTypeName, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {")
- g.P("return ", enc, ", ", dec, ", ", size, ", []interface{}{")
- for _, field := range message.Field {
- if field.OneofIndex == nil {
- continue
- }
- g.P("(*", oneofTypeName[field], ")(nil),")
+ // Extension support methods
+ if len(mc.message.ExtensionRange) > 0 {
+ g.P()
+ g.P("var extRange_", mc.goName, " = []", g.Pkg["proto"], ".ExtensionRange{")
+ for _, r := range mc.message.ExtensionRange {
+ end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
+ g.P("{Start: ", r.Start, ", End: ", end, "},")
}
g.P("}")
+ g.P("func (*", mc.goName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
+ g.P("return extRange_", mc.goName)
g.P("}")
g.P()
+ }
- // marshaler
- g.P("func ", enc, encSig, " {")
- g.P("m := msg.(*", ccTypeName, ")")
- for oi, odp := range message.OneofDecl {
- g.P("// ", odp.GetName())
- fname := oneofFieldName[int32(oi)]
- g.P("switch x := m.", fname, ".(type) {")
- for _, field := range message.Field {
- if field.OneofIndex == nil || int(*field.OneofIndex) != oi {
- continue
- }
- g.P("case *", oneofTypeName[field], ":")
- var wire, pre, post string
- val := "x." + fieldNames[field] // overridden for TYPE_BOOL
- canFail := false // only TYPE_MESSAGE and TYPE_GROUP can fail
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
- wire = "WireFixed64"
- pre = "b.EncodeFixed64(" + g.Pkg["math"] + ".Float64bits("
- post = "))"
- case descriptor.FieldDescriptorProto_TYPE_FLOAT:
- wire = "WireFixed32"
- pre = "b.EncodeFixed32(uint64(" + g.Pkg["math"] + ".Float32bits("
- post = ")))"
- case descriptor.FieldDescriptorProto_TYPE_INT64,
- descriptor.FieldDescriptorProto_TYPE_UINT64:
- wire = "WireVarint"
- pre, post = "b.EncodeVarint(uint64(", "))"
- case descriptor.FieldDescriptorProto_TYPE_INT32,
- descriptor.FieldDescriptorProto_TYPE_UINT32,
- descriptor.FieldDescriptorProto_TYPE_ENUM:
- wire = "WireVarint"
- pre, post = "b.EncodeVarint(uint64(", "))"
- case descriptor.FieldDescriptorProto_TYPE_FIXED64,
- descriptor.FieldDescriptorProto_TYPE_SFIXED64:
- wire = "WireFixed64"
- pre, post = "b.EncodeFixed64(uint64(", "))"
- case descriptor.FieldDescriptorProto_TYPE_FIXED32,
- descriptor.FieldDescriptorProto_TYPE_SFIXED32:
- wire = "WireFixed32"
- pre, post = "b.EncodeFixed32(uint64(", "))"
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- // bool needs special handling.
- g.P("t := uint64(0)")
- g.P("if ", val, " { t = 1 }")
- val = "t"
- wire = "WireVarint"
- pre, post = "b.EncodeVarint(", ")"
- case descriptor.FieldDescriptorProto_TYPE_STRING:
- wire = "WireBytes"
- pre, post = "b.EncodeStringBytes(", ")"
- case descriptor.FieldDescriptorProto_TYPE_GROUP:
- wire = "WireStartGroup"
- pre, post = "b.Marshal(", ")"
- canFail = true
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- wire = "WireBytes"
- pre, post = "b.EncodeMessage(", ")"
- canFail = true
- case descriptor.FieldDescriptorProto_TYPE_BYTES:
- wire = "WireBytes"
- pre, post = "b.EncodeRawBytes(", ")"
- case descriptor.FieldDescriptorProto_TYPE_SINT32:
- wire = "WireVarint"
- pre, post = "b.EncodeZigzag32(uint64(", "))"
- case descriptor.FieldDescriptorProto_TYPE_SINT64:
- wire = "WireVarint"
- pre, post = "b.EncodeZigzag64(uint64(", "))"
- default:
- g.Fail("unhandled oneof field type ", field.Type.String())
- }
- fieldWire[field] = wire
- g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")")
- if !canFail {
- g.P(pre, val, post)
- } else {
- g.P("if err := ", pre, val, post, "; err != nil {")
- g.P("return err")
- g.P("}")
- }
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
- g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)")
+ // TODO: It does not scale to keep adding another method for every
+ // operation on protos that we want to switch over to using the
+ // table-driven approach. Instead, we should only add a single method
+ // that allows getting access to the *InternalMessageInfo struct and then
+ // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
+
+ // Wrapper for table-driven marshaling and unmarshaling.
+ g.P("func (m *", mc.goName, ") XXX_Unmarshal(b []byte) error {")
+ g.P("return xxx_messageInfo_", mc.goName, ".Unmarshal(m, b)")
+ g.P("}")
+
+ g.P("func (m *", mc.goName, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
+ g.P("return xxx_messageInfo_", mc.goName, ".Marshal(b, m, deterministic)")
+ g.P("}")
+
+ g.P("func (m *", mc.goName, ") XXX_Merge(src ", g.Pkg["proto"], ".Message) {")
+ g.P("xxx_messageInfo_", mc.goName, ".Merge(m, src)")
+ g.P("}")
+
+ g.P("func (m *", mc.goName, ") XXX_Size() int {") // avoid name clash with "Size" field in some message
+ g.P("return xxx_messageInfo_", mc.goName, ".Size(m)")
+ g.P("}")
+
+ g.P("func (m *", mc.goName, ") XXX_DiscardUnknown() {")
+ g.P("xxx_messageInfo_", mc.goName, ".DiscardUnknown(m)")
+ g.P("}")
+
+ g.P("var xxx_messageInfo_", mc.goName, " ", g.Pkg["proto"], ".InternalMessageInfo")
+ g.P()
+}
+
+// Generate the type, methods and default constant definitions for this Descriptor.
+func (g *Generator) generateMessage(message *Descriptor) {
+ topLevelFields := []topLevelField{}
+ oFields := make(map[int32]*oneofField)
+ // The full type name
+ typeName := message.TypeName()
+ // The full type name, CamelCased.
+ goTypeName := CamelCaseSlice(typeName)
+
+ usedNames := make(map[string]bool)
+ for _, n := range methodNames {
+ usedNames[n] = true
+ }
+
+ // allocNames finds a conflict-free variation of the given strings,
+ // consistently mutating their suffixes.
+ // It returns the same number of strings.
+ allocNames := func(ns ...string) []string {
+ Loop:
+ for {
+ for _, n := range ns {
+ if usedNames[n] {
+ for i := range ns {
+ ns[i] += "_"
+ }
+ continue Loop
}
}
- g.P("case nil:")
- g.P("default: return ", g.Pkg["fmt"], `.Errorf("`, ccTypeName, ".", fname, ` has unexpected type %T", x)`)
- g.P("}")
+ for _, n := range ns {
+ usedNames[n] = true
+ }
+ return ns
}
- g.P("return nil")
- g.P("}")
- g.P()
+ }
- // unmarshaler
- g.P("func ", dec, decSig, " {")
- g.P("m := msg.(*", ccTypeName, ")")
- g.P("switch tag {")
- for _, field := range message.Field {
- if field.OneofIndex == nil {
- continue
- }
+ mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) // keep track of the map fields to be added later
+
+ // Build a structure more suitable for generating the text in one pass
+ for i, field := range message.Field {
+ // Allocate the getter and the field at the same time so name
+ // collisions create field/method consistent names.
+ // TODO: This allocation occurs based on the order of the fields
+ // in the proto file, meaning that a change in the field
+ // ordering can change generated Method/Field names.
+ base := CamelCase(*field.Name)
+ ns := allocNames(base, "Get"+base)
+ fieldName, fieldGetterName := ns[0], ns[1]
+ typename, wiretype := g.GoType(message, field)
+ jsonName := *field.Name
+ tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty")
+
+ oneof := field.OneofIndex != nil
+ if oneof && oFields[*field.OneofIndex] == nil {
odp := message.OneofDecl[int(*field.OneofIndex)]
- g.P("case ", field.Number, ": // ", odp.GetName(), ".", *field.Name)
- g.P("if wire != ", g.Pkg["proto"], ".", fieldWire[field], " {")
- g.P("return true, ", g.Pkg["proto"], ".ErrInternalBadWireType")
- g.P("}")
- lhs := "x, err" // overridden for TYPE_MESSAGE and TYPE_GROUP
- var dec, cast, cast2 string
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
- dec, cast = "b.DecodeFixed64()", g.Pkg["math"]+".Float64frombits"
- case descriptor.FieldDescriptorProto_TYPE_FLOAT:
- dec, cast, cast2 = "b.DecodeFixed32()", "uint32", g.Pkg["math"]+".Float32frombits"
- case descriptor.FieldDescriptorProto_TYPE_INT64:
- dec, cast = "b.DecodeVarint()", "int64"
- case descriptor.FieldDescriptorProto_TYPE_UINT64:
- dec = "b.DecodeVarint()"
- case descriptor.FieldDescriptorProto_TYPE_INT32:
- dec, cast = "b.DecodeVarint()", "int32"
- case descriptor.FieldDescriptorProto_TYPE_FIXED64:
- dec = "b.DecodeFixed64()"
- case descriptor.FieldDescriptorProto_TYPE_FIXED32:
- dec, cast = "b.DecodeFixed32()", "uint32"
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- dec = "b.DecodeVarint()"
- // handled specially below
- case descriptor.FieldDescriptorProto_TYPE_STRING:
- dec = "b.DecodeStringBytes()"
- case descriptor.FieldDescriptorProto_TYPE_GROUP:
- g.P("msg := new(", fieldTypes[field][1:], ")") // drop star
- lhs = "err"
- dec = "b.DecodeGroup(msg)"
- // handled specially below
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- g.P("msg := new(", fieldTypes[field][1:], ")") // drop star
- lhs = "err"
- dec = "b.DecodeMessage(msg)"
- // handled specially below
- case descriptor.FieldDescriptorProto_TYPE_BYTES:
- dec = "b.DecodeRawBytes(true)"
- case descriptor.FieldDescriptorProto_TYPE_UINT32:
- dec, cast = "b.DecodeVarint()", "uint32"
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- dec, cast = "b.DecodeVarint()", fieldTypes[field]
- case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
- dec, cast = "b.DecodeFixed32()", "int32"
- case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
- dec, cast = "b.DecodeFixed64()", "int64"
- case descriptor.FieldDescriptorProto_TYPE_SINT32:
- dec, cast = "b.DecodeZigzag32()", "int32"
- case descriptor.FieldDescriptorProto_TYPE_SINT64:
- dec, cast = "b.DecodeZigzag64()", "int64"
- default:
- g.Fail("unhandled oneof field type ", field.Type.String())
- }
- g.P(lhs, " := ", dec)
- val := "x"
- if cast != "" {
- val = cast + "(" + val + ")"
- }
- if cast2 != "" {
- val = cast2 + "(" + val + ")"
+ base := CamelCase(odp.GetName())
+ names := allocNames(base, "Get"+base)
+ fname, gname := names[0], names[1]
+
+ // This is the first field of a oneof we haven't seen before.
+ // Generate the union field.
+ oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)
+ c, ok := g.makeComments(oneofFullPath)
+ if ok {
+ c += "\n//\n"
}
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- val += " != 0"
- case descriptor.FieldDescriptorProto_TYPE_GROUP,
- descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- val = "msg"
+ c += "// Types that are valid to be assigned to " + fname + ":\n"
+ // Generate the rest of this comment later,
+ // when we've computed any disambiguation.
+
+ dname := "is" + goTypeName + "_" + fname
+ tag := `protobuf_oneof:"` + odp.GetName() + `"`
+ of := oneofField{
+ fieldCommon: fieldCommon{
+ goName: fname,
+ getterName: gname,
+ goType: dname,
+ tags: tag,
+ protoName: odp.GetName(),
+ fullPath: oneofFullPath,
+ },
+ comment: c,
}
- g.P("m.", oneofFieldName[*field.OneofIndex], " = &", oneofTypeName[field], "{", val, "}")
- g.P("return true, err")
+ topLevelFields = append(topLevelFields, &of)
+ oFields[*field.OneofIndex] = &of
}
- g.P("default: return false, nil")
- g.P("}")
- g.P("}")
- g.P()
- // sizer
- g.P("func ", size, sizeSig, " {")
- g.P("m := msg.(*", ccTypeName, ")")
- for oi, odp := range message.OneofDecl {
- g.P("// ", odp.GetName())
- fname := oneofFieldName[int32(oi)]
- g.P("switch x := m.", fname, ".(type) {")
- for _, field := range message.Field {
- if field.OneofIndex == nil || int(*field.OneofIndex) != oi {
- continue
- }
- g.P("case *", oneofTypeName[field], ":")
- val := "x." + fieldNames[field]
- var varint, fixed string
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
- fixed = "8"
- case descriptor.FieldDescriptorProto_TYPE_FLOAT:
- fixed = "4"
- case descriptor.FieldDescriptorProto_TYPE_INT64,
- descriptor.FieldDescriptorProto_TYPE_UINT64,
- descriptor.FieldDescriptorProto_TYPE_INT32,
- descriptor.FieldDescriptorProto_TYPE_UINT32,
- descriptor.FieldDescriptorProto_TYPE_ENUM:
- varint = val
- case descriptor.FieldDescriptorProto_TYPE_FIXED64,
- descriptor.FieldDescriptorProto_TYPE_SFIXED64:
- fixed = "8"
- case descriptor.FieldDescriptorProto_TYPE_FIXED32,
- descriptor.FieldDescriptorProto_TYPE_SFIXED32:
- fixed = "4"
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- fixed = "1"
- case descriptor.FieldDescriptorProto_TYPE_STRING:
- fixed = "len(" + val + ")"
- varint = fixed
- case descriptor.FieldDescriptorProto_TYPE_GROUP:
- fixed = g.Pkg["proto"] + ".Size(" + val + ")"
+ if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
+ desc := g.ObjectNamed(field.GetTypeName())
+ if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() {
+ // Figure out the Go types and tags for the key and value types.
+ keyField, valField := d.Field[0], d.Field[1]
+ keyType, keyWire := g.GoType(d, keyField)
+ valType, valWire := g.GoType(d, valField)
+ keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire)
+
+ // We don't use stars, except for message-typed values.
+ // Message and enum types are the only two possibly foreign types used in maps,
+ // so record their use. They are not permitted as map keys.
+ keyType = strings.TrimPrefix(keyType, "*")
+ switch *valField.Type {
+ case descriptor.FieldDescriptorProto_TYPE_ENUM:
+ valType = strings.TrimPrefix(valType, "*")
+ g.RecordTypeUse(valField.GetTypeName())
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- g.P("s := ", g.Pkg["proto"], ".Size(", val, ")")
- fixed = "s"
- varint = fixed
- case descriptor.FieldDescriptorProto_TYPE_BYTES:
- fixed = "len(" + val + ")"
- varint = fixed
- case descriptor.FieldDescriptorProto_TYPE_SINT32:
- varint = "(uint32(" + val + ") << 1) ^ uint32((int32(" + val + ") >> 31))"
- case descriptor.FieldDescriptorProto_TYPE_SINT64:
- varint = "uint64(" + val + " << 1) ^ uint64((int64(" + val + ") >> 63))"
+ g.RecordTypeUse(valField.GetTypeName())
default:
- g.Fail("unhandled oneof field type ", field.Type.String())
+ valType = strings.TrimPrefix(valType, "*")
}
- // Tag and wire varint is known statically,
- // so don't generate code for that part of the size computation.
- tagAndWireSize := proto.SizeVarint(uint64(*field.Number << 3)) // wire doesn't affect varint size
- g.P("n += ", tagAndWireSize, " // tag and wire")
- if varint != "" {
- g.P("n += ", g.Pkg["proto"], ".SizeVarint(uint64(", varint, "))")
+
+ typename = fmt.Sprintf("map[%s]%s", keyType, valType)
+ mapFieldTypes[field] = typename // record for the getter generation
+
+ tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag)
+ }
+ }
+
+ fieldDeprecated := ""
+ if field.GetOptions().GetDeprecated() {
+ fieldDeprecated = deprecationComment
+ }
+
+ dvalue := g.getterDefault(field, goTypeName)
+ if oneof {
+ tname := goTypeName + "_" + fieldName
+ // It is possible for this to collide with a message or enum
+ // nested in this message. Check for collisions.
+ for {
+ ok := true
+ for _, desc := range message.nested {
+ if CamelCaseSlice(desc.TypeName()) == tname {
+ ok = false
+ break
+ }
}
- if fixed != "" {
- g.P("n += ", fixed)
+ for _, enum := range message.enums {
+ if CamelCaseSlice(enum.TypeName()) == tname {
+ ok = false
+ break
+ }
}
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
- g.P("n += ", tagAndWireSize, " // tag and wire")
+ if !ok {
+ tname += "_"
+ continue
}
+ break
+ }
+
+ oneofField := oFields[*field.OneofIndex]
+ tag := "protobuf:" + g.goTag(message, field, wiretype)
+ sf := oneofSubField{
+ fieldCommon: fieldCommon{
+ goName: fieldName,
+ getterName: fieldGetterName,
+ goType: typename,
+ tags: tag,
+ protoName: field.GetName(),
+ fullPath: fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i),
+ },
+ protoTypeName: field.GetTypeName(),
+ fieldNumber: int(*field.Number),
+ protoType: *field.Type,
+ getterDef: dvalue,
+ protoDef: field.GetDefaultValue(),
+ oneofTypeName: tname,
+ deprecated: fieldDeprecated,
}
- g.P("case nil:")
- g.P("default:")
- g.P("panic(", g.Pkg["fmt"], ".Sprintf(\"proto: unexpected type %T in oneof\", x))")
- g.P("}")
+ oneofField.subFields = append(oneofField.subFields, &sf)
+ g.RecordTypeUse(field.GetTypeName())
+ continue
}
- g.P("return n")
- g.P("}")
- g.P()
+
+ fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)
+ c, ok := g.makeComments(fieldFullPath)
+ if ok {
+ c += "\n"
+ }
+ rf := simpleField{
+ fieldCommon: fieldCommon{
+ goName: fieldName,
+ getterName: fieldGetterName,
+ goType: typename,
+ tags: tag,
+ protoName: field.GetName(),
+ fullPath: fieldFullPath,
+ },
+ protoTypeName: field.GetTypeName(),
+ protoType: *field.Type,
+ deprecated: fieldDeprecated,
+ getterDef: dvalue,
+ protoDef: field.GetDefaultValue(),
+ comment: c,
+ }
+ var pf topLevelField = &rf
+
+ topLevelFields = append(topLevelFields, pf)
+ g.RecordTypeUse(field.GetTypeName())
+ }
+
+ mc := &msgCtx{
+ goName: goTypeName,
+ message: message,
+ }
+
+ g.generateMessageStruct(mc, topLevelFields)
+ g.P()
+ g.generateCommonMethods(mc)
+ g.P()
+ g.generateDefaultConstants(mc, topLevelFields)
+ g.P()
+ g.generateGetters(mc, topLevelFields)
+ g.P()
+ g.generateSetters(mc, topLevelFields)
+ g.P()
+ g.generateOneofFuncs(mc, topLevelFields)
+ g.P()
+
+ var oneofTypes []string
+ for _, f := range topLevelFields {
+ if of, ok := f.(*oneofField); ok {
+ for _, osf := range of.subFields {
+ oneofTypes = append(oneofTypes, osf.oneofTypeName)
+ }
+ }
+ }
+
+ opts := message.Options
+ ms := &messageSymbol{
+ sym: goTypeName,
+ hasExtensions: len(message.ExtensionRange) > 0,
+ isMessageSet: opts != nil && opts.GetMessageSetWireFormat(),
+ oneofTypes: oneofTypes,
}
+ g.file.addExport(message, ms)
for _, ext := range message.ext {
g.generateExtension(ext)
@@ -2530,12 +2416,13 @@ func (g *Generator) generateMessage(message *Descriptor) {
fullName = *g.file.Package + "." + fullName
}
- g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], ccTypeName, fullName)
+ g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], goTypeName, fullName)
// Register types for native map types.
for _, k := range mapFieldKeys(mapFieldTypes) {
fullName := strings.TrimPrefix(*k.TypeName, ".")
g.addInitf("%s.RegisterMapType((%s)(nil), %q)", g.Pkg["proto"], mapFieldTypes[k], fullName)
}
+
}
type byTypeName []*descriptor.FieldDescriptorProto
@@ -2647,10 +2534,8 @@ func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
// In addition, the situation for when to apply this special case is implemented
// differently in other languages:
// https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
- mset := false
if extDesc.GetOptions().GetMessageSetWireFormat() && typeName[len(typeName)-1] == "message_set_extension" {
typeName = typeName[:len(typeName)-1]
- mset = true
}
// For text formatting, the package must be exactly what the .proto file declares,
@@ -2661,7 +2546,6 @@ func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
}
g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{")
- g.In()
g.P("ExtendedType: (", extendedType, ")(nil),")
g.P("ExtensionType: (", fieldType, ")(nil),")
g.P("Field: ", field.Number, ",")
@@ -2669,39 +2553,22 @@ func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
g.P("Tag: ", tag, ",")
g.P(`Filename: "`, g.file.GetName(), `",`)
- g.Out()
g.P("}")
g.P()
- if mset {
- // Generate a bit more code to register with message_set.go.
- g.addInitf("%s.RegisterMessageSetType((%s)(nil), %d, %q)", g.Pkg["proto"], fieldType, *field.Number, extName)
- }
+ g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName())
g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""})
}
func (g *Generator) generateInitFunction() {
- for _, enum := range g.file.enum {
- g.generateEnumRegistration(enum)
- }
- for _, d := range g.file.desc {
- for _, ext := range d.ext {
- g.generateExtensionRegistration(ext)
- }
- }
- for _, ext := range g.file.ext {
- g.generateExtensionRegistration(ext)
- }
if len(g.init) == 0 {
return
}
g.P("func init() {")
- g.In()
for _, l := range g.init {
g.P(l)
}
- g.Out()
g.P("}")
g.init = nil
}
@@ -2727,7 +2594,6 @@ func (g *Generator) generateFileDescriptor(file *FileDescriptor) {
g.P()
g.P("func init() { ", g.Pkg["proto"], ".RegisterFile(", strconv.Quote(*file.Name), ", ", v, ") }")
g.P("var ", v, " = []byte{")
- g.In()
g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
for len(b) > 0 {
n := 16
@@ -2743,7 +2609,6 @@ func (g *Generator) generateFileDescriptor(file *FileDescriptor) {
b = b[n:]
}
- g.Out()
g.P("}")
}
@@ -2760,10 +2625,6 @@ func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName)
}
-func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) {
- g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName())
-}
-
// And now lots of helper functions.
// Is c an ASCII lower-case letter?
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go
index a9b61036c..e688c8941 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go
@@ -1,38 +1,9 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2017 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
-/*
-Package remap handles tracking the locations of Go tokens in a source text
-across a rewrite by the Go formatter.
-*/
+// Package remap handles tracking the locations of Go tokens in a source text
+// across a rewrite by the Go formatter.
package remap
import (
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go
index ccc7fca03..441ef57cb 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go
@@ -1,33 +1,6 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2017 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package remap
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go
deleted file mode 100644
index 571147cfc..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go
+++ /dev/null
@@ -1,115 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2013 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package generator
-
-import (
- "testing"
-
- "github.com/golang/protobuf/protoc-gen-go/descriptor"
-)
-
-func TestCamelCase(t *testing.T) {
- tests := []struct {
- in, want string
- }{
- {"one", "One"},
- {"one_two", "OneTwo"},
- {"_my_field_name_2", "XMyFieldName_2"},
- {"Something_Capped", "Something_Capped"},
- {"my_Name", "My_Name"},
- {"OneTwo", "OneTwo"},
- {"_", "X"},
- {"_a_", "XA_"},
- }
- for _, tc := range tests {
- if got := CamelCase(tc.in); got != tc.want {
- t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want)
- }
- }
-}
-
-func TestGoPackageOption(t *testing.T) {
- tests := []struct {
- in string
- impPath GoImportPath
- pkg GoPackageName
- ok bool
- }{
- {"", "", "", false},
- {"foo", "", "foo", true},
- {"github.com/golang/bar", "github.com/golang/bar", "bar", true},
- {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true},
- }
- for _, tc := range tests {
- d := &FileDescriptor{
- FileDescriptorProto: &descriptor.FileDescriptorProto{
- Options: &descriptor.FileOptions{
- GoPackage: &tc.in,
- },
- },
- }
- impPath, pkg, ok := d.goPackageOption()
- if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok {
- t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in,
- impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok)
- }
- }
-}
-
-func TestUnescape(t *testing.T) {
- tests := []struct {
- in string
- out string
- }{
- // successful cases, including all kinds of escapes
- {"", ""},
- {"foo bar baz frob nitz", "foo bar baz frob nitz"},
- {`\000\001\002\003\004\005\006\007`, string([]byte{0, 1, 2, 3, 4, 5, 6, 7})},
- {`\a\b\f\n\r\t\v\\\?\'\"`, string([]byte{'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '?', '\'', '"'})},
- {`\x10\x20\x30\x40\x50\x60\x70\x80`, string([]byte{16, 32, 48, 64, 80, 96, 112, 128})},
- // variable length octal escapes
- {`\0\018\222\377\3\04\005\6\07`, string([]byte{0, 1, '8', 0222, 255, 3, 4, 5, 6, 7})},
- // malformed escape sequences left as is
- {"foo \\g bar", "foo \\g bar"},
- {"foo \\xg0 bar", "foo \\xg0 bar"},
- {"\\", "\\"},
- {"\\x", "\\x"},
- {"\\xf", "\\xf"},
- {"\\777", "\\777"}, // overflows byte
- }
- for _, tc := range tests {
- s := unescape(tc.in)
- if s != tc.out {
- t.Errorf("doUnescape(%q) = %q; should have been %q", tc.in, s, tc.out)
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/golden_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/golden_test.go
deleted file mode 100644
index 2630de68a..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/golden_test.go
+++ /dev/null
@@ -1,422 +0,0 @@
-package main
-
-import (
- "bytes"
- "flag"
- "fmt"
- "go/build"
- "go/parser"
- "go/token"
- "io/ioutil"
- "os"
- "os/exec"
- "path/filepath"
- "regexp"
- "runtime"
- "strings"
- "testing"
-)
-
-// Set --regenerate to regenerate the golden files.
-var regenerate = flag.Bool("regenerate", false, "regenerate golden files")
-
-// When the environment variable RUN_AS_PROTOC_GEN_GO is set, we skip running
-// tests and instead act as protoc-gen-go. This allows the test binary to
-// pass itself to protoc.
-func init() {
- if os.Getenv("RUN_AS_PROTOC_GEN_GO") != "" {
- main()
- os.Exit(0)
- }
-}
-
-func TestGolden(t *testing.T) {
- workdir, err := ioutil.TempDir("", "proto-test")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(workdir)
-
- // Find all the proto files we need to compile. We assume that each directory
- // contains the files for a single package.
- supportTypeAliases := hasReleaseTag("go1.9")
- packages := map[string][]string{}
- err = filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error {
- if filepath.Base(path) == "import_public" && !supportTypeAliases {
- // Public imports require type alias support.
- return filepath.SkipDir
- }
- if !strings.HasSuffix(path, ".proto") {
- return nil
- }
- dir := filepath.Dir(path)
- packages[dir] = append(packages[dir], path)
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Compile each package, using this binary as protoc-gen-go.
- for _, sources := range packages {
- args := []string{"-Itestdata", "--go_out=plugins=grpc,paths=source_relative:" + workdir}
- args = append(args, sources...)
- protoc(t, args)
- }
-
- // Compare each generated file to the golden version.
- filepath.Walk(workdir, func(genPath string, info os.FileInfo, _ error) error {
- if info.IsDir() {
- return nil
- }
-
- // For each generated file, figure out the path to the corresponding
- // golden file in the testdata directory.
- relPath, err := filepath.Rel(workdir, genPath)
- if err != nil {
- t.Errorf("filepath.Rel(%q, %q): %v", workdir, genPath, err)
- return nil
- }
- if filepath.SplitList(relPath)[0] == ".." {
- t.Errorf("generated file %q is not relative to %q", genPath, workdir)
- }
- goldenPath := filepath.Join("testdata", relPath)
-
- got, err := ioutil.ReadFile(genPath)
- if err != nil {
- t.Error(err)
- return nil
- }
- if *regenerate {
- // If --regenerate set, just rewrite the golden files.
- err := ioutil.WriteFile(goldenPath, got, 0666)
- if err != nil {
- t.Error(err)
- }
- return nil
- }
-
- want, err := ioutil.ReadFile(goldenPath)
- if err != nil {
- t.Error(err)
- return nil
- }
-
- want = fdescRE.ReplaceAll(want, nil)
- got = fdescRE.ReplaceAll(got, nil)
- if bytes.Equal(got, want) {
- return nil
- }
-
- cmd := exec.Command("diff", "-u", goldenPath, genPath)
- out, _ := cmd.CombinedOutput()
- t.Errorf("golden file differs: %v\n%v", relPath, string(out))
- return nil
- })
-}
-
-var fdescRE = regexp.MustCompile(`(?ms)^var fileDescriptor.*}`)
-
-// Source files used by TestParameters.
-const (
- aProto = `
-syntax = "proto3";
-package test.alpha;
-option go_package = "package/alpha";
-import "beta/b.proto";
-message M { test.beta.M field = 1; }`
-
- bProto = `
-syntax = "proto3";
-package test.beta;
-// no go_package option
-message M {}`
-)
-
-func TestParameters(t *testing.T) {
- for _, test := range []struct {
- parameters string
- wantFiles map[string]bool
- wantImportsA map[string]bool
- wantPackageA string
- wantPackageB string
- }{{
- parameters: "",
- wantFiles: map[string]bool{
- "package/alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- wantPackageA: "alpha",
- wantPackageB: "test_beta",
- wantImportsA: map[string]bool{
- "github.com/golang/protobuf/proto": true,
- "beta": true,
- },
- }, {
- parameters: "import_prefix=prefix",
- wantFiles: map[string]bool{
- "package/alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- wantPackageA: "alpha",
- wantPackageB: "test_beta",
- wantImportsA: map[string]bool{
- // This really doesn't seem like useful behavior.
- "prefixgithub.com/golang/protobuf/proto": true,
- "prefixbeta": true,
- },
- }, {
- // import_path only affects the 'package' line.
- parameters: "import_path=import/path/of/pkg",
- wantPackageA: "alpha",
- wantPackageB: "pkg",
- wantFiles: map[string]bool{
- "package/alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- }, {
- parameters: "Mbeta/b.proto=package/gamma",
- wantFiles: map[string]bool{
- "package/alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- wantPackageA: "alpha",
- wantPackageB: "test_beta",
- wantImportsA: map[string]bool{
- "github.com/golang/protobuf/proto": true,
- // Rewritten by the M parameter.
- "package/gamma": true,
- },
- }, {
- parameters: "import_prefix=prefix,Mbeta/b.proto=package/gamma",
- wantFiles: map[string]bool{
- "package/alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- wantPackageA: "alpha",
- wantPackageB: "test_beta",
- wantImportsA: map[string]bool{
- // import_prefix applies after M.
- "prefixpackage/gamma": true,
- },
- }, {
- parameters: "paths=source_relative",
- wantFiles: map[string]bool{
- "alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- wantPackageA: "alpha",
- wantPackageB: "test_beta",
- }, {
- parameters: "paths=source_relative,import_prefix=prefix",
- wantFiles: map[string]bool{
- // import_prefix doesn't affect filenames.
- "alpha/a.pb.go": true,
- "beta/b.pb.go": true,
- },
- wantPackageA: "alpha",
- wantPackageB: "test_beta",
- }} {
- name := test.parameters
- if name == "" {
- name = "defaults"
- }
- // TODO: Switch to t.Run when we no longer support Go 1.6.
- t.Logf("TEST: %v", name)
- workdir, err := ioutil.TempDir("", "proto-test")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(workdir)
-
- for _, dir := range []string{"alpha", "beta", "out"} {
- if err := os.MkdirAll(filepath.Join(workdir, dir), 0777); err != nil {
- t.Fatal(err)
- }
- }
-
- if err := ioutil.WriteFile(filepath.Join(workdir, "alpha", "a.proto"), []byte(aProto), 0666); err != nil {
- t.Fatal(err)
- }
-
- if err := ioutil.WriteFile(filepath.Join(workdir, "beta", "b.proto"), []byte(bProto), 0666); err != nil {
- t.Fatal(err)
- }
-
- protoc(t, []string{
- "-I" + workdir,
- "--go_out=" + test.parameters + ":" + filepath.Join(workdir, "out"),
- filepath.Join(workdir, "alpha", "a.proto"),
- })
- protoc(t, []string{
- "-I" + workdir,
- "--go_out=" + test.parameters + ":" + filepath.Join(workdir, "out"),
- filepath.Join(workdir, "beta", "b.proto"),
- })
-
- contents := make(map[string]string)
- gotFiles := make(map[string]bool)
- outdir := filepath.Join(workdir, "out")
- filepath.Walk(outdir, func(p string, info os.FileInfo, _ error) error {
- if info.IsDir() {
- return nil
- }
- base := filepath.Base(p)
- if base == "a.pb.go" || base == "b.pb.go" {
- b, err := ioutil.ReadFile(p)
- if err != nil {
- t.Fatal(err)
- }
- contents[base] = string(b)
- }
- relPath, _ := filepath.Rel(outdir, p)
- gotFiles[relPath] = true
- return nil
- })
- for got := range gotFiles {
- if runtime.GOOS == "windows" {
- got = filepath.ToSlash(got)
- }
- if !test.wantFiles[got] {
- t.Errorf("unexpected output file: %v", got)
- }
- }
- for want := range test.wantFiles {
- if runtime.GOOS == "windows" {
- want = filepath.FromSlash(want)
- }
- if !gotFiles[want] {
- t.Errorf("missing output file: %v", want)
- }
- }
- gotPackageA, gotImports, err := parseFile(contents["a.pb.go"])
- if err != nil {
- t.Fatal(err)
- }
- gotPackageB, _, err := parseFile(contents["b.pb.go"])
- if err != nil {
- t.Fatal(err)
- }
- if got, want := gotPackageA, test.wantPackageA; want != got {
- t.Errorf("output file a.pb.go is package %q, want %q", got, want)
- }
- if got, want := gotPackageB, test.wantPackageB; want != got {
- t.Errorf("output file b.pb.go is package %q, want %q", got, want)
- }
- missingImport := false
- WantImport:
- for want := range test.wantImportsA {
- for _, imp := range gotImports {
- if `"`+want+`"` == imp {
- continue WantImport
- }
- }
- t.Errorf("output file a.pb.go does not contain expected import %q", want)
- missingImport = true
- }
- if missingImport {
- t.Error("got imports:")
- for _, imp := range gotImports {
- t.Errorf(" %v", imp)
- }
- }
- }
-}
-
-func TestPackageComment(t *testing.T) {
- workdir, err := ioutil.TempDir("", "proto-test")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(workdir)
-
- var packageRE = regexp.MustCompile(`(?m)^package .*`)
-
- for i, test := range []struct {
- goPackageOption string
- wantPackage string
- }{{
- goPackageOption: ``,
- wantPackage: `package proto_package`,
- }, {
- goPackageOption: `option go_package = "go_package";`,
- wantPackage: `package go_package`,
- }, {
- goPackageOption: `option go_package = "import/path/of/go_package";`,
- wantPackage: `package go_package // import "import/path/of/go_package"`,
- }, {
- goPackageOption: `option go_package = "import/path/of/something;go_package";`,
- wantPackage: `package go_package // import "import/path/of/something"`,
- }, {
- goPackageOption: `option go_package = "import_path;go_package";`,
- wantPackage: `package go_package // import "import_path"`,
- }} {
- srcName := filepath.Join(workdir, fmt.Sprintf("%d.proto", i))
- tgtName := filepath.Join(workdir, fmt.Sprintf("%d.pb.go", i))
-
- buf := &bytes.Buffer{}
- fmt.Fprintln(buf, `syntax = "proto3";`)
- fmt.Fprintln(buf, `package proto_package;`)
- fmt.Fprintln(buf, test.goPackageOption)
- if err := ioutil.WriteFile(srcName, buf.Bytes(), 0666); err != nil {
- t.Fatal(err)
- }
-
- protoc(t, []string{"-I" + workdir, "--go_out=paths=source_relative:" + workdir, srcName})
-
- out, err := ioutil.ReadFile(tgtName)
- if err != nil {
- t.Fatal(err)
- }
-
- pkg := packageRE.Find(out)
- if pkg == nil {
- t.Errorf("generated .pb.go contains no package line\n\nsource:\n%v\n\noutput:\n%v", buf.String(), string(out))
- continue
- }
-
- if got, want := string(pkg), test.wantPackage; got != want {
- t.Errorf("unexpected package statement with go_package = %q\n got: %v\nwant: %v", test.goPackageOption, got, want)
- }
- }
-}
-
-// parseFile returns a file's package name and a list of all packages it imports.
-func parseFile(source string) (packageName string, imports []string, err error) {
- fset := token.NewFileSet()
- f, err := parser.ParseFile(fset, "", source, parser.ImportsOnly)
- if err != nil {
- return "", nil, err
- }
- for _, imp := range f.Imports {
- imports = append(imports, imp.Path.Value)
- }
- return f.Name.Name, imports, nil
-}
-
-func protoc(t *testing.T, args []string) {
- cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
- cmd.Args = append(cmd.Args, args...)
- // We set the RUN_AS_PROTOC_GEN_GO environment variable to indicate that
- // the subprocess should act as a proto compiler rather than a test.
- cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_GEN_GO=1")
- out, err := cmd.CombinedOutput()
- if len(out) > 0 || err != nil {
- t.Log("RUNNING: ", strings.Join(cmd.Args, " "))
- }
- if len(out) > 0 {
- t.Log(string(out))
- }
- if err != nil {
- t.Fatalf("protoc: %v", err)
- }
-}
-
-func hasReleaseTag(want string) bool {
- for _, tag := range build.Default.ReleaseTags {
- if tag == want {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go
index faef1abb7..40cba163b 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go
@@ -1,42 +1,17 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package grpc is deprecated.
//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
+// This package is excluded from the Go protocol buffer compatibility guarantee
+// and may be deleted at some point in the future.
//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Package grpc outputs gRPC service descriptions in Go code.
-// It runs as a plugin for the Go protocol buffer compiler plugin.
-// It is linked in to protoc-gen-go.
+// Deprecated: Do not use.
package grpc
import (
"fmt"
- "path"
"strconv"
"strings"
@@ -48,13 +23,15 @@ import (
// It is incremented whenever an incompatibility between the generated code and
// the grpc package is introduced; the generated code references
// a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion).
-const generatedCodeVersion = 4
+const generatedCodeVersion = 6
// Paths for packages used by code generated in this file,
// relative to the import_prefix of the generator.Generator.
const (
- contextPkgPath = "golang.org/x/net/context"
+ contextPkgPath = "context"
grpcPkgPath = "google.golang.org/grpc"
+ codePkgPath = "google.golang.org/grpc/codes"
+ statusPkgPath = "google.golang.org/grpc/status"
)
func init() {
@@ -83,8 +60,6 @@ var (
// Init initializes the plugin.
func (g *grpc) Init(gen *generator.Generator) {
g.gen = gen
- contextPkg = generator.RegisterUniquePackageName("context", nil)
- grpcPkg = generator.RegisterUniquePackageName("grpc", nil)
}
// Given a type name defined in a .proto, return its object.
@@ -108,9 +83,12 @@ func (g *grpc) Generate(file *generator.FileDescriptor) {
return
}
+ contextPkg = string(g.gen.AddImport(contextPkgPath))
+ grpcPkg = string(g.gen.AddImport(grpcPkgPath))
+
g.P("// Reference imports to suppress errors if they are not otherwise used.")
g.P("var _ ", contextPkg, ".Context")
- g.P("var _ ", grpcPkg, ".ClientConn")
+ g.P("var _ ", grpcPkg, ".ClientConnInterface")
g.P()
// Assert version compatibility.
@@ -126,14 +104,6 @@ func (g *grpc) Generate(file *generator.FileDescriptor) {
// GenerateImports generates the import declaration for this file.
func (g *grpc) GenerateImports(file *generator.FileDescriptor) {
- if len(file.FileDescriptorProto.Service) == 0 {
- return
- }
- g.P("import (")
- g.P(contextPkg, " ", generator.GoImportPath(path.Join(string(g.gen.ImportPrefix), contextPkgPath)))
- g.P(grpcPkg, " ", generator.GoImportPath(path.Join(string(g.gen.ImportPrefix), grpcPkgPath)))
- g.P(")")
- g.P()
}
// reservedClientName records whether a client name is reserved on the client side.
@@ -172,6 +142,10 @@ func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.Servi
g.P("type ", servName, "Client interface {")
for i, method := range service.Method {
g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
+ if method.GetOptions().GetDeprecated() {
+ g.P("//")
+ g.P(deprecationComment)
+ }
g.P(g.generateClientSignature(servName, method))
}
g.P("}")
@@ -179,7 +153,7 @@ func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.Servi
// Client structure.
g.P("type ", unexport(servName), "Client struct {")
- g.P("cc *", grpcPkg, ".ClientConn")
+ g.P("cc ", grpcPkg, ".ClientConnInterface")
g.P("}")
g.P()
@@ -187,7 +161,7 @@ func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.Servi
if deprecated {
g.P(deprecationComment)
}
- g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
+ g.P("func New", servName, "Client (cc ", grpcPkg, ".ClientConnInterface) ", servName, "Client {")
g.P("return &", unexport(servName), "Client{cc}")
g.P("}")
g.P()
@@ -219,11 +193,21 @@ func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.Servi
g.P("type ", serverType, " interface {")
for i, method := range service.Method {
g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
+ if method.GetOptions().GetDeprecated() {
+ g.P("//")
+ g.P(deprecationComment)
+ }
g.P(g.generateServerSignature(servName, method))
}
g.P("}")
g.P()
+ // Server Unimplemented struct for forward compatibility.
+ if deprecated {
+ g.P(deprecationComment)
+ }
+ g.generateUnimplementedServer(servName, service)
+
// Server registration.
if deprecated {
g.P(deprecationComment)
@@ -277,6 +261,35 @@ func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.Servi
g.P()
}
+// generateUnimplementedServer creates the unimplemented server struct
+func (g *grpc) generateUnimplementedServer(servName string, service *pb.ServiceDescriptorProto) {
+ serverType := servName + "Server"
+ g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.")
+ g.P("type Unimplemented", serverType, " struct {")
+ g.P("}")
+ g.P()
+ // UnimplementedServer's concrete methods
+ for _, method := range service.Method {
+ g.generateServerMethodConcrete(servName, method)
+ }
+ g.P()
+}
+
+// generateServerMethodConcrete returns unimplemented methods which ensure forward compatibility
+func (g *grpc) generateServerMethodConcrete(servName string, method *pb.MethodDescriptorProto) {
+ header := g.generateServerSignatureWithParamNames(servName, method)
+ g.P("func (*Unimplemented", servName, "Server) ", header, " {")
+ var nilArg string
+ if !method.GetServerStreaming() && !method.GetClientStreaming() {
+ nilArg = "nil, "
+ }
+ methName := generator.CamelCase(method.GetName())
+ statusPkg := string(g.gen.AddImport(statusPkgPath))
+ codePkg := string(g.gen.AddImport(codePkgPath))
+ g.P("return ", nilArg, statusPkg, `.Errorf(`, codePkg, `.Unimplemented, "method `, methName, ` not implemented")`)
+ g.P("}")
+}
+
// generateClientSignature returns the client-side signature for a method.
func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string {
origMethName := method.GetName()
@@ -376,6 +389,30 @@ func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar strin
}
}
+// generateServerSignatureWithParamNames returns the server-side signature for a method with parameter names.
+func (g *grpc) generateServerSignatureWithParamNames(servName string, method *pb.MethodDescriptorProto) string {
+ origMethName := method.GetName()
+ methName := generator.CamelCase(origMethName)
+ if reservedClientName[methName] {
+ methName += "_"
+ }
+
+ var reqArgs []string
+ ret := "error"
+ if !method.GetServerStreaming() && !method.GetClientStreaming() {
+ reqArgs = append(reqArgs, "ctx "+contextPkg+".Context")
+ ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
+ }
+ if !method.GetClientStreaming() {
+ reqArgs = append(reqArgs, "req *"+g.typeName(method.GetInputType()))
+ }
+ if method.GetServerStreaming() || method.GetClientStreaming() {
+ reqArgs = append(reqArgs, "srv "+servName+"_"+generator.CamelCase(origMethName)+"Server")
+ }
+
+ return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
+}
+
// generateServerSignature returns the server-side signature for a method.
func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string {
origMethName := method.GetName()
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go
deleted file mode 100644
index 532a55005..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package main
-
-import _ "github.com/golang/protobuf/protoc-gen-go/grpc"
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go
index 8e2486de0..d45b719d1 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go
@@ -1,98 +1,74 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2010 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate
-// Go code. Run it by building this program and putting it in your path with
-// the name
-// protoc-gen-go
-// That word 'go' at the end becomes part of the option string set for the
-// protocol compiler, so once the protocol compiler (protoc) is installed
-// you can run
-// protoc --go_out=output_directory input_directory/file.proto
-// to generate Go bindings for the protocol defined by file.proto.
-// With that input, the output will be written to
-// output_directory/file.pb.go
+// Go code. Install it by building this program and making it accessible within
+// your PATH with the name:
+// protoc-gen-go
+//
+// The 'go' suffix becomes part of the argument for the protocol compiler,
+// such that it can be invoked as:
+// protoc --go_out=paths=source_relative:. path/to/file.proto
//
-// The generated code is documented in the package comment for
-// the library.
+// This generates Go bindings for the protocol buffer defined by file.proto.
+// With that input, the output will be written to:
+// path/to/file.pb.go
//
// See the README and documentation for protocol buffers to learn more:
-// https://developers.google.com/protocol-buffers/
+// https://developers.google.com/protocol-buffers/
package main
import (
- "io/ioutil"
- "os"
+ "flag"
+ "fmt"
+ "strings"
- "github.com/golang/protobuf/proto"
- "github.com/golang/protobuf/protoc-gen-go/generator"
+ "github.com/golang/protobuf/internal/gengogrpc"
+ gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
+ "google.golang.org/protobuf/compiler/protogen"
)
func main() {
- // Begin by allocating a generator. The request and response structures are stored there
- // so we can do error handling easily - the response structure contains the field to
- // report failure.
- g := generator.New()
-
- data, err := ioutil.ReadAll(os.Stdin)
- if err != nil {
- g.Error(err, "reading input")
- }
-
- if err := proto.Unmarshal(data, g.Request); err != nil {
- g.Error(err, "parsing input proto")
- }
-
- if len(g.Request.FileToGenerate) == 0 {
- g.Fail("no files to generate")
- }
-
- g.CommandLineParameters(g.Request.GetParameter())
-
- // Create a wrapped version of the Descriptors and EnumDescriptors that
- // point to the file that defines them.
- g.WrapTypes()
-
- g.SetPackageNames()
- g.BuildTypeNameMap()
-
- g.GenerateAllFiles()
-
- // Send back the results.
- data, err = proto.Marshal(g.Response)
- if err != nil {
- g.Error(err, "failed to marshal output proto")
- }
- _, err = os.Stdout.Write(data)
- if err != nil {
- g.Error(err, "failed to write output proto")
+ var (
+ flags flag.FlagSet
+ plugins = flags.String("plugins", "", "list of plugins to enable (supported values: grpc)")
+ importPrefix = flags.String("import_prefix", "", "prefix to prepend to import paths")
+ )
+ importRewriteFunc := func(importPath protogen.GoImportPath) protogen.GoImportPath {
+ switch importPath {
+ case "context", "fmt", "math":
+ return importPath
+ }
+ if *importPrefix != "" {
+ return protogen.GoImportPath(*importPrefix) + importPath
+ }
+ return importPath
}
+ protogen.Options{
+ ParamFunc: flags.Set,
+ ImportRewriteFunc: importRewriteFunc,
+ }.Run(func(gen *protogen.Plugin) error {
+ grpc := false
+ for _, plugin := range strings.Split(*plugins, ",") {
+ switch plugin {
+ case "grpc":
+ grpc = true
+ case "":
+ default:
+ return fmt.Errorf("protoc-gen-go: unknown plugin %q", plugin)
+ }
+ }
+ for _, f := range gen.Files {
+ if !f.Generate {
+ continue
+ }
+ g := gengo.GenerateFile(gen, f)
+ if grpc {
+ gengogrpc.GenerateFileContent(gen, f, g)
+ }
+ }
+ gen.SupportedFeatures = gengo.SupportedFeatures
+ return nil
+ })
}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go
index 61bfc10e0..b7b4a2f94 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go
@@ -1,369 +1,75 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/compiler/plugin.proto
+// source: github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto
-/*
-Package plugin_go is a generated protocol buffer package.
-
-It is generated from these files:
- google/protobuf/compiler/plugin.proto
-
-It has these top-level messages:
- Version
- CodeGeneratorRequest
- CodeGeneratorResponse
-*/
package plugin_go
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// The version number of protocol compiler.
-type Version struct {
- Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
- Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
- Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"`
- // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
- // be empty for mainline stable releases.
- Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Version) Reset() { *m = Version{} }
-func (m *Version) String() string { return proto.CompactTextString(m) }
-func (*Version) ProtoMessage() {}
-func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-func (m *Version) Unmarshal(b []byte) error {
- return xxx_messageInfo_Version.Unmarshal(m, b)
-}
-func (m *Version) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Version.Marshal(b, m, deterministic)
-}
-func (dst *Version) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Version.Merge(dst, src)
-}
-func (m *Version) XXX_Size() int {
- return xxx_messageInfo_Version.Size(m)
-}
-func (m *Version) XXX_DiscardUnknown() {
- xxx_messageInfo_Version.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Version proto.InternalMessageInfo
-
-func (m *Version) GetMajor() int32 {
- if m != nil && m.Major != nil {
- return *m.Major
- }
- return 0
-}
-
-func (m *Version) GetMinor() int32 {
- if m != nil && m.Minor != nil {
- return *m.Minor
- }
- return 0
-}
-
-func (m *Version) GetPatch() int32 {
- if m != nil && m.Patch != nil {
- return *m.Patch
- }
- return 0
-}
-
-func (m *Version) GetSuffix() string {
- if m != nil && m.Suffix != nil {
- return *m.Suffix
- }
- return ""
-}
-
-// An encoded CodeGeneratorRequest is written to the plugin's stdin.
-type CodeGeneratorRequest struct {
- // The .proto files that were explicitly listed on the command-line. The
- // code generator should generate code only for these files. Each file's
- // descriptor will be included in proto_file, below.
- FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"`
- // The generator parameter passed on the command-line.
- Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
- // FileDescriptorProtos for all files in files_to_generate and everything
- // they import. The files will appear in topological order, so each file
- // appears before any file that imports it.
- //
- // protoc guarantees that all proto_files will be written after
- // the fields above, even though this is not technically guaranteed by the
- // protobuf wire format. This theoretically could allow a plugin to stream
- // in the FileDescriptorProtos and handle them one by one rather than read
- // the entire set into memory at once. However, as of this writing, this
- // is not similarly optimized on protoc's end -- it will store all fields in
- // memory at once before sending them to the plugin.
- //
- // Type names of fields and extensions in the FileDescriptorProto are always
- // fully qualified.
- ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"`
- // The version number of protocol compiler.
- CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} }
-func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) }
-func (*CodeGeneratorRequest) ProtoMessage() {}
-func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
-func (m *CodeGeneratorRequest) Unmarshal(b []byte) error {
- return xxx_messageInfo_CodeGeneratorRequest.Unmarshal(m, b)
-}
-func (m *CodeGeneratorRequest) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_CodeGeneratorRequest.Marshal(b, m, deterministic)
-}
-func (dst *CodeGeneratorRequest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_CodeGeneratorRequest.Merge(dst, src)
-}
-func (m *CodeGeneratorRequest) XXX_Size() int {
- return xxx_messageInfo_CodeGeneratorRequest.Size(m)
-}
-func (m *CodeGeneratorRequest) XXX_DiscardUnknown() {
- xxx_messageInfo_CodeGeneratorRequest.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_CodeGeneratorRequest proto.InternalMessageInfo
-
-func (m *CodeGeneratorRequest) GetFileToGenerate() []string {
- if m != nil {
- return m.FileToGenerate
- }
- return nil
-}
-
-func (m *CodeGeneratorRequest) GetParameter() string {
- if m != nil && m.Parameter != nil {
- return *m.Parameter
- }
- return ""
-}
-
-func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto {
- if m != nil {
- return m.ProtoFile
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ pluginpb "google.golang.org/protobuf/types/pluginpb"
+ reflect "reflect"
+)
+
+// Symbols defined in public import of google/protobuf/compiler/plugin.proto.
+
+type CodeGeneratorResponse_Feature = pluginpb.CodeGeneratorResponse_Feature
+
+const CodeGeneratorResponse_FEATURE_NONE = pluginpb.CodeGeneratorResponse_FEATURE_NONE
+const CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL = pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL
+
+var CodeGeneratorResponse_Feature_name = pluginpb.CodeGeneratorResponse_Feature_name
+var CodeGeneratorResponse_Feature_value = pluginpb.CodeGeneratorResponse_Feature_value
+
+type Version = pluginpb.Version
+type CodeGeneratorRequest = pluginpb.CodeGeneratorRequest
+type CodeGeneratorResponse = pluginpb.CodeGeneratorResponse
+type CodeGeneratorResponse_File = pluginpb.CodeGeneratorResponse_File
+
+var File_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto protoreflect.FileDescriptor
+
+var file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_rawDesc = []byte{
+ 0x0a, 0x3c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69,
+ 0x6e, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x25,
+ 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f,
+ 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x72, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x2e,
+ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x3b, 0x5a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
+ 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
+ 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67,
+ 0x6f, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x3b, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x5f,
+ 0x67, 0x6f, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x32,
+}
+
+var file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_init() }
+func file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_init() {
+ if File_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto != nil {
+ return
}
- return nil
-}
-
-func (m *CodeGeneratorRequest) GetCompilerVersion() *Version {
- if m != nil {
- return m.CompilerVersion
- }
- return nil
-}
-
-// The plugin writes an encoded CodeGeneratorResponse to stdout.
-type CodeGeneratorResponse struct {
- // Error message. If non-empty, code generation failed. The plugin process
- // should exit with status code zero even if it reports an error in this way.
- //
- // This should be used to indicate errors in .proto files which prevent the
- // code generator from generating correct code. Errors which indicate a
- // problem in protoc itself -- such as the input CodeGeneratorRequest being
- // unparseable -- should be reported by writing a message to stderr and
- // exiting with a non-zero status code.
- Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
- File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} }
-func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) }
-func (*CodeGeneratorResponse) ProtoMessage() {}
-func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
-func (m *CodeGeneratorResponse) Unmarshal(b []byte) error {
- return xxx_messageInfo_CodeGeneratorResponse.Unmarshal(m, b)
-}
-func (m *CodeGeneratorResponse) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_CodeGeneratorResponse.Marshal(b, m, deterministic)
-}
-func (dst *CodeGeneratorResponse) XXX_Merge(src proto.Message) {
- xxx_messageInfo_CodeGeneratorResponse.Merge(dst, src)
-}
-func (m *CodeGeneratorResponse) XXX_Size() int {
- return xxx_messageInfo_CodeGeneratorResponse.Size(m)
-}
-func (m *CodeGeneratorResponse) XXX_DiscardUnknown() {
- xxx_messageInfo_CodeGeneratorResponse.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_CodeGeneratorResponse proto.InternalMessageInfo
-
-func (m *CodeGeneratorResponse) GetError() string {
- if m != nil && m.Error != nil {
- return *m.Error
- }
- return ""
-}
-
-func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File {
- if m != nil {
- return m.File
- }
- return nil
-}
-
-// Represents a single generated file.
-type CodeGeneratorResponse_File struct {
- // The file name, relative to the output directory. The name must not
- // contain "." or ".." components and must be relative, not be absolute (so,
- // the file cannot lie outside the output directory). "/" must be used as
- // the path separator, not "\".
- //
- // If the name is omitted, the content will be appended to the previous
- // file. This allows the generator to break large files into small chunks,
- // and allows the generated text to be streamed back to protoc so that large
- // files need not reside completely in memory at one time. Note that as of
- // this writing protoc does not optimize for this -- it will read the entire
- // CodeGeneratorResponse before writing files to disk.
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- // If non-empty, indicates that the named file should already exist, and the
- // content here is to be inserted into that file at a defined insertion
- // point. This feature allows a code generator to extend the output
- // produced by another code generator. The original generator may provide
- // insertion points by placing special annotations in the file that look
- // like:
- // @@protoc_insertion_point(NAME)
- // The annotation can have arbitrary text before and after it on the line,
- // which allows it to be placed in a comment. NAME should be replaced with
- // an identifier naming the point -- this is what other generators will use
- // as the insertion_point. Code inserted at this point will be placed
- // immediately above the line containing the insertion point (thus multiple
- // insertions to the same point will come out in the order they were added).
- // The double-@ is intended to make it unlikely that the generated code
- // could contain things that look like insertion points by accident.
- //
- // For example, the C++ code generator places the following line in the
- // .pb.h files that it generates:
- // // @@protoc_insertion_point(namespace_scope)
- // This line appears within the scope of the file's package namespace, but
- // outside of any particular class. Another plugin can then specify the
- // insertion_point "namespace_scope" to generate additional classes or
- // other declarations that should be placed in this scope.
- //
- // Note that if the line containing the insertion point begins with
- // whitespace, the same whitespace will be added to every line of the
- // inserted text. This is useful for languages like Python, where
- // indentation matters. In these languages, the insertion point comment
- // should be indented the same amount as any inserted code will need to be
- // in order to work correctly in that context.
- //
- // The code generator that generates the initial file and the one which
- // inserts into it must both run as part of a single invocation of protoc.
- // Code generators are executed in the order in which they appear on the
- // command line.
- //
- // If |insertion_point| is present, |name| must also be present.
- InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"`
- // The file contents.
- Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} }
-func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) }
-func (*CodeGeneratorResponse_File) ProtoMessage() {}
-func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
-func (m *CodeGeneratorResponse_File) Unmarshal(b []byte) error {
- return xxx_messageInfo_CodeGeneratorResponse_File.Unmarshal(m, b)
-}
-func (m *CodeGeneratorResponse_File) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_CodeGeneratorResponse_File.Marshal(b, m, deterministic)
-}
-func (dst *CodeGeneratorResponse_File) XXX_Merge(src proto.Message) {
- xxx_messageInfo_CodeGeneratorResponse_File.Merge(dst, src)
-}
-func (m *CodeGeneratorResponse_File) XXX_Size() int {
- return xxx_messageInfo_CodeGeneratorResponse_File.Size(m)
-}
-func (m *CodeGeneratorResponse_File) XXX_DiscardUnknown() {
- xxx_messageInfo_CodeGeneratorResponse_File.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_CodeGeneratorResponse_File proto.InternalMessageInfo
-
-func (m *CodeGeneratorResponse_File) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *CodeGeneratorResponse_File) GetInsertionPoint() string {
- if m != nil && m.InsertionPoint != nil {
- return *m.InsertionPoint
- }
- return ""
-}
-
-func (m *CodeGeneratorResponse_File) GetContent() string {
- if m != nil && m.Content != nil {
- return *m.Content
- }
- return ""
-}
-
-func init() {
- proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version")
- proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest")
- proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse")
- proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File")
-}
-
-func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) }
-
-var fileDescriptor0 = []byte{
- // 417 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41,
- 0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2,
- 0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30,
- 0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa,
- 0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91,
- 0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63,
- 0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb,
- 0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55,
- 0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8,
- 0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1,
- 0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f,
- 0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d,
- 0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2,
- 0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a,
- 0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2,
- 0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d,
- 0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda,
- 0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed,
- 0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34,
- 0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79,
- 0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45,
- 0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4,
- 0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e,
- 0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92,
- 0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d,
- 0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00,
- 0x00,
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto = out.File
+ file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_rawDesc = nil
+ file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_goTypes = nil
+ file_github_com_golang_protobuf_protoc_gen_go_plugin_plugin_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden
deleted file mode 100644
index 8953d0ff8..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden
+++ /dev/null
@@ -1,83 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: google/protobuf/compiler/plugin.proto
-// DO NOT EDIT!
-
-package google_protobuf_compiler
-
-import proto "github.com/golang/protobuf/proto"
-import "math"
-import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
-
-// Reference proto and math imports to suppress error if they are not otherwise used.
-var _ = proto.GetString
-var _ = math.Inf
-
-type CodeGeneratorRequest struct {
- FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"`
- Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
- ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} }
-func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) }
-func (*CodeGeneratorRequest) ProtoMessage() {}
-
-func (this *CodeGeneratorRequest) GetParameter() string {
- if this != nil && this.Parameter != nil {
- return *this.Parameter
- }
- return ""
-}
-
-type CodeGeneratorResponse struct {
- Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
- File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} }
-func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) }
-func (*CodeGeneratorResponse) ProtoMessage() {}
-
-func (this *CodeGeneratorResponse) GetError() string {
- if this != nil && this.Error != nil {
- return *this.Error
- }
- return ""
-}
-
-type CodeGeneratorResponse_File struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"`
- Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} }
-func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) }
-func (*CodeGeneratorResponse_File) ProtoMessage() {}
-
-func (this *CodeGeneratorResponse_File) GetName() string {
- if this != nil && this.Name != nil {
- return *this.Name
- }
- return ""
-}
-
-func (this *CodeGeneratorResponse_File) GetInsertionPoint() string {
- if this != nil && this.InsertionPoint != nil {
- return *this.InsertionPoint
- }
- return ""
-}
-
-func (this *CodeGeneratorResponse_File) GetContent() string {
- if this != nil && this.Content != nil {
- return *this.Content
- }
- return ""
-}
-
-func init() {
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto
deleted file mode 100644
index 5b5574529..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto
+++ /dev/null
@@ -1,167 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-//
-// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
-// change.
-//
-// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
-// just a program that reads a CodeGeneratorRequest from stdin and writes a
-// CodeGeneratorResponse to stdout.
-//
-// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
-// of dealing with the raw protocol defined here.
-//
-// A plugin executable needs only to be placed somewhere in the path. The
-// plugin should be named "protoc-gen-$NAME", and will then be used when the
-// flag "--${NAME}_out" is passed to protoc.
-
-syntax = "proto2";
-package google.protobuf.compiler;
-option java_package = "com.google.protobuf.compiler";
-option java_outer_classname = "PluginProtos";
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go";
-
-import "google/protobuf/descriptor.proto";
-
-// The version number of protocol compiler.
-message Version {
- optional int32 major = 1;
- optional int32 minor = 2;
- optional int32 patch = 3;
- // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
- // be empty for mainline stable releases.
- optional string suffix = 4;
-}
-
-// An encoded CodeGeneratorRequest is written to the plugin's stdin.
-message CodeGeneratorRequest {
- // The .proto files that were explicitly listed on the command-line. The
- // code generator should generate code only for these files. Each file's
- // descriptor will be included in proto_file, below.
- repeated string file_to_generate = 1;
-
- // The generator parameter passed on the command-line.
- optional string parameter = 2;
-
- // FileDescriptorProtos for all files in files_to_generate and everything
- // they import. The files will appear in topological order, so each file
- // appears before any file that imports it.
- //
- // protoc guarantees that all proto_files will be written after
- // the fields above, even though this is not technically guaranteed by the
- // protobuf wire format. This theoretically could allow a plugin to stream
- // in the FileDescriptorProtos and handle them one by one rather than read
- // the entire set into memory at once. However, as of this writing, this
- // is not similarly optimized on protoc's end -- it will store all fields in
- // memory at once before sending them to the plugin.
- //
- // Type names of fields and extensions in the FileDescriptorProto are always
- // fully qualified.
- repeated FileDescriptorProto proto_file = 15;
-
- // The version number of protocol compiler.
- optional Version compiler_version = 3;
-
-}
-
-// The plugin writes an encoded CodeGeneratorResponse to stdout.
-message CodeGeneratorResponse {
- // Error message. If non-empty, code generation failed. The plugin process
- // should exit with status code zero even if it reports an error in this way.
- //
- // This should be used to indicate errors in .proto files which prevent the
- // code generator from generating correct code. Errors which indicate a
- // problem in protoc itself -- such as the input CodeGeneratorRequest being
- // unparseable -- should be reported by writing a message to stderr and
- // exiting with a non-zero status code.
- optional string error = 1;
-
- // Represents a single generated file.
- message File {
- // The file name, relative to the output directory. The name must not
- // contain "." or ".." components and must be relative, not be absolute (so,
- // the file cannot lie outside the output directory). "/" must be used as
- // the path separator, not "\".
- //
- // If the name is omitted, the content will be appended to the previous
- // file. This allows the generator to break large files into small chunks,
- // and allows the generated text to be streamed back to protoc so that large
- // files need not reside completely in memory at one time. Note that as of
- // this writing protoc does not optimize for this -- it will read the entire
- // CodeGeneratorResponse before writing files to disk.
- optional string name = 1;
-
- // If non-empty, indicates that the named file should already exist, and the
- // content here is to be inserted into that file at a defined insertion
- // point. This feature allows a code generator to extend the output
- // produced by another code generator. The original generator may provide
- // insertion points by placing special annotations in the file that look
- // like:
- // @@protoc_insertion_point(NAME)
- // The annotation can have arbitrary text before and after it on the line,
- // which allows it to be placed in a comment. NAME should be replaced with
- // an identifier naming the point -- this is what other generators will use
- // as the insertion_point. Code inserted at this point will be placed
- // immediately above the line containing the insertion point (thus multiple
- // insertions to the same point will come out in the order they were added).
- // The double-@ is intended to make it unlikely that the generated code
- // could contain things that look like insertion points by accident.
- //
- // For example, the C++ code generator places the following line in the
- // .pb.h files that it generates:
- // // @@protoc_insertion_point(namespace_scope)
- // This line appears within the scope of the file's package namespace, but
- // outside of any particular class. Another plugin can then specify the
- // insertion_point "namespace_scope" to generate additional classes or
- // other declarations that should be placed in this scope.
- //
- // Note that if the line containing the insertion point begins with
- // whitespace, the same whitespace will be added to every line of the
- // inserted text. This is useful for languages like Python, where
- // indentation matters. In these languages, the insertion point comment
- // should be indented the same amount as any inserted code will need to be
- // in order to work correctly in that context.
- //
- // The code generator that generates the initial file and the one which
- // inserts into it must both run as part of a single invocation of protoc.
- // Code generators are executed in the order in which they appear on the
- // command line.
- //
- // If |insertion_point| is present, |name| must also be present.
- optional string insertion_point = 2;
-
- // The file contents.
- optional string content = 15;
- }
- repeated File file = 15;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go
deleted file mode 100644
index ea699eabe..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go
+++ /dev/null
@@ -1,234 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// deprecated/deprecated.proto is a deprecated file.
-
-package deprecated // import "github.com/golang/protobuf/protoc-gen-go/testdata/deprecated"
-
-/*
-package deprecated contains only deprecated messages and services.
-*/
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// DeprecatedEnum contains deprecated values.
-type DeprecatedEnum int32 // Deprecated: Do not use.
-const (
- // DEPRECATED is the iota value of this enum.
- DeprecatedEnum_DEPRECATED DeprecatedEnum = 0 // Deprecated: Do not use.
-)
-
-var DeprecatedEnum_name = map[int32]string{
- 0: "DEPRECATED",
-}
-var DeprecatedEnum_value = map[string]int32{
- "DEPRECATED": 0,
-}
-
-func (x DeprecatedEnum) String() string {
- return proto.EnumName(DeprecatedEnum_name, int32(x))
-}
-func (DeprecatedEnum) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_deprecated_9e1889ba21817fad, []int{0}
-}
-
-// DeprecatedRequest is a request to DeprecatedCall.
-//
-// Deprecated: Do not use.
-type DeprecatedRequest struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DeprecatedRequest) Reset() { *m = DeprecatedRequest{} }
-func (m *DeprecatedRequest) String() string { return proto.CompactTextString(m) }
-func (*DeprecatedRequest) ProtoMessage() {}
-func (*DeprecatedRequest) Descriptor() ([]byte, []int) {
- return fileDescriptor_deprecated_9e1889ba21817fad, []int{0}
-}
-func (m *DeprecatedRequest) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DeprecatedRequest.Unmarshal(m, b)
-}
-func (m *DeprecatedRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DeprecatedRequest.Marshal(b, m, deterministic)
-}
-func (dst *DeprecatedRequest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DeprecatedRequest.Merge(dst, src)
-}
-func (m *DeprecatedRequest) XXX_Size() int {
- return xxx_messageInfo_DeprecatedRequest.Size(m)
-}
-func (m *DeprecatedRequest) XXX_DiscardUnknown() {
- xxx_messageInfo_DeprecatedRequest.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DeprecatedRequest proto.InternalMessageInfo
-
-// Deprecated: Do not use.
-type DeprecatedResponse struct {
- // DeprecatedField contains a DeprecatedEnum.
- DeprecatedField DeprecatedEnum `protobuf:"varint,1,opt,name=deprecated_field,json=deprecatedField,enum=deprecated.DeprecatedEnum" json:"deprecated_field,omitempty"` // Deprecated: Do not use.
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DeprecatedResponse) Reset() { *m = DeprecatedResponse{} }
-func (m *DeprecatedResponse) String() string { return proto.CompactTextString(m) }
-func (*DeprecatedResponse) ProtoMessage() {}
-func (*DeprecatedResponse) Descriptor() ([]byte, []int) {
- return fileDescriptor_deprecated_9e1889ba21817fad, []int{1}
-}
-func (m *DeprecatedResponse) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DeprecatedResponse.Unmarshal(m, b)
-}
-func (m *DeprecatedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DeprecatedResponse.Marshal(b, m, deterministic)
-}
-func (dst *DeprecatedResponse) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DeprecatedResponse.Merge(dst, src)
-}
-func (m *DeprecatedResponse) XXX_Size() int {
- return xxx_messageInfo_DeprecatedResponse.Size(m)
-}
-func (m *DeprecatedResponse) XXX_DiscardUnknown() {
- xxx_messageInfo_DeprecatedResponse.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DeprecatedResponse proto.InternalMessageInfo
-
-// Deprecated: Do not use.
-func (m *DeprecatedResponse) GetDeprecatedField() DeprecatedEnum {
- if m != nil {
- return m.DeprecatedField
- }
- return DeprecatedEnum_DEPRECATED
-}
-
-func init() {
- proto.RegisterType((*DeprecatedRequest)(nil), "deprecated.DeprecatedRequest")
- proto.RegisterType((*DeprecatedResponse)(nil), "deprecated.DeprecatedResponse")
- proto.RegisterEnum("deprecated.DeprecatedEnum", DeprecatedEnum_name, DeprecatedEnum_value)
-}
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the grpc package it is being compiled against.
-const _ = grpc.SupportPackageIsVersion4
-
-// DeprecatedServiceClient is the client API for DeprecatedService service.
-//
-// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
-//
-// Deprecated: Do not use.
-type DeprecatedServiceClient interface {
- // DeprecatedCall takes a DeprecatedRequest and returns a DeprecatedResponse.
- DeprecatedCall(ctx context.Context, in *DeprecatedRequest, opts ...grpc.CallOption) (*DeprecatedResponse, error)
-}
-
-type deprecatedServiceClient struct {
- cc *grpc.ClientConn
-}
-
-// Deprecated: Do not use.
-func NewDeprecatedServiceClient(cc *grpc.ClientConn) DeprecatedServiceClient {
- return &deprecatedServiceClient{cc}
-}
-
-// Deprecated: Do not use.
-func (c *deprecatedServiceClient) DeprecatedCall(ctx context.Context, in *DeprecatedRequest, opts ...grpc.CallOption) (*DeprecatedResponse, error) {
- out := new(DeprecatedResponse)
- err := c.cc.Invoke(ctx, "/deprecated.DeprecatedService/DeprecatedCall", in, out, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// DeprecatedServiceServer is the server API for DeprecatedService service.
-//
-// Deprecated: Do not use.
-type DeprecatedServiceServer interface {
- // DeprecatedCall takes a DeprecatedRequest and returns a DeprecatedResponse.
- DeprecatedCall(context.Context, *DeprecatedRequest) (*DeprecatedResponse, error)
-}
-
-// Deprecated: Do not use.
-func RegisterDeprecatedServiceServer(s *grpc.Server, srv DeprecatedServiceServer) {
- s.RegisterService(&_DeprecatedService_serviceDesc, srv)
-}
-
-func _DeprecatedService_DeprecatedCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(DeprecatedRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(DeprecatedServiceServer).DeprecatedCall(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: "/deprecated.DeprecatedService/DeprecatedCall",
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(DeprecatedServiceServer).DeprecatedCall(ctx, req.(*DeprecatedRequest))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-var _DeprecatedService_serviceDesc = grpc.ServiceDesc{
- ServiceName: "deprecated.DeprecatedService",
- HandlerType: (*DeprecatedServiceServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "DeprecatedCall",
- Handler: _DeprecatedService_DeprecatedCall_Handler,
- },
- },
- Streams: []grpc.StreamDesc{},
- Metadata: "deprecated/deprecated.proto",
-}
-
-func init() {
- proto.RegisterFile("deprecated/deprecated.proto", fileDescriptor_deprecated_9e1889ba21817fad)
-}
-
-var fileDescriptor_deprecated_9e1889ba21817fad = []byte{
- // 248 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0x49, 0x2d, 0x28,
- 0x4a, 0x4d, 0x4e, 0x2c, 0x49, 0x4d, 0xd1, 0x47, 0x30, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85,
- 0xb8, 0x10, 0x22, 0x4a, 0xe2, 0x5c, 0x82, 0x2e, 0x70, 0x5e, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71,
- 0x89, 0x15, 0x93, 0x04, 0xa3, 0x52, 0x32, 0x97, 0x10, 0xb2, 0x44, 0x71, 0x41, 0x7e, 0x5e, 0x71,
- 0xaa, 0x90, 0x27, 0x97, 0x00, 0x42, 0x73, 0x7c, 0x5a, 0x66, 0x6a, 0x4e, 0x8a, 0x04, 0xa3, 0x02,
- 0xa3, 0x06, 0x9f, 0x91, 0x94, 0x1e, 0x92, 0x3d, 0x08, 0x9d, 0xae, 0x79, 0xa5, 0xb9, 0x4e, 0x4c,
- 0x12, 0x8c, 0x41, 0xfc, 0x08, 0x69, 0x37, 0x90, 0x36, 0x90, 0x25, 0x5a, 0x1a, 0x5c, 0x7c, 0xa8,
- 0x4a, 0x85, 0x84, 0xb8, 0xb8, 0x5c, 0x5c, 0x03, 0x82, 0x5c, 0x9d, 0x1d, 0x43, 0x5c, 0x5d, 0x04,
- 0x18, 0xa4, 0x98, 0x38, 0x18, 0xa5, 0x98, 0x24, 0x18, 0x8d, 0xf2, 0x90, 0xdd, 0x19, 0x9c, 0x5a,
- 0x54, 0x96, 0x99, 0x9c, 0x2a, 0x14, 0x82, 0xac, 0xdd, 0x39, 0x31, 0x27, 0x47, 0x48, 0x16, 0xbb,
- 0x2b, 0xa0, 0x1e, 0x93, 0x92, 0xc3, 0x25, 0x0d, 0xf1, 0x9e, 0x12, 0x73, 0x07, 0x13, 0xa3, 0x14,
- 0x88, 0x70, 0x72, 0x8c, 0xb2, 0x49, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5,
- 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x07, 0x07, 0x5f, 0x52, 0x69, 0x1a, 0x84, 0x91, 0xac,
- 0x9b, 0x9e, 0x9a, 0xa7, 0x9b, 0x9e, 0xaf, 0x5f, 0x92, 0x5a, 0x5c, 0x92, 0x92, 0x58, 0x92, 0x88,
- 0x14, 0xd2, 0x3b, 0x18, 0x19, 0x93, 0xd8, 0xc0, 0xaa, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff,
- 0x0e, 0xf5, 0x6c, 0x87, 0x8c, 0x01, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto
deleted file mode 100644
index b314166d2..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto
+++ /dev/null
@@ -1,69 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-// package deprecated contains only deprecated messages and services.
-package deprecated;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/deprecated";
-
-option deprecated = true; // file-level deprecation
-
-// DeprecatedRequest is a request to DeprecatedCall.
-message DeprecatedRequest {
- option deprecated = true;
-}
-
-message DeprecatedResponse {
- // comment for DeprecatedResponse is omitted to guarantee deprecation
- // message doesn't append unnecessary comments.
- option deprecated = true;
- // DeprecatedField contains a DeprecatedEnum.
- DeprecatedEnum deprecated_field = 1 [deprecated=true];
-}
-
-// DeprecatedEnum contains deprecated values.
-enum DeprecatedEnum {
- option deprecated = true;
- // DEPRECATED is the iota value of this enum.
- DEPRECATED = 0 [deprecated=true];
-}
-
-// DeprecatedService is for making DeprecatedCalls
-service DeprecatedService {
- option deprecated = true;
-
- // DeprecatedCall takes a DeprecatedRequest and returns a DeprecatedResponse.
- rpc DeprecatedCall(DeprecatedRequest) returns (DeprecatedResponse) {
- option deprecated = true;
- }
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go
deleted file mode 100644
index a08e8eda5..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go
+++ /dev/null
@@ -1,139 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: extension_base/extension_base.proto
-
-package extension_base // import "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type BaseMessage struct {
- Height *int32 `protobuf:"varint,1,opt,name=height" json:"height,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *BaseMessage) Reset() { *m = BaseMessage{} }
-func (m *BaseMessage) String() string { return proto.CompactTextString(m) }
-func (*BaseMessage) ProtoMessage() {}
-func (*BaseMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_base_41d3c712c9fc37fc, []int{0}
-}
-
-var extRange_BaseMessage = []proto.ExtensionRange{
- {Start: 4, End: 9},
- {Start: 16, End: 536870911},
-}
-
-func (*BaseMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_BaseMessage
-}
-func (m *BaseMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_BaseMessage.Unmarshal(m, b)
-}
-func (m *BaseMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_BaseMessage.Marshal(b, m, deterministic)
-}
-func (dst *BaseMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_BaseMessage.Merge(dst, src)
-}
-func (m *BaseMessage) XXX_Size() int {
- return xxx_messageInfo_BaseMessage.Size(m)
-}
-func (m *BaseMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_BaseMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_BaseMessage proto.InternalMessageInfo
-
-func (m *BaseMessage) GetHeight() int32 {
- if m != nil && m.Height != nil {
- return *m.Height
- }
- return 0
-}
-
-// Another message that may be extended, using message_set_wire_format.
-type OldStyleMessage struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `protobuf_messageset:"1" json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OldStyleMessage) Reset() { *m = OldStyleMessage{} }
-func (m *OldStyleMessage) String() string { return proto.CompactTextString(m) }
-func (*OldStyleMessage) ProtoMessage() {}
-func (*OldStyleMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_base_41d3c712c9fc37fc, []int{1}
-}
-
-func (m *OldStyleMessage) MarshalJSON() ([]byte, error) {
- return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions)
-}
-func (m *OldStyleMessage) UnmarshalJSON(buf []byte) error {
- return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)
-}
-
-var extRange_OldStyleMessage = []proto.ExtensionRange{
- {Start: 100, End: 2147483646},
-}
-
-func (*OldStyleMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OldStyleMessage
-}
-func (m *OldStyleMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OldStyleMessage.Unmarshal(m, b)
-}
-func (m *OldStyleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OldStyleMessage.Marshal(b, m, deterministic)
-}
-func (dst *OldStyleMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OldStyleMessage.Merge(dst, src)
-}
-func (m *OldStyleMessage) XXX_Size() int {
- return xxx_messageInfo_OldStyleMessage.Size(m)
-}
-func (m *OldStyleMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_OldStyleMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OldStyleMessage proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*BaseMessage)(nil), "extension_base.BaseMessage")
- proto.RegisterType((*OldStyleMessage)(nil), "extension_base.OldStyleMessage")
-}
-
-func init() {
- proto.RegisterFile("extension_base/extension_base.proto", fileDescriptor_extension_base_41d3c712c9fc37fc)
-}
-
-var fileDescriptor_extension_base_41d3c712c9fc37fc = []byte{
- // 179 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4e, 0xad, 0x28, 0x49,
- 0xcd, 0x2b, 0xce, 0xcc, 0xcf, 0x8b, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x47, 0xe5, 0xea, 0x15, 0x14,
- 0xe5, 0x97, 0xe4, 0x0b, 0xf1, 0xa1, 0x8a, 0x2a, 0x99, 0x72, 0x71, 0x3b, 0x25, 0x16, 0xa7, 0xfa,
- 0xa6, 0x16, 0x17, 0x27, 0xa6, 0xa7, 0x0a, 0x89, 0x71, 0xb1, 0x65, 0xa4, 0x66, 0xa6, 0x67, 0x94,
- 0x48, 0x30, 0x2a, 0x30, 0x6a, 0xb0, 0x06, 0x41, 0x79, 0x5a, 0x2c, 0x1c, 0x2c, 0x02, 0x5c, 0x5a,
- 0x1c, 0x1c, 0x02, 0x02, 0x0d, 0x0d, 0x0d, 0x0d, 0x4c, 0x4a, 0xf2, 0x5c, 0xfc, 0xfe, 0x39, 0x29,
- 0xc1, 0x25, 0x95, 0x39, 0x30, 0xad, 0x5a, 0x1c, 0x1c, 0x29, 0x02, 0xff, 0xff, 0xff, 0xff, 0xcf,
- 0x6e, 0xc5, 0xc4, 0xc1, 0xe8, 0xe4, 0x14, 0xe5, 0x90, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97,
- 0x9c, 0x9f, 0xab, 0x9f, 0x9e, 0x9f, 0x93, 0x98, 0x97, 0xae, 0x0f, 0x76, 0x42, 0x52, 0x69, 0x1a,
- 0x84, 0x91, 0xac, 0x9b, 0x9e, 0x9a, 0xa7, 0x9b, 0x9e, 0xaf, 0x5f, 0x92, 0x5a, 0x5c, 0x92, 0x92,
- 0x58, 0x92, 0x88, 0xe6, 0x62, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7a, 0x7f, 0xb7, 0x2a, 0xd1,
- 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto
deleted file mode 100644
index 0ba74def8..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto
+++ /dev/null
@@ -1,48 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-package extension_base;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base";
-
-message BaseMessage {
- optional int32 height = 1;
- extensions 4 to 9;
- extensions 16 to max;
-}
-
-// Another message that may be extended, using message_set_wire_format.
-message OldStyleMessage {
- option message_set_wire_format = true;
- extensions 100 to max;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go
deleted file mode 100644
index b37321690..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: extension_extra/extension_extra.proto
-
-package extension_extra // import "github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type ExtraMessage struct {
- Width *int32 `protobuf:"varint,1,opt,name=width" json:"width,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ExtraMessage) Reset() { *m = ExtraMessage{} }
-func (m *ExtraMessage) String() string { return proto.CompactTextString(m) }
-func (*ExtraMessage) ProtoMessage() {}
-func (*ExtraMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_extra_83adf2410f49f816, []int{0}
-}
-func (m *ExtraMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ExtraMessage.Unmarshal(m, b)
-}
-func (m *ExtraMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ExtraMessage.Marshal(b, m, deterministic)
-}
-func (dst *ExtraMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ExtraMessage.Merge(dst, src)
-}
-func (m *ExtraMessage) XXX_Size() int {
- return xxx_messageInfo_ExtraMessage.Size(m)
-}
-func (m *ExtraMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_ExtraMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ExtraMessage proto.InternalMessageInfo
-
-func (m *ExtraMessage) GetWidth() int32 {
- if m != nil && m.Width != nil {
- return *m.Width
- }
- return 0
-}
-
-func init() {
- proto.RegisterType((*ExtraMessage)(nil), "extension_extra.ExtraMessage")
-}
-
-func init() {
- proto.RegisterFile("extension_extra/extension_extra.proto", fileDescriptor_extension_extra_83adf2410f49f816)
-}
-
-var fileDescriptor_extension_extra_83adf2410f49f816 = []byte{
- // 133 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xad, 0x28, 0x49,
- 0xcd, 0x2b, 0xce, 0xcc, 0xcf, 0x8b, 0x4f, 0xad, 0x28, 0x29, 0x4a, 0xd4, 0x47, 0xe3, 0xeb, 0x15,
- 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0xf1, 0xa3, 0x09, 0x2b, 0xa9, 0x70, 0xf1, 0xb8, 0x82, 0x18, 0xbe,
- 0xa9, 0xc5, 0xc5, 0x89, 0xe9, 0xa9, 0x42, 0x22, 0x5c, 0xac, 0xe5, 0x99, 0x29, 0x25, 0x19, 0x12,
- 0x8c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x93, 0x73, 0x94, 0x63, 0x7a, 0x66, 0x49, 0x46,
- 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, 0xba, 0x3e, 0xd8, 0xc4,
- 0xa4, 0xd2, 0x34, 0x08, 0x23, 0x59, 0x37, 0x3d, 0x35, 0x4f, 0x37, 0x3d, 0x5f, 0xbf, 0x24, 0xb5,
- 0xb8, 0x24, 0x25, 0xb1, 0x04, 0xc3, 0x05, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf1, 0xec, 0xe3,
- 0xb7, 0xa3, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto
deleted file mode 100644
index 1dd03e70b..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto
+++ /dev/null
@@ -1,40 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-package extension_extra;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra";
-
-message ExtraMessage {
- optional int32 width = 1;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go
deleted file mode 100644
index 052472992..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go
+++ /dev/null
@@ -1,206 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Test that we can use protocol buffers that use extensions.
-
-package testdata
-
-import (
- "bytes"
- "regexp"
- "testing"
-
- "github.com/golang/protobuf/proto"
- base "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base"
- user "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user"
-)
-
-func TestSingleFieldExtension(t *testing.T) {
- bm := &base.BaseMessage{
- Height: proto.Int32(178),
- }
-
- // Use extension within scope of another type.
- vol := proto.Uint32(11)
- err := proto.SetExtension(bm, user.E_LoudMessage_Volume, vol)
- if err != nil {
- t.Fatal("Failed setting extension:", err)
- }
- buf, err := proto.Marshal(bm)
- if err != nil {
- t.Fatal("Failed encoding message with extension:", err)
- }
- bm_new := new(base.BaseMessage)
- if err := proto.Unmarshal(buf, bm_new); err != nil {
- t.Fatal("Failed decoding message with extension:", err)
- }
- if !proto.HasExtension(bm_new, user.E_LoudMessage_Volume) {
- t.Fatal("Decoded message didn't contain extension.")
- }
- vol_out, err := proto.GetExtension(bm_new, user.E_LoudMessage_Volume)
- if err != nil {
- t.Fatal("Failed getting extension:", err)
- }
- if v := vol_out.(*uint32); *v != *vol {
- t.Errorf("vol_out = %v, expected %v", *v, *vol)
- }
- proto.ClearExtension(bm_new, user.E_LoudMessage_Volume)
- if proto.HasExtension(bm_new, user.E_LoudMessage_Volume) {
- t.Fatal("Failed clearing extension.")
- }
-}
-
-func TestMessageExtension(t *testing.T) {
- bm := &base.BaseMessage{
- Height: proto.Int32(179),
- }
-
- // Use extension that is itself a message.
- um := &user.UserMessage{
- Name: proto.String("Dave"),
- Rank: proto.String("Major"),
- }
- err := proto.SetExtension(bm, user.E_LoginMessage_UserMessage, um)
- if err != nil {
- t.Fatal("Failed setting extension:", err)
- }
- buf, err := proto.Marshal(bm)
- if err != nil {
- t.Fatal("Failed encoding message with extension:", err)
- }
- bm_new := new(base.BaseMessage)
- if err := proto.Unmarshal(buf, bm_new); err != nil {
- t.Fatal("Failed decoding message with extension:", err)
- }
- if !proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) {
- t.Fatal("Decoded message didn't contain extension.")
- }
- um_out, err := proto.GetExtension(bm_new, user.E_LoginMessage_UserMessage)
- if err != nil {
- t.Fatal("Failed getting extension:", err)
- }
- if n := um_out.(*user.UserMessage).Name; *n != *um.Name {
- t.Errorf("um_out.Name = %q, expected %q", *n, *um.Name)
- }
- if r := um_out.(*user.UserMessage).Rank; *r != *um.Rank {
- t.Errorf("um_out.Rank = %q, expected %q", *r, *um.Rank)
- }
- proto.ClearExtension(bm_new, user.E_LoginMessage_UserMessage)
- if proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) {
- t.Fatal("Failed clearing extension.")
- }
-}
-
-func TestTopLevelExtension(t *testing.T) {
- bm := &base.BaseMessage{
- Height: proto.Int32(179),
- }
-
- width := proto.Int32(17)
- err := proto.SetExtension(bm, user.E_Width, width)
- if err != nil {
- t.Fatal("Failed setting extension:", err)
- }
- buf, err := proto.Marshal(bm)
- if err != nil {
- t.Fatal("Failed encoding message with extension:", err)
- }
- bm_new := new(base.BaseMessage)
- if err := proto.Unmarshal(buf, bm_new); err != nil {
- t.Fatal("Failed decoding message with extension:", err)
- }
- if !proto.HasExtension(bm_new, user.E_Width) {
- t.Fatal("Decoded message didn't contain extension.")
- }
- width_out, err := proto.GetExtension(bm_new, user.E_Width)
- if err != nil {
- t.Fatal("Failed getting extension:", err)
- }
- if w := width_out.(*int32); *w != *width {
- t.Errorf("width_out = %v, expected %v", *w, *width)
- }
- proto.ClearExtension(bm_new, user.E_Width)
- if proto.HasExtension(bm_new, user.E_Width) {
- t.Fatal("Failed clearing extension.")
- }
-}
-
-func TestMessageSetWireFormat(t *testing.T) {
- osm := new(base.OldStyleMessage)
- osp := &user.OldStyleParcel{
- Name: proto.String("Dave"),
- Height: proto.Int32(178),
- }
-
- err := proto.SetExtension(osm, user.E_OldStyleParcel_MessageSetExtension, osp)
- if err != nil {
- t.Fatal("Failed setting extension:", err)
- }
-
- buf, err := proto.Marshal(osm)
- if err != nil {
- t.Fatal("Failed encoding message:", err)
- }
-
- // Data generated from Python implementation.
- expected := []byte{
- 11, 16, 209, 15, 26, 9, 10, 4, 68, 97, 118, 101, 16, 178, 1, 12,
- }
-
- if !bytes.Equal(expected, buf) {
- t.Errorf("Encoding mismatch.\nwant %+v\n got %+v", expected, buf)
- }
-
- // Check that it is restored correctly.
- osm = new(base.OldStyleMessage)
- if err := proto.Unmarshal(buf, osm); err != nil {
- t.Fatal("Failed decoding message:", err)
- }
- osp_out, err := proto.GetExtension(osm, user.E_OldStyleParcel_MessageSetExtension)
- if err != nil {
- t.Fatal("Failed getting extension:", err)
- }
- osp = osp_out.(*user.OldStyleParcel)
- if *osp.Name != "Dave" || *osp.Height != 178 {
- t.Errorf("Retrieved extension from decoded message is not correct: %+v", osp)
- }
-}
-
-func main() {
- // simpler than rigging up gotest
- testing.Main(regexp.MatchString, []testing.InternalTest{
- {"TestSingleFieldExtension", TestSingleFieldExtension},
- {"TestMessageExtension", TestMessageExtension},
- {"TestTopLevelExtension", TestTopLevelExtension},
- },
- []testing.InternalBenchmark{},
- []testing.InternalExample{})
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go
deleted file mode 100644
index c71879215..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go
+++ /dev/null
@@ -1,401 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: extension_user/extension_user.proto
-
-package extension_user // import "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import extension_base "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base"
-import extension_extra "github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type UserMessage struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Rank *string `protobuf:"bytes,2,opt,name=rank" json:"rank,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UserMessage) Reset() { *m = UserMessage{} }
-func (m *UserMessage) String() string { return proto.CompactTextString(m) }
-func (*UserMessage) ProtoMessage() {}
-func (*UserMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{0}
-}
-func (m *UserMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UserMessage.Unmarshal(m, b)
-}
-func (m *UserMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UserMessage.Marshal(b, m, deterministic)
-}
-func (dst *UserMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UserMessage.Merge(dst, src)
-}
-func (m *UserMessage) XXX_Size() int {
- return xxx_messageInfo_UserMessage.Size(m)
-}
-func (m *UserMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_UserMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UserMessage proto.InternalMessageInfo
-
-func (m *UserMessage) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *UserMessage) GetRank() string {
- if m != nil && m.Rank != nil {
- return *m.Rank
- }
- return ""
-}
-
-// Extend inside the scope of another type
-type LoudMessage struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *LoudMessage) Reset() { *m = LoudMessage{} }
-func (m *LoudMessage) String() string { return proto.CompactTextString(m) }
-func (*LoudMessage) ProtoMessage() {}
-func (*LoudMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{1}
-}
-
-var extRange_LoudMessage = []proto.ExtensionRange{
- {Start: 100, End: 536870911},
-}
-
-func (*LoudMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_LoudMessage
-}
-func (m *LoudMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_LoudMessage.Unmarshal(m, b)
-}
-func (m *LoudMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_LoudMessage.Marshal(b, m, deterministic)
-}
-func (dst *LoudMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_LoudMessage.Merge(dst, src)
-}
-func (m *LoudMessage) XXX_Size() int {
- return xxx_messageInfo_LoudMessage.Size(m)
-}
-func (m *LoudMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_LoudMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_LoudMessage proto.InternalMessageInfo
-
-var E_LoudMessage_Volume = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 8,
- Name: "extension_user.LoudMessage.volume",
- Tag: "varint,8,opt,name=volume",
- Filename: "extension_user/extension_user.proto",
-}
-
-// Extend inside the scope of another type, using a message.
-type LoginMessage struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *LoginMessage) Reset() { *m = LoginMessage{} }
-func (m *LoginMessage) String() string { return proto.CompactTextString(m) }
-func (*LoginMessage) ProtoMessage() {}
-func (*LoginMessage) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{2}
-}
-func (m *LoginMessage) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_LoginMessage.Unmarshal(m, b)
-}
-func (m *LoginMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_LoginMessage.Marshal(b, m, deterministic)
-}
-func (dst *LoginMessage) XXX_Merge(src proto.Message) {
- xxx_messageInfo_LoginMessage.Merge(dst, src)
-}
-func (m *LoginMessage) XXX_Size() int {
- return xxx_messageInfo_LoginMessage.Size(m)
-}
-func (m *LoginMessage) XXX_DiscardUnknown() {
- xxx_messageInfo_LoginMessage.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_LoginMessage proto.InternalMessageInfo
-
-var E_LoginMessage_UserMessage = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: (*UserMessage)(nil),
- Field: 16,
- Name: "extension_user.LoginMessage.user_message",
- Tag: "bytes,16,opt,name=user_message,json=userMessage",
- Filename: "extension_user/extension_user.proto",
-}
-
-type Detail struct {
- Color *string `protobuf:"bytes,1,opt,name=color" json:"color,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Detail) Reset() { *m = Detail{} }
-func (m *Detail) String() string { return proto.CompactTextString(m) }
-func (*Detail) ProtoMessage() {}
-func (*Detail) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{3}
-}
-func (m *Detail) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Detail.Unmarshal(m, b)
-}
-func (m *Detail) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Detail.Marshal(b, m, deterministic)
-}
-func (dst *Detail) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Detail.Merge(dst, src)
-}
-func (m *Detail) XXX_Size() int {
- return xxx_messageInfo_Detail.Size(m)
-}
-func (m *Detail) XXX_DiscardUnknown() {
- xxx_messageInfo_Detail.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Detail proto.InternalMessageInfo
-
-func (m *Detail) GetColor() string {
- if m != nil && m.Color != nil {
- return *m.Color
- }
- return ""
-}
-
-// An extension of an extension
-type Announcement struct {
- Words *string `protobuf:"bytes,1,opt,name=words" json:"words,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Announcement) Reset() { *m = Announcement{} }
-func (m *Announcement) String() string { return proto.CompactTextString(m) }
-func (*Announcement) ProtoMessage() {}
-func (*Announcement) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{4}
-}
-func (m *Announcement) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Announcement.Unmarshal(m, b)
-}
-func (m *Announcement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Announcement.Marshal(b, m, deterministic)
-}
-func (dst *Announcement) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Announcement.Merge(dst, src)
-}
-func (m *Announcement) XXX_Size() int {
- return xxx_messageInfo_Announcement.Size(m)
-}
-func (m *Announcement) XXX_DiscardUnknown() {
- xxx_messageInfo_Announcement.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Announcement proto.InternalMessageInfo
-
-func (m *Announcement) GetWords() string {
- if m != nil && m.Words != nil {
- return *m.Words
- }
- return ""
-}
-
-var E_Announcement_LoudExt = &proto.ExtensionDesc{
- ExtendedType: (*LoudMessage)(nil),
- ExtensionType: (*Announcement)(nil),
- Field: 100,
- Name: "extension_user.Announcement.loud_ext",
- Tag: "bytes,100,opt,name=loud_ext,json=loudExt",
- Filename: "extension_user/extension_user.proto",
-}
-
-// Something that can be put in a message set.
-type OldStyleParcel struct {
- Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"`
- Height *int32 `protobuf:"varint,2,opt,name=height" json:"height,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OldStyleParcel) Reset() { *m = OldStyleParcel{} }
-func (m *OldStyleParcel) String() string { return proto.CompactTextString(m) }
-func (*OldStyleParcel) ProtoMessage() {}
-func (*OldStyleParcel) Descriptor() ([]byte, []int) {
- return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{5}
-}
-func (m *OldStyleParcel) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OldStyleParcel.Unmarshal(m, b)
-}
-func (m *OldStyleParcel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OldStyleParcel.Marshal(b, m, deterministic)
-}
-func (dst *OldStyleParcel) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OldStyleParcel.Merge(dst, src)
-}
-func (m *OldStyleParcel) XXX_Size() int {
- return xxx_messageInfo_OldStyleParcel.Size(m)
-}
-func (m *OldStyleParcel) XXX_DiscardUnknown() {
- xxx_messageInfo_OldStyleParcel.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OldStyleParcel proto.InternalMessageInfo
-
-func (m *OldStyleParcel) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *OldStyleParcel) GetHeight() int32 {
- if m != nil && m.Height != nil {
- return *m.Height
- }
- return 0
-}
-
-var E_OldStyleParcel_MessageSetExtension = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.OldStyleMessage)(nil),
- ExtensionType: (*OldStyleParcel)(nil),
- Field: 2001,
- Name: "extension_user.OldStyleParcel",
- Tag: "bytes,2001,opt,name=message_set_extension,json=messageSetExtension",
- Filename: "extension_user/extension_user.proto",
-}
-
-var E_UserMessage = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: (*UserMessage)(nil),
- Field: 5,
- Name: "extension_user.user_message",
- Tag: "bytes,5,opt,name=user_message,json=userMessage",
- Filename: "extension_user/extension_user.proto",
-}
-
-var E_ExtraMessage = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: (*extension_extra.ExtraMessage)(nil),
- Field: 9,
- Name: "extension_user.extra_message",
- Tag: "bytes,9,opt,name=extra_message,json=extraMessage",
- Filename: "extension_user/extension_user.proto",
-}
-
-var E_Width = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 6,
- Name: "extension_user.width",
- Tag: "varint,6,opt,name=width",
- Filename: "extension_user/extension_user.proto",
-}
-
-var E_Area = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 7,
- Name: "extension_user.area",
- Tag: "varint,7,opt,name=area",
- Filename: "extension_user/extension_user.proto",
-}
-
-var E_Detail = &proto.ExtensionDesc{
- ExtendedType: (*extension_base.BaseMessage)(nil),
- ExtensionType: ([]*Detail)(nil),
- Field: 17,
- Name: "extension_user.detail",
- Tag: "bytes,17,rep,name=detail",
- Filename: "extension_user/extension_user.proto",
-}
-
-func init() {
- proto.RegisterType((*UserMessage)(nil), "extension_user.UserMessage")
- proto.RegisterType((*LoudMessage)(nil), "extension_user.LoudMessage")
- proto.RegisterType((*LoginMessage)(nil), "extension_user.LoginMessage")
- proto.RegisterType((*Detail)(nil), "extension_user.Detail")
- proto.RegisterType((*Announcement)(nil), "extension_user.Announcement")
- proto.RegisterMessageSetType((*OldStyleParcel)(nil), 2001, "extension_user.OldStyleParcel")
- proto.RegisterType((*OldStyleParcel)(nil), "extension_user.OldStyleParcel")
- proto.RegisterExtension(E_LoudMessage_Volume)
- proto.RegisterExtension(E_LoginMessage_UserMessage)
- proto.RegisterExtension(E_Announcement_LoudExt)
- proto.RegisterExtension(E_OldStyleParcel_MessageSetExtension)
- proto.RegisterExtension(E_UserMessage)
- proto.RegisterExtension(E_ExtraMessage)
- proto.RegisterExtension(E_Width)
- proto.RegisterExtension(E_Area)
- proto.RegisterExtension(E_Detail)
-}
-
-func init() {
- proto.RegisterFile("extension_user/extension_user.proto", fileDescriptor_extension_user_af41b5e0bdfb7846)
-}
-
-var fileDescriptor_extension_user_af41b5e0bdfb7846 = []byte{
- // 492 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x51, 0x6f, 0x94, 0x40,
- 0x10, 0x0e, 0x6d, 0x8f, 0x5e, 0x87, 0x6b, 0xad, 0xa8, 0xcd, 0xa5, 0x6a, 0x25, 0x18, 0x13, 0x62,
- 0xd2, 0x23, 0x62, 0x7c, 0xe1, 0x49, 0x2f, 0xde, 0x93, 0x67, 0x34, 0x54, 0x5f, 0xf4, 0x81, 0xec,
- 0xc1, 0xc8, 0x91, 0xc2, 0xae, 0xd9, 0x5d, 0xec, 0xe9, 0xd3, 0xfd, 0x26, 0xff, 0x89, 0xff, 0xc8,
- 0xb0, 0x2c, 0x2d, 0x87, 0xc9, 0xc5, 0xbe, 0x90, 0xfd, 0x86, 0x6f, 0xbe, 0x99, 0xfd, 0x66, 0x00,
- 0x9e, 0xe2, 0x4a, 0x22, 0x15, 0x39, 0xa3, 0x71, 0x25, 0x90, 0xfb, 0x9b, 0x70, 0xf2, 0x9d, 0x33,
- 0xc9, 0xec, 0xa3, 0xcd, 0xe8, 0x69, 0x27, 0x69, 0x41, 0x04, 0xfa, 0x9b, 0xb0, 0x49, 0x3a, 0x7d,
- 0x76, 0x13, 0xc5, 0x95, 0xe4, 0xc4, 0xef, 0xe1, 0x86, 0xe6, 0xbe, 0x02, 0xeb, 0xb3, 0x40, 0xfe,
- 0x1e, 0x85, 0x20, 0x19, 0xda, 0x36, 0xec, 0x51, 0x52, 0xe2, 0xd8, 0x70, 0x0c, 0xef, 0x20, 0x52,
- 0xe7, 0x3a, 0xc6, 0x09, 0xbd, 0x1c, 0xef, 0x34, 0xb1, 0xfa, 0xec, 0xce, 0xc1, 0x9a, 0xb3, 0x2a,
- 0xd5, 0x69, 0xcf, 0x87, 0xc3, 0xf4, 0x78, 0xbd, 0x5e, 0xaf, 0x77, 0x82, 0x97, 0x60, 0xfe, 0x60,
- 0x45, 0x55, 0xa2, 0xfd, 0x70, 0xd2, 0xeb, 0x6b, 0x4a, 0x04, 0xea, 0x84, 0xf1, 0xd0, 0x31, 0xbc,
- 0xc3, 0x48, 0x53, 0xdd, 0x4b, 0x18, 0xcd, 0x59, 0x96, 0x53, 0xfd, 0x36, 0xf8, 0x0a, 0xa3, 0xfa,
- 0xa2, 0x71, 0xa9, 0xbb, 0xda, 0x2a, 0x75, 0xec, 0x18, 0x9e, 0x15, 0x74, 0x29, 0xca, 0xba, 0xce,
- 0xad, 0x22, 0xab, 0xba, 0x01, 0xee, 0x19, 0x98, 0x6f, 0x51, 0x92, 0xbc, 0xb0, 0xef, 0xc3, 0x20,
- 0x61, 0x05, 0xe3, 0xfa, 0xb6, 0x0d, 0x70, 0x7f, 0xc1, 0xe8, 0x0d, 0xa5, 0xac, 0xa2, 0x09, 0x96,
- 0x48, 0x65, 0xcd, 0xba, 0x62, 0x3c, 0x15, 0x2d, 0x4b, 0x81, 0xe0, 0x13, 0x0c, 0x0b, 0x56, 0xa5,
- 0xb5, 0x97, 0xf6, 0x3f, 0xb5, 0x3b, 0xd6, 0x8c, 0x53, 0xd5, 0xde, 0xa3, 0x3e, 0xa5, 0x5b, 0x22,
- 0xda, 0xaf, 0xa5, 0x66, 0x2b, 0xe9, 0xfe, 0x36, 0xe0, 0xe8, 0x43, 0x91, 0x5e, 0xc8, 0x9f, 0x05,
- 0x7e, 0x24, 0x3c, 0xc1, 0xa2, 0x33, 0x91, 0x9d, 0xeb, 0x89, 0x9c, 0x80, 0xb9, 0xc4, 0x3c, 0x5b,
- 0x4a, 0x35, 0x93, 0x41, 0xa4, 0x51, 0x20, 0xe1, 0x81, 0xb6, 0x2c, 0x16, 0x28, 0xe3, 0xeb, 0x92,
- 0xf6, 0x93, 0xbe, 0x81, 0x6d, 0x91, 0xb6, 0xcb, 0x3f, 0x77, 0x54, 0x9b, 0x67, 0xfd, 0x36, 0x37,
- 0x9b, 0x89, 0xee, 0x69, 0xf9, 0x0b, 0x94, 0xb3, 0x96, 0x18, 0xde, 0x6a, 0x5a, 0x83, 0xdb, 0x4d,
- 0x2b, 0x8c, 0xe1, 0x50, 0xad, 0xeb, 0xff, 0xa9, 0x1f, 0x28, 0xf5, 0xc7, 0x93, 0xfe, 0xae, 0xcf,
- 0xea, 0x67, 0xab, 0x3f, 0xc2, 0x0e, 0x0a, 0x5f, 0xc0, 0xe0, 0x2a, 0x4f, 0xe5, 0x72, 0xbb, 0xb0,
- 0xa9, 0x7c, 0x6e, 0x98, 0xa1, 0x0f, 0x7b, 0x84, 0x23, 0xd9, 0x9e, 0xb1, 0xef, 0x18, 0xde, 0x6e,
- 0xa4, 0x88, 0xe1, 0x3b, 0x30, 0xd3, 0x66, 0xe5, 0xb6, 0xa6, 0xdc, 0x75, 0x76, 0x3d, 0x2b, 0x38,
- 0xe9, 0x7b, 0xd3, 0x6c, 0x6b, 0xa4, 0x25, 0xa6, 0xd3, 0x2f, 0xaf, 0xb3, 0x5c, 0x2e, 0xab, 0xc5,
- 0x24, 0x61, 0xa5, 0x9f, 0xb1, 0x82, 0xd0, 0xcc, 0x57, 0x1f, 0xf3, 0xa2, 0xfa, 0xd6, 0x1c, 0x92,
- 0xf3, 0x0c, 0xe9, 0x79, 0xc6, 0x7c, 0x89, 0x42, 0xa6, 0x44, 0x92, 0xde, 0x7f, 0xe5, 0x6f, 0x00,
- 0x00, 0x00, 0xff, 0xff, 0xdf, 0x18, 0x64, 0x15, 0x77, 0x04, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto
deleted file mode 100644
index 033c186c0..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto
+++ /dev/null
@@ -1,102 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-import "extension_base/extension_base.proto";
-import "extension_extra/extension_extra.proto";
-
-package extension_user;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user";
-
-message UserMessage {
- optional string name = 1;
- optional string rank = 2;
-}
-
-// Extend with a message
-extend extension_base.BaseMessage {
- optional UserMessage user_message = 5;
-}
-
-// Extend with a foreign message
-extend extension_base.BaseMessage {
- optional extension_extra.ExtraMessage extra_message = 9;
-}
-
-// Extend with some primitive types
-extend extension_base.BaseMessage {
- optional int32 width = 6;
- optional int64 area = 7;
-}
-
-// Extend inside the scope of another type
-message LoudMessage {
- extend extension_base.BaseMessage {
- optional uint32 volume = 8;
- }
- extensions 100 to max;
-}
-
-// Extend inside the scope of another type, using a message.
-message LoginMessage {
- extend extension_base.BaseMessage {
- optional UserMessage user_message = 16;
- }
-}
-
-// Extend with a repeated field
-extend extension_base.BaseMessage {
- repeated Detail detail = 17;
-}
-
-message Detail {
- optional string color = 1;
-}
-
-// An extension of an extension
-message Announcement {
- optional string words = 1;
- extend LoudMessage {
- optional Announcement loud_ext = 100;
- }
-}
-
-// Something that can be put in a message set.
-message OldStyleParcel {
- extend extension_base.OldStyleMessage {
- optional OldStyleParcel message_set_extension = 2001;
- }
-
- required string name = 1;
- optional int32 height = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go
deleted file mode 100644
index 1bc0283f3..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go
+++ /dev/null
@@ -1,444 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: grpc/grpc.proto
-
-package testing // import "github.com/golang/protobuf/protoc-gen-go/testdata/grpc"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type SimpleRequest struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SimpleRequest) Reset() { *m = SimpleRequest{} }
-func (m *SimpleRequest) String() string { return proto.CompactTextString(m) }
-func (*SimpleRequest) ProtoMessage() {}
-func (*SimpleRequest) Descriptor() ([]byte, []int) {
- return fileDescriptor_grpc_65bf3902e49ee873, []int{0}
-}
-func (m *SimpleRequest) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SimpleRequest.Unmarshal(m, b)
-}
-func (m *SimpleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SimpleRequest.Marshal(b, m, deterministic)
-}
-func (dst *SimpleRequest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SimpleRequest.Merge(dst, src)
-}
-func (m *SimpleRequest) XXX_Size() int {
- return xxx_messageInfo_SimpleRequest.Size(m)
-}
-func (m *SimpleRequest) XXX_DiscardUnknown() {
- xxx_messageInfo_SimpleRequest.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SimpleRequest proto.InternalMessageInfo
-
-type SimpleResponse struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SimpleResponse) Reset() { *m = SimpleResponse{} }
-func (m *SimpleResponse) String() string { return proto.CompactTextString(m) }
-func (*SimpleResponse) ProtoMessage() {}
-func (*SimpleResponse) Descriptor() ([]byte, []int) {
- return fileDescriptor_grpc_65bf3902e49ee873, []int{1}
-}
-func (m *SimpleResponse) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SimpleResponse.Unmarshal(m, b)
-}
-func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic)
-}
-func (dst *SimpleResponse) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SimpleResponse.Merge(dst, src)
-}
-func (m *SimpleResponse) XXX_Size() int {
- return xxx_messageInfo_SimpleResponse.Size(m)
-}
-func (m *SimpleResponse) XXX_DiscardUnknown() {
- xxx_messageInfo_SimpleResponse.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo
-
-type StreamMsg struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *StreamMsg) Reset() { *m = StreamMsg{} }
-func (m *StreamMsg) String() string { return proto.CompactTextString(m) }
-func (*StreamMsg) ProtoMessage() {}
-func (*StreamMsg) Descriptor() ([]byte, []int) {
- return fileDescriptor_grpc_65bf3902e49ee873, []int{2}
-}
-func (m *StreamMsg) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_StreamMsg.Unmarshal(m, b)
-}
-func (m *StreamMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_StreamMsg.Marshal(b, m, deterministic)
-}
-func (dst *StreamMsg) XXX_Merge(src proto.Message) {
- xxx_messageInfo_StreamMsg.Merge(dst, src)
-}
-func (m *StreamMsg) XXX_Size() int {
- return xxx_messageInfo_StreamMsg.Size(m)
-}
-func (m *StreamMsg) XXX_DiscardUnknown() {
- xxx_messageInfo_StreamMsg.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_StreamMsg proto.InternalMessageInfo
-
-type StreamMsg2 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *StreamMsg2) Reset() { *m = StreamMsg2{} }
-func (m *StreamMsg2) String() string { return proto.CompactTextString(m) }
-func (*StreamMsg2) ProtoMessage() {}
-func (*StreamMsg2) Descriptor() ([]byte, []int) {
- return fileDescriptor_grpc_65bf3902e49ee873, []int{3}
-}
-func (m *StreamMsg2) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_StreamMsg2.Unmarshal(m, b)
-}
-func (m *StreamMsg2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_StreamMsg2.Marshal(b, m, deterministic)
-}
-func (dst *StreamMsg2) XXX_Merge(src proto.Message) {
- xxx_messageInfo_StreamMsg2.Merge(dst, src)
-}
-func (m *StreamMsg2) XXX_Size() int {
- return xxx_messageInfo_StreamMsg2.Size(m)
-}
-func (m *StreamMsg2) XXX_DiscardUnknown() {
- xxx_messageInfo_StreamMsg2.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_StreamMsg2 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest")
- proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse")
- proto.RegisterType((*StreamMsg)(nil), "grpc.testing.StreamMsg")
- proto.RegisterType((*StreamMsg2)(nil), "grpc.testing.StreamMsg2")
-}
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the grpc package it is being compiled against.
-const _ = grpc.SupportPackageIsVersion4
-
-// TestClient is the client API for Test service.
-//
-// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
-type TestClient interface {
- UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error)
- // This RPC streams from the server only.
- Downstream(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (Test_DownstreamClient, error)
- // This RPC streams from the client.
- Upstream(ctx context.Context, opts ...grpc.CallOption) (Test_UpstreamClient, error)
- // This one streams in both directions.
- Bidi(ctx context.Context, opts ...grpc.CallOption) (Test_BidiClient, error)
-}
-
-type testClient struct {
- cc *grpc.ClientConn
-}
-
-func NewTestClient(cc *grpc.ClientConn) TestClient {
- return &testClient{cc}
-}
-
-func (c *testClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
- out := new(SimpleResponse)
- err := c.cc.Invoke(ctx, "/grpc.testing.Test/UnaryCall", in, out, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *testClient) Downstream(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (Test_DownstreamClient, error) {
- stream, err := c.cc.NewStream(ctx, &_Test_serviceDesc.Streams[0], "/grpc.testing.Test/Downstream", opts...)
- if err != nil {
- return nil, err
- }
- x := &testDownstreamClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type Test_DownstreamClient interface {
- Recv() (*StreamMsg, error)
- grpc.ClientStream
-}
-
-type testDownstreamClient struct {
- grpc.ClientStream
-}
-
-func (x *testDownstreamClient) Recv() (*StreamMsg, error) {
- m := new(StreamMsg)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testClient) Upstream(ctx context.Context, opts ...grpc.CallOption) (Test_UpstreamClient, error) {
- stream, err := c.cc.NewStream(ctx, &_Test_serviceDesc.Streams[1], "/grpc.testing.Test/Upstream", opts...)
- if err != nil {
- return nil, err
- }
- x := &testUpstreamClient{stream}
- return x, nil
-}
-
-type Test_UpstreamClient interface {
- Send(*StreamMsg) error
- CloseAndRecv() (*SimpleResponse, error)
- grpc.ClientStream
-}
-
-type testUpstreamClient struct {
- grpc.ClientStream
-}
-
-func (x *testUpstreamClient) Send(m *StreamMsg) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testUpstreamClient) CloseAndRecv() (*SimpleResponse, error) {
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- m := new(SimpleResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testClient) Bidi(ctx context.Context, opts ...grpc.CallOption) (Test_BidiClient, error) {
- stream, err := c.cc.NewStream(ctx, &_Test_serviceDesc.Streams[2], "/grpc.testing.Test/Bidi", opts...)
- if err != nil {
- return nil, err
- }
- x := &testBidiClient{stream}
- return x, nil
-}
-
-type Test_BidiClient interface {
- Send(*StreamMsg) error
- Recv() (*StreamMsg2, error)
- grpc.ClientStream
-}
-
-type testBidiClient struct {
- grpc.ClientStream
-}
-
-func (x *testBidiClient) Send(m *StreamMsg) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testBidiClient) Recv() (*StreamMsg2, error) {
- m := new(StreamMsg2)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// TestServer is the server API for Test service.
-type TestServer interface {
- UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
- // This RPC streams from the server only.
- Downstream(*SimpleRequest, Test_DownstreamServer) error
- // This RPC streams from the client.
- Upstream(Test_UpstreamServer) error
- // This one streams in both directions.
- Bidi(Test_BidiServer) error
-}
-
-func RegisterTestServer(s *grpc.Server, srv TestServer) {
- s.RegisterService(&_Test_serviceDesc, srv)
-}
-
-func _Test_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(SimpleRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(TestServer).UnaryCall(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: "/grpc.testing.Test/UnaryCall",
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(TestServer).UnaryCall(ctx, req.(*SimpleRequest))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-func _Test_Downstream_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(SimpleRequest)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(TestServer).Downstream(m, &testDownstreamServer{stream})
-}
-
-type Test_DownstreamServer interface {
- Send(*StreamMsg) error
- grpc.ServerStream
-}
-
-type testDownstreamServer struct {
- grpc.ServerStream
-}
-
-func (x *testDownstreamServer) Send(m *StreamMsg) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _Test_Upstream_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServer).Upstream(&testUpstreamServer{stream})
-}
-
-type Test_UpstreamServer interface {
- SendAndClose(*SimpleResponse) error
- Recv() (*StreamMsg, error)
- grpc.ServerStream
-}
-
-type testUpstreamServer struct {
- grpc.ServerStream
-}
-
-func (x *testUpstreamServer) SendAndClose(m *SimpleResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testUpstreamServer) Recv() (*StreamMsg, error) {
- m := new(StreamMsg)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _Test_Bidi_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServer).Bidi(&testBidiServer{stream})
-}
-
-type Test_BidiServer interface {
- Send(*StreamMsg2) error
- Recv() (*StreamMsg, error)
- grpc.ServerStream
-}
-
-type testBidiServer struct {
- grpc.ServerStream
-}
-
-func (x *testBidiServer) Send(m *StreamMsg2) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testBidiServer) Recv() (*StreamMsg, error) {
- m := new(StreamMsg)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-var _Test_serviceDesc = grpc.ServiceDesc{
- ServiceName: "grpc.testing.Test",
- HandlerType: (*TestServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "UnaryCall",
- Handler: _Test_UnaryCall_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "Downstream",
- Handler: _Test_Downstream_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Upstream",
- Handler: _Test_Upstream_Handler,
- ClientStreams: true,
- },
- {
- StreamName: "Bidi",
- Handler: _Test_Bidi_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
- Metadata: "grpc/grpc.proto",
-}
-
-func init() { proto.RegisterFile("grpc/grpc.proto", fileDescriptor_grpc_65bf3902e49ee873) }
-
-var fileDescriptor_grpc_65bf3902e49ee873 = []byte{
- // 244 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4f, 0x2f, 0x2a, 0x48,
- 0xd6, 0x07, 0x11, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x3c, 0x60, 0x76, 0x49, 0x6a, 0x71,
- 0x49, 0x66, 0x5e, 0xba, 0x12, 0x3f, 0x17, 0x6f, 0x70, 0x66, 0x6e, 0x41, 0x4e, 0x6a, 0x50, 0x6a,
- 0x61, 0x69, 0x6a, 0x71, 0x89, 0x92, 0x00, 0x17, 0x1f, 0x4c, 0xa0, 0xb8, 0x20, 0x3f, 0xaf, 0x38,
- 0x55, 0x89, 0x9b, 0x8b, 0x33, 0xb8, 0xa4, 0x28, 0x35, 0x31, 0xd7, 0xb7, 0x38, 0x5d, 0x89, 0x87,
- 0x8b, 0x0b, 0xce, 0x31, 0x32, 0x9a, 0xc1, 0xc4, 0xc5, 0x12, 0x92, 0x5a, 0x5c, 0x22, 0xe4, 0xc6,
- 0xc5, 0x19, 0x9a, 0x97, 0x58, 0x54, 0xe9, 0x9c, 0x98, 0x93, 0x23, 0x24, 0xad, 0x87, 0x6c, 0x85,
- 0x1e, 0x8a, 0xf9, 0x52, 0x32, 0xd8, 0x25, 0x21, 0x76, 0x09, 0xb9, 0x70, 0x71, 0xb9, 0xe4, 0x97,
- 0xe7, 0x15, 0x83, 0xad, 0xc0, 0x6f, 0x90, 0x38, 0x9a, 0x24, 0xcc, 0x55, 0x06, 0x8c, 0x42, 0xce,
- 0x5c, 0x1c, 0xa1, 0x05, 0x50, 0x33, 0x70, 0x29, 0xc3, 0xef, 0x10, 0x0d, 0x46, 0x21, 0x5b, 0x2e,
- 0x16, 0xa7, 0xcc, 0x94, 0x4c, 0xdc, 0x06, 0x48, 0xe0, 0x90, 0x30, 0xd2, 0x60, 0x34, 0x60, 0x74,
- 0x72, 0x88, 0xb2, 0x4b, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf,
- 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x07, 0xc7, 0x40, 0x52, 0x69, 0x1a, 0x84, 0x91, 0xac, 0x9b, 0x9e,
- 0x9a, 0xa7, 0x9b, 0x9e, 0xaf, 0x0f, 0x32, 0x22, 0x25, 0xb1, 0x24, 0x11, 0x1c, 0x4d, 0xd6, 0x50,
- 0x03, 0x93, 0xd8, 0xc0, 0x8a, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x90, 0xb9, 0x95, 0x42,
- 0xc2, 0x01, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto
deleted file mode 100644
index 0e5c64a91..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto
+++ /dev/null
@@ -1,61 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/grpc;testing";
-
-message SimpleRequest {
-}
-
-message SimpleResponse {
-}
-
-message StreamMsg {
-}
-
-message StreamMsg2 {
-}
-
-service Test {
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // This RPC streams from the server only.
- rpc Downstream(SimpleRequest) returns (stream StreamMsg);
-
- // This RPC streams from the client.
- rpc Upstream(stream StreamMsg) returns (SimpleResponse);
-
- // This one streams in both directions.
- rpc Bidi(stream StreamMsg) returns (stream StreamMsg2);
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go
deleted file mode 100644
index 5b780fd5c..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: import_public/a.proto
-
-package import_public // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import sub "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// M from public import import_public/sub/a.proto
-type M = sub.M
-
-// E from public import import_public/sub/a.proto
-type E = sub.E
-
-var E_name = sub.E_name
-var E_value = sub.E_value
-
-const E_ZERO = E(sub.E_ZERO)
-
-// Ignoring public import of Local from import_public/b.proto
-
-type Public struct {
- M *sub.M `protobuf:"bytes,1,opt,name=m" json:"m,omitempty"`
- E sub.E `protobuf:"varint,2,opt,name=e,enum=goproto.test.import_public.sub.E" json:"e,omitempty"`
- Local *Local `protobuf:"bytes,3,opt,name=local" json:"local,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Public) Reset() { *m = Public{} }
-func (m *Public) String() string { return proto.CompactTextString(m) }
-func (*Public) ProtoMessage() {}
-func (*Public) Descriptor() ([]byte, []int) {
- return fileDescriptor_a_c0314c022b7c17d8, []int{0}
-}
-func (m *Public) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Public.Unmarshal(m, b)
-}
-func (m *Public) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Public.Marshal(b, m, deterministic)
-}
-func (dst *Public) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Public.Merge(dst, src)
-}
-func (m *Public) XXX_Size() int {
- return xxx_messageInfo_Public.Size(m)
-}
-func (m *Public) XXX_DiscardUnknown() {
- xxx_messageInfo_Public.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Public proto.InternalMessageInfo
-
-func (m *Public) GetM() *sub.M {
- if m != nil {
- return m.M
- }
- return nil
-}
-
-func (m *Public) GetE() sub.E {
- if m != nil {
- return m.E
- }
- return sub.E_ZERO
-}
-
-func (m *Public) GetLocal() *Local {
- if m != nil {
- return m.Local
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*Public)(nil), "goproto.test.import_public.Public")
-}
-
-func init() { proto.RegisterFile("import_public/a.proto", fileDescriptor_a_c0314c022b7c17d8) }
-
-var fileDescriptor_a_c0314c022b7c17d8 = []byte{
- // 200 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xcd, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x4f, 0xd4, 0x2b, 0x28, 0xca, 0x2f,
- 0xc9, 0x17, 0x92, 0x4a, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b, 0xf4, 0x50, 0xd4, 0x48,
- 0x49, 0xa2, 0x6a, 0x29, 0x2e, 0x4d, 0x82, 0x69, 0x93, 0x42, 0x33, 0x2d, 0x09, 0x22, 0xac, 0xb4,
- 0x98, 0x91, 0x8b, 0x2d, 0x00, 0x2c, 0x24, 0xa4, 0xcf, 0xc5, 0x98, 0x2b, 0xc1, 0xa8, 0xc0, 0xa8,
- 0xc1, 0x6d, 0xa4, 0xa8, 0x87, 0xdb, 0x12, 0xbd, 0xe2, 0xd2, 0x24, 0x3d, 0xdf, 0x20, 0xc6, 0x5c,
- 0x90, 0x86, 0x54, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x3e, 0xc2, 0x1a, 0x5c, 0x83, 0x18, 0x53, 0x85,
- 0xcc, 0xb9, 0x58, 0x73, 0xf2, 0x93, 0x13, 0x73, 0x24, 0x98, 0x09, 0xdb, 0xe2, 0x03, 0x52, 0x18,
- 0x04, 0x51, 0xef, 0xe4, 0x18, 0x65, 0x9f, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f,
- 0xab, 0x9f, 0x9e, 0x9f, 0x93, 0x98, 0x97, 0xae, 0x0f, 0xd6, 0x9a, 0x54, 0x9a, 0x06, 0x61, 0x24,
- 0xeb, 0xa6, 0xa7, 0xe6, 0xe9, 0xa6, 0xe7, 0xeb, 0x83, 0xcc, 0x4a, 0x49, 0x2c, 0x49, 0xd4, 0x47,
- 0x31, 0x2f, 0x80, 0x21, 0x80, 0x31, 0x89, 0x0d, 0xac, 0xd2, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff,
- 0x70, 0xc5, 0xc3, 0x79, 0x5a, 0x01, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto
deleted file mode 100644
index 957ad8971..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto
+++ /dev/null
@@ -1,45 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package goproto.test.import_public;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public";
-
-import public "import_public/sub/a.proto"; // Different Go package.
-import public "import_public/b.proto"; // Same Go package.
-
-message Public {
- goproto.test.import_public.sub.M m = 1;
- goproto.test.import_public.sub.E e = 2;
- Local local = 3;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go
deleted file mode 100644
index 427aa4f32..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go
+++ /dev/null
@@ -1,87 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: import_public/b.proto
-
-package import_public // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import sub "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type Local struct {
- M *sub.M `protobuf:"bytes,1,opt,name=m" json:"m,omitempty"`
- E sub.E `protobuf:"varint,2,opt,name=e,enum=goproto.test.import_public.sub.E" json:"e,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Local) Reset() { *m = Local{} }
-func (m *Local) String() string { return proto.CompactTextString(m) }
-func (*Local) ProtoMessage() {}
-func (*Local) Descriptor() ([]byte, []int) {
- return fileDescriptor_b_7f20a805fad67bd0, []int{0}
-}
-func (m *Local) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Local.Unmarshal(m, b)
-}
-func (m *Local) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Local.Marshal(b, m, deterministic)
-}
-func (dst *Local) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Local.Merge(dst, src)
-}
-func (m *Local) XXX_Size() int {
- return xxx_messageInfo_Local.Size(m)
-}
-func (m *Local) XXX_DiscardUnknown() {
- xxx_messageInfo_Local.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Local proto.InternalMessageInfo
-
-func (m *Local) GetM() *sub.M {
- if m != nil {
- return m.M
- }
- return nil
-}
-
-func (m *Local) GetE() sub.E {
- if m != nil {
- return m.E
- }
- return sub.E_ZERO
-}
-
-func init() {
- proto.RegisterType((*Local)(nil), "goproto.test.import_public.Local")
-}
-
-func init() { proto.RegisterFile("import_public/b.proto", fileDescriptor_b_7f20a805fad67bd0) }
-
-var fileDescriptor_b_7f20a805fad67bd0 = []byte{
- // 174 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xcd, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x4f, 0xd2, 0x2b, 0x28, 0xca, 0x2f,
- 0xc9, 0x17, 0x92, 0x4a, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b, 0xf4, 0x50, 0xd4, 0x48,
- 0x49, 0xa2, 0x6a, 0x29, 0x2e, 0x4d, 0xd2, 0x4f, 0x84, 0x68, 0x53, 0xca, 0xe4, 0x62, 0xf5, 0xc9,
- 0x4f, 0x4e, 0xcc, 0x11, 0xd2, 0xe7, 0x62, 0xcc, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0x52,
- 0xd4, 0xc3, 0x6d, 0x96, 0x5e, 0x71, 0x69, 0x92, 0x9e, 0x6f, 0x10, 0x63, 0x2e, 0x48, 0x43, 0xaa,
- 0x04, 0x93, 0x02, 0xa3, 0x06, 0x1f, 0x61, 0x0d, 0xae, 0x41, 0x8c, 0xa9, 0x4e, 0x8e, 0x51, 0xf6,
- 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, 0x79,
- 0xe9, 0xfa, 0x60, 0x6d, 0x49, 0xa5, 0x69, 0x10, 0x46, 0xb2, 0x6e, 0x7a, 0x6a, 0x9e, 0x6e, 0x7a,
- 0xbe, 0x3e, 0xc8, 0x9c, 0x94, 0xc4, 0x92, 0x44, 0x7d, 0x14, 0xb3, 0x92, 0xd8, 0xc0, 0xaa, 0x8c,
- 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x2b, 0x5f, 0x8e, 0x04, 0x01, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto
deleted file mode 100644
index 1dbca3e49..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto
+++ /dev/null
@@ -1,43 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package goproto.test.import_public;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public";
-
-import "import_public/sub/a.proto";
-
-message Local {
- goproto.test.import_public.sub.M m = 1;
- goproto.test.import_public.sub.E e = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go
deleted file mode 100644
index 4f8f6d243..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: import_public/sub/a.proto
-
-package sub // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type E int32
-
-const (
- E_ZERO E = 0
-)
-
-var E_name = map[int32]string{
- 0: "ZERO",
-}
-var E_value = map[string]int32{
- "ZERO": 0,
-}
-
-func (x E) String() string {
- return proto.EnumName(E_name, int32(x))
-}
-func (E) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_a_91ca0264a534463a, []int{0}
-}
-
-type M struct {
- // Field using a type in the same Go package, but a different source file.
- M2 *M2 `protobuf:"bytes,1,opt,name=m2" json:"m2,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M) Reset() { *m = M{} }
-func (m *M) String() string { return proto.CompactTextString(m) }
-func (*M) ProtoMessage() {}
-func (*M) Descriptor() ([]byte, []int) {
- return fileDescriptor_a_91ca0264a534463a, []int{0}
-}
-func (m *M) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M.Unmarshal(m, b)
-}
-func (m *M) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M.Marshal(b, m, deterministic)
-}
-func (dst *M) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M.Merge(dst, src)
-}
-func (m *M) XXX_Size() int {
- return xxx_messageInfo_M.Size(m)
-}
-func (m *M) XXX_DiscardUnknown() {
- xxx_messageInfo_M.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M proto.InternalMessageInfo
-
-func (m *M) GetM2() *M2 {
- if m != nil {
- return m.M2
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*M)(nil), "goproto.test.import_public.sub.M")
- proto.RegisterEnum("goproto.test.import_public.sub.E", E_name, E_value)
-}
-
-func init() { proto.RegisterFile("import_public/sub/a.proto", fileDescriptor_a_91ca0264a534463a) }
-
-var fileDescriptor_a_91ca0264a534463a = []byte{
- // 172 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x2f, 0x2e, 0x4d, 0xd2, 0x4f, 0xd4,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x4b, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b,
- 0xf4, 0x50, 0xd4, 0xe9, 0x15, 0x97, 0x26, 0x49, 0x61, 0xd1, 0x9a, 0x04, 0xd1, 0xaa, 0x64, 0xce,
- 0xc5, 0xe8, 0x2b, 0x64, 0xc4, 0xc5, 0x94, 0x6b, 0x24, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0xa4,
- 0xa4, 0x87, 0xdf, 0x30, 0x3d, 0x5f, 0xa3, 0x20, 0xa6, 0x5c, 0x23, 0x2d, 0x5e, 0x2e, 0x46, 0x57,
- 0x21, 0x0e, 0x2e, 0x96, 0x28, 0xd7, 0x20, 0x7f, 0x01, 0x06, 0x27, 0xd7, 0x28, 0xe7, 0xf4, 0xcc,
- 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0xf4, 0xfc, 0x9c, 0xc4, 0xbc, 0x74, 0x7d,
- 0xb0, 0x39, 0x49, 0xa5, 0x69, 0x10, 0x46, 0xb2, 0x6e, 0x7a, 0x6a, 0x9e, 0x6e, 0x7a, 0xbe, 0x3e,
- 0xc8, 0xe0, 0x94, 0xc4, 0x92, 0x44, 0x7d, 0x0c, 0x67, 0x25, 0xb1, 0x81, 0x55, 0x1a, 0x03, 0x02,
- 0x00, 0x00, 0xff, 0xff, 0x81, 0xcc, 0x07, 0x7d, 0xed, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto
deleted file mode 100644
index 4494c818a..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto
+++ /dev/null
@@ -1,47 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package goproto.test.import_public.sub;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub";
-
-import "import_public/sub/b.proto";
-
-message M {
- // Field using a type in the same Go package, but a different source file.
- M2 m2 = 1;
-}
-
-enum E {
- ZERO = 0;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go
deleted file mode 100644
index d57a3bb9a..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: import_public/sub/b.proto
-
-package sub // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M2 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M2) Reset() { *m = M2{} }
-func (m *M2) String() string { return proto.CompactTextString(m) }
-func (*M2) ProtoMessage() {}
-func (*M2) Descriptor() ([]byte, []int) {
- return fileDescriptor_b_eba25180453d86b4, []int{0}
-}
-func (m *M2) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M2.Unmarshal(m, b)
-}
-func (m *M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M2.Marshal(b, m, deterministic)
-}
-func (dst *M2) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M2.Merge(dst, src)
-}
-func (m *M2) XXX_Size() int {
- return xxx_messageInfo_M2.Size(m)
-}
-func (m *M2) XXX_DiscardUnknown() {
- xxx_messageInfo_M2.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M2 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M2)(nil), "goproto.test.import_public.sub.M2")
-}
-
-func init() { proto.RegisterFile("import_public/sub/b.proto", fileDescriptor_b_eba25180453d86b4) }
-
-var fileDescriptor_b_eba25180453d86b4 = []byte{
- // 127 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x2f, 0x2e, 0x4d, 0xd2, 0x4f, 0xd2,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x4b, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b,
- 0xf4, 0x50, 0xd4, 0xe9, 0x15, 0x97, 0x26, 0x29, 0xb1, 0x70, 0x31, 0xf9, 0x1a, 0x39, 0xb9, 0x46,
- 0x39, 0xa7, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24,
- 0xe6, 0xa5, 0xeb, 0x83, 0xf5, 0x25, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, 0xe9, 0xa9, 0x79, 0xba,
- 0xe9, 0xf9, 0xfa, 0x20, 0x83, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0x31, 0x2c, 0x4d, 0x62, 0x03, 0xab,
- 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x64, 0x42, 0xe4, 0xa8, 0x90, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto
deleted file mode 100644
index c7299e0f2..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto
+++ /dev/null
@@ -1,39 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package goproto.test.import_public.sub;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub";
-
-message M2 {
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go
deleted file mode 100644
index 7ef776bf7..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// +build go1.9
-
-package testdata
-
-import (
- "testing"
-
- mainpb "github.com/golang/protobuf/protoc-gen-go/testdata/import_public"
- subpb "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"
-)
-
-func TestImportPublicLink(t *testing.T) {
- // mainpb.[ME] should be interchangable with subpb.[ME].
- var _ mainpb.M = subpb.M{}
- var _ mainpb.E = subpb.E(0)
- _ = &mainpb.Public{
- M: &mainpb.M{},
- E: mainpb.E_ZERO,
- Local: &mainpb.Local{
- M: &mainpb.M{},
- E: mainpb.E_ZERO,
- },
- }
- _ = &mainpb.Public{
- M: &subpb.M{},
- E: subpb.E_ZERO,
- Local: &mainpb.Local{
- M: &subpb.M{},
- E: subpb.E_ZERO,
- },
- }
- _ = &mainpb.M{
- M2: &subpb.M2{},
- }
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go
deleted file mode 100644
index ca312d6cc..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/fmt/m.proto
-
-package fmt // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M) Reset() { *m = M{} }
-func (m *M) String() string { return proto.CompactTextString(m) }
-func (*M) ProtoMessage() {}
-func (*M) Descriptor() ([]byte, []int) {
- return fileDescriptor_m_867dd34c461422b8, []int{0}
-}
-func (m *M) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M.Unmarshal(m, b)
-}
-func (m *M) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M.Marshal(b, m, deterministic)
-}
-func (dst *M) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M.Merge(dst, src)
-}
-func (m *M) XXX_Size() int {
- return xxx_messageInfo_M.Size(m)
-}
-func (m *M) XXX_DiscardUnknown() {
- xxx_messageInfo_M.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M)(nil), "fmt.M")
-}
-
-func init() { proto.RegisterFile("imports/fmt/m.proto", fileDescriptor_m_867dd34c461422b8) }
-
-var fileDescriptor_m_867dd34c461422b8 = []byte{
- // 109 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xce, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x4f, 0xcb, 0x2d, 0xd1, 0xcf, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17,
- 0x62, 0x4e, 0xcb, 0x2d, 0x51, 0x62, 0xe6, 0x62, 0xf4, 0x75, 0xb2, 0x8f, 0xb2, 0x4d, 0xcf, 0x2c,
- 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x07,
- 0x2b, 0x4a, 0x2a, 0x4d, 0x83, 0x30, 0x92, 0x75, 0xd3, 0x53, 0xf3, 0x74, 0xd3, 0xf3, 0xf5, 0x4b,
- 0x52, 0x8b, 0x4b, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0x91, 0x8c, 0x4c, 0x62, 0x03, 0xab, 0x31, 0x06,
- 0x04, 0x00, 0x00, 0xff, 0xff, 0xc4, 0xc9, 0xee, 0xbe, 0x68, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto
deleted file mode 100644
index 142d8cfac..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package fmt;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt";
-message M {}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go
deleted file mode 100644
index 82ec35e10..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go
+++ /dev/null
@@ -1,130 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_a_1/m1.proto
-
-package test_a_1 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type E1 int32
-
-const (
- E1_E1_ZERO E1 = 0
-)
-
-var E1_name = map[int32]string{
- 0: "E1_ZERO",
-}
-var E1_value = map[string]int32{
- "E1_ZERO": 0,
-}
-
-func (x E1) String() string {
- return proto.EnumName(E1_name, int32(x))
-}
-func (E1) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_m1_56a2598431d21e61, []int{0}
-}
-
-type M1 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M1) Reset() { *m = M1{} }
-func (m *M1) String() string { return proto.CompactTextString(m) }
-func (*M1) ProtoMessage() {}
-func (*M1) Descriptor() ([]byte, []int) {
- return fileDescriptor_m1_56a2598431d21e61, []int{0}
-}
-func (m *M1) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M1.Unmarshal(m, b)
-}
-func (m *M1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M1.Marshal(b, m, deterministic)
-}
-func (dst *M1) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M1.Merge(dst, src)
-}
-func (m *M1) XXX_Size() int {
- return xxx_messageInfo_M1.Size(m)
-}
-func (m *M1) XXX_DiscardUnknown() {
- xxx_messageInfo_M1.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M1 proto.InternalMessageInfo
-
-type M1_1 struct {
- M1 *M1 `protobuf:"bytes,1,opt,name=m1" json:"m1,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M1_1) Reset() { *m = M1_1{} }
-func (m *M1_1) String() string { return proto.CompactTextString(m) }
-func (*M1_1) ProtoMessage() {}
-func (*M1_1) Descriptor() ([]byte, []int) {
- return fileDescriptor_m1_56a2598431d21e61, []int{1}
-}
-func (m *M1_1) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M1_1.Unmarshal(m, b)
-}
-func (m *M1_1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M1_1.Marshal(b, m, deterministic)
-}
-func (dst *M1_1) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M1_1.Merge(dst, src)
-}
-func (m *M1_1) XXX_Size() int {
- return xxx_messageInfo_M1_1.Size(m)
-}
-func (m *M1_1) XXX_DiscardUnknown() {
- xxx_messageInfo_M1_1.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M1_1 proto.InternalMessageInfo
-
-func (m *M1_1) GetM1() *M1 {
- if m != nil {
- return m.M1
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*M1)(nil), "test.a.M1")
- proto.RegisterType((*M1_1)(nil), "test.a.M1_1")
- proto.RegisterEnum("test.a.E1", E1_name, E1_value)
-}
-
-func init() { proto.RegisterFile("imports/test_a_1/m1.proto", fileDescriptor_m1_56a2598431d21e61) }
-
-var fileDescriptor_m1_56a2598431d21e61 = []byte{
- // 165 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd4, 0xcf, 0x35, 0xd4,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9,
- 0x1a, 0x2a, 0x29, 0x71, 0xb1, 0xf8, 0x1a, 0xc6, 0x1b, 0x0a, 0x49, 0x71, 0x31, 0xe5, 0x1a, 0x4a,
- 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0x71, 0xe9, 0x41, 0x94, 0xe8, 0xf9, 0x1a, 0x06, 0x31, 0xe5,
- 0x1a, 0x6a, 0x09, 0x72, 0x31, 0xb9, 0x1a, 0x0a, 0x71, 0x73, 0xb1, 0xbb, 0x1a, 0xc6, 0x47, 0xb9,
- 0x06, 0xf9, 0x0b, 0x30, 0x38, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25,
- 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0xcd, 0x4f, 0x2a, 0x4d, 0x83,
- 0x30, 0x92, 0x75, 0xd3, 0x53, 0xf3, 0x74, 0xd3, 0xf3, 0xc1, 0x4e, 0x48, 0x49, 0x2c, 0x49, 0xd4,
- 0x47, 0x77, 0x53, 0x12, 0x1b, 0x58, 0xa1, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xcc, 0xae, 0xc9,
- 0xcd, 0xae, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto
deleted file mode 100644
index da54c1ee4..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto
+++ /dev/null
@@ -1,44 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package test.a;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1";
-
-message M1 {}
-
-message M1_1 {
- M1 m1 = 1;
-}
-
-enum E1 {
- E1_ZERO = 0;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go
deleted file mode 100644
index 1b629bf32..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_a_1/m2.proto
-
-package test_a_1 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M2 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M2) Reset() { *m = M2{} }
-func (m *M2) String() string { return proto.CompactTextString(m) }
-func (*M2) ProtoMessage() {}
-func (*M2) Descriptor() ([]byte, []int) {
- return fileDescriptor_m2_ccd6356c045a9ac3, []int{0}
-}
-func (m *M2) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M2.Unmarshal(m, b)
-}
-func (m *M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M2.Marshal(b, m, deterministic)
-}
-func (dst *M2) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M2.Merge(dst, src)
-}
-func (m *M2) XXX_Size() int {
- return xxx_messageInfo_M2.Size(m)
-}
-func (m *M2) XXX_DiscardUnknown() {
- xxx_messageInfo_M2.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M2 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M2)(nil), "test.a.M2")
-}
-
-func init() { proto.RegisterFile("imports/test_a_1/m2.proto", fileDescriptor_m2_ccd6356c045a9ac3) }
-
-var fileDescriptor_m2_ccd6356c045a9ac3 = []byte{
- // 114 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd4, 0xcf, 0x35, 0xd2,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9,
- 0x1a, 0x39, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea,
- 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x15, 0x26, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba,
- 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0xb3, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0xd1, 0x0d, 0x4f,
- 0x62, 0x03, 0x2b, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xe3, 0xe0, 0x7e, 0xc0, 0x77, 0x00,
- 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto
deleted file mode 100644
index 49499dc9c..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package test.a;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1";
-message M2 {}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go
deleted file mode 100644
index e3895d2be..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_a_2/m3.proto
-
-package test_a_2 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M3 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M3) Reset() { *m = M3{} }
-func (m *M3) String() string { return proto.CompactTextString(m) }
-func (*M3) ProtoMessage() {}
-func (*M3) Descriptor() ([]byte, []int) {
- return fileDescriptor_m3_de310e87d08d4216, []int{0}
-}
-func (m *M3) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M3.Unmarshal(m, b)
-}
-func (m *M3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M3.Marshal(b, m, deterministic)
-}
-func (dst *M3) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M3.Merge(dst, src)
-}
-func (m *M3) XXX_Size() int {
- return xxx_messageInfo_M3.Size(m)
-}
-func (m *M3) XXX_DiscardUnknown() {
- xxx_messageInfo_M3.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M3 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M3)(nil), "test.a.M3")
-}
-
-func init() { proto.RegisterFile("imports/test_a_2/m3.proto", fileDescriptor_m3_de310e87d08d4216) }
-
-var fileDescriptor_m3_de310e87d08d4216 = []byte{
- // 114 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd2, 0xcf, 0x35, 0xd6,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9,
- 0x1a, 0x3b, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea,
- 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x15, 0x26, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba,
- 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0xb3, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0xd1, 0x0d, 0x4f,
- 0x62, 0x03, 0x2b, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x23, 0x86, 0x27, 0x47, 0x77, 0x00,
- 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto
deleted file mode 100644
index 5e811ef84..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package test.a;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2";
-message M3 {}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go
deleted file mode 100644
index 65a3bad29..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_a_2/m4.proto
-
-package test_a_2 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M4 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M4) Reset() { *m = M4{} }
-func (m *M4) String() string { return proto.CompactTextString(m) }
-func (*M4) ProtoMessage() {}
-func (*M4) Descriptor() ([]byte, []int) {
- return fileDescriptor_m4_da12b386229f3791, []int{0}
-}
-func (m *M4) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M4.Unmarshal(m, b)
-}
-func (m *M4) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M4.Marshal(b, m, deterministic)
-}
-func (dst *M4) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M4.Merge(dst, src)
-}
-func (m *M4) XXX_Size() int {
- return xxx_messageInfo_M4.Size(m)
-}
-func (m *M4) XXX_DiscardUnknown() {
- xxx_messageInfo_M4.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M4 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M4)(nil), "test.a.M4")
-}
-
-func init() { proto.RegisterFile("imports/test_a_2/m4.proto", fileDescriptor_m4_da12b386229f3791) }
-
-var fileDescriptor_m4_da12b386229f3791 = []byte{
- // 114 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd2, 0xcf, 0x35, 0xd1,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9,
- 0x9a, 0x38, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea,
- 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x15, 0x26, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba,
- 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0xb3, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0xd1, 0x0d, 0x4f,
- 0x62, 0x03, 0x2b, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x58, 0xcb, 0x10, 0xc8, 0x77, 0x00,
- 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto
deleted file mode 100644
index 8f8fe3e12..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package test.a;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2";
-message M4 {}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go
deleted file mode 100644
index 831f41498..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_b_1/m1.proto
-
-package beta // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M1 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M1) Reset() { *m = M1{} }
-func (m *M1) String() string { return proto.CompactTextString(m) }
-func (*M1) ProtoMessage() {}
-func (*M1) Descriptor() ([]byte, []int) {
- return fileDescriptor_m1_aff127b054aec649, []int{0}
-}
-func (m *M1) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M1.Unmarshal(m, b)
-}
-func (m *M1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M1.Marshal(b, m, deterministic)
-}
-func (dst *M1) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M1.Merge(dst, src)
-}
-func (m *M1) XXX_Size() int {
- return xxx_messageInfo_M1.Size(m)
-}
-func (m *M1) XXX_DiscardUnknown() {
- xxx_messageInfo_M1.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M1 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M1)(nil), "test.b.part1.M1")
-}
-
-func init() { proto.RegisterFile("imports/test_b_1/m1.proto", fileDescriptor_m1_aff127b054aec649) }
-
-var fileDescriptor_m1_aff127b054aec649 = []byte{
- // 125 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8a, 0x37, 0xd4, 0xcf, 0x35, 0xd4,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x01, 0x09, 0xe9, 0x25, 0xe9, 0x15, 0x24, 0x16, 0x95,
- 0x18, 0x2a, 0xb1, 0x70, 0x31, 0xf9, 0x1a, 0x3a, 0x79, 0x46, 0xb9, 0xa7, 0x67, 0x96, 0x64, 0x94,
- 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x95, 0x27,
- 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0x13, 0x53, 0x12,
- 0x4b, 0x12, 0xf5, 0xd1, 0xad, 0xb0, 0x4e, 0x4a, 0x2d, 0x49, 0x4c, 0x62, 0x03, 0xab, 0x36, 0x06,
- 0x04, 0x00, 0x00, 0xff, 0xff, 0x4a, 0xf1, 0x3b, 0x7f, 0x82, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto
deleted file mode 100644
index 2c35ec4ae..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package test.b.part1;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1;beta";
-message M1 {}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go
deleted file mode 100644
index bc741056a..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go
+++ /dev/null
@@ -1,67 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_b_1/m2.proto
-
-package beta // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type M2 struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *M2) Reset() { *m = M2{} }
-func (m *M2) String() string { return proto.CompactTextString(m) }
-func (*M2) ProtoMessage() {}
-func (*M2) Descriptor() ([]byte, []int) {
- return fileDescriptor_m2_0c59cab35ba1b0d8, []int{0}
-}
-func (m *M2) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_M2.Unmarshal(m, b)
-}
-func (m *M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_M2.Marshal(b, m, deterministic)
-}
-func (dst *M2) XXX_Merge(src proto.Message) {
- xxx_messageInfo_M2.Merge(dst, src)
-}
-func (m *M2) XXX_Size() int {
- return xxx_messageInfo_M2.Size(m)
-}
-func (m *M2) XXX_DiscardUnknown() {
- xxx_messageInfo_M2.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_M2 proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*M2)(nil), "test.b.part2.M2")
-}
-
-func init() { proto.RegisterFile("imports/test_b_1/m2.proto", fileDescriptor_m2_0c59cab35ba1b0d8) }
-
-var fileDescriptor_m2_0c59cab35ba1b0d8 = []byte{
- // 125 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8a, 0x37, 0xd4, 0xcf, 0x35, 0xd2,
- 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x01, 0x09, 0xe9, 0x25, 0xe9, 0x15, 0x24, 0x16, 0x95,
- 0x18, 0x29, 0xb1, 0x70, 0x31, 0xf9, 0x1a, 0x39, 0x79, 0x46, 0xb9, 0xa7, 0x67, 0x96, 0x64, 0x94,
- 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x95, 0x27,
- 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0x13, 0x53, 0x12,
- 0x4b, 0x12, 0xf5, 0xd1, 0xad, 0xb0, 0x4e, 0x4a, 0x2d, 0x49, 0x4c, 0x62, 0x03, 0xab, 0x36, 0x06,
- 0x04, 0x00, 0x00, 0xff, 0xff, 0x44, 0x29, 0xbe, 0x6d, 0x82, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto
deleted file mode 100644
index 13723be41..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-package test.b.part2;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1;beta";
-message M2 {}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go
deleted file mode 100644
index 72daffdbf..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go
+++ /dev/null
@@ -1,80 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_import_a1m1.proto
-
-package imports // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import test_a_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type A1M1 struct {
- F *test_a_1.M1 `protobuf:"bytes,1,opt,name=f" json:"f,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *A1M1) Reset() { *m = A1M1{} }
-func (m *A1M1) String() string { return proto.CompactTextString(m) }
-func (*A1M1) ProtoMessage() {}
-func (*A1M1) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_import_a1m1_d7f2b5c638a69f6e, []int{0}
-}
-func (m *A1M1) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_A1M1.Unmarshal(m, b)
-}
-func (m *A1M1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_A1M1.Marshal(b, m, deterministic)
-}
-func (dst *A1M1) XXX_Merge(src proto.Message) {
- xxx_messageInfo_A1M1.Merge(dst, src)
-}
-func (m *A1M1) XXX_Size() int {
- return xxx_messageInfo_A1M1.Size(m)
-}
-func (m *A1M1) XXX_DiscardUnknown() {
- xxx_messageInfo_A1M1.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_A1M1 proto.InternalMessageInfo
-
-func (m *A1M1) GetF() *test_a_1.M1 {
- if m != nil {
- return m.F
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*A1M1)(nil), "test.A1M1")
-}
-
-func init() {
- proto.RegisterFile("imports/test_import_a1m1.proto", fileDescriptor_test_import_a1m1_d7f2b5c638a69f6e)
-}
-
-var fileDescriptor_test_import_a1m1_d7f2b5c638a69f6e = []byte{
- // 149 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcb, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x87, 0x70, 0xe2, 0x13, 0x0d, 0x73, 0x0d,
- 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0xe2, 0x52, 0x92, 0x28, 0xaa, 0x12, 0xe3,
- 0x0d, 0xf5, 0x61, 0x0a, 0x94, 0x14, 0xb8, 0x58, 0x1c, 0x0d, 0x7d, 0x0d, 0x85, 0x24, 0xb8, 0x18,
- 0xd3, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xb8, 0xf4, 0x40, 0xca, 0xf4, 0x12, 0xf5, 0x7c,
- 0x0d, 0x83, 0x18, 0xd3, 0x9c, 0xac, 0xa3, 0x2c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92,
- 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0x73, 0x12, 0xf3, 0xd2, 0xf5, 0xc1, 0x9a, 0x93, 0x4a, 0xd3, 0x20,
- 0x8c, 0x64, 0xdd, 0xf4, 0xd4, 0x3c, 0xdd, 0xf4, 0x7c, 0xb0, 0xf9, 0x29, 0x89, 0x25, 0x89, 0xfa,
- 0x50, 0x0b, 0x93, 0xd8, 0xc0, 0xf2, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x84, 0x2f, 0x18,
- 0x23, 0xa8, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto
deleted file mode 100644
index abf07f2a4..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto
+++ /dev/null
@@ -1,42 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package test;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports";
-
-import "imports/test_a_1/m1.proto";
-
-message A1M1 {
- test.a.M1 f = 1;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go
deleted file mode 100644
index 9e36ebdeb..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go
+++ /dev/null
@@ -1,80 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_import_a1m2.proto
-
-package imports // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import test_a_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type A1M2 struct {
- F *test_a_1.M2 `protobuf:"bytes,1,opt,name=f" json:"f,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *A1M2) Reset() { *m = A1M2{} }
-func (m *A1M2) String() string { return proto.CompactTextString(m) }
-func (*A1M2) ProtoMessage() {}
-func (*A1M2) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_import_a1m2_9a3281ce9464e116, []int{0}
-}
-func (m *A1M2) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_A1M2.Unmarshal(m, b)
-}
-func (m *A1M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_A1M2.Marshal(b, m, deterministic)
-}
-func (dst *A1M2) XXX_Merge(src proto.Message) {
- xxx_messageInfo_A1M2.Merge(dst, src)
-}
-func (m *A1M2) XXX_Size() int {
- return xxx_messageInfo_A1M2.Size(m)
-}
-func (m *A1M2) XXX_DiscardUnknown() {
- xxx_messageInfo_A1M2.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_A1M2 proto.InternalMessageInfo
-
-func (m *A1M2) GetF() *test_a_1.M2 {
- if m != nil {
- return m.F
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*A1M2)(nil), "test.A1M2")
-}
-
-func init() {
- proto.RegisterFile("imports/test_import_a1m2.proto", fileDescriptor_test_import_a1m2_9a3281ce9464e116)
-}
-
-var fileDescriptor_test_import_a1m2_9a3281ce9464e116 = []byte{
- // 149 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcb, 0xcc, 0x2d, 0xc8,
- 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x87, 0x70, 0xe2, 0x13, 0x0d, 0x73, 0x8d,
- 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0xe2, 0x52, 0x92, 0x28, 0xaa, 0x12, 0xe3,
- 0x0d, 0xf5, 0x61, 0x0a, 0x94, 0x14, 0xb8, 0x58, 0x1c, 0x0d, 0x7d, 0x8d, 0x84, 0x24, 0xb8, 0x18,
- 0xd3, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xb8, 0xf4, 0x40, 0xca, 0xf4, 0x12, 0xf5, 0x7c,
- 0x8d, 0x82, 0x18, 0xd3, 0x9c, 0xac, 0xa3, 0x2c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92,
- 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0x73, 0x12, 0xf3, 0xd2, 0xf5, 0xc1, 0x9a, 0x93, 0x4a, 0xd3, 0x20,
- 0x8c, 0x64, 0xdd, 0xf4, 0xd4, 0x3c, 0xdd, 0xf4, 0x7c, 0xb0, 0xf9, 0x29, 0x89, 0x25, 0x89, 0xfa,
- 0x50, 0x0b, 0x93, 0xd8, 0xc0, 0xf2, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1f, 0x88, 0xfb,
- 0xea, 0xa8, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto
deleted file mode 100644
index 5c53950da..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto
+++ /dev/null
@@ -1,42 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package test;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports";
-
-import "imports/test_a_1/m2.proto";
-
-message A1M2 {
- test.a.M2 f = 1;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go
deleted file mode 100644
index f40e0b738..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go
+++ /dev/null
@@ -1,138 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: imports/test_import_all.proto
-
-package imports // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import fmt1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt"
-import test_a_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"
-import test_a_2 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2"
-import test_b_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type All struct {
- Am1 *test_a_1.M1 `protobuf:"bytes,1,opt,name=am1" json:"am1,omitempty"`
- Am2 *test_a_1.M2 `protobuf:"bytes,2,opt,name=am2" json:"am2,omitempty"`
- Am3 *test_a_2.M3 `protobuf:"bytes,3,opt,name=am3" json:"am3,omitempty"`
- Am4 *test_a_2.M4 `protobuf:"bytes,4,opt,name=am4" json:"am4,omitempty"`
- Bm1 *test_b_1.M1 `protobuf:"bytes,5,opt,name=bm1" json:"bm1,omitempty"`
- Bm2 *test_b_1.M2 `protobuf:"bytes,6,opt,name=bm2" json:"bm2,omitempty"`
- Fmt *fmt1.M `protobuf:"bytes,7,opt,name=fmt" json:"fmt,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *All) Reset() { *m = All{} }
-func (m *All) String() string { return proto.CompactTextString(m) }
-func (*All) ProtoMessage() {}
-func (*All) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_import_all_b41dc4592e4a4f3b, []int{0}
-}
-func (m *All) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_All.Unmarshal(m, b)
-}
-func (m *All) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_All.Marshal(b, m, deterministic)
-}
-func (dst *All) XXX_Merge(src proto.Message) {
- xxx_messageInfo_All.Merge(dst, src)
-}
-func (m *All) XXX_Size() int {
- return xxx_messageInfo_All.Size(m)
-}
-func (m *All) XXX_DiscardUnknown() {
- xxx_messageInfo_All.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_All proto.InternalMessageInfo
-
-func (m *All) GetAm1() *test_a_1.M1 {
- if m != nil {
- return m.Am1
- }
- return nil
-}
-
-func (m *All) GetAm2() *test_a_1.M2 {
- if m != nil {
- return m.Am2
- }
- return nil
-}
-
-func (m *All) GetAm3() *test_a_2.M3 {
- if m != nil {
- return m.Am3
- }
- return nil
-}
-
-func (m *All) GetAm4() *test_a_2.M4 {
- if m != nil {
- return m.Am4
- }
- return nil
-}
-
-func (m *All) GetBm1() *test_b_1.M1 {
- if m != nil {
- return m.Bm1
- }
- return nil
-}
-
-func (m *All) GetBm2() *test_b_1.M2 {
- if m != nil {
- return m.Bm2
- }
- return nil
-}
-
-func (m *All) GetFmt() *fmt1.M {
- if m != nil {
- return m.Fmt
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*All)(nil), "test.All")
-}
-
-func init() {
- proto.RegisterFile("imports/test_import_all.proto", fileDescriptor_test_import_all_b41dc4592e4a4f3b)
-}
-
-var fileDescriptor_test_import_all_b41dc4592e4a4f3b = []byte{
- // 258 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0xd0, 0xb1, 0x4e, 0xc3, 0x30,
- 0x10, 0x06, 0x60, 0x15, 0x97, 0x20, 0x99, 0x05, 0x85, 0xc5, 0x20, 0x90, 0x50, 0x27, 0x96, 0xda,
- 0xb2, 0x9d, 0x05, 0x31, 0xc1, 0xde, 0xa5, 0x23, 0x4b, 0x64, 0x97, 0xc6, 0x54, 0xf2, 0xd5, 0x51,
- 0x7a, 0x7d, 0x5e, 0x5e, 0x05, 0xd9, 0x07, 0x12, 0x84, 0x66, 0x4b, 0xfe, 0xef, 0xb7, 0xce, 0x3e,
- 0x7e, 0xbf, 0x83, 0x3e, 0x0d, 0x78, 0x50, 0xb8, 0x3d, 0x60, 0x4b, 0x3f, 0xad, 0x8b, 0x51, 0xf6,
- 0x43, 0xc2, 0x54, 0xcf, 0x73, 0x7c, 0x7b, 0xf3, 0xa7, 0xe4, 0x5a, 0xad, 0x40, 0x53, 0xe1, 0x14,
- 0x99, 0x09, 0x32, 0x0a, 0xec, 0x34, 0x35, 0x27, 0xc9, 0x4f, 0xcf, 0xf2, 0xbf, 0x67, 0x5d, 0xff,
- 0x50, 0x07, 0xa8, 0x80, 0xc2, 0xc5, 0xe7, 0x8c, 0xb3, 0x97, 0x18, 0xeb, 0x3b, 0xce, 0x1c, 0x68,
- 0x31, 0x7b, 0x98, 0x3d, 0x5e, 0x1a, 0x2e, 0xf3, 0x69, 0xe9, 0xe4, 0x4a, 0xaf, 0x73, 0x4c, 0x6a,
- 0xc4, 0xd9, 0x48, 0x4d, 0x56, 0x43, 0x6a, 0x05, 0x1b, 0xa9, 0xcd, 0x6a, 0x49, 0x1b, 0x31, 0x1f,
- 0x69, 0x93, 0xb5, 0xa9, 0x17, 0x9c, 0x79, 0xd0, 0xe2, 0xbc, 0xe8, 0x15, 0xa9, 0x97, 0xbd, 0x1b,
- 0x50, 0x97, 0xe9, 0x1e, 0x34, 0x75, 0x8c, 0xa8, 0xfe, 0x77, 0x4c, 0xb9, 0x83, 0x07, 0x53, 0x0b,
- 0xce, 0x3a, 0x40, 0x71, 0x51, 0x3a, 0x95, 0xec, 0x00, 0xe5, 0x6a, 0x9d, 0xa3, 0xd7, 0xe7, 0xb7,
- 0xa7, 0xb0, 0xc3, 0x8f, 0xa3, 0x97, 0x9b, 0x04, 0x2a, 0xa4, 0xe8, 0xf6, 0x41, 0x95, 0xc7, 0xfb,
- 0x63, 0x47, 0x1f, 0x9b, 0x65, 0xd8, 0xee, 0x97, 0x21, 0x95, 0xa5, 0xbd, 0x3b, 0x74, 0xea, 0x7b,
- 0x55, 0xbe, 0x2a, 0x6e, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0x95, 0x39, 0xa3, 0x82, 0x03, 0x02,
- 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto
deleted file mode 100644
index 582d722e3..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto
+++ /dev/null
@@ -1,58 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package test;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports";
-
-// test_a_1/m*.proto are in the same Go package and proto package.
-// test_a_*/*.proto are in different Go packages, but the same proto package.
-// test_b_1/*.proto are in the same Go package, but different proto packages.
-// fmt/m.proto has a package name which conflicts with "fmt".
-import "imports/test_a_1/m1.proto";
-import "imports/test_a_1/m2.proto";
-import "imports/test_a_2/m3.proto";
-import "imports/test_a_2/m4.proto";
-import "imports/test_b_1/m1.proto";
-import "imports/test_b_1/m2.proto";
-import "imports/fmt/m.proto";
-
-message All {
- test.a.M1 am1 = 1;
- test.a.M2 am2 = 2;
- test.a.M3 am3 = 3;
- test.a.M4 am4 = 4;
- test.b.part1.M1 bm1 = 5;
- test.b.part2.M2 bm2 = 6;
- fmt.M fmt = 7;
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go
deleted file mode 100644
index 7ec1f2dba..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// A simple binary to link together the protocol buffers in this test.
-
-package testdata
-
-import (
- "testing"
-
- importspb "github.com/golang/protobuf/protoc-gen-go/testdata/imports"
- multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
- mytestpb "github.com/golang/protobuf/protoc-gen-go/testdata/my_test"
-)
-
-func TestLink(t *testing.T) {
- _ = &multipb.Multi1{}
- _ = &mytestpb.Request{}
- _ = &importspb.All{}
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go
deleted file mode 100644
index da0fdf8fd..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go
+++ /dev/null
@@ -1,96 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: multi/multi1.proto
-
-package multitest // import "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type Multi1 struct {
- Multi2 *Multi2 `protobuf:"bytes,1,req,name=multi2" json:"multi2,omitempty"`
- Color *Multi2_Color `protobuf:"varint,2,opt,name=color,enum=multitest.Multi2_Color" json:"color,omitempty"`
- HatType *Multi3_HatType `protobuf:"varint,3,opt,name=hat_type,json=hatType,enum=multitest.Multi3_HatType" json:"hat_type,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Multi1) Reset() { *m = Multi1{} }
-func (m *Multi1) String() string { return proto.CompactTextString(m) }
-func (*Multi1) ProtoMessage() {}
-func (*Multi1) Descriptor() ([]byte, []int) {
- return fileDescriptor_multi1_08e50c6822e808b8, []int{0}
-}
-func (m *Multi1) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Multi1.Unmarshal(m, b)
-}
-func (m *Multi1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Multi1.Marshal(b, m, deterministic)
-}
-func (dst *Multi1) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Multi1.Merge(dst, src)
-}
-func (m *Multi1) XXX_Size() int {
- return xxx_messageInfo_Multi1.Size(m)
-}
-func (m *Multi1) XXX_DiscardUnknown() {
- xxx_messageInfo_Multi1.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Multi1 proto.InternalMessageInfo
-
-func (m *Multi1) GetMulti2() *Multi2 {
- if m != nil {
- return m.Multi2
- }
- return nil
-}
-
-func (m *Multi1) GetColor() Multi2_Color {
- if m != nil && m.Color != nil {
- return *m.Color
- }
- return Multi2_BLUE
-}
-
-func (m *Multi1) GetHatType() Multi3_HatType {
- if m != nil && m.HatType != nil {
- return *m.HatType
- }
- return Multi3_FEDORA
-}
-
-func init() {
- proto.RegisterType((*Multi1)(nil), "multitest.Multi1")
-}
-
-func init() { proto.RegisterFile("multi/multi1.proto", fileDescriptor_multi1_08e50c6822e808b8) }
-
-var fileDescriptor_multi1_08e50c6822e808b8 = []byte{
- // 200 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xca, 0x2d, 0xcd, 0x29,
- 0xc9, 0xd4, 0x07, 0x93, 0x86, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x9c, 0x60, 0x5e, 0x49,
- 0x6a, 0x71, 0x89, 0x14, 0xb2, 0xb4, 0x11, 0x44, 0x1a, 0x45, 0xcc, 0x18, 0x22, 0xa6, 0x34, 0x83,
- 0x91, 0x8b, 0xcd, 0x17, 0x6c, 0x86, 0x90, 0x26, 0x17, 0x1b, 0x44, 0xb9, 0x04, 0xa3, 0x02, 0x93,
- 0x06, 0xb7, 0x91, 0xa0, 0x1e, 0xdc, 0x38, 0x3d, 0xb0, 0x12, 0xa3, 0x20, 0xa8, 0x02, 0x21, 0x5d,
- 0x2e, 0xd6, 0xe4, 0xfc, 0x9c, 0xfc, 0x22, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x3e, 0x23, 0x71, 0x0c,
- 0x95, 0x7a, 0xce, 0x20, 0xe9, 0x20, 0x88, 0x2a, 0x21, 0x13, 0x2e, 0x8e, 0x8c, 0xc4, 0x92, 0xf8,
- 0x92, 0xca, 0x82, 0x54, 0x09, 0x66, 0xb0, 0x0e, 0x49, 0x74, 0x1d, 0xc6, 0x7a, 0x1e, 0x89, 0x25,
- 0x21, 0x95, 0x05, 0xa9, 0x41, 0xec, 0x19, 0x10, 0x86, 0x93, 0x73, 0x94, 0x63, 0x7a, 0x66, 0x49,
- 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, 0xba, 0x3e, 0xd8,
- 0xd5, 0x49, 0xa5, 0x69, 0x10, 0x46, 0xb2, 0x6e, 0x7a, 0x6a, 0x9e, 0x6e, 0x7a, 0xbe, 0x3e, 0xc8,
- 0xa0, 0x94, 0xc4, 0x92, 0x44, 0x88, 0xe7, 0xac, 0xe1, 0x86, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff,
- 0x60, 0x7d, 0xfc, 0x9f, 0x27, 0x01, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto
deleted file mode 100644
index d3a32041e..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto
+++ /dev/null
@@ -1,46 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-import "multi/multi2.proto";
-import "multi/multi3.proto";
-
-package multitest;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/multi;multitest";
-
-message Multi1 {
- required Multi2 multi2 = 1;
- optional Multi2.Color color = 2;
- optional Multi3.HatType hat_type = 3;
-}
-
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go
deleted file mode 100644
index b66ce7930..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go
+++ /dev/null
@@ -1,128 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: multi/multi2.proto
-
-package multitest // import "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type Multi2_Color int32
-
-const (
- Multi2_BLUE Multi2_Color = 1
- Multi2_GREEN Multi2_Color = 2
- Multi2_RED Multi2_Color = 3
-)
-
-var Multi2_Color_name = map[int32]string{
- 1: "BLUE",
- 2: "GREEN",
- 3: "RED",
-}
-var Multi2_Color_value = map[string]int32{
- "BLUE": 1,
- "GREEN": 2,
- "RED": 3,
-}
-
-func (x Multi2_Color) Enum() *Multi2_Color {
- p := new(Multi2_Color)
- *p = x
- return p
-}
-func (x Multi2_Color) String() string {
- return proto.EnumName(Multi2_Color_name, int32(x))
-}
-func (x *Multi2_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Multi2_Color_value, data, "Multi2_Color")
- if err != nil {
- return err
- }
- *x = Multi2_Color(value)
- return nil
-}
-func (Multi2_Color) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_multi2_c47490ad66d93e67, []int{0, 0}
-}
-
-type Multi2 struct {
- RequiredValue *int32 `protobuf:"varint,1,req,name=required_value,json=requiredValue" json:"required_value,omitempty"`
- Color *Multi2_Color `protobuf:"varint,2,opt,name=color,enum=multitest.Multi2_Color" json:"color,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Multi2) Reset() { *m = Multi2{} }
-func (m *Multi2) String() string { return proto.CompactTextString(m) }
-func (*Multi2) ProtoMessage() {}
-func (*Multi2) Descriptor() ([]byte, []int) {
- return fileDescriptor_multi2_c47490ad66d93e67, []int{0}
-}
-func (m *Multi2) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Multi2.Unmarshal(m, b)
-}
-func (m *Multi2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Multi2.Marshal(b, m, deterministic)
-}
-func (dst *Multi2) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Multi2.Merge(dst, src)
-}
-func (m *Multi2) XXX_Size() int {
- return xxx_messageInfo_Multi2.Size(m)
-}
-func (m *Multi2) XXX_DiscardUnknown() {
- xxx_messageInfo_Multi2.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Multi2 proto.InternalMessageInfo
-
-func (m *Multi2) GetRequiredValue() int32 {
- if m != nil && m.RequiredValue != nil {
- return *m.RequiredValue
- }
- return 0
-}
-
-func (m *Multi2) GetColor() Multi2_Color {
- if m != nil && m.Color != nil {
- return *m.Color
- }
- return Multi2_BLUE
-}
-
-func init() {
- proto.RegisterType((*Multi2)(nil), "multitest.Multi2")
- proto.RegisterEnum("multitest.Multi2_Color", Multi2_Color_name, Multi2_Color_value)
-}
-
-func init() { proto.RegisterFile("multi/multi2.proto", fileDescriptor_multi2_c47490ad66d93e67) }
-
-var fileDescriptor_multi2_c47490ad66d93e67 = []byte{
- // 202 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xca, 0x2d, 0xcd, 0x29,
- 0xc9, 0xd4, 0x07, 0x93, 0x46, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x9c, 0x60, 0x5e, 0x49,
- 0x6a, 0x71, 0x89, 0x52, 0x2b, 0x23, 0x17, 0x9b, 0x2f, 0x58, 0x4e, 0x48, 0x95, 0x8b, 0xaf, 0x28,
- 0xb5, 0xb0, 0x34, 0xb3, 0x28, 0x35, 0x25, 0xbe, 0x2c, 0x31, 0xa7, 0x34, 0x55, 0x82, 0x51, 0x81,
- 0x49, 0x83, 0x35, 0x88, 0x17, 0x26, 0x1a, 0x06, 0x12, 0x14, 0xd2, 0xe5, 0x62, 0x4d, 0xce, 0xcf,
- 0xc9, 0x2f, 0x92, 0x60, 0x52, 0x60, 0xd4, 0xe0, 0x33, 0x12, 0xd7, 0x83, 0x1b, 0xa6, 0x07, 0x31,
- 0x48, 0xcf, 0x19, 0x24, 0x1d, 0x04, 0x51, 0xa5, 0xa4, 0xca, 0xc5, 0x0a, 0xe6, 0x0b, 0x71, 0x70,
- 0xb1, 0x38, 0xf9, 0x84, 0xba, 0x0a, 0x30, 0x0a, 0x71, 0x72, 0xb1, 0xba, 0x07, 0xb9, 0xba, 0xfa,
- 0x09, 0x30, 0x09, 0xb1, 0x73, 0x31, 0x07, 0xb9, 0xba, 0x08, 0x30, 0x3b, 0x39, 0x47, 0x39, 0xa6,
- 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5,
- 0xeb, 0x83, 0x5d, 0x9b, 0x54, 0x9a, 0x06, 0x61, 0x24, 0xeb, 0xa6, 0xa7, 0xe6, 0xe9, 0xa6, 0xe7,
- 0xeb, 0x83, 0xec, 0x4a, 0x49, 0x2c, 0x49, 0x84, 0x78, 0xca, 0x1a, 0x6e, 0x3f, 0x20, 0x00, 0x00,
- 0xff, 0xff, 0x49, 0x3b, 0x52, 0x44, 0xec, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto
deleted file mode 100644
index ec5b431e3..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto
+++ /dev/null
@@ -1,48 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-package multitest;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/multi;multitest";
-
-message Multi2 {
- required int32 required_value = 1;
-
- enum Color {
- BLUE = 1;
- GREEN = 2;
- RED = 3;
- };
- optional Color color = 2;
-}
-
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go
deleted file mode 100644
index f03c350a0..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go
+++ /dev/null
@@ -1,115 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: multi/multi3.proto
-
-package multitest // import "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type Multi3_HatType int32
-
-const (
- Multi3_FEDORA Multi3_HatType = 1
- Multi3_FEZ Multi3_HatType = 2
-)
-
-var Multi3_HatType_name = map[int32]string{
- 1: "FEDORA",
- 2: "FEZ",
-}
-var Multi3_HatType_value = map[string]int32{
- "FEDORA": 1,
- "FEZ": 2,
-}
-
-func (x Multi3_HatType) Enum() *Multi3_HatType {
- p := new(Multi3_HatType)
- *p = x
- return p
-}
-func (x Multi3_HatType) String() string {
- return proto.EnumName(Multi3_HatType_name, int32(x))
-}
-func (x *Multi3_HatType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Multi3_HatType_value, data, "Multi3_HatType")
- if err != nil {
- return err
- }
- *x = Multi3_HatType(value)
- return nil
-}
-func (Multi3_HatType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_multi3_d55a72b4628b7875, []int{0, 0}
-}
-
-type Multi3 struct {
- HatType *Multi3_HatType `protobuf:"varint,1,opt,name=hat_type,json=hatType,enum=multitest.Multi3_HatType" json:"hat_type,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Multi3) Reset() { *m = Multi3{} }
-func (m *Multi3) String() string { return proto.CompactTextString(m) }
-func (*Multi3) ProtoMessage() {}
-func (*Multi3) Descriptor() ([]byte, []int) {
- return fileDescriptor_multi3_d55a72b4628b7875, []int{0}
-}
-func (m *Multi3) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Multi3.Unmarshal(m, b)
-}
-func (m *Multi3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Multi3.Marshal(b, m, deterministic)
-}
-func (dst *Multi3) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Multi3.Merge(dst, src)
-}
-func (m *Multi3) XXX_Size() int {
- return xxx_messageInfo_Multi3.Size(m)
-}
-func (m *Multi3) XXX_DiscardUnknown() {
- xxx_messageInfo_Multi3.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Multi3 proto.InternalMessageInfo
-
-func (m *Multi3) GetHatType() Multi3_HatType {
- if m != nil && m.HatType != nil {
- return *m.HatType
- }
- return Multi3_FEDORA
-}
-
-func init() {
- proto.RegisterType((*Multi3)(nil), "multitest.Multi3")
- proto.RegisterEnum("multitest.Multi3_HatType", Multi3_HatType_name, Multi3_HatType_value)
-}
-
-func init() { proto.RegisterFile("multi/multi3.proto", fileDescriptor_multi3_d55a72b4628b7875) }
-
-var fileDescriptor_multi3_d55a72b4628b7875 = []byte{
- // 170 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xca, 0x2d, 0xcd, 0x29,
- 0xc9, 0xd4, 0x07, 0x93, 0xc6, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x9c, 0x60, 0x5e, 0x49,
- 0x6a, 0x71, 0x89, 0x52, 0x1c, 0x17, 0x9b, 0x2f, 0x58, 0x4a, 0xc8, 0x84, 0x8b, 0x23, 0x23, 0xb1,
- 0x24, 0xbe, 0xa4, 0xb2, 0x20, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0xcf, 0x48, 0x52, 0x0f, 0xae,
- 0x4e, 0x0f, 0xa2, 0x48, 0xcf, 0x23, 0xb1, 0x24, 0xa4, 0xb2, 0x20, 0x35, 0x88, 0x3d, 0x03, 0xc2,
- 0x50, 0x92, 0xe3, 0x62, 0x87, 0x8a, 0x09, 0x71, 0x71, 0xb1, 0xb9, 0xb9, 0xba, 0xf8, 0x07, 0x39,
- 0x0a, 0x30, 0x0a, 0xb1, 0x73, 0x31, 0xbb, 0xb9, 0x46, 0x09, 0x30, 0x39, 0x39, 0x47, 0x39, 0xa6,
- 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5,
- 0xeb, 0x83, 0x5d, 0x91, 0x54, 0x9a, 0x06, 0x61, 0x24, 0xeb, 0xa6, 0xa7, 0xe6, 0xe9, 0xa6, 0xe7,
- 0xeb, 0x83, 0x2c, 0x4a, 0x49, 0x2c, 0x49, 0x84, 0x38, 0xd6, 0x1a, 0x6e, 0x39, 0x20, 0x00, 0x00,
- 0xff, 0xff, 0xd5, 0xa4, 0x1a, 0x0e, 0xc4, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto
deleted file mode 100644
index 8690b8815..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto
+++ /dev/null
@@ -1,45 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-package multitest;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/multi;multitest";
-
-message Multi3 {
- enum HatType {
- FEDORA = 1;
- FEZ = 2;
- };
- optional HatType hat_type = 1;
-}
-
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
deleted file mode 100644
index 8cf6a698f..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
+++ /dev/null
@@ -1,1174 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: my_test/test.proto
-
-package test // import "github.com/golang/protobuf/protoc-gen-go/testdata/my_test"
-
-/*
-This package holds interesting messages.
-*/
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type HatType int32
-
-const (
- // deliberately skipping 0
- HatType_FEDORA HatType = 1
- HatType_FEZ HatType = 2
-)
-
-var HatType_name = map[int32]string{
- 1: "FEDORA",
- 2: "FEZ",
-}
-var HatType_value = map[string]int32{
- "FEDORA": 1,
- "FEZ": 2,
-}
-
-func (x HatType) Enum() *HatType {
- p := new(HatType)
- *p = x
- return p
-}
-func (x HatType) String() string {
- return proto.EnumName(HatType_name, int32(x))
-}
-func (x *HatType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType")
- if err != nil {
- return err
- }
- *x = HatType(value)
- return nil
-}
-func (HatType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{0}
-}
-
-// This enum represents days of the week.
-type Days int32
-
-const (
- Days_MONDAY Days = 1
- Days_TUESDAY Days = 2
- Days_LUNDI Days = 1
-)
-
-var Days_name = map[int32]string{
- 1: "MONDAY",
- 2: "TUESDAY",
- // Duplicate value: 1: "LUNDI",
-}
-var Days_value = map[string]int32{
- "MONDAY": 1,
- "TUESDAY": 2,
- "LUNDI": 1,
-}
-
-func (x Days) Enum() *Days {
- p := new(Days)
- *p = x
- return p
-}
-func (x Days) String() string {
- return proto.EnumName(Days_name, int32(x))
-}
-func (x *Days) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days")
- if err != nil {
- return err
- }
- *x = Days(value)
- return nil
-}
-func (Days) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{1}
-}
-
-type Request_Color int32
-
-const (
- Request_RED Request_Color = 0
- Request_GREEN Request_Color = 1
- Request_BLUE Request_Color = 2
-)
-
-var Request_Color_name = map[int32]string{
- 0: "RED",
- 1: "GREEN",
- 2: "BLUE",
-}
-var Request_Color_value = map[string]int32{
- "RED": 0,
- "GREEN": 1,
- "BLUE": 2,
-}
-
-func (x Request_Color) Enum() *Request_Color {
- p := new(Request_Color)
- *p = x
- return p
-}
-func (x Request_Color) String() string {
- return proto.EnumName(Request_Color_name, int32(x))
-}
-func (x *Request_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color")
- if err != nil {
- return err
- }
- *x = Request_Color(value)
- return nil
-}
-func (Request_Color) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{0, 0}
-}
-
-type Reply_Entry_Game int32
-
-const (
- Reply_Entry_FOOTBALL Reply_Entry_Game = 1
- Reply_Entry_TENNIS Reply_Entry_Game = 2
-)
-
-var Reply_Entry_Game_name = map[int32]string{
- 1: "FOOTBALL",
- 2: "TENNIS",
-}
-var Reply_Entry_Game_value = map[string]int32{
- "FOOTBALL": 1,
- "TENNIS": 2,
-}
-
-func (x Reply_Entry_Game) Enum() *Reply_Entry_Game {
- p := new(Reply_Entry_Game)
- *p = x
- return p
-}
-func (x Reply_Entry_Game) String() string {
- return proto.EnumName(Reply_Entry_Game_name, int32(x))
-}
-func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game")
- if err != nil {
- return err
- }
- *x = Reply_Entry_Game(value)
- return nil
-}
-func (Reply_Entry_Game) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{1, 0, 0}
-}
-
-// This is a message that might be sent somewhere.
-type Request struct {
- Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"`
- // optional imp.ImportedMessage imported_message = 2;
- Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"`
- Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"`
- // optional imp.ImportedMessage.Owner owner = 6;
- Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"`
- Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
- // This is a map field. It will generate map[int32]string.
- NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- // This is a map field whose value type is a message.
- MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"`
- // This field should not conflict with any getters.
- GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Request) Reset() { *m = Request{} }
-func (m *Request) String() string { return proto.CompactTextString(m) }
-func (*Request) ProtoMessage() {}
-func (*Request) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{0}
-}
-func (m *Request) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Request.Unmarshal(m, b)
-}
-func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Request.Marshal(b, m, deterministic)
-}
-func (dst *Request) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Request.Merge(dst, src)
-}
-func (m *Request) XXX_Size() int {
- return xxx_messageInfo_Request.Size(m)
-}
-func (m *Request) XXX_DiscardUnknown() {
- xxx_messageInfo_Request.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Request proto.InternalMessageInfo
-
-const Default_Request_Hat HatType = HatType_FEDORA
-
-var Default_Request_Deadline float32 = float32(math.Inf(1))
-
-func (m *Request) GetKey() []int64 {
- if m != nil {
- return m.Key
- }
- return nil
-}
-
-func (m *Request) GetHue() Request_Color {
- if m != nil && m.Hue != nil {
- return *m.Hue
- }
- return Request_RED
-}
-
-func (m *Request) GetHat() HatType {
- if m != nil && m.Hat != nil {
- return *m.Hat
- }
- return Default_Request_Hat
-}
-
-func (m *Request) GetDeadline() float32 {
- if m != nil && m.Deadline != nil {
- return *m.Deadline
- }
- return Default_Request_Deadline
-}
-
-func (m *Request) GetSomegroup() *Request_SomeGroup {
- if m != nil {
- return m.Somegroup
- }
- return nil
-}
-
-func (m *Request) GetNameMapping() map[int32]string {
- if m != nil {
- return m.NameMapping
- }
- return nil
-}
-
-func (m *Request) GetMsgMapping() map[int64]*Reply {
- if m != nil {
- return m.MsgMapping
- }
- return nil
-}
-
-func (m *Request) GetReset_() int32 {
- if m != nil && m.Reset_ != nil {
- return *m.Reset_
- }
- return 0
-}
-
-func (m *Request) GetGetKey_() string {
- if m != nil && m.GetKey_ != nil {
- return *m.GetKey_
- }
- return ""
-}
-
-type Request_SomeGroup struct {
- GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} }
-func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) }
-func (*Request_SomeGroup) ProtoMessage() {}
-func (*Request_SomeGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{0, 0}
-}
-func (m *Request_SomeGroup) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Request_SomeGroup.Unmarshal(m, b)
-}
-func (m *Request_SomeGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Request_SomeGroup.Marshal(b, m, deterministic)
-}
-func (dst *Request_SomeGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Request_SomeGroup.Merge(dst, src)
-}
-func (m *Request_SomeGroup) XXX_Size() int {
- return xxx_messageInfo_Request_SomeGroup.Size(m)
-}
-func (m *Request_SomeGroup) XXX_DiscardUnknown() {
- xxx_messageInfo_Request_SomeGroup.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Request_SomeGroup proto.InternalMessageInfo
-
-func (m *Request_SomeGroup) GetGroupField() int32 {
- if m != nil && m.GroupField != nil {
- return *m.GroupField
- }
- return 0
-}
-
-type Reply struct {
- Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"`
- CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Reply) Reset() { *m = Reply{} }
-func (m *Reply) String() string { return proto.CompactTextString(m) }
-func (*Reply) ProtoMessage() {}
-func (*Reply) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{1}
-}
-
-var extRange_Reply = []proto.ExtensionRange{
- {Start: 100, End: 536870911},
-}
-
-func (*Reply) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_Reply
-}
-func (m *Reply) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Reply.Unmarshal(m, b)
-}
-func (m *Reply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Reply.Marshal(b, m, deterministic)
-}
-func (dst *Reply) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Reply.Merge(dst, src)
-}
-func (m *Reply) XXX_Size() int {
- return xxx_messageInfo_Reply.Size(m)
-}
-func (m *Reply) XXX_DiscardUnknown() {
- xxx_messageInfo_Reply.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Reply proto.InternalMessageInfo
-
-func (m *Reply) GetFound() []*Reply_Entry {
- if m != nil {
- return m.Found
- }
- return nil
-}
-
-func (m *Reply) GetCompactKeys() []int32 {
- if m != nil {
- return m.CompactKeys
- }
- return nil
-}
-
-type Reply_Entry struct {
- KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"`
- Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"`
- XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Reply_Entry) Reset() { *m = Reply_Entry{} }
-func (m *Reply_Entry) String() string { return proto.CompactTextString(m) }
-func (*Reply_Entry) ProtoMessage() {}
-func (*Reply_Entry) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{1, 0}
-}
-func (m *Reply_Entry) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Reply_Entry.Unmarshal(m, b)
-}
-func (m *Reply_Entry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Reply_Entry.Marshal(b, m, deterministic)
-}
-func (dst *Reply_Entry) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Reply_Entry.Merge(dst, src)
-}
-func (m *Reply_Entry) XXX_Size() int {
- return xxx_messageInfo_Reply_Entry.Size(m)
-}
-func (m *Reply_Entry) XXX_DiscardUnknown() {
- xxx_messageInfo_Reply_Entry.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Reply_Entry proto.InternalMessageInfo
-
-const Default_Reply_Entry_Value int64 = 7
-
-func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 {
- if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil {
- return *m.KeyThatNeeds_1234Camel_CasIng
- }
- return 0
-}
-
-func (m *Reply_Entry) GetValue() int64 {
- if m != nil && m.Value != nil {
- return *m.Value
- }
- return Default_Reply_Entry_Value
-}
-
-func (m *Reply_Entry) GetXMyFieldName_2() int64 {
- if m != nil && m.XMyFieldName_2 != nil {
- return *m.XMyFieldName_2
- }
- return 0
-}
-
-type OtherBase struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OtherBase) Reset() { *m = OtherBase{} }
-func (m *OtherBase) String() string { return proto.CompactTextString(m) }
-func (*OtherBase) ProtoMessage() {}
-func (*OtherBase) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{2}
-}
-
-var extRange_OtherBase = []proto.ExtensionRange{
- {Start: 100, End: 536870911},
-}
-
-func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OtherBase
-}
-func (m *OtherBase) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OtherBase.Unmarshal(m, b)
-}
-func (m *OtherBase) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OtherBase.Marshal(b, m, deterministic)
-}
-func (dst *OtherBase) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OtherBase.Merge(dst, src)
-}
-func (m *OtherBase) XXX_Size() int {
- return xxx_messageInfo_OtherBase.Size(m)
-}
-func (m *OtherBase) XXX_DiscardUnknown() {
- xxx_messageInfo_OtherBase.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OtherBase proto.InternalMessageInfo
-
-func (m *OtherBase) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-type ReplyExtensions struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} }
-func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) }
-func (*ReplyExtensions) ProtoMessage() {}
-func (*ReplyExtensions) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{3}
-}
-func (m *ReplyExtensions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ReplyExtensions.Unmarshal(m, b)
-}
-func (m *ReplyExtensions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ReplyExtensions.Marshal(b, m, deterministic)
-}
-func (dst *ReplyExtensions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ReplyExtensions.Merge(dst, src)
-}
-func (m *ReplyExtensions) XXX_Size() int {
- return xxx_messageInfo_ReplyExtensions.Size(m)
-}
-func (m *ReplyExtensions) XXX_DiscardUnknown() {
- xxx_messageInfo_ReplyExtensions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ReplyExtensions proto.InternalMessageInfo
-
-var E_ReplyExtensions_Time = &proto.ExtensionDesc{
- ExtendedType: (*Reply)(nil),
- ExtensionType: (*float64)(nil),
- Field: 101,
- Name: "my.test.ReplyExtensions.time",
- Tag: "fixed64,101,opt,name=time",
- Filename: "my_test/test.proto",
-}
-
-var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{
- ExtendedType: (*Reply)(nil),
- ExtensionType: (*ReplyExtensions)(nil),
- Field: 105,
- Name: "my.test.ReplyExtensions.carrot",
- Tag: "bytes,105,opt,name=carrot",
- Filename: "my_test/test.proto",
-}
-
-var E_ReplyExtensions_Donut = &proto.ExtensionDesc{
- ExtendedType: (*OtherBase)(nil),
- ExtensionType: (*ReplyExtensions)(nil),
- Field: 101,
- Name: "my.test.ReplyExtensions.donut",
- Tag: "bytes,101,opt,name=donut",
- Filename: "my_test/test.proto",
-}
-
-type OtherReplyExtensions struct {
- Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} }
-func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) }
-func (*OtherReplyExtensions) ProtoMessage() {}
-func (*OtherReplyExtensions) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{4}
-}
-func (m *OtherReplyExtensions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OtherReplyExtensions.Unmarshal(m, b)
-}
-func (m *OtherReplyExtensions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OtherReplyExtensions.Marshal(b, m, deterministic)
-}
-func (dst *OtherReplyExtensions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OtherReplyExtensions.Merge(dst, src)
-}
-func (m *OtherReplyExtensions) XXX_Size() int {
- return xxx_messageInfo_OtherReplyExtensions.Size(m)
-}
-func (m *OtherReplyExtensions) XXX_DiscardUnknown() {
- xxx_messageInfo_OtherReplyExtensions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OtherReplyExtensions proto.InternalMessageInfo
-
-func (m *OtherReplyExtensions) GetKey() int32 {
- if m != nil && m.Key != nil {
- return *m.Key
- }
- return 0
-}
-
-type OldReply struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `protobuf_messageset:"1" json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OldReply) Reset() { *m = OldReply{} }
-func (m *OldReply) String() string { return proto.CompactTextString(m) }
-func (*OldReply) ProtoMessage() {}
-func (*OldReply) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{5}
-}
-
-func (m *OldReply) MarshalJSON() ([]byte, error) {
- return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions)
-}
-func (m *OldReply) UnmarshalJSON(buf []byte) error {
- return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)
-}
-
-var extRange_OldReply = []proto.ExtensionRange{
- {Start: 100, End: 2147483646},
-}
-
-func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OldReply
-}
-func (m *OldReply) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OldReply.Unmarshal(m, b)
-}
-func (m *OldReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OldReply.Marshal(b, m, deterministic)
-}
-func (dst *OldReply) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OldReply.Merge(dst, src)
-}
-func (m *OldReply) XXX_Size() int {
- return xxx_messageInfo_OldReply.Size(m)
-}
-func (m *OldReply) XXX_DiscardUnknown() {
- xxx_messageInfo_OldReply.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OldReply proto.InternalMessageInfo
-
-type Communique struct {
- MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"`
- // This is a oneof, called "union".
- //
- // Types that are valid to be assigned to Union:
- // *Communique_Number
- // *Communique_Name
- // *Communique_Data
- // *Communique_TempC
- // *Communique_Height
- // *Communique_Today
- // *Communique_Maybe
- // *Communique_Delta_
- // *Communique_Msg
- // *Communique_Somegroup
- Union isCommunique_Union `protobuf_oneof:"union"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Communique) Reset() { *m = Communique{} }
-func (m *Communique) String() string { return proto.CompactTextString(m) }
-func (*Communique) ProtoMessage() {}
-func (*Communique) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{6}
-}
-func (m *Communique) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Communique.Unmarshal(m, b)
-}
-func (m *Communique) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Communique.Marshal(b, m, deterministic)
-}
-func (dst *Communique) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Communique.Merge(dst, src)
-}
-func (m *Communique) XXX_Size() int {
- return xxx_messageInfo_Communique.Size(m)
-}
-func (m *Communique) XXX_DiscardUnknown() {
- xxx_messageInfo_Communique.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Communique proto.InternalMessageInfo
-
-type isCommunique_Union interface {
- isCommunique_Union()
-}
-
-type Communique_Number struct {
- Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
-}
-type Communique_Name struct {
- Name string `protobuf:"bytes,6,opt,name=name,oneof"`
-}
-type Communique_Data struct {
- Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
-}
-type Communique_TempC struct {
- TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
-}
-type Communique_Height struct {
- Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"`
-}
-type Communique_Today struct {
- Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"`
-}
-type Communique_Maybe struct {
- Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"`
-}
-type Communique_Delta_ struct {
- Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"`
-}
-type Communique_Msg struct {
- Msg *Reply `protobuf:"bytes,16,opt,name=msg,oneof"`
-}
-type Communique_Somegroup struct {
- Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"`
-}
-
-func (*Communique_Number) isCommunique_Union() {}
-func (*Communique_Name) isCommunique_Union() {}
-func (*Communique_Data) isCommunique_Union() {}
-func (*Communique_TempC) isCommunique_Union() {}
-func (*Communique_Height) isCommunique_Union() {}
-func (*Communique_Today) isCommunique_Union() {}
-func (*Communique_Maybe) isCommunique_Union() {}
-func (*Communique_Delta_) isCommunique_Union() {}
-func (*Communique_Msg) isCommunique_Union() {}
-func (*Communique_Somegroup) isCommunique_Union() {}
-
-func (m *Communique) GetUnion() isCommunique_Union {
- if m != nil {
- return m.Union
- }
- return nil
-}
-
-func (m *Communique) GetMakeMeCry() bool {
- if m != nil && m.MakeMeCry != nil {
- return *m.MakeMeCry
- }
- return false
-}
-
-func (m *Communique) GetNumber() int32 {
- if x, ok := m.GetUnion().(*Communique_Number); ok {
- return x.Number
- }
- return 0
-}
-
-func (m *Communique) GetName() string {
- if x, ok := m.GetUnion().(*Communique_Name); ok {
- return x.Name
- }
- return ""
-}
-
-func (m *Communique) GetData() []byte {
- if x, ok := m.GetUnion().(*Communique_Data); ok {
- return x.Data
- }
- return nil
-}
-
-func (m *Communique) GetTempC() float64 {
- if x, ok := m.GetUnion().(*Communique_TempC); ok {
- return x.TempC
- }
- return 0
-}
-
-func (m *Communique) GetHeight() float32 {
- if x, ok := m.GetUnion().(*Communique_Height); ok {
- return x.Height
- }
- return 0
-}
-
-func (m *Communique) GetToday() Days {
- if x, ok := m.GetUnion().(*Communique_Today); ok {
- return x.Today
- }
- return Days_MONDAY
-}
-
-func (m *Communique) GetMaybe() bool {
- if x, ok := m.GetUnion().(*Communique_Maybe); ok {
- return x.Maybe
- }
- return false
-}
-
-func (m *Communique) GetDelta() int32 {
- if x, ok := m.GetUnion().(*Communique_Delta_); ok {
- return x.Delta
- }
- return 0
-}
-
-func (m *Communique) GetMsg() *Reply {
- if x, ok := m.GetUnion().(*Communique_Msg); ok {
- return x.Msg
- }
- return nil
-}
-
-func (m *Communique) GetSomegroup() *Communique_SomeGroup {
- if x, ok := m.GetUnion().(*Communique_Somegroup); ok {
- return x.Somegroup
- }
- return nil
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{
- (*Communique_Number)(nil),
- (*Communique_Name)(nil),
- (*Communique_Data)(nil),
- (*Communique_TempC)(nil),
- (*Communique_Height)(nil),
- (*Communique_Today)(nil),
- (*Communique_Maybe)(nil),
- (*Communique_Delta_)(nil),
- (*Communique_Msg)(nil),
- (*Communique_Somegroup)(nil),
- }
-}
-
-func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*Communique)
- // union
- switch x := m.Union.(type) {
- case *Communique_Number:
- b.EncodeVarint(5<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Number))
- case *Communique_Name:
- b.EncodeVarint(6<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.Name)
- case *Communique_Data:
- b.EncodeVarint(7<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.Data)
- case *Communique_TempC:
- b.EncodeVarint(8<<3 | proto.WireFixed64)
- b.EncodeFixed64(math.Float64bits(x.TempC))
- case *Communique_Height:
- b.EncodeVarint(9<<3 | proto.WireFixed32)
- b.EncodeFixed32(uint64(math.Float32bits(x.Height)))
- case *Communique_Today:
- b.EncodeVarint(10<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Today))
- case *Communique_Maybe:
- t := uint64(0)
- if x.Maybe {
- t = 1
- }
- b.EncodeVarint(11<<3 | proto.WireVarint)
- b.EncodeVarint(t)
- case *Communique_Delta_:
- b.EncodeVarint(12<<3 | proto.WireVarint)
- b.EncodeZigzag32(uint64(x.Delta))
- case *Communique_Msg:
- b.EncodeVarint(16<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.Msg); err != nil {
- return err
- }
- case *Communique_Somegroup:
- b.EncodeVarint(14<<3 | proto.WireStartGroup)
- if err := b.Marshal(x.Somegroup); err != nil {
- return err
- }
- b.EncodeVarint(14<<3 | proto.WireEndGroup)
- case nil:
- default:
- return fmt.Errorf("Communique.Union has unexpected type %T", x)
- }
- return nil
-}
-
-func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*Communique)
- switch tag {
- case 5: // union.number
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Number{int32(x)}
- return true, err
- case 6: // union.name
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &Communique_Name{x}
- return true, err
- case 7: // union.data
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Union = &Communique_Data{x}
- return true, err
- case 8: // union.temp_c
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Communique_TempC{math.Float64frombits(x)}
- return true, err
- case 9: // union.height
- if wire != proto.WireFixed32 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed32()
- m.Union = &Communique_Height{math.Float32frombits(uint32(x))}
- return true, err
- case 10: // union.today
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Today{Days(x)}
- return true, err
- case 11: // union.maybe
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Maybe{x != 0}
- return true, err
- case 12: // union.delta
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeZigzag32()
- m.Union = &Communique_Delta_{int32(x)}
- return true, err
- case 16: // union.msg
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Reply)
- err := b.DecodeMessage(msg)
- m.Union = &Communique_Msg{msg}
- return true, err
- case 14: // union.somegroup
- if wire != proto.WireStartGroup {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Communique_SomeGroup)
- err := b.DecodeGroup(msg)
- m.Union = &Communique_Somegroup{msg}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _Communique_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*Communique)
- // union
- switch x := m.Union.(type) {
- case *Communique_Number:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.Number))
- case *Communique_Name:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Name)))
- n += len(x.Name)
- case *Communique_Data:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.Data)))
- n += len(x.Data)
- case *Communique_TempC:
- n += 1 // tag and wire
- n += 8
- case *Communique_Height:
- n += 1 // tag and wire
- n += 4
- case *Communique_Today:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.Today))
- case *Communique_Maybe:
- n += 1 // tag and wire
- n += 1
- case *Communique_Delta_:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31))))
- case *Communique_Msg:
- s := proto.Size(x.Msg)
- n += 2 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case *Communique_Somegroup:
- n += 1 // tag and wire
- n += proto.Size(x.Somegroup)
- n += 1 // tag and wire
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-type Communique_SomeGroup struct {
- Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} }
-func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) }
-func (*Communique_SomeGroup) ProtoMessage() {}
-func (*Communique_SomeGroup) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{6, 0}
-}
-func (m *Communique_SomeGroup) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Communique_SomeGroup.Unmarshal(m, b)
-}
-func (m *Communique_SomeGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Communique_SomeGroup.Marshal(b, m, deterministic)
-}
-func (dst *Communique_SomeGroup) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Communique_SomeGroup.Merge(dst, src)
-}
-func (m *Communique_SomeGroup) XXX_Size() int {
- return xxx_messageInfo_Communique_SomeGroup.Size(m)
-}
-func (m *Communique_SomeGroup) XXX_DiscardUnknown() {
- xxx_messageInfo_Communique_SomeGroup.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Communique_SomeGroup proto.InternalMessageInfo
-
-func (m *Communique_SomeGroup) GetMember() string {
- if m != nil && m.Member != nil {
- return *m.Member
- }
- return ""
-}
-
-type Communique_Delta struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Communique_Delta) Reset() { *m = Communique_Delta{} }
-func (m *Communique_Delta) String() string { return proto.CompactTextString(m) }
-func (*Communique_Delta) ProtoMessage() {}
-func (*Communique_Delta) Descriptor() ([]byte, []int) {
- return fileDescriptor_test_2309d445eee26af7, []int{6, 1}
-}
-func (m *Communique_Delta) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Communique_Delta.Unmarshal(m, b)
-}
-func (m *Communique_Delta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Communique_Delta.Marshal(b, m, deterministic)
-}
-func (dst *Communique_Delta) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Communique_Delta.Merge(dst, src)
-}
-func (m *Communique_Delta) XXX_Size() int {
- return xxx_messageInfo_Communique_Delta.Size(m)
-}
-func (m *Communique_Delta) XXX_DiscardUnknown() {
- xxx_messageInfo_Communique_Delta.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Communique_Delta proto.InternalMessageInfo
-
-var E_Tag = &proto.ExtensionDesc{
- ExtendedType: (*Reply)(nil),
- ExtensionType: (*string)(nil),
- Field: 103,
- Name: "my.test.tag",
- Tag: "bytes,103,opt,name=tag",
- Filename: "my_test/test.proto",
-}
-
-var E_Donut = &proto.ExtensionDesc{
- ExtendedType: (*Reply)(nil),
- ExtensionType: (*OtherReplyExtensions)(nil),
- Field: 106,
- Name: "my.test.donut",
- Tag: "bytes,106,opt,name=donut",
- Filename: "my_test/test.proto",
-}
-
-func init() {
- proto.RegisterType((*Request)(nil), "my.test.Request")
- proto.RegisterMapType((map[int64]*Reply)(nil), "my.test.Request.MsgMappingEntry")
- proto.RegisterMapType((map[int32]string)(nil), "my.test.Request.NameMappingEntry")
- proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup")
- proto.RegisterType((*Reply)(nil), "my.test.Reply")
- proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry")
- proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase")
- proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions")
- proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions")
- proto.RegisterType((*OldReply)(nil), "my.test.OldReply")
- proto.RegisterType((*Communique)(nil), "my.test.Communique")
- proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup")
- proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta")
- proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value)
- proto.RegisterEnum("my.test.Days", Days_name, Days_value)
- proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value)
- proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value)
- proto.RegisterExtension(E_ReplyExtensions_Time)
- proto.RegisterExtension(E_ReplyExtensions_Carrot)
- proto.RegisterExtension(E_ReplyExtensions_Donut)
- proto.RegisterExtension(E_Tag)
- proto.RegisterExtension(E_Donut)
-}
-
-func init() { proto.RegisterFile("my_test/test.proto", fileDescriptor_test_2309d445eee26af7) }
-
-var fileDescriptor_test_2309d445eee26af7 = []byte{
- // 1033 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x55, 0xdd, 0x6e, 0xe3, 0x44,
- 0x14, 0xce, 0xd8, 0x71, 0x7e, 0x4e, 0x42, 0x6b, 0x46, 0x55, 0x6b, 0x05, 0xed, 0xd6, 0x04, 0x8a,
- 0x4c, 0xc5, 0xa6, 0xda, 0x80, 0xc4, 0x2a, 0x88, 0xd5, 0x36, 0x3f, 0x6d, 0xaa, 0x6d, 0x12, 0x69,
- 0xda, 0x5e, 0xb0, 0x37, 0xd6, 0x34, 0x9e, 0x3a, 0xa6, 0x19, 0x3b, 0x6b, 0x8f, 0x11, 0xbe, 0xeb,
- 0x53, 0xc0, 0x6b, 0x70, 0xcf, 0x0b, 0xf1, 0x16, 0x45, 0x33, 0x0e, 0x49, 0xda, 0xa0, 0xbd, 0xb1,
- 0x7c, 0xce, 0xf9, 0xce, 0xe7, 0x39, 0x3f, 0xfe, 0x06, 0x30, 0xcf, 0x5c, 0xc1, 0x12, 0x71, 0x22,
- 0x1f, 0xad, 0x45, 0x1c, 0x89, 0x08, 0x97, 0x79, 0xd6, 0x92, 0x66, 0x03, 0xf3, 0x74, 0x2e, 0x82,
- 0x13, 0xf5, 0x7c, 0x9d, 0x07, 0x9b, 0xff, 0x14, 0xa1, 0x4c, 0xd8, 0xc7, 0x94, 0x25, 0x02, 0x9b,
- 0xa0, 0xdf, 0xb3, 0xcc, 0x42, 0xb6, 0xee, 0xe8, 0x44, 0xbe, 0x62, 0x07, 0xf4, 0x59, 0xca, 0x2c,
- 0xdd, 0x46, 0xce, 0x4e, 0x7b, 0xbf, 0xb5, 0x24, 0x6a, 0x2d, 0x13, 0x5a, 0xbd, 0x68, 0x1e, 0xc5,
- 0x44, 0x42, 0xf0, 0x31, 0xe8, 0x33, 0x2a, 0xac, 0xa2, 0x42, 0x9a, 0x2b, 0xe4, 0x90, 0x8a, 0xeb,
- 0x6c, 0xc1, 0x3a, 0xa5, 0xb3, 0x41, 0x7f, 0x42, 0x4e, 0x89, 0x04, 0xe1, 0x43, 0xa8, 0x78, 0x8c,
- 0x7a, 0xf3, 0x20, 0x64, 0x56, 0xd9, 0x46, 0x8e, 0xd6, 0xd1, 0x83, 0xf0, 0x8e, 0xac, 0x9c, 0xf8,
- 0x0d, 0x54, 0x93, 0x88, 0x33, 0x3f, 0x8e, 0xd2, 0x85, 0x55, 0xb1, 0x91, 0x03, 0xed, 0xc6, 0xd6,
- 0xc7, 0xaf, 0x22, 0xce, 0xce, 0x25, 0x82, 0xac, 0xc1, 0xb8, 0x0f, 0xf5, 0x90, 0x72, 0xe6, 0x72,
- 0xba, 0x58, 0x04, 0xa1, 0x6f, 0xed, 0xd8, 0xba, 0x53, 0x6b, 0x7f, 0xb9, 0x95, 0x3c, 0xa6, 0x9c,
- 0x8d, 0x72, 0xcc, 0x20, 0x14, 0x71, 0x46, 0x6a, 0xe1, 0xda, 0x83, 0x4f, 0xa1, 0xc6, 0x13, 0x7f,
- 0x45, 0xb2, 0xab, 0x48, 0xec, 0x2d, 0x92, 0x51, 0xe2, 0x3f, 0xe1, 0x00, 0xbe, 0x72, 0xe0, 0x3d,
- 0x30, 0x62, 0x96, 0x30, 0x61, 0xd5, 0x6d, 0xe4, 0x18, 0x24, 0x37, 0xf0, 0x01, 0x94, 0x7d, 0x26,
- 0x5c, 0xd9, 0x65, 0xd3, 0x46, 0x4e, 0x95, 0x94, 0x7c, 0x26, 0xde, 0xb3, 0xac, 0xf1, 0x1d, 0x54,
- 0x57, 0xf5, 0xe0, 0x43, 0xa8, 0xa9, 0x6a, 0xdc, 0xbb, 0x80, 0xcd, 0x3d, 0xab, 0xaa, 0x18, 0x40,
- 0xb9, 0xce, 0xa4, 0xa7, 0xf1, 0x16, 0xcc, 0xe7, 0x05, 0xac, 0x87, 0x27, 0xc1, 0x6a, 0x78, 0x7b,
- 0x60, 0xfc, 0x46, 0xe7, 0x29, 0xb3, 0x34, 0xf5, 0xa9, 0xdc, 0xe8, 0x68, 0x6f, 0x50, 0x63, 0x04,
- 0xbb, 0xcf, 0xce, 0xbe, 0x99, 0x8e, 0xf3, 0xf4, 0xaf, 0x37, 0xd3, 0x6b, 0xed, 0x9d, 0x8d, 0xf2,
- 0x17, 0xf3, 0x6c, 0x83, 0xae, 0x79, 0x04, 0x86, 0xda, 0x04, 0x5c, 0x06, 0x9d, 0x0c, 0xfa, 0x66,
- 0x01, 0x57, 0xc1, 0x38, 0x27, 0x83, 0xc1, 0xd8, 0x44, 0xb8, 0x02, 0xc5, 0xee, 0xe5, 0xcd, 0xc0,
- 0xd4, 0x9a, 0x7f, 0x6a, 0x60, 0xa8, 0x5c, 0x7c, 0x0c, 0xc6, 0x5d, 0x94, 0x86, 0x9e, 0x5a, 0xb5,
- 0x5a, 0x7b, 0xef, 0x29, 0x75, 0x2b, 0xef, 0x66, 0x0e, 0xc1, 0x47, 0x50, 0x9f, 0x46, 0x7c, 0x41,
- 0xa7, 0xaa, 0x6d, 0x89, 0xa5, 0xd9, 0xba, 0x63, 0x74, 0x35, 0x13, 0x91, 0xda, 0xd2, 0xff, 0x9e,
- 0x65, 0x49, 0xe3, 0x2f, 0x04, 0x46, 0x5e, 0x49, 0x1f, 0x0e, 0xef, 0x59, 0xe6, 0x8a, 0x19, 0x15,
- 0x6e, 0xc8, 0x98, 0x97, 0xb8, 0xaf, 0xdb, 0xdf, 0xff, 0x30, 0xa5, 0x9c, 0xcd, 0xdd, 0x1e, 0x4d,
- 0x2e, 0x42, 0xdf, 0x42, 0xb6, 0xe6, 0xe8, 0xe4, 0x8b, 0x7b, 0x96, 0x5d, 0xcf, 0xa8, 0x18, 0x4b,
- 0xd0, 0x0a, 0x93, 0x43, 0xf0, 0xc1, 0x66, 0xf5, 0x7a, 0x07, 0xfd, 0xb8, 0x2c, 0x18, 0x7f, 0x03,
- 0xa6, 0xcb, 0xb3, 0x7c, 0x34, 0xae, 0xda, 0xb5, 0xb6, 0xfa, 0x3f, 0x74, 0x52, 0x1f, 0x65, 0x6a,
- 0x3c, 0x72, 0x34, 0xed, 0xa6, 0x0d, 0xc5, 0x73, 0xca, 0x19, 0xae, 0x43, 0xe5, 0x6c, 0x32, 0xb9,
- 0xee, 0x9e, 0x5e, 0x5e, 0x9a, 0x08, 0x03, 0x94, 0xae, 0x07, 0xe3, 0xf1, 0xc5, 0x95, 0xa9, 0x1d,
- 0x57, 0x2a, 0x9e, 0xf9, 0xf0, 0xf0, 0xf0, 0xa0, 0x35, 0xbf, 0x85, 0xea, 0x44, 0xcc, 0x58, 0xdc,
- 0xa5, 0x09, 0xc3, 0x18, 0x8a, 0x92, 0x56, 0x8d, 0xa2, 0x4a, 0xd4, 0xfb, 0x06, 0xf4, 0x6f, 0x04,
- 0xbb, 0xaa, 0x4b, 0x83, 0xdf, 0x05, 0x0b, 0x93, 0x20, 0x0a, 0x93, 0x76, 0x13, 0x8a, 0x22, 0xe0,
- 0x0c, 0x3f, 0x1b, 0x91, 0xc5, 0x6c, 0xe4, 0x20, 0xa2, 0x62, 0xed, 0x77, 0x50, 0x9a, 0xd2, 0x38,
- 0x8e, 0xc4, 0x16, 0x2a, 0x50, 0xe3, 0xb5, 0x9e, 0x7a, 0xd7, 0xec, 0x64, 0x99, 0xd7, 0xee, 0x82,
- 0xe1, 0x45, 0x61, 0x2a, 0x30, 0x5e, 0x41, 0x57, 0x87, 0x56, 0x9f, 0xfa, 0x14, 0x49, 0x9e, 0xda,
- 0x74, 0x60, 0x4f, 0xe5, 0x3c, 0x0b, 0x6f, 0x2f, 0x6f, 0xd3, 0x82, 0xca, 0x64, 0xee, 0x29, 0x9c,
- 0xaa, 0xfe, 0xf1, 0xf1, 0xf1, 0xb1, 0xdc, 0xd1, 0x2a, 0xa8, 0xf9, 0x87, 0x0e, 0xd0, 0x8b, 0x38,
- 0x4f, 0xc3, 0xe0, 0x63, 0xca, 0xf0, 0x4b, 0xa8, 0x71, 0x7a, 0xcf, 0x5c, 0xce, 0xdc, 0x69, 0x9c,
- 0x53, 0x54, 0x48, 0x55, 0xba, 0x46, 0xac, 0x17, 0x67, 0xd8, 0x82, 0x52, 0x98, 0xf2, 0x5b, 0x16,
- 0x5b, 0x86, 0x64, 0x1f, 0x16, 0xc8, 0xd2, 0xc6, 0x7b, 0xcb, 0x46, 0x97, 0x64, 0xa3, 0x87, 0x85,
- 0xbc, 0xd5, 0xd2, 0xeb, 0x51, 0x41, 0x95, 0x30, 0xd5, 0xa5, 0x57, 0x5a, 0xf8, 0x00, 0x4a, 0x82,
- 0xf1, 0x85, 0x3b, 0x55, 0x72, 0x84, 0x86, 0x05, 0x62, 0x48, 0xbb, 0x27, 0xe9, 0x67, 0x2c, 0xf0,
- 0x67, 0x42, 0xfd, 0xa6, 0x9a, 0xa4, 0xcf, 0x6d, 0x7c, 0x04, 0x86, 0x88, 0x3c, 0x9a, 0x59, 0xa0,
- 0x34, 0xf1, 0xb3, 0x55, 0x6f, 0xfa, 0x34, 0x4b, 0x14, 0x81, 0x8c, 0xe2, 0x7d, 0x30, 0x38, 0xcd,
- 0x6e, 0x99, 0x55, 0x93, 0x27, 0x97, 0x7e, 0x65, 0x4a, 0xbf, 0xc7, 0xe6, 0x82, 0x2a, 0x01, 0xf9,
- 0x5c, 0xfa, 0x95, 0x89, 0x9b, 0xa0, 0xf3, 0xc4, 0x57, 0xf2, 0xb1, 0xf5, 0x53, 0x0e, 0x0b, 0x44,
- 0x06, 0xf1, 0xcf, 0x9b, 0xfa, 0xb9, 0xa3, 0xf4, 0xf3, 0xc5, 0x0a, 0xb9, 0xee, 0xdd, 0x5a, 0x42,
- 0x87, 0x85, 0x0d, 0x11, 0x6d, 0x7c, 0xb5, 0x29, 0x46, 0xfb, 0x50, 0xe2, 0x4c, 0xf5, 0x6f, 0x37,
- 0x57, 0xac, 0xdc, 0x6a, 0x94, 0xc1, 0xe8, 0xcb, 0x03, 0x75, 0xcb, 0x60, 0xa4, 0x61, 0x10, 0x85,
- 0xc7, 0x2f, 0xa1, 0xbc, 0x94, 0x7b, 0xb9, 0xe6, 0xb9, 0xe0, 0x9b, 0x48, 0x8a, 0xc2, 0xd9, 0xe0,
- 0x83, 0xa9, 0x1d, 0xb7, 0xa0, 0x28, 0x4b, 0x97, 0xc1, 0xd1, 0x64, 0xdc, 0x3f, 0xfd, 0xc5, 0x44,
- 0xb8, 0x06, 0xe5, 0xeb, 0x9b, 0xc1, 0x95, 0x34, 0x34, 0xa9, 0x1a, 0x97, 0x37, 0xe3, 0xfe, 0x85,
- 0x89, 0x1a, 0x9a, 0x89, 0x3a, 0x36, 0xe8, 0x82, 0xfa, 0x5b, 0xfb, 0xea, 0xab, 0x63, 0xc8, 0x50,
- 0xa7, 0xf7, 0xdf, 0x4a, 0x3e, 0xc7, 0xfc, 0xaa, 0xba, 0xf3, 0xe2, 0xe9, 0xa2, 0xfe, 0xff, 0x4e,
- 0x76, 0xdf, 0x7d, 0x78, 0xeb, 0x07, 0x62, 0x96, 0xde, 0xb6, 0xa6, 0x11, 0x3f, 0xf1, 0xa3, 0x39,
- 0x0d, 0xfd, 0x13, 0x75, 0x39, 0xde, 0xa6, 0x77, 0xf9, 0xcb, 0xf4, 0x95, 0xcf, 0xc2, 0x57, 0x7e,
- 0xa4, 0x6e, 0x55, 0xb9, 0x0f, 0x27, 0xcb, 0x6b, 0xf6, 0x27, 0xf9, 0xf8, 0x37, 0x00, 0x00, 0xff,
- 0xff, 0x12, 0xd5, 0x46, 0x00, 0x75, 0x07, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto
deleted file mode 100644
index 1ef3fd029..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto
+++ /dev/null
@@ -1,158 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto2";
-
-// This package holds interesting messages.
-package my.test; // dotted package name
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/my_test;test";
-
-//import "imp.proto";
-import "multi/multi1.proto"; // unused import
-
-enum HatType {
- // deliberately skipping 0
- FEDORA = 1;
- FEZ = 2;
-}
-
-// This enum represents days of the week.
-enum Days {
- option allow_alias = true;
-
- MONDAY = 1;
- TUESDAY = 2;
- LUNDI = 1; // same value as MONDAY
-}
-
-// This is a message that might be sent somewhere.
-message Request {
- enum Color {
- RED = 0;
- GREEN = 1;
- BLUE = 2;
- }
- repeated int64 key = 1;
-// optional imp.ImportedMessage imported_message = 2;
- optional Color hue = 3; // no default
- optional HatType hat = 4 [default=FEDORA];
-// optional imp.ImportedMessage.Owner owner = 6;
- optional float deadline = 7 [default=inf];
- optional group SomeGroup = 8 {
- optional int32 group_field = 9;
- }
-
- // These foreign types are in imp2.proto,
- // which is publicly imported by imp.proto.
-// optional imp.PubliclyImportedMessage pub = 10;
-// optional imp.PubliclyImportedEnum pub_enum = 13 [default=HAIR];
-
-
- // This is a map field. It will generate map[int32]string.
- map name_mapping = 14;
- // This is a map field whose value type is a message.
- map msg_mapping = 15;
-
- optional int32 reset = 12;
- // This field should not conflict with any getters.
- optional string get_key = 16;
-}
-
-message Reply {
- message Entry {
- required int64 key_that_needs_1234camel_CasIng = 1;
- optional int64 value = 2 [default=7];
- optional int64 _my_field_name_2 = 3;
- enum Game {
- FOOTBALL = 1;
- TENNIS = 2;
- }
- }
- repeated Entry found = 1;
- repeated int32 compact_keys = 2 [packed=true];
- extensions 100 to max;
-}
-
-message OtherBase {
- optional string name = 1;
- extensions 100 to max;
-}
-
-message ReplyExtensions {
- extend Reply {
- optional double time = 101;
- optional ReplyExtensions carrot = 105;
- }
- extend OtherBase {
- optional ReplyExtensions donut = 101;
- }
-}
-
-message OtherReplyExtensions {
- optional int32 key = 1;
-}
-
-// top-level extension
-extend Reply {
- optional string tag = 103;
- optional OtherReplyExtensions donut = 106;
-// optional imp.ImportedMessage elephant = 107; // extend with message from another file.
-}
-
-message OldReply {
- // Extensions will be encoded in MessageSet wire format.
- option message_set_wire_format = true;
- extensions 100 to max;
-}
-
-message Communique {
- optional bool make_me_cry = 1;
-
- // This is a oneof, called "union".
- oneof union {
- int32 number = 5;
- string name = 6;
- bytes data = 7;
- double temp_c = 8;
- float height = 9;
- Days today = 10;
- bool maybe = 11;
- sint32 delta = 12; // name will conflict with Delta below
- Reply msg = 16; // requires two bytes to encode field tag
- group SomeGroup = 14 {
- optional string member = 15;
- }
- }
-
- message Delta {}
-}
-
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go
deleted file mode 100644
index 3b0ad8491..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go
+++ /dev/null
@@ -1,196 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: proto3/proto3.proto
-
-package proto3 // import "github.com/golang/protobuf/protoc-gen-go/testdata/proto3"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type Request_Flavour int32
-
-const (
- Request_SWEET Request_Flavour = 0
- Request_SOUR Request_Flavour = 1
- Request_UMAMI Request_Flavour = 2
- Request_GOPHERLICIOUS Request_Flavour = 3
-)
-
-var Request_Flavour_name = map[int32]string{
- 0: "SWEET",
- 1: "SOUR",
- 2: "UMAMI",
- 3: "GOPHERLICIOUS",
-}
-var Request_Flavour_value = map[string]int32{
- "SWEET": 0,
- "SOUR": 1,
- "UMAMI": 2,
- "GOPHERLICIOUS": 3,
-}
-
-func (x Request_Flavour) String() string {
- return proto.EnumName(Request_Flavour_name, int32(x))
-}
-func (Request_Flavour) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_proto3_a752e09251f17e01, []int{0, 0}
-}
-
-type Request struct {
- Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Key []int64 `protobuf:"varint,2,rep,packed,name=key" json:"key,omitempty"`
- Taste Request_Flavour `protobuf:"varint,3,opt,name=taste,enum=proto3.Request_Flavour" json:"taste,omitempty"`
- Book *Book `protobuf:"bytes,4,opt,name=book" json:"book,omitempty"`
- Unpacked []int64 `protobuf:"varint,5,rep,name=unpacked" json:"unpacked,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Request) Reset() { *m = Request{} }
-func (m *Request) String() string { return proto.CompactTextString(m) }
-func (*Request) ProtoMessage() {}
-func (*Request) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_a752e09251f17e01, []int{0}
-}
-func (m *Request) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Request.Unmarshal(m, b)
-}
-func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Request.Marshal(b, m, deterministic)
-}
-func (dst *Request) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Request.Merge(dst, src)
-}
-func (m *Request) XXX_Size() int {
- return xxx_messageInfo_Request.Size(m)
-}
-func (m *Request) XXX_DiscardUnknown() {
- xxx_messageInfo_Request.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Request proto.InternalMessageInfo
-
-func (m *Request) GetName() string {
- if m != nil {
- return m.Name
- }
- return ""
-}
-
-func (m *Request) GetKey() []int64 {
- if m != nil {
- return m.Key
- }
- return nil
-}
-
-func (m *Request) GetTaste() Request_Flavour {
- if m != nil {
- return m.Taste
- }
- return Request_SWEET
-}
-
-func (m *Request) GetBook() *Book {
- if m != nil {
- return m.Book
- }
- return nil
-}
-
-func (m *Request) GetUnpacked() []int64 {
- if m != nil {
- return m.Unpacked
- }
- return nil
-}
-
-type Book struct {
- Title string `protobuf:"bytes,1,opt,name=title" json:"title,omitempty"`
- RawData []byte `protobuf:"bytes,2,opt,name=raw_data,json=rawData,proto3" json:"raw_data,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Book) Reset() { *m = Book{} }
-func (m *Book) String() string { return proto.CompactTextString(m) }
-func (*Book) ProtoMessage() {}
-func (*Book) Descriptor() ([]byte, []int) {
- return fileDescriptor_proto3_a752e09251f17e01, []int{1}
-}
-func (m *Book) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Book.Unmarshal(m, b)
-}
-func (m *Book) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Book.Marshal(b, m, deterministic)
-}
-func (dst *Book) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Book.Merge(dst, src)
-}
-func (m *Book) XXX_Size() int {
- return xxx_messageInfo_Book.Size(m)
-}
-func (m *Book) XXX_DiscardUnknown() {
- xxx_messageInfo_Book.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Book proto.InternalMessageInfo
-
-func (m *Book) GetTitle() string {
- if m != nil {
- return m.Title
- }
- return ""
-}
-
-func (m *Book) GetRawData() []byte {
- if m != nil {
- return m.RawData
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*Request)(nil), "proto3.Request")
- proto.RegisterType((*Book)(nil), "proto3.Book")
- proto.RegisterEnum("proto3.Request_Flavour", Request_Flavour_name, Request_Flavour_value)
-}
-
-func init() { proto.RegisterFile("proto3/proto3.proto", fileDescriptor_proto3_a752e09251f17e01) }
-
-var fileDescriptor_proto3_a752e09251f17e01 = []byte{
- // 306 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x3c, 0x90, 0xcf, 0x4e, 0xf2, 0x40,
- 0x14, 0xc5, 0x99, 0xfe, 0xf9, 0x80, 0xfb, 0xa1, 0x19, 0xaf, 0x26, 0x8e, 0x1b, 0x33, 0x61, 0xd5,
- 0x0d, 0x25, 0xc1, 0x85, 0xc6, 0xb8, 0x11, 0x45, 0x25, 0x91, 0x60, 0x06, 0x89, 0x89, 0x1b, 0x33,
- 0x85, 0xb1, 0x92, 0x42, 0x07, 0xcb, 0x54, 0xe2, 0xcb, 0xfa, 0x2c, 0xa6, 0x9d, 0xe2, 0xea, 0x9e,
- 0x7b, 0xe7, 0xe4, 0x77, 0x32, 0x07, 0x0e, 0xd7, 0x99, 0x36, 0xfa, 0xac, 0x6b, 0x47, 0x58, 0x0e,
- 0xfc, 0x67, 0xb7, 0xf6, 0x0f, 0x81, 0xba, 0x50, 0x9f, 0xb9, 0xda, 0x18, 0x44, 0xf0, 0x52, 0xb9,
- 0x52, 0x8c, 0x70, 0x12, 0x34, 0x45, 0xa9, 0x91, 0x82, 0x9b, 0xa8, 0x6f, 0xe6, 0x70, 0x37, 0x70,
- 0x45, 0x21, 0xb1, 0x03, 0xbe, 0x91, 0x1b, 0xa3, 0x98, 0xcb, 0x49, 0xb0, 0xdf, 0x3b, 0x0e, 0x2b,
- 0x6e, 0x45, 0x09, 0xef, 0x96, 0xf2, 0x4b, 0xe7, 0x99, 0xb0, 0x2e, 0xe4, 0xe0, 0x45, 0x5a, 0x27,
- 0xcc, 0xe3, 0x24, 0xf8, 0xdf, 0x6b, 0xed, 0xdc, 0x7d, 0xad, 0x13, 0x51, 0xbe, 0xe0, 0x29, 0x34,
- 0xf2, 0x74, 0x2d, 0x67, 0x89, 0x9a, 0x33, 0xbf, 0xc8, 0xe9, 0x3b, 0xb4, 0x26, 0xfe, 0x6e, 0xed,
- 0x2b, 0xa8, 0x57, 0x4c, 0x6c, 0x82, 0x3f, 0x79, 0x19, 0x0c, 0x9e, 0x69, 0x0d, 0x1b, 0xe0, 0x4d,
- 0xc6, 0x53, 0x41, 0x49, 0x71, 0x9c, 0x8e, 0xae, 0x47, 0x43, 0xea, 0xe0, 0x01, 0xec, 0xdd, 0x8f,
- 0x9f, 0x1e, 0x06, 0xe2, 0x71, 0x78, 0x33, 0x1c, 0x4f, 0x27, 0xd4, 0x6d, 0x9f, 0x83, 0x57, 0x64,
- 0xe1, 0x11, 0xf8, 0x66, 0x61, 0x96, 0xbb, 0xdf, 0xd9, 0x05, 0x4f, 0xa0, 0x91, 0xc9, 0xed, 0xdb,
- 0x5c, 0x1a, 0xc9, 0x1c, 0x4e, 0x82, 0x96, 0xa8, 0x67, 0x72, 0x7b, 0x2b, 0x8d, 0xec, 0x5f, 0xbe,
- 0x5e, 0xc4, 0x0b, 0xf3, 0x91, 0x47, 0xe1, 0x4c, 0xaf, 0xba, 0xb1, 0x5e, 0xca, 0x34, 0xb6, 0x1d,
- 0x46, 0xf9, 0xbb, 0x15, 0xb3, 0x4e, 0xac, 0xd2, 0x4e, 0xac, 0xbb, 0x46, 0x6d, 0x4c, 0xc1, 0xa8,
- 0x3a, 0x8e, 0xaa, 0x76, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xec, 0x71, 0xee, 0xdb, 0x7b, 0x01,
- 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto
deleted file mode 100644
index 79954e4e2..000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto
+++ /dev/null
@@ -1,55 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package proto3;
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/proto3";
-
-message Request {
- enum Flavour {
- SWEET = 0;
- SOUR = 1;
- UMAMI = 2;
- GOPHERLICIOUS = 3;
- }
- string name = 1;
- repeated int64 key = 2;
- Flavour taste = 3;
- Book book = 4;
- repeated int64 unpacked = 5 [packed=false];
-}
-
-message Book {
- string title = 1;
- bytes raw_data = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go
index 70276e8f5..e729dcff1 100644
--- a/vendor/github.com/golang/protobuf/ptypes/any.go
+++ b/vendor/github.com/golang/protobuf/ptypes/any.go
@@ -1,141 +1,165 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package ptypes
-// This file implements functions to marshal proto.Message to/from
-// google.protobuf.Any message.
-
import (
"fmt"
- "reflect"
"strings"
"github.com/golang/protobuf/proto"
- "github.com/golang/protobuf/ptypes/any"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+
+ anypb "github.com/golang/protobuf/ptypes/any"
)
-const googleApis = "type.googleapis.com/"
+const urlPrefix = "type.googleapis.com/"
-// AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
-//
-// Note that regular type assertions should be done using the Is
-// function. AnyMessageName is provided for less common use cases like filtering a
-// sequence of Any messages based on a set of allowed message type names.
-func AnyMessageName(any *any.Any) (string, error) {
+// AnyMessageName returns the message name contained in an anypb.Any message.
+// Most type assertions should use the Is function instead.
+func AnyMessageName(any *anypb.Any) (string, error) {
+ name, err := anyMessageName(any)
+ return string(name), err
+}
+func anyMessageName(any *anypb.Any) (protoreflect.FullName, error) {
if any == nil {
return "", fmt.Errorf("message is nil")
}
- slash := strings.LastIndex(any.TypeUrl, "/")
- if slash < 0 {
+ name := protoreflect.FullName(any.TypeUrl)
+ if i := strings.LastIndex(any.TypeUrl, "/"); i >= 0 {
+ name = name[i+len("/"):]
+ }
+ if !name.IsValid() {
return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
}
- return any.TypeUrl[slash+1:], nil
+ return name, nil
}
-// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
-func MarshalAny(pb proto.Message) (*any.Any, error) {
- value, err := proto.Marshal(pb)
+// MarshalAny marshals the given message m into an anypb.Any message.
+func MarshalAny(m proto.Message) (*anypb.Any, error) {
+ switch dm := m.(type) {
+ case DynamicAny:
+ m = dm.Message
+ case *DynamicAny:
+ if dm == nil {
+ return nil, proto.ErrNil
+ }
+ m = dm.Message
+ }
+ b, err := proto.Marshal(m)
if err != nil {
return nil, err
}
- return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
-}
-
-// DynamicAny is a value that can be passed to UnmarshalAny to automatically
-// allocate a proto.Message for the type specified in a google.protobuf.Any
-// message. The allocated message is stored in the embedded proto.Message.
-//
-// Example:
-//
-// var x ptypes.DynamicAny
-// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
-// fmt.Printf("unmarshaled message: %v", x.Message)
-type DynamicAny struct {
- proto.Message
+ return &anypb.Any{TypeUrl: urlPrefix + proto.MessageName(m), Value: b}, nil
}
-// Empty returns a new proto.Message of the type specified in a
-// google.protobuf.Any message. It returns an error if corresponding message
-// type isn't linked in.
-func Empty(any *any.Any) (proto.Message, error) {
- aname, err := AnyMessageName(any)
+// Empty returns a new message of the type specified in an anypb.Any message.
+// It returns protoregistry.NotFound if the corresponding message type could not
+// be resolved in the global registry.
+func Empty(any *anypb.Any) (proto.Message, error) {
+ name, err := anyMessageName(any)
if err != nil {
return nil, err
}
-
- t := proto.MessageType(aname)
- if t == nil {
- return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
+ mt, err := protoregistry.GlobalTypes.FindMessageByName(name)
+ if err != nil {
+ return nil, err
}
- return reflect.New(t.Elem()).Interface().(proto.Message), nil
+ return proto.MessageV1(mt.New().Interface()), nil
}
-// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
-// message and places the decoded result in pb. It returns an error if type of
-// contents of Any message does not match type of pb message.
+// UnmarshalAny unmarshals the encoded value contained in the anypb.Any message
+// into the provided message m. It returns an error if the target message
+// does not match the type in the Any message or if an unmarshal error occurs.
//
-// pb can be a proto.Message, or a *DynamicAny.
-func UnmarshalAny(any *any.Any, pb proto.Message) error {
- if d, ok := pb.(*DynamicAny); ok {
- if d.Message == nil {
+// The target message m may be a *DynamicAny message. If the underlying message
+// type could not be resolved, then this returns protoregistry.NotFound.
+func UnmarshalAny(any *anypb.Any, m proto.Message) error {
+ if dm, ok := m.(*DynamicAny); ok {
+ if dm.Message == nil {
var err error
- d.Message, err = Empty(any)
+ dm.Message, err = Empty(any)
if err != nil {
return err
}
}
- return UnmarshalAny(any, d.Message)
+ m = dm.Message
}
- aname, err := AnyMessageName(any)
+ anyName, err := AnyMessageName(any)
if err != nil {
return err
}
-
- mname := proto.MessageName(pb)
- if aname != mname {
- return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
+ msgName := proto.MessageName(m)
+ if anyName != msgName {
+ return fmt.Errorf("mismatched message type: got %q want %q", anyName, msgName)
}
- return proto.Unmarshal(any.Value, pb)
+ return proto.Unmarshal(any.Value, m)
}
-// Is returns true if any value contains a given message type.
-func Is(any *any.Any, pb proto.Message) bool {
- // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb),
- // but it avoids scanning TypeUrl for the slash.
- if any == nil {
+// Is reports whether the Any message contains a message of the specified type.
+func Is(any *anypb.Any, m proto.Message) bool {
+ if any == nil || m == nil {
return false
}
- name := proto.MessageName(pb)
- prefix := len(any.TypeUrl) - len(name)
- return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name
+ name := proto.MessageName(m)
+ if !strings.HasSuffix(any.TypeUrl, name) {
+ return false
+ }
+ return len(any.TypeUrl) == len(name) || any.TypeUrl[len(any.TypeUrl)-len(name)-1] == '/'
+}
+
+// DynamicAny is a value that can be passed to UnmarshalAny to automatically
+// allocate a proto.Message for the type specified in an anypb.Any message.
+// The allocated message is stored in the embedded proto.Message.
+//
+// Example:
+// var x ptypes.DynamicAny
+// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
+// fmt.Printf("unmarshaled message: %v", x.Message)
+type DynamicAny struct{ proto.Message }
+
+func (m DynamicAny) String() string {
+ if m.Message == nil {
+ return ""
+ }
+ return m.Message.String()
+}
+func (m DynamicAny) Reset() {
+ if m.Message == nil {
+ return
+ }
+ m.Message.Reset()
+}
+func (m DynamicAny) ProtoMessage() {
+ return
+}
+func (m DynamicAny) ProtoReflect() protoreflect.Message {
+ if m.Message == nil {
+ return nil
+ }
+ return dynamicAny{proto.MessageReflect(m.Message)}
+}
+
+type dynamicAny struct{ protoreflect.Message }
+
+func (m dynamicAny) Type() protoreflect.MessageType {
+ return dynamicAnyType{m.Message.Type()}
+}
+func (m dynamicAny) New() protoreflect.Message {
+ return dynamicAnyType{m.Message.Type()}.New()
+}
+func (m dynamicAny) Interface() protoreflect.ProtoMessage {
+ return DynamicAny{proto.MessageV1(m.Message.Interface())}
+}
+
+type dynamicAnyType struct{ protoreflect.MessageType }
+
+func (t dynamicAnyType) New() protoreflect.Message {
+ return dynamicAny{t.MessageType.New()}
+}
+func (t dynamicAnyType) Zero() protoreflect.Message {
+ return dynamicAny{t.MessageType.Zero()}
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
index f67edc7dc..0ef27d33d 100644
--- a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
+++ b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
@@ -1,191 +1,62 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/any.proto
+// source: github.com/golang/protobuf/ptypes/any/any.proto
-package any // import "github.com/golang/protobuf/ptypes/any"
+package any
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ anypb "google.golang.org/protobuf/types/known/anypb"
+ reflect "reflect"
+)
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
+// Symbols defined in public import of google/protobuf/any.proto.
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+type Any = anypb.Any
-// `Any` contains an arbitrary serialized protocol buffer message along with a
-// URL that describes the type of the serialized message.
-//
-// Protobuf library provides support to pack/unpack Any values in the form
-// of utility functions or additional generated methods of the Any type.
-//
-// Example 1: Pack and unpack a message in C++.
-//
-// Foo foo = ...;
-// Any any;
-// any.PackFrom(foo);
-// ...
-// if (any.UnpackTo(&foo)) {
-// ...
-// }
-//
-// Example 2: Pack and unpack a message in Java.
-//
-// Foo foo = ...;
-// Any any = Any.pack(foo);
-// ...
-// if (any.is(Foo.class)) {
-// foo = any.unpack(Foo.class);
-// }
-//
-// Example 3: Pack and unpack a message in Python.
-//
-// foo = Foo(...)
-// any = Any()
-// any.Pack(foo)
-// ...
-// if any.Is(Foo.DESCRIPTOR):
-// any.Unpack(foo)
-// ...
-//
-// Example 4: Pack and unpack a message in Go
-//
-// foo := &pb.Foo{...}
-// any, err := ptypes.MarshalAny(foo)
-// ...
-// foo := &pb.Foo{}
-// if err := ptypes.UnmarshalAny(any, foo); err != nil {
-// ...
-// }
-//
-// The pack methods provided by protobuf library will by default use
-// 'type.googleapis.com/full.type.name' as the type URL and the unpack
-// methods only use the fully qualified type name after the last '/'
-// in the type URL, for example "foo.bar.com/x/y.z" will yield type
-// name "y.z".
-//
-//
-// JSON
-// ====
-// The JSON representation of an `Any` value uses the regular
-// representation of the deserialized, embedded message, with an
-// additional field `@type` which contains the type URL. Example:
-//
-// package google.profile;
-// message Person {
-// string first_name = 1;
-// string last_name = 2;
-// }
-//
-// {
-// "@type": "type.googleapis.com/google.profile.Person",
-// "firstName": ,
-// "lastName":
-// }
-//
-// If the embedded message type is well-known and has a custom JSON
-// representation, that representation will be embedded adding a field
-// `value` which holds the custom JSON in addition to the `@type`
-// field. Example (for message [google.protobuf.Duration][]):
-//
-// {
-// "@type": "type.googleapis.com/google.protobuf.Duration",
-// "value": "1.212s"
-// }
-//
-type Any struct {
- // A URL/resource name whose content describes the type of the
- // serialized protocol buffer message.
- //
- // For URLs which use the scheme `http`, `https`, or no scheme, the
- // following restrictions and interpretations apply:
- //
- // * If no scheme is provided, `https` is assumed.
- // * The last segment of the URL's path must represent the fully
- // qualified name of the type (as in `path/google.protobuf.Duration`).
- // The name should be in a canonical form (e.g., leading "." is
- // not accepted).
- // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
- // value in binary format, or produce an error.
- // * Applications are allowed to cache lookup results based on the
- // URL, or have them precompiled into a binary to avoid any
- // lookup. Therefore, binary compatibility needs to be preserved
- // on changes to types. (Use versioned type names to manage
- // breaking changes.)
- //
- // Schemes other than `http`, `https` (or the empty scheme) might be
- // used with implementation specific semantics.
- //
- TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"`
- // Must be a valid serialized protocol buffer of the above specified type.
- Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
+var File_github_com_golang_protobuf_ptypes_any_any_proto protoreflect.FileDescriptor
-func (m *Any) Reset() { *m = Any{} }
-func (m *Any) String() string { return proto.CompactTextString(m) }
-func (*Any) ProtoMessage() {}
-func (*Any) Descriptor() ([]byte, []int) {
- return fileDescriptor_any_744b9ca530f228db, []int{0}
-}
-func (*Any) XXX_WellKnownType() string { return "Any" }
-func (m *Any) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Any.Unmarshal(m, b)
-}
-func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Any.Marshal(b, m, deterministic)
-}
-func (dst *Any) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Any.Merge(dst, src)
+var file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = []byte{
+ 0x0a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74,
+ 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
+ 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x2b, 0x5a, 0x29,
+ 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e,
+ 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65,
+ 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x3b, 0x61, 0x6e, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x33,
}
-func (m *Any) XXX_Size() int {
- return xxx_messageInfo_Any.Size(m)
-}
-func (m *Any) XXX_DiscardUnknown() {
- xxx_messageInfo_Any.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Any proto.InternalMessageInfo
-func (m *Any) GetTypeUrl() string {
- if m != nil {
- return m.TypeUrl
- }
- return ""
+var file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
}
-func (m *Any) GetValue() []byte {
- if m != nil {
- return m.Value
+func init() { file_github_com_golang_protobuf_ptypes_any_any_proto_init() }
+func file_github_com_golang_protobuf_ptypes_any_any_proto_init() {
+ if File_github_com_golang_protobuf_ptypes_any_any_proto != nil {
+ return
}
- return nil
-}
-
-func init() {
- proto.RegisterType((*Any)(nil), "google.protobuf.Any")
-}
-
-func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_any_744b9ca530f228db) }
-
-var fileDescriptor_any_744b9ca530f228db = []byte{
- // 185 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4,
- 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a,
- 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46,
- 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7,
- 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce,
- 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52,
- 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc,
- 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c,
- 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce,
- 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff,
- 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00,
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_ptypes_any_any_proto = out.File
+ file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = nil
+ file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = nil
+ file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto
deleted file mode 100644
index c74866762..000000000
--- a/vendor/github.com/golang/protobuf/ptypes/any/any.proto
+++ /dev/null
@@ -1,149 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option go_package = "github.com/golang/protobuf/ptypes/any";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "AnyProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// `Any` contains an arbitrary serialized protocol buffer message along with a
-// URL that describes the type of the serialized message.
-//
-// Protobuf library provides support to pack/unpack Any values in the form
-// of utility functions or additional generated methods of the Any type.
-//
-// Example 1: Pack and unpack a message in C++.
-//
-// Foo foo = ...;
-// Any any;
-// any.PackFrom(foo);
-// ...
-// if (any.UnpackTo(&foo)) {
-// ...
-// }
-//
-// Example 2: Pack and unpack a message in Java.
-//
-// Foo foo = ...;
-// Any any = Any.pack(foo);
-// ...
-// if (any.is(Foo.class)) {
-// foo = any.unpack(Foo.class);
-// }
-//
-// Example 3: Pack and unpack a message in Python.
-//
-// foo = Foo(...)
-// any = Any()
-// any.Pack(foo)
-// ...
-// if any.Is(Foo.DESCRIPTOR):
-// any.Unpack(foo)
-// ...
-//
-// Example 4: Pack and unpack a message in Go
-//
-// foo := &pb.Foo{...}
-// any, err := ptypes.MarshalAny(foo)
-// ...
-// foo := &pb.Foo{}
-// if err := ptypes.UnmarshalAny(any, foo); err != nil {
-// ...
-// }
-//
-// The pack methods provided by protobuf library will by default use
-// 'type.googleapis.com/full.type.name' as the type URL and the unpack
-// methods only use the fully qualified type name after the last '/'
-// in the type URL, for example "foo.bar.com/x/y.z" will yield type
-// name "y.z".
-//
-//
-// JSON
-// ====
-// The JSON representation of an `Any` value uses the regular
-// representation of the deserialized, embedded message, with an
-// additional field `@type` which contains the type URL. Example:
-//
-// package google.profile;
-// message Person {
-// string first_name = 1;
-// string last_name = 2;
-// }
-//
-// {
-// "@type": "type.googleapis.com/google.profile.Person",
-// "firstName": ,
-// "lastName":
-// }
-//
-// If the embedded message type is well-known and has a custom JSON
-// representation, that representation will be embedded adding a field
-// `value` which holds the custom JSON in addition to the `@type`
-// field. Example (for message [google.protobuf.Duration][]):
-//
-// {
-// "@type": "type.googleapis.com/google.protobuf.Duration",
-// "value": "1.212s"
-// }
-//
-message Any {
- // A URL/resource name whose content describes the type of the
- // serialized protocol buffer message.
- //
- // For URLs which use the scheme `http`, `https`, or no scheme, the
- // following restrictions and interpretations apply:
- //
- // * If no scheme is provided, `https` is assumed.
- // * The last segment of the URL's path must represent the fully
- // qualified name of the type (as in `path/google.protobuf.Duration`).
- // The name should be in a canonical form (e.g., leading "." is
- // not accepted).
- // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
- // value in binary format, or produce an error.
- // * Applications are allowed to cache lookup results based on the
- // URL, or have them precompiled into a binary to avoid any
- // lookup. Therefore, binary compatibility needs to be preserved
- // on changes to types. (Use versioned type names to manage
- // breaking changes.)
- //
- // Schemes other than `http`, `https` (or the empty scheme) might be
- // used with implementation specific semantics.
- //
- string type_url = 1;
-
- // Must be a valid serialized protocol buffer of the above specified type.
- bytes value = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any_test.go b/vendor/github.com/golang/protobuf/ptypes/any_test.go
index 163ca312b..c865e1ca5 100644
--- a/vendor/github.com/golang/protobuf/ptypes/any_test.go
+++ b/vendor/github.com/golang/protobuf/ptypes/any_test.go
@@ -1,53 +1,28 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package ptypes
import (
+ "reflect"
"testing"
"github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
- "github.com/golang/protobuf/ptypes/any"
+
+ descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
+ anypb "github.com/golang/protobuf/ptypes/any"
)
func TestMarshalUnmarshal(t *testing.T) {
- orig := &any.Any{Value: []byte("test")}
+ orig := &anypb.Any{Value: []byte("test")}
packed, err := MarshalAny(orig)
if err != nil {
t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err)
}
- unpacked := &any.Any{}
+ unpacked := &anypb.Any{}
err = UnmarshalAny(packed, unpacked)
if err != nil || !proto.Equal(unpacked, orig) {
t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig)
@@ -55,49 +30,48 @@ func TestMarshalUnmarshal(t *testing.T) {
}
func TestIs(t *testing.T) {
- a, err := MarshalAny(&pb.FileDescriptorProto{})
+ a, err := MarshalAny(&descriptorpb.FileDescriptorProto{})
if err != nil {
t.Fatal(err)
}
- if Is(a, &pb.DescriptorProto{}) {
+ if Is(a, &descriptorpb.DescriptorProto{}) {
// No spurious match for message names of different length.
t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is")
}
- if Is(a, &pb.EnumDescriptorProto{}) {
+ if Is(a, &descriptorpb.EnumDescriptorProto{}) {
// No spurious match for message names of equal length.
t.Error("FileDescriptorProto is not an EnumDescriptorProto, but Is says it is")
}
- if !Is(a, &pb.FileDescriptorProto{}) {
+ if !Is(a, &descriptorpb.FileDescriptorProto{}) {
t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not")
}
}
func TestIsDifferentUrlPrefixes(t *testing.T) {
- m := &pb.FileDescriptorProto{}
- a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)}
+ m := &descriptorpb.FileDescriptorProto{}
+ a := &anypb.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)}
if !Is(a, m) {
t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m))
}
}
-
func TestIsCornerCases(t *testing.T) {
- m := &pb.FileDescriptorProto{}
+ m := &descriptorpb.FileDescriptorProto{}
if Is(nil, m) {
t.Errorf("message with nil type url incorrectly claimed to be %q", proto.MessageName(m))
}
- noPrefix := &any.Any{TypeUrl: proto.MessageName(m)}
- if Is(noPrefix, m) {
- t.Errorf("message with type url %q incorrectly claimed to be %q", noPrefix.TypeUrl, proto.MessageName(m))
+ noPrefix := &anypb.Any{TypeUrl: proto.MessageName(m)}
+ if !Is(noPrefix, m) {
+ t.Errorf("message with type url %q didn't satisfy Is for type %q", noPrefix.TypeUrl, proto.MessageName(m))
}
- shortPrefix := &any.Any{TypeUrl: "/" + proto.MessageName(m)}
+ shortPrefix := &anypb.Any{TypeUrl: "/" + proto.MessageName(m)}
if !Is(shortPrefix, m) {
t.Errorf("message with type url %q didn't satisfy Is for type %q", shortPrefix.TypeUrl, proto.MessageName(m))
}
}
func TestUnmarshalDynamic(t *testing.T) {
- want := &pb.FileDescriptorProto{Name: proto.String("foo")}
+ want := &descriptorpb.FileDescriptorProto{Name: proto.String("foo")}
a, err := MarshalAny(want)
if err != nil {
t.Fatal(err)
@@ -112,7 +86,7 @@ func TestUnmarshalDynamic(t *testing.T) {
}
func TestEmpty(t *testing.T) {
- want := &pb.FileDescriptorProto{}
+ want := &descriptorpb.FileDescriptorProto{}
a, err := MarshalAny(want)
if err != nil {
t.Fatal(err)
@@ -138,14 +112,17 @@ func TestEmptyCornerCases(t *testing.T) {
if err == nil {
t.Error("expected Empty for nil to fail")
}
- want := &pb.FileDescriptorProto{}
- noPrefix := &any.Any{TypeUrl: proto.MessageName(want)}
- _, err = Empty(noPrefix)
- if err == nil {
- t.Errorf("expected Empty for any type %q to fail", noPrefix.TypeUrl)
+ want := &descriptorpb.FileDescriptorProto{}
+ noPrefix := &anypb.Any{TypeUrl: proto.MessageName(want)}
+ got, err := Empty(noPrefix)
+ if err != nil {
+ t.Errorf("Empty for any type %q failed: %s", noPrefix.TypeUrl, err)
+ }
+ if !proto.Equal(got, want) {
+ t.Errorf("Empty for any type %q differs, got %q, want %q", noPrefix.TypeUrl, got, want)
}
- shortPrefix := &any.Any{TypeUrl: "/" + proto.MessageName(want)}
- got, err := Empty(shortPrefix)
+ shortPrefix := &anypb.Any{TypeUrl: "/" + proto.MessageName(want)}
+ got, err = Empty(shortPrefix)
if err != nil {
t.Errorf("Empty for any type %q failed: %s", shortPrefix.TypeUrl, err)
}
@@ -153,3 +130,37 @@ func TestEmptyCornerCases(t *testing.T) {
t.Errorf("Empty for any type %q differs, got %q, want %q", shortPrefix.TypeUrl, got, want)
}
}
+
+func TestAnyReflect(t *testing.T) {
+ want := &descriptorpb.FileDescriptorProto{Name: proto.String("foo")}
+ a, err := MarshalAny(want)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got DynamicAny
+ if err := UnmarshalAny(a, &got); err != nil {
+ t.Fatal(err)
+ }
+ wantName := want.ProtoReflect().Descriptor().FullName()
+ gotName := got.ProtoReflect().Descriptor().FullName()
+ if gotName != wantName {
+ t.Errorf("name mismatch: got %v, want %v", gotName, wantName)
+ }
+ wantType := reflect.TypeOf(got)
+ gotType := reflect.TypeOf(got.ProtoReflect().Interface())
+ if gotType != wantType {
+ t.Errorf("ProtoReflect().Interface() round-trip type mismatch: got %v, want %v", gotType, wantType)
+ }
+ gotType = reflect.TypeOf(got.ProtoReflect().New().Interface())
+ if gotType != wantType {
+ t.Errorf("ProtoReflect().New().Interface() type mismatch: got %v, want %v", gotType, wantType)
+ }
+ gotType = reflect.TypeOf(got.ProtoReflect().Type().New().Interface())
+ if gotType != wantType {
+ t.Errorf("ProtoReflect().Type().New().Interface() type mismatch: got %v, want %v", gotType, wantType)
+ }
+ gotType = reflect.TypeOf(got.ProtoReflect().Type().Zero().Interface())
+ if gotType != wantType {
+ t.Errorf("ProtoReflect().Type().Zero().Interface() type mismatch: got %v, want %v", gotType, wantType)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go
index c0d595da7..fb9edd5c6 100644
--- a/vendor/github.com/golang/protobuf/ptypes/doc.go
+++ b/vendor/github.com/golang/protobuf/ptypes/doc.go
@@ -1,35 +1,6 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
-/*
-Package ptypes contains code for interacting with well-known types.
-*/
+// Package ptypes provides functionality for interacting with well-known types.
package ptypes
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go
index 65cb0f8eb..6110ae8a4 100644
--- a/vendor/github.com/golang/protobuf/ptypes/duration.go
+++ b/vendor/github.com/golang/protobuf/ptypes/duration.go
@@ -1,102 +1,72 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package ptypes
-// This file implements conversions between google.protobuf.Duration
-// and time.Duration.
-
import (
"errors"
"fmt"
"time"
- durpb "github.com/golang/protobuf/ptypes/duration"
+ durationpb "github.com/golang/protobuf/ptypes/duration"
)
+// Range of google.protobuf.Duration as specified in duration.proto.
+// This is about 10,000 years in seconds.
const (
- // Range of a durpb.Duration in seconds, as specified in
- // google/protobuf/duration.proto. This is about 10,000 years in seconds.
maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
minSeconds = -maxSeconds
)
-// validateDuration determines whether the durpb.Duration is valid according to the
-// definition in google/protobuf/duration.proto. A valid durpb.Duration
-// may still be too large to fit into a time.Duration (the range of durpb.Duration
-// is about 10,000 years, and the range of time.Duration is about 290).
-func validateDuration(d *durpb.Duration) error {
- if d == nil {
- return errors.New("duration: nil Duration")
- }
- if d.Seconds < minSeconds || d.Seconds > maxSeconds {
- return fmt.Errorf("duration: %v: seconds out of range", d)
- }
- if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
- return fmt.Errorf("duration: %v: nanos out of range", d)
- }
- // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
- if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
- return fmt.Errorf("duration: %v: seconds and nanos have different signs", d)
- }
- return nil
-}
-
-// Duration converts a durpb.Duration to a time.Duration. Duration
-// returns an error if the durpb.Duration is invalid or is too large to be
-// represented in a time.Duration.
-func Duration(p *durpb.Duration) (time.Duration, error) {
- if err := validateDuration(p); err != nil {
+// Duration converts a durationpb.Duration to a time.Duration.
+// Duration returns an error if dur is invalid or overflows a time.Duration.
+func Duration(dur *durationpb.Duration) (time.Duration, error) {
+ if err := validateDuration(dur); err != nil {
return 0, err
}
- d := time.Duration(p.Seconds) * time.Second
- if int64(d/time.Second) != p.Seconds {
- return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
+ d := time.Duration(dur.Seconds) * time.Second
+ if int64(d/time.Second) != dur.Seconds {
+ return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
}
- if p.Nanos != 0 {
- d += time.Duration(p.Nanos)
- if (d < 0) != (p.Nanos < 0) {
- return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
+ if dur.Nanos != 0 {
+ d += time.Duration(dur.Nanos) * time.Nanosecond
+ if (d < 0) != (dur.Nanos < 0) {
+ return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur)
}
}
return d, nil
}
-// DurationProto converts a time.Duration to a durpb.Duration.
-func DurationProto(d time.Duration) *durpb.Duration {
+// DurationProto converts a time.Duration to a durationpb.Duration.
+func DurationProto(d time.Duration) *durationpb.Duration {
nanos := d.Nanoseconds()
secs := nanos / 1e9
nanos -= secs * 1e9
- return &durpb.Duration{
- Seconds: secs,
+ return &durationpb.Duration{
+ Seconds: int64(secs),
Nanos: int32(nanos),
}
}
+
+// validateDuration determines whether the durationpb.Duration is valid
+// according to the definition in google/protobuf/duration.proto.
+// A valid durpb.Duration may still be too large to fit into a time.Duration
+// Note that the range of durationpb.Duration is about 10,000 years,
+// while the range of time.Duration is about 290 years.
+func validateDuration(dur *durationpb.Duration) error {
+ if dur == nil {
+ return errors.New("duration: nil Duration")
+ }
+ if dur.Seconds < minSeconds || dur.Seconds > maxSeconds {
+ return fmt.Errorf("duration: %v: seconds out of range", dur)
+ }
+ if dur.Nanos <= -1e9 || dur.Nanos >= 1e9 {
+ return fmt.Errorf("duration: %v: nanos out of range", dur)
+ }
+ // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
+ if (dur.Seconds < 0 && dur.Nanos > 0) || (dur.Seconds > 0 && dur.Nanos < 0) {
+ return fmt.Errorf("duration: %v: seconds and nanos have different signs", dur)
+ }
+ return nil
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
index 4d75473b8..d0079ee3e 100644
--- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
+++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
@@ -1,159 +1,63 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/duration.proto
+// source: github.com/golang/protobuf/ptypes/duration/duration.proto
-package duration // import "github.com/golang/protobuf/ptypes/duration"
+package duration
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ durationpb "google.golang.org/protobuf/types/known/durationpb"
+ reflect "reflect"
+)
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
+// Symbols defined in public import of google/protobuf/duration.proto.
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+type Duration = durationpb.Duration
-// A Duration represents a signed, fixed-length span of time represented
-// as a count of seconds and fractions of seconds at nanosecond
-// resolution. It is independent of any calendar and concepts like "day"
-// or "month". It is related to Timestamp in that the difference between
-// two Timestamp values is a Duration and it can be added or subtracted
-// from a Timestamp. Range is approximately +-10,000 years.
-//
-// # Examples
-//
-// Example 1: Compute Duration from two Timestamps in pseudo code.
-//
-// Timestamp start = ...;
-// Timestamp end = ...;
-// Duration duration = ...;
-//
-// duration.seconds = end.seconds - start.seconds;
-// duration.nanos = end.nanos - start.nanos;
-//
-// if (duration.seconds < 0 && duration.nanos > 0) {
-// duration.seconds += 1;
-// duration.nanos -= 1000000000;
-// } else if (durations.seconds > 0 && duration.nanos < 0) {
-// duration.seconds -= 1;
-// duration.nanos += 1000000000;
-// }
-//
-// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
-//
-// Timestamp start = ...;
-// Duration duration = ...;
-// Timestamp end = ...;
-//
-// end.seconds = start.seconds + duration.seconds;
-// end.nanos = start.nanos + duration.nanos;
-//
-// if (end.nanos < 0) {
-// end.seconds -= 1;
-// end.nanos += 1000000000;
-// } else if (end.nanos >= 1000000000) {
-// end.seconds += 1;
-// end.nanos -= 1000000000;
-// }
-//
-// Example 3: Compute Duration from datetime.timedelta in Python.
-//
-// td = datetime.timedelta(days=3, minutes=10)
-// duration = Duration()
-// duration.FromTimedelta(td)
-//
-// # JSON Mapping
-//
-// In JSON format, the Duration type is encoded as a string rather than an
-// object, where the string ends in the suffix "s" (indicating seconds) and
-// is preceded by the number of seconds, with nanoseconds expressed as
-// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
-// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
-// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
-// microsecond should be expressed in JSON format as "3.000001s".
-//
-//
-type Duration struct {
- // Signed seconds of the span of time. Must be from -315,576,000,000
- // to +315,576,000,000 inclusive. Note: these bounds are computed from:
- // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
- Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
- // Signed fractions of a second at nanosecond resolution of the span
- // of time. Durations less than one second are represented with a 0
- // `seconds` field and a positive or negative `nanos` field. For durations
- // of one second or more, a non-zero value for the `nanos` field must be
- // of the same sign as the `seconds` field. Must be from -999,999,999
- // to +999,999,999 inclusive.
- Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
+var File_github_com_golang_protobuf_ptypes_duration_duration_proto protoreflect.FileDescriptor
-func (m *Duration) Reset() { *m = Duration{} }
-func (m *Duration) String() string { return proto.CompactTextString(m) }
-func (*Duration) ProtoMessage() {}
-func (*Duration) Descriptor() ([]byte, []int) {
- return fileDescriptor_duration_e7d612259e3f0613, []int{0}
-}
-func (*Duration) XXX_WellKnownType() string { return "Duration" }
-func (m *Duration) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Duration.Unmarshal(m, b)
-}
-func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Duration.Marshal(b, m, deterministic)
-}
-func (dst *Duration) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Duration.Merge(dst, src)
+var file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = []byte{
+ 0x0a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x64, 0x75, 0x72,
+ 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f,
+ 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72,
+ 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x35, 0x5a, 0x33, 0x67,
+ 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67,
+ 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73,
+ 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69,
+ 0x6f, 0x6e, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
-func (m *Duration) XXX_Size() int {
- return xxx_messageInfo_Duration.Size(m)
-}
-func (m *Duration) XXX_DiscardUnknown() {
- xxx_messageInfo_Duration.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Duration proto.InternalMessageInfo
-func (m *Duration) GetSeconds() int64 {
- if m != nil {
- return m.Seconds
- }
- return 0
+var file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
}
-func (m *Duration) GetNanos() int32 {
- if m != nil {
- return m.Nanos
+func init() { file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() }
+func file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() {
+ if File_github_com_golang_protobuf_ptypes_duration_duration_proto != nil {
+ return
}
- return 0
-}
-
-func init() {
- proto.RegisterType((*Duration)(nil), "google.protobuf.Duration")
-}
-
-func init() {
- proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_duration_e7d612259e3f0613)
-}
-
-var fileDescriptor_duration_e7d612259e3f0613 = []byte{
- // 190 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a,
- 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56,
- 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5,
- 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e,
- 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c,
- 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56,
- 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e,
- 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4,
- 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78,
- 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63,
- 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00,
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_ptypes_duration_duration_proto = out.File
+ file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = nil
+ file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = nil
+ file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
deleted file mode 100644
index 975fce41a..000000000
--- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
+++ /dev/null
@@ -1,117 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option cc_enable_arenas = true;
-option go_package = "github.com/golang/protobuf/ptypes/duration";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "DurationProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// A Duration represents a signed, fixed-length span of time represented
-// as a count of seconds and fractions of seconds at nanosecond
-// resolution. It is independent of any calendar and concepts like "day"
-// or "month". It is related to Timestamp in that the difference between
-// two Timestamp values is a Duration and it can be added or subtracted
-// from a Timestamp. Range is approximately +-10,000 years.
-//
-// # Examples
-//
-// Example 1: Compute Duration from two Timestamps in pseudo code.
-//
-// Timestamp start = ...;
-// Timestamp end = ...;
-// Duration duration = ...;
-//
-// duration.seconds = end.seconds - start.seconds;
-// duration.nanos = end.nanos - start.nanos;
-//
-// if (duration.seconds < 0 && duration.nanos > 0) {
-// duration.seconds += 1;
-// duration.nanos -= 1000000000;
-// } else if (durations.seconds > 0 && duration.nanos < 0) {
-// duration.seconds -= 1;
-// duration.nanos += 1000000000;
-// }
-//
-// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
-//
-// Timestamp start = ...;
-// Duration duration = ...;
-// Timestamp end = ...;
-//
-// end.seconds = start.seconds + duration.seconds;
-// end.nanos = start.nanos + duration.nanos;
-//
-// if (end.nanos < 0) {
-// end.seconds -= 1;
-// end.nanos += 1000000000;
-// } else if (end.nanos >= 1000000000) {
-// end.seconds += 1;
-// end.nanos -= 1000000000;
-// }
-//
-// Example 3: Compute Duration from datetime.timedelta in Python.
-//
-// td = datetime.timedelta(days=3, minutes=10)
-// duration = Duration()
-// duration.FromTimedelta(td)
-//
-// # JSON Mapping
-//
-// In JSON format, the Duration type is encoded as a string rather than an
-// object, where the string ends in the suffix "s" (indicating seconds) and
-// is preceded by the number of seconds, with nanoseconds expressed as
-// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
-// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
-// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
-// microsecond should be expressed in JSON format as "3.000001s".
-//
-//
-message Duration {
-
- // Signed seconds of the span of time. Must be from -315,576,000,000
- // to +315,576,000,000 inclusive. Note: these bounds are computed from:
- // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
- int64 seconds = 1;
-
- // Signed fractions of a second at nanosecond resolution of the span
- // of time. Durations less than one second are represented with a 0
- // `seconds` field and a positive or negative `nanos` field. For durations
- // of one second or more, a non-zero value for the `nanos` field must be
- // of the same sign as the `seconds` field. Must be from -999,999,999
- // to +999,999,999 inclusive.
- int32 nanos = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration_test.go b/vendor/github.com/golang/protobuf/ptypes/duration_test.go
index e00491a34..b11827c2c 100644
--- a/vendor/github.com/golang/protobuf/ptypes/duration_test.go
+++ b/vendor/github.com/golang/protobuf/ptypes/duration_test.go
@@ -1,33 +1,6 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package ptypes
@@ -37,6 +10,7 @@ import (
"time"
"github.com/golang/protobuf/proto"
+
durpb "github.com/golang/protobuf/ptypes/duration"
)
diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
index a69b403ce..16686a655 100644
--- a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
+++ b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
@@ -1,79 +1,62 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/empty.proto
-
-package empty // import "github.com/golang/protobuf/ptypes/empty"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// A generic empty message that you can re-use to avoid defining duplicated
-// empty messages in your APIs. A typical example is to use it as the request
-// or the response type of an API method. For instance:
-//
-// service Foo {
-// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
-// }
-//
-// The JSON representation for `Empty` is empty JSON object `{}`.
-type Empty struct {
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Empty) Reset() { *m = Empty{} }
-func (m *Empty) String() string { return proto.CompactTextString(m) }
-func (*Empty) ProtoMessage() {}
-func (*Empty) Descriptor() ([]byte, []int) {
- return fileDescriptor_empty_39e6d6db0632e5b2, []int{0}
-}
-func (*Empty) XXX_WellKnownType() string { return "Empty" }
-func (m *Empty) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Empty.Unmarshal(m, b)
-}
-func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Empty.Marshal(b, m, deterministic)
-}
-func (dst *Empty) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Empty.Merge(dst, src)
-}
-func (m *Empty) XXX_Size() int {
- return xxx_messageInfo_Empty.Size(m)
-}
-func (m *Empty) XXX_DiscardUnknown() {
- xxx_messageInfo_Empty.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Empty proto.InternalMessageInfo
-
-func init() {
- proto.RegisterType((*Empty)(nil), "google.protobuf.Empty")
-}
-
-func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor_empty_39e6d6db0632e5b2) }
-
-var fileDescriptor_empty_39e6d6db0632e5b2 = []byte{
- // 148 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28,
- 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57,
- 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36,
- 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf,
- 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c,
- 0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10,
- 0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40,
- 0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6,
- 0xb7, 0x00, 0x00, 0x00,
+// source: github.com/golang/protobuf/ptypes/empty/empty.proto
+
+package empty
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ emptypb "google.golang.org/protobuf/types/known/emptypb"
+ reflect "reflect"
+)
+
+// Symbols defined in public import of google/protobuf/empty.proto.
+
+type Empty = emptypb.Empty
+
+var File_github_com_golang_protobuf_ptypes_empty_empty_proto protoreflect.FileDescriptor
+
+var file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = []byte{
+ 0x0a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e,
+ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d,
+ 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
+ 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x3b, 0x65, 0x6d,
+ 0x70, 0x74, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() }
+func file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() {
+ if File_github_com_golang_protobuf_ptypes_empty_empty_proto != nil {
+ return
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_ptypes_empty_empty_proto = out.File
+ file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = nil
+ file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = nil
+ file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto b/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto
deleted file mode 100644
index 03cacd233..000000000
--- a/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto
+++ /dev/null
@@ -1,52 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option go_package = "github.com/golang/protobuf/ptypes/empty";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "EmptyProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-option cc_enable_arenas = true;
-
-// A generic empty message that you can re-use to avoid defining duplicated
-// empty messages in your APIs. A typical example is to use it as the request
-// or the response type of an API method. For instance:
-//
-// service Foo {
-// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
-// }
-//
-// The JSON representation for `Empty` is empty JSON object `{}`.
-message Empty {}
diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go b/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
index 442c0e099..8d82abe21 100644
--- a/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
+++ b/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
@@ -1,440 +1,78 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/struct.proto
+// source: github.com/golang/protobuf/ptypes/struct/struct.proto
-package structpb // import "github.com/golang/protobuf/ptypes/struct"
+package structpb
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// `NullValue` is a singleton enumeration to represent the null value for the
-// `Value` type union.
-//
-// The JSON representation for `NullValue` is JSON `null`.
-type NullValue int32
-
-const (
- // Null value.
- NullValue_NULL_VALUE NullValue = 0
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ structpb "google.golang.org/protobuf/types/known/structpb"
+ reflect "reflect"
)
-var NullValue_name = map[int32]string{
- 0: "NULL_VALUE",
-}
-var NullValue_value = map[string]int32{
- "NULL_VALUE": 0,
-}
-
-func (x NullValue) String() string {
- return proto.EnumName(NullValue_name, int32(x))
-}
-func (NullValue) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_struct_3a5a94e0c7801b27, []int{0}
-}
-func (NullValue) XXX_WellKnownType() string { return "NullValue" }
-
-// `Struct` represents a structured data value, consisting of fields
-// which map to dynamically typed values. In some languages, `Struct`
-// might be supported by a native representation. For example, in
-// scripting languages like JS a struct is represented as an
-// object. The details of that representation are described together
-// with the proto support for the language.
-//
-// The JSON representation for `Struct` is JSON object.
-type Struct struct {
- // Unordered map of dynamically typed values.
- Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Struct) Reset() { *m = Struct{} }
-func (m *Struct) String() string { return proto.CompactTextString(m) }
-func (*Struct) ProtoMessage() {}
-func (*Struct) Descriptor() ([]byte, []int) {
- return fileDescriptor_struct_3a5a94e0c7801b27, []int{0}
-}
-func (*Struct) XXX_WellKnownType() string { return "Struct" }
-func (m *Struct) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Struct.Unmarshal(m, b)
-}
-func (m *Struct) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Struct.Marshal(b, m, deterministic)
-}
-func (dst *Struct) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Struct.Merge(dst, src)
-}
-func (m *Struct) XXX_Size() int {
- return xxx_messageInfo_Struct.Size(m)
-}
-func (m *Struct) XXX_DiscardUnknown() {
- xxx_messageInfo_Struct.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Struct proto.InternalMessageInfo
-
-func (m *Struct) GetFields() map[string]*Value {
- if m != nil {
- return m.Fields
- }
- return nil
-}
-
-// `Value` represents a dynamically typed value which can be either
-// null, a number, a string, a boolean, a recursive struct value, or a
-// list of values. A producer of value is expected to set one of that
-// variants, absence of any variant indicates an error.
-//
-// The JSON representation for `Value` is JSON value.
-type Value struct {
- // The kind of value.
- //
- // Types that are valid to be assigned to Kind:
- // *Value_NullValue
- // *Value_NumberValue
- // *Value_StringValue
- // *Value_BoolValue
- // *Value_StructValue
- // *Value_ListValue
- Kind isValue_Kind `protobuf_oneof:"kind"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Value) Reset() { *m = Value{} }
-func (m *Value) String() string { return proto.CompactTextString(m) }
-func (*Value) ProtoMessage() {}
-func (*Value) Descriptor() ([]byte, []int) {
- return fileDescriptor_struct_3a5a94e0c7801b27, []int{1}
-}
-func (*Value) XXX_WellKnownType() string { return "Value" }
-func (m *Value) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Value.Unmarshal(m, b)
-}
-func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Value.Marshal(b, m, deterministic)
-}
-func (dst *Value) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Value.Merge(dst, src)
-}
-func (m *Value) XXX_Size() int {
- return xxx_messageInfo_Value.Size(m)
-}
-func (m *Value) XXX_DiscardUnknown() {
- xxx_messageInfo_Value.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Value proto.InternalMessageInfo
-
-type isValue_Kind interface {
- isValue_Kind()
-}
-
-type Value_NullValue struct {
- NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"`
-}
-type Value_NumberValue struct {
- NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"`
-}
-type Value_StringValue struct {
- StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"`
-}
-type Value_BoolValue struct {
- BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"`
-}
-type Value_StructValue struct {
- StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"`
-}
-type Value_ListValue struct {
- ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"`
-}
-
-func (*Value_NullValue) isValue_Kind() {}
-func (*Value_NumberValue) isValue_Kind() {}
-func (*Value_StringValue) isValue_Kind() {}
-func (*Value_BoolValue) isValue_Kind() {}
-func (*Value_StructValue) isValue_Kind() {}
-func (*Value_ListValue) isValue_Kind() {}
-
-func (m *Value) GetKind() isValue_Kind {
- if m != nil {
- return m.Kind
- }
- return nil
-}
-
-func (m *Value) GetNullValue() NullValue {
- if x, ok := m.GetKind().(*Value_NullValue); ok {
- return x.NullValue
+// Symbols defined in public import of google/protobuf/struct.proto.
+
+type NullValue = structpb.NullValue
+
+const NullValue_NULL_VALUE = structpb.NullValue_NULL_VALUE
+
+var NullValue_name = structpb.NullValue_name
+var NullValue_value = structpb.NullValue_value
+
+type Struct = structpb.Struct
+type Value = structpb.Value
+type Value_NullValue = structpb.Value_NullValue
+type Value_NumberValue = structpb.Value_NumberValue
+type Value_StringValue = structpb.Value_StringValue
+type Value_BoolValue = structpb.Value_BoolValue
+type Value_StructValue = structpb.Value_StructValue
+type Value_ListValue = structpb.Value_ListValue
+type ListValue = structpb.ListValue
+
+var File_github_com_golang_protobuf_ptypes_struct_struct_proto protoreflect.FileDescriptor
+
+var file_github_com_golang_protobuf_ptypes_struct_struct_proto_rawDesc = []byte{
+ 0x0a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63,
+ 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f,
+ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e,
+ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x33, 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
+ 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
+ 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63,
+ 0x74, 0x3b, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x70, 0x62, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var file_github_com_golang_protobuf_ptypes_struct_struct_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_ptypes_struct_struct_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_github_com_golang_protobuf_ptypes_struct_struct_proto_init() }
+func file_github_com_golang_protobuf_ptypes_struct_struct_proto_init() {
+ if File_github_com_golang_protobuf_ptypes_struct_struct_proto != nil {
+ return
}
- return NullValue_NULL_VALUE
-}
-
-func (m *Value) GetNumberValue() float64 {
- if x, ok := m.GetKind().(*Value_NumberValue); ok {
- return x.NumberValue
- }
- return 0
-}
-
-func (m *Value) GetStringValue() string {
- if x, ok := m.GetKind().(*Value_StringValue); ok {
- return x.StringValue
- }
- return ""
-}
-
-func (m *Value) GetBoolValue() bool {
- if x, ok := m.GetKind().(*Value_BoolValue); ok {
- return x.BoolValue
- }
- return false
-}
-
-func (m *Value) GetStructValue() *Struct {
- if x, ok := m.GetKind().(*Value_StructValue); ok {
- return x.StructValue
- }
- return nil
-}
-
-func (m *Value) GetListValue() *ListValue {
- if x, ok := m.GetKind().(*Value_ListValue); ok {
- return x.ListValue
- }
- return nil
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{
- (*Value_NullValue)(nil),
- (*Value_NumberValue)(nil),
- (*Value_StringValue)(nil),
- (*Value_BoolValue)(nil),
- (*Value_StructValue)(nil),
- (*Value_ListValue)(nil),
- }
-}
-
-func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*Value)
- // kind
- switch x := m.Kind.(type) {
- case *Value_NullValue:
- b.EncodeVarint(1<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.NullValue))
- case *Value_NumberValue:
- b.EncodeVarint(2<<3 | proto.WireFixed64)
- b.EncodeFixed64(math.Float64bits(x.NumberValue))
- case *Value_StringValue:
- b.EncodeVarint(3<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.StringValue)
- case *Value_BoolValue:
- t := uint64(0)
- if x.BoolValue {
- t = 1
- }
- b.EncodeVarint(4<<3 | proto.WireVarint)
- b.EncodeVarint(t)
- case *Value_StructValue:
- b.EncodeVarint(5<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.StructValue); err != nil {
- return err
- }
- case *Value_ListValue:
- b.EncodeVarint(6<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.ListValue); err != nil {
- return err
- }
- case nil:
- default:
- return fmt.Errorf("Value.Kind has unexpected type %T", x)
- }
- return nil
-}
-
-func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*Value)
- switch tag {
- case 1: // kind.null_value
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Kind = &Value_NullValue{NullValue(x)}
- return true, err
- case 2: // kind.number_value
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Kind = &Value_NumberValue{math.Float64frombits(x)}
- return true, err
- case 3: // kind.string_value
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Kind = &Value_StringValue{x}
- return true, err
- case 4: // kind.bool_value
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Kind = &Value_BoolValue{x != 0}
- return true, err
- case 5: // kind.struct_value
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Struct)
- err := b.DecodeMessage(msg)
- m.Kind = &Value_StructValue{msg}
- return true, err
- case 6: // kind.list_value
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(ListValue)
- err := b.DecodeMessage(msg)
- m.Kind = &Value_ListValue{msg}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _Value_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*Value)
- // kind
- switch x := m.Kind.(type) {
- case *Value_NullValue:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(x.NullValue))
- case *Value_NumberValue:
- n += 1 // tag and wire
- n += 8
- case *Value_StringValue:
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(len(x.StringValue)))
- n += len(x.StringValue)
- case *Value_BoolValue:
- n += 1 // tag and wire
- n += 1
- case *Value_StructValue:
- s := proto.Size(x.StructValue)
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case *Value_ListValue:
- s := proto.Size(x.ListValue)
- n += 1 // tag and wire
- n += proto.SizeVarint(uint64(s))
- n += s
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-// `ListValue` is a wrapper around a repeated field of values.
-//
-// The JSON representation for `ListValue` is JSON array.
-type ListValue struct {
- // Repeated field of dynamically typed values.
- Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ListValue) Reset() { *m = ListValue{} }
-func (m *ListValue) String() string { return proto.CompactTextString(m) }
-func (*ListValue) ProtoMessage() {}
-func (*ListValue) Descriptor() ([]byte, []int) {
- return fileDescriptor_struct_3a5a94e0c7801b27, []int{2}
-}
-func (*ListValue) XXX_WellKnownType() string { return "ListValue" }
-func (m *ListValue) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ListValue.Unmarshal(m, b)
-}
-func (m *ListValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ListValue.Marshal(b, m, deterministic)
-}
-func (dst *ListValue) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ListValue.Merge(dst, src)
-}
-func (m *ListValue) XXX_Size() int {
- return xxx_messageInfo_ListValue.Size(m)
-}
-func (m *ListValue) XXX_DiscardUnknown() {
- xxx_messageInfo_ListValue.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ListValue proto.InternalMessageInfo
-
-func (m *ListValue) GetValues() []*Value {
- if m != nil {
- return m.Values
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*Struct)(nil), "google.protobuf.Struct")
- proto.RegisterMapType((map[string]*Value)(nil), "google.protobuf.Struct.FieldsEntry")
- proto.RegisterType((*Value)(nil), "google.protobuf.Value")
- proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue")
- proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value)
-}
-
-func init() {
- proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor_struct_3a5a94e0c7801b27)
-}
-
-var fileDescriptor_struct_3a5a94e0c7801b27 = []byte{
- // 417 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40,
- 0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09,
- 0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94,
- 0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa,
- 0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff,
- 0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc,
- 0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15,
- 0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d,
- 0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce,
- 0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39,
- 0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab,
- 0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84,
- 0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48,
- 0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f,
- 0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59,
- 0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a,
- 0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64,
- 0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92,
- 0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25,
- 0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37,
- 0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6,
- 0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4,
- 0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda,
- 0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9,
- 0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53,
- 0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00,
- 0x00,
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_ptypes_struct_struct_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_ptypes_struct_struct_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_ptypes_struct_struct_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_ptypes_struct_struct_proto = out.File
+ file_github_com_golang_protobuf_ptypes_struct_struct_proto_rawDesc = nil
+ file_github_com_golang_protobuf_ptypes_struct_struct_proto_goTypes = nil
+ file_github_com_golang_protobuf_ptypes_struct_struct_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto b/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto
deleted file mode 100644
index 7d7808e7f..000000000
--- a/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto
+++ /dev/null
@@ -1,96 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option cc_enable_arenas = true;
-option go_package = "github.com/golang/protobuf/ptypes/struct;structpb";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "StructProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-
-// `Struct` represents a structured data value, consisting of fields
-// which map to dynamically typed values. In some languages, `Struct`
-// might be supported by a native representation. For example, in
-// scripting languages like JS a struct is represented as an
-// object. The details of that representation are described together
-// with the proto support for the language.
-//
-// The JSON representation for `Struct` is JSON object.
-message Struct {
- // Unordered map of dynamically typed values.
- map fields = 1;
-}
-
-// `Value` represents a dynamically typed value which can be either
-// null, a number, a string, a boolean, a recursive struct value, or a
-// list of values. A producer of value is expected to set one of that
-// variants, absence of any variant indicates an error.
-//
-// The JSON representation for `Value` is JSON value.
-message Value {
- // The kind of value.
- oneof kind {
- // Represents a null value.
- NullValue null_value = 1;
- // Represents a double value.
- double number_value = 2;
- // Represents a string value.
- string string_value = 3;
- // Represents a boolean value.
- bool bool_value = 4;
- // Represents a structured value.
- Struct struct_value = 5;
- // Represents a repeated `Value`.
- ListValue list_value = 6;
- }
-}
-
-// `NullValue` is a singleton enumeration to represent the null value for the
-// `Value` type union.
-//
-// The JSON representation for `NullValue` is JSON `null`.
-enum NullValue {
- // Null value.
- NULL_VALUE = 0;
-}
-
-// `ListValue` is a wrapper around a repeated field of values.
-//
-// The JSON representation for `ListValue` is JSON array.
-message ListValue {
- // Repeated field of dynamically typed values.
- repeated Value values = 1;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
index 47f10dbc2..026d0d491 100644
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp.go
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
@@ -1,46 +1,18 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package ptypes
-// This file implements operations on google.protobuf.Timestamp.
-
import (
"errors"
"fmt"
"time"
- tspb "github.com/golang/protobuf/ptypes/timestamp"
+ timestamppb "github.com/golang/protobuf/ptypes/timestamp"
)
+// Range of google.protobuf.Duration as specified in timestamp.proto.
const (
// Seconds field of the earliest valid Timestamp.
// This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
@@ -50,44 +22,18 @@ const (
maxValidSeconds = 253402300800
)
-// validateTimestamp determines whether a Timestamp is valid.
-// A valid timestamp represents a time in the range
-// [0001-01-01, 10000-01-01) and has a Nanos field
-// in the range [0, 1e9).
-//
-// If the Timestamp is valid, validateTimestamp returns nil.
-// Otherwise, it returns an error that describes
-// the problem.
-//
-// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
-func validateTimestamp(ts *tspb.Timestamp) error {
- if ts == nil {
- return errors.New("timestamp: nil Timestamp")
- }
- if ts.Seconds < minValidSeconds {
- return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
- }
- if ts.Seconds >= maxValidSeconds {
- return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
- }
- if ts.Nanos < 0 || ts.Nanos >= 1e9 {
- return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
- }
- return nil
-}
-
-// Timestamp converts a google.protobuf.Timestamp proto to a time.Time.
+// Timestamp converts a timestamppb.Timestamp to a time.Time.
// It returns an error if the argument is invalid.
//
-// Unlike most Go functions, if Timestamp returns an error, the first return value
-// is not the zero time.Time. Instead, it is the value obtained from the
+// Unlike most Go functions, if Timestamp returns an error, the first return
+// value is not the zero time.Time. Instead, it is the value obtained from the
// time.Unix function when passed the contents of the Timestamp, in the UTC
// locale. This may or may not be a meaningful time; many invalid Timestamps
// do map to valid time.Times.
//
// A nil Timestamp returns an error. The first return value in that case is
// undefined.
-func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
+func Timestamp(ts *timestamppb.Timestamp) (time.Time, error) {
// Don't return the zero value on error, because corresponds to a valid
// timestamp. Instead return whatever time.Unix gives us.
var t time.Time
@@ -100,7 +46,7 @@ func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
}
// TimestampNow returns a google.protobuf.Timestamp for the current time.
-func TimestampNow() *tspb.Timestamp {
+func TimestampNow() *timestamppb.Timestamp {
ts, err := TimestampProto(time.Now())
if err != nil {
panic("ptypes: time.Now() out of Timestamp range")
@@ -110,12 +56,10 @@ func TimestampNow() *tspb.Timestamp {
// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
// It returns an error if the resulting Timestamp is invalid.
-func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
- seconds := t.Unix()
- nanos := int32(t.Sub(time.Unix(seconds, 0)))
- ts := &tspb.Timestamp{
- Seconds: seconds,
- Nanos: nanos,
+func TimestampProto(t time.Time) (*timestamppb.Timestamp, error) {
+ ts := ×tamppb.Timestamp{
+ Seconds: t.Unix(),
+ Nanos: int32(t.Nanosecond()),
}
if err := validateTimestamp(ts); err != nil {
return nil, err
@@ -123,12 +67,37 @@ func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
return ts, nil
}
-// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid
-// Timestamps, it returns an error message in parentheses.
-func TimestampString(ts *tspb.Timestamp) string {
+// TimestampString returns the RFC 3339 string for valid Timestamps.
+// For invalid Timestamps, it returns an error message in parentheses.
+func TimestampString(ts *timestamppb.Timestamp) string {
t, err := Timestamp(ts)
if err != nil {
return fmt.Sprintf("(%v)", err)
}
return t.Format(time.RFC3339Nano)
}
+
+// validateTimestamp determines whether a Timestamp is valid.
+// A valid timestamp represents a time in the range [0001-01-01, 10000-01-01)
+// and has a Nanos field in the range [0, 1e9).
+//
+// If the Timestamp is valid, validateTimestamp returns nil.
+// Otherwise, it returns an error that describes the problem.
+//
+// Every valid Timestamp can be represented by a time.Time,
+// but the converse is not true.
+func validateTimestamp(ts *timestamppb.Timestamp) error {
+ if ts == nil {
+ return errors.New("timestamp: nil Timestamp")
+ }
+ if ts.Seconds < minValidSeconds {
+ return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
+ }
+ if ts.Seconds >= maxValidSeconds {
+ return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
+ }
+ if ts.Nanos < 0 || ts.Nanos >= 1e9 {
+ return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
+ }
+ return nil
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
index e9c222282..a76f80760 100644
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
@@ -1,175 +1,64 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/timestamp.proto
+// source: github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
-package timestamp // import "github.com/golang/protobuf/ptypes/timestamp"
+package timestamp
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ timestamppb "google.golang.org/protobuf/types/known/timestamppb"
+ reflect "reflect"
+)
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
+// Symbols defined in public import of google/protobuf/timestamp.proto.
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+type Timestamp = timestamppb.Timestamp
-// A Timestamp represents a point in time independent of any time zone
-// or calendar, represented as seconds and fractions of seconds at
-// nanosecond resolution in UTC Epoch time. It is encoded using the
-// Proleptic Gregorian Calendar which extends the Gregorian calendar
-// backwards to year one. It is encoded assuming all minutes are 60
-// seconds long, i.e. leap seconds are "smeared" so that no leap second
-// table is needed for interpretation. Range is from
-// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
-// By restricting to that range, we ensure that we can convert to
-// and from RFC 3339 date strings.
-// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
-//
-// # Examples
-//
-// Example 1: Compute Timestamp from POSIX `time()`.
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(time(NULL));
-// timestamp.set_nanos(0);
-//
-// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
-//
-// struct timeval tv;
-// gettimeofday(&tv, NULL);
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(tv.tv_sec);
-// timestamp.set_nanos(tv.tv_usec * 1000);
-//
-// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
-//
-// FILETIME ft;
-// GetSystemTimeAsFileTime(&ft);
-// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
-//
-// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
-// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
-// Timestamp timestamp;
-// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
-// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
-//
-// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
-//
-// long millis = System.currentTimeMillis();
-//
-// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
-// .setNanos((int) ((millis % 1000) * 1000000)).build();
-//
-//
-// Example 5: Compute Timestamp from current time in Python.
-//
-// timestamp = Timestamp()
-// timestamp.GetCurrentTime()
-//
-// # JSON Mapping
-//
-// In JSON format, the Timestamp type is encoded as a string in the
-// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
-// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
-// where {year} is always expressed using four digits while {month}, {day},
-// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
-// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
-// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
-// is required, though only UTC (as indicated by "Z") is presently supported.
-//
-// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
-// 01:30 UTC on January 15, 2017.
-//
-// In JavaScript, one can convert a Date object to this format using the
-// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
-// method. In Python, a standard `datetime.datetime` object can be converted
-// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
-// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
-// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
-// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
-// to obtain a formatter capable of generating timestamps in this format.
-//
-//
-type Timestamp struct {
- // Represents seconds of UTC time since Unix epoch
- // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
- // 9999-12-31T23:59:59Z inclusive.
- Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
- // Non-negative fractions of a second at nanosecond resolution. Negative
- // second values with fractions must still have non-negative nanos values
- // that count forward in time. Must be from 0 to 999,999,999
- // inclusive.
- Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
+var File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto protoreflect.FileDescriptor
-func (m *Timestamp) Reset() { *m = Timestamp{} }
-func (m *Timestamp) String() string { return proto.CompactTextString(m) }
-func (*Timestamp) ProtoMessage() {}
-func (*Timestamp) Descriptor() ([]byte, []int) {
- return fileDescriptor_timestamp_b826e8e5fba671a8, []int{0}
-}
-func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" }
-func (m *Timestamp) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Timestamp.Unmarshal(m, b)
-}
-func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic)
-}
-func (dst *Timestamp) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Timestamp.Merge(dst, src)
+var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = []byte{
+ 0x0a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2f, 0x74, 0x69,
+ 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67,
+ 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74,
+ 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x37,
+ 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x3b, 0x74, 0x69,
+ 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
+ 0x33,
}
-func (m *Timestamp) XXX_Size() int {
- return xxx_messageInfo_Timestamp.Size(m)
-}
-func (m *Timestamp) XXX_DiscardUnknown() {
- xxx_messageInfo_Timestamp.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Timestamp proto.InternalMessageInfo
-func (m *Timestamp) GetSeconds() int64 {
- if m != nil {
- return m.Seconds
- }
- return 0
+var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
}
-func (m *Timestamp) GetNanos() int32 {
- if m != nil {
- return m.Nanos
+func init() { file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() }
+func file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() {
+ if File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto != nil {
+ return
}
- return 0
-}
-
-func init() {
- proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp")
-}
-
-func init() {
- proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_timestamp_b826e8e5fba671a8)
-}
-
-var fileDescriptor_timestamp_b826e8e5fba671a8 = []byte{
- // 191 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d,
- 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28,
- 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5,
- 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89,
- 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70,
- 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51,
- 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89,
- 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71,
- 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a,
- 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43,
- 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00,
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto = out.File
+ file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = nil
+ file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = nil
+ file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
deleted file mode 100644
index 06750ab1f..000000000
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
+++ /dev/null
@@ -1,133 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option cc_enable_arenas = true;
-option go_package = "github.com/golang/protobuf/ptypes/timestamp";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "TimestampProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// A Timestamp represents a point in time independent of any time zone
-// or calendar, represented as seconds and fractions of seconds at
-// nanosecond resolution in UTC Epoch time. It is encoded using the
-// Proleptic Gregorian Calendar which extends the Gregorian calendar
-// backwards to year one. It is encoded assuming all minutes are 60
-// seconds long, i.e. leap seconds are "smeared" so that no leap second
-// table is needed for interpretation. Range is from
-// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
-// By restricting to that range, we ensure that we can convert to
-// and from RFC 3339 date strings.
-// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
-//
-// # Examples
-//
-// Example 1: Compute Timestamp from POSIX `time()`.
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(time(NULL));
-// timestamp.set_nanos(0);
-//
-// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
-//
-// struct timeval tv;
-// gettimeofday(&tv, NULL);
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(tv.tv_sec);
-// timestamp.set_nanos(tv.tv_usec * 1000);
-//
-// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
-//
-// FILETIME ft;
-// GetSystemTimeAsFileTime(&ft);
-// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
-//
-// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
-// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
-// Timestamp timestamp;
-// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
-// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
-//
-// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
-//
-// long millis = System.currentTimeMillis();
-//
-// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
-// .setNanos((int) ((millis % 1000) * 1000000)).build();
-//
-//
-// Example 5: Compute Timestamp from current time in Python.
-//
-// timestamp = Timestamp()
-// timestamp.GetCurrentTime()
-//
-// # JSON Mapping
-//
-// In JSON format, the Timestamp type is encoded as a string in the
-// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
-// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
-// where {year} is always expressed using four digits while {month}, {day},
-// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
-// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
-// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
-// is required, though only UTC (as indicated by "Z") is presently supported.
-//
-// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
-// 01:30 UTC on January 15, 2017.
-//
-// In JavaScript, one can convert a Date object to this format using the
-// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
-// method. In Python, a standard `datetime.datetime` object can be converted
-// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
-// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
-// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
-// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--)
-// to obtain a formatter capable of generating timestamps in this format.
-//
-//
-message Timestamp {
-
- // Represents seconds of UTC time since Unix epoch
- // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
- // 9999-12-31T23:59:59Z inclusive.
- int64 seconds = 1;
-
- // Non-negative fractions of a second at nanosecond resolution. Negative
- // second values with fractions must still have non-negative nanos values
- // that count forward in time. Must be from 0 to 999,999,999
- // inclusive.
- int32 nanos = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
index 6e3c969b9..07efdfd82 100644
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
@@ -1,33 +1,6 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
package ptypes
@@ -37,6 +10,7 @@ import (
"time"
"github.com/golang/protobuf/proto"
+
tspb "github.com/golang/protobuf/ptypes/timestamp"
)
@@ -124,7 +98,6 @@ func TestTimestampString(t *testing.T) {
// Not much testing needed because presumably time.Format is
// well-tested.
{&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"},
- {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"},
} {
got := TimestampString(test.ts)
if got != test.want {
diff --git a/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go
index d1fc4d0b8..cc40f27ad 100644
--- a/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go
+++ b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go
@@ -1,443 +1,71 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/wrappers.proto
-
-package wrappers // import "github.com/golang/protobuf/ptypes/wrappers"
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// Wrapper message for `double`.
-//
-// The JSON representation for `DoubleValue` is JSON number.
-type DoubleValue struct {
- // The double value.
- Value float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DoubleValue) Reset() { *m = DoubleValue{} }
-func (m *DoubleValue) String() string { return proto.CompactTextString(m) }
-func (*DoubleValue) ProtoMessage() {}
-func (*DoubleValue) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{0}
-}
-func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" }
-func (m *DoubleValue) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DoubleValue.Unmarshal(m, b)
-}
-func (m *DoubleValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DoubleValue.Marshal(b, m, deterministic)
-}
-func (dst *DoubleValue) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DoubleValue.Merge(dst, src)
-}
-func (m *DoubleValue) XXX_Size() int {
- return xxx_messageInfo_DoubleValue.Size(m)
-}
-func (m *DoubleValue) XXX_DiscardUnknown() {
- xxx_messageInfo_DoubleValue.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DoubleValue proto.InternalMessageInfo
-
-func (m *DoubleValue) GetValue() float64 {
- if m != nil {
- return m.Value
- }
- return 0
-}
-
-// Wrapper message for `float`.
-//
-// The JSON representation for `FloatValue` is JSON number.
-type FloatValue struct {
- // The float value.
- Value float32 `protobuf:"fixed32,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FloatValue) Reset() { *m = FloatValue{} }
-func (m *FloatValue) String() string { return proto.CompactTextString(m) }
-func (*FloatValue) ProtoMessage() {}
-func (*FloatValue) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{1}
-}
-func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" }
-func (m *FloatValue) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FloatValue.Unmarshal(m, b)
-}
-func (m *FloatValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FloatValue.Marshal(b, m, deterministic)
-}
-func (dst *FloatValue) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FloatValue.Merge(dst, src)
-}
-func (m *FloatValue) XXX_Size() int {
- return xxx_messageInfo_FloatValue.Size(m)
-}
-func (m *FloatValue) XXX_DiscardUnknown() {
- xxx_messageInfo_FloatValue.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FloatValue proto.InternalMessageInfo
-
-func (m *FloatValue) GetValue() float32 {
- if m != nil {
- return m.Value
+// source: github.com/golang/protobuf/ptypes/wrappers/wrappers.proto
+
+package wrappers
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
+ reflect "reflect"
+)
+
+// Symbols defined in public import of google/protobuf/wrappers.proto.
+
+type DoubleValue = wrapperspb.DoubleValue
+type FloatValue = wrapperspb.FloatValue
+type Int64Value = wrapperspb.Int64Value
+type UInt64Value = wrapperspb.UInt64Value
+type Int32Value = wrapperspb.Int32Value
+type UInt32Value = wrapperspb.UInt32Value
+type BoolValue = wrapperspb.BoolValue
+type StringValue = wrapperspb.StringValue
+type BytesValue = wrapperspb.BytesValue
+
+var File_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto protoreflect.FileDescriptor
+
+var file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_rawDesc = []byte{
+ 0x0a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c,
+ 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79,
+ 0x70, 0x65, 0x73, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2f, 0x77, 0x72, 0x61,
+ 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f,
+ 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61,
+ 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x35, 0x5a, 0x33, 0x67,
+ 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67,
+ 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73,
+ 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x3b, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65,
+ 0x72, 0x73, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_goTypes = []interface{}{}
+var file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_depIdxs = []int32{
+ 0, // [0:0] is the sub-list for method output_type
+ 0, // [0:0] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_init() }
+func file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_init() {
+ if File_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto != nil {
+ return
}
- return 0
-}
-
-// Wrapper message for `int64`.
-//
-// The JSON representation for `Int64Value` is JSON string.
-type Int64Value struct {
- // The int64 value.
- Value int64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Int64Value) Reset() { *m = Int64Value{} }
-func (m *Int64Value) String() string { return proto.CompactTextString(m) }
-func (*Int64Value) ProtoMessage() {}
-func (*Int64Value) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{2}
-}
-func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" }
-func (m *Int64Value) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Int64Value.Unmarshal(m, b)
-}
-func (m *Int64Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Int64Value.Marshal(b, m, deterministic)
-}
-func (dst *Int64Value) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Int64Value.Merge(dst, src)
-}
-func (m *Int64Value) XXX_Size() int {
- return xxx_messageInfo_Int64Value.Size(m)
-}
-func (m *Int64Value) XXX_DiscardUnknown() {
- xxx_messageInfo_Int64Value.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Int64Value proto.InternalMessageInfo
-
-func (m *Int64Value) GetValue() int64 {
- if m != nil {
- return m.Value
- }
- return 0
-}
-
-// Wrapper message for `uint64`.
-//
-// The JSON representation for `UInt64Value` is JSON string.
-type UInt64Value struct {
- // The uint64 value.
- Value uint64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UInt64Value) Reset() { *m = UInt64Value{} }
-func (m *UInt64Value) String() string { return proto.CompactTextString(m) }
-func (*UInt64Value) ProtoMessage() {}
-func (*UInt64Value) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{3}
-}
-func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" }
-func (m *UInt64Value) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UInt64Value.Unmarshal(m, b)
-}
-func (m *UInt64Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UInt64Value.Marshal(b, m, deterministic)
-}
-func (dst *UInt64Value) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UInt64Value.Merge(dst, src)
-}
-func (m *UInt64Value) XXX_Size() int {
- return xxx_messageInfo_UInt64Value.Size(m)
-}
-func (m *UInt64Value) XXX_DiscardUnknown() {
- xxx_messageInfo_UInt64Value.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UInt64Value proto.InternalMessageInfo
-
-func (m *UInt64Value) GetValue() uint64 {
- if m != nil {
- return m.Value
- }
- return 0
-}
-
-// Wrapper message for `int32`.
-//
-// The JSON representation for `Int32Value` is JSON number.
-type Int32Value struct {
- // The int32 value.
- Value int32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Int32Value) Reset() { *m = Int32Value{} }
-func (m *Int32Value) String() string { return proto.CompactTextString(m) }
-func (*Int32Value) ProtoMessage() {}
-func (*Int32Value) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{4}
-}
-func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" }
-func (m *Int32Value) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Int32Value.Unmarshal(m, b)
-}
-func (m *Int32Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Int32Value.Marshal(b, m, deterministic)
-}
-func (dst *Int32Value) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Int32Value.Merge(dst, src)
-}
-func (m *Int32Value) XXX_Size() int {
- return xxx_messageInfo_Int32Value.Size(m)
-}
-func (m *Int32Value) XXX_DiscardUnknown() {
- xxx_messageInfo_Int32Value.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Int32Value proto.InternalMessageInfo
-
-func (m *Int32Value) GetValue() int32 {
- if m != nil {
- return m.Value
- }
- return 0
-}
-
-// Wrapper message for `uint32`.
-//
-// The JSON representation for `UInt32Value` is JSON number.
-type UInt32Value struct {
- // The uint32 value.
- Value uint32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UInt32Value) Reset() { *m = UInt32Value{} }
-func (m *UInt32Value) String() string { return proto.CompactTextString(m) }
-func (*UInt32Value) ProtoMessage() {}
-func (*UInt32Value) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{5}
-}
-func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" }
-func (m *UInt32Value) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UInt32Value.Unmarshal(m, b)
-}
-func (m *UInt32Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UInt32Value.Marshal(b, m, deterministic)
-}
-func (dst *UInt32Value) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UInt32Value.Merge(dst, src)
-}
-func (m *UInt32Value) XXX_Size() int {
- return xxx_messageInfo_UInt32Value.Size(m)
-}
-func (m *UInt32Value) XXX_DiscardUnknown() {
- xxx_messageInfo_UInt32Value.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UInt32Value proto.InternalMessageInfo
-
-func (m *UInt32Value) GetValue() uint32 {
- if m != nil {
- return m.Value
- }
- return 0
-}
-
-// Wrapper message for `bool`.
-//
-// The JSON representation for `BoolValue` is JSON `true` and `false`.
-type BoolValue struct {
- // The bool value.
- Value bool `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *BoolValue) Reset() { *m = BoolValue{} }
-func (m *BoolValue) String() string { return proto.CompactTextString(m) }
-func (*BoolValue) ProtoMessage() {}
-func (*BoolValue) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{6}
-}
-func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" }
-func (m *BoolValue) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_BoolValue.Unmarshal(m, b)
-}
-func (m *BoolValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_BoolValue.Marshal(b, m, deterministic)
-}
-func (dst *BoolValue) XXX_Merge(src proto.Message) {
- xxx_messageInfo_BoolValue.Merge(dst, src)
-}
-func (m *BoolValue) XXX_Size() int {
- return xxx_messageInfo_BoolValue.Size(m)
-}
-func (m *BoolValue) XXX_DiscardUnknown() {
- xxx_messageInfo_BoolValue.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_BoolValue proto.InternalMessageInfo
-
-func (m *BoolValue) GetValue() bool {
- if m != nil {
- return m.Value
- }
- return false
-}
-
-// Wrapper message for `string`.
-//
-// The JSON representation for `StringValue` is JSON string.
-type StringValue struct {
- // The string value.
- Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *StringValue) Reset() { *m = StringValue{} }
-func (m *StringValue) String() string { return proto.CompactTextString(m) }
-func (*StringValue) ProtoMessage() {}
-func (*StringValue) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{7}
-}
-func (*StringValue) XXX_WellKnownType() string { return "StringValue" }
-func (m *StringValue) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_StringValue.Unmarshal(m, b)
-}
-func (m *StringValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_StringValue.Marshal(b, m, deterministic)
-}
-func (dst *StringValue) XXX_Merge(src proto.Message) {
- xxx_messageInfo_StringValue.Merge(dst, src)
-}
-func (m *StringValue) XXX_Size() int {
- return xxx_messageInfo_StringValue.Size(m)
-}
-func (m *StringValue) XXX_DiscardUnknown() {
- xxx_messageInfo_StringValue.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_StringValue proto.InternalMessageInfo
-
-func (m *StringValue) GetValue() string {
- if m != nil {
- return m.Value
- }
- return ""
-}
-
-// Wrapper message for `bytes`.
-//
-// The JSON representation for `BytesValue` is JSON string.
-type BytesValue struct {
- // The bytes value.
- Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *BytesValue) Reset() { *m = BytesValue{} }
-func (m *BytesValue) String() string { return proto.CompactTextString(m) }
-func (*BytesValue) ProtoMessage() {}
-func (*BytesValue) Descriptor() ([]byte, []int) {
- return fileDescriptor_wrappers_16c7c35c009f3253, []int{8}
-}
-func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" }
-func (m *BytesValue) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_BytesValue.Unmarshal(m, b)
-}
-func (m *BytesValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_BytesValue.Marshal(b, m, deterministic)
-}
-func (dst *BytesValue) XXX_Merge(src proto.Message) {
- xxx_messageInfo_BytesValue.Merge(dst, src)
-}
-func (m *BytesValue) XXX_Size() int {
- return xxx_messageInfo_BytesValue.Size(m)
-}
-func (m *BytesValue) XXX_DiscardUnknown() {
- xxx_messageInfo_BytesValue.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_BytesValue proto.InternalMessageInfo
-
-func (m *BytesValue) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue")
- proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue")
- proto.RegisterType((*Int64Value)(nil), "google.protobuf.Int64Value")
- proto.RegisterType((*UInt64Value)(nil), "google.protobuf.UInt64Value")
- proto.RegisterType((*Int32Value)(nil), "google.protobuf.Int32Value")
- proto.RegisterType((*UInt32Value)(nil), "google.protobuf.UInt32Value")
- proto.RegisterType((*BoolValue)(nil), "google.protobuf.BoolValue")
- proto.RegisterType((*StringValue)(nil), "google.protobuf.StringValue")
- proto.RegisterType((*BytesValue)(nil), "google.protobuf.BytesValue")
-}
-
-func init() {
- proto.RegisterFile("google/protobuf/wrappers.proto", fileDescriptor_wrappers_16c7c35c009f3253)
-}
-
-var fileDescriptor_wrappers_16c7c35c009f3253 = []byte{
- // 259 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x2f, 0x4a, 0x2c,
- 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0xca,
- 0x5c, 0xdc, 0x2e, 0xf9, 0xa5, 0x49, 0x39, 0xa9, 0x61, 0x89, 0x39, 0xa5, 0xa9, 0x42, 0x22, 0x5c,
- 0xac, 0x65, 0x20, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x63, 0x10, 0x84, 0xa3, 0xa4, 0xc4, 0xc5,
- 0xe5, 0x96, 0x93, 0x9f, 0x58, 0x82, 0x45, 0x0d, 0x13, 0x92, 0x1a, 0xcf, 0xbc, 0x12, 0x33, 0x13,
- 0x2c, 0x6a, 0x98, 0x61, 0x6a, 0x94, 0xb9, 0xb8, 0x43, 0x71, 0x29, 0x62, 0x41, 0x35, 0xc8, 0xd8,
- 0x08, 0x8b, 0x1a, 0x56, 0x34, 0x83, 0xb0, 0x2a, 0xe2, 0x85, 0x29, 0x52, 0xe4, 0xe2, 0x74, 0xca,
- 0xcf, 0xcf, 0xc1, 0xa2, 0x84, 0x03, 0xc9, 0x9c, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x2c, 0x8a,
- 0x38, 0x91, 0x1c, 0xe4, 0x54, 0x59, 0x92, 0x5a, 0x8c, 0x45, 0x0d, 0x0f, 0x54, 0x8d, 0x53, 0x0d,
- 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x5a, 0xe8, 0x3a, 0xf1, 0x86, 0x43, 0x83, 0x3f, 0x00, 0x24,
- 0x12, 0xc0, 0x18, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f,
- 0x9e, 0x9f, 0x93, 0x98, 0x97, 0x8e, 0x88, 0xaa, 0x82, 0x92, 0xca, 0x82, 0xd4, 0x62, 0x78, 0x8c,
- 0xfd, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e,
- 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b,
- 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x19, 0x6c, 0xb9, 0xb8, 0xfe,
- 0x01, 0x00, 0x00,
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 0,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_goTypes,
+ DependencyIndexes: file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_depIdxs,
+ }.Build()
+ File_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto = out.File
+ file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_rawDesc = nil
+ file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_goTypes = nil
+ file_github_com_golang_protobuf_ptypes_wrappers_wrappers_proto_depIdxs = nil
}
diff --git a/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto
deleted file mode 100644
index 01947639a..000000000
--- a/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto
+++ /dev/null
@@ -1,118 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Wrappers for primitive (non-message) types. These types are useful
-// for embedding primitives in the `google.protobuf.Any` type and for places
-// where we need to distinguish between the absence of a primitive
-// typed field and its default value.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option cc_enable_arenas = true;
-option go_package = "github.com/golang/protobuf/ptypes/wrappers";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "WrappersProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// Wrapper message for `double`.
-//
-// The JSON representation for `DoubleValue` is JSON number.
-message DoubleValue {
- // The double value.
- double value = 1;
-}
-
-// Wrapper message for `float`.
-//
-// The JSON representation for `FloatValue` is JSON number.
-message FloatValue {
- // The float value.
- float value = 1;
-}
-
-// Wrapper message for `int64`.
-//
-// The JSON representation for `Int64Value` is JSON string.
-message Int64Value {
- // The int64 value.
- int64 value = 1;
-}
-
-// Wrapper message for `uint64`.
-//
-// The JSON representation for `UInt64Value` is JSON string.
-message UInt64Value {
- // The uint64 value.
- uint64 value = 1;
-}
-
-// Wrapper message for `int32`.
-//
-// The JSON representation for `Int32Value` is JSON number.
-message Int32Value {
- // The int32 value.
- int32 value = 1;
-}
-
-// Wrapper message for `uint32`.
-//
-// The JSON representation for `UInt32Value` is JSON number.
-message UInt32Value {
- // The uint32 value.
- uint32 value = 1;
-}
-
-// Wrapper message for `bool`.
-//
-// The JSON representation for `BoolValue` is JSON `true` and `false`.
-message BoolValue {
- // The bool value.
- bool value = 1;
-}
-
-// Wrapper message for `string`.
-//
-// The JSON representation for `StringValue` is JSON string.
-message StringValue {
- // The string value.
- string value = 1;
-}
-
-// Wrapper message for `bytes`.
-//
-// The JSON representation for `BytesValue` is JSON string.
-message BytesValue {
- // The bytes value.
- bytes value = 1;
-}
diff --git a/vendor/github.com/golang/protobuf/regenerate.bash b/vendor/github.com/golang/protobuf/regenerate.bash
new file mode 100644
index 000000000..f6c35c5af
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/regenerate.bash
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Copyright 2018 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+cd "$(git rev-parse --show-toplevel)"
+set -e
+go run ./internal/cmd/generate-alias -execute
+go test ./protoc-gen-go -regenerate
diff --git a/vendor/github.com/golang/protobuf/regenerate.sh b/vendor/github.com/golang/protobuf/regenerate.sh
deleted file mode 100644
index dc7e2d1f6..000000000
--- a/vendor/github.com/golang/protobuf/regenerate.sh
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/bin/bash
-
-set -e
-
-# Install the working tree's protoc-gen-gen in a tempdir.
-tmpdir=$(mktemp -d -t regen-wkt.XXXXXX)
-trap 'rm -rf $tmpdir' EXIT
-mkdir -p $tmpdir/bin
-PATH=$tmpdir/bin:$PATH
-GOBIN=$tmpdir/bin go install ./protoc-gen-go
-
-# Public imports require at least Go 1.9.
-supportTypeAliases=""
-if go list -f '{{context.ReleaseTags}}' runtime | grep -q go1.9; then
- supportTypeAliases=1
-fi
-
-# Generate various test protos.
-PROTO_DIRS=(
- conformance/internal/conformance_proto
- jsonpb/jsonpb_test_proto
- proto
- protoc-gen-go/testdata
-)
-for dir in ${PROTO_DIRS[@]}; do
- for p in `find $dir -name "*.proto"`; do
- if [[ $p == */import_public/* && ! $supportTypeAliases ]]; then
- echo "# $p (skipped)"
- continue;
- fi
- echo "# $p"
- protoc -I$dir --go_out=plugins=grpc,paths=source_relative:$dir $p
- done
-done
-
-# Deriving the location of the source protos from the path to the
-# protoc binary may be a bit odd, but this is what protoc itself does.
-PROTO_INCLUDE=$(dirname $(dirname $(which protoc)))/include
-
-# Well-known types.
-WKT_PROTOS=(any duration empty struct timestamp wrappers)
-for p in ${WKT_PROTOS[@]}; do
- echo "# google/protobuf/$p.proto"
- protoc --go_out=paths=source_relative:$tmpdir google/protobuf/$p.proto
- cp $tmpdir/google/protobuf/$p.pb.go ptypes/$p
- cp $PROTO_INCLUDE/google/protobuf/$p.proto ptypes/$p
-done
-
-# descriptor.proto.
-echo "# google/protobuf/descriptor.proto"
-protoc --go_out=paths=source_relative:$tmpdir google/protobuf/descriptor.proto
-cp $tmpdir/google/protobuf/descriptor.pb.go protoc-gen-go/descriptor
-cp $PROTO_INCLUDE/google/protobuf/descriptor.proto protoc-gen-go/descriptor
diff --git a/vendor/github.com/golang/protobuf/test.bash b/vendor/github.com/golang/protobuf/test.bash
new file mode 100644
index 000000000..c213adebd
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/test.bash
@@ -0,0 +1,41 @@
+#!/bin/bash
+# Copyright 2018 The Go Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+cd "$(git rev-parse --show-toplevel)"
+
+BOLD="\x1b[1mRunning: "
+PASS="\x1b[32mPASS"
+FAIL="\x1b[31mFAIL"
+RESET="\x1b[0m"
+
+echo -e "${BOLD}go test ./...${RESET}"
+RET_TEST0=$(go test ./... | egrep -v "^(ok|[?])\s+")
+if [[ ! -z "$RET_TEST0" ]]; then echo "$RET_TEST0"; echo; fi
+
+echo -e "${BOLD}go test -tags purego ./...${RESET}"
+RET_TEST1=$(go test -tags purego ./... | egrep -v "^(ok|[?])\s+")
+if [[ ! -z "$RET_TEST1" ]]; then echo "$RET_TEST1"; echo; fi
+
+echo -e "${BOLD}go generate${RESET}"
+RET_GEN=$(go run ./internal/cmd/generate-alias 2>&1)
+if [[ ! -z "$RET_GEN" ]]; then echo "$RET_GEN"; echo; fi
+
+echo -e "${BOLD}go fmt${RESET}"
+RET_FMT=$(gofmt -d $(git ls-files *.go) 2>&1)
+if [[ ! -z "$RET_FMT" ]]; then echo "$RET_FMT"; echo; fi
+
+echo -e "${BOLD}git diff${RESET}"
+RET_DIFF=$(git diff --no-prefix HEAD 2>&1)
+if [[ ! -z "$RET_DIFF" ]]; then echo "$RET_DIFF"; echo; fi
+
+echo -e "${BOLD}git ls-files${RESET}"
+RET_FILES=$(git ls-files --others --exclude-standard 2>&1)
+if [[ ! -z "$RET_FILES" ]]; then echo "$RET_FILES"; echo; fi
+
+if [[ ! -z "$RET_TEST0" ]] || [[ ! -z "$RET_TEST1" ]] || [[ ! -z "$RET_GEN" ]] || [ ! -z "$RET_FMT" ] || [[ ! -z "$RET_DIFF" ]] || [[ ! -z "$RET_FILES" ]]; then
+ echo -e "${FAIL}${RESET}"; exit 1
+else
+ echo -e "${PASS}${RESET}"; exit 0
+fi
diff --git a/vendor/github.com/google/uuid/.travis.yml b/vendor/github.com/google/uuid/.travis.yml
new file mode 100644
index 000000000..d8156a60b
--- /dev/null
+++ b/vendor/github.com/google/uuid/.travis.yml
@@ -0,0 +1,9 @@
+language: go
+
+go:
+ - 1.4.3
+ - 1.5.3
+ - tip
+
+script:
+ - go test -v ./...
diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md
new file mode 100644
index 000000000..04fdf09f1
--- /dev/null
+++ b/vendor/github.com/google/uuid/CONTRIBUTING.md
@@ -0,0 +1,10 @@
+# How to contribute
+
+We definitely welcome patches and contribution to this project!
+
+### Legal requirements
+
+In order to protect both you and ourselves, you will need to sign the
+[Contributor License Agreement](https://cla.developers.google.com/clas).
+
+You may have already signed it for other Google projects.
diff --git a/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/google/uuid/CONTRIBUTORS
new file mode 100644
index 000000000..b4bb97f6b
--- /dev/null
+++ b/vendor/github.com/google/uuid/CONTRIBUTORS
@@ -0,0 +1,9 @@
+Paul Borman
+bmatsuo
+shawnps
+theory
+jboverfelt
+dsymonds
+cd1
+wallclockbuilder
+dansouza
diff --git a/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/google/uuid/LICENSE
new file mode 100644
index 000000000..5dc68268d
--- /dev/null
+++ b/vendor/github.com/google/uuid/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2009,2014 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/google/uuid/README.md b/vendor/github.com/google/uuid/README.md
new file mode 100644
index 000000000..f765a46f9
--- /dev/null
+++ b/vendor/github.com/google/uuid/README.md
@@ -0,0 +1,19 @@
+# uuid 
+The uuid package generates and inspects UUIDs based on
+[RFC 4122](http://tools.ietf.org/html/rfc4122)
+and DCE 1.1: Authentication and Security Services.
+
+This package is based on the github.com/pborman/uuid package (previously named
+code.google.com/p/go-uuid). It differs from these earlier packages in that
+a UUID is a 16 byte array rather than a byte slice. One loss due to this
+change is the ability to represent an invalid UUID (vs a NIL UUID).
+
+###### Install
+`go get github.com/google/uuid`
+
+###### Documentation
+[](http://godoc.org/github.com/google/uuid)
+
+Full `go doc` style documentation for the package can be viewed online without
+installing this package by using the GoDoc site here:
+http://pkg.go.dev/github.com/google/uuid
diff --git a/vendor/github.com/google/uuid/dce.go b/vendor/github.com/google/uuid/dce.go
new file mode 100644
index 000000000..fa820b9d3
--- /dev/null
+++ b/vendor/github.com/google/uuid/dce.go
@@ -0,0 +1,80 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+ "fmt"
+ "os"
+)
+
+// A Domain represents a Version 2 domain
+type Domain byte
+
+// Domain constants for DCE Security (Version 2) UUIDs.
+const (
+ Person = Domain(0)
+ Group = Domain(1)
+ Org = Domain(2)
+)
+
+// NewDCESecurity returns a DCE Security (Version 2) UUID.
+//
+// The domain should be one of Person, Group or Org.
+// On a POSIX system the id should be the users UID for the Person
+// domain and the users GID for the Group. The meaning of id for
+// the domain Org or on non-POSIX systems is site defined.
+//
+// For a given domain/id pair the same token may be returned for up to
+// 7 minutes and 10 seconds.
+func NewDCESecurity(domain Domain, id uint32) (UUID, error) {
+ uuid, err := NewUUID()
+ if err == nil {
+ uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2
+ uuid[9] = byte(domain)
+ binary.BigEndian.PutUint32(uuid[0:], id)
+ }
+ return uuid, err
+}
+
+// NewDCEPerson returns a DCE Security (Version 2) UUID in the person
+// domain with the id returned by os.Getuid.
+//
+// NewDCESecurity(Person, uint32(os.Getuid()))
+func NewDCEPerson() (UUID, error) {
+ return NewDCESecurity(Person, uint32(os.Getuid()))
+}
+
+// NewDCEGroup returns a DCE Security (Version 2) UUID in the group
+// domain with the id returned by os.Getgid.
+//
+// NewDCESecurity(Group, uint32(os.Getgid()))
+func NewDCEGroup() (UUID, error) {
+ return NewDCESecurity(Group, uint32(os.Getgid()))
+}
+
+// Domain returns the domain for a Version 2 UUID. Domains are only defined
+// for Version 2 UUIDs.
+func (uuid UUID) Domain() Domain {
+ return Domain(uuid[9])
+}
+
+// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2
+// UUIDs.
+func (uuid UUID) ID() uint32 {
+ return binary.BigEndian.Uint32(uuid[0:4])
+}
+
+func (d Domain) String() string {
+ switch d {
+ case Person:
+ return "Person"
+ case Group:
+ return "Group"
+ case Org:
+ return "Org"
+ }
+ return fmt.Sprintf("Domain%d", int(d))
+}
diff --git a/vendor/github.com/google/uuid/doc.go b/vendor/github.com/google/uuid/doc.go
new file mode 100644
index 000000000..5b8a4b9af
--- /dev/null
+++ b/vendor/github.com/google/uuid/doc.go
@@ -0,0 +1,12 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package uuid generates and inspects UUIDs.
+//
+// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security
+// Services.
+//
+// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to
+// maps or compared directly.
+package uuid
diff --git a/vendor/github.com/google/uuid/go.mod b/vendor/github.com/google/uuid/go.mod
new file mode 100644
index 000000000..fc84cd79d
--- /dev/null
+++ b/vendor/github.com/google/uuid/go.mod
@@ -0,0 +1 @@
+module github.com/google/uuid
diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go
new file mode 100644
index 000000000..b404f4bec
--- /dev/null
+++ b/vendor/github.com/google/uuid/hash.go
@@ -0,0 +1,53 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "crypto/md5"
+ "crypto/sha1"
+ "hash"
+)
+
+// Well known namespace IDs and UUIDs
+var (
+ NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))
+ NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8"))
+ NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8"))
+ NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8"))
+ Nil UUID // empty UUID, all zeros
+)
+
+// NewHash returns a new UUID derived from the hash of space concatenated with
+// data generated by h. The hash should be at least 16 byte in length. The
+// first 16 bytes of the hash are used to form the UUID. The version of the
+// UUID will be the lower 4 bits of version. NewHash is used to implement
+// NewMD5 and NewSHA1.
+func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID {
+ h.Reset()
+ h.Write(space[:]) //nolint:errcheck
+ h.Write(data) //nolint:errcheck
+ s := h.Sum(nil)
+ var uuid UUID
+ copy(uuid[:], s)
+ uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4)
+ uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant
+ return uuid
+}
+
+// NewMD5 returns a new MD5 (Version 3) UUID based on the
+// supplied name space and data. It is the same as calling:
+//
+// NewHash(md5.New(), space, data, 3)
+func NewMD5(space UUID, data []byte) UUID {
+ return NewHash(md5.New(), space, data, 3)
+}
+
+// NewSHA1 returns a new SHA1 (Version 5) UUID based on the
+// supplied name space and data. It is the same as calling:
+//
+// NewHash(sha1.New(), space, data, 5)
+func NewSHA1(space UUID, data []byte) UUID {
+ return NewHash(sha1.New(), space, data, 5)
+}
diff --git a/vendor/github.com/google/uuid/json_test.go b/vendor/github.com/google/uuid/json_test.go
new file mode 100644
index 000000000..245f91edf
--- /dev/null
+++ b/vendor/github.com/google/uuid/json_test.go
@@ -0,0 +1,62 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+)
+
+var testUUID = Must(Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479"))
+
+func TestJSON(t *testing.T) {
+ type S struct {
+ ID1 UUID
+ ID2 UUID
+ }
+ s1 := S{ID1: testUUID}
+ data, err := json.Marshal(&s1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var s2 S
+ if err := json.Unmarshal(data, &s2); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(&s1, &s2) {
+ t.Errorf("got %#v, want %#v", s2, s1)
+ }
+}
+
+func BenchmarkUUID_MarshalJSON(b *testing.B) {
+ x := &struct {
+ UUID UUID `json:"uuid"`
+ }{}
+ var err error
+ x.UUID, err = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
+ if err != nil {
+ b.Fatal(err)
+ }
+ for i := 0; i < b.N; i++ {
+ js, err := json.Marshal(x)
+ if err != nil {
+ b.Fatalf("marshal json: %#v (%v)", js, err)
+ }
+ }
+}
+
+func BenchmarkUUID_UnmarshalJSON(b *testing.B) {
+ js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`)
+ var x *struct {
+ UUID UUID `json:"uuid"`
+ }
+ for i := 0; i < b.N; i++ {
+ err := json.Unmarshal(js, &x)
+ if err != nil {
+ b.Fatalf("marshal json: %#v (%v)", js, err)
+ }
+ }
+}
diff --git a/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/google/uuid/marshal.go
new file mode 100644
index 000000000..14bd34072
--- /dev/null
+++ b/vendor/github.com/google/uuid/marshal.go
@@ -0,0 +1,38 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import "fmt"
+
+// MarshalText implements encoding.TextMarshaler.
+func (uuid UUID) MarshalText() ([]byte, error) {
+ var js [36]byte
+ encodeHex(js[:], uuid)
+ return js[:], nil
+}
+
+// UnmarshalText implements encoding.TextUnmarshaler.
+func (uuid *UUID) UnmarshalText(data []byte) error {
+ id, err := ParseBytes(data)
+ if err != nil {
+ return err
+ }
+ *uuid = id
+ return nil
+}
+
+// MarshalBinary implements encoding.BinaryMarshaler.
+func (uuid UUID) MarshalBinary() ([]byte, error) {
+ return uuid[:], nil
+}
+
+// UnmarshalBinary implements encoding.BinaryUnmarshaler.
+func (uuid *UUID) UnmarshalBinary(data []byte) error {
+ if len(data) != 16 {
+ return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
+ }
+ copy(uuid[:], data)
+ return nil
+}
diff --git a/vendor/github.com/google/uuid/node.go b/vendor/github.com/google/uuid/node.go
new file mode 100644
index 000000000..d651a2b06
--- /dev/null
+++ b/vendor/github.com/google/uuid/node.go
@@ -0,0 +1,90 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "sync"
+)
+
+var (
+ nodeMu sync.Mutex
+ ifname string // name of interface being used
+ nodeID [6]byte // hardware for version 1 UUIDs
+ zeroID [6]byte // nodeID with only 0's
+)
+
+// NodeInterface returns the name of the interface from which the NodeID was
+// derived. The interface "user" is returned if the NodeID was set by
+// SetNodeID.
+func NodeInterface() string {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ return ifname
+}
+
+// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs.
+// If name is "" then the first usable interface found will be used or a random
+// Node ID will be generated. If a named interface cannot be found then false
+// is returned.
+//
+// SetNodeInterface never fails when name is "".
+func SetNodeInterface(name string) bool {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ return setNodeInterface(name)
+}
+
+func setNodeInterface(name string) bool {
+ iname, addr := getHardwareInterface(name) // null implementation for js
+ if iname != "" && addr != nil {
+ ifname = iname
+ copy(nodeID[:], addr)
+ return true
+ }
+
+ // We found no interfaces with a valid hardware address. If name
+ // does not specify a specific interface generate a random Node ID
+ // (section 4.1.6)
+ if name == "" {
+ ifname = "random"
+ randomBits(nodeID[:])
+ return true
+ }
+ return false
+}
+
+// NodeID returns a slice of a copy of the current Node ID, setting the Node ID
+// if not already set.
+func NodeID() []byte {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ if nodeID == zeroID {
+ setNodeInterface("")
+ }
+ nid := nodeID
+ return nid[:]
+}
+
+// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes
+// of id are used. If id is less than 6 bytes then false is returned and the
+// Node ID is not set.
+func SetNodeID(id []byte) bool {
+ if len(id) < 6 {
+ return false
+ }
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ copy(nodeID[:], id)
+ ifname = "user"
+ return true
+}
+
+// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is
+// not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
+func (uuid UUID) NodeID() []byte {
+ var node [6]byte
+ copy(node[:], uuid[10:])
+ return node[:]
+}
diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go
new file mode 100644
index 000000000..24b78edc9
--- /dev/null
+++ b/vendor/github.com/google/uuid/node_js.go
@@ -0,0 +1,12 @@
+// Copyright 2017 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build js
+
+package uuid
+
+// getHardwareInterface returns nil values for the JS version of the code.
+// This remvoves the "net" dependency, because it is not used in the browser.
+// Using the "net" library inflates the size of the transpiled JS code by 673k bytes.
+func getHardwareInterface(name string) (string, []byte) { return "", nil }
diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go
new file mode 100644
index 000000000..0cbbcddbd
--- /dev/null
+++ b/vendor/github.com/google/uuid/node_net.go
@@ -0,0 +1,33 @@
+// Copyright 2017 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !js
+
+package uuid
+
+import "net"
+
+var interfaces []net.Interface // cached list of interfaces
+
+// getHardwareInterface returns the name and hardware address of interface name.
+// If name is "" then the name and hardware address of one of the system's
+// interfaces is returned. If no interfaces are found (name does not exist or
+// there are no interfaces) then "", nil is returned.
+//
+// Only addresses of at least 6 bytes are returned.
+func getHardwareInterface(name string) (string, []byte) {
+ if interfaces == nil {
+ var err error
+ interfaces, err = net.Interfaces()
+ if err != nil {
+ return "", nil
+ }
+ }
+ for _, ifs := range interfaces {
+ if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) {
+ return ifs.Name, ifs.HardwareAddr
+ }
+ }
+ return "", nil
+}
diff --git a/vendor/github.com/google/uuid/seq_test.go b/vendor/github.com/google/uuid/seq_test.go
new file mode 100644
index 000000000..4f6c54912
--- /dev/null
+++ b/vendor/github.com/google/uuid/seq_test.go
@@ -0,0 +1,66 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "flag"
+ "runtime"
+ "testing"
+ "time"
+)
+
+// This test is only run when --regressions is passed on the go test line.
+var regressions = flag.Bool("regressions", false, "run uuid regression tests")
+
+// TestClockSeqRace tests for a particular race condition of returning two
+// identical Version1 UUIDs. The duration of 1 minute was chosen as the race
+// condition, before being fixed, nearly always occurred in under 30 seconds.
+func TestClockSeqRace(t *testing.T) {
+ if !*regressions {
+ t.Skip("skipping regression tests")
+ }
+ duration := time.Minute
+
+ done := make(chan struct{})
+ defer close(done)
+
+ ch := make(chan UUID, 10000)
+ ncpu := runtime.NumCPU()
+ switch ncpu {
+ case 0, 1:
+ // We can't run the test effectively.
+ t.Skip("skipping race test, only one CPU detected")
+ return
+ default:
+ runtime.GOMAXPROCS(ncpu)
+ }
+ for i := 0; i < ncpu; i++ {
+ go func() {
+ for {
+ select {
+ case <-done:
+ return
+ case ch <- Must(NewUUID()):
+ }
+ }
+ }()
+ }
+
+ uuids := make(map[string]bool)
+ cnt := 0
+ start := time.Now()
+ for u := range ch {
+ s := u.String()
+ if uuids[s] {
+ t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s)
+ return
+ }
+ uuids[s] = true
+ if time.Since(start) > duration {
+ return
+ }
+ cnt++
+ }
+}
diff --git a/vendor/github.com/google/uuid/sql.go b/vendor/github.com/google/uuid/sql.go
new file mode 100644
index 000000000..2e02ec06c
--- /dev/null
+++ b/vendor/github.com/google/uuid/sql.go
@@ -0,0 +1,59 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "database/sql/driver"
+ "fmt"
+)
+
+// Scan implements sql.Scanner so UUIDs can be read from databases transparently.
+// Currently, database types that map to string and []byte are supported. Please
+// consult database-specific driver documentation for matching types.
+func (uuid *UUID) Scan(src interface{}) error {
+ switch src := src.(type) {
+ case nil:
+ return nil
+
+ case string:
+ // if an empty UUID comes from a table, we return a null UUID
+ if src == "" {
+ return nil
+ }
+
+ // see Parse for required string format
+ u, err := Parse(src)
+ if err != nil {
+ return fmt.Errorf("Scan: %v", err)
+ }
+
+ *uuid = u
+
+ case []byte:
+ // if an empty UUID comes from a table, we return a null UUID
+ if len(src) == 0 {
+ return nil
+ }
+
+ // assumes a simple slice of bytes if 16 bytes
+ // otherwise attempts to parse
+ if len(src) != 16 {
+ return uuid.Scan(string(src))
+ }
+ copy((*uuid)[:], src)
+
+ default:
+ return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
+ }
+
+ return nil
+}
+
+// Value implements sql.Valuer so that UUIDs can be written to databases
+// transparently. Currently, UUIDs map to strings. Please consult
+// database-specific driver documentation for matching types.
+func (uuid UUID) Value() (driver.Value, error) {
+ return uuid.String(), nil
+}
diff --git a/vendor/github.com/google/uuid/sql_test.go b/vendor/github.com/google/uuid/sql_test.go
new file mode 100644
index 000000000..1803dfd87
--- /dev/null
+++ b/vendor/github.com/google/uuid/sql_test.go
@@ -0,0 +1,113 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestScan(t *testing.T) {
+ stringTest := "f47ac10b-58cc-0372-8567-0e02b2c3d479"
+ badTypeTest := 6
+ invalidTest := "f47ac10b-58cc-0372-8567-0e02b2c3d4"
+
+ byteTest := make([]byte, 16)
+ byteTestUUID := Must(Parse(stringTest))
+ copy(byteTest, byteTestUUID[:])
+
+ // sunny day tests
+
+ var uuid UUID
+ err := (&uuid).Scan(stringTest)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = (&uuid).Scan([]byte(stringTest))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = (&uuid).Scan(byteTest)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // bad type tests
+
+ err = (&uuid).Scan(badTypeTest)
+ if err == nil {
+ t.Error("int correctly parsed and shouldn't have")
+ }
+ if !strings.Contains(err.Error(), "unable to scan type") {
+ t.Error("attempting to parse an int returned an incorrect error message")
+ }
+
+ // invalid/incomplete uuids
+
+ err = (&uuid).Scan(invalidTest)
+ if err == nil {
+ t.Error("invalid uuid was parsed without error")
+ }
+ if !strings.Contains(err.Error(), "invalid UUID") {
+ t.Error("attempting to parse an invalid UUID returned an incorrect error message")
+ }
+
+ err = (&uuid).Scan(byteTest[:len(byteTest)-2])
+ if err == nil {
+ t.Error("invalid byte uuid was parsed without error")
+ }
+ if !strings.Contains(err.Error(), "invalid UUID") {
+ t.Error("attempting to parse an invalid byte UUID returned an incorrect error message")
+ }
+
+ // empty tests
+
+ uuid = UUID{}
+ var emptySlice []byte
+ err = (&uuid).Scan(emptySlice)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, v := range uuid {
+ if v != 0 {
+ t.Error("UUID was not nil after scanning empty byte slice")
+ }
+ }
+
+ uuid = UUID{}
+ var emptyString string
+ err = (&uuid).Scan(emptyString)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, v := range uuid {
+ if v != 0 {
+ t.Error("UUID was not nil after scanning empty byte slice")
+ }
+ }
+
+ uuid = UUID{}
+ err = (&uuid).Scan(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, v := range uuid {
+ if v != 0 {
+ t.Error("UUID was not nil after scanning nil")
+ }
+ }
+}
+
+func TestValue(t *testing.T) {
+ stringTest := "f47ac10b-58cc-0372-8567-0e02b2c3d479"
+ uuid := Must(Parse(stringTest))
+ val, _ := uuid.Value()
+ if val != stringTest {
+ t.Error("Value() did not return expected string")
+ }
+}
diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go
new file mode 100644
index 000000000..e6ef06cdc
--- /dev/null
+++ b/vendor/github.com/google/uuid/time.go
@@ -0,0 +1,123 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+ "sync"
+ "time"
+)
+
+// A Time represents a time as the number of 100's of nanoseconds since 15 Oct
+// 1582.
+type Time int64
+
+const (
+ lillian = 2299160 // Julian day of 15 Oct 1582
+ unix = 2440587 // Julian day of 1 Jan 1970
+ epoch = unix - lillian // Days between epochs
+ g1582 = epoch * 86400 // seconds between epochs
+ g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs
+)
+
+var (
+ timeMu sync.Mutex
+ lasttime uint64 // last time we returned
+ clockSeq uint16 // clock sequence for this run
+
+ timeNow = time.Now // for testing
+)
+
+// UnixTime converts t the number of seconds and nanoseconds using the Unix
+// epoch of 1 Jan 1970.
+func (t Time) UnixTime() (sec, nsec int64) {
+ sec = int64(t - g1582ns100)
+ nsec = (sec % 10000000) * 100
+ sec /= 10000000
+ return sec, nsec
+}
+
+// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and
+// clock sequence as well as adjusting the clock sequence as needed. An error
+// is returned if the current time cannot be determined.
+func GetTime() (Time, uint16, error) {
+ defer timeMu.Unlock()
+ timeMu.Lock()
+ return getTime()
+}
+
+func getTime() (Time, uint16, error) {
+ t := timeNow()
+
+ // If we don't have a clock sequence already, set one.
+ if clockSeq == 0 {
+ setClockSequence(-1)
+ }
+ now := uint64(t.UnixNano()/100) + g1582ns100
+
+ // If time has gone backwards with this clock sequence then we
+ // increment the clock sequence
+ if now <= lasttime {
+ clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000
+ }
+ lasttime = now
+ return Time(now), clockSeq, nil
+}
+
+// ClockSequence returns the current clock sequence, generating one if not
+// already set. The clock sequence is only used for Version 1 UUIDs.
+//
+// The uuid package does not use global static storage for the clock sequence or
+// the last time a UUID was generated. Unless SetClockSequence is used, a new
+// random clock sequence is generated the first time a clock sequence is
+// requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1)
+func ClockSequence() int {
+ defer timeMu.Unlock()
+ timeMu.Lock()
+ return clockSequence()
+}
+
+func clockSequence() int {
+ if clockSeq == 0 {
+ setClockSequence(-1)
+ }
+ return int(clockSeq & 0x3fff)
+}
+
+// SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to
+// -1 causes a new sequence to be generated.
+func SetClockSequence(seq int) {
+ defer timeMu.Unlock()
+ timeMu.Lock()
+ setClockSequence(seq)
+}
+
+func setClockSequence(seq int) {
+ if seq == -1 {
+ var b [2]byte
+ randomBits(b[:]) // clock sequence
+ seq = int(b[0])<<8 | int(b[1])
+ }
+ oldSeq := clockSeq
+ clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant
+ if oldSeq != clockSeq {
+ lasttime = 0
+ }
+}
+
+// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in
+// uuid. The time is only defined for version 1 and 2 UUIDs.
+func (uuid UUID) Time() Time {
+ time := int64(binary.BigEndian.Uint32(uuid[0:4]))
+ time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32
+ time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48
+ return Time(time)
+}
+
+// ClockSequence returns the clock sequence encoded in uuid.
+// The clock sequence is only well defined for version 1 and 2 UUIDs.
+func (uuid UUID) ClockSequence() int {
+ return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff
+}
diff --git a/vendor/github.com/google/uuid/util.go b/vendor/github.com/google/uuid/util.go
new file mode 100644
index 000000000..5ea6c7378
--- /dev/null
+++ b/vendor/github.com/google/uuid/util.go
@@ -0,0 +1,43 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "io"
+)
+
+// randomBits completely fills slice b with random data.
+func randomBits(b []byte) {
+ if _, err := io.ReadFull(rander, b); err != nil {
+ panic(err.Error()) // rand should never fail
+ }
+}
+
+// xvalues returns the value of a byte as a hexadecimal digit or 255.
+var xvalues = [256]byte{
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+}
+
+// xtob converts hex characters x1 and x2 into a byte.
+func xtob(x1, x2 byte) (byte, bool) {
+ b1 := xvalues[x1]
+ b2 := xvalues[x2]
+ return (b1 << 4) | b2, b1 != 255 && b2 != 255
+}
diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go
new file mode 100644
index 000000000..60d26bb50
--- /dev/null
+++ b/vendor/github.com/google/uuid/uuid.go
@@ -0,0 +1,251 @@
+// Copyright 2018 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
+// 4122.
+type UUID [16]byte
+
+// A Version represents a UUID's version.
+type Version byte
+
+// A Variant represents a UUID's variant.
+type Variant byte
+
+// Constants returned by Variant.
+const (
+ Invalid = Variant(iota) // Invalid UUID
+ RFC4122 // The variant specified in RFC4122
+ Reserved // Reserved, NCS backward compatibility.
+ Microsoft // Reserved, Microsoft Corporation backward compatibility.
+ Future // Reserved for future definition.
+)
+
+var rander = rand.Reader // random function
+
+type invalidLengthError struct{ len int }
+
+func (err invalidLengthError) Error() string {
+ return fmt.Sprintf("invalid UUID length: %d", err.len)
+}
+
+// Parse decodes s into a UUID or returns an error. Both the standard UUID
+// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
+// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
+// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
+// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
+func Parse(s string) (UUID, error) {
+ var uuid UUID
+ switch len(s) {
+ // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+ case 36:
+
+ // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+ case 36 + 9:
+ if strings.ToLower(s[:9]) != "urn:uuid:" {
+ return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
+ }
+ s = s[9:]
+
+ // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
+ case 36 + 2:
+ s = s[1:]
+
+ // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ case 32:
+ var ok bool
+ for i := range uuid {
+ uuid[i], ok = xtob(s[i*2], s[i*2+1])
+ if !ok {
+ return uuid, errors.New("invalid UUID format")
+ }
+ }
+ return uuid, nil
+ default:
+ return uuid, invalidLengthError{len(s)}
+ }
+ // s is now at least 36 bytes long
+ // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+ if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
+ return uuid, errors.New("invalid UUID format")
+ }
+ for i, x := range [16]int{
+ 0, 2, 4, 6,
+ 9, 11,
+ 14, 16,
+ 19, 21,
+ 24, 26, 28, 30, 32, 34} {
+ v, ok := xtob(s[x], s[x+1])
+ if !ok {
+ return uuid, errors.New("invalid UUID format")
+ }
+ uuid[i] = v
+ }
+ return uuid, nil
+}
+
+// ParseBytes is like Parse, except it parses a byte slice instead of a string.
+func ParseBytes(b []byte) (UUID, error) {
+ var uuid UUID
+ switch len(b) {
+ case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+ case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+ if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) {
+ return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9])
+ }
+ b = b[9:]
+ case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
+ b = b[1:]
+ case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+ var ok bool
+ for i := 0; i < 32; i += 2 {
+ uuid[i/2], ok = xtob(b[i], b[i+1])
+ if !ok {
+ return uuid, errors.New("invalid UUID format")
+ }
+ }
+ return uuid, nil
+ default:
+ return uuid, invalidLengthError{len(b)}
+ }
+ // s is now at least 36 bytes long
+ // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+ if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' {
+ return uuid, errors.New("invalid UUID format")
+ }
+ for i, x := range [16]int{
+ 0, 2, 4, 6,
+ 9, 11,
+ 14, 16,
+ 19, 21,
+ 24, 26, 28, 30, 32, 34} {
+ v, ok := xtob(b[x], b[x+1])
+ if !ok {
+ return uuid, errors.New("invalid UUID format")
+ }
+ uuid[i] = v
+ }
+ return uuid, nil
+}
+
+// MustParse is like Parse but panics if the string cannot be parsed.
+// It simplifies safe initialization of global variables holding compiled UUIDs.
+func MustParse(s string) UUID {
+ uuid, err := Parse(s)
+ if err != nil {
+ panic(`uuid: Parse(` + s + `): ` + err.Error())
+ }
+ return uuid
+}
+
+// FromBytes creates a new UUID from a byte slice. Returns an error if the slice
+// does not have a length of 16. The bytes are copied from the slice.
+func FromBytes(b []byte) (uuid UUID, err error) {
+ err = uuid.UnmarshalBinary(b)
+ return uuid, err
+}
+
+// Must returns uuid if err is nil and panics otherwise.
+func Must(uuid UUID, err error) UUID {
+ if err != nil {
+ panic(err)
+ }
+ return uuid
+}
+
+// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+// , or "" if uuid is invalid.
+func (uuid UUID) String() string {
+ var buf [36]byte
+ encodeHex(buf[:], uuid)
+ return string(buf[:])
+}
+
+// URN returns the RFC 2141 URN form of uuid,
+// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
+func (uuid UUID) URN() string {
+ var buf [36 + 9]byte
+ copy(buf[:], "urn:uuid:")
+ encodeHex(buf[9:], uuid)
+ return string(buf[:])
+}
+
+func encodeHex(dst []byte, uuid UUID) {
+ hex.Encode(dst, uuid[:4])
+ dst[8] = '-'
+ hex.Encode(dst[9:13], uuid[4:6])
+ dst[13] = '-'
+ hex.Encode(dst[14:18], uuid[6:8])
+ dst[18] = '-'
+ hex.Encode(dst[19:23], uuid[8:10])
+ dst[23] = '-'
+ hex.Encode(dst[24:], uuid[10:])
+}
+
+// Variant returns the variant encoded in uuid.
+func (uuid UUID) Variant() Variant {
+ switch {
+ case (uuid[8] & 0xc0) == 0x80:
+ return RFC4122
+ case (uuid[8] & 0xe0) == 0xc0:
+ return Microsoft
+ case (uuid[8] & 0xe0) == 0xe0:
+ return Future
+ default:
+ return Reserved
+ }
+}
+
+// Version returns the version of uuid.
+func (uuid UUID) Version() Version {
+ return Version(uuid[6] >> 4)
+}
+
+func (v Version) String() string {
+ if v > 15 {
+ return fmt.Sprintf("BAD_VERSION_%d", v)
+ }
+ return fmt.Sprintf("VERSION_%d", v)
+}
+
+func (v Variant) String() string {
+ switch v {
+ case RFC4122:
+ return "RFC4122"
+ case Reserved:
+ return "Reserved"
+ case Microsoft:
+ return "Microsoft"
+ case Future:
+ return "Future"
+ case Invalid:
+ return "Invalid"
+ }
+ return fmt.Sprintf("BadVariant%d", int(v))
+}
+
+// SetRand sets the random number generator to r, which implements io.Reader.
+// If r.Read returns an error when the package requests random data then
+// a panic will be issued.
+//
+// Calling SetRand with nil sets the random number generator to the default
+// generator.
+func SetRand(r io.Reader) {
+ if r == nil {
+ rander = rand.Reader
+ return
+ }
+ rander = r
+}
diff --git a/vendor/github.com/google/uuid/uuid_test.go b/vendor/github.com/google/uuid/uuid_test.go
new file mode 100644
index 000000000..709e34c66
--- /dev/null
+++ b/vendor/github.com/google/uuid/uuid_test.go
@@ -0,0 +1,636 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+ "unsafe"
+)
+
+type test struct {
+ in string
+ version Version
+ variant Variant
+ isuuid bool
+}
+
+var tests = []test{
+ {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true},
+ {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true},
+ {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true},
+ {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true},
+ {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true},
+ {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true},
+ {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true},
+ {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true},
+ {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true},
+ {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true},
+ {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true},
+ {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true},
+ {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true},
+ {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true},
+ {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true},
+
+ {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
+ {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true},
+ {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true},
+ {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true},
+ {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true},
+
+ {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false},
+ {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false},
+
+ {"{f47ac10b-58cc-0372-8567-0e02b2c3d479}", 0, RFC4122, true},
+ {"{f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-0372-8567-0e02b2c3d479}", 0, Invalid, false},
+
+ {"f47ac10b58cc037285670e02b2c3d479", 0, RFC4122, true},
+ {"f47ac10b58cc037285670e02b2c3d4790", 0, Invalid, false},
+ {"f47ac10b58cc037285670e02b2c3d47", 0, Invalid, false},
+}
+
+var constants = []struct {
+ c interface{}
+ name string
+}{
+ {Person, "Person"},
+ {Group, "Group"},
+ {Org, "Org"},
+ {Invalid, "Invalid"},
+ {RFC4122, "RFC4122"},
+ {Reserved, "Reserved"},
+ {Microsoft, "Microsoft"},
+ {Future, "Future"},
+ {Domain(17), "Domain17"},
+ {Variant(42), "BadVariant42"},
+}
+
+func testTest(t *testing.T, in string, tt test) {
+ uuid, err := Parse(in)
+ if ok := (err == nil); ok != tt.isuuid {
+ t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid)
+ }
+ if err != nil {
+ return
+ }
+
+ if v := uuid.Variant(); v != tt.variant {
+ t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant)
+ }
+ if v := uuid.Version(); v != tt.version {
+ t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version)
+ }
+}
+
+func testBytes(t *testing.T, in []byte, tt test) {
+ uuid, err := ParseBytes(in)
+ if ok := (err == nil); ok != tt.isuuid {
+ t.Errorf("ParseBytes(%s) got %v expected %v\b", in, ok, tt.isuuid)
+ }
+ if err != nil {
+ return
+ }
+ suuid, _ := Parse(string(in))
+ if uuid != suuid {
+ t.Errorf("ParseBytes(%s) got %v expected %v\b", in, uuid, suuid)
+ }
+}
+
+func TestUUID(t *testing.T) {
+ for _, tt := range tests {
+ testTest(t, tt.in, tt)
+ testTest(t, strings.ToUpper(tt.in), tt)
+ testBytes(t, []byte(tt.in), tt)
+ }
+}
+
+func TestFromBytes(t *testing.T) {
+ b := []byte{
+ 0x7d, 0x44, 0x48, 0x40,
+ 0x9d, 0xc0,
+ 0x11, 0xd1,
+ 0xb2, 0x45,
+ 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2,
+ }
+ uuid, err := FromBytes(b)
+ if err != nil {
+ t.Fatalf("%s", err)
+ }
+ for i := 0; i < len(uuid); i++ {
+ if b[i] != uuid[i] {
+ t.Fatalf("FromBytes() got %v expected %v\b", uuid[:], b)
+ }
+ }
+}
+
+func TestConstants(t *testing.T) {
+ for x, tt := range constants {
+ v, ok := tt.c.(fmt.Stringer)
+ if !ok {
+ t.Errorf("%x: %v: not a stringer", x, v)
+ } else if s := v.String(); s != tt.name {
+ v, _ := tt.c.(int)
+ t.Errorf("%x: Constant %T:%d gives %q, expected %q", x, tt.c, v, s, tt.name)
+ }
+ }
+}
+
+func TestRandomUUID(t *testing.T) {
+ m := make(map[string]bool)
+ for x := 1; x < 32; x++ {
+ uuid := New()
+ s := uuid.String()
+ if m[s] {
+ t.Errorf("NewRandom returned duplicated UUID %s", s)
+ }
+ m[s] = true
+ if v := uuid.Version(); v != 4 {
+ t.Errorf("Random UUID of version %s", v)
+ }
+ if uuid.Variant() != RFC4122 {
+ t.Errorf("Random UUID is variant %d", uuid.Variant())
+ }
+ }
+}
+
+func TestNew(t *testing.T) {
+ m := make(map[UUID]bool)
+ for x := 1; x < 32; x++ {
+ s := New()
+ if m[s] {
+ t.Errorf("New returned duplicated UUID %s", s)
+ }
+ m[s] = true
+ uuid, err := Parse(s.String())
+ if err != nil {
+ t.Errorf("New.String() returned %q which does not decode", s)
+ continue
+ }
+ if v := uuid.Version(); v != 4 {
+ t.Errorf("Random UUID of version %s", v)
+ }
+ if uuid.Variant() != RFC4122 {
+ t.Errorf("Random UUID is variant %d", uuid.Variant())
+ }
+ }
+}
+
+func TestClockSeq(t *testing.T) {
+ // Fake time.Now for this test to return a monotonically advancing time; restore it at end.
+ defer func(orig func() time.Time) { timeNow = orig }(timeNow)
+ monTime := time.Now()
+ timeNow = func() time.Time {
+ monTime = monTime.Add(1 * time.Second)
+ return monTime
+ }
+
+ SetClockSequence(-1)
+ uuid1, err := NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+ uuid2, err := NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+
+ if s1, s2 := uuid1.ClockSequence(), uuid2.ClockSequence(); s1 != s2 {
+ t.Errorf("clock sequence %d != %d", s1, s2)
+ }
+
+ SetClockSequence(-1)
+ uuid2, err = NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+
+ // Just on the very off chance we generated the same sequence
+ // two times we try again.
+ if uuid1.ClockSequence() == uuid2.ClockSequence() {
+ SetClockSequence(-1)
+ uuid2, err = NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+ }
+ if s1, s2 := uuid1.ClockSequence(), uuid2.ClockSequence(); s1 == s2 {
+ t.Errorf("Duplicate clock sequence %d", s1)
+ }
+
+ SetClockSequence(0x1234)
+ uuid1, err = NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+ if seq := uuid1.ClockSequence(); seq != 0x1234 {
+ t.Errorf("%s: expected seq 0x1234 got 0x%04x", uuid1, seq)
+ }
+}
+
+func TestCoding(t *testing.T) {
+ text := "7d444840-9dc0-11d1-b245-5ffdce74fad2"
+ urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2"
+ data := UUID{
+ 0x7d, 0x44, 0x48, 0x40,
+ 0x9d, 0xc0,
+ 0x11, 0xd1,
+ 0xb2, 0x45,
+ 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2,
+ }
+ if v := data.String(); v != text {
+ t.Errorf("%x: encoded to %s, expected %s", data, v, text)
+ }
+ if v := data.URN(); v != urn {
+ t.Errorf("%x: urn is %s, expected %s", data, v, urn)
+ }
+
+ uuid, err := Parse(text)
+ if err != nil {
+ t.Errorf("Parse returned unexpected error %v", err)
+ }
+ if data != uuid {
+ t.Errorf("%s: decoded to %s, expected %s", text, uuid, data)
+ }
+}
+
+func TestVersion1(t *testing.T) {
+ uuid1, err := NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+ uuid2, err := NewUUID()
+ if err != nil {
+ t.Fatalf("could not create UUID: %v", err)
+ }
+
+ if uuid1 == uuid2 {
+ t.Errorf("%s:duplicate uuid", uuid1)
+ }
+ if v := uuid1.Version(); v != 1 {
+ t.Errorf("%s: version %s expected 1", uuid1, v)
+ }
+ if v := uuid2.Version(); v != 1 {
+ t.Errorf("%s: version %s expected 1", uuid2, v)
+ }
+ n1 := uuid1.NodeID()
+ n2 := uuid2.NodeID()
+ if !bytes.Equal(n1, n2) {
+ t.Errorf("Different nodes %x != %x", n1, n2)
+ }
+ t1 := uuid1.Time()
+ t2 := uuid2.Time()
+ q1 := uuid1.ClockSequence()
+ q2 := uuid2.ClockSequence()
+
+ switch {
+ case t1 == t2 && q1 == q2:
+ t.Error("time stopped")
+ case t1 > t2 && q1 == q2:
+ t.Error("time reversed")
+ case t1 < t2 && q1 != q2:
+ t.Error("clock sequence changed unexpectedly")
+ }
+}
+
+func TestNode(t *testing.T) {
+ // This test is mostly to make sure we don't leave nodeMu locked.
+ ifname = ""
+ if ni := NodeInterface(); ni != "" {
+ t.Errorf("NodeInterface got %q, want %q", ni, "")
+ }
+ if SetNodeInterface("xyzzy") {
+ t.Error("SetNodeInterface succeeded on a bad interface name")
+ }
+ if !SetNodeInterface("") {
+ t.Error("SetNodeInterface failed")
+ }
+ if runtime.GOARCH != "js" {
+ if ni := NodeInterface(); ni == "" {
+ t.Error("NodeInterface returned an empty string")
+ }
+ }
+
+ ni := NodeID()
+ if len(ni) != 6 {
+ t.Errorf("ni got %d bytes, want 6", len(ni))
+ }
+ hasData := false
+ for _, b := range ni {
+ if b != 0 {
+ hasData = true
+ }
+ }
+ if !hasData {
+ t.Error("nodeid is all zeros")
+ }
+
+ id := []byte{1, 2, 3, 4, 5, 6, 7, 8}
+ SetNodeID(id)
+ ni = NodeID()
+ if !bytes.Equal(ni, id[:6]) {
+ t.Errorf("got nodeid %v, want %v", ni, id[:6])
+ }
+
+ if ni := NodeInterface(); ni != "user" {
+ t.Errorf("got interface %q, want %q", ni, "user")
+ }
+}
+
+func TestNodeAndTime(t *testing.T) {
+ // Time is February 5, 1998 12:30:23.136364800 AM GMT
+
+ uuid, err := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2")
+ if err != nil {
+ t.Fatalf("Parser returned unexpected error %v", err)
+ }
+ node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2}
+
+ ts := uuid.Time()
+ c := time.Unix(ts.UnixTime())
+ want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC)
+ if !c.Equal(want) {
+ t.Errorf("Got time %v, want %v", c, want)
+ }
+ if !bytes.Equal(node, uuid.NodeID()) {
+ t.Errorf("Expected node %v got %v", node, uuid.NodeID())
+ }
+}
+
+func TestMD5(t *testing.T) {
+ uuid := NewMD5(NameSpaceDNS, []byte("python.org")).String()
+ want := "6fa459ea-ee8a-3ca4-894e-db77e160355e"
+ if uuid != want {
+ t.Errorf("MD5: got %q expected %q", uuid, want)
+ }
+}
+
+func TestSHA1(t *testing.T) {
+ uuid := NewSHA1(NameSpaceDNS, []byte("python.org")).String()
+ want := "886313e1-3b8a-5372-9b90-0c9aee199e5d"
+ if uuid != want {
+ t.Errorf("SHA1: got %q expected %q", uuid, want)
+ }
+}
+
+func TestNodeID(t *testing.T) {
+ nid := []byte{1, 2, 3, 4, 5, 6}
+ SetNodeInterface("")
+ s := NodeInterface()
+ if runtime.GOARCH != "js" {
+ if s == "" || s == "user" {
+ t.Errorf("NodeInterface %q after SetInterface", s)
+ }
+ }
+ node1 := NodeID()
+ if node1 == nil {
+ t.Error("NodeID nil after SetNodeInterface", s)
+ }
+ SetNodeID(nid)
+ s = NodeInterface()
+ if s != "user" {
+ t.Errorf("Expected NodeInterface %q got %q", "user", s)
+ }
+ node2 := NodeID()
+ if node2 == nil {
+ t.Error("NodeID nil after SetNodeID", s)
+ }
+ if bytes.Equal(node1, node2) {
+ t.Error("NodeID not changed after SetNodeID", s)
+ } else if !bytes.Equal(nid, node2) {
+ t.Errorf("NodeID is %x, expected %x", node2, nid)
+ }
+}
+
+func testDCE(t *testing.T, name string, uuid UUID, err error, domain Domain, id uint32) {
+ if err != nil {
+ t.Errorf("%s failed: %v", name, err)
+ return
+ }
+ if v := uuid.Version(); v != 2 {
+ t.Errorf("%s: %s: expected version 2, got %s", name, uuid, v)
+ return
+ }
+ if v := uuid.Domain(); v != domain {
+ t.Errorf("%s: %s: expected domain %d, got %d", name, uuid, domain, v)
+ }
+ if v := uuid.ID(); v != id {
+ t.Errorf("%s: %s: expected id %d, got %d", name, uuid, id, v)
+ }
+}
+
+func TestDCE(t *testing.T) {
+ uuid, err := NewDCESecurity(42, 12345678)
+ testDCE(t, "NewDCESecurity", uuid, err, 42, 12345678)
+ uuid, err = NewDCEPerson()
+ testDCE(t, "NewDCEPerson", uuid, err, Person, uint32(os.Getuid()))
+ uuid, err = NewDCEGroup()
+ testDCE(t, "NewDCEGroup", uuid, err, Group, uint32(os.Getgid()))
+}
+
+type badRand struct{}
+
+func (r badRand) Read(buf []byte) (int, error) {
+ for i := range buf {
+ buf[i] = byte(i)
+ }
+ return len(buf), nil
+}
+
+func TestBadRand(t *testing.T) {
+ SetRand(badRand{})
+ uuid1 := New()
+ uuid2 := New()
+ if uuid1 != uuid2 {
+ t.Errorf("expected duplicates, got %q and %q", uuid1, uuid2)
+ }
+ SetRand(nil)
+ uuid1 = New()
+ uuid2 = New()
+ if uuid1 == uuid2 {
+ t.Errorf("unexpected duplicates, got %q", uuid1)
+ }
+}
+
+func TestSetRand(t *testing.T) {
+ myString := "805-9dd6-1a877cb526c678e71d38-7122-44c0-9b7c-04e7001cc78783ac3e82-47a3-4cc3-9951-13f3339d88088f5d685a-11f7-4078-ada9-de44ad2daeb7"
+
+ SetRand(strings.NewReader(myString))
+ uuid1 := New()
+ uuid2 := New()
+
+ SetRand(strings.NewReader(myString))
+ uuid3 := New()
+ uuid4 := New()
+
+ if uuid1 != uuid3 {
+ t.Errorf("expected duplicates, got %q and %q", uuid1, uuid3)
+ }
+ if uuid2 != uuid4 {
+ t.Errorf("expected duplicates, got %q and %q", uuid2, uuid4)
+ }
+}
+
+func TestRandomFromReader(t *testing.T) {
+ myString := "8059ddhdle77cb52"
+ r := bytes.NewReader([]byte(myString))
+ r2 := bytes.NewReader([]byte(myString))
+ uuid1, err := NewRandomFromReader(r)
+ if err != nil {
+ t.Errorf("failed generating UUID from a reader")
+ }
+ _, err = NewRandomFromReader(r)
+ if err == nil {
+ t.Errorf("expecting an error as reader has no more bytes. Got uuid. NewRandomFromReader may not be using the provided reader")
+ }
+ uuid3, err := NewRandomFromReader(r2)
+ if err != nil {
+ t.Errorf("failed generating UUID from a reader")
+ }
+ if uuid1 != uuid3 {
+ t.Errorf("expected duplicates, got %q and %q", uuid1, uuid3)
+ }
+}
+
+func TestWrongLength(t *testing.T) {
+ _, err := Parse("12345")
+ if err == nil {
+ t.Errorf("expected ‘12345’ was invalid")
+ } else if err.Error() != "invalid UUID length: 5" {
+ t.Errorf("expected a different error message for an invalid length")
+ }
+}
+
+var asString = "f47ac10b-58cc-0372-8567-0e02b2c3d479"
+var asBytes = []byte(asString)
+
+func BenchmarkParse(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _, err := Parse(asString)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkParseBytes(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _, err := ParseBytes(asBytes)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+// parseBytesUnsafe is to benchmark using unsafe.
+func parseBytesUnsafe(b []byte) (UUID, error) {
+ return Parse(*(*string)(unsafe.Pointer(&b)))
+}
+
+func BenchmarkParseBytesUnsafe(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _, err := parseBytesUnsafe(asBytes)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+// parseBytesCopy is to benchmark not using unsafe.
+func parseBytesCopy(b []byte) (UUID, error) {
+ return Parse(string(b))
+}
+
+func BenchmarkParseBytesCopy(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ _, err := parseBytesCopy(asBytes)
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkNew(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ New()
+ }
+}
+
+func BenchmarkUUID_String(b *testing.B) {
+ uuid, err := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
+ if err != nil {
+ b.Fatal(err)
+ }
+ for i := 0; i < b.N; i++ {
+ if uuid.String() == "" {
+ b.Fatal("invalid uuid")
+ }
+ }
+}
+
+func BenchmarkUUID_URN(b *testing.B) {
+ uuid, err := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
+ if err != nil {
+ b.Fatal(err)
+ }
+ for i := 0; i < b.N; i++ {
+ if uuid.URN() == "" {
+ b.Fatal("invalid uuid")
+ }
+ }
+}
+
+func BenchmarkParseBadLength(b *testing.B) {
+ short := asString[:10]
+ for i := 0; i < b.N; i++ {
+ _, err := Parse(short)
+ if err == nil {
+ b.Fatalf("expected ‘%s’ was invalid", short)
+ }
+ }
+}
+
+func BenchmarkParseLen32Truncated(b *testing.B) {
+ partial := asString[:len(asString)-4]
+ for i := 0; i < b.N; i++ {
+ _, err := Parse(partial)
+ if err == nil {
+ b.Fatalf("expected ‘%s’ was invalid", partial)
+ }
+ }
+}
+
+func BenchmarkParseLen36Corrupted(b *testing.B) {
+ wrong := asString[:len(asString)-1] + "x"
+ for i := 0; i < b.N; i++ {
+ _, err := Parse(wrong)
+ if err == nil {
+ b.Fatalf("expected ‘%s’ was invalid", wrong)
+ }
+ }
+}
diff --git a/vendor/github.com/google/uuid/version1.go b/vendor/github.com/google/uuid/version1.go
new file mode 100644
index 000000000..463109629
--- /dev/null
+++ b/vendor/github.com/google/uuid/version1.go
@@ -0,0 +1,44 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+)
+
+// NewUUID returns a Version 1 UUID based on the current NodeID and clock
+// sequence, and the current time. If the NodeID has not been set by SetNodeID
+// or SetNodeInterface then it will be set automatically. If the NodeID cannot
+// be set NewUUID returns nil. If clock sequence has not been set by
+// SetClockSequence then it will be set automatically. If GetTime fails to
+// return the current NewUUID returns nil and an error.
+//
+// In most cases, New should be used.
+func NewUUID() (UUID, error) {
+ var uuid UUID
+ now, seq, err := GetTime()
+ if err != nil {
+ return uuid, err
+ }
+
+ timeLow := uint32(now & 0xffffffff)
+ timeMid := uint16((now >> 32) & 0xffff)
+ timeHi := uint16((now >> 48) & 0x0fff)
+ timeHi |= 0x1000 // Version 1
+
+ binary.BigEndian.PutUint32(uuid[0:], timeLow)
+ binary.BigEndian.PutUint16(uuid[4:], timeMid)
+ binary.BigEndian.PutUint16(uuid[6:], timeHi)
+ binary.BigEndian.PutUint16(uuid[8:], seq)
+
+ nodeMu.Lock()
+ if nodeID == zeroID {
+ setNodeInterface("")
+ }
+ copy(uuid[10:], nodeID[:])
+ nodeMu.Unlock()
+
+ return uuid, nil
+}
diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go
new file mode 100644
index 000000000..c110465db
--- /dev/null
+++ b/vendor/github.com/google/uuid/version4.go
@@ -0,0 +1,43 @@
+// Copyright 2016 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import "io"
+
+// New creates a new random UUID or panics. New is equivalent to
+// the expression
+//
+// uuid.Must(uuid.NewRandom())
+func New() UUID {
+ return Must(NewRandom())
+}
+
+// NewRandom returns a Random (Version 4) UUID.
+//
+// The strength of the UUIDs is based on the strength of the crypto/rand
+// package.
+//
+// A note about uniqueness derived from the UUID Wikipedia entry:
+//
+// Randomly generated UUIDs have 122 random bits. One's annual risk of being
+// hit by a meteorite is estimated to be one chance in 17 billion, that
+// means the probability is about 0.00000000006 (6 × 10−11),
+// equivalent to the odds of creating a few tens of trillions of UUIDs in a
+// year and having one duplicate.
+func NewRandom() (UUID, error) {
+ return NewRandomFromReader(rander)
+}
+
+// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
+func NewRandomFromReader(r io.Reader) (UUID, error) {
+ var uuid UUID
+ _, err := io.ReadFull(r, uuid[:])
+ if err != nil {
+ return Nil, err
+ }
+ uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
+ uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
+ return uuid, nil
+}
diff --git a/vendor/github.com/karalabe/usb/.travis.yml b/vendor/github.com/karalabe/usb/.travis.yml
new file mode 100644
index 000000000..7f925fbc0
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/.travis.yml
@@ -0,0 +1,49 @@
+language: go
+
+matrix:
+ include:
+ - os: linux
+ dist: trusty
+ go: 1.5.x
+ - os: linux
+ dist: trusty
+ go: 1.6.x
+ - os: linux
+ dist: trusty
+ go: 1.7.x
+ - os: linux
+ dist: trusty
+ go: 1.8.x
+ - os: linux
+ dist: trusty
+ go: 1.9.x
+ - os: linux
+ dist: xenial
+ go: 1.9.x
+ - os: linux
+ dist: xenial
+ go: 1.10.x
+ - os: linux
+ dist: xenial
+ go: 1.11.x
+ - os: linux
+ dist: xenial
+ go: 1.12.x
+ - os: osx
+ go: 1.12.x
+ - os: linux
+ dist: bionic
+ go: 1.13.x
+ services:
+ - docker
+ env:
+ - docker
+ script:
+ - docker build -f Dockerfile.ubuntu .
+ - docker build -f Dockerfile.alpine .
+
+script:
+ - go install ./...
+ - go test -v ./...
+ - CGO_ENABLED=0 go install ./...
+ - CGO_ENABLED=0 go test -v ./...
diff --git a/vendor/github.com/karalabe/usb/AUTHORS b/vendor/github.com/karalabe/usb/AUTHORS
new file mode 100644
index 000000000..bae45b3ec
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/AUTHORS
@@ -0,0 +1,7 @@
+Felix Lange
+Guillaume Ballet
+Jakob Weisblat
+Martin Holst Swende
+Mateusz Mikołajczyk
+Péter Szilágyi
+Rosen Penev
diff --git a/vendor/github.com/karalabe/usb/Dockerfile.alpine b/vendor/github.com/karalabe/usb/Dockerfile.alpine
new file mode 100644
index 000000000..342bdf79a
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/Dockerfile.alpine
@@ -0,0 +1,6 @@
+FROM golang:alpine
+
+RUN apk add --no-cache git gcc musl-dev linux-headers
+
+ADD . $GOPATH/src/github.com/karalabe/usb
+RUN cd $GOPATH/src/github.com/karalabe/usb && go install
diff --git a/vendor/github.com/karalabe/usb/Dockerfile.ubuntu b/vendor/github.com/karalabe/usb/Dockerfile.ubuntu
new file mode 100644
index 000000000..b861e497b
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/Dockerfile.ubuntu
@@ -0,0 +1,4 @@
+FROM golang:latest
+
+ADD . $GOPATH/src/github.com/karalabe/usb
+RUN cd $GOPATH/src/github.com/karalabe/usb && go install
diff --git a/vendor/github.com/karalabe/usb/LICENSE b/vendor/github.com/karalabe/usb/LICENSE
new file mode 100644
index 000000000..65c5ca88a
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/vendor/github.com/karalabe/usb/README.md b/vendor/github.com/karalabe/usb/README.md
new file mode 100644
index 000000000..b6920f51a
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/README.md
@@ -0,0 +1,47 @@
+[![Travis][travisimg]][travisurl]
+[![AppVeyor][appveyorimg]][appveyorurl]
+[![GoDoc][docimg]][docurl]
+
+[travisimg]: https://travis-ci.org/karalabe/usb.svg?branch=master
+[travisurl]: https://travis-ci.org/karalabe/usb
+[appveyorimg]: https://ci.appveyor.com/api/projects/status/u96eq262bj2itprh/branch/master?svg=true
+[appveyorurl]: https://ci.appveyor.com/project/karalabe/usb
+[docimg]: https://godoc.org/github.com/karalabe/usb?status.svg
+[docurl]: https://godoc.org/github.com/karalabe/usb
+
+# Yet another USB library for Go
+
+The `usb` package is a cross platform, fully self-contained library for accessing and communicating with USB devices **either via HID or low level interrupts**. The goal of the library was to create a simple way to find-, attach to- and read/write form USB devices.
+
+There are multiple already existing USB libraries:
+
+ * The original `gousb` package [created by @kylelemons](https://github.com/kylelemons/gousb) and nowadays [maintained by @google](https://github.com/google/gousb) is a CGO wrapper around `libusb`. It is the most advanced USB library for Go out there.
+ * Unfortunately, `gousb` requires the `libusb` C library to be installed both during build as well as during runtime on the host operating system. This breaks binary portability and also adds unnecessary hurdles on Windows.
+ * Furthermore, whilst HID devices are supported by `libusb`, the OS on Macos and Windows explicitly takes over these devices, so only native system calls can be used on recent versions (i.e. you **cannot** use `libusb` for HID).
+ * There is a fork of `gousb` [created by @karalabe](https://github.com/karalabe/gousb) that statically linked `libusb` during build, but with the lack of HID access, that work was abandoned.
+ * For HID-only devices, a previous self-contained package was created at [`github.com/karalabe/hid`](https://github.com/karalabe/hid), which worked well for hardware wallet uses cases in [`go-ethereum`](https://github.com/ethereum/go-ethereum). It's a simple package that does it's thing well.
+ * Unfortunately, `hid` is not capable of talking to generic USB devices. When multiple different devices are needed, eventually some will not support the HID spec (e.g. WebUSB). Pulling in both `hid` and `gousb` will break down due to both depending internally on different versions of `libusb` on Linux.
+
+This `usb` package is a proper integration of `hidapi` and `libusb` so that communication with HID devices is done via system calls, whereas communication with lower level USB devices is done via interrupts. All this detail is hidden away behind a tiny interface.
+
+The package supports Linux, macOS, Windows and FreeBSD. Exclude constraints are also specified for Android and iOS to allow smoother vendoring into cross platform projects.
+
+## Cross-compiling
+
+Using `go get`, the embedded C library is compiled into the binary format of your host OS. Cross compiling to a different platform or architecture entails disabling CGO by default in Go, causing device enumeration `hid.Enumerate()` to yield no results.
+
+To cross compile a functional version of this library, you'll need to enable CGO during cross compilation via `CGO_ENABLED=1` and you'll need to install and set a cross compilation enabled C toolkit via `CC=your-cross-gcc`.
+
+## Acknowledgements
+
+Although the `usb` package is an implementation from scratch, HID support was heavily inspired by the existing [`go.hid`](https://github.com/GeertJohan/go.hid) library, which seems abandoned since 2015; is incompatible with Go 1.6+; and has various external dependencies.
+
+Wide character support in the HID support is done via the [`gowchar`](https://github.com/orofarne/gowchar) library, unmaintained since 2013; non buildable with a modern Go release and failing `go vet` checks. As such, `gowchar` was also vendored in inline.
+
+Error handling for the `libusb` integration originates from the [`gousb`](https://github.com/google/gousb) library.
+
+## License
+
+This USB library is licensed under the [GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html) (dictated by libusb).
+
+If you are only interested in Human Interface devices, a less restrictive package can be found at [`github.com/karalabe/hid`](https://github.com/karalabe/hid).
diff --git a/vendor/github.com/karalabe/usb/appveyor.yml b/vendor/github.com/karalabe/usb/appveyor.yml
new file mode 100644
index 000000000..595fd34ad
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/appveyor.yml
@@ -0,0 +1,35 @@
+os: Visual Studio 2015
+
+# Clone directly into GOPATH.
+clone_folder: C:\gopath\src\github.com\karalabe\usb
+clone_depth: 1
+version: "{branch}.{build}"
+environment:
+ global:
+ GOPATH: C:\gopath
+ CC: gcc.exe
+ matrix:
+ - GOARCH: amd64
+ MSYS2_ARCH: x86_64
+ MSYS2_BITS: 64
+ MSYSTEM: MINGW64
+ PATH: C:\msys64\mingw64\bin\;%PATH%
+ - GOARCH: 386
+ MSYS2_ARCH: i686
+ MSYS2_BITS: 32
+ MSYSTEM: MINGW32
+ PATH: C:\msys64\mingw32\bin\;%PATH%
+
+install:
+ - rmdir C:\go /s /q
+ - appveyor DownloadFile https://storage.googleapis.com/golang/go1.13.4.windows-%GOARCH%.zip
+ - 7z x go1.13.4.windows-%GOARCH%.zip -y -oC:\ > NUL
+ - go version
+ - gcc --version
+
+build_script:
+ - go install ./...
+ - go test -v ./...
+ - set CGO_ENABLED=0
+ - go install ./...
+ - go test -v ./...
diff --git a/vendor/github.com/karalabe/usb/demo.go b/vendor/github.com/karalabe/usb/demo.go
new file mode 100644
index 000000000..229faaf5f
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/demo.go
@@ -0,0 +1,76 @@
+// usb - Self contained USB and HID library for Go
+// Copyright 2019 The library Authors
+//
+// This library is free software: you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License as published by the Free
+// Software Foundation, either version 3 of the License, or (at your option) any
+// later version.
+//
+// The library is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License along
+// with the library. If not, see .
+
+// +build none
+
+package main
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/karalabe/usb"
+)
+
+func main() {
+ // Enumerate all the HID devices in alphabetical path order
+ hids, err := usb.EnumerateHid(0, 0)
+ if err != nil {
+ panic(err)
+ }
+ for i := 0; i < len(hids); i++ {
+ for j := i + 1; j < len(hids); j++ {
+ if hids[i].Path > hids[j].Path {
+ hids[i], hids[j] = hids[j], hids[i]
+ }
+ }
+ }
+ for i, hid := range hids {
+ fmt.Println(strings.Repeat("-", 128))
+ fmt.Printf("HID #%d\n", i)
+ fmt.Printf(" OS Path: %s\n", hid.Path)
+ fmt.Printf(" Vendor ID: %#04x\n", hid.VendorID)
+ fmt.Printf(" Product ID: %#04x\n", hid.ProductID)
+ fmt.Printf(" Release: %d\n", hid.Release)
+ fmt.Printf(" Serial: %s\n", hid.Serial)
+ fmt.Printf(" Manufacturer: %s\n", hid.Manufacturer)
+ fmt.Printf(" Product: %s\n", hid.Product)
+ fmt.Printf(" Usage Page: %d\n", hid.UsagePage)
+ fmt.Printf(" Usage: %d\n", hid.Usage)
+ fmt.Printf(" Interface: %d\n", hid.Interface)
+ }
+ fmt.Println(strings.Repeat("=", 128))
+
+ // Enumerate all the non-HID devices in alphabetical path order
+ raws, err := usb.EnumerateRaw(0, 0)
+ if err != nil {
+ panic(err)
+ }
+ for i := 0; i < len(raws); i++ {
+ for j := i + 1; j < len(raws); j++ {
+ if raws[i].Path > raws[j].Path {
+ raws[i], raws[j] = raws[j], raws[i]
+ }
+ }
+ }
+ for i, raw := range raws {
+ fmt.Printf("RAW #%d\n", i)
+ fmt.Printf(" OS Path: %s\n", raw.Path)
+ fmt.Printf(" Vendor ID: %#04x\n", raw.VendorID)
+ fmt.Printf(" Product ID: %#04x\n", raw.ProductID)
+ fmt.Printf(" Interface: %d\n", raw.Interface)
+ fmt.Println(strings.Repeat("-", 128))
+ }
+}
diff --git a/vendor/github.com/karalabe/usb/go.mod b/vendor/github.com/karalabe/usb/go.mod
new file mode 100644
index 000000000..ef549d28f
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/go.mod
@@ -0,0 +1,3 @@
+module github.com/karalabe/usb
+
+go 1.12
diff --git a/vendor/github.com/karalabe/usb/hid_disabled.go b/vendor/github.com/karalabe/usb/hid_disabled.go
new file mode 100644
index 000000000..a85964bf3
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hid_disabled.go
@@ -0,0 +1,42 @@
+// usb - Self contained USB and HID library for Go
+// Copyright 2017 The library Authors
+//
+// This library is free software: you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License as published by the Free
+// Software Foundation, either version 3 of the License, or (at your option) any
+// later version.
+//
+// The library is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License along
+// with the library. If not, see .
+
+// +build !freebsd,!linux,!darwin,!windows ios !cgo
+
+package usb
+
+// HidDevice is a live HID USB connected device handle. On platforms that this file
+// implements, the type lacks the actual HID device and all methods are noop.
+type HidDevice struct {
+ DeviceInfo // Embed the infos for easier access
+}
+
+// Close releases the HID USB device handle. On platforms that this file implements,
+// the method is just a noop.
+func (dev *HidDevice) Close() error {
+ return ErrUnsupportedPlatform
+}
+
+// Write sends an output report to a HID device. On platforms that this file
+// implements, the method just returns an error.
+func (dev *HidDevice) Write(b []byte) (int, error) {
+ return 0, ErrUnsupportedPlatform
+}
+
+// Read retrieves an input report from a HID device. On platforms that this file
+// implements, the method just returns an error.
+func (dev *HidDevice) Read(b []byte) (int, error) {
+ return 0, ErrUnsupportedPlatform
+}
diff --git a/vendor/github.com/karalabe/usb/hid_enabled.go b/vendor/github.com/karalabe/usb/hid_enabled.go
new file mode 100644
index 000000000..c2b372098
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hid_enabled.go
@@ -0,0 +1,187 @@
+// usb - Self contained USB and HID library for Go
+// Copyright 2017 The library Authors
+//
+// This library is free software: you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License as published by the Free
+// Software Foundation, either version 3 of the License, or (at your option) any
+// later version.
+//
+// The library is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License along
+// with the library. If not, see .
+
+// +build freebsd,cgo linux,cgo darwin,!ios,cgo windows,cgo
+
+package usb
+
+/*
+#include
+#include "./hidapi/hidapi/hidapi.h"
+*/
+import "C"
+
+import (
+ "errors"
+ "runtime"
+ "sync"
+ "unsafe"
+)
+
+// enumerateHid returns a list of all the HID devices attached to the system which
+// match the vendor and product id:
+// - If the vendor id is set to 0 then any vendor matches.
+// - If the product id is set to 0 then any product matches.
+// - If the vendor and product id are both 0, all HID devices are returned.
+func enumerateHid(vendorID uint16, productID uint16) ([]DeviceInfo, error) {
+ // Gather all device infos and ensure they are freed before returning
+ head := C.hid_enumerate(C.ushort(vendorID), C.ushort(productID))
+ if head == nil {
+ return nil, nil
+ }
+ defer C.hid_free_enumeration(head)
+
+ // Iterate the list and retrieve the device details
+ var infos []DeviceInfo
+ for ; head != nil; head = head.next {
+ info := DeviceInfo{
+ Path: C.GoString(head.path),
+ VendorID: uint16(head.vendor_id),
+ ProductID: uint16(head.product_id),
+ Release: uint16(head.release_number),
+ UsagePage: uint16(head.usage_page),
+ Usage: uint16(head.usage),
+ Interface: int(head.interface_number),
+ }
+ if head.serial_number != nil {
+ info.Serial, _ = wcharTToString(head.serial_number)
+ }
+ if head.product_string != nil {
+ info.Product, _ = wcharTToString(head.product_string)
+ }
+ if head.manufacturer_string != nil {
+ info.Manufacturer, _ = wcharTToString(head.manufacturer_string)
+ }
+ infos = append(infos, info)
+ }
+ return infos, nil
+}
+
+// openHid connects to an HID device by its path name.
+func openHid(info DeviceInfo) (*hidDevice, error) {
+ path := C.CString(info.Path)
+ defer C.free(unsafe.Pointer(path))
+
+ device := C.hid_open_path(path)
+ if device == nil {
+ return nil, errors.New("hidapi: failed to open device")
+ }
+ return &hidDevice{
+ DeviceInfo: info,
+ device: device,
+ }, nil
+}
+
+// hidDevice is a live HID USB connected device handle.
+type hidDevice struct {
+ DeviceInfo // Embed the infos for easier access
+
+ device *C.hid_device // Low level HID device to communicate through
+ lock sync.Mutex
+}
+
+// Close releases the HID USB device handle.
+func (dev *hidDevice) Close() error {
+ dev.lock.Lock()
+ defer dev.lock.Unlock()
+
+ if dev.device != nil {
+ C.hid_close(dev.device)
+ dev.device = nil
+ }
+ return nil
+}
+
+// Write sends an output report to a HID device.
+//
+// Write will send the data on the first OUT endpoint, if one exists. If it does
+// not, it will send the data through the Control Endpoint (Endpoint 0).
+func (dev *hidDevice) Write(b []byte) (int, error) {
+ // Abort if nothing to write
+ if len(b) == 0 {
+ return 0, nil
+ }
+ // Abort if device closed in between
+ dev.lock.Lock()
+ device := dev.device
+ dev.lock.Unlock()
+
+ if device == nil {
+ return 0, ErrDeviceClosed
+ }
+ // Prepend a HID report ID on Windows, other OSes don't need it
+ var report []byte
+ if runtime.GOOS == "windows" {
+ report = append([]byte{0x00}, b...)
+ } else {
+ report = b
+ }
+ // Execute the write operation
+ written := int(C.hid_write(device, (*C.uchar)(&report[0]), C.size_t(len(report))))
+ if written == -1 {
+ // If the write failed, verify if closed or other error
+ dev.lock.Lock()
+ device = dev.device
+ dev.lock.Unlock()
+
+ if device == nil {
+ return 0, ErrDeviceClosed
+ }
+ // Device not closed, some other error occurred
+ message := C.hid_error(device)
+ if message == nil {
+ return 0, errors.New("hidapi: unknown failure")
+ }
+ failure, _ := wcharTToString(message)
+ return 0, errors.New("hidapi: " + failure)
+ }
+ return written, nil
+}
+
+// Read retrieves an input report from a HID device.
+func (dev *hidDevice) Read(b []byte) (int, error) {
+ // Aborth if nothing to read
+ if len(b) == 0 {
+ return 0, nil
+ }
+ // Abort if device closed in between
+ dev.lock.Lock()
+ device := dev.device
+ dev.lock.Unlock()
+
+ if device == nil {
+ return 0, ErrDeviceClosed
+ }
+ // Execute the read operation
+ read := int(C.hid_read(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
+ if read == -1 {
+ // If the read failed, verify if closed or other error
+ dev.lock.Lock()
+ device = dev.device
+ dev.lock.Unlock()
+
+ if device == nil {
+ return 0, ErrDeviceClosed
+ }
+ // Device not closed, some other error occurred
+ message := C.hid_error(device)
+ if message == nil {
+ return 0, errors.New("hidapi: unknown failure")
+ }
+ failure, _ := wcharTToString(message)
+ return 0, errors.New("hidapi: " + failure)
+ }
+ return read, nil
+}
diff --git a/vendor/github.com/karalabe/usb/hidapi/AUTHORS.txt b/vendor/github.com/karalabe/usb/hidapi/AUTHORS.txt
new file mode 100644
index 000000000..7acafd78c
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/AUTHORS.txt
@@ -0,0 +1,16 @@
+
+HIDAPI Authors:
+
+Alan Ott :
+ Original Author and Maintainer
+ Linux, Windows, and Mac implementations
+
+Ludovic Rousseau :
+ Formatting for Doxygen documentation
+ Bug fixes
+ Correctness fixes
+
+
+For a comprehensive list of contributions, see the commit list at github:
+ http://github.com/signal11/hidapi/commits/master
+
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE-bsd.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE-bsd.txt
new file mode 100644
index 000000000..538cdf95c
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/LICENSE-bsd.txt
@@ -0,0 +1,26 @@
+Copyright (c) 2010, Alan Ott, Signal 11 Software
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of Signal 11 Software nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE-gpl3.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE-gpl3.txt
new file mode 100644
index 000000000..94a9ed024
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/LICENSE-gpl3.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE-orig.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE-orig.txt
new file mode 100644
index 000000000..e3f338082
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/LICENSE-orig.txt
@@ -0,0 +1,9 @@
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Copyright 2009, Alan Ott, Signal 11 Software.
+ All Rights Reserved.
+
+ This software may be used by anyone for any reason so
+ long as the copyright notice in the source files
+ remains intact.
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE.txt
new file mode 100644
index 000000000..e1676d4c4
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/LICENSE.txt
@@ -0,0 +1,13 @@
+HIDAPI can be used under one of three licenses.
+
+1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt
+2. A BSD-Style License, in LICENSE-bsd.txt.
+3. The more liberal original HIDAPI license. LICENSE-orig.txt
+
+The license chosen is at the discretion of the user of HIDAPI. For example:
+1. An author of GPL software would likely use HIDAPI under the terms of the
+GPL.
+
+2. An author of commercial closed-source software would likely use HIDAPI
+under the terms of the BSD-style license or the original HIDAPI license.
+
diff --git a/vendor/github.com/karalabe/usb/hidapi/README.txt b/vendor/github.com/karalabe/usb/hidapi/README.txt
new file mode 100644
index 000000000..f19dae4ab
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/README.txt
@@ -0,0 +1,339 @@
+ HIDAPI library for Windows, Linux, FreeBSD and Mac OS X
+ =========================================================
+
+About
+======
+
+HIDAPI is a multi-platform library which allows an application to interface
+with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and Mac
+OS X. HIDAPI can be either built as a shared library (.so or .dll) or
+can be embedded directly into a target application by adding a single source
+file (per platform) and a single header.
+
+HIDAPI has four back-ends:
+ * Windows (using hid.dll)
+ * Linux/hidraw (using the Kernel's hidraw driver)
+ * Linux/libusb (using libusb-1.0)
+ * FreeBSD (using libusb-1.0)
+ * Mac (using IOHidManager)
+
+On Linux, either the hidraw or the libusb back-end can be used. There are
+tradeoffs, and the functionality supported is slightly different.
+
+Linux/hidraw (linux/hid.c):
+This back-end uses the hidraw interface in the Linux kernel. While this
+back-end will support both USB and Bluetooth, it has some limitations on
+kernels prior to 2.6.39, including the inability to send or receive feature
+reports. In addition, it will only communicate with devices which have
+hidraw nodes associated with them. Keyboards, mice, and some other devices
+which are blacklisted from having hidraw nodes will not work. Fortunately,
+for nearly all the uses of hidraw, this is not a problem.
+
+Linux/FreeBSD/libusb (libusb/hid.c):
+This back-end uses libusb-1.0 to communicate directly to a USB device. This
+back-end will of course not work with Bluetooth devices.
+
+HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses
+Fox Toolkit (http://www.fox-toolkit.org). It will build on every platform
+which HIDAPI supports. Since it relies on a 3rd party library, building it
+is optional but recommended because it is so useful when debugging hardware.
+
+What Does the API Look Like?
+=============================
+The API provides the the most commonly used HID functions including sending
+and receiving of input, output, and feature reports. The sample program,
+which communicates with a heavily hacked up version of the Microchip USB
+Generic HID sample looks like this (with error checking removed for
+simplicity):
+
+#ifdef WIN32
+#include
+#endif
+#include
+#include
+#include "hidapi.h"
+
+#define MAX_STR 255
+
+int main(int argc, char* argv[])
+{
+ int res;
+ unsigned char buf[65];
+ wchar_t wstr[MAX_STR];
+ hid_device *handle;
+ int i;
+
+ // Initialize the hidapi library
+ res = hid_init();
+
+ // Open the device using the VID, PID,
+ // and optionally the Serial number.
+ handle = hid_open(0x4d8, 0x3f, NULL);
+
+ // Read the Manufacturer String
+ res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
+ wprintf(L"Manufacturer String: %s\n", wstr);
+
+ // Read the Product String
+ res = hid_get_product_string(handle, wstr, MAX_STR);
+ wprintf(L"Product String: %s\n", wstr);
+
+ // Read the Serial Number String
+ res = hid_get_serial_number_string(handle, wstr, MAX_STR);
+ wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr);
+
+ // Read Indexed String 1
+ res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
+ wprintf(L"Indexed String 1: %s\n", wstr);
+
+ // Toggle LED (cmd 0x80). The first byte is the report number (0x0).
+ buf[0] = 0x0;
+ buf[1] = 0x80;
+ res = hid_write(handle, buf, 65);
+
+ // Request state (cmd 0x81). The first byte is the report number (0x0).
+ buf[0] = 0x0;
+ buf[1] = 0x81;
+ res = hid_write(handle, buf, 65);
+
+ // Read requested state
+ res = hid_read(handle, buf, 65);
+
+ // Print out the returned buffer.
+ for (i = 0; i < 4; i++)
+ printf("buf[%d]: %d\n", i, buf[i]);
+
+ // Finalize the hidapi library
+ res = hid_exit();
+
+ return 0;
+}
+
+If you have your own simple test programs which communicate with standard
+hardware development boards (such as those from Microchip, TI, Atmel,
+FreeScale and others), please consider sending me something like the above
+for inclusion into the HIDAPI source. This will help others who have the
+same hardware as you do.
+
+License
+========
+HIDAPI may be used by one of three licenses as outlined in LICENSE.txt.
+
+Download
+=========
+HIDAPI can be downloaded from github
+ git clone git://github.com/signal11/hidapi.git
+
+Build Instructions
+===================
+
+This section is long. Don't be put off by this. It's not long because it's
+complicated to build HIDAPI; it's quite the opposite. This section is long
+because of the flexibility of HIDAPI and the large number of ways in which
+it can be built and used. You will likely pick a single build method.
+
+HIDAPI can be built in several different ways. If you elect to build a
+shared library, you will need to build it from the HIDAPI source
+distribution. If you choose instead to embed HIDAPI directly into your
+application, you can skip the building and look at the provided platform
+Makefiles for guidance. These platform Makefiles are located in linux/
+libusb/ mac/ and windows/ and are called Makefile-manual. In addition,
+Visual Studio projects are provided. Even if you're going to embed HIDAPI
+into your project, it is still beneficial to build the example programs.
+
+
+Prerequisites:
+---------------
+
+ Linux:
+ -------
+ On Linux, you will need to install development packages for libudev,
+ libusb and optionally Fox-toolkit (for the test GUI). On
+ Debian/Ubuntu systems these can be installed by running:
+ sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev
+
+ If you downloaded the source directly from the git repository (using
+ git clone), you'll need Autotools:
+ sudo apt-get install autotools-dev autoconf automake libtool
+
+ FreeBSD:
+ ---------
+ On FreeBSD you will need to install GNU make, libiconv, and
+ optionally Fox-Toolkit (for the test GUI). This is done by running
+ the following:
+ pkg_add -r gmake libiconv fox16
+
+ If you downloaded the source directly from the git repository (using
+ git clone), you'll need Autotools:
+ pkg_add -r autotools
+
+ Mac:
+ -----
+ On Mac, you will need to install Fox-Toolkit if you wish to build
+ the Test GUI. There are two ways to do this, and each has a slight
+ complication. Which method you use depends on your use case.
+
+ If you wish to build the Test GUI just for your own testing on your
+ own computer, then the easiest method is to install Fox-Toolkit
+ using ports:
+ sudo port install fox
+
+ If you wish to build the TestGUI app bundle to redistribute to
+ others, you will need to install Fox-toolkit from source. This is
+ because the version of fox that gets installed using ports uses the
+ ports X11 libraries which are not compatible with the Apple X11
+ libraries. If you install Fox with ports and then try to distribute
+ your built app bundle, it will simply fail to run on other systems.
+ To install Fox-Toolkit manually, download the source package from
+ http://www.fox-toolkit.org, extract it, and run the following from
+ within the extracted source:
+ ./configure && make && make install
+
+ Windows:
+ ---------
+ On Windows, if you want to build the test GUI, you will need to get
+ the hidapi-externals.zip package from the download site. This
+ contains pre-built binaries for Fox-toolkit. Extract
+ hidapi-externals.zip just outside of hidapi, so that
+ hidapi-externals and hidapi are on the same level, as shown:
+
+ Parent_Folder
+ |
+ +hidapi
+ +hidapi-externals
+
+ Again, this step is not required if you do not wish to build the
+ test GUI.
+
+
+Building HIDAPI into a shared library on Unix Platforms:
+---------------------------------------------------------
+
+On Unix-like systems such as Linux, FreeBSD, Mac, and even Windows, using
+Mingw or Cygwin, the easiest way to build a standard system-installed shared
+library is to use the GNU Autotools build system. If you checked out the
+source from the git repository, run the following:
+
+ ./bootstrap
+ ./configure
+ make
+ make install <----- as root, or using sudo
+
+If you downloaded a source package (ie: if you did not run git clone), you
+can skip the ./bootstrap step.
+
+./configure can take several arguments which control the build. The two most
+likely to be used are:
+ --enable-testgui
+ Enable build of the Test GUI. This requires Fox toolkit to
+ be installed. Instructions for installing Fox-Toolkit on
+ each platform are in the Prerequisites section above.
+
+ --prefix=/usr
+ Specify where you want the output headers and libraries to
+ be installed. The example above will put the headers in
+ /usr/include and the binaries in /usr/lib. The default is to
+ install into /usr/local which is fine on most systems.
+
+Building the manual way on Unix platforms:
+-------------------------------------------
+
+Manual Makefiles are provided mostly to give the user and idea what it takes
+to build a program which embeds HIDAPI directly inside of it. These should
+really be used as examples only. If you want to build a system-wide shared
+library, use the Autotools method described above.
+
+ To build HIDAPI using the manual makefiles, change to the directory
+ of your platform and run make. For example, on Linux run:
+ cd linux/
+ make -f Makefile-manual
+
+ To build the Test GUI using the manual makefiles:
+ cd testgui/
+ make -f Makefile-manual
+
+Building on Windows:
+---------------------
+
+To build the HIDAPI DLL on Windows using Visual Studio, build the .sln file
+in the windows/ directory.
+
+To build the Test GUI on windows using Visual Studio, build the .sln file in
+the testgui/ directory.
+
+To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions
+in the section titled "Building HIDAPI into a shared library on Unix
+Platforms" above. Note that building the Test GUI with MinGW or Cygwin will
+require the Windows procedure in the Prerequisites section above (ie:
+hidapi-externals.zip).
+
+To build HIDAPI using MinGW using the Manual Makefiles, see the section
+"Building the manual way on Unix platforms" above.
+
+HIDAPI can also be built using the Windows DDK (now also called the Windows
+Driver Kit or WDK). This method was originally required for the HIDAPI build
+but not anymore. However, some users still prefer this method. It is not as
+well supported anymore but should still work. Patches are welcome if it does
+not. To build using the DDK:
+
+ 1. Install the Windows Driver Kit (WDK) from Microsoft.
+ 2. From the Start menu, in the Windows Driver Kits folder, select Build
+ Environments, then your operating system, then the x86 Free Build
+ Environment (or one that is appropriate for your system).
+ 3. From the console, change directory to the windows/ddk_build/ directory,
+ which is part of the HIDAPI distribution.
+ 4. Type build.
+ 5. You can find the output files (DLL and LIB) in a subdirectory created
+ by the build system which is appropriate for your environment. On
+ Windows XP, this directory is objfre_wxp_x86/i386.
+
+Cross Compiling
+================
+
+This section talks about cross compiling HIDAPI for Linux using autotools.
+This is useful for using HIDAPI on embedded Linux targets. These
+instructions assume the most raw kind of embedded Linux build, where all
+prerequisites will need to be built first. This process will of course vary
+based on your embedded Linux build system if you are using one, such as
+OpenEmbedded or Buildroot.
+
+For the purpose of this section, it will be assumed that the following
+environment variables are exported.
+
+ $ export STAGING=$HOME/out
+ $ export HOST=arm-linux
+
+STAGING and HOST can be modified to suit your setup.
+
+Prerequisites
+--------------
+
+Note that the build of libudev is the very basic configuration.
+
+Build Libusb. From the libusb source directory, run:
+ ./configure --host=$HOST --prefix=$STAGING
+ make
+ make install
+
+Build libudev. From the libudev source directory, run:
+ ./configure --disable-gudev --disable-introspection --disable-hwdb \
+ --host=$HOST --prefix=$STAGING
+ make
+ make install
+
+Building HIDAPI
+----------------
+
+Build HIDAPI:
+
+ PKG_CONFIG_DIR= \
+ PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \
+ PKG_CONFIG_SYSROOT_DIR=$STAGING \
+ ./configure --host=$HOST --prefix=$STAGING
+
+
+Signal 11 Software - 2010-04-11
+ 2010-07-28
+ 2011-09-10
+ 2012-05-01
+ 2012-07-03
diff --git a/vendor/github.com/karalabe/usb/hidapi/hidapi/hidapi.h b/vendor/github.com/karalabe/usb/hidapi/hidapi/hidapi.h
new file mode 100644
index 000000000..166f3509a
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/hidapi/hidapi.h
@@ -0,0 +1,390 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+/** @file
+ * @defgroup API hidapi API
+ */
+
+#ifndef HIDAPI_H__
+#define HIDAPI_H__
+
+#include
+
+#ifdef _WIN32
+ #define HID_API_EXPORT __declspec(dllexport)
+ #define HID_API_CALL
+#else
+ #define HID_API_EXPORT /**< API export macro */
+ #define HID_API_CALL /**< API call macro */
+#endif
+
+#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ struct hid_device_;
+ typedef struct hid_device_ hid_device; /**< opaque hidapi structure */
+
+ /** hidapi info structure */
+ struct hid_device_info {
+ /** Platform-specific device path */
+ char *path;
+ /** Device Vendor ID */
+ unsigned short vendor_id;
+ /** Device Product ID */
+ unsigned short product_id;
+ /** Serial Number */
+ wchar_t *serial_number;
+ /** Device Release Number in binary-coded decimal,
+ also known as Device Version Number */
+ unsigned short release_number;
+ /** Manufacturer String */
+ wchar_t *manufacturer_string;
+ /** Product string */
+ wchar_t *product_string;
+ /** Usage Page for this Device/Interface
+ (Windows/Mac only). */
+ unsigned short usage_page;
+ /** Usage for this Device/Interface
+ (Windows/Mac only).*/
+ unsigned short usage;
+ /** The USB interface which this logical device
+ represents. Valid on both Linux implementations
+ in all cases, and valid on the Windows implementation
+ only if the device contains more than one interface. */
+ int interface_number;
+
+ /** Pointer to the next device */
+ struct hid_device_info *next;
+ };
+
+
+ /** @brief Initialize the HIDAPI library.
+
+ This function initializes the HIDAPI library. Calling it is not
+ strictly necessary, as it will be called automatically by
+ hid_enumerate() and any of the hid_open_*() functions if it is
+ needed. This function should be called at the beginning of
+ execution however, if there is a chance of HIDAPI handles
+ being opened by different threads simultaneously.
+
+ @ingroup API
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_init(void);
+
+ /** @brief Finalize the HIDAPI library.
+
+ This function frees all of the static data associated with
+ HIDAPI. It should be called at the end of execution to avoid
+ memory leaks.
+
+ @ingroup API
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_exit(void);
+
+ /** @brief Enumerate the HID Devices.
+
+ This function returns a linked list of all the HID devices
+ attached to the system which match vendor_id and product_id.
+ If @p vendor_id is set to 0 then any vendor matches.
+ If @p product_id is set to 0 then any product matches.
+ If @p vendor_id and @p product_id are both set to 0, then
+ all HID devices will be returned.
+
+ @ingroup API
+ @param vendor_id The Vendor ID (VID) of the types of device
+ to open.
+ @param product_id The Product ID (PID) of the types of
+ device to open.
+
+ @returns
+ This function returns a pointer to a linked list of type
+ struct #hid_device, containing information about the HID devices
+ attached to the system, or NULL in the case of failure. Free
+ this linked list by calling hid_free_enumeration().
+ */
+ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);
+
+ /** @brief Free an enumeration Linked List
+
+ This function frees a linked list created by hid_enumerate().
+
+ @ingroup API
+ @param devs Pointer to a list of struct_device returned from
+ hid_enumerate().
+ */
+ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);
+
+ /** @brief Open a HID device using a Vendor ID (VID), Product ID
+ (PID) and optionally a serial number.
+
+ If @p serial_number is NULL, the first device with the
+ specified VID and PID is opened.
+
+ @ingroup API
+ @param vendor_id The Vendor ID (VID) of the device to open.
+ @param product_id The Product ID (PID) of the device to open.
+ @param serial_number The Serial Number of the device to open
+ (Optionally NULL).
+
+ @returns
+ This function returns a pointer to a #hid_device object on
+ success or NULL on failure.
+ */
+ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number);
+
+ /** @brief Open a HID device by its path name.
+
+ The path name be determined by calling hid_enumerate(), or a
+ platform-specific path name can be used (eg: /dev/hidraw0 on
+ Linux).
+
+ @ingroup API
+ @param path The path name of the device to open
+
+ @returns
+ This function returns a pointer to a #hid_device object on
+ success or NULL on failure.
+ */
+ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path);
+
+ /** @brief Write an Output report to a HID device.
+
+ The first byte of @p data[] must contain the Report ID. For
+ devices which only support a single report, this must be set
+ to 0x0. The remaining bytes contain the report data. Since
+ the Report ID is mandatory, calls to hid_write() will always
+ contain one more byte than the report contains. For example,
+ if a hid report is 16 bytes long, 17 bytes must be passed to
+ hid_write(), the Report ID (or 0x0, for devices with a
+ single report), followed by the report data (16 bytes). In
+ this example, the length passed in would be 17.
+
+ hid_write() will send the data on the first OUT endpoint, if
+ one exists. If it does not, it will send the data through
+ the Control Endpoint (Endpoint 0).
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data The data to send, including the report number as
+ the first byte.
+ @param length The length in bytes of the data to send.
+
+ @returns
+ This function returns the actual number of bytes written and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
+
+ /** @brief Read an Input report from a HID device with timeout.
+
+ Input reports are returned
+ to the host through the INTERRUPT IN endpoint. The first byte will
+ contain the Report number if the device uses numbered reports.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into.
+ @param length The number of bytes to read. For devices with
+ multiple reports, make sure to read an extra byte for
+ the report number.
+ @param milliseconds timeout in milliseconds or -1 for blocking wait.
+
+ @returns
+ This function returns the actual number of bytes read and
+ -1 on error. If no packet was available to be read within
+ the timeout period, this function returns 0.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);
+
+ /** @brief Read an Input report from a HID device.
+
+ Input reports are returned
+ to the host through the INTERRUPT IN endpoint. The first byte will
+ contain the Report number if the device uses numbered reports.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into.
+ @param length The number of bytes to read. For devices with
+ multiple reports, make sure to read an extra byte for
+ the report number.
+
+ @returns
+ This function returns the actual number of bytes read and
+ -1 on error. If no packet was available to be read and
+ the handle is in non-blocking mode, this function returns 0.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
+
+ /** @brief Set the device handle to be non-blocking.
+
+ In non-blocking mode calls to hid_read() will return
+ immediately with a value of 0 if there is no data to be
+ read. In blocking mode, hid_read() will wait (block) until
+ there is data to read before returning.
+
+ Nonblocking can be turned on and off at any time.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param nonblock enable or not the nonblocking reads
+ - 1 to enable nonblocking
+ - 0 to disable nonblocking.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);
+
+ /** @brief Send a Feature report to the device.
+
+ Feature reports are sent over the Control endpoint as a
+ Set_Report transfer. The first byte of @p data[] must
+ contain the Report ID. For devices which only support a
+ single report, this must be set to 0x0. The remaining bytes
+ contain the report data. Since the Report ID is mandatory,
+ calls to hid_send_feature_report() will always contain one
+ more byte than the report contains. For example, if a hid
+ report is 16 bytes long, 17 bytes must be passed to
+ hid_send_feature_report(): the Report ID (or 0x0, for
+ devices which do not use numbered reports), followed by the
+ report data (16 bytes). In this example, the length passed
+ in would be 17.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data The data to send, including the report number as
+ the first byte.
+ @param length The length in bytes of the data to send, including
+ the report number.
+
+ @returns
+ This function returns the actual number of bytes written and
+ -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);
+
+ /** @brief Get a feature report from a HID device.
+
+ Set the first byte of @p data[] to the Report ID of the
+ report to be read. Make sure to allow space for this
+ extra byte in @p data[]. Upon return, the first byte will
+ still contain the Report ID, and the report data will
+ start in data[1].
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param data A buffer to put the read data into, including
+ the Report ID. Set the first byte of @p data[] to the
+ Report ID of the report to be read, or set it to zero
+ if your device does not use numbered reports.
+ @param length The number of bytes to read, including an
+ extra byte for the report ID. The buffer can be longer
+ than the actual report.
+
+ @returns
+ This function returns the number of bytes read plus
+ one for the report ID (which is still in the first
+ byte), or -1 on error.
+ */
+ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);
+
+ /** @brief Close a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ */
+ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);
+
+ /** @brief Get The Manufacturer String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get The Product String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get The Serial Number String from a HID device.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);
+
+ /** @brief Get a string from a HID device, based on its string index.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+ @param string_index The index of the string to get.
+ @param string A wide string buffer to put the data into.
+ @param maxlen The length of the buffer in multiples of wchar_t.
+
+ @returns
+ This function returns 0 on success and -1 on error.
+ */
+ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);
+
+ /** @brief Get a string describing the last error which occurred.
+
+ @ingroup API
+ @param device A device handle returned from hid_open().
+
+ @returns
+ This function returns a string containing the last error
+ which occurred or NULL if none has occurred.
+ */
+ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/vendor/github.com/karalabe/usb/hidapi/libusb/hid.c b/vendor/github.com/karalabe/usb/hidapi/libusb/hid.c
new file mode 100644
index 000000000..e91474065
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/libusb/hid.c
@@ -0,0 +1,1508 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+ Linux Version - 6/2/2010
+ Libusb Version - 8/13/2010
+ FreeBSD Version - 11/1/2011
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+/* C */
+#include
+#include
+#include
+#include
+#include
+#include
+
+/* Unix */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+/* GNU / LibUSB */
+#include
+#ifndef __ANDROID__
+#include
+#endif
+
+#include "hidapi.h"
+
+#ifdef __ANDROID__
+
+/* Barrier implementation because Android/Bionic don't have pthread_barrier.
+ This implementation came from Brent Priddy and was posted on
+ StackOverflow. It is used with his permission. */
+typedef int pthread_barrierattr_t;
+typedef struct pthread_barrier {
+ pthread_mutex_t mutex;
+ pthread_cond_t cond;
+ int count;
+ int trip_count;
+} pthread_barrier_t;
+
+static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
+{
+ if(count == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
+ return -1;
+ }
+ if(pthread_cond_init(&barrier->cond, 0) < 0) {
+ pthread_mutex_destroy(&barrier->mutex);
+ return -1;
+ }
+ barrier->trip_count = count;
+ barrier->count = 0;
+
+ return 0;
+}
+
+static int pthread_barrier_destroy(pthread_barrier_t *barrier)
+{
+ pthread_cond_destroy(&barrier->cond);
+ pthread_mutex_destroy(&barrier->mutex);
+ return 0;
+}
+
+static int pthread_barrier_wait(pthread_barrier_t *barrier)
+{
+ pthread_mutex_lock(&barrier->mutex);
+ ++(barrier->count);
+ if(barrier->count >= barrier->trip_count)
+ {
+ barrier->count = 0;
+ pthread_cond_broadcast(&barrier->cond);
+ pthread_mutex_unlock(&barrier->mutex);
+ return 1;
+ }
+ else
+ {
+ pthread_cond_wait(&barrier->cond, &(barrier->mutex));
+ pthread_mutex_unlock(&barrier->mutex);
+ return 0;
+ }
+}
+
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef DEBUG_PRINTF
+#define LOG(...) fprintf(stderr, __VA_ARGS__)
+#else
+#define LOG(...) do {} while (0)
+#endif
+
+#ifndef __FreeBSD__
+#define DETACH_KERNEL_DRIVER
+#endif
+
+/* Uncomment to enable the retrieval of Usage and Usage Page in
+hid_enumerate(). Warning, on platforms different from FreeBSD
+this is very invasive as it requires the detach
+and re-attach of the kernel driver. See comments inside hid_enumerate().
+libusb HIDAPI programs are encouraged to use the interface number
+instead to differentiate between interfaces on a composite HID device. */
+/*#define INVASIVE_GET_USAGE*/
+
+/* Linked List of input reports received from the device. */
+struct input_report {
+ uint8_t *data;
+ size_t len;
+ struct input_report *next;
+};
+
+
+struct hid_device_ {
+ /* Handle to the actual device. */
+ libusb_device_handle *device_handle;
+
+ /* Endpoint information */
+ int input_endpoint;
+ int output_endpoint;
+ int input_ep_max_packet_size;
+
+ /* The interface number of the HID */
+ int interface;
+
+ /* Indexes of Strings */
+ int manufacturer_index;
+ int product_index;
+ int serial_index;
+
+ /* Whether blocking reads are used */
+ int blocking; /* boolean */
+
+ /* Read thread objects */
+ pthread_t thread;
+ pthread_mutex_t mutex; /* Protects input_reports */
+ pthread_cond_t condition;
+ pthread_barrier_t barrier; /* Ensures correct startup sequence */
+ int shutdown_thread;
+ int cancelled;
+ struct libusb_transfer *transfer;
+
+ /* List of received input reports. */
+ struct input_report *input_reports;
+};
+
+static libusb_context *usb_context = NULL;
+
+uint16_t get_usb_code_for_current_locale(void);
+static int return_data(hid_device *dev, unsigned char *data, size_t length);
+
+static hid_device *new_hid_device(void)
+{
+ hid_device *dev = calloc(1, sizeof(hid_device));
+ dev->blocking = 1;
+
+ pthread_mutex_init(&dev->mutex, NULL);
+ pthread_cond_init(&dev->condition, NULL);
+ pthread_barrier_init(&dev->barrier, NULL, 2);
+
+ return dev;
+}
+
+static void free_hid_device(hid_device *dev)
+{
+ /* Clean up the thread objects */
+ pthread_barrier_destroy(&dev->barrier);
+ pthread_cond_destroy(&dev->condition);
+ pthread_mutex_destroy(&dev->mutex);
+
+ /* Free the device itself */
+ free(dev);
+}
+
+#if 0
+/*TODO: Implement this funciton on hidapi/libusb.. */
+static void register_error(hid_device *device, const char *op)
+{
+
+}
+#endif
+
+#ifdef INVASIVE_GET_USAGE
+/* Get bytes from a HID Report Descriptor.
+ Only call with a num_bytes of 0, 1, 2, or 4. */
+static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
+{
+ /* Return if there aren't enough bytes. */
+ if (cur + num_bytes >= len)
+ return 0;
+
+ if (num_bytes == 0)
+ return 0;
+ else if (num_bytes == 1) {
+ return rpt[cur+1];
+ }
+ else if (num_bytes == 2) {
+ return (rpt[cur+2] * 256 + rpt[cur+1]);
+ }
+ else if (num_bytes == 4) {
+ return (rpt[cur+4] * 0x01000000 +
+ rpt[cur+3] * 0x00010000 +
+ rpt[cur+2] * 0x00000100 +
+ rpt[cur+1] * 0x00000001);
+ }
+ else
+ return 0;
+}
+
+/* Retrieves the device's Usage Page and Usage from the report
+ descriptor. The algorithm is simple, as it just returns the first
+ Usage and Usage Page that it finds in the descriptor.
+ The return value is 0 on success and -1 on failure. */
+static int get_usage(uint8_t *report_descriptor, size_t size,
+ unsigned short *usage_page, unsigned short *usage)
+{
+ unsigned int i = 0;
+ int size_code;
+ int data_len, key_size;
+ int usage_found = 0, usage_page_found = 0;
+
+ while (i < size) {
+ int key = report_descriptor[i];
+ int key_cmd = key & 0xfc;
+
+ //printf("key: %02hhx\n", key);
+
+ if ((key & 0xf0) == 0xf0) {
+ /* This is a Long Item. The next byte contains the
+ length of the data section (value) for this key.
+ See the HID specification, version 1.11, section
+ 6.2.2.3, titled "Long Items." */
+ if (i+1 < size)
+ data_len = report_descriptor[i+1];
+ else
+ data_len = 0; /* malformed report */
+ key_size = 3;
+ }
+ else {
+ /* This is a Short Item. The bottom two bits of the
+ key contain the size code for the data section
+ (value) for this key. Refer to the HID
+ specification, version 1.11, section 6.2.2.2,
+ titled "Short Items." */
+ size_code = key & 0x3;
+ switch (size_code) {
+ case 0:
+ case 1:
+ case 2:
+ data_len = size_code;
+ break;
+ case 3:
+ data_len = 4;
+ break;
+ default:
+ /* Can't ever happen since size_code is & 0x3 */
+ data_len = 0;
+ break;
+ };
+ key_size = 1;
+ }
+
+ if (key_cmd == 0x4) {
+ *usage_page = get_bytes(report_descriptor, size, data_len, i);
+ usage_page_found = 1;
+ //printf("Usage Page: %x\n", (uint32_t)*usage_page);
+ }
+ if (key_cmd == 0x8) {
+ *usage = get_bytes(report_descriptor, size, data_len, i);
+ usage_found = 1;
+ //printf("Usage: %x\n", (uint32_t)*usage);
+ }
+
+ if (usage_page_found && usage_found)
+ return 0; /* success */
+
+ /* Skip over this key and it's associated data */
+ i += data_len + key_size;
+ }
+
+ return -1; /* failure */
+}
+#endif /* INVASIVE_GET_USAGE */
+
+#if defined(__FreeBSD__) && __FreeBSD__ < 10
+/* The libusb version included in FreeBSD < 10 doesn't have this function. In
+ mainline libusb, it's inlined in libusb.h. This function will bear a striking
+ resemblance to that one, because there's about one way to code it.
+
+ Note that the data parameter is Unicode in UTF-16LE encoding.
+ Return value is the number of bytes in data, or LIBUSB_ERROR_*.
+ */
+static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
+ uint8_t descriptor_index, uint16_t lang_id,
+ unsigned char *data, int length)
+{
+ return libusb_control_transfer(dev,
+ LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
+ LIBUSB_REQUEST_GET_DESCRIPTOR,
+ (LIBUSB_DT_STRING << 8) | descriptor_index,
+ lang_id, data, (uint16_t) length, 1000);
+}
+
+#endif
+
+
+/* Get the first language the device says it reports. This comes from
+ USB string #0. */
+static uint16_t get_first_language(libusb_device_handle *dev)
+{
+ uint16_t buf[32];
+ int len;
+
+ /* Get the string from libusb. */
+ len = libusb_get_string_descriptor(dev,
+ 0x0, /* String ID */
+ 0x0, /* Language */
+ (unsigned char*)buf,
+ sizeof(buf));
+ if (len < 4)
+ return 0x0;
+
+ return buf[1]; /* First two bytes are len and descriptor type. */
+}
+
+static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
+{
+ uint16_t buf[32];
+ int len;
+ int i;
+
+ /* Get the string from libusb. */
+ len = libusb_get_string_descriptor(dev,
+ 0x0, /* String ID */
+ 0x0, /* Language */
+ (unsigned char*)buf,
+ sizeof(buf));
+ if (len < 4)
+ return 0x0;
+
+
+ len /= 2; /* language IDs are two-bytes each. */
+ /* Start at index 1 because there are two bytes of protocol data. */
+ for (i = 1; i < len; i++) {
+ if (buf[i] == lang)
+ return 1;
+ }
+
+ return 0;
+}
+
+
+/* This function returns a newly allocated wide string containing the USB
+ device string numbered by the index. The returned string must be freed
+ by using free(). */
+static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
+{
+ char buf[512];
+ int len;
+ wchar_t *str = NULL;
+
+#ifndef __ANDROID__ /* we don't use iconv on Android */
+ wchar_t wbuf[256];
+ /* iconv variables */
+ iconv_t ic;
+ size_t inbytes;
+ size_t outbytes;
+ size_t res;
+ char *inptr;
+ char *outptr;
+#endif
+
+ /* Determine which language to use. */
+ uint16_t lang;
+ lang = get_usb_code_for_current_locale();
+ if (!is_language_supported(dev, lang))
+ lang = get_first_language(dev);
+
+ /* Get the string from libusb. */
+ len = libusb_get_string_descriptor(dev,
+ idx,
+ lang,
+ (unsigned char*)buf,
+ sizeof(buf));
+ if (len < 0)
+ return NULL;
+
+#ifdef __ANDROID__
+
+ /* Bionic does not have iconv support nor wcsdup() function, so it
+ has to be done manually. The following code will only work for
+ code points that can be represented as a single UTF-16 character,
+ and will incorrectly convert any code points which require more
+ than one UTF-16 character.
+
+ Skip over the first character (2-bytes). */
+ len -= 2;
+ str = malloc((len / 2 + 1) * sizeof(wchar_t));
+ int i;
+ for (i = 0; i < len / 2; i++) {
+ str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8);
+ }
+ str[len / 2] = 0x00000000;
+
+#else
+
+ /* buf does not need to be explicitly NULL-terminated because
+ it is only passed into iconv() which does not need it. */
+
+ /* Initialize iconv. */
+ ic = iconv_open("WCHAR_T", "UTF-16LE");
+ if (ic == (iconv_t)-1) {
+ LOG("iconv_open() failed\n");
+ return NULL;
+ }
+
+ /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
+ Skip the first character (2-bytes). */
+ inptr = buf+2;
+ inbytes = len-2;
+ outptr = (char*) wbuf;
+ outbytes = sizeof(wbuf);
+ res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
+ if (res == (size_t)-1) {
+ LOG("iconv() failed\n");
+ goto err;
+ }
+
+ /* Write the terminating NULL. */
+ wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
+ if (outbytes >= sizeof(wbuf[0]))
+ *((wchar_t*)outptr) = 0x00000000;
+
+ /* Allocate and copy the string. */
+ str = wcsdup(wbuf);
+
+err:
+ iconv_close(ic);
+
+#endif
+
+ return str;
+}
+
+static char *make_path(libusb_device *dev, int interface_number)
+{
+ char str[64];
+ snprintf(str, sizeof(str), "%04x:%04x:%02x",
+ libusb_get_bus_number(dev),
+ libusb_get_device_address(dev),
+ interface_number);
+ str[sizeof(str)-1] = '\0';
+
+ return strdup(str);
+}
+
+
+int HID_API_EXPORT hid_init(void)
+{
+ if (!usb_context) {
+ const char *locale;
+
+ /* Init Libusb */
+ if (libusb_init(&usb_context))
+ return -1;
+
+ /* Set the locale if it's not set. */
+ locale = setlocale(LC_CTYPE, NULL);
+ if (!locale)
+ setlocale(LC_CTYPE, "");
+ }
+
+ return 0;
+}
+
+int HID_API_EXPORT hid_exit(void)
+{
+ if (usb_context) {
+ libusb_exit(usb_context);
+ usb_context = NULL;
+ }
+
+ return 0;
+}
+
+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
+{
+ libusb_device **devs;
+ libusb_device *dev;
+ libusb_device_handle *handle;
+ ssize_t num_devs;
+ int i = 0;
+
+ struct hid_device_info *root = NULL; /* return object */
+ struct hid_device_info *cur_dev = NULL;
+
+ if(hid_init() < 0)
+ return NULL;
+
+ num_devs = libusb_get_device_list(usb_context, &devs);
+ if (num_devs < 0)
+ return NULL;
+ while ((dev = devs[i++]) != NULL) {
+ struct libusb_device_descriptor desc;
+ struct libusb_config_descriptor *conf_desc = NULL;
+ int j, k;
+ int interface_num = 0;
+
+ int res = libusb_get_device_descriptor(dev, &desc);
+ unsigned short dev_vid = desc.idVendor;
+ unsigned short dev_pid = desc.idProduct;
+
+ res = libusb_get_active_config_descriptor(dev, &conf_desc);
+ if (res < 0)
+ libusb_get_config_descriptor(dev, 0, &conf_desc);
+ if (conf_desc) {
+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
+ const struct libusb_interface *intf = &conf_desc->interface[j];
+ for (k = 0; k < intf->num_altsetting; k++) {
+ const struct libusb_interface_descriptor *intf_desc;
+ intf_desc = &intf->altsetting[k];
+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
+ interface_num = intf_desc->bInterfaceNumber;
+
+ /* Check the VID/PID against the arguments */
+ if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
+ (product_id == 0x0 || product_id == dev_pid)) {
+ struct hid_device_info *tmp;
+
+ /* VID/PID match. Create the record. */
+ tmp = calloc(1, sizeof(struct hid_device_info));
+ if (cur_dev) {
+ cur_dev->next = tmp;
+ }
+ else {
+ root = tmp;
+ }
+ cur_dev = tmp;
+
+ /* Fill out the record */
+ cur_dev->next = NULL;
+ cur_dev->path = make_path(dev, interface_num);
+
+ res = libusb_open(dev, &handle);
+
+ if (res >= 0) {
+ /* Serial Number */
+ if (desc.iSerialNumber > 0)
+ cur_dev->serial_number =
+ get_usb_string(handle, desc.iSerialNumber);
+
+ /* Manufacturer and Product strings */
+ if (desc.iManufacturer > 0)
+ cur_dev->manufacturer_string =
+ get_usb_string(handle, desc.iManufacturer);
+ if (desc.iProduct > 0)
+ cur_dev->product_string =
+ get_usb_string(handle, desc.iProduct);
+
+#ifdef INVASIVE_GET_USAGE
+{
+ /*
+ This section is removed because it is too
+ invasive on the system. Getting a Usage Page
+ and Usage requires parsing the HID Report
+ descriptor. Getting a HID Report descriptor
+ involves claiming the interface. Claiming the
+ interface involves detaching the kernel driver.
+ Detaching the kernel driver is hard on the system
+ because it will unclaim interfaces (if another
+ app has them claimed) and the re-attachment of
+ the driver will sometimes change /dev entry names.
+ It is for these reasons that this section is
+ #if 0. For composite devices, use the interface
+ field in the hid_device_info struct to distinguish
+ between interfaces. */
+ unsigned char data[256];
+#ifdef DETACH_KERNEL_DRIVER
+ int detached = 0;
+ /* Usage Page and Usage */
+ res = libusb_kernel_driver_active(handle, interface_num);
+ if (res == 1) {
+ res = libusb_detach_kernel_driver(handle, interface_num);
+ if (res < 0)
+ LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
+ else
+ detached = 1;
+ }
+#endif
+ res = libusb_claim_interface(handle, interface_num);
+ if (res >= 0) {
+ /* Get the HID Report Descriptor. */
+ res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
+ if (res >= 0) {
+ unsigned short page=0, usage=0;
+ /* Parse the usage and usage page
+ out of the report descriptor. */
+ get_usage(data, res, &page, &usage);
+ cur_dev->usage_page = page;
+ cur_dev->usage = usage;
+ }
+ else
+ LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
+
+ /* Release the interface */
+ res = libusb_release_interface(handle, interface_num);
+ if (res < 0)
+ LOG("Can't release the interface.\n");
+ }
+ else
+ LOG("Can't claim interface %d\n", res);
+#ifdef DETACH_KERNEL_DRIVER
+ /* Re-attach kernel driver if necessary. */
+ if (detached) {
+ res = libusb_attach_kernel_driver(handle, interface_num);
+ if (res < 0)
+ LOG("Couldn't re-attach kernel driver.\n");
+ }
+#endif
+}
+#endif /* INVASIVE_GET_USAGE */
+
+ libusb_close(handle);
+ }
+ /* VID/PID */
+ cur_dev->vendor_id = dev_vid;
+ cur_dev->product_id = dev_pid;
+
+ /* Release Number */
+ cur_dev->release_number = desc.bcdDevice;
+
+ /* Interface Number */
+ cur_dev->interface_number = interface_num;
+ }
+ }
+ } /* altsettings */
+ } /* interfaces */
+ libusb_free_config_descriptor(conf_desc);
+ }
+ }
+
+ libusb_free_device_list(devs, 1);
+
+ return root;
+}
+
+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
+{
+ struct hid_device_info *d = devs;
+ while (d) {
+ struct hid_device_info *next = d->next;
+ free(d->path);
+ free(d->serial_number);
+ free(d->manufacturer_string);
+ free(d->product_string);
+ free(d);
+ d = next;
+ }
+}
+
+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
+{
+ struct hid_device_info *devs, *cur_dev;
+ const char *path_to_open = NULL;
+ hid_device *handle = NULL;
+
+ devs = hid_enumerate(vendor_id, product_id);
+ cur_dev = devs;
+ while (cur_dev) {
+ if (cur_dev->vendor_id == vendor_id &&
+ cur_dev->product_id == product_id) {
+ if (serial_number) {
+ if (cur_dev->serial_number &&
+ wcscmp(serial_number, cur_dev->serial_number) == 0) {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ else {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ cur_dev = cur_dev->next;
+ }
+
+ if (path_to_open) {
+ /* Open the device */
+ handle = hid_open_path(path_to_open);
+ }
+
+ hid_free_enumeration(devs);
+
+ return handle;
+}
+
+static void read_callback(struct libusb_transfer *transfer)
+{
+ hid_device *dev = transfer->user_data;
+ int res;
+
+ if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
+
+ struct input_report *rpt = malloc(sizeof(*rpt));
+ rpt->data = malloc(transfer->actual_length);
+ memcpy(rpt->data, transfer->buffer, transfer->actual_length);
+ rpt->len = transfer->actual_length;
+ rpt->next = NULL;
+
+ pthread_mutex_lock(&dev->mutex);
+
+ /* Attach the new report object to the end of the list. */
+ if (dev->input_reports == NULL) {
+ /* The list is empty. Put it at the root. */
+ dev->input_reports = rpt;
+ pthread_cond_signal(&dev->condition);
+ }
+ else {
+ /* Find the end of the list and attach. */
+ struct input_report *cur = dev->input_reports;
+ int num_queued = 0;
+ while (cur->next != NULL) {
+ cur = cur->next;
+ num_queued++;
+ }
+ cur->next = rpt;
+
+ /* Pop one off if we've reached 30 in the queue. This
+ way we don't grow forever if the user never reads
+ anything from the device. */
+ if (num_queued > 30) {
+ return_data(dev, NULL, 0);
+ }
+ }
+ pthread_mutex_unlock(&dev->mutex);
+ }
+ else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
+ dev->shutdown_thread = 1;
+ dev->cancelled = 1;
+ return;
+ }
+ else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
+ dev->shutdown_thread = 1;
+ dev->cancelled = 1;
+ return;
+ }
+ else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
+ //LOG("Timeout (normal)\n");
+ }
+ else {
+ LOG("Unknown transfer code: %d\n", transfer->status);
+ }
+
+ /* Re-submit the transfer object. */
+ res = libusb_submit_transfer(transfer);
+ if (res != 0) {
+ LOG("Unable to submit URB. libusb error code: %d\n", res);
+ dev->shutdown_thread = 1;
+ dev->cancelled = 1;
+ }
+}
+
+
+static void *read_thread(void *param)
+{
+ hid_device *dev = param;
+ unsigned char *buf;
+ const size_t length = dev->input_ep_max_packet_size;
+
+ /* Set up the transfer object. */
+ buf = malloc(length);
+ dev->transfer = libusb_alloc_transfer(0);
+ libusb_fill_interrupt_transfer(dev->transfer,
+ dev->device_handle,
+ dev->input_endpoint,
+ buf,
+ length,
+ read_callback,
+ dev,
+ 5000/*timeout*/);
+
+ /* Make the first submission. Further submissions are made
+ from inside read_callback() */
+ libusb_submit_transfer(dev->transfer);
+
+ /* Notify the main thread that the read thread is up and running. */
+ pthread_barrier_wait(&dev->barrier);
+
+ /* Handle all the events. */
+ while (!dev->shutdown_thread) {
+ int res;
+ res = libusb_handle_events(usb_context);
+ if (res < 0) {
+ /* There was an error. */
+ LOG("read_thread(): libusb reports error # %d\n", res);
+
+ /* Break out of this loop only on fatal error.*/
+ if (res != LIBUSB_ERROR_BUSY &&
+ res != LIBUSB_ERROR_TIMEOUT &&
+ res != LIBUSB_ERROR_OVERFLOW &&
+ res != LIBUSB_ERROR_INTERRUPTED) {
+ break;
+ }
+ }
+ }
+
+ /* Cancel any transfer that may be pending. This call will fail
+ if no transfers are pending, but that's OK. */
+ libusb_cancel_transfer(dev->transfer);
+
+ while (!dev->cancelled)
+ libusb_handle_events_completed(usb_context, &dev->cancelled);
+
+ /* Now that the read thread is stopping, Wake any threads which are
+ waiting on data (in hid_read_timeout()). Do this under a mutex to
+ make sure that a thread which is about to go to sleep waiting on
+ the condition actually will go to sleep before the condition is
+ signaled. */
+ pthread_mutex_lock(&dev->mutex);
+ pthread_cond_broadcast(&dev->condition);
+ pthread_mutex_unlock(&dev->mutex);
+
+ /* The dev->transfer->buffer and dev->transfer objects are cleaned up
+ in hid_close(). They are not cleaned up here because this thread
+ could end either due to a disconnect or due to a user
+ call to hid_close(). In both cases the objects can be safely
+ cleaned up after the call to pthread_join() (in hid_close()), but
+ since hid_close() calls libusb_cancel_transfer(), on these objects,
+ they can not be cleaned up here. */
+
+ return NULL;
+}
+
+
+hid_device * HID_API_EXPORT hid_open_path(const char *path)
+{
+ hid_device *dev = NULL;
+
+ libusb_device **devs;
+ libusb_device *usb_dev;
+ int res;
+ int d = 0;
+ int good_open = 0;
+
+ if(hid_init() < 0)
+ return NULL;
+
+ dev = new_hid_device();
+
+ libusb_get_device_list(usb_context, &devs);
+ while ((usb_dev = devs[d++]) != NULL) {
+ struct libusb_device_descriptor desc;
+ struct libusb_config_descriptor *conf_desc = NULL;
+ int i,j,k;
+ libusb_get_device_descriptor(usb_dev, &desc);
+
+ if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
+ continue;
+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
+ const struct libusb_interface *intf = &conf_desc->interface[j];
+ for (k = 0; k < intf->num_altsetting; k++) {
+ const struct libusb_interface_descriptor *intf_desc;
+ intf_desc = &intf->altsetting[k];
+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
+ char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
+ if (!strcmp(dev_path, path)) {
+ /* Matched Paths. Open this device */
+
+ /* OPEN HERE */
+ res = libusb_open(usb_dev, &dev->device_handle);
+ if (res < 0) {
+ LOG("can't open device\n");
+ free(dev_path);
+ break;
+ }
+ good_open = 1;
+#ifdef DETACH_KERNEL_DRIVER
+ /* Detach the kernel driver, but only if the
+ device is managed by the kernel */
+ if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
+ res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
+ if (res < 0) {
+ libusb_close(dev->device_handle);
+ LOG("Unable to detach Kernel Driver\n");
+ free(dev_path);
+ good_open = 0;
+ break;
+ }
+ }
+#endif
+ res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
+ if (res < 0) {
+ LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
+ free(dev_path);
+ libusb_close(dev->device_handle);
+ good_open = 0;
+ break;
+ }
+
+ /* Store off the string descriptor indexes */
+ dev->manufacturer_index = desc.iManufacturer;
+ dev->product_index = desc.iProduct;
+ dev->serial_index = desc.iSerialNumber;
+
+ /* Store off the interface number */
+ dev->interface = intf_desc->bInterfaceNumber;
+
+ /* Find the INPUT and OUTPUT endpoints. An
+ OUTPUT endpoint is not required. */
+ for (i = 0; i < intf_desc->bNumEndpoints; i++) {
+ const struct libusb_endpoint_descriptor *ep
+ = &intf_desc->endpoint[i];
+
+ /* Determine the type and direction of this
+ endpoint. */
+ int is_interrupt =
+ (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
+ == LIBUSB_TRANSFER_TYPE_INTERRUPT;
+ int is_output =
+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
+ == LIBUSB_ENDPOINT_OUT;
+ int is_input =
+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
+ == LIBUSB_ENDPOINT_IN;
+
+ /* Decide whether to use it for input or output. */
+ if (dev->input_endpoint == 0 &&
+ is_interrupt && is_input) {
+ /* Use this endpoint for INPUT */
+ dev->input_endpoint = ep->bEndpointAddress;
+ dev->input_ep_max_packet_size = ep->wMaxPacketSize;
+ }
+ if (dev->output_endpoint == 0 &&
+ is_interrupt && is_output) {
+ /* Use this endpoint for OUTPUT */
+ dev->output_endpoint = ep->bEndpointAddress;
+ }
+ }
+
+ pthread_create(&dev->thread, NULL, read_thread, dev);
+
+ /* Wait here for the read thread to be initialized. */
+ pthread_barrier_wait(&dev->barrier);
+
+ }
+ free(dev_path);
+ }
+ }
+ }
+ libusb_free_config_descriptor(conf_desc);
+
+ }
+
+ libusb_free_device_list(devs, 1);
+
+ /* If we have a good handle, return it. */
+ if (good_open) {
+ return dev;
+ }
+ else {
+ /* Unable to open any devices. */
+ free_hid_device(dev);
+ return NULL;
+ }
+}
+
+
+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
+{
+ int res;
+ int report_number = data[0];
+ int skipped_report_id = 0;
+
+ if (report_number == 0x0) {
+ data++;
+ length--;
+ skipped_report_id = 1;
+ }
+
+
+ if (dev->output_endpoint <= 0) {
+ /* No interrupt out endpoint. Use the Control Endpoint */
+ res = libusb_control_transfer(dev->device_handle,
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
+ 0x09/*HID Set_Report*/,
+ (2/*HID output*/ << 8) | report_number,
+ dev->interface,
+ (unsigned char *)data, length,
+ 1000/*timeout millis*/);
+
+ if (res < 0)
+ return -1;
+
+ if (skipped_report_id)
+ length++;
+
+ return length;
+ }
+ else {
+ /* Use the interrupt out endpoint */
+ int actual_length;
+ res = libusb_interrupt_transfer(dev->device_handle,
+ dev->output_endpoint,
+ (unsigned char*)data,
+ length,
+ &actual_length, 1000);
+
+ if (res < 0)
+ return -1;
+
+ if (skipped_report_id)
+ actual_length++;
+
+ return actual_length;
+ }
+}
+
+/* Helper function, to simplify hid_read().
+ This should be called with dev->mutex locked. */
+static int return_data(hid_device *dev, unsigned char *data, size_t length)
+{
+ /* Copy the data out of the linked list item (rpt) into the
+ return buffer (data), and delete the liked list item. */
+ struct input_report *rpt = dev->input_reports;
+ size_t len = (length < rpt->len)? length: rpt->len;
+ if (len > 0)
+ memcpy(data, rpt->data, len);
+ dev->input_reports = rpt->next;
+ free(rpt->data);
+ free(rpt);
+ return len;
+}
+
+static void cleanup_mutex(void *param)
+{
+ hid_device *dev = param;
+ pthread_mutex_unlock(&dev->mutex);
+}
+
+
+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
+{
+ int bytes_read = -1;
+
+#if 0
+ int transferred;
+ int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
+ LOG("transferred: %d\n", transferred);
+ return transferred;
+#endif
+
+ pthread_mutex_lock(&dev->mutex);
+ pthread_cleanup_push(&cleanup_mutex, dev);
+
+ /* There's an input report queued up. Return it. */
+ if (dev->input_reports) {
+ /* Return the first one */
+ bytes_read = return_data(dev, data, length);
+ goto ret;
+ }
+
+ if (dev->shutdown_thread) {
+ /* This means the device has been disconnected.
+ An error code of -1 should be returned. */
+ bytes_read = -1;
+ goto ret;
+ }
+
+ if (milliseconds == -1) {
+ /* Blocking */
+ while (!dev->input_reports && !dev->shutdown_thread) {
+ pthread_cond_wait(&dev->condition, &dev->mutex);
+ }
+ if (dev->input_reports) {
+ bytes_read = return_data(dev, data, length);
+ }
+ }
+ else if (milliseconds > 0) {
+ /* Non-blocking, but called with timeout. */
+ int res;
+ struct timespec ts;
+ clock_gettime(CLOCK_REALTIME, &ts);
+ ts.tv_sec += milliseconds / 1000;
+ ts.tv_nsec += (milliseconds % 1000) * 1000000;
+ if (ts.tv_nsec >= 1000000000L) {
+ ts.tv_sec++;
+ ts.tv_nsec -= 1000000000L;
+ }
+
+ while (!dev->input_reports && !dev->shutdown_thread) {
+ res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
+ if (res == 0) {
+ if (dev->input_reports) {
+ bytes_read = return_data(dev, data, length);
+ break;
+ }
+
+ /* If we're here, there was a spurious wake up
+ or the read thread was shutdown. Run the
+ loop again (ie: don't break). */
+ }
+ else if (res == ETIMEDOUT) {
+ /* Timed out. */
+ bytes_read = 0;
+ break;
+ }
+ else {
+ /* Error. */
+ bytes_read = -1;
+ break;
+ }
+ }
+ }
+ else {
+ /* Purely non-blocking */
+ bytes_read = 0;
+ }
+
+ret:
+ pthread_mutex_unlock(&dev->mutex);
+ pthread_cleanup_pop(0);
+
+ return bytes_read;
+}
+
+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
+{
+ return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
+}
+
+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
+{
+ dev->blocking = !nonblock;
+
+ return 0;
+}
+
+
+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
+{
+ int res = -1;
+ int skipped_report_id = 0;
+ int report_number = data[0];
+
+ if (report_number == 0x0) {
+ data++;
+ length--;
+ skipped_report_id = 1;
+ }
+
+ res = libusb_control_transfer(dev->device_handle,
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
+ 0x09/*HID set_report*/,
+ (3/*HID feature*/ << 8) | report_number,
+ dev->interface,
+ (unsigned char *)data, length,
+ 1000/*timeout millis*/);
+
+ if (res < 0)
+ return -1;
+
+ /* Account for the report ID */
+ if (skipped_report_id)
+ length++;
+
+ return length;
+}
+
+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
+{
+ int res = -1;
+ int skipped_report_id = 0;
+ int report_number = data[0];
+
+ if (report_number == 0x0) {
+ /* Offset the return buffer by 1, so that the report ID
+ will remain in byte 0. */
+ data++;
+ length--;
+ skipped_report_id = 1;
+ }
+ res = libusb_control_transfer(dev->device_handle,
+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
+ 0x01/*HID get_report*/,
+ (3/*HID feature*/ << 8) | report_number,
+ dev->interface,
+ (unsigned char *)data, length,
+ 1000/*timeout millis*/);
+
+ if (res < 0)
+ return -1;
+
+ if (skipped_report_id)
+ res++;
+
+ return res;
+}
+
+
+void HID_API_EXPORT hid_close(hid_device *dev)
+{
+ if (!dev)
+ return;
+
+ /* Cause read_thread() to stop. */
+ dev->shutdown_thread = 1;
+ libusb_cancel_transfer(dev->transfer);
+
+ /* Wait for read_thread() to end. */
+ pthread_join(dev->thread, NULL);
+
+ /* Clean up the Transfer objects allocated in read_thread(). */
+ free(dev->transfer->buffer);
+ libusb_free_transfer(dev->transfer);
+
+ /* release the interface */
+ libusb_release_interface(dev->device_handle, dev->interface);
+
+ /* Close the handle */
+ libusb_close(dev->device_handle);
+
+ /* Clear out the queue of received reports. */
+ pthread_mutex_lock(&dev->mutex);
+ while (dev->input_reports) {
+ return_data(dev, NULL, 0);
+ }
+ pthread_mutex_unlock(&dev->mutex);
+
+ free_hid_device(dev);
+}
+
+
+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
+{
+ wchar_t *str;
+
+ str = get_usb_string(dev->device_handle, string_index);
+ if (str) {
+ wcsncpy(string, str, maxlen);
+ string[maxlen-1] = L'\0';
+ free(str);
+ return 0;
+ }
+ else
+ return -1;
+}
+
+
+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
+{
+ return NULL;
+}
+
+
+struct lang_map_entry {
+ const char *name;
+ const char *string_code;
+ uint16_t usb_code;
+};
+
+#define LANG(name,code,usb_code) { name, code, usb_code }
+static struct lang_map_entry lang_map[] = {
+ LANG("Afrikaans", "af", 0x0436),
+ LANG("Albanian", "sq", 0x041C),
+ LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
+ LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
+ LANG("Arabic - Algeria", "ar_dz", 0x1401),
+ LANG("Arabic - Egypt", "ar_eg", 0x0C01),
+ LANG("Arabic - Iraq", "ar_iq", 0x0801),
+ LANG("Arabic - Jordan", "ar_jo", 0x2C01),
+ LANG("Arabic - Kuwait", "ar_kw", 0x3401),
+ LANG("Arabic - Lebanon", "ar_lb", 0x3001),
+ LANG("Arabic - Libya", "ar_ly", 0x1001),
+ LANG("Arabic - Morocco", "ar_ma", 0x1801),
+ LANG("Arabic - Oman", "ar_om", 0x2001),
+ LANG("Arabic - Qatar", "ar_qa", 0x4001),
+ LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
+ LANG("Arabic - Syria", "ar_sy", 0x2801),
+ LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
+ LANG("Arabic - Yemen", "ar_ye", 0x2401),
+ LANG("Armenian", "hy", 0x042B),
+ LANG("Azeri - Latin", "az_az", 0x042C),
+ LANG("Azeri - Cyrillic", "az_az", 0x082C),
+ LANG("Basque", "eu", 0x042D),
+ LANG("Belarusian", "be", 0x0423),
+ LANG("Bulgarian", "bg", 0x0402),
+ LANG("Catalan", "ca", 0x0403),
+ LANG("Chinese - China", "zh_cn", 0x0804),
+ LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
+ LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
+ LANG("Chinese - Singapore", "zh_sg", 0x1004),
+ LANG("Chinese - Taiwan", "zh_tw", 0x0404),
+ LANG("Croatian", "hr", 0x041A),
+ LANG("Czech", "cs", 0x0405),
+ LANG("Danish", "da", 0x0406),
+ LANG("Dutch - Netherlands", "nl_nl", 0x0413),
+ LANG("Dutch - Belgium", "nl_be", 0x0813),
+ LANG("English - Australia", "en_au", 0x0C09),
+ LANG("English - Belize", "en_bz", 0x2809),
+ LANG("English - Canada", "en_ca", 0x1009),
+ LANG("English - Caribbean", "en_cb", 0x2409),
+ LANG("English - Ireland", "en_ie", 0x1809),
+ LANG("English - Jamaica", "en_jm", 0x2009),
+ LANG("English - New Zealand", "en_nz", 0x1409),
+ LANG("English - Phillippines", "en_ph", 0x3409),
+ LANG("English - Southern Africa", "en_za", 0x1C09),
+ LANG("English - Trinidad", "en_tt", 0x2C09),
+ LANG("English - Great Britain", "en_gb", 0x0809),
+ LANG("English - United States", "en_us", 0x0409),
+ LANG("Estonian", "et", 0x0425),
+ LANG("Farsi", "fa", 0x0429),
+ LANG("Finnish", "fi", 0x040B),
+ LANG("Faroese", "fo", 0x0438),
+ LANG("French - France", "fr_fr", 0x040C),
+ LANG("French - Belgium", "fr_be", 0x080C),
+ LANG("French - Canada", "fr_ca", 0x0C0C),
+ LANG("French - Luxembourg", "fr_lu", 0x140C),
+ LANG("French - Switzerland", "fr_ch", 0x100C),
+ LANG("Gaelic - Ireland", "gd_ie", 0x083C),
+ LANG("Gaelic - Scotland", "gd", 0x043C),
+ LANG("German - Germany", "de_de", 0x0407),
+ LANG("German - Austria", "de_at", 0x0C07),
+ LANG("German - Liechtenstein", "de_li", 0x1407),
+ LANG("German - Luxembourg", "de_lu", 0x1007),
+ LANG("German - Switzerland", "de_ch", 0x0807),
+ LANG("Greek", "el", 0x0408),
+ LANG("Hebrew", "he", 0x040D),
+ LANG("Hindi", "hi", 0x0439),
+ LANG("Hungarian", "hu", 0x040E),
+ LANG("Icelandic", "is", 0x040F),
+ LANG("Indonesian", "id", 0x0421),
+ LANG("Italian - Italy", "it_it", 0x0410),
+ LANG("Italian - Switzerland", "it_ch", 0x0810),
+ LANG("Japanese", "ja", 0x0411),
+ LANG("Korean", "ko", 0x0412),
+ LANG("Latvian", "lv", 0x0426),
+ LANG("Lithuanian", "lt", 0x0427),
+ LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
+ LANG("Malay - Malaysia", "ms_my", 0x043E),
+ LANG("Malay – Brunei", "ms_bn", 0x083E),
+ LANG("Maltese", "mt", 0x043A),
+ LANG("Marathi", "mr", 0x044E),
+ LANG("Norwegian - Bokml", "no_no", 0x0414),
+ LANG("Norwegian - Nynorsk", "no_no", 0x0814),
+ LANG("Polish", "pl", 0x0415),
+ LANG("Portuguese - Portugal", "pt_pt", 0x0816),
+ LANG("Portuguese - Brazil", "pt_br", 0x0416),
+ LANG("Raeto-Romance", "rm", 0x0417),
+ LANG("Romanian - Romania", "ro", 0x0418),
+ LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
+ LANG("Russian", "ru", 0x0419),
+ LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
+ LANG("Sanskrit", "sa", 0x044F),
+ LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
+ LANG("Serbian - Latin", "sr_sp", 0x081A),
+ LANG("Setsuana", "tn", 0x0432),
+ LANG("Slovenian", "sl", 0x0424),
+ LANG("Slovak", "sk", 0x041B),
+ LANG("Sorbian", "sb", 0x042E),
+ LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
+ LANG("Spanish - Argentina", "es_ar", 0x2C0A),
+ LANG("Spanish - Bolivia", "es_bo", 0x400A),
+ LANG("Spanish - Chile", "es_cl", 0x340A),
+ LANG("Spanish - Colombia", "es_co", 0x240A),
+ LANG("Spanish - Costa Rica", "es_cr", 0x140A),
+ LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
+ LANG("Spanish - Ecuador", "es_ec", 0x300A),
+ LANG("Spanish - Guatemala", "es_gt", 0x100A),
+ LANG("Spanish - Honduras", "es_hn", 0x480A),
+ LANG("Spanish - Mexico", "es_mx", 0x080A),
+ LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
+ LANG("Spanish - Panama", "es_pa", 0x180A),
+ LANG("Spanish - Peru", "es_pe", 0x280A),
+ LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
+ LANG("Spanish - Paraguay", "es_py", 0x3C0A),
+ LANG("Spanish - El Salvador", "es_sv", 0x440A),
+ LANG("Spanish - Uruguay", "es_uy", 0x380A),
+ LANG("Spanish - Venezuela", "es_ve", 0x200A),
+ LANG("Southern Sotho", "st", 0x0430),
+ LANG("Swahili", "sw", 0x0441),
+ LANG("Swedish - Sweden", "sv_se", 0x041D),
+ LANG("Swedish - Finland", "sv_fi", 0x081D),
+ LANG("Tamil", "ta", 0x0449),
+ LANG("Tatar", "tt", 0X0444),
+ LANG("Thai", "th", 0x041E),
+ LANG("Turkish", "tr", 0x041F),
+ LANG("Tsonga", "ts", 0x0431),
+ LANG("Ukrainian", "uk", 0x0422),
+ LANG("Urdu", "ur", 0x0420),
+ LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
+ LANG("Uzbek – Latin", "uz_uz", 0x0443),
+ LANG("Vietnamese", "vi", 0x042A),
+ LANG("Xhosa", "xh", 0x0434),
+ LANG("Yiddish", "yi", 0x043D),
+ LANG("Zulu", "zu", 0x0435),
+ LANG(NULL, NULL, 0x0),
+};
+
+uint16_t get_usb_code_for_current_locale(void)
+{
+ char *locale;
+ char search_string[64];
+ char *ptr;
+ struct lang_map_entry *lang;
+
+ /* Get the current locale. */
+ locale = setlocale(0, NULL);
+ if (!locale)
+ return 0x0;
+
+ /* Make a copy of the current locale string. */
+ strncpy(search_string, locale, sizeof(search_string));
+ search_string[sizeof(search_string)-1] = '\0';
+
+ /* Chop off the encoding part, and make it lower case. */
+ ptr = search_string;
+ while (*ptr) {
+ *ptr = tolower(*ptr);
+ if (*ptr == '.') {
+ *ptr = '\0';
+ break;
+ }
+ ptr++;
+ }
+
+ /* Find the entry which matches the string code of our locale. */
+ lang = lang_map;
+ while (lang->string_code) {
+ if (!strcmp(lang->string_code, search_string)) {
+ return lang->usb_code;
+ }
+ lang++;
+ }
+
+ /* There was no match. Find with just the language only. */
+ /* Chop off the variant. Chop it off at the '_'. */
+ ptr = search_string;
+ while (*ptr) {
+ *ptr = tolower(*ptr);
+ if (*ptr == '_') {
+ *ptr = '\0';
+ break;
+ }
+ ptr++;
+ }
+
+#if 0 /* TODO: Do we need this? */
+ /* Find the entry which matches the string code of our language. */
+ lang = lang_map;
+ while (lang->string_code) {
+ if (!strcmp(lang->string_code, search_string)) {
+ return lang->usb_code;
+ }
+ lang++;
+ }
+#endif
+
+ /* Found nothing. */
+ return 0x0;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/vendor/github.com/karalabe/usb/hidapi/mac/hid.c b/vendor/github.com/karalabe/usb/hidapi/mac/hid.c
new file mode 100644
index 000000000..e0756a158
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/mac/hid.c
@@ -0,0 +1,1110 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 2010-07-03
+
+ Copyright 2010, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+/* See Apple Technical Note TN2187 for details on IOHidManager. */
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "hidapi.h"
+
+/* Barrier implementation because Mac OSX doesn't have pthread_barrier.
+ It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
+ This implementation came from Brent Priddy and was posted on
+ StackOverflow. It is used with his permission. */
+typedef int pthread_barrierattr_t;
+typedef struct pthread_barrier {
+ pthread_mutex_t mutex;
+ pthread_cond_t cond;
+ int count;
+ int trip_count;
+} pthread_barrier_t;
+
+static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
+{
+ if(count == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
+ return -1;
+ }
+ if(pthread_cond_init(&barrier->cond, 0) < 0) {
+ pthread_mutex_destroy(&barrier->mutex);
+ return -1;
+ }
+ barrier->trip_count = count;
+ barrier->count = 0;
+
+ return 0;
+}
+
+static int pthread_barrier_destroy(pthread_barrier_t *barrier)
+{
+ pthread_cond_destroy(&barrier->cond);
+ pthread_mutex_destroy(&barrier->mutex);
+ return 0;
+}
+
+static int pthread_barrier_wait(pthread_barrier_t *barrier)
+{
+ pthread_mutex_lock(&barrier->mutex);
+ ++(barrier->count);
+ if(barrier->count >= barrier->trip_count)
+ {
+ barrier->count = 0;
+ pthread_cond_broadcast(&barrier->cond);
+ pthread_mutex_unlock(&barrier->mutex);
+ return 1;
+ }
+ else
+ {
+ pthread_cond_wait(&barrier->cond, &(barrier->mutex));
+ pthread_mutex_unlock(&barrier->mutex);
+ return 0;
+ }
+}
+
+static int return_data(hid_device *dev, unsigned char *data, size_t length);
+
+/* Linked List of input reports received from the device. */
+struct input_report {
+ uint8_t *data;
+ size_t len;
+ struct input_report *next;
+};
+
+struct hid_device_ {
+ IOHIDDeviceRef device_handle;
+ int blocking;
+ int uses_numbered_reports;
+ int disconnected;
+ CFStringRef run_loop_mode;
+ CFRunLoopRef run_loop;
+ CFRunLoopSourceRef source;
+ uint8_t *input_report_buf;
+ CFIndex max_input_report_len;
+ struct input_report *input_reports;
+
+ pthread_t thread;
+ pthread_mutex_t mutex; /* Protects input_reports */
+ pthread_cond_t condition;
+ pthread_barrier_t barrier; /* Ensures correct startup sequence */
+ pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */
+ int shutdown_thread;
+};
+
+static hid_device *new_hid_device(void)
+{
+ hid_device *dev = calloc(1, sizeof(hid_device));
+ dev->device_handle = NULL;
+ dev->blocking = 1;
+ dev->uses_numbered_reports = 0;
+ dev->disconnected = 0;
+ dev->run_loop_mode = NULL;
+ dev->run_loop = NULL;
+ dev->source = NULL;
+ dev->input_report_buf = NULL;
+ dev->input_reports = NULL;
+ dev->shutdown_thread = 0;
+
+ /* Thread objects */
+ pthread_mutex_init(&dev->mutex, NULL);
+ pthread_cond_init(&dev->condition, NULL);
+ pthread_barrier_init(&dev->barrier, NULL, 2);
+ pthread_barrier_init(&dev->shutdown_barrier, NULL, 2);
+
+ return dev;
+}
+
+static void free_hid_device(hid_device *dev)
+{
+ if (!dev)
+ return;
+
+ /* Delete any input reports still left over. */
+ struct input_report *rpt = dev->input_reports;
+ while (rpt) {
+ struct input_report *next = rpt->next;
+ free(rpt->data);
+ free(rpt);
+ rpt = next;
+ }
+
+ /* Free the string and the report buffer. The check for NULL
+ is necessary here as CFRelease() doesn't handle NULL like
+ free() and others do. */
+ if (dev->run_loop_mode)
+ CFRelease(dev->run_loop_mode);
+ if (dev->source)
+ CFRelease(dev->source);
+ free(dev->input_report_buf);
+
+ /* Clean up the thread objects */
+ pthread_barrier_destroy(&dev->shutdown_barrier);
+ pthread_barrier_destroy(&dev->barrier);
+ pthread_cond_destroy(&dev->condition);
+ pthread_mutex_destroy(&dev->mutex);
+
+ /* Free the structure itself. */
+ free(dev);
+}
+
+static IOHIDManagerRef hid_mgr = 0x0;
+
+
+#if 0
+static void register_error(hid_device *device, const char *op)
+{
+
+}
+#endif
+
+
+static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key)
+{
+ CFTypeRef ref;
+ int32_t value;
+
+ ref = IOHIDDeviceGetProperty(device, key);
+ if (ref) {
+ if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
+ CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value);
+ return value;
+ }
+ }
+ return 0;
+}
+
+static unsigned short get_vendor_id(IOHIDDeviceRef device)
+{
+ return get_int_property(device, CFSTR(kIOHIDVendorIDKey));
+}
+
+static unsigned short get_product_id(IOHIDDeviceRef device)
+{
+ return get_int_property(device, CFSTR(kIOHIDProductIDKey));
+}
+
+static int32_t get_max_report_length(IOHIDDeviceRef device)
+{
+ return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
+}
+
+static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len)
+{
+ CFStringRef str;
+
+ if (!len)
+ return 0;
+
+ str = IOHIDDeviceGetProperty(device, prop);
+
+ buf[0] = 0;
+
+ if (str) {
+ CFIndex str_len = CFStringGetLength(str);
+ CFRange range;
+ CFIndex used_buf_len;
+ CFIndex chars_copied;
+
+ len --;
+
+ range.location = 0;
+ range.length = ((size_t)str_len > len)? len: (size_t)str_len;
+ chars_copied = CFStringGetBytes(str,
+ range,
+ kCFStringEncodingUTF32LE,
+ (char)'?',
+ FALSE,
+ (UInt8*)buf,
+ len * sizeof(wchar_t),
+ &used_buf_len);
+
+ if (chars_copied == len)
+ buf[len] = 0; /* len is decremented above */
+ else
+ buf[chars_copied] = 0;
+
+ return 0;
+ }
+ else
+ return -1;
+
+}
+
+static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len)
+{
+ return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len);
+}
+
+static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
+{
+ return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len);
+}
+
+static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
+{
+ return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len);
+}
+
+
+/* Implementation of wcsdup() for Mac. */
+static wchar_t *dup_wcs(const wchar_t *s)
+{
+ size_t len = wcslen(s);
+ wchar_t *ret = malloc((len+1)*sizeof(wchar_t));
+ wcscpy(ret, s);
+
+ return ret;
+}
+
+/* hidapi_IOHIDDeviceGetService()
+ *
+ * Return the io_service_t corresponding to a given IOHIDDeviceRef, either by:
+ * - on OS X 10.6 and above, calling IOHIDDeviceGetService()
+ * - on OS X 10.5, extract it from the IOHIDDevice struct
+ */
+static io_service_t hidapi_IOHIDDeviceGetService(IOHIDDeviceRef device)
+{
+ static void *iokit_framework = NULL;
+ static io_service_t (*dynamic_IOHIDDeviceGetService)(IOHIDDeviceRef device) = NULL;
+
+ /* Use dlopen()/dlsym() to get a pointer to IOHIDDeviceGetService() if it exists.
+ * If any of these steps fail, dynamic_IOHIDDeviceGetService will be left NULL
+ * and the fallback method will be used.
+ */
+ if (iokit_framework == NULL) {
+ iokit_framework = dlopen("/System/Library/IOKit.framework/IOKit", RTLD_LAZY);
+
+ if (iokit_framework != NULL)
+ dynamic_IOHIDDeviceGetService = dlsym(iokit_framework, "IOHIDDeviceGetService");
+ }
+
+ if (dynamic_IOHIDDeviceGetService != NULL) {
+ /* Running on OS X 10.6 and above: IOHIDDeviceGetService() exists */
+ return dynamic_IOHIDDeviceGetService(device);
+ }
+ else
+ {
+ /* Running on OS X 10.5: IOHIDDeviceGetService() doesn't exist.
+ *
+ * Be naughty and pull the service out of the IOHIDDevice.
+ * IOHIDDevice is an opaque struct not exposed to applications, but its
+ * layout is stable through all available versions of OS X.
+ * Tested and working on OS X 10.5.8 i386, x86_64, and ppc.
+ */
+ struct IOHIDDevice_internal {
+ /* The first field of the IOHIDDevice struct is a
+ * CFRuntimeBase (which is a private CF struct).
+ *
+ * a, b, and c are the 3 fields that make up a CFRuntimeBase.
+ * See http://opensource.apple.com/source/CF/CF-476.18/CFRuntime.h
+ *
+ * The second field of the IOHIDDevice is the io_service_t we're looking for.
+ */
+ uintptr_t a;
+ uint8_t b[4];
+#if __LP64__
+ uint32_t c;
+#endif
+ io_service_t service;
+ };
+ struct IOHIDDevice_internal *tmp = (struct IOHIDDevice_internal *)device;
+
+ return tmp->service;
+ }
+}
+
+/* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */
+static int init_hid_manager(void)
+{
+ /* Initialize all the HID Manager Objects */
+ hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
+ if (hid_mgr) {
+ IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
+ IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
+ return 0;
+ }
+
+ return -1;
+}
+
+/* Initialize the IOHIDManager if necessary. This is the public function, and
+ it is safe to call this function repeatedly. Return 0 for success and -1
+ for failure. */
+int HID_API_EXPORT hid_init(void)
+{
+ if (!hid_mgr) {
+ return init_hid_manager();
+ }
+
+ /* Already initialized. */
+ return 0;
+}
+
+int HID_API_EXPORT hid_exit(void)
+{
+ if (hid_mgr) {
+ /* Close the HID manager. */
+ IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone);
+ CFRelease(hid_mgr);
+ hid_mgr = NULL;
+ }
+
+ return 0;
+}
+
+static void process_pending_events(void) {
+ SInt32 res;
+ do {
+ res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE);
+ } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut);
+}
+
+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
+{
+ struct hid_device_info *root = NULL; /* return object */
+ struct hid_device_info *cur_dev = NULL;
+ CFIndex num_devices;
+ int i;
+
+ /* Set up the HID Manager if it hasn't been done */
+ if (hid_init() < 0)
+ return NULL;
+
+ /* give the IOHIDManager a chance to update itself */
+ process_pending_events();
+
+ /* Get a list of the Devices */
+ IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
+ CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
+
+ /* Convert the list into a C array so we can iterate easily. */
+ num_devices = CFSetGetCount(device_set);
+ IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
+ CFSetGetValues(device_set, (const void **) device_array);
+
+ /* Iterate over each device, making an entry for it. */
+ for (i = 0; i < num_devices; i++) {
+ unsigned short dev_vid;
+ unsigned short dev_pid;
+ #define BUF_LEN 256
+ wchar_t buf[BUF_LEN];
+
+ IOHIDDeviceRef dev = device_array[i];
+
+ if (!dev) {
+ continue;
+ }
+ dev_vid = get_vendor_id(dev);
+ dev_pid = get_product_id(dev);
+
+ /* Check the VID/PID against the arguments */
+ if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
+ (product_id == 0x0 || product_id == dev_pid)) {
+ struct hid_device_info *tmp;
+ io_object_t iokit_dev;
+ kern_return_t res;
+ io_string_t path;
+
+ /* VID/PID match. Create the record. */
+ tmp = malloc(sizeof(struct hid_device_info));
+ if (cur_dev) {
+ cur_dev->next = tmp;
+ }
+ else {
+ root = tmp;
+ }
+ cur_dev = tmp;
+
+ /* Get the Usage Page and Usage for this device. */
+ cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey));
+ cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey));
+
+ /* Fill out the record */
+ cur_dev->next = NULL;
+
+ /* Fill in the path (IOService plane) */
+ iokit_dev = hidapi_IOHIDDeviceGetService(dev);
+ res = IORegistryEntryGetPath(iokit_dev, kIOServicePlane, path);
+ if (res == KERN_SUCCESS)
+ cur_dev->path = strdup(path);
+ else
+ cur_dev->path = strdup("");
+
+ /* Serial Number */
+ get_serial_number(dev, buf, BUF_LEN);
+ cur_dev->serial_number = dup_wcs(buf);
+
+ /* Manufacturer and Product strings */
+ get_manufacturer_string(dev, buf, BUF_LEN);
+ cur_dev->manufacturer_string = dup_wcs(buf);
+ get_product_string(dev, buf, BUF_LEN);
+ cur_dev->product_string = dup_wcs(buf);
+
+ /* VID/PID */
+ cur_dev->vendor_id = dev_vid;
+ cur_dev->product_id = dev_pid;
+
+ /* Release Number */
+ cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));
+
+ /* Interface Number (Unsupported on Mac)*/
+ cur_dev->interface_number = -1;
+ }
+ }
+
+ free(device_array);
+ CFRelease(device_set);
+
+ return root;
+}
+
+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
+{
+ /* This function is identical to the Linux version. Platform independent. */
+ struct hid_device_info *d = devs;
+ while (d) {
+ struct hid_device_info *next = d->next;
+ free(d->path);
+ free(d->serial_number);
+ free(d->manufacturer_string);
+ free(d->product_string);
+ free(d);
+ d = next;
+ }
+}
+
+hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
+{
+ /* This function is identical to the Linux version. Platform independent. */
+ struct hid_device_info *devs, *cur_dev;
+ const char *path_to_open = NULL;
+ hid_device * handle = NULL;
+
+ devs = hid_enumerate(vendor_id, product_id);
+ cur_dev = devs;
+ while (cur_dev) {
+ if (cur_dev->vendor_id == vendor_id &&
+ cur_dev->product_id == product_id) {
+ if (serial_number) {
+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ else {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ cur_dev = cur_dev->next;
+ }
+
+ if (path_to_open) {
+ /* Open the device */
+ handle = hid_open_path(path_to_open);
+ }
+
+ hid_free_enumeration(devs);
+
+ return handle;
+}
+
+static void hid_device_removal_callback(void *context, IOReturn result,
+ void *sender)
+{
+ /* Stop the Run Loop for this device. */
+ hid_device *d = context;
+
+ d->disconnected = 1;
+ CFRunLoopStop(d->run_loop);
+}
+
+/* The Run Loop calls this function for each input report received.
+ This function puts the data into a linked list to be picked up by
+ hid_read(). */
+static void hid_report_callback(void *context, IOReturn result, void *sender,
+ IOHIDReportType report_type, uint32_t report_id,
+ uint8_t *report, CFIndex report_length)
+{
+ struct input_report *rpt;
+ hid_device *dev = context;
+
+ /* Make a new Input Report object */
+ rpt = calloc(1, sizeof(struct input_report));
+ rpt->data = calloc(1, report_length);
+ memcpy(rpt->data, report, report_length);
+ rpt->len = report_length;
+ rpt->next = NULL;
+
+ /* Lock this section */
+ pthread_mutex_lock(&dev->mutex);
+
+ /* Attach the new report object to the end of the list. */
+ if (dev->input_reports == NULL) {
+ /* The list is empty. Put it at the root. */
+ dev->input_reports = rpt;
+ }
+ else {
+ /* Find the end of the list and attach. */
+ struct input_report *cur = dev->input_reports;
+ int num_queued = 0;
+ while (cur->next != NULL) {
+ cur = cur->next;
+ num_queued++;
+ }
+ cur->next = rpt;
+
+ /* Pop one off if we've reached 30 in the queue. This
+ way we don't grow forever if the user never reads
+ anything from the device. */
+ if (num_queued > 30) {
+ return_data(dev, NULL, 0);
+ }
+ }
+
+ /* Signal a waiting thread that there is data. */
+ pthread_cond_signal(&dev->condition);
+
+ /* Unlock */
+ pthread_mutex_unlock(&dev->mutex);
+
+}
+
+/* This gets called when the read_thread's run loop gets signaled by
+ hid_close(), and serves to stop the read_thread's run loop. */
+static void perform_signal_callback(void *context)
+{
+ hid_device *dev = context;
+ CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/
+}
+
+static void *read_thread(void *param)
+{
+ hid_device *dev = param;
+ SInt32 code;
+
+ /* Move the device's run loop to this thread. */
+ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
+
+ /* Create the RunLoopSource which is used to signal the
+ event loop to stop when hid_close() is called. */
+ CFRunLoopSourceContext ctx;
+ memset(&ctx, 0, sizeof(ctx));
+ ctx.version = 0;
+ ctx.info = dev;
+ ctx.perform = &perform_signal_callback;
+ dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
+ CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
+
+ /* Store off the Run Loop so it can be stopped from hid_close()
+ and on device disconnection. */
+ dev->run_loop = CFRunLoopGetCurrent();
+
+ /* Notify the main thread that the read thread is up and running. */
+ pthread_barrier_wait(&dev->barrier);
+
+ /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
+ reports into the hid_report_callback(). */
+ while (!dev->shutdown_thread && !dev->disconnected) {
+ code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
+ /* Return if the device has been disconnected */
+ if (code == kCFRunLoopRunFinished) {
+ dev->disconnected = 1;
+ break;
+ }
+
+
+ /* Break if The Run Loop returns Finished or Stopped. */
+ if (code != kCFRunLoopRunTimedOut &&
+ code != kCFRunLoopRunHandledSource) {
+ /* There was some kind of error. Setting
+ shutdown seems to make sense, but
+ there may be something else more appropriate */
+ dev->shutdown_thread = 1;
+ break;
+ }
+ }
+
+ /* Now that the read thread is stopping, Wake any threads which are
+ waiting on data (in hid_read_timeout()). Do this under a mutex to
+ make sure that a thread which is about to go to sleep waiting on
+ the condition actually will go to sleep before the condition is
+ signaled. */
+ pthread_mutex_lock(&dev->mutex);
+ pthread_cond_broadcast(&dev->condition);
+ pthread_mutex_unlock(&dev->mutex);
+
+ /* Wait here until hid_close() is called and makes it past
+ the call to CFRunLoopWakeUp(). This thread still needs to
+ be valid when that function is called on the other thread. */
+ pthread_barrier_wait(&dev->shutdown_barrier);
+
+ return NULL;
+}
+
+/* hid_open_path()
+ *
+ * path must be a valid path to an IOHIDDevice in the IOService plane
+ * Example: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver"
+ */
+hid_device * HID_API_EXPORT hid_open_path(const char *path)
+{
+ hid_device *dev = NULL;
+ io_registry_entry_t entry = MACH_PORT_NULL;
+
+ dev = new_hid_device();
+
+ /* Set up the HID Manager if it hasn't been done */
+ if (hid_init() < 0)
+ return NULL;
+
+ /* Get the IORegistry entry for the given path */
+ entry = IORegistryEntryFromPath(kIOMasterPortDefault, path);
+ if (entry == MACH_PORT_NULL) {
+ /* Path wasn't valid (maybe device was removed?) */
+ goto return_error;
+ }
+
+ /* Create an IOHIDDevice for the entry */
+ dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry);
+ if (dev->device_handle == NULL) {
+ /* Error creating the HID device */
+ goto return_error;
+ }
+
+ /* Open the IOHIDDevice */
+ IOReturn ret = IOHIDDeviceOpen(dev->device_handle, kIOHIDOptionsTypeSeizeDevice);
+ if (ret == kIOReturnSuccess) {
+ char str[32];
+
+ /* Create the buffers for receiving data */
+ dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle);
+ dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t));
+
+ /* Create the Run Loop Mode for this device.
+ printing the reference seems to work. */
+ sprintf(str, "HIDAPI_%p", dev->device_handle);
+ dev->run_loop_mode =
+ CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
+
+ /* Attach the device to a Run Loop */
+ IOHIDDeviceRegisterInputReportCallback(
+ dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
+ &hid_report_callback, dev);
+ IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev);
+
+ /* Start the read thread */
+ pthread_create(&dev->thread, NULL, read_thread, dev);
+
+ /* Wait here for the read thread to be initialized. */
+ pthread_barrier_wait(&dev->barrier);
+
+ IOObjectRelease(entry);
+ return dev;
+ }
+ else {
+ goto return_error;
+ }
+
+return_error:
+ if (dev->device_handle != NULL)
+ CFRelease(dev->device_handle);
+
+ if (entry != MACH_PORT_NULL)
+ IOObjectRelease(entry);
+
+ free_hid_device(dev);
+ return NULL;
+}
+
+static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length)
+{
+ const unsigned char *data_to_send;
+ size_t length_to_send;
+ IOReturn res;
+
+ /* Return if the device has been disconnected. */
+ if (dev->disconnected)
+ return -1;
+
+ if (data[0] == 0x0) {
+ /* Not using numbered Reports.
+ Don't send the report number. */
+ data_to_send = data+1;
+ length_to_send = length-1;
+ }
+ else {
+ /* Using numbered Reports.
+ Send the Report Number */
+ data_to_send = data;
+ length_to_send = length;
+ }
+
+ if (!dev->disconnected) {
+ res = IOHIDDeviceSetReport(dev->device_handle,
+ type,
+ data[0], /* Report ID*/
+ data_to_send, length_to_send);
+
+ if (res == kIOReturnSuccess) {
+ return length;
+ }
+ else
+ return -1;
+ }
+
+ return -1;
+}
+
+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
+{
+ return set_report(dev, kIOHIDReportTypeOutput, data, length);
+}
+
+/* Helper function, so that this isn't duplicated in hid_read(). */
+static int return_data(hid_device *dev, unsigned char *data, size_t length)
+{
+ /* Copy the data out of the linked list item (rpt) into the
+ return buffer (data), and delete the liked list item. */
+ struct input_report *rpt = dev->input_reports;
+ size_t len = (length < rpt->len)? length: rpt->len;
+ memcpy(data, rpt->data, len);
+ dev->input_reports = rpt->next;
+ free(rpt->data);
+ free(rpt);
+ return len;
+}
+
+static int cond_wait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex)
+{
+ while (!dev->input_reports) {
+ int res = pthread_cond_wait(cond, mutex);
+ if (res != 0)
+ return res;
+
+ /* A res of 0 means we may have been signaled or it may
+ be a spurious wakeup. Check to see that there's acutally
+ data in the queue before returning, and if not, go back
+ to sleep. See the pthread_cond_timedwait() man page for
+ details. */
+
+ if (dev->shutdown_thread || dev->disconnected)
+ return -1;
+ }
+
+ return 0;
+}
+
+static int cond_timedwait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
+{
+ while (!dev->input_reports) {
+ int res = pthread_cond_timedwait(cond, mutex, abstime);
+ if (res != 0)
+ return res;
+
+ /* A res of 0 means we may have been signaled or it may
+ be a spurious wakeup. Check to see that there's acutally
+ data in the queue before returning, and if not, go back
+ to sleep. See the pthread_cond_timedwait() man page for
+ details. */
+
+ if (dev->shutdown_thread || dev->disconnected)
+ return -1;
+ }
+
+ return 0;
+
+}
+
+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
+{
+ int bytes_read = -1;
+
+ /* Lock the access to the report list. */
+ pthread_mutex_lock(&dev->mutex);
+
+ /* There's an input report queued up. Return it. */
+ if (dev->input_reports) {
+ /* Return the first one */
+ bytes_read = return_data(dev, data, length);
+ goto ret;
+ }
+
+ /* Return if the device has been disconnected. */
+ if (dev->disconnected) {
+ bytes_read = -1;
+ goto ret;
+ }
+
+ if (dev->shutdown_thread) {
+ /* This means the device has been closed (or there
+ has been an error. An error code of -1 should
+ be returned. */
+ bytes_read = -1;
+ goto ret;
+ }
+
+ /* There is no data. Go to sleep and wait for data. */
+
+ if (milliseconds == -1) {
+ /* Blocking */
+ int res;
+ res = cond_wait(dev, &dev->condition, &dev->mutex);
+ if (res == 0)
+ bytes_read = return_data(dev, data, length);
+ else {
+ /* There was an error, or a device disconnection. */
+ bytes_read = -1;
+ }
+ }
+ else if (milliseconds > 0) {
+ /* Non-blocking, but called with timeout. */
+ int res;
+ struct timespec ts;
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+ TIMEVAL_TO_TIMESPEC(&tv, &ts);
+ ts.tv_sec += milliseconds / 1000;
+ ts.tv_nsec += (milliseconds % 1000) * 1000000;
+ if (ts.tv_nsec >= 1000000000L) {
+ ts.tv_sec++;
+ ts.tv_nsec -= 1000000000L;
+ }
+
+ res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts);
+ if (res == 0)
+ bytes_read = return_data(dev, data, length);
+ else if (res == ETIMEDOUT)
+ bytes_read = 0;
+ else
+ bytes_read = -1;
+ }
+ else {
+ /* Purely non-blocking */
+ bytes_read = 0;
+ }
+
+ret:
+ /* Unlock */
+ pthread_mutex_unlock(&dev->mutex);
+ return bytes_read;
+}
+
+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
+{
+ return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
+}
+
+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
+{
+ /* All Nonblocking operation is handled by the library. */
+ dev->blocking = !nonblock;
+
+ return 0;
+}
+
+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
+{
+ return set_report(dev, kIOHIDReportTypeFeature, data, length);
+}
+
+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
+{
+ CFIndex len = length;
+ IOReturn res;
+
+ /* Return if the device has been unplugged. */
+ if (dev->disconnected)
+ return -1;
+
+ res = IOHIDDeviceGetReport(dev->device_handle,
+ kIOHIDReportTypeFeature,
+ data[0], /* Report ID */
+ data, &len);
+ if (res == kIOReturnSuccess)
+ return len;
+ else
+ return -1;
+}
+
+
+void HID_API_EXPORT hid_close(hid_device *dev)
+{
+ if (!dev)
+ return;
+
+ /* Disconnect the report callback before close. */
+ if (!dev->disconnected) {
+ IOHIDDeviceRegisterInputReportCallback(
+ dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
+ NULL, dev);
+ IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev);
+ IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode);
+ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
+ }
+
+ /* Cause read_thread() to stop. */
+ dev->shutdown_thread = 1;
+
+ /* Wake up the run thread's event loop so that the thread can exit. */
+ CFRunLoopSourceSignal(dev->source);
+ CFRunLoopWakeUp(dev->run_loop);
+
+ /* Notify the read thread that it can shut down now. */
+ pthread_barrier_wait(&dev->shutdown_barrier);
+
+ /* Wait for read_thread() to end. */
+ pthread_join(dev->thread, NULL);
+
+ /* Close the OS handle to the device, but only if it's not
+ been unplugged. If it's been unplugged, then calling
+ IOHIDDeviceClose() will crash. */
+ if (!dev->disconnected) {
+ IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeSeizeDevice);
+ }
+
+ /* Clear out the queue of received reports. */
+ pthread_mutex_lock(&dev->mutex);
+ while (dev->input_reports) {
+ return_data(dev, NULL, 0);
+ }
+ pthread_mutex_unlock(&dev->mutex);
+ CFRelease(dev->device_handle);
+
+ free_hid_device(dev);
+}
+
+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return get_manufacturer_string(dev->device_handle, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return get_product_string(dev->device_handle, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ return get_serial_number(dev->device_handle, string, maxlen);
+}
+
+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
+{
+ /* TODO: */
+
+ return 0;
+}
+
+
+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
+{
+ /* TODO: */
+
+ return NULL;
+}
+
+
+
+
+
+
+
+#if 0
+static int32_t get_location_id(IOHIDDeviceRef device)
+{
+ return get_int_property(device, CFSTR(kIOHIDLocationIDKey));
+}
+
+static int32_t get_usage(IOHIDDeviceRef device)
+{
+ int32_t res;
+ res = get_int_property(device, CFSTR(kIOHIDDeviceUsageKey));
+ if (!res)
+ res = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey));
+ return res;
+}
+
+static int32_t get_usage_page(IOHIDDeviceRef device)
+{
+ int32_t res;
+ res = get_int_property(device, CFSTR(kIOHIDDeviceUsagePageKey));
+ if (!res)
+ res = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey));
+ return res;
+}
+
+static int get_transport(IOHIDDeviceRef device, wchar_t *buf, size_t len)
+{
+ return get_string_property(device, CFSTR(kIOHIDTransportKey), buf, len);
+}
+
+
+int main(void)
+{
+ IOHIDManagerRef mgr;
+ int i;
+
+ mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
+ IOHIDManagerSetDeviceMatching(mgr, NULL);
+ IOHIDManagerOpen(mgr, kIOHIDOptionsTypeNone);
+
+ CFSetRef device_set = IOHIDManagerCopyDevices(mgr);
+
+ CFIndex num_devices = CFSetGetCount(device_set);
+ IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
+ CFSetGetValues(device_set, (const void **) device_array);
+
+ for (i = 0; i < num_devices; i++) {
+ IOHIDDeviceRef dev = device_array[i];
+ printf("Device: %p\n", dev);
+ printf(" %04hx %04hx\n", get_vendor_id(dev), get_product_id(dev));
+
+ wchar_t serial[256], buf[256];
+ char cbuf[256];
+ get_serial_number(dev, serial, 256);
+
+
+ printf(" Serial: %ls\n", serial);
+ printf(" Loc: %ld\n", get_location_id(dev));
+ get_transport(dev, buf, 256);
+ printf(" Trans: %ls\n", buf);
+ make_path(dev, cbuf, 256);
+ printf(" Path: %s\n", cbuf);
+
+ }
+
+ return 0;
+}
+#endif
diff --git a/vendor/github.com/karalabe/usb/hidapi/windows/hid.c b/vendor/github.com/karalabe/usb/hidapi/windows/hid.c
new file mode 100644
index 000000000..60da64608
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/hidapi/windows/hid.c
@@ -0,0 +1,946 @@
+/*******************************************************
+ HIDAPI - Multi-Platform library for
+ communication with HID devices.
+
+ Alan Ott
+ Signal 11 Software
+
+ 8/22/2009
+
+ Copyright 2009, All Rights Reserved.
+
+ At the discretion of the user of this library,
+ this software may be licensed under the terms of the
+ GNU General Public License v3, a BSD-Style license, or the
+ original HIDAPI license as outlined in the LICENSE.txt,
+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
+ files located at the root of the source distribution.
+ These files may also be found in the public source
+ code repository located at:
+ http://github.com/signal11/hidapi .
+********************************************************/
+
+#include
+
+#ifndef _NTDEF_
+typedef LONG NTSTATUS;
+#endif
+
+#ifdef __MINGW32__
+#include
+#include
+#endif
+
+#ifdef __CYGWIN__
+#include
+#define _wcsdup wcsdup
+#endif
+
+/* The maximum number of characters that can be passed into the
+ HidD_Get*String() functions without it failing.*/
+#define MAX_STRING_WCHARS 0xFFF
+
+/*#define HIDAPI_USE_DDK*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ #include
+ #include
+ #ifdef HIDAPI_USE_DDK
+ #include
+ #endif
+
+ /* Copied from inc/ddk/hidclass.h, part of the Windows DDK. */
+ #define HID_OUT_CTL_CODE(id) \
+ CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
+ #define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#include
+#include
+
+
+#include "hidapi.h"
+
+#undef MIN
+#define MIN(x,y) ((x) < (y)? (x): (y))
+
+#ifdef _MSC_VER
+ /* Thanks Microsoft, but I know how to use strncpy(). */
+ #pragma warning(disable:4996)
+#endif
+
+#pragma GCC diagnostic ignored "-Wstringop-overflow"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef HIDAPI_USE_DDK
+ /* Since we're not building with the DDK, and the HID header
+ files aren't part of the SDK, we have to define all this
+ stuff here. In lookup_functions(), the function pointers
+ defined below are set. */
+ typedef struct _HIDD_ATTRIBUTES{
+ ULONG Size;
+ USHORT VendorID;
+ USHORT ProductID;
+ USHORT VersionNumber;
+ } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
+
+ typedef USHORT USAGE;
+ typedef struct _HIDP_CAPS {
+ USAGE Usage;
+ USAGE UsagePage;
+ USHORT InputReportByteLength;
+ USHORT OutputReportByteLength;
+ USHORT FeatureReportByteLength;
+ USHORT Reserved[17];
+ USHORT fields_not_used_by_hidapi[10];
+ } HIDP_CAPS, *PHIDP_CAPS;
+ typedef void* PHIDP_PREPARSED_DATA;
+ #define HIDP_STATUS_SUCCESS 0x110000
+
+ typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib);
+ typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len);
+ typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
+ typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
+ typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length);
+ typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length);
+ typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len);
+ typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data);
+ typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data);
+ typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS *caps);
+ typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers);
+
+ static HidD_GetAttributes_ HidD_GetAttributes;
+ static HidD_GetSerialNumberString_ HidD_GetSerialNumberString;
+ static HidD_GetManufacturerString_ HidD_GetManufacturerString;
+ static HidD_GetProductString_ HidD_GetProductString;
+ static HidD_SetFeature_ HidD_SetFeature;
+ static HidD_GetFeature_ HidD_GetFeature;
+ static HidD_GetIndexedString_ HidD_GetIndexedString;
+ static HidD_GetPreparsedData_ HidD_GetPreparsedData;
+ static HidD_FreePreparsedData_ HidD_FreePreparsedData;
+ static HidP_GetCaps_ HidP_GetCaps;
+ static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers;
+
+ static HMODULE lib_handle = NULL;
+ static BOOLEAN initialized = FALSE;
+#endif /* HIDAPI_USE_DDK */
+
+struct hid_device_ {
+ HANDLE device_handle;
+ BOOL blocking;
+ USHORT output_report_length;
+ size_t input_report_length;
+ void *last_error_str;
+ DWORD last_error_num;
+ BOOL read_pending;
+ char *read_buf;
+ OVERLAPPED ol;
+};
+
+static hid_device *new_hid_device()
+{
+ hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
+ dev->device_handle = INVALID_HANDLE_VALUE;
+ dev->blocking = TRUE;
+ dev->output_report_length = 0;
+ dev->input_report_length = 0;
+ dev->last_error_str = NULL;
+ dev->last_error_num = 0;
+ dev->read_pending = FALSE;
+ dev->read_buf = NULL;
+ memset(&dev->ol, 0, sizeof(dev->ol));
+ dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
+
+ return dev;
+}
+
+static void free_hid_device(hid_device *dev)
+{
+ CloseHandle(dev->ol.hEvent);
+ CloseHandle(dev->device_handle);
+ LocalFree(dev->last_error_str);
+ free(dev->read_buf);
+ free(dev);
+}
+
+static void register_error(hid_device *device, const char *op)
+{
+ WCHAR *ptr, *msg;
+
+ FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ GetLastError(),
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPVOID)&msg, 0/*sz*/,
+ NULL);
+
+ /* Get rid of the CR and LF that FormatMessage() sticks at the
+ end of the message. Thanks Microsoft! */
+ ptr = msg;
+ while (*ptr) {
+ if (*ptr == '\r') {
+ *ptr = 0x0000;
+ break;
+ }
+ ptr++;
+ }
+
+ /* Store the message off in the Device entry so that
+ the hid_error() function can pick it up. */
+ LocalFree(device->last_error_str);
+ device->last_error_str = msg;
+}
+
+#ifndef HIDAPI_USE_DDK
+static int lookup_functions()
+{
+ lib_handle = LoadLibraryA("hid.dll");
+ if (lib_handle) {
+#define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1;
+ RESOLVE(HidD_GetAttributes);
+ RESOLVE(HidD_GetSerialNumberString);
+ RESOLVE(HidD_GetManufacturerString);
+ RESOLVE(HidD_GetProductString);
+ RESOLVE(HidD_SetFeature);
+ RESOLVE(HidD_GetFeature);
+ RESOLVE(HidD_GetIndexedString);
+ RESOLVE(HidD_GetPreparsedData);
+ RESOLVE(HidD_FreePreparsedData);
+ RESOLVE(HidP_GetCaps);
+ RESOLVE(HidD_SetNumInputBuffers);
+#undef RESOLVE
+ }
+ else
+ return -1;
+
+ return 0;
+}
+#endif
+
+static HANDLE open_device(const char *path, BOOL enumerate)
+{
+ HANDLE handle;
+ DWORD desired_access = (enumerate)? 0: (GENERIC_WRITE | GENERIC_READ);
+ DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
+
+ handle = CreateFileA(path,
+ desired_access,
+ share_mode,
+ NULL,
+ OPEN_EXISTING,
+ FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/
+ 0);
+
+ return handle;
+}
+
+int HID_API_EXPORT hid_init(void)
+{
+#ifndef HIDAPI_USE_DDK
+ if (!initialized) {
+ if (lookup_functions() < 0) {
+ hid_exit();
+ return -1;
+ }
+ initialized = TRUE;
+ }
+#endif
+ return 0;
+}
+
+int HID_API_EXPORT hid_exit(void)
+{
+#ifndef HIDAPI_USE_DDK
+ if (lib_handle)
+ FreeLibrary(lib_handle);
+ lib_handle = NULL;
+ initialized = FALSE;
+#endif
+ return 0;
+}
+
+struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
+{
+ BOOL res;
+ struct hid_device_info *root = NULL; /* return object */
+ struct hid_device_info *cur_dev = NULL;
+
+ /* Windows objects for interacting with the driver. */
+ GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} };
+ SP_DEVINFO_DATA devinfo_data;
+ SP_DEVICE_INTERFACE_DATA device_interface_data;
+ SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL;
+ HDEVINFO device_info_set = INVALID_HANDLE_VALUE;
+ int device_index = 0;
+ int i;
+
+ if (hid_init() < 0)
+ return NULL;
+
+ /* Initialize the Windows objects. */
+ memset(&devinfo_data, 0x0, sizeof(devinfo_data));
+ devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA);
+ device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+
+ /* Get information for all the devices belonging to the HID class. */
+ device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
+
+ /* Iterate over each device in the HID class, looking for the right one. */
+
+ for (;;) {
+ HANDLE write_handle = INVALID_HANDLE_VALUE;
+ DWORD required_size = 0;
+ HIDD_ATTRIBUTES attrib;
+
+ res = SetupDiEnumDeviceInterfaces(device_info_set,
+ NULL,
+ &InterfaceClassGuid,
+ device_index,
+ &device_interface_data);
+
+ if (!res) {
+ /* A return of FALSE from this function means that
+ there are no more devices. */
+ break;
+ }
+
+ /* Call with 0-sized detail size, and let the function
+ tell us how long the detail struct needs to be. The
+ size is put in &required_size. */
+ res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
+ &device_interface_data,
+ NULL,
+ 0,
+ &required_size,
+ NULL);
+
+ /* Allocate a long enough structure for device_interface_detail_data. */
+ device_interface_detail_data = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) malloc(required_size);
+ device_interface_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
+
+ /* Get the detailed data for this device. The detail data gives us
+ the device path for this device, which is then passed into
+ CreateFile() to get a handle to the device. */
+ res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
+ &device_interface_data,
+ device_interface_detail_data,
+ required_size,
+ NULL,
+ NULL);
+
+ if (!res) {
+ /* register_error(dev, "Unable to call SetupDiGetDeviceInterfaceDetail");
+ Continue to the next device. */
+ goto cont;
+ }
+
+ /* Make sure this device is of Setup Class "HIDClass" and has a
+ driver bound to it. */
+ for (i = 0; ; i++) {
+ char driver_name[256];
+
+ /* Populate devinfo_data. This function will return failure
+ when there are no more interfaces left. */
+ res = SetupDiEnumDeviceInfo(device_info_set, i, &devinfo_data);
+ if (!res)
+ goto cont;
+
+ res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
+ SPDRP_CLASS, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
+ if (!res)
+ goto cont;
+
+ if (strcmp(driver_name, "HIDClass") == 0) {
+ /* See if there's a driver bound. */
+ res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
+ SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
+ if (res)
+ break;
+ }
+ }
+
+ //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath);
+
+ /* Open a handle to the device */
+ write_handle = open_device(device_interface_detail_data->DevicePath, TRUE);
+
+ /* Check validity of write_handle. */
+ if (write_handle == INVALID_HANDLE_VALUE) {
+ /* Unable to open the device. */
+ //register_error(dev, "CreateFile");
+ goto cont_close;
+ }
+
+
+ /* Get the Vendor ID and Product ID for this device. */
+ attrib.Size = sizeof(HIDD_ATTRIBUTES);
+ HidD_GetAttributes(write_handle, &attrib);
+ //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID);
+
+ /* Check the VID/PID to see if we should add this
+ device to the enumeration list. */
+ if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) &&
+ (product_id == 0x0 || attrib.ProductID == product_id)) {
+
+ #define WSTR_LEN 512
+ const char *str;
+ struct hid_device_info *tmp;
+ PHIDP_PREPARSED_DATA pp_data = NULL;
+ HIDP_CAPS caps;
+ BOOLEAN res;
+ NTSTATUS nt_res;
+ wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */
+ size_t len;
+
+ /* VID/PID match. Create the record. */
+ tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
+ if (cur_dev) {
+ cur_dev->next = tmp;
+ }
+ else {
+ root = tmp;
+ }
+ cur_dev = tmp;
+
+ /* Get the Usage Page and Usage for this device. */
+ res = HidD_GetPreparsedData(write_handle, &pp_data);
+ if (res) {
+ nt_res = HidP_GetCaps(pp_data, &caps);
+ if (nt_res == HIDP_STATUS_SUCCESS) {
+ cur_dev->usage_page = caps.UsagePage;
+ cur_dev->usage = caps.Usage;
+ }
+
+ HidD_FreePreparsedData(pp_data);
+ }
+
+ /* Fill out the record */
+ cur_dev->next = NULL;
+ str = device_interface_detail_data->DevicePath;
+ if (str) {
+ len = strlen(str);
+ cur_dev->path = (char*) calloc(len+1, sizeof(char));
+ strncpy(cur_dev->path, str, len+1);
+ cur_dev->path[len] = '\0';
+ }
+ else
+ cur_dev->path = NULL;
+
+ /* Serial Number */
+ res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr));
+ wstr[WSTR_LEN-1] = 0x0000;
+ if (res) {
+ cur_dev->serial_number = _wcsdup(wstr);
+ }
+
+ /* Manufacturer String */
+ res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr));
+ wstr[WSTR_LEN-1] = 0x0000;
+ if (res) {
+ cur_dev->manufacturer_string = _wcsdup(wstr);
+ }
+
+ /* Product String */
+ res = HidD_GetProductString(write_handle, wstr, sizeof(wstr));
+ wstr[WSTR_LEN-1] = 0x0000;
+ if (res) {
+ cur_dev->product_string = _wcsdup(wstr);
+ }
+
+ /* VID/PID */
+ cur_dev->vendor_id = attrib.VendorID;
+ cur_dev->product_id = attrib.ProductID;
+
+ /* Release Number */
+ cur_dev->release_number = attrib.VersionNumber;
+
+ /* Interface Number. It can sometimes be parsed out of the path
+ on Windows if a device has multiple interfaces. See
+ http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or
+ search for "Hardware IDs for HID Devices" at MSDN. If it's not
+ in the path, it's set to -1. */
+ cur_dev->interface_number = -1;
+ if (cur_dev->path) {
+ char *interface_component = strstr(cur_dev->path, "&mi_");
+ if (interface_component) {
+ char *hex_str = interface_component + 4;
+ char *endptr = NULL;
+ cur_dev->interface_number = strtol(hex_str, &endptr, 16);
+ if (endptr == hex_str) {
+ /* The parsing failed. Set interface_number to -1. */
+ cur_dev->interface_number = -1;
+ }
+ }
+ }
+ }
+
+cont_close:
+ CloseHandle(write_handle);
+cont:
+ /* We no longer need the detail data. It can be freed */
+ free(device_interface_detail_data);
+
+ device_index++;
+
+ }
+
+ /* Close the device information handle. */
+ SetupDiDestroyDeviceInfoList(device_info_set);
+
+ return root;
+
+}
+
+void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
+{
+ /* TODO: Merge this with the Linux version. This function is platform-independent. */
+ struct hid_device_info *d = devs;
+ while (d) {
+ struct hid_device_info *next = d->next;
+ free(d->path);
+ free(d->serial_number);
+ free(d->manufacturer_string);
+ free(d->product_string);
+ free(d);
+ d = next;
+ }
+}
+
+
+HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
+{
+ /* TODO: Merge this functions with the Linux version. This function should be platform independent. */
+ struct hid_device_info *devs, *cur_dev;
+ const char *path_to_open = NULL;
+ hid_device *handle = NULL;
+
+ devs = hid_enumerate(vendor_id, product_id);
+ cur_dev = devs;
+ while (cur_dev) {
+ if (cur_dev->vendor_id == vendor_id &&
+ cur_dev->product_id == product_id) {
+ if (serial_number) {
+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ else {
+ path_to_open = cur_dev->path;
+ break;
+ }
+ }
+ cur_dev = cur_dev->next;
+ }
+
+ if (path_to_open) {
+ /* Open the device */
+ handle = hid_open_path(path_to_open);
+ }
+
+ hid_free_enumeration(devs);
+
+ return handle;
+}
+
+HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
+{
+ hid_device *dev;
+ HIDP_CAPS caps;
+ PHIDP_PREPARSED_DATA pp_data = NULL;
+ BOOLEAN res;
+ NTSTATUS nt_res;
+
+ if (hid_init() < 0) {
+ return NULL;
+ }
+
+ dev = new_hid_device();
+
+ /* Open a handle to the device */
+ dev->device_handle = open_device(path, FALSE);
+
+ /* Check validity of write_handle. */
+ if (dev->device_handle == INVALID_HANDLE_VALUE) {
+ /* Unable to open the device. */
+ register_error(dev, "CreateFile");
+ goto err;
+ }
+
+ /* Set the Input Report buffer size to 64 reports. */
+ res = HidD_SetNumInputBuffers(dev->device_handle, 64);
+ if (!res) {
+ register_error(dev, "HidD_SetNumInputBuffers");
+ goto err;
+ }
+
+ /* Get the Input Report length for the device. */
+ res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
+ if (!res) {
+ register_error(dev, "HidD_GetPreparsedData");
+ goto err;
+ }
+ nt_res = HidP_GetCaps(pp_data, &caps);
+ if (nt_res != HIDP_STATUS_SUCCESS) {
+ register_error(dev, "HidP_GetCaps");
+ goto err_pp_data;
+ }
+ dev->output_report_length = caps.OutputReportByteLength;
+ dev->input_report_length = caps.InputReportByteLength;
+ HidD_FreePreparsedData(pp_data);
+
+ dev->read_buf = (char*) malloc(dev->input_report_length);
+
+ return dev;
+
+err_pp_data:
+ HidD_FreePreparsedData(pp_data);
+err:
+ free_hid_device(dev);
+ return NULL;
+}
+
+int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
+{
+ DWORD bytes_written;
+ BOOL res;
+
+ OVERLAPPED ol;
+ unsigned char *buf;
+ memset(&ol, 0, sizeof(ol));
+
+ /* Make sure the right number of bytes are passed to WriteFile. Windows
+ expects the number of bytes which are in the _longest_ report (plus
+ one for the report number) bytes even if the data is a report
+ which is shorter than that. Windows gives us this value in
+ caps.OutputReportByteLength. If a user passes in fewer bytes than this,
+ create a temporary buffer which is the proper size. */
+ if (length >= dev->output_report_length) {
+ /* The user passed the right number of bytes. Use the buffer as-is. */
+ buf = (unsigned char *) data;
+ } else {
+ /* Create a temporary buffer and copy the user's data
+ into it, padding the rest with zeros. */
+ buf = (unsigned char *) malloc(dev->output_report_length);
+ memcpy(buf, data, length);
+ memset(buf + length, 0, dev->output_report_length - length);
+ length = dev->output_report_length;
+ }
+
+ res = WriteFile(dev->device_handle, buf, length, NULL, &ol);
+
+ if (!res) {
+ if (GetLastError() != ERROR_IO_PENDING) {
+ /* WriteFile() failed. Return error. */
+ register_error(dev, "WriteFile");
+ bytes_written = -1;
+ goto end_of_function;
+ }
+ }
+
+ /* Wait here until the write is done. This makes
+ hid_write() synchronous. */
+ res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, TRUE/*wait*/);
+ if (!res) {
+ /* The Write operation failed. */
+ register_error(dev, "WriteFile");
+ bytes_written = -1;
+ goto end_of_function;
+ }
+
+end_of_function:
+ if (buf != data)
+ free(buf);
+
+ return bytes_written;
+}
+
+
+int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
+{
+ DWORD bytes_read = 0;
+ size_t copy_len = 0;
+ BOOL res;
+
+ /* Copy the handle for convenience. */
+ HANDLE ev = dev->ol.hEvent;
+
+ if (!dev->read_pending) {
+ /* Start an Overlapped I/O read. */
+ dev->read_pending = TRUE;
+ memset(dev->read_buf, 0, dev->input_report_length);
+ ResetEvent(ev);
+ res = ReadFile(dev->device_handle, dev->read_buf, dev->input_report_length, &bytes_read, &dev->ol);
+
+ if (!res) {
+ if (GetLastError() != ERROR_IO_PENDING) {
+ /* ReadFile() has failed.
+ Clean up and return error. */
+ CancelIo(dev->device_handle);
+ dev->read_pending = FALSE;
+ goto end_of_function;
+ }
+ }
+ }
+
+ if (milliseconds >= 0) {
+ /* See if there is any data yet. */
+ res = WaitForSingleObject(ev, milliseconds);
+ if (res != WAIT_OBJECT_0) {
+ /* There was no data this time. Return zero bytes available,
+ but leave the Overlapped I/O running. */
+ return 0;
+ }
+ }
+
+ /* Either WaitForSingleObject() told us that ReadFile has completed, or
+ we are in non-blocking mode. Get the number of bytes read. The actual
+ data has been copied to the data[] array which was passed to ReadFile(). */
+ res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
+
+ /* Set pending back to false, even if GetOverlappedResult() returned error. */
+ dev->read_pending = FALSE;
+
+ if (res && bytes_read > 0) {
+ if (dev->read_buf[0] == 0x0) {
+ /* If report numbers aren't being used, but Windows sticks a report
+ number (0x0) on the beginning of the report anyway. To make this
+ work like the other platforms, and to make it work more like the
+ HID spec, we'll skip over this byte. */
+ bytes_read--;
+ copy_len = length > bytes_read ? bytes_read : length;
+ memcpy(data, dev->read_buf+1, copy_len);
+ }
+ else {
+ /* Copy the whole buffer, report number and all. */
+ copy_len = length > bytes_read ? bytes_read : length;
+ memcpy(data, dev->read_buf, copy_len);
+ }
+ }
+
+end_of_function:
+ if (!res) {
+ register_error(dev, "GetOverlappedResult");
+ return -1;
+ }
+
+ return copy_len;
+}
+
+int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
+{
+ return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
+}
+
+int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock)
+{
+ dev->blocking = !nonblock;
+ return 0; /* Success */
+}
+
+int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
+{
+ BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, length);
+ if (!res) {
+ register_error(dev, "HidD_SetFeature");
+ return -1;
+ }
+
+ return length;
+}
+
+
+int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
+{
+ BOOL res;
+#if 0
+ res = HidD_GetFeature(dev->device_handle, data, length);
+ if (!res) {
+ register_error(dev, "HidD_GetFeature");
+ return -1;
+ }
+ return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
+#else
+ DWORD bytes_returned;
+
+ OVERLAPPED ol;
+ memset(&ol, 0, sizeof(ol));
+
+ res = DeviceIoControl(dev->device_handle,
+ IOCTL_HID_GET_FEATURE,
+ data, length,
+ data, length,
+ &bytes_returned, &ol);
+
+ if (!res) {
+ if (GetLastError() != ERROR_IO_PENDING) {
+ /* DeviceIoControl() failed. Return error. */
+ register_error(dev, "Send Feature Report DeviceIoControl");
+ return -1;
+ }
+ }
+
+ /* Wait here until the write is done. This makes
+ hid_get_feature_report() synchronous. */
+ res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
+ if (!res) {
+ /* The operation failed. */
+ register_error(dev, "Send Feature Report GetOverLappedResult");
+ return -1;
+ }
+
+ /* bytes_returned does not include the first byte which contains the
+ report ID. The data buffer actually contains one more byte than
+ bytes_returned. */
+ bytes_returned++;
+
+ return bytes_returned;
+#endif
+}
+
+void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev)
+{
+ if (!dev)
+ return;
+ CancelIo(dev->device_handle);
+ free_hid_device(dev);
+}
+
+int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ BOOL res;
+
+ res = HidD_GetManufacturerString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
+ if (!res) {
+ register_error(dev, "HidD_GetManufacturerString");
+ return -1;
+ }
+
+ return 0;
+}
+
+int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ BOOL res;
+
+ res = HidD_GetProductString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
+ if (!res) {
+ register_error(dev, "HidD_GetProductString");
+ return -1;
+ }
+
+ return 0;
+}
+
+int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
+{
+ BOOL res;
+
+ res = HidD_GetSerialNumberString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
+ if (!res) {
+ register_error(dev, "HidD_GetSerialNumberString");
+ return -1;
+ }
+
+ return 0;
+}
+
+int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
+{
+ BOOL res;
+
+ res = HidD_GetIndexedString(dev->device_handle, string_index, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
+ if (!res) {
+ register_error(dev, "HidD_GetIndexedString");
+ return -1;
+ }
+
+ return 0;
+}
+
+
+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
+{
+ return (wchar_t*)dev->last_error_str;
+}
+
+
+/*#define PICPGM*/
+/*#define S11*/
+#define P32
+#ifdef S11
+ unsigned short VendorID = 0xa0a0;
+ unsigned short ProductID = 0x0001;
+#endif
+
+#ifdef P32
+ unsigned short VendorID = 0x04d8;
+ unsigned short ProductID = 0x3f;
+#endif
+
+
+#ifdef PICPGM
+ unsigned short VendorID = 0x04d8;
+ unsigned short ProductID = 0x0033;
+#endif
+
+
+#if 0
+int __cdecl main(int argc, char* argv[])
+{
+ int res;
+ unsigned char buf[65];
+
+ UNREFERENCED_PARAMETER(argc);
+ UNREFERENCED_PARAMETER(argv);
+
+ /* Set up the command buffer. */
+ memset(buf,0x00,sizeof(buf));
+ buf[0] = 0;
+ buf[1] = 0x81;
+
+
+ /* Open the device. */
+ int handle = open(VendorID, ProductID, L"12345");
+ if (handle < 0)
+ printf("unable to open device\n");
+
+
+ /* Toggle LED (cmd 0x80) */
+ buf[1] = 0x80;
+ res = write(handle, buf, 65);
+ if (res < 0)
+ printf("Unable to write()\n");
+
+ /* Request state (cmd 0x81) */
+ buf[1] = 0x81;
+ write(handle, buf, 65);
+ if (res < 0)
+ printf("Unable to write() (2)\n");
+
+ /* Read requested state */
+ read(handle, buf, 65);
+ if (res < 0)
+ printf("Unable to read()\n");
+
+ /* Print out the returned buffer. */
+ for (int i = 0; i < 4; i++)
+ printf("buf[%d]: %d\n", i, buf[i]);
+
+ return 0;
+}
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
diff --git a/vendor/github.com/karalabe/usb/libs.go b/vendor/github.com/karalabe/usb/libs.go
new file mode 100644
index 000000000..6446acee9
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libs.go
@@ -0,0 +1,74 @@
+// usb - Self contained USB and HID library for Go
+// Copyright 2019 The library Authors
+//
+// This library is free software: you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License as published by the Free
+// Software Foundation, either version 3 of the License, or (at your option) any
+// later version.
+//
+// The library is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License along
+// with the library. If not, see .
+
+// +build freebsd,cgo linux,cgo darwin,!ios,cgo windows,cgo
+
+package usb
+
+/*
+#cgo CFLAGS: -I./hidapi/hidapi
+#cgo CFLAGS: -I./libusb/libusb
+#cgo CFLAGS: -DDEFAULT_VISIBILITY=""
+#cgo CFLAGS: -DPOLL_NFDS_TYPE=int
+
+#cgo linux CFLAGS: -DOS_LINUX -D_GNU_SOURCE -DHAVE_SYS_TIME_H
+#cgo linux,!android LDFLAGS: -lrt
+#cgo darwin CFLAGS: -DOS_DARWIN -DHAVE_SYS_TIME_H
+#cgo darwin LDFLAGS: -framework CoreFoundation -framework IOKit -lobjc
+#cgo windows CFLAGS: -DOS_WINDOWS
+#cgo windows LDFLAGS: -lsetupapi
+#cgo freebsd CFLAGS: -DOS_FREEBSD
+#cgo freebsd LDFLAGS: -lusb
+#cgo openbsd CFLAGS: -DOS_OPENBSD
+
+#if defined(OS_LINUX) || defined(OS_DARWIN) || defined(DOS_FREEBSD) || defined(OS_OPENBSD)
+ #include
+ #include "os/threads_posix.c"
+ #include "os/poll_posix.c"
+#elif defined(OS_WINDOWS)
+ #include "os/poll_windows.c"
+ #include "os/threads_windows.c"
+#endif
+
+#ifdef OS_LINUX
+ #include "os/linux_usbfs.c"
+ #include "os/linux_netlink.c"
+ #include "hidapi/libusb/hid.c"
+#elif OS_DARWIN
+ #include "os/darwin_usb.c"
+ #include "hidapi/mac/hid.c"
+#elif OS_WINDOWS
+ #include "os/windows_nt_common.c"
+ #include "os/windows_usbdk.c"
+ #include "os/windows_winusb.c"
+ #include "hidapi/windows/hid.c"
+#elif OS_FREEBSD
+ #include
+ #include "hidapi/libusb/hid.c"
+#elif DOS_OPENBSD
+ #include "os/openbsd_usb.c"
+ #include "hidapi/libusb/hid.c"
+#endif
+
+#ifndef OS_FREEBSD
+ #include "core.c"
+ #include "descriptor.c"
+ #include "hotplug.c"
+ #include "io.c"
+ #include "strerror.c"
+ #include "sync.c"
+#endif
+*/
+import "C"
diff --git a/vendor/github.com/karalabe/usb/libusb/AUTHORS b/vendor/github.com/karalabe/usb/libusb/AUTHORS
new file mode 100644
index 000000000..e90ad9bb2
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/AUTHORS
@@ -0,0 +1,119 @@
+Copyright © 2001 Johannes Erdfelt
+Copyright © 2007-2009 Daniel Drake
+Copyright © 2010-2012 Peter Stuge
+Copyright © 2008-2016 Nathan Hjelm
+Copyright © 2009-2013 Pete Batard
+Copyright © 2009-2013 Ludovic Rousseau
+Copyright © 2010-2012 Michael Plante
+Copyright © 2011-2013 Hans de Goede
+Copyright © 2012-2013 Martin Pieuchot
+Copyright © 2012-2013 Toby Gray
+Copyright © 2013-2018 Chris Dickens
+
+Other contributors:
+Adrian Bunk
+Akshay Jaggi
+Alan Ott
+Alan Stern
+Alex Vatchenko
+Andrew Fernandes
+Andy Chunyu
+Andy McFadden
+Angus Gratton
+Anil Nair
+Anthony Clay
+Antonio Ospite
+Artem Egorkine
+Aurelien Jarno
+Bastien Nocera
+Bei Zhang
+Benjamin Dobell
+Brent Rector
+Carl Karsten
+Christophe Zeitouny
+Colin Walters
+Dave Camarillo
+David Engraf
+David Moore
+Davidlohr Bueso
+Dmitry Fleytman
+Doug Johnston
+Evan Hunter
+Federico Manzan
+Felipe Balbi
+Florian Albrechtskirchinger
+Francesco Montorsi
+Francisco Facioni
+Gaurav Gupta
+Graeme Gill
+Gustavo Zacarias
+Hans Ulrich Niedermann
+Hector Martin
+Hoi-Ho Chan
+Ilya Konstantinov
+Jakub Klama
+James Hanko
+Jeffrey Nichols
+Johann Richard
+John Sheu
+Jonathon Jongsma
+Joost Muller
+Josh Gao
+Joshua Blake
+Justin Bischoff
+KIMURA Masaru
+Karsten Koenig
+Konrad Rzepecki
+Kuangye Guo
+Lars Kanis
+Lars Wirzenius
+Lei Chen
+Luca Longinotti
+Marcus Meissner
+Markus Heidelberg
+Martin Ettl
+Martin Koegler
+Matthew Stapleton
+Matthias Bolte
+Michel Zou
+Mike Frysinger
+Mikhail Gusarov
+Morgan Leborgne
+Moritz Fischer
+Ларионов Даниил
+Nicholas Corgan
+Omri Iluz
+Orin Eman
+Paul Fertser
+Pekka Nikander
+Rob Walker
+Romain Vimont
+Roman Kalashnikov
+Sameeh Jubran
+Sean McBride
+Sebastian Pipping
+Sergey Serb
+Simon Haggett
+Simon Newton
+Stefan Agner
+Stefan Tauner
+Steinar H. Gunderson
+Thomas Röfer
+Tim Hutt
+Tim Roberts
+Tobias Klauser
+Toby Peterson
+Tormod Volden
+Trygve Laugstøl
+Uri Lublin
+Vasily Khoruzhick
+Vegard Storheil Eriksen
+Venkatesh Shukla
+Vianney le Clément de Saint-Marcq
+Victor Toso
+Vitali Lovich
+William Skellenger
+Xiaofan Chen
+Zoltán Kovács
+Роман Донченко
+parafin
diff --git a/vendor/github.com/karalabe/usb/libusb/COPYING b/vendor/github.com/karalabe/usb/libusb/COPYING
new file mode 100644
index 000000000..5ab7695ab
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/COPYING
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ , 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/config.h b/vendor/github.com/karalabe/usb/libusb/libusb/config.h
new file mode 100644
index 000000000..e004f03cd
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/config.h
@@ -0,0 +1,3 @@
+#ifndef CONFIG_H
+#define CONFIG_H
+#endif
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/core.c b/vendor/github.com/karalabe/usb/libusb/libusb/core.c
new file mode 100644
index 000000000..50f92f6b1
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/core.c
@@ -0,0 +1,2579 @@
+/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
+/*
+ * Core functions for libusb
+ * Copyright © 2012-2013 Nathan Hjelm
+ * Copyright © 2007-2008 Daniel Drake
+ * Copyright © 2001 Johannes Erdfelt
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+
+#include
+#include
+#include
+#include
+#include
+#ifdef HAVE_SYS_TYPES_H
+#include
+#endif
+#ifdef HAVE_SYS_TIME_H
+#include
+#endif
+#ifdef HAVE_SYSLOG_H
+#include
+#endif
+
+#ifdef __ANDROID__
+#include
+#endif
+
+#include "libusbi.h"
+#include "hotplug.h"
+
+struct libusb_context *usbi_default_context = NULL;
+static const struct libusb_version libusb_version_internal =
+ { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
+ LIBUSB_RC, "http://libusb.info" };
+static int default_context_refcnt = 0;
+static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
+static struct timespec timestamp_origin = { 0, 0 };
+
+usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
+struct list_head active_contexts_list;
+
+/**
+ * \mainpage libusb-1.0 API Reference
+ *
+ * \section intro Introduction
+ *
+ * libusb is an open source library that allows you to communicate with USB
+ * devices from userspace. For more info, see the
+ * libusb homepage.
+ *
+ * This documentation is aimed at application developers wishing to
+ * communicate with USB peripherals from their own software. After reviewing
+ * this documentation, feedback and questions can be sent to the
+ * libusb-devel mailing list.
+ *
+ * This documentation assumes knowledge of how to operate USB devices from
+ * a software standpoint (descriptors, configurations, interfaces, endpoints,
+ * control/bulk/interrupt/isochronous transfers, etc). Full information
+ * can be found in the USB 3.0
+ * Specification which is available for free download. You can probably
+ * find less verbose introductions by searching the web.
+ *
+ * \section API Application Programming Interface (API)
+ *
+ * See the \ref libusb_api page for a complete list of the libusb functions.
+ *
+ * \section features Library features
+ *
+ * - All transfer types supported (control/bulk/interrupt/isochronous)
+ * - 2 transfer interfaces:
+ * -# Synchronous (simple)
+ * -# Asynchronous (more complicated, but more powerful)
+ * - Thread safe (although the asynchronous interface means that you
+ * usually won't need to thread)
+ * - Lightweight with lean API
+ * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
+ * - Hotplug support (on some platforms). See \ref libusb_hotplug.
+ *
+ * \section gettingstarted Getting Started
+ *
+ * To begin reading the API documentation, start with the Modules page which
+ * links to the different categories of libusb's functionality.
+ *
+ * One decision you will have to make is whether to use the synchronous
+ * or the asynchronous data transfer interface. The \ref libusb_io documentation
+ * provides some insight into this topic.
+ *
+ * Some example programs can be found in the libusb source distribution under
+ * the "examples" subdirectory. The libusb homepage includes a list of
+ * real-life project examples which use libusb.
+ *
+ * \section errorhandling Error handling
+ *
+ * libusb functions typically return 0 on success or a negative error code
+ * on failure. These negative error codes relate to LIBUSB_ERROR constants
+ * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
+ *
+ * \section msglog Debug message logging
+ *
+ * libusb uses stderr for all logging. By default, logging is set to NONE,
+ * which means that no output will be produced. However, unless the library
+ * has been compiled with logging disabled, then any application calls to
+ * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level), or the setting of the
+ * environmental variable LIBUSB_DEBUG outside of the application, can result
+ * in logging being produced. Your application should therefore not close
+ * stderr, but instead direct it to the null device if its output is
+ * undesirable.
+ *
+ * The libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) function can be
+ * used to enable logging of certain messages. Under standard configuration,
+ * libusb doesn't really log much so you are advised to use this function
+ * to enable all error/warning/ informational messages. It will help debug
+ * problems with your software.
+ *
+ * The logged messages are unstructured. There is no one-to-one correspondence
+ * between messages being logged and success or failure return codes from
+ * libusb functions. There is no format to the messages, so you should not
+ * try to capture or parse them. They are not and will not be localized.
+ * These messages are not intended to being passed to your application user;
+ * instead, you should interpret the error codes returned from libusb functions
+ * and provide appropriate notification to the user. The messages are simply
+ * there to aid you as a programmer, and if you're confused because you're
+ * getting a strange error code from a libusb function, enabling message
+ * logging may give you a suitable explanation.
+ *
+ * The LIBUSB_DEBUG environment variable can be used to enable message logging
+ * at run-time. This environment variable should be set to a log level number,
+ * which is interpreted the same as the
+ * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) parameter. When this
+ * environment variable is set, the message logging verbosity level is fixed
+ * and libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) effectively does
+ * nothing.
+ *
+ * libusb can be compiled without any logging functions, useful for embedded
+ * systems. In this case, libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level)
+ * and the LIBUSB_DEBUG environment variable have no effects.
+ *
+ * libusb can also be compiled with verbose debugging messages always. When
+ * the library is compiled in this way, all messages of all verbosities are
+ * always logged. libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) and
+ * the LIBUSB_DEBUG environment variable have no effects.
+ *
+ * \section remarks Other remarks
+ *
+ * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
+ * to document these.
+ */
+
+/**
+ * \page libusb_caveats Caveats
+ *
+ * \section fork Fork considerations
+ *
+ * libusb is not designed to work across fork() calls. Depending on
+ * the platform, there may be resources in the parent process that are not
+ * available to the child (e.g. the hotplug monitor thread on Linux). In
+ * addition, since the parent and child will share libusb's internal file
+ * descriptors, using libusb in any way from the child could cause the parent
+ * process's \ref libusb_context to get into an inconsistent state.
+ *
+ * On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
+ * that it is safe to fork() and exec() without worrying about the child
+ * process needing to clean up state or having access to these file descriptors.
+ * Other platforms may not be so forgiving, so consider yourself warned!
+ *
+ * \section devresets Device resets
+ *
+ * The libusb_reset_device() function allows you to reset a device. If your
+ * program has to call such a function, it should obviously be aware that
+ * the reset will cause device state to change (e.g. register values may be
+ * reset).
+ *
+ * The problem is that any other program could reset the device your program
+ * is working with, at any time. libusb does not offer a mechanism to inform
+ * you when this has happened, so if someone else resets your device it will
+ * not be clear to your own program why the device state has changed.
+ *
+ * Ultimately, this is a limitation of writing drivers in userspace.
+ * Separation from the USB stack in the underlying kernel makes it difficult
+ * for the operating system to deliver such notifications to your program.
+ * The Linux kernel USB stack allows such reset notifications to be delivered
+ * to in-kernel USB drivers, but it is not clear how such notifications could
+ * be delivered to second-class drivers that live in userspace.
+ *
+ * \section blockonly Blocking-only functionality
+ *
+ * The functionality listed below is only available through synchronous,
+ * blocking functions. There are no asynchronous/non-blocking alternatives,
+ * and no clear ways of implementing these.
+ *
+ * - Configuration activation (libusb_set_configuration())
+ * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
+ * - Releasing of interfaces (libusb_release_interface())
+ * - Clearing of halt/stall condition (libusb_clear_halt())
+ * - Device resets (libusb_reset_device())
+ *
+ * \section configsel Configuration selection and handling
+ *
+ * When libusb presents a device handle to an application, there is a chance
+ * that the corresponding device may be in unconfigured state. For devices
+ * with multiple configurations, there is also a chance that the configuration
+ * currently selected is not the one that the application wants to use.
+ *
+ * The obvious solution is to add a call to libusb_set_configuration() early
+ * on during your device initialization routines, but there are caveats to
+ * be aware of:
+ * -# If the device is already in the desired configuration, calling
+ * libusb_set_configuration() using the same configuration value will cause
+ * a lightweight device reset. This may not be desirable behaviour.
+ * -# In the case where the desired configuration is already active, libusb
+ * may not even be able to perform a lightweight device reset. For example,
+ * take my USB keyboard with fingerprint reader: I'm interested in driving
+ * the fingerprint reader interface through libusb, but the kernel's
+ * USB-HID driver will almost always have claimed the keyboard interface.
+ * Because the kernel has claimed an interface, it is not even possible to
+ * perform the lightweight device reset, so libusb_set_configuration() will
+ * fail. (Luckily the device in question only has a single configuration.)
+ * -# libusb will be unable to set a configuration if other programs or
+ * drivers have claimed interfaces. In particular, this means that kernel
+ * drivers must be detached from all the interfaces before
+ * libusb_set_configuration() may succeed.
+ *
+ * One solution to some of the above problems is to consider the currently
+ * active configuration. If the configuration we want is already active, then
+ * we don't have to select any configuration:
+\code
+cfg = -1;
+libusb_get_configuration(dev, &cfg);
+if (cfg != desired)
+ libusb_set_configuration(dev, desired);
+\endcode
+ *
+ * This is probably suitable for most scenarios, but is inherently racy:
+ * another application or driver may change the selected configuration
+ * after the libusb_get_configuration() call.
+ *
+ * Even in cases where libusb_set_configuration() succeeds, consider that other
+ * applications or drivers may change configuration after your application
+ * calls libusb_set_configuration().
+ *
+ * One possible way to lock your device into a specific configuration is as
+ * follows:
+ * -# Set the desired configuration (or use the logic above to realise that
+ * it is already in the desired configuration)
+ * -# Claim the interface that you wish to use
+ * -# Check that the currently active configuration is the one that you want
+ * to use.
+ *
+ * The above method works because once an interface is claimed, no application
+ * or driver is able to select another configuration.
+ *
+ * \section earlycomp Early transfer completion
+ *
+ * NOTE: This section is currently Linux-centric. I am not sure if any of these
+ * considerations apply to Darwin or other platforms.
+ *
+ * When a transfer completes early (i.e. when less data is received/sent in
+ * any one packet than the transfer buffer allows for) then libusb is designed
+ * to terminate the transfer immediately, not transferring or receiving any
+ * more data unless other transfers have been queued by the user.
+ *
+ * On legacy platforms, libusb is unable to do this in all situations. After
+ * the incomplete packet occurs, "surplus" data may be transferred. For recent
+ * versions of libusb, this information is kept (the data length of the
+ * transfer is updated) and, for device-to-host transfers, any surplus data was
+ * added to the buffer. Still, this is not a nice solution because it loses the
+ * information about the end of the short packet, and the user probably wanted
+ * that surplus data to arrive in the next logical transfer.
+ *
+ * \section zlp Zero length packets
+ *
+ * - libusb is able to send a packet of zero length to an endpoint simply by
+ * submitting a transfer of zero length.
+ * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
+ * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
+ */
+
+/**
+ * \page libusb_contexts Contexts
+ *
+ * It is possible that libusb may be used simultaneously from two independent
+ * libraries linked into the same executable. For example, if your application
+ * has a plugin-like system which allows the user to dynamically load a range
+ * of modules into your program, it is feasible that two independently
+ * developed modules may both use libusb.
+ *
+ * libusb is written to allow for these multiple user scenarios. The two
+ * "instances" of libusb will not interfere: libusb_set_option() calls
+ * from one user will not affect the same settings for other users, other
+ * users can continue using libusb after one of them calls libusb_exit(), etc.
+ *
+ * This is made possible through libusb's context concept. When you
+ * call libusb_init(), you are (optionally) given a context. You can then pass
+ * this context pointer back into future libusb functions.
+ *
+ * In order to keep things simple for more simplistic applications, it is
+ * legal to pass NULL to all functions requiring a context pointer (as long as
+ * you're sure no other code will attempt to use libusb from the same process).
+ * When you pass NULL, the default context will be used. The default context
+ * is created the first time a process calls libusb_init() when no other
+ * context is alive. Contexts are destroyed during libusb_exit().
+ *
+ * The default context is reference-counted and can be shared. That means that
+ * if libusb_init(NULL) is called twice within the same process, the two
+ * users end up sharing the same context. The deinitialization and freeing of
+ * the default context will only happen when the last user calls libusb_exit().
+ * In other words, the default context is created and initialized when its
+ * reference count goes from 0 to 1, and is deinitialized and destroyed when
+ * its reference count goes from 1 to 0.
+ *
+ * You may be wondering why only a subset of libusb functions require a
+ * context pointer in their function definition. Internally, libusb stores
+ * context pointers in other objects (e.g. libusb_device instances) and hence
+ * can infer the context from those objects.
+ */
+
+ /**
+ * \page libusb_api Application Programming Interface
+ *
+ * This is the complete list of libusb functions, structures and
+ * enumerations in alphabetical order.
+ *
+ * \section Functions
+ * - libusb_alloc_streams()
+ * - libusb_alloc_transfer()
+ * - libusb_attach_kernel_driver()
+ * - libusb_bulk_transfer()
+ * - libusb_cancel_transfer()
+ * - libusb_claim_interface()
+ * - libusb_clear_halt()
+ * - libusb_close()
+ * - libusb_control_transfer()
+ * - libusb_control_transfer_get_data()
+ * - libusb_control_transfer_get_setup()
+ * - libusb_cpu_to_le16()
+ * - libusb_detach_kernel_driver()
+ * - libusb_dev_mem_alloc()
+ * - libusb_dev_mem_free()
+ * - libusb_error_name()
+ * - libusb_event_handler_active()
+ * - libusb_event_handling_ok()
+ * - libusb_exit()
+ * - libusb_fill_bulk_stream_transfer()
+ * - libusb_fill_bulk_transfer()
+ * - libusb_fill_control_setup()
+ * - libusb_fill_control_transfer()
+ * - libusb_fill_interrupt_transfer()
+ * - libusb_fill_iso_transfer()
+ * - libusb_free_bos_descriptor()
+ * - libusb_free_config_descriptor()
+ * - libusb_free_container_id_descriptor()
+ * - libusb_free_device_list()
+ * - libusb_free_pollfds()
+ * - libusb_free_ss_endpoint_companion_descriptor()
+ * - libusb_free_ss_usb_device_capability_descriptor()
+ * - libusb_free_streams()
+ * - libusb_free_transfer()
+ * - libusb_free_usb_2_0_extension_descriptor()
+ * - libusb_get_active_config_descriptor()
+ * - libusb_get_bos_descriptor()
+ * - libusb_get_bus_number()
+ * - libusb_get_config_descriptor()
+ * - libusb_get_config_descriptor_by_value()
+ * - libusb_get_configuration()
+ * - libusb_get_container_id_descriptor()
+ * - libusb_get_descriptor()
+ * - libusb_get_device()
+ * - libusb_get_device_address()
+ * - libusb_get_device_descriptor()
+ * - libusb_get_device_list()
+ * - libusb_get_device_speed()
+ * - libusb_get_iso_packet_buffer()
+ * - libusb_get_iso_packet_buffer_simple()
+ * - libusb_get_max_iso_packet_size()
+ * - libusb_get_max_packet_size()
+ * - libusb_get_next_timeout()
+ * - libusb_get_parent()
+ * - libusb_get_pollfds()
+ * - libusb_get_port_number()
+ * - libusb_get_port_numbers()
+ * - libusb_get_port_path()
+ * - libusb_get_ss_endpoint_companion_descriptor()
+ * - libusb_get_ss_usb_device_capability_descriptor()
+ * - libusb_get_string_descriptor()
+ * - libusb_get_string_descriptor_ascii()
+ * - libusb_get_usb_2_0_extension_descriptor()
+ * - libusb_get_version()
+ * - libusb_handle_events()
+ * - libusb_handle_events_completed()
+ * - libusb_handle_events_locked()
+ * - libusb_handle_events_timeout()
+ * - libusb_handle_events_timeout_completed()
+ * - libusb_has_capability()
+ * - libusb_hotplug_deregister_callback()
+ * - libusb_hotplug_register_callback()
+ * - libusb_init()
+ * - libusb_interrupt_event_handler()
+ * - libusb_interrupt_transfer()
+ * - libusb_kernel_driver_active()
+ * - libusb_lock_events()
+ * - libusb_lock_event_waiters()
+ * - libusb_open()
+ * - libusb_open_device_with_vid_pid()
+ * - libusb_pollfds_handle_timeouts()
+ * - libusb_ref_device()
+ * - libusb_release_interface()
+ * - libusb_reset_device()
+ * - libusb_set_auto_detach_kernel_driver()
+ * - libusb_set_configuration()
+ * - libusb_set_debug()
+ * - libusb_set_interface_alt_setting()
+ * - libusb_set_iso_packet_lengths()
+ * - libusb_set_option()
+ * - libusb_setlocale()
+ * - libusb_set_pollfd_notifiers()
+ * - libusb_strerror()
+ * - libusb_submit_transfer()
+ * - libusb_transfer_get_stream_id()
+ * - libusb_transfer_set_stream_id()
+ * - libusb_try_lock_events()
+ * - libusb_unlock_events()
+ * - libusb_unlock_event_waiters()
+ * - libusb_unref_device()
+ * - libusb_wait_for_event()
+ *
+ * \section Structures
+ * - libusb_bos_descriptor
+ * - libusb_bos_dev_capability_descriptor
+ * - libusb_config_descriptor
+ * - libusb_container_id_descriptor
+ * - \ref libusb_context
+ * - libusb_control_setup
+ * - \ref libusb_device
+ * - libusb_device_descriptor
+ * - \ref libusb_device_handle
+ * - libusb_endpoint_descriptor
+ * - libusb_interface
+ * - libusb_interface_descriptor
+ * - libusb_iso_packet_descriptor
+ * - libusb_pollfd
+ * - libusb_ss_endpoint_companion_descriptor
+ * - libusb_ss_usb_device_capability_descriptor
+ * - libusb_transfer
+ * - libusb_usb_2_0_extension_descriptor
+ * - libusb_version
+ *
+ * \section Enums
+ * - \ref libusb_bos_type
+ * - \ref libusb_capability
+ * - \ref libusb_class_code
+ * - \ref libusb_descriptor_type
+ * - \ref libusb_endpoint_direction
+ * - \ref libusb_error
+ * - \ref libusb_iso_sync_type
+ * - \ref libusb_iso_usage_type
+ * - \ref libusb_log_level
+ * - \ref libusb_option
+ * - \ref libusb_request_recipient
+ * - \ref libusb_request_type
+ * - \ref libusb_speed
+ * - \ref libusb_ss_usb_device_capability_attributes
+ * - \ref libusb_standard_request
+ * - \ref libusb_supported_speed
+ * - \ref libusb_transfer_flags
+ * - \ref libusb_transfer_status
+ * - \ref libusb_transfer_type
+ * - \ref libusb_usb_2_0_extension_attributes
+ */
+
+/**
+ * @defgroup libusb_lib Library initialization/deinitialization
+ * This page details how to initialize and deinitialize libusb. Initialization
+ * must be performed before using any libusb functionality, and similarly you
+ * must not call any libusb functions after deinitialization.
+ */
+
+/**
+ * @defgroup libusb_dev Device handling and enumeration
+ * The functionality documented below is designed to help with the following
+ * operations:
+ * - Enumerating the USB devices currently attached to the system
+ * - Choosing a device to operate from your software
+ * - Opening and closing the chosen device
+ *
+ * \section nutshell In a nutshell...
+ *
+ * The description below really makes things sound more complicated than they
+ * actually are. The following sequence of function calls will be suitable
+ * for almost all scenarios and does not require you to have such a deep
+ * understanding of the resource management issues:
+ * \code
+// discover devices
+libusb_device **list;
+libusb_device *found = NULL;
+ssize_t cnt = libusb_get_device_list(NULL, &list);
+ssize_t i = 0;
+int err = 0;
+if (cnt < 0)
+ error();
+
+for (i = 0; i < cnt; i++) {
+ libusb_device *device = list[i];
+ if (is_interesting(device)) {
+ found = device;
+ break;
+ }
+}
+
+if (found) {
+ libusb_device_handle *handle;
+
+ err = libusb_open(found, &handle);
+ if (err)
+ error();
+ // etc
+}
+
+libusb_free_device_list(list, 1);
+\endcode
+ *
+ * The two important points:
+ * - You asked libusb_free_device_list() to unreference the devices (2nd
+ * parameter)
+ * - You opened the device before freeing the list and unreferencing the
+ * devices
+ *
+ * If you ended up with a handle, you can now proceed to perform I/O on the
+ * device.
+ *
+ * \section devshandles Devices and device handles
+ * libusb has a concept of a USB device, represented by the
+ * \ref libusb_device opaque type. A device represents a USB device that
+ * is currently or was previously connected to the system. Using a reference
+ * to a device, you can determine certain information about the device (e.g.
+ * you can read the descriptor data).
+ *
+ * The libusb_get_device_list() function can be used to obtain a list of
+ * devices currently connected to the system. This is known as device
+ * discovery.
+ *
+ * Just because you have a reference to a device does not mean it is
+ * necessarily usable. The device may have been unplugged, you may not have
+ * permission to operate such device, or another program or driver may be
+ * using the device.
+ *
+ * When you've found a device that you'd like to operate, you must ask
+ * libusb to open the device using the libusb_open() function. Assuming
+ * success, libusb then returns you a device handle
+ * (a \ref libusb_device_handle pointer). All "real" I/O operations then
+ * operate on the handle rather than the original device pointer.
+ *
+ * \section devref Device discovery and reference counting
+ *
+ * Device discovery (i.e. calling libusb_get_device_list()) returns a
+ * freshly-allocated list of devices. The list itself must be freed when
+ * you are done with it. libusb also needs to know when it is OK to free
+ * the contents of the list - the devices themselves.
+ *
+ * To handle these issues, libusb provides you with two separate items:
+ * - A function to free the list itself
+ * - A reference counting system for the devices inside
+ *
+ * New devices presented by the libusb_get_device_list() function all have a
+ * reference count of 1. You can increase and decrease reference count using
+ * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
+ * its reference count reaches 0.
+ *
+ * With the above information in mind, the process of opening a device can
+ * be viewed as follows:
+ * -# Discover devices using libusb_get_device_list().
+ * -# Choose the device that you want to operate, and call libusb_open().
+ * -# Unref all devices in the discovered device list.
+ * -# Free the discovered device list.
+ *
+ * The order is important - you must not unreference the device before
+ * attempting to open it, because unreferencing it may destroy the device.
+ *
+ * For convenience, the libusb_free_device_list() function includes a
+ * parameter to optionally unreference all the devices in the list before
+ * freeing the list itself. This combines steps 3 and 4 above.
+ *
+ * As an implementation detail, libusb_open() actually adds a reference to
+ * the device in question. This is because the device remains available
+ * through the handle via libusb_get_device(). The reference is deleted during
+ * libusb_close().
+ */
+
+/** @defgroup libusb_misc Miscellaneous */
+
+/* we traverse usbfs without knowing how many devices we are going to find.
+ * so we create this discovered_devs model which is similar to a linked-list
+ * which grows when required. it can be freed once discovery has completed,
+ * eliminating the need for a list node in the libusb_device structure
+ * itself. */
+#define DISCOVERED_DEVICES_SIZE_STEP 8
+
+static struct discovered_devs *discovered_devs_alloc(void)
+{
+ struct discovered_devs *ret =
+ malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
+
+ if (ret) {
+ ret->len = 0;
+ ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
+ }
+ return ret;
+}
+
+static void discovered_devs_free(struct discovered_devs *discdevs)
+{
+ size_t i;
+
+ for (i = 0; i < discdevs->len; i++)
+ libusb_unref_device(discdevs->devices[i]);
+
+ free(discdevs);
+}
+
+/* append a device to the discovered devices collection. may realloc itself,
+ * returning new discdevs. returns NULL on realloc failure. */
+struct discovered_devs *discovered_devs_append(
+ struct discovered_devs *discdevs, struct libusb_device *dev)
+{
+ size_t len = discdevs->len;
+ size_t capacity;
+ struct discovered_devs *new_discdevs;
+
+ /* if there is space, just append the device */
+ if (len < discdevs->capacity) {
+ discdevs->devices[len] = libusb_ref_device(dev);
+ discdevs->len++;
+ return discdevs;
+ }
+
+ /* exceeded capacity, need to grow */
+ usbi_dbg("need to increase capacity");
+ capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
+ /* can't use usbi_reallocf here because in failure cases it would
+ * free the existing discdevs without unreferencing its devices. */
+ new_discdevs = realloc(discdevs,
+ sizeof(*discdevs) + (sizeof(void *) * capacity));
+ if (!new_discdevs) {
+ discovered_devs_free(discdevs);
+ return NULL;
+ }
+
+ discdevs = new_discdevs;
+ discdevs->capacity = capacity;
+ discdevs->devices[len] = libusb_ref_device(dev);
+ discdevs->len++;
+
+ return discdevs;
+}
+
+/* Allocate a new device with a specific session ID. The returned device has
+ * a reference count of 1. */
+struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
+ unsigned long session_id)
+{
+ size_t priv_size = usbi_backend.device_priv_size;
+ struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
+ int r;
+
+ if (!dev)
+ return NULL;
+
+ r = usbi_mutex_init(&dev->lock);
+ if (r) {
+ free(dev);
+ return NULL;
+ }
+
+ dev->ctx = ctx;
+ dev->refcnt = 1;
+ dev->session_data = session_id;
+ dev->speed = LIBUSB_SPEED_UNKNOWN;
+
+ if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ usbi_connect_device (dev);
+ }
+
+ return dev;
+}
+
+void usbi_connect_device(struct libusb_device *dev)
+{
+ struct libusb_context *ctx = DEVICE_CTX(dev);
+
+ dev->attached = 1;
+
+ usbi_mutex_lock(&dev->ctx->usb_devs_lock);
+ list_add(&dev->list, &dev->ctx->usb_devs);
+ usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
+
+ /* Signal that an event has occurred for this device if we support hotplug AND
+ * the hotplug message list is ready. This prevents an event from getting raised
+ * during initial enumeration. */
+ if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
+ usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
+ }
+}
+
+void usbi_disconnect_device(struct libusb_device *dev)
+{
+ struct libusb_context *ctx = DEVICE_CTX(dev);
+
+ usbi_mutex_lock(&dev->lock);
+ dev->attached = 0;
+ usbi_mutex_unlock(&dev->lock);
+
+ usbi_mutex_lock(&ctx->usb_devs_lock);
+ list_del(&dev->list);
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
+
+ /* Signal that an event has occurred for this device if we support hotplug AND
+ * the hotplug message list is ready. This prevents an event from getting raised
+ * during initial enumeration. libusb_handle_events will take care of dereferencing
+ * the device. */
+ if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) {
+ usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
+ }
+}
+
+/* Perform some final sanity checks on a newly discovered device. If this
+ * function fails (negative return code), the device should not be added
+ * to the discovered device list. */
+int usbi_sanitize_device(struct libusb_device *dev)
+{
+ int r;
+ uint8_t num_configurations;
+
+ r = usbi_device_cache_descriptor(dev);
+ if (r < 0)
+ return r;
+
+ num_configurations = dev->device_descriptor.bNumConfigurations;
+ if (num_configurations > USB_MAXCONFIG) {
+ usbi_err(DEVICE_CTX(dev), "too many configurations");
+ return LIBUSB_ERROR_IO;
+ } else if (0 == num_configurations)
+ usbi_dbg("zero configurations, maybe an unauthorized device");
+
+ dev->num_configurations = num_configurations;
+ return 0;
+}
+
+/* Examine libusb's internal list of known devices, looking for one with
+ * a specific session ID. Returns the matching device if it was found, and
+ * NULL otherwise. */
+struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
+ unsigned long session_id)
+{
+ struct libusb_device *dev;
+ struct libusb_device *ret = NULL;
+
+ usbi_mutex_lock(&ctx->usb_devs_lock);
+ list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
+ if (dev->session_data == session_id) {
+ ret = libusb_ref_device(dev);
+ break;
+ }
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
+
+ return ret;
+}
+
+/** @ingroup libusb_dev
+ * Returns a list of USB devices currently attached to the system. This is
+ * your entry point into finding a USB device to operate.
+ *
+ * You are expected to unreference all the devices when you are done with
+ * them, and then free the list with libusb_free_device_list(). Note that
+ * libusb_free_device_list() can unref all the devices for you. Be careful
+ * not to unreference a device you are about to open until after you have
+ * opened it.
+ *
+ * This return value of this function indicates the number of devices in
+ * the resultant list. The list is actually one element larger, as it is
+ * NULL-terminated.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param list output location for a list of devices. Must be later freed with
+ * libusb_free_device_list().
+ * \returns the number of devices in the outputted list, or any
+ * \ref libusb_error according to errors encountered by the backend.
+ */
+ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
+ libusb_device ***list)
+{
+ struct discovered_devs *discdevs = discovered_devs_alloc();
+ struct libusb_device **ret;
+ int r = 0;
+ ssize_t i, len;
+ USBI_GET_CONTEXT(ctx);
+ usbi_dbg("");
+
+ if (!discdevs)
+ return LIBUSB_ERROR_NO_MEM;
+
+ if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ /* backend provides hotplug support */
+ struct libusb_device *dev;
+
+ if (usbi_backend.hotplug_poll)
+ usbi_backend.hotplug_poll();
+
+ usbi_mutex_lock(&ctx->usb_devs_lock);
+ list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
+ discdevs = discovered_devs_append(discdevs, dev);
+
+ if (!discdevs) {
+ r = LIBUSB_ERROR_NO_MEM;
+ break;
+ }
+ }
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
+ } else {
+ /* backend does not provide hotplug support */
+ r = usbi_backend.get_device_list(ctx, &discdevs);
+ }
+
+ if (r < 0) {
+ len = r;
+ goto out;
+ }
+
+ /* convert discovered_devs into a list */
+ len = discdevs->len;
+ ret = calloc(len + 1, sizeof(struct libusb_device *));
+ if (!ret) {
+ len = LIBUSB_ERROR_NO_MEM;
+ goto out;
+ }
+
+ ret[len] = NULL;
+ for (i = 0; i < len; i++) {
+ struct libusb_device *dev = discdevs->devices[i];
+ ret[i] = libusb_ref_device(dev);
+ }
+ *list = ret;
+
+out:
+ if (discdevs)
+ discovered_devs_free(discdevs);
+ return len;
+}
+
+/** \ingroup libusb_dev
+ * Frees a list of devices previously discovered using
+ * libusb_get_device_list(). If the unref_devices parameter is set, the
+ * reference count of each device in the list is decremented by 1.
+ * \param list the list to free
+ * \param unref_devices whether to unref the devices in the list
+ */
+void API_EXPORTED libusb_free_device_list(libusb_device **list,
+ int unref_devices)
+{
+ if (!list)
+ return;
+
+ if (unref_devices) {
+ int i = 0;
+ struct libusb_device *dev;
+
+ while ((dev = list[i++]) != NULL)
+ libusb_unref_device(dev);
+ }
+ free(list);
+}
+
+/** \ingroup libusb_dev
+ * Get the number of the bus that a device is connected to.
+ * \param dev a device
+ * \returns the bus number
+ */
+uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
+{
+ return dev->bus_number;
+}
+
+/** \ingroup libusb_dev
+ * Get the number of the port that a device is connected to.
+ * Unless the OS does something funky, or you are hot-plugging USB extension cards,
+ * the port number returned by this call is usually guaranteed to be uniquely tied
+ * to a physical port, meaning that different devices plugged on the same physical
+ * port should return the same port number.
+ *
+ * But outside of this, there is no guarantee that the port number returned by this
+ * call will remain the same, or even match the order in which ports have been
+ * numbered by the HUB/HCD manufacturer.
+ *
+ * \param dev a device
+ * \returns the port number (0 if not available)
+ */
+uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
+{
+ return dev->port_number;
+}
+
+/** \ingroup libusb_dev
+ * Get the list of all port numbers from root for the specified device
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ * \param dev a device
+ * \param port_numbers the array that should contain the port numbers
+ * \param port_numbers_len the maximum length of the array. As per the USB 3.0
+ * specs, the current maximum limit for the depth is 7.
+ * \returns the number of elements filled
+ * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
+ */
+int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
+ uint8_t* port_numbers, int port_numbers_len)
+{
+ int i = port_numbers_len;
+ struct libusb_context *ctx = DEVICE_CTX(dev);
+
+ if (port_numbers_len <= 0)
+ return LIBUSB_ERROR_INVALID_PARAM;
+
+ // HCDs can be listed as devices with port #0
+ while((dev) && (dev->port_number != 0)) {
+ if (--i < 0) {
+ usbi_warn(ctx, "port numbers array is too small");
+ return LIBUSB_ERROR_OVERFLOW;
+ }
+ port_numbers[i] = dev->port_number;
+ dev = dev->parent_dev;
+ }
+ if (i < port_numbers_len)
+ memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
+ return port_numbers_len - i;
+}
+
+/** \ingroup libusb_dev
+ * Deprecated please use libusb_get_port_numbers instead.
+ */
+int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
+ uint8_t* port_numbers, uint8_t port_numbers_len)
+{
+ UNUSED(ctx);
+
+ return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
+}
+
+/** \ingroup libusb_dev
+ * Get the the parent from the specified device.
+ * \param dev a device
+ * \returns the device parent or NULL if not available
+ * You should issue a \ref libusb_get_device_list() before calling this
+ * function and make sure that you only access the parent before issuing
+ * \ref libusb_free_device_list(). The reason is that libusb currently does
+ * not maintain a permanent list of device instances, and therefore can
+ * only guarantee that parents are fully instantiated within a
+ * libusb_get_device_list() - libusb_free_device_list() block.
+ */
+DEFAULT_VISIBILITY
+libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
+{
+ return dev->parent_dev;
+}
+
+/** \ingroup libusb_dev
+ * Get the address of the device on the bus it is connected to.
+ * \param dev a device
+ * \returns the device address
+ */
+uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
+{
+ return dev->device_address;
+}
+
+/** \ingroup libusb_dev
+ * Get the negotiated connection speed for a device.
+ * \param dev a device
+ * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
+ * the OS doesn't know or doesn't support returning the negotiated speed.
+ */
+int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
+{
+ return dev->speed;
+}
+
+static const struct libusb_endpoint_descriptor *find_endpoint(
+ struct libusb_config_descriptor *config, unsigned char endpoint)
+{
+ int iface_idx;
+ for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
+ const struct libusb_interface *iface = &config->interface[iface_idx];
+ int altsetting_idx;
+
+ for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
+ altsetting_idx++) {
+ const struct libusb_interface_descriptor *altsetting
+ = &iface->altsetting[altsetting_idx];
+ int ep_idx;
+
+ for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
+ const struct libusb_endpoint_descriptor *ep =
+ &altsetting->endpoint[ep_idx];
+ if (ep->bEndpointAddress == endpoint)
+ return ep;
+ }
+ }
+ }
+ return NULL;
+}
+
+/** \ingroup libusb_dev
+ * Convenience function to retrieve the wMaxPacketSize value for a particular
+ * endpoint in the active device configuration.
+ *
+ * This function was originally intended to be of assistance when setting up
+ * isochronous transfers, but a design mistake resulted in this function
+ * instead. It simply returns the wMaxPacketSize value without considering
+ * its contents. If you're dealing with isochronous transfers, you probably
+ * want libusb_get_max_iso_packet_size() instead.
+ *
+ * \param dev a device
+ * \param endpoint address of the endpoint in question
+ * \returns the wMaxPacketSize value
+ * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
+ * \returns LIBUSB_ERROR_OTHER on other failure
+ */
+int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
+ unsigned char endpoint)
+{
+ struct libusb_config_descriptor *config;
+ const struct libusb_endpoint_descriptor *ep;
+ int r;
+
+ r = libusb_get_active_config_descriptor(dev, &config);
+ if (r < 0) {
+ usbi_err(DEVICE_CTX(dev),
+ "could not retrieve active config descriptor");
+ return LIBUSB_ERROR_OTHER;
+ }
+
+ ep = find_endpoint(config, endpoint);
+ if (!ep) {
+ r = LIBUSB_ERROR_NOT_FOUND;
+ goto out;
+ }
+
+ r = ep->wMaxPacketSize;
+
+out:
+ libusb_free_config_descriptor(config);
+ return r;
+}
+
+/** \ingroup libusb_dev
+ * Calculate the maximum packet size which a specific endpoint is capable is
+ * sending or receiving in the duration of 1 microframe
+ *
+ * Only the active configuration is examined. The calculation is based on the
+ * wMaxPacketSize field in the endpoint descriptor as described in section
+ * 9.6.6 in the USB 2.0 specifications.
+ *
+ * If acting on an isochronous or interrupt endpoint, this function will
+ * multiply the value found in bits 0:10 by the number of transactions per
+ * microframe (determined by bits 11:12). Otherwise, this function just
+ * returns the numeric value found in bits 0:10.
+ *
+ * This function is useful for setting up isochronous transfers, for example
+ * you might pass the return value from this function to
+ * libusb_set_iso_packet_lengths() in order to set the length field of every
+ * isochronous packet in a transfer.
+ *
+ * Since v1.0.3.
+ *
+ * \param dev a device
+ * \param endpoint address of the endpoint in question
+ * \returns the maximum packet size which can be sent/received on this endpoint
+ * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
+ * \returns LIBUSB_ERROR_OTHER on other failure
+ */
+int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
+ unsigned char endpoint)
+{
+ struct libusb_config_descriptor *config;
+ const struct libusb_endpoint_descriptor *ep;
+ enum libusb_transfer_type ep_type;
+ uint16_t val;
+ int r;
+
+ r = libusb_get_active_config_descriptor(dev, &config);
+ if (r < 0) {
+ usbi_err(DEVICE_CTX(dev),
+ "could not retrieve active config descriptor");
+ return LIBUSB_ERROR_OTHER;
+ }
+
+ ep = find_endpoint(config, endpoint);
+ if (!ep) {
+ r = LIBUSB_ERROR_NOT_FOUND;
+ goto out;
+ }
+
+ val = ep->wMaxPacketSize;
+ ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
+
+ r = val & 0x07ff;
+ if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
+ || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
+ r *= (1 + ((val >> 11) & 3));
+
+out:
+ libusb_free_config_descriptor(config);
+ return r;
+}
+
+/** \ingroup libusb_dev
+ * Increment the reference count of a device.
+ * \param dev the device to reference
+ * \returns the same device
+ */
+DEFAULT_VISIBILITY
+libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
+{
+ usbi_mutex_lock(&dev->lock);
+ dev->refcnt++;
+ usbi_mutex_unlock(&dev->lock);
+ return dev;
+}
+
+/** \ingroup libusb_dev
+ * Decrement the reference count of a device. If the decrement operation
+ * causes the reference count to reach zero, the device shall be destroyed.
+ * \param dev the device to unreference
+ */
+void API_EXPORTED libusb_unref_device(libusb_device *dev)
+{
+ int refcnt;
+
+ if (!dev)
+ return;
+
+ usbi_mutex_lock(&dev->lock);
+ refcnt = --dev->refcnt;
+ usbi_mutex_unlock(&dev->lock);
+
+ if (refcnt == 0) {
+ usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
+
+ libusb_unref_device(dev->parent_dev);
+
+ if (usbi_backend.destroy_device)
+ usbi_backend.destroy_device(dev);
+
+ if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ /* backend does not support hotplug */
+ usbi_disconnect_device(dev);
+ }
+
+ usbi_mutex_destroy(&dev->lock);
+ free(dev);
+ }
+}
+
+/*
+ * Signal the event pipe so that the event handling thread will be
+ * interrupted to process an internal event.
+ */
+int usbi_signal_event(struct libusb_context *ctx)
+{
+ unsigned char dummy = 1;
+ ssize_t r;
+
+ /* write some data on event pipe to interrupt event handlers */
+ r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy));
+ if (r != sizeof(dummy)) {
+ usbi_warn(ctx, "internal signalling write failed");
+ return LIBUSB_ERROR_IO;
+ }
+
+ return 0;
+}
+
+/*
+ * Clear the event pipe so that the event handling will no longer be
+ * interrupted.
+ */
+int usbi_clear_event(struct libusb_context *ctx)
+{
+ unsigned char dummy;
+ ssize_t r;
+
+ /* read some data on event pipe to clear it */
+ r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy));
+ if (r != sizeof(dummy)) {
+ usbi_warn(ctx, "internal signalling read failed");
+ return LIBUSB_ERROR_IO;
+ }
+
+ return 0;
+}
+
+/** \ingroup libusb_dev
+ * Open a device and obtain a device handle. A handle allows you to perform
+ * I/O on the device in question.
+ *
+ * Internally, this function adds a reference to the device and makes it
+ * available to you through libusb_get_device(). This reference is removed
+ * during libusb_close().
+ *
+ * This is a non-blocking function; no requests are sent over the bus.
+ *
+ * \param dev the device to open
+ * \param dev_handle output location for the returned device handle pointer. Only
+ * populated when the return code is 0.
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
+ * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ */
+int API_EXPORTED libusb_open(libusb_device *dev,
+ libusb_device_handle **dev_handle)
+{
+ struct libusb_context *ctx = DEVICE_CTX(dev);
+ struct libusb_device_handle *_dev_handle;
+ size_t priv_size = usbi_backend.device_handle_priv_size;
+ int r;
+ usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
+
+ if (!dev->attached) {
+ return LIBUSB_ERROR_NO_DEVICE;
+ }
+
+ _dev_handle = malloc(sizeof(*_dev_handle) + priv_size);
+ if (!_dev_handle)
+ return LIBUSB_ERROR_NO_MEM;
+
+ r = usbi_mutex_init(&_dev_handle->lock);
+ if (r) {
+ free(_dev_handle);
+ return LIBUSB_ERROR_OTHER;
+ }
+
+ _dev_handle->dev = libusb_ref_device(dev);
+ _dev_handle->auto_detach_kernel_driver = 0;
+ _dev_handle->claimed_interfaces = 0;
+ memset(&_dev_handle->os_priv, 0, priv_size);
+
+ r = usbi_backend.open(_dev_handle);
+ if (r < 0) {
+ usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
+ libusb_unref_device(dev);
+ usbi_mutex_destroy(&_dev_handle->lock);
+ free(_dev_handle);
+ return r;
+ }
+
+ usbi_mutex_lock(&ctx->open_devs_lock);
+ list_add(&_dev_handle->list, &ctx->open_devs);
+ usbi_mutex_unlock(&ctx->open_devs_lock);
+ *dev_handle = _dev_handle;
+
+ return 0;
+}
+
+/** \ingroup libusb_dev
+ * Convenience function for finding a device with a particular
+ * idVendor/idProduct combination. This function is intended
+ * for those scenarios where you are using libusb to knock up a quick test
+ * application - it allows you to avoid calling libusb_get_device_list() and
+ * worrying about traversing/freeing the list.
+ *
+ * This function has limitations and is hence not intended for use in real
+ * applications: if multiple devices have the same IDs it will only
+ * give you the first one, etc.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param vendor_id the idVendor value to search for
+ * \param product_id the idProduct value to search for
+ * \returns a device handle for the first found device, or NULL on error
+ * or if the device could not be found. */
+DEFAULT_VISIBILITY
+libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
+ libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
+{
+ struct libusb_device **devs;
+ struct libusb_device *found = NULL;
+ struct libusb_device *dev;
+ struct libusb_device_handle *dev_handle = NULL;
+ size_t i = 0;
+ int r;
+
+ if (libusb_get_device_list(ctx, &devs) < 0)
+ return NULL;
+
+ while ((dev = devs[i++]) != NULL) {
+ struct libusb_device_descriptor desc;
+ r = libusb_get_device_descriptor(dev, &desc);
+ if (r < 0)
+ goto out;
+ if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
+ found = dev;
+ break;
+ }
+ }
+
+ if (found) {
+ r = libusb_open(found, &dev_handle);
+ if (r < 0)
+ dev_handle = NULL;
+ }
+
+out:
+ libusb_free_device_list(devs, 1);
+ return dev_handle;
+}
+
+static void do_close(struct libusb_context *ctx,
+ struct libusb_device_handle *dev_handle)
+{
+ struct usbi_transfer *itransfer;
+ struct usbi_transfer *tmp;
+
+ /* remove any transfers in flight that are for this device */
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+
+ /* safe iteration because transfers may be being deleted */
+ list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
+ struct libusb_transfer *transfer =
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+
+ if (transfer->dev_handle != dev_handle)
+ continue;
+
+ usbi_mutex_lock(&itransfer->lock);
+ if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
+ usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
+
+ if (itransfer->state_flags & USBI_TRANSFER_CANCELLING)
+ usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
+ else
+ usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
+ }
+ usbi_mutex_unlock(&itransfer->lock);
+
+ /* remove from the list of in-flight transfers and make sure
+ * we don't accidentally use the device handle in the future
+ * (or that such accesses will be easily caught and identified as a crash)
+ */
+ list_del(&itransfer->list);
+ transfer->dev_handle = NULL;
+
+ /* it is up to the user to free up the actual transfer struct. this is
+ * just making sure that we don't attempt to process the transfer after
+ * the device handle is invalid
+ */
+ usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
+ transfer, dev_handle);
+ }
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+
+ usbi_mutex_lock(&ctx->open_devs_lock);
+ list_del(&dev_handle->list);
+ usbi_mutex_unlock(&ctx->open_devs_lock);
+
+ usbi_backend.close(dev_handle);
+ libusb_unref_device(dev_handle->dev);
+ usbi_mutex_destroy(&dev_handle->lock);
+ free(dev_handle);
+}
+
+/** \ingroup libusb_dev
+ * Close a device handle. Should be called on all open handles before your
+ * application exits.
+ *
+ * Internally, this function destroys the reference that was added by
+ * libusb_open() on the given device.
+ *
+ * This is a non-blocking function; no requests are sent over the bus.
+ *
+ * \param dev_handle the device handle to close
+ */
+void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
+{
+ struct libusb_context *ctx;
+ int handling_events;
+ int pending_events;
+
+ if (!dev_handle)
+ return;
+ usbi_dbg("");
+
+ ctx = HANDLE_CTX(dev_handle);
+ handling_events = usbi_handling_events(ctx);
+
+ /* Similarly to libusb_open(), we want to interrupt all event handlers
+ * at this point. More importantly, we want to perform the actual close of
+ * the device while holding the event handling lock (preventing any other
+ * thread from doing event handling) because we will be removing a file
+ * descriptor from the polling loop. If this is being called by the current
+ * event handler, we can bypass the interruption code because we already
+ * hold the event handling lock. */
+
+ if (!handling_events) {
+ /* Record that we are closing a device.
+ * Only signal an event if there are no prior pending events. */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ pending_events = usbi_pending_events(ctx);
+ ctx->device_close++;
+ if (!pending_events)
+ usbi_signal_event(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+
+ /* take event handling lock */
+ libusb_lock_events(ctx);
+ }
+
+ /* Close the device */
+ do_close(ctx, dev_handle);
+
+ if (!handling_events) {
+ /* We're done with closing this device.
+ * Clear the event pipe if there are no further pending events. */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ ctx->device_close--;
+ pending_events = usbi_pending_events(ctx);
+ if (!pending_events)
+ usbi_clear_event(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+
+ /* Release event handling lock and wake up event waiters */
+ libusb_unlock_events(ctx);
+ }
+}
+
+/** \ingroup libusb_dev
+ * Get the underlying device for a device handle. This function does not modify
+ * the reference count of the returned device, so do not feel compelled to
+ * unreference it when you are done.
+ * \param dev_handle a device handle
+ * \returns the underlying device
+ */
+DEFAULT_VISIBILITY
+libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
+{
+ return dev_handle->dev;
+}
+
+/** \ingroup libusb_dev
+ * Determine the bConfigurationValue of the currently active configuration.
+ *
+ * You could formulate your own control request to obtain this information,
+ * but this function has the advantage that it may be able to retrieve the
+ * information from operating system caches (no I/O involved).
+ *
+ * If the OS does not cache this information, then this function will block
+ * while a control transfer is submitted to retrieve the information.
+ *
+ * This function will return a value of 0 in the config output
+ * parameter if the device is in unconfigured state.
+ *
+ * \param dev_handle a device handle
+ * \param config output location for the bConfigurationValue of the active
+ * configuration (only valid for return code 0)
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ */
+int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
+ int *config)
+{
+ int r = LIBUSB_ERROR_NOT_SUPPORTED;
+
+ usbi_dbg("");
+ if (usbi_backend.get_configuration)
+ r = usbi_backend.get_configuration(dev_handle, config);
+
+ if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
+ uint8_t tmp = 0;
+ usbi_dbg("falling back to control message");
+ r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
+ LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
+ if (r == 0) {
+ usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?");
+ r = LIBUSB_ERROR_IO;
+ } else if (r == 1) {
+ r = 0;
+ *config = tmp;
+ } else {
+ usbi_dbg("control failed, error %d", r);
+ }
+ }
+
+ if (r == 0)
+ usbi_dbg("active config %d", *config);
+
+ return r;
+}
+
+/** \ingroup libusb_dev
+ * Set the active configuration for a device.
+ *
+ * The operating system may or may not have already set an active
+ * configuration on the device. It is up to your application to ensure the
+ * correct configuration is selected before you attempt to claim interfaces
+ * and perform other operations.
+ *
+ * If you call this function on a device already configured with the selected
+ * configuration, then this function will act as a lightweight device reset:
+ * it will issue a SET_CONFIGURATION request using the current configuration,
+ * causing most USB-related device state to be reset (altsetting reset to zero,
+ * endpoint halts cleared, toggles reset).
+ *
+ * You cannot change/reset configuration if your application has claimed
+ * interfaces. It is advised to set the desired configuration before claiming
+ * interfaces.
+ *
+ * Alternatively you can call libusb_release_interface() first. Note if you
+ * do things this way you must ensure that auto_detach_kernel_driver for
+ * dev is 0, otherwise the kernel driver will be re-attached when you
+ * release the interface(s).
+ *
+ * You cannot change/reset configuration if other applications or drivers have
+ * claimed interfaces.
+ *
+ * A configuration value of -1 will put the device in unconfigured state.
+ * The USB specifications state that a configuration value of 0 does this,
+ * however buggy devices exist which actually have a configuration 0.
+ *
+ * You should always use this function rather than formulating your own
+ * SET_CONFIGURATION control request. This is because the underlying operating
+ * system needs to know when such changes happen.
+ *
+ * This is a blocking function.
+ *
+ * \param dev_handle a device handle
+ * \param configuration the bConfigurationValue of the configuration you
+ * wish to activate, or -1 if you wish to put the device in an unconfigured
+ * state
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
+ * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_set_auto_detach_kernel_driver()
+ */
+int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
+ int configuration)
+{
+ usbi_dbg("configuration %d", configuration);
+ return usbi_backend.set_configuration(dev_handle, configuration);
+}
+
+/** \ingroup libusb_dev
+ * Claim an interface on a given device handle. You must claim the interface
+ * you wish to use before you can perform I/O on any of its endpoints.
+ *
+ * It is legal to attempt to claim an already-claimed interface, in which
+ * case libusb just returns 0 without doing anything.
+ *
+ * If auto_detach_kernel_driver is set to 1 for dev, the kernel driver
+ * will be detached if necessary, on failure the detach error is returned.
+ *
+ * Claiming of interfaces is a purely logical operation; it does not cause
+ * any requests to be sent over the bus. Interface claiming is used to
+ * instruct the underlying operating system that your application wishes
+ * to take ownership of the interface.
+ *
+ * This is a non-blocking function.
+ *
+ * \param dev_handle a device handle
+ * \param interface_number the bInterfaceNumber of the interface you
+ * wish to claim
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
+ * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
+ * interface
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns a LIBUSB_ERROR code on other failure
+ * \see libusb_set_auto_detach_kernel_driver()
+ */
+int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
+ int interface_number)
+{
+ int r = 0;
+
+ usbi_dbg("interface %d", interface_number);
+ if (interface_number >= USB_MAXINTERFACES)
+ return LIBUSB_ERROR_INVALID_PARAM;
+
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ usbi_mutex_lock(&dev_handle->lock);
+ if (dev_handle->claimed_interfaces & (1 << interface_number))
+ goto out;
+
+ r = usbi_backend.claim_interface(dev_handle, interface_number);
+ if (r == 0)
+ dev_handle->claimed_interfaces |= 1 << interface_number;
+
+out:
+ usbi_mutex_unlock(&dev_handle->lock);
+ return r;
+}
+
+/** \ingroup libusb_dev
+ * Release an interface previously claimed with libusb_claim_interface(). You
+ * should release all claimed interfaces before closing a device handle.
+ *
+ * This is a blocking function. A SET_INTERFACE control request will be sent
+ * to the device, resetting interface state to the first alternate setting.
+ *
+ * If auto_detach_kernel_driver is set to 1 for dev, the kernel
+ * driver will be re-attached after releasing the interface.
+ *
+ * \param dev_handle a device handle
+ * \param interface_number the bInterfaceNumber of the
+ * previously-claimed interface
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_set_auto_detach_kernel_driver()
+ */
+int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
+ int interface_number)
+{
+ int r;
+
+ usbi_dbg("interface %d", interface_number);
+ if (interface_number >= USB_MAXINTERFACES)
+ return LIBUSB_ERROR_INVALID_PARAM;
+
+ usbi_mutex_lock(&dev_handle->lock);
+ if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
+ r = LIBUSB_ERROR_NOT_FOUND;
+ goto out;
+ }
+
+ r = usbi_backend.release_interface(dev_handle, interface_number);
+ if (r == 0)
+ dev_handle->claimed_interfaces &= ~(1 << interface_number);
+
+out:
+ usbi_mutex_unlock(&dev_handle->lock);
+ return r;
+}
+
+/** \ingroup libusb_dev
+ * Activate an alternate setting for an interface. The interface must have
+ * been previously claimed with libusb_claim_interface().
+ *
+ * You should always use this function rather than formulating your own
+ * SET_INTERFACE control request. This is because the underlying operating
+ * system needs to know when such changes happen.
+ *
+ * This is a blocking function.
+ *
+ * \param dev_handle a device handle
+ * \param interface_number the bInterfaceNumber of the
+ * previously-claimed interface
+ * \param alternate_setting the bAlternateSetting of the alternate
+ * setting to activate
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
+ * requested alternate setting does not exist
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ */
+int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
+ int interface_number, int alternate_setting)
+{
+ usbi_dbg("interface %d altsetting %d",
+ interface_number, alternate_setting);
+ if (interface_number >= USB_MAXINTERFACES)
+ return LIBUSB_ERROR_INVALID_PARAM;
+
+ usbi_mutex_lock(&dev_handle->lock);
+ if (!dev_handle->dev->attached) {
+ usbi_mutex_unlock(&dev_handle->lock);
+ return LIBUSB_ERROR_NO_DEVICE;
+ }
+
+ if (!(dev_handle->claimed_interfaces & (1 << interface_number))) {
+ usbi_mutex_unlock(&dev_handle->lock);
+ return LIBUSB_ERROR_NOT_FOUND;
+ }
+ usbi_mutex_unlock(&dev_handle->lock);
+
+ return usbi_backend.set_interface_altsetting(dev_handle, interface_number,
+ alternate_setting);
+}
+
+/** \ingroup libusb_dev
+ * Clear the halt/stall condition for an endpoint. Endpoints with halt status
+ * are unable to receive or transmit data until the halt condition is stalled.
+ *
+ * You should cancel all pending transfers before attempting to clear the halt
+ * condition.
+ *
+ * This is a blocking function.
+ *
+ * \param dev_handle a device handle
+ * \param endpoint the endpoint to clear halt status
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ */
+int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
+ unsigned char endpoint)
+{
+ usbi_dbg("endpoint %x", endpoint);
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ return usbi_backend.clear_halt(dev_handle, endpoint);
+}
+
+/** \ingroup libusb_dev
+ * Perform a USB port reset to reinitialize a device. The system will attempt
+ * to restore the previous configuration and alternate settings after the
+ * reset has completed.
+ *
+ * If the reset fails, the descriptors change, or the previous state cannot be
+ * restored, the device will appear to be disconnected and reconnected. This
+ * means that the device handle is no longer valid (you should close it) and
+ * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
+ * when this is the case.
+ *
+ * This is a blocking function which usually incurs a noticeable delay.
+ *
+ * \param dev_handle a handle of the device to reset
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
+ * device has been disconnected
+ * \returns another LIBUSB_ERROR code on other failure
+ */
+int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
+{
+ usbi_dbg("");
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ return usbi_backend.reset_device(dev_handle);
+}
+
+/** \ingroup libusb_asyncio
+ * Allocate up to num_streams usb bulk streams on the specified endpoints. This
+ * function takes an array of endpoints rather then a single endpoint because
+ * some protocols require that endpoints are setup with similar stream ids.
+ * All endpoints passed in must belong to the same interface.
+ *
+ * Note this function may return less streams then requested. Also note that the
+ * same number of streams are allocated for each endpoint in the endpoint array.
+ *
+ * Stream id 0 is reserved, and should not be used to communicate with devices.
+ * If libusb_alloc_streams() returns with a value of N, you may use stream ids
+ * 1 to N.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param dev_handle a device handle
+ * \param num_streams number of streams to try to allocate
+ * \param endpoints array of endpoints to allocate streams on
+ * \param num_endpoints length of the endpoints array
+ * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
+ uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
+{
+ usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
+
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ if (usbi_backend.alloc_streams)
+ return usbi_backend.alloc_streams(dev_handle, num_streams, endpoints,
+ num_endpoints);
+ else
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_asyncio
+ * Free usb bulk streams allocated with libusb_alloc_streams().
+ *
+ * Note streams are automatically free-ed when releasing an interface.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param dev_handle a device handle
+ * \param endpoints array of endpoints to free streams on
+ * \param num_endpoints length of the endpoints array
+ * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
+ unsigned char *endpoints, int num_endpoints)
+{
+ usbi_dbg("eps %d", num_endpoints);
+
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ if (usbi_backend.free_streams)
+ return usbi_backend.free_streams(dev_handle, endpoints,
+ num_endpoints);
+ else
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_asyncio
+ * Attempts to allocate a block of persistent DMA memory suitable for transfers
+ * against the given device. If successful, will return a block of memory
+ * that is suitable for use as "buffer" in \ref libusb_transfer against this
+ * device. Using this memory instead of regular memory means that the host
+ * controller can use DMA directly into the buffer to increase performance, and
+ * also that transfers can no longer fail due to kernel memory fragmentation.
+ *
+ * Note that this means you should not modify this memory (or even data on
+ * the same cache lines) when a transfer is in progress, although it is legal
+ * to have several transfers going on within the same memory block.
+ *
+ * Will return NULL on failure. Many systems do not support such zerocopy
+ * and will always return NULL. Memory allocated with this function must be
+ * freed with \ref libusb_dev_mem_free. Specifically, this means that the
+ * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
+ * with this function.
+ *
+ * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
+ *
+ * \param dev_handle a device handle
+ * \param length size of desired data buffer
+ * \returns a pointer to the newly allocated memory, or NULL on failure
+ */
+DEFAULT_VISIBILITY
+unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
+ size_t length)
+{
+ if (!dev_handle->dev->attached)
+ return NULL;
+
+ if (usbi_backend.dev_mem_alloc)
+ return usbi_backend.dev_mem_alloc(dev_handle, length);
+ else
+ return NULL;
+}
+
+/** \ingroup libusb_asyncio
+ * Free device memory allocated with libusb_dev_mem_alloc().
+ *
+ * \param dev_handle a device handle
+ * \param buffer pointer to the previously allocated memory
+ * \param length size of previously allocated memory
+ * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
+ unsigned char *buffer, size_t length)
+{
+ if (usbi_backend.dev_mem_free)
+ return usbi_backend.dev_mem_free(dev_handle, buffer, length);
+ else
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_dev
+ * Determine if a kernel driver is active on an interface. If a kernel driver
+ * is active, you cannot claim the interface, and libusb will be unable to
+ * perform I/O.
+ *
+ * This functionality is not available on Windows.
+ *
+ * \param dev_handle a device handle
+ * \param interface_number the interface to check
+ * \returns 0 if no kernel driver is active
+ * \returns 1 if a kernel driver is active
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
+ * is not available
+ * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_detach_kernel_driver()
+ */
+int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
+ int interface_number)
+{
+ usbi_dbg("interface %d", interface_number);
+
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ if (usbi_backend.kernel_driver_active)
+ return usbi_backend.kernel_driver_active(dev_handle, interface_number);
+ else
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_dev
+ * Detach a kernel driver from an interface. If successful, you will then be
+ * able to claim the interface and perform I/O.
+ *
+ * This functionality is not available on Darwin or Windows.
+ *
+ * Note that libusb itself also talks to the device through a special kernel
+ * driver, if this driver is already attached to the device, this call will
+ * not detach it and return LIBUSB_ERROR_NOT_FOUND.
+ *
+ * \param dev_handle a device handle
+ * \param interface_number the interface to detach the driver from
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
+ * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
+ * is not available
+ * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_kernel_driver_active()
+ */
+int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
+ int interface_number)
+{
+ usbi_dbg("interface %d", interface_number);
+
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ if (usbi_backend.detach_kernel_driver)
+ return usbi_backend.detach_kernel_driver(dev_handle, interface_number);
+ else
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_dev
+ * Re-attach an interface's kernel driver, which was previously detached
+ * using libusb_detach_kernel_driver(). This call is only effective on
+ * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
+ *
+ * This functionality is not available on Darwin or Windows.
+ *
+ * \param dev_handle a device handle
+ * \param interface_number the interface to attach the driver from
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
+ * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
+ * is not available
+ * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
+ * interface is claimed by a program or driver
+ * \returns another LIBUSB_ERROR code on other failure
+ * \see libusb_kernel_driver_active()
+ */
+int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
+ int interface_number)
+{
+ usbi_dbg("interface %d", interface_number);
+
+ if (!dev_handle->dev->attached)
+ return LIBUSB_ERROR_NO_DEVICE;
+
+ if (usbi_backend.attach_kernel_driver)
+ return usbi_backend.attach_kernel_driver(dev_handle, interface_number);
+ else
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+}
+
+/** \ingroup libusb_dev
+ * Enable/disable libusb's automatic kernel driver detachment. When this is
+ * enabled libusb will automatically detach the kernel driver on an interface
+ * when claiming the interface, and attach it when releasing the interface.
+ *
+ * Automatic kernel driver detachment is disabled on newly opened device
+ * handles by default.
+ *
+ * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
+ * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
+ * continue as if this function was never called.
+ *
+ * \param dev_handle a device handle
+ * \param enable whether to enable or disable auto kernel driver detachment
+ *
+ * \returns LIBUSB_SUCCESS on success
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
+ * is not available
+ * \see libusb_claim_interface()
+ * \see libusb_release_interface()
+ * \see libusb_set_configuration()
+ */
+int API_EXPORTED libusb_set_auto_detach_kernel_driver(
+ libusb_device_handle *dev_handle, int enable)
+{
+ if (!(usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+
+ dev_handle->auto_detach_kernel_driver = enable;
+ return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_lib
+ * \deprecated Use libusb_set_option() instead using the
+ * \ref LIBUSB_OPTION_LOG_LEVEL option.
+ */
+void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
+{
+#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
+ USBI_GET_CONTEXT(ctx);
+ if (!ctx->debug_fixed) {
+ level = CLAMP(level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
+ ctx->debug = (enum libusb_log_level)level;
+ }
+#else
+ UNUSED(ctx);
+ UNUSED(level);
+#endif
+}
+
+/** \ingroup libusb_lib
+ * Set an option in the library.
+ *
+ * Use this function to configure a specific option within the library.
+ *
+ * Some options require one or more arguments to be provided. Consult each
+ * option's documentation for specific requirements.
+ *
+ * Since version 1.0.22, \ref LIBUSB_API_VERSION >= 0x01000106
+ *
+ * \param ctx context on which to operate
+ * \param option which option to set
+ * \param ... any required arguments for the specified option
+ *
+ * \returns LIBUSB_SUCCESS on success
+ * \returns LIBUSB_ERROR_INVALID_PARAM if the option or arguments are invalid
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED if the option is valid but not supported
+ * on this platform
+ */
+int API_EXPORTED libusb_set_option(libusb_context *ctx,
+ enum libusb_option option, ...)
+{
+ int arg, r = LIBUSB_SUCCESS;
+ va_list ap;
+
+ USBI_GET_CONTEXT(ctx);
+
+ va_start(ap, option);
+ switch (option) {
+ case LIBUSB_OPTION_LOG_LEVEL:
+ arg = va_arg(ap, int);
+ if (arg < LIBUSB_LOG_LEVEL_NONE || arg > LIBUSB_LOG_LEVEL_DEBUG) {
+ r = LIBUSB_ERROR_INVALID_PARAM;
+ break;
+ }
+#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
+ if (!ctx->debug_fixed)
+ ctx->debug = (enum libusb_log_level)arg;
+#endif
+ break;
+
+ /* Handle all backend-specific options here */
+ case LIBUSB_OPTION_USE_USBDK:
+ if (usbi_backend.set_option)
+ r = usbi_backend.set_option(ctx, option, ap);
+ else
+ r = LIBUSB_ERROR_NOT_SUPPORTED;
+ break;
+
+ default:
+ r = LIBUSB_ERROR_INVALID_PARAM;
+ }
+ va_end(ap);
+
+ return r;
+}
+
+#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
+/* returns the log level as defined in the LIBUSB_DEBUG environment variable.
+ * if LIBUSB_DEBUG is not present or not a number, returns LIBUSB_LOG_LEVEL_NONE.
+ * value is clamped to ensure it is within the valid range of possibilities.
+ */
+static enum libusb_log_level get_env_debug_level(void)
+{
+ const char *dbg = getenv("LIBUSB_DEBUG");
+ enum libusb_log_level level;
+ if (dbg) {
+ int dbg_level = atoi(dbg);
+ dbg_level = CLAMP(dbg_level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
+ level = (enum libusb_log_level)dbg_level;
+ } else {
+ level = LIBUSB_LOG_LEVEL_NONE;
+ }
+ return level;
+}
+#endif
+
+/** \ingroup libusb_lib
+ * Initialize libusb. This function must be called before calling any other
+ * libusb function.
+ *
+ * If you do not provide an output location for a context pointer, a default
+ * context will be created. If there was already a default context, it will
+ * be reused (and nothing will be initialized/reinitialized).
+ *
+ * \param context Optional output location for context pointer.
+ * Only valid on return code 0.
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
+ * \see libusb_contexts
+ */
+int API_EXPORTED libusb_init(libusb_context **context)
+{
+ struct libusb_device *dev, *next;
+ size_t priv_size = usbi_backend.context_priv_size;
+ struct libusb_context *ctx;
+ static int first_init = 1;
+ int r = 0;
+
+ usbi_mutex_static_lock(&default_context_lock);
+
+ if (!timestamp_origin.tv_sec) {
+ usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, ×tamp_origin);
+ }
+
+ if (!context && usbi_default_context) {
+ usbi_dbg("reusing default context");
+ default_context_refcnt++;
+ usbi_mutex_static_unlock(&default_context_lock);
+ return 0;
+ }
+
+ ctx = calloc(1, sizeof(*ctx) + priv_size);
+ if (!ctx) {
+ r = LIBUSB_ERROR_NO_MEM;
+ goto err_unlock;
+ }
+
+#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
+ ctx->debug = get_env_debug_level();
+ if (ctx->debug != LIBUSB_LOG_LEVEL_NONE)
+ ctx->debug_fixed = 1;
+#endif
+
+ /* default context should be initialized before calling usbi_dbg */
+ if (!usbi_default_context) {
+ usbi_default_context = ctx;
+ default_context_refcnt++;
+ usbi_dbg("created default context");
+ }
+
+ usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
+ libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
+
+ usbi_mutex_init(&ctx->usb_devs_lock);
+ usbi_mutex_init(&ctx->open_devs_lock);
+ usbi_mutex_init(&ctx->hotplug_cbs_lock);
+ list_init(&ctx->usb_devs);
+ list_init(&ctx->open_devs);
+ list_init(&ctx->hotplug_cbs);
+ ctx->next_hotplug_cb_handle = 1;
+
+ usbi_mutex_static_lock(&active_contexts_lock);
+ if (first_init) {
+ first_init = 0;
+ list_init (&active_contexts_list);
+ }
+ list_add (&ctx->list, &active_contexts_list);
+ usbi_mutex_static_unlock(&active_contexts_lock);
+
+ if (usbi_backend.init) {
+ r = usbi_backend.init(ctx);
+ if (r)
+ goto err_free_ctx;
+ }
+
+ r = usbi_io_init(ctx);
+ if (r < 0)
+ goto err_backend_exit;
+
+ usbi_mutex_static_unlock(&default_context_lock);
+
+ if (context)
+ *context = ctx;
+
+ return 0;
+
+err_backend_exit:
+ if (usbi_backend.exit)
+ usbi_backend.exit(ctx);
+err_free_ctx:
+ if (ctx == usbi_default_context) {
+ usbi_default_context = NULL;
+ default_context_refcnt--;
+ }
+
+ usbi_mutex_static_lock(&active_contexts_lock);
+ list_del (&ctx->list);
+ usbi_mutex_static_unlock(&active_contexts_lock);
+
+ usbi_mutex_lock(&ctx->usb_devs_lock);
+ list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
+ list_del(&dev->list);
+ libusb_unref_device(dev);
+ }
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
+
+ usbi_mutex_destroy(&ctx->open_devs_lock);
+ usbi_mutex_destroy(&ctx->usb_devs_lock);
+ usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
+
+ free(ctx);
+err_unlock:
+ usbi_mutex_static_unlock(&default_context_lock);
+ return r;
+}
+
+/** \ingroup libusb_lib
+ * Deinitialize libusb. Should be called after closing all open devices and
+ * before your application terminates.
+ * \param ctx the context to deinitialize, or NULL for the default context
+ */
+void API_EXPORTED libusb_exit(struct libusb_context *ctx)
+{
+ struct libusb_device *dev, *next;
+ struct timeval tv = { 0, 0 };
+
+ usbi_dbg("");
+ USBI_GET_CONTEXT(ctx);
+
+ /* if working with default context, only actually do the deinitialization
+ * if we're the last user */
+ usbi_mutex_static_lock(&default_context_lock);
+ if (ctx == usbi_default_context) {
+ if (--default_context_refcnt > 0) {
+ usbi_dbg("not destroying default context");
+ usbi_mutex_static_unlock(&default_context_lock);
+ return;
+ }
+ usbi_dbg("destroying default context");
+ usbi_default_context = NULL;
+ }
+ usbi_mutex_static_unlock(&default_context_lock);
+
+ usbi_mutex_static_lock(&active_contexts_lock);
+ list_del (&ctx->list);
+ usbi_mutex_static_unlock(&active_contexts_lock);
+
+ if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ usbi_hotplug_deregister(ctx, 1);
+
+ /*
+ * Ensure any pending unplug events are read from the hotplug
+ * pipe. The usb_device-s hold in the events are no longer part
+ * of usb_devs, but the events still hold a reference!
+ *
+ * Note we don't do this if the application has left devices
+ * open (which implies a buggy app) to avoid packet completion
+ * handlers running when the app does not expect them to run.
+ */
+ if (list_empty(&ctx->open_devs))
+ libusb_handle_events_timeout(ctx, &tv);
+
+ usbi_mutex_lock(&ctx->usb_devs_lock);
+ list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
+ list_del(&dev->list);
+ libusb_unref_device(dev);
+ }
+ usbi_mutex_unlock(&ctx->usb_devs_lock);
+ }
+
+ /* a few sanity checks. don't bother with locking because unless
+ * there is an application bug, nobody will be accessing these. */
+ if (!list_empty(&ctx->usb_devs))
+ usbi_warn(ctx, "some libusb_devices were leaked");
+ if (!list_empty(&ctx->open_devs))
+ usbi_warn(ctx, "application left some devices open");
+
+ usbi_io_exit(ctx);
+ if (usbi_backend.exit)
+ usbi_backend.exit(ctx);
+
+ usbi_mutex_destroy(&ctx->open_devs_lock);
+ usbi_mutex_destroy(&ctx->usb_devs_lock);
+ usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
+ free(ctx);
+}
+
+/** \ingroup libusb_misc
+ * Check at runtime if the loaded library has a given capability.
+ * This call should be performed after \ref libusb_init(), to ensure the
+ * backend has updated its capability set.
+ *
+ * \param capability the \ref libusb_capability to check for
+ * \returns nonzero if the running library has the capability, 0 otherwise
+ */
+int API_EXPORTED libusb_has_capability(uint32_t capability)
+{
+ switch (capability) {
+ case LIBUSB_CAP_HAS_CAPABILITY:
+ return 1;
+ case LIBUSB_CAP_HAS_HOTPLUG:
+ return !(usbi_backend.get_device_list);
+ case LIBUSB_CAP_HAS_HID_ACCESS:
+ return (usbi_backend.caps & USBI_CAP_HAS_HID_ACCESS);
+ case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
+ return (usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
+ }
+ return 0;
+}
+
+#ifdef ENABLE_LOGGING
+
+/* this is defined in libusbi.h if needed */
+#ifdef LIBUSB_PRINTF_WIN32
+/*
+ * Prior to VS2015, Microsoft did not provide the snprintf() function and
+ * provided a vsnprintf() that did not guarantee NULL-terminated output.
+ * Microsoft did provide a _snprintf() function, but again it did not
+ * guarantee NULL-terminated output.
+ *
+ * The below implementations guarantee NULL-terminated output and are
+ * C99 compliant.
+ */
+
+int usbi_snprintf(char *str, size_t size, const char *format, ...)
+{
+ va_list ap;
+ int ret;
+
+ va_start(ap, format);
+ ret = usbi_vsnprintf(str, size, format, ap);
+ va_end(ap);
+
+ return ret;
+}
+
+int usbi_vsnprintf(char *str, size_t size, const char *format, va_list ap)
+{
+ int ret;
+
+ ret = _vsnprintf(str, size, format, ap);
+ if (ret < 0 || ret == (int)size) {
+ /* Output is truncated, ensure buffer is NULL-terminated and
+ * determine how many characters would have been written. */
+ str[size - 1] = '\0';
+ if (ret < 0)
+ ret = _vsnprintf(NULL, 0, format, ap);
+ }
+
+ return ret;
+}
+#endif /* LIBUSB_PRINTF_WIN32 */
+
+static void usbi_log_str(enum libusb_log_level level, const char *str)
+{
+#if defined(USE_SYSTEM_LOGGING_FACILITY)
+#if defined(OS_WINDOWS)
+ OutputDebugString(str);
+#elif defined(OS_WINCE)
+ /* Windows CE only supports the Unicode version of OutputDebugString. */
+ WCHAR wbuf[USBI_MAX_LOG_LEN];
+ MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
+ OutputDebugStringW(wbuf);
+#elif defined(__ANDROID__)
+ int priority = ANDROID_LOG_UNKNOWN;
+ switch (level) {
+ case LIBUSB_LOG_LEVEL_NONE: return;
+ case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
+ case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
+ case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
+ case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
+ }
+ __android_log_write(priority, "libusb", str);
+#elif defined(HAVE_SYSLOG_FUNC)
+ int syslog_level = LOG_INFO;
+ switch (level) {
+ case LIBUSB_LOG_LEVEL_NONE: return;
+ case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
+ case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
+ case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
+ case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
+ }
+ syslog(syslog_level, "%s", str);
+#else /* All of gcc, Clang, XCode seem to use #warning */
+#warning System logging is not supported on this platform. Logging to stderr will be used instead.
+ fputs(str, stderr);
+#endif
+#else
+ fputs(str, stderr);
+#endif /* USE_SYSTEM_LOGGING_FACILITY */
+ UNUSED(level);
+}
+
+void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
+ const char *function, const char *format, va_list args)
+{
+ const char *prefix;
+ char buf[USBI_MAX_LOG_LEN];
+ struct timespec now;
+ int global_debug, header_len, text_len;
+ static int has_debug_header_been_displayed = 0;
+
+#ifdef ENABLE_DEBUG_LOGGING
+ global_debug = 1;
+ UNUSED(ctx);
+#else
+ enum libusb_log_level ctx_level = LIBUSB_LOG_LEVEL_NONE;
+
+ USBI_GET_CONTEXT(ctx);
+ if (ctx)
+ ctx_level = ctx->debug;
+ else
+ ctx_level = get_env_debug_level();
+
+ if (ctx_level == LIBUSB_LOG_LEVEL_NONE)
+ return;
+ if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
+ return;
+ if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
+ return;
+ if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
+ return;
+
+ global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
+#endif
+
+ usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &now);
+ if ((global_debug) && (!has_debug_header_been_displayed)) {
+ has_debug_header_been_displayed = 1;
+ usbi_log_str(LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] " USBI_LOG_LINE_END);
+ usbi_log_str(LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
+ }
+ if (now.tv_nsec < timestamp_origin.tv_nsec) {
+ now.tv_sec--;
+ now.tv_nsec += 1000000000L;
+ }
+ now.tv_sec -= timestamp_origin.tv_sec;
+ now.tv_nsec -= timestamp_origin.tv_nsec;
+
+ switch (level) {
+ case LIBUSB_LOG_LEVEL_NONE:
+ return;
+ case LIBUSB_LOG_LEVEL_ERROR:
+ prefix = "error";
+ break;
+ case LIBUSB_LOG_LEVEL_WARNING:
+ prefix = "warning";
+ break;
+ case LIBUSB_LOG_LEVEL_INFO:
+ prefix = "info";
+ break;
+ case LIBUSB_LOG_LEVEL_DEBUG:
+ prefix = "debug";
+ break;
+ default:
+ prefix = "unknown";
+ break;
+ }
+
+ if (global_debug) {
+ header_len = snprintf(buf, sizeof(buf),
+ "[%2d.%06d] [%08x] libusb: %s [%s] ",
+ (int)now.tv_sec, (int)(now.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
+ } else {
+ header_len = snprintf(buf, sizeof(buf),
+ "libusb: %s [%s] ", prefix, function);
+ }
+
+ if (header_len < 0 || header_len >= (int)sizeof(buf)) {
+ /* Somehow snprintf failed to write to the buffer,
+ * remove the header so something useful is output. */
+ header_len = 0;
+ }
+ /* Make sure buffer is NUL terminated */
+ buf[header_len] = '\0';
+ text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
+ format, args);
+ if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
+ /* Truncated log output. On some platforms a -1 return value means
+ * that the output was truncated. */
+ text_len = sizeof(buf) - header_len;
+ }
+ if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
+ /* Need to truncate the text slightly to fit on the terminator. */
+ text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
+ }
+ strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
+
+ usbi_log_str(level, buf);
+}
+
+void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
+ const char *function, const char *format, ...)
+{
+ va_list args;
+
+ va_start (args, format);
+ usbi_log_v(ctx, level, function, format, args);
+ va_end (args);
+}
+
+#endif /* ENABLE_LOGGING */
+
+/** \ingroup libusb_misc
+ * Returns a constant NULL-terminated string with the ASCII name of a libusb
+ * error or transfer status code. The caller must not free() the returned
+ * string.
+ *
+ * \param error_code The \ref libusb_error or libusb_transfer_status code to
+ * return the name of.
+ * \returns The error name, or the string **UNKNOWN** if the value of
+ * error_code is not a known error / status code.
+ */
+DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
+{
+ switch (error_code) {
+ case LIBUSB_ERROR_IO:
+ return "LIBUSB_ERROR_IO";
+ case LIBUSB_ERROR_INVALID_PARAM:
+ return "LIBUSB_ERROR_INVALID_PARAM";
+ case LIBUSB_ERROR_ACCESS:
+ return "LIBUSB_ERROR_ACCESS";
+ case LIBUSB_ERROR_NO_DEVICE:
+ return "LIBUSB_ERROR_NO_DEVICE";
+ case LIBUSB_ERROR_NOT_FOUND:
+ return "LIBUSB_ERROR_NOT_FOUND";
+ case LIBUSB_ERROR_BUSY:
+ return "LIBUSB_ERROR_BUSY";
+ case LIBUSB_ERROR_TIMEOUT:
+ return "LIBUSB_ERROR_TIMEOUT";
+ case LIBUSB_ERROR_OVERFLOW:
+ return "LIBUSB_ERROR_OVERFLOW";
+ case LIBUSB_ERROR_PIPE:
+ return "LIBUSB_ERROR_PIPE";
+ case LIBUSB_ERROR_INTERRUPTED:
+ return "LIBUSB_ERROR_INTERRUPTED";
+ case LIBUSB_ERROR_NO_MEM:
+ return "LIBUSB_ERROR_NO_MEM";
+ case LIBUSB_ERROR_NOT_SUPPORTED:
+ return "LIBUSB_ERROR_NOT_SUPPORTED";
+ case LIBUSB_ERROR_OTHER:
+ return "LIBUSB_ERROR_OTHER";
+
+ case LIBUSB_TRANSFER_ERROR:
+ return "LIBUSB_TRANSFER_ERROR";
+ case LIBUSB_TRANSFER_TIMED_OUT:
+ return "LIBUSB_TRANSFER_TIMED_OUT";
+ case LIBUSB_TRANSFER_CANCELLED:
+ return "LIBUSB_TRANSFER_CANCELLED";
+ case LIBUSB_TRANSFER_STALL:
+ return "LIBUSB_TRANSFER_STALL";
+ case LIBUSB_TRANSFER_NO_DEVICE:
+ return "LIBUSB_TRANSFER_NO_DEVICE";
+ case LIBUSB_TRANSFER_OVERFLOW:
+ return "LIBUSB_TRANSFER_OVERFLOW";
+
+ case 0:
+ return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
+ default:
+ return "**UNKNOWN**";
+ }
+}
+
+/** \ingroup libusb_misc
+ * Returns a pointer to const struct libusb_version with the version
+ * (major, minor, micro, nano and rc) of the running library.
+ */
+DEFAULT_VISIBILITY
+const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
+{
+ return &libusb_version_internal;
+}
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/descriptor.c b/vendor/github.com/karalabe/usb/libusb/libusb/descriptor.c
new file mode 100644
index 000000000..74d6de557
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/descriptor.c
@@ -0,0 +1,1192 @@
+/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
+/*
+ * USB descriptor handling functions for libusb
+ * Copyright © 2007 Daniel Drake
+ * Copyright © 2001 Johannes Erdfelt
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include
+
+#include
+#include
+#include
+#include
+
+#include "libusbi.h"
+
+#define DESC_HEADER_LENGTH 2
+#define DEVICE_DESC_LENGTH 18
+#define CONFIG_DESC_LENGTH 9
+#define INTERFACE_DESC_LENGTH 9
+#define ENDPOINT_DESC_LENGTH 7
+#define ENDPOINT_AUDIO_DESC_LENGTH 9
+
+/** @defgroup libusb_desc USB descriptors
+ * This page details how to examine the various standard USB descriptors
+ * for detected devices
+ */
+
+/* set host_endian if the w values are already in host endian format,
+ * as opposed to bus endian. */
+int usbi_parse_descriptor(const unsigned char *source, const char *descriptor,
+ void *dest, int host_endian)
+{
+ const unsigned char *sp = source;
+ unsigned char *dp = dest;
+ uint16_t w;
+ const char *cp;
+ uint32_t d;
+
+ for (cp = descriptor; *cp; cp++) {
+ switch (*cp) {
+ case 'b': /* 8-bit byte */
+ *dp++ = *sp++;
+ break;
+ case 'w': /* 16-bit word, convert from little endian to CPU */
+ dp += ((uintptr_t)dp & 1); /* Align to word boundary */
+
+ if (host_endian) {
+ memcpy(dp, sp, 2);
+ } else {
+ w = (sp[1] << 8) | sp[0];
+ *((uint16_t *)dp) = w;
+ }
+ sp += 2;
+ dp += 2;
+ break;
+ case 'd': /* 32-bit word, convert from little endian to CPU */
+ dp += ((uintptr_t)dp & 1); /* Align to word boundary */
+
+ if (host_endian) {
+ memcpy(dp, sp, 4);
+ } else {
+ d = (sp[3] << 24) | (sp[2] << 16) |
+ (sp[1] << 8) | sp[0];
+ *((uint32_t *)dp) = d;
+ }
+ sp += 4;
+ dp += 4;
+ break;
+ case 'u': /* 16 byte UUID */
+ memcpy(dp, sp, 16);
+ sp += 16;
+ dp += 16;
+ break;
+ }
+ }
+
+ return (int) (sp - source);
+}
+
+static void clear_endpoint(struct libusb_endpoint_descriptor *endpoint)
+{
+ free((void *) endpoint->extra);
+}
+
+static int parse_endpoint(struct libusb_context *ctx,
+ struct libusb_endpoint_descriptor *endpoint, unsigned char *buffer,
+ int size, int host_endian)
+{
+ struct usb_descriptor_header header;
+ unsigned char *extra;
+ unsigned char *begin;
+ int parsed = 0;
+ int len;
+
+ if (size < DESC_HEADER_LENGTH) {
+ usbi_err(ctx, "short endpoint descriptor read %d/%d",
+ size, DESC_HEADER_LENGTH);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usbi_parse_descriptor(buffer, "bb", &header, 0);
+ if (header.bDescriptorType != LIBUSB_DT_ENDPOINT) {
+ usbi_err(ctx, "unexpected descriptor %x (expected %x)",
+ header.bDescriptorType, LIBUSB_DT_ENDPOINT);
+ return parsed;
+ }
+ if (header.bLength > size) {
+ usbi_warn(ctx, "short endpoint descriptor read %d/%d",
+ size, header.bLength);
+ return parsed;
+ }
+ if (header.bLength >= ENDPOINT_AUDIO_DESC_LENGTH)
+ usbi_parse_descriptor(buffer, "bbbbwbbb", endpoint, host_endian);
+ else if (header.bLength >= ENDPOINT_DESC_LENGTH)
+ usbi_parse_descriptor(buffer, "bbbbwb", endpoint, host_endian);
+ else {
+ usbi_err(ctx, "invalid endpoint bLength (%d)", header.bLength);
+ return LIBUSB_ERROR_IO;
+ }
+
+ buffer += header.bLength;
+ size -= header.bLength;
+ parsed += header.bLength;
+
+ /* Skip over the rest of the Class Specific or Vendor Specific */
+ /* descriptors */
+ begin = buffer;
+ while (size >= DESC_HEADER_LENGTH) {
+ usbi_parse_descriptor(buffer, "bb", &header, 0);
+ if (header.bLength < DESC_HEADER_LENGTH) {
+ usbi_err(ctx, "invalid extra ep desc len (%d)",
+ header.bLength);
+ return LIBUSB_ERROR_IO;
+ } else if (header.bLength > size) {
+ usbi_warn(ctx, "short extra ep desc read %d/%d",
+ size, header.bLength);
+ return parsed;
+ }
+
+ /* If we find another "proper" descriptor then we're done */
+ if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
+ (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
+ (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
+ (header.bDescriptorType == LIBUSB_DT_DEVICE))
+ break;
+
+ usbi_dbg("skipping descriptor %x", header.bDescriptorType);
+ buffer += header.bLength;
+ size -= header.bLength;
+ parsed += header.bLength;
+ }
+
+ /* Copy any unknown descriptors into a storage area for drivers */
+ /* to later parse */
+ len = (int)(buffer - begin);
+ if (!len) {
+ endpoint->extra = NULL;
+ endpoint->extra_length = 0;
+ return parsed;
+ }
+
+ extra = malloc(len);
+ endpoint->extra = extra;
+ if (!extra) {
+ endpoint->extra_length = 0;
+ return LIBUSB_ERROR_NO_MEM;
+ }
+
+ memcpy(extra, begin, len);
+ endpoint->extra_length = len;
+
+ return parsed;
+}
+
+static void clear_interface(struct libusb_interface *usb_interface)
+{
+ int i;
+ int j;
+
+ if (usb_interface->altsetting) {
+ for (i = 0; i < usb_interface->num_altsetting; i++) {
+ struct libusb_interface_descriptor *ifp =
+ (struct libusb_interface_descriptor *)
+ usb_interface->altsetting + i;
+ free((void *) ifp->extra);
+ if (ifp->endpoint) {
+ for (j = 0; j < ifp->bNumEndpoints; j++)
+ clear_endpoint((struct libusb_endpoint_descriptor *)
+ ifp->endpoint + j);
+ }
+ free((void *) ifp->endpoint);
+ }
+ }
+ free((void *) usb_interface->altsetting);
+ usb_interface->altsetting = NULL;
+}
+
+static int parse_interface(libusb_context *ctx,
+ struct libusb_interface *usb_interface, unsigned char *buffer, int size,
+ int host_endian)
+{
+ int i;
+ int len;
+ int r;
+ int parsed = 0;
+ int interface_number = -1;
+ struct usb_descriptor_header header;
+ struct libusb_interface_descriptor *ifp;
+ unsigned char *begin;
+
+ usb_interface->num_altsetting = 0;
+
+ while (size >= INTERFACE_DESC_LENGTH) {
+ struct libusb_interface_descriptor *altsetting =
+ (struct libusb_interface_descriptor *) usb_interface->altsetting;
+ altsetting = usbi_reallocf(altsetting,
+ sizeof(struct libusb_interface_descriptor) *
+ (usb_interface->num_altsetting + 1));
+ if (!altsetting) {
+ r = LIBUSB_ERROR_NO_MEM;
+ goto err;
+ }
+ usb_interface->altsetting = altsetting;
+
+ ifp = altsetting + usb_interface->num_altsetting;
+ usbi_parse_descriptor(buffer, "bbbbbbbbb", ifp, 0);
+ if (ifp->bDescriptorType != LIBUSB_DT_INTERFACE) {
+ usbi_err(ctx, "unexpected descriptor %x (expected %x)",
+ ifp->bDescriptorType, LIBUSB_DT_INTERFACE);
+ return parsed;
+ }
+ if (ifp->bLength < INTERFACE_DESC_LENGTH) {
+ usbi_err(ctx, "invalid interface bLength (%d)",
+ ifp->bLength);
+ r = LIBUSB_ERROR_IO;
+ goto err;
+ }
+ if (ifp->bLength > size) {
+ usbi_warn(ctx, "short intf descriptor read %d/%d",
+ size, ifp->bLength);
+ return parsed;
+ }
+ if (ifp->bNumEndpoints > USB_MAXENDPOINTS) {
+ usbi_err(ctx, "too many endpoints (%d)", ifp->bNumEndpoints);
+ r = LIBUSB_ERROR_IO;
+ goto err;
+ }
+
+ usb_interface->num_altsetting++;
+ ifp->extra = NULL;
+ ifp->extra_length = 0;
+ ifp->endpoint = NULL;
+
+ if (interface_number == -1)
+ interface_number = ifp->bInterfaceNumber;
+
+ /* Skip over the interface */
+ buffer += ifp->bLength;
+ parsed += ifp->bLength;
+ size -= ifp->bLength;
+
+ begin = buffer;
+
+ /* Skip over any interface, class or vendor descriptors */
+ while (size >= DESC_HEADER_LENGTH) {
+ usbi_parse_descriptor(buffer, "bb", &header, 0);
+ if (header.bLength < DESC_HEADER_LENGTH) {
+ usbi_err(ctx,
+ "invalid extra intf desc len (%d)",
+ header.bLength);
+ r = LIBUSB_ERROR_IO;
+ goto err;
+ } else if (header.bLength > size) {
+ usbi_warn(ctx,
+ "short extra intf desc read %d/%d",
+ size, header.bLength);
+ return parsed;
+ }
+
+ /* If we find another "proper" descriptor then we're done */
+ if ((header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
+ (header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
+ (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
+ (header.bDescriptorType == LIBUSB_DT_DEVICE))
+ break;
+
+ buffer += header.bLength;
+ parsed += header.bLength;
+ size -= header.bLength;
+ }
+
+ /* Copy any unknown descriptors into a storage area for */
+ /* drivers to later parse */
+ len = (int)(buffer - begin);
+ if (len) {
+ ifp->extra = malloc(len);
+ if (!ifp->extra) {
+ r = LIBUSB_ERROR_NO_MEM;
+ goto err;
+ }
+ memcpy((unsigned char *) ifp->extra, begin, len);
+ ifp->extra_length = len;
+ }
+
+ if (ifp->bNumEndpoints > 0) {
+ struct libusb_endpoint_descriptor *endpoint;
+ endpoint = calloc(ifp->bNumEndpoints, sizeof(struct libusb_endpoint_descriptor));
+ ifp->endpoint = endpoint;
+ if (!endpoint) {
+ r = LIBUSB_ERROR_NO_MEM;
+ goto err;
+ }
+
+ for (i = 0; i < ifp->bNumEndpoints; i++) {
+ r = parse_endpoint(ctx, endpoint + i, buffer, size,
+ host_endian);
+ if (r < 0)
+ goto err;
+ if (r == 0) {
+ ifp->bNumEndpoints = (uint8_t)i;
+ break;
+ }
+
+ buffer += r;
+ parsed += r;
+ size -= r;
+ }
+ }
+
+ /* We check to see if it's an alternate to this one */
+ ifp = (struct libusb_interface_descriptor *) buffer;
+ if (size < LIBUSB_DT_INTERFACE_SIZE ||
+ ifp->bDescriptorType != LIBUSB_DT_INTERFACE ||
+ ifp->bInterfaceNumber != interface_number)
+ return parsed;
+ }
+
+ return parsed;
+err:
+ clear_interface(usb_interface);
+ return r;
+}
+
+static void clear_configuration(struct libusb_config_descriptor *config)
+{
+ int i;
+ if (config->interface) {
+ for (i = 0; i < config->bNumInterfaces; i++)
+ clear_interface((struct libusb_interface *)
+ config->interface + i);
+ }
+ free((void *) config->interface);
+ free((void *) config->extra);
+}
+
+static int parse_configuration(struct libusb_context *ctx,
+ struct libusb_config_descriptor *config, unsigned char *buffer,
+ int size, int host_endian)
+{
+ int i;
+ int r;
+ struct usb_descriptor_header header;
+ struct libusb_interface *usb_interface;
+
+ if (size < LIBUSB_DT_CONFIG_SIZE) {
+ usbi_err(ctx, "short config descriptor read %d/%d",
+ size, LIBUSB_DT_CONFIG_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usbi_parse_descriptor(buffer, "bbwbbbbb", config, host_endian);
+ if (config->bDescriptorType != LIBUSB_DT_CONFIG) {
+ usbi_err(ctx, "unexpected descriptor %x (expected %x)",
+ config->bDescriptorType, LIBUSB_DT_CONFIG);
+ return LIBUSB_ERROR_IO;
+ }
+ if (config->bLength < LIBUSB_DT_CONFIG_SIZE) {
+ usbi_err(ctx, "invalid config bLength (%d)", config->bLength);
+ return LIBUSB_ERROR_IO;
+ }
+ if (config->bLength > size) {
+ usbi_err(ctx, "short config descriptor read %d/%d",
+ size, config->bLength);
+ return LIBUSB_ERROR_IO;
+ }
+ if (config->bNumInterfaces > USB_MAXINTERFACES) {
+ usbi_err(ctx, "too many interfaces (%d)", config->bNumInterfaces);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usb_interface = calloc(config->bNumInterfaces, sizeof(struct libusb_interface));
+ config->interface = usb_interface;
+ if (!usb_interface)
+ return LIBUSB_ERROR_NO_MEM;
+
+ buffer += config->bLength;
+ size -= config->bLength;
+
+ config->extra = NULL;
+ config->extra_length = 0;
+
+ for (i = 0; i < config->bNumInterfaces; i++) {
+ int len;
+ unsigned char *begin;
+
+ /* Skip over the rest of the Class Specific or Vendor */
+ /* Specific descriptors */
+ begin = buffer;
+ while (size >= DESC_HEADER_LENGTH) {
+ usbi_parse_descriptor(buffer, "bb", &header, 0);
+
+ if (header.bLength < DESC_HEADER_LENGTH) {
+ usbi_err(ctx,
+ "invalid extra config desc len (%d)",
+ header.bLength);
+ r = LIBUSB_ERROR_IO;
+ goto err;
+ } else if (header.bLength > size) {
+ usbi_warn(ctx,
+ "short extra config desc read %d/%d",
+ size, header.bLength);
+ config->bNumInterfaces = (uint8_t)i;
+ return size;
+ }
+
+ /* If we find another "proper" descriptor then we're done */
+ if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) ||
+ (header.bDescriptorType == LIBUSB_DT_INTERFACE) ||
+ (header.bDescriptorType == LIBUSB_DT_CONFIG) ||
+ (header.bDescriptorType == LIBUSB_DT_DEVICE))
+ break;
+
+ usbi_dbg("skipping descriptor 0x%x", header.bDescriptorType);
+ buffer += header.bLength;
+ size -= header.bLength;
+ }
+
+ /* Copy any unknown descriptors into a storage area for */
+ /* drivers to later parse */
+ len = (int)(buffer - begin);
+ if (len) {
+ /* FIXME: We should realloc and append here */
+ if (!config->extra_length) {
+ config->extra = malloc(len);
+ if (!config->extra) {
+ r = LIBUSB_ERROR_NO_MEM;
+ goto err;
+ }
+
+ memcpy((unsigned char *) config->extra, begin, len);
+ config->extra_length = len;
+ }
+ }
+
+ r = parse_interface(ctx, usb_interface + i, buffer, size, host_endian);
+ if (r < 0)
+ goto err;
+ if (r == 0) {
+ config->bNumInterfaces = (uint8_t)i;
+ break;
+ }
+
+ buffer += r;
+ size -= r;
+ }
+
+ return size;
+
+err:
+ clear_configuration(config);
+ return r;
+}
+
+static int raw_desc_to_config(struct libusb_context *ctx,
+ unsigned char *buf, int size, int host_endian,
+ struct libusb_config_descriptor **config)
+{
+ struct libusb_config_descriptor *_config = malloc(sizeof(*_config));
+ int r;
+
+ if (!_config)
+ return LIBUSB_ERROR_NO_MEM;
+
+ r = parse_configuration(ctx, _config, buf, size, host_endian);
+ if (r < 0) {
+ usbi_err(ctx, "parse_configuration failed with error %d", r);
+ free(_config);
+ return r;
+ } else if (r > 0) {
+ usbi_warn(ctx, "still %d bytes of descriptor data left", r);
+ }
+
+ *config = _config;
+ return LIBUSB_SUCCESS;
+}
+
+int usbi_device_cache_descriptor(libusb_device *dev)
+{
+ int r, host_endian = 0;
+
+ r = usbi_backend.get_device_descriptor(dev, (unsigned char *) &dev->device_descriptor,
+ &host_endian);
+ if (r < 0)
+ return r;
+
+ if (!host_endian) {
+ dev->device_descriptor.bcdUSB = libusb_le16_to_cpu(dev->device_descriptor.bcdUSB);
+ dev->device_descriptor.idVendor = libusb_le16_to_cpu(dev->device_descriptor.idVendor);
+ dev->device_descriptor.idProduct = libusb_le16_to_cpu(dev->device_descriptor.idProduct);
+ dev->device_descriptor.bcdDevice = libusb_le16_to_cpu(dev->device_descriptor.bcdDevice);
+ }
+
+ return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_desc
+ * Get the USB device descriptor for a given device.
+ *
+ * This is a non-blocking function; the device descriptor is cached in memory.
+ *
+ * Note since libusb-1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, this
+ * function always succeeds.
+ *
+ * \param dev the device
+ * \param desc output location for the descriptor data
+ * \returns 0 on success or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_get_device_descriptor(libusb_device *dev,
+ struct libusb_device_descriptor *desc)
+{
+ usbi_dbg("");
+ memcpy((unsigned char *) desc, (unsigned char *) &dev->device_descriptor,
+ sizeof (dev->device_descriptor));
+ return 0;
+}
+
+/** \ingroup libusb_desc
+ * Get the USB configuration descriptor for the currently active configuration.
+ * This is a non-blocking function which does not involve any requests being
+ * sent to the device.
+ *
+ * \param dev a device
+ * \param config output location for the USB configuration descriptor. Only
+ * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
+ * after use.
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
+ * \returns another LIBUSB_ERROR code on error
+ * \see libusb_get_config_descriptor
+ */
+int API_EXPORTED libusb_get_active_config_descriptor(libusb_device *dev,
+ struct libusb_config_descriptor **config)
+{
+ struct libusb_config_descriptor _config;
+ unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
+ unsigned char *buf = NULL;
+ int host_endian = 0;
+ int r;
+
+ r = usbi_backend.get_active_config_descriptor(dev, tmp,
+ LIBUSB_DT_CONFIG_SIZE, &host_endian);
+ if (r < 0)
+ return r;
+ if (r < LIBUSB_DT_CONFIG_SIZE) {
+ usbi_err(dev->ctx, "short config descriptor read %d/%d",
+ r, LIBUSB_DT_CONFIG_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
+ buf = malloc(_config.wTotalLength);
+ if (!buf)
+ return LIBUSB_ERROR_NO_MEM;
+
+ r = usbi_backend.get_active_config_descriptor(dev, buf,
+ _config.wTotalLength, &host_endian);
+ if (r >= 0)
+ r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
+
+ free(buf);
+ return r;
+}
+
+/** \ingroup libusb_desc
+ * Get a USB configuration descriptor based on its index.
+ * This is a non-blocking function which does not involve any requests being
+ * sent to the device.
+ *
+ * \param dev a device
+ * \param config_index the index of the configuration you wish to retrieve
+ * \param config output location for the USB configuration descriptor. Only
+ * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
+ * after use.
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
+ * \returns another LIBUSB_ERROR code on error
+ * \see libusb_get_active_config_descriptor()
+ * \see libusb_get_config_descriptor_by_value()
+ */
+int API_EXPORTED libusb_get_config_descriptor(libusb_device *dev,
+ uint8_t config_index, struct libusb_config_descriptor **config)
+{
+ struct libusb_config_descriptor _config;
+ unsigned char tmp[LIBUSB_DT_CONFIG_SIZE];
+ unsigned char *buf = NULL;
+ int host_endian = 0;
+ int r;
+
+ usbi_dbg("index %d", config_index);
+ if (config_index >= dev->num_configurations)
+ return LIBUSB_ERROR_NOT_FOUND;
+
+ r = usbi_backend.get_config_descriptor(dev, config_index, tmp,
+ LIBUSB_DT_CONFIG_SIZE, &host_endian);
+ if (r < 0)
+ return r;
+ if (r < LIBUSB_DT_CONFIG_SIZE) {
+ usbi_err(dev->ctx, "short config descriptor read %d/%d",
+ r, LIBUSB_DT_CONFIG_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usbi_parse_descriptor(tmp, "bbw", &_config, host_endian);
+ buf = malloc(_config.wTotalLength);
+ if (!buf)
+ return LIBUSB_ERROR_NO_MEM;
+
+ r = usbi_backend.get_config_descriptor(dev, config_index, buf,
+ _config.wTotalLength, &host_endian);
+ if (r >= 0)
+ r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
+
+ free(buf);
+ return r;
+}
+
+/* iterate through all configurations, returning the index of the configuration
+ * matching a specific bConfigurationValue in the idx output parameter, or -1
+ * if the config was not found.
+ * returns 0 on success or a LIBUSB_ERROR code
+ */
+int usbi_get_config_index_by_value(struct libusb_device *dev,
+ uint8_t bConfigurationValue, int *idx)
+{
+ uint8_t i;
+
+ usbi_dbg("value %d", bConfigurationValue);
+ for (i = 0; i < dev->num_configurations; i++) {
+ unsigned char tmp[6];
+ int host_endian;
+ int r = usbi_backend.get_config_descriptor(dev, i, tmp, sizeof(tmp),
+ &host_endian);
+ if (r < 0) {
+ *idx = -1;
+ return r;
+ }
+ if (tmp[5] == bConfigurationValue) {
+ *idx = i;
+ return 0;
+ }
+ }
+
+ *idx = -1;
+ return 0;
+}
+
+/** \ingroup libusb_desc
+ * Get a USB configuration descriptor with a specific bConfigurationValue.
+ * This is a non-blocking function which does not involve any requests being
+ * sent to the device.
+ *
+ * \param dev a device
+ * \param bConfigurationValue the bConfigurationValue of the configuration you
+ * wish to retrieve
+ * \param config output location for the USB configuration descriptor. Only
+ * valid if 0 was returned. Must be freed with libusb_free_config_descriptor()
+ * after use.
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
+ * \returns another LIBUSB_ERROR code on error
+ * \see libusb_get_active_config_descriptor()
+ * \see libusb_get_config_descriptor()
+ */
+int API_EXPORTED libusb_get_config_descriptor_by_value(libusb_device *dev,
+ uint8_t bConfigurationValue, struct libusb_config_descriptor **config)
+{
+ int r, idx, host_endian;
+ unsigned char *buf = NULL;
+
+ if (usbi_backend.get_config_descriptor_by_value) {
+ r = usbi_backend.get_config_descriptor_by_value(dev,
+ bConfigurationValue, &buf, &host_endian);
+ if (r < 0)
+ return r;
+ return raw_desc_to_config(dev->ctx, buf, r, host_endian, config);
+ }
+
+ r = usbi_get_config_index_by_value(dev, bConfigurationValue, &idx);
+ if (r < 0)
+ return r;
+ else if (idx == -1)
+ return LIBUSB_ERROR_NOT_FOUND;
+ else
+ return libusb_get_config_descriptor(dev, (uint8_t) idx, config);
+}
+
+/** \ingroup libusb_desc
+ * Free a configuration descriptor obtained from
+ * libusb_get_active_config_descriptor() or libusb_get_config_descriptor().
+ * It is safe to call this function with a NULL config parameter, in which
+ * case the function simply returns.
+ *
+ * \param config the configuration descriptor to free
+ */
+void API_EXPORTED libusb_free_config_descriptor(
+ struct libusb_config_descriptor *config)
+{
+ if (!config)
+ return;
+
+ clear_configuration(config);
+ free(config);
+}
+
+/** \ingroup libusb_desc
+ * Get an endpoints superspeed endpoint companion descriptor (if any)
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param endpoint endpoint descriptor from which to get the superspeed
+ * endpoint companion descriptor
+ * \param ep_comp output location for the superspeed endpoint companion
+ * descriptor. Only valid if 0 was returned. Must be freed with
+ * libusb_free_ss_endpoint_companion_descriptor() after use.
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
+ * \returns another LIBUSB_ERROR code on error
+ */
+int API_EXPORTED libusb_get_ss_endpoint_companion_descriptor(
+ struct libusb_context *ctx,
+ const struct libusb_endpoint_descriptor *endpoint,
+ struct libusb_ss_endpoint_companion_descriptor **ep_comp)
+{
+ struct usb_descriptor_header header;
+ int size = endpoint->extra_length;
+ const unsigned char *buffer = endpoint->extra;
+
+ *ep_comp = NULL;
+
+ while (size >= DESC_HEADER_LENGTH) {
+ usbi_parse_descriptor(buffer, "bb", &header, 0);
+ if (header.bLength < 2 || header.bLength > size) {
+ usbi_err(ctx, "invalid descriptor length %d",
+ header.bLength);
+ return LIBUSB_ERROR_IO;
+ }
+ if (header.bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) {
+ buffer += header.bLength;
+ size -= header.bLength;
+ continue;
+ }
+ if (header.bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) {
+ usbi_err(ctx, "invalid ss-ep-comp-desc length %d",
+ header.bLength);
+ return LIBUSB_ERROR_IO;
+ }
+ *ep_comp = malloc(sizeof(**ep_comp));
+ if (*ep_comp == NULL)
+ return LIBUSB_ERROR_NO_MEM;
+ usbi_parse_descriptor(buffer, "bbbbw", *ep_comp, 0);
+ return LIBUSB_SUCCESS;
+ }
+ return LIBUSB_ERROR_NOT_FOUND;
+}
+
+/** \ingroup libusb_desc
+ * Free a superspeed endpoint companion descriptor obtained from
+ * libusb_get_ss_endpoint_companion_descriptor().
+ * It is safe to call this function with a NULL ep_comp parameter, in which
+ * case the function simply returns.
+ *
+ * \param ep_comp the superspeed endpoint companion descriptor to free
+ */
+void API_EXPORTED libusb_free_ss_endpoint_companion_descriptor(
+ struct libusb_ss_endpoint_companion_descriptor *ep_comp)
+{
+ free(ep_comp);
+}
+
+static int parse_bos(struct libusb_context *ctx,
+ struct libusb_bos_descriptor **bos,
+ unsigned char *buffer, int size, int host_endian)
+{
+ struct libusb_bos_descriptor bos_header, *_bos;
+ struct libusb_bos_dev_capability_descriptor dev_cap;
+ int i;
+
+ if (size < LIBUSB_DT_BOS_SIZE) {
+ usbi_err(ctx, "short bos descriptor read %d/%d",
+ size, LIBUSB_DT_BOS_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usbi_parse_descriptor(buffer, "bbwb", &bos_header, host_endian);
+ if (bos_header.bDescriptorType != LIBUSB_DT_BOS) {
+ usbi_err(ctx, "unexpected descriptor %x (expected %x)",
+ bos_header.bDescriptorType, LIBUSB_DT_BOS);
+ return LIBUSB_ERROR_IO;
+ }
+ if (bos_header.bLength < LIBUSB_DT_BOS_SIZE) {
+ usbi_err(ctx, "invalid bos bLength (%d)", bos_header.bLength);
+ return LIBUSB_ERROR_IO;
+ }
+ if (bos_header.bLength > size) {
+ usbi_err(ctx, "short bos descriptor read %d/%d",
+ size, bos_header.bLength);
+ return LIBUSB_ERROR_IO;
+ }
+
+ _bos = calloc (1,
+ sizeof(*_bos) + bos_header.bNumDeviceCaps * sizeof(void *));
+ if (!_bos)
+ return LIBUSB_ERROR_NO_MEM;
+
+ usbi_parse_descriptor(buffer, "bbwb", _bos, host_endian);
+ buffer += bos_header.bLength;
+ size -= bos_header.bLength;
+
+ /* Get the device capability descriptors */
+ for (i = 0; i < bos_header.bNumDeviceCaps; i++) {
+ if (size < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
+ usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
+ size, LIBUSB_DT_DEVICE_CAPABILITY_SIZE);
+ break;
+ }
+ usbi_parse_descriptor(buffer, "bbb", &dev_cap, host_endian);
+ if (dev_cap.bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) {
+ usbi_warn(ctx, "unexpected descriptor %x (expected %x)",
+ dev_cap.bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY);
+ break;
+ }
+ if (dev_cap.bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) {
+ usbi_err(ctx, "invalid dev-cap bLength (%d)",
+ dev_cap.bLength);
+ libusb_free_bos_descriptor(_bos);
+ return LIBUSB_ERROR_IO;
+ }
+ if (dev_cap.bLength > size) {
+ usbi_warn(ctx, "short dev-cap descriptor read %d/%d",
+ size, dev_cap.bLength);
+ break;
+ }
+
+ _bos->dev_capability[i] = malloc(dev_cap.bLength);
+ if (!_bos->dev_capability[i]) {
+ libusb_free_bos_descriptor(_bos);
+ return LIBUSB_ERROR_NO_MEM;
+ }
+ memcpy(_bos->dev_capability[i], buffer, dev_cap.bLength);
+ buffer += dev_cap.bLength;
+ size -= dev_cap.bLength;
+ }
+ _bos->bNumDeviceCaps = (uint8_t)i;
+ *bos = _bos;
+
+ return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_desc
+ * Get a Binary Object Store (BOS) descriptor
+ * This is a BLOCKING function, which will send requests to the device.
+ *
+ * \param dev_handle the handle of an open libusb device
+ * \param bos output location for the BOS descriptor. Only valid if 0 was returned.
+ * Must be freed with \ref libusb_free_bos_descriptor() after use.
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the device doesn't have a BOS descriptor
+ * \returns another LIBUSB_ERROR code on error
+ */
+int API_EXPORTED libusb_get_bos_descriptor(libusb_device_handle *dev_handle,
+ struct libusb_bos_descriptor **bos)
+{
+ struct libusb_bos_descriptor _bos;
+ uint8_t bos_header[LIBUSB_DT_BOS_SIZE] = {0};
+ unsigned char *bos_data = NULL;
+ const int host_endian = 0;
+ int r;
+
+ /* Read the BOS. This generates 2 requests on the bus,
+ * one for the header, and one for the full BOS */
+ r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_header,
+ LIBUSB_DT_BOS_SIZE);
+ if (r < 0) {
+ if (r != LIBUSB_ERROR_PIPE)
+ usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r);
+ return r;
+ }
+ if (r < LIBUSB_DT_BOS_SIZE) {
+ usbi_err(HANDLE_CTX(dev_handle), "short BOS read %d/%d",
+ r, LIBUSB_DT_BOS_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ usbi_parse_descriptor(bos_header, "bbwb", &_bos, host_endian);
+ usbi_dbg("found BOS descriptor: size %d bytes, %d capabilities",
+ _bos.wTotalLength, _bos.bNumDeviceCaps);
+ bos_data = calloc(_bos.wTotalLength, 1);
+ if (bos_data == NULL)
+ return LIBUSB_ERROR_NO_MEM;
+
+ r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_data,
+ _bos.wTotalLength);
+ if (r >= 0)
+ r = parse_bos(HANDLE_CTX(dev_handle), bos, bos_data, r, host_endian);
+ else
+ usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r);
+
+ free(bos_data);
+ return r;
+}
+
+/** \ingroup libusb_desc
+ * Free a BOS descriptor obtained from libusb_get_bos_descriptor().
+ * It is safe to call this function with a NULL bos parameter, in which
+ * case the function simply returns.
+ *
+ * \param bos the BOS descriptor to free
+ */
+void API_EXPORTED libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos)
+{
+ int i;
+
+ if (!bos)
+ return;
+
+ for (i = 0; i < bos->bNumDeviceCaps; i++)
+ free(bos->dev_capability[i]);
+ free(bos);
+}
+
+/** \ingroup libusb_desc
+ * Get an USB 2.0 Extension descriptor
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
+ * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION
+ * LIBUSB_BT_USB_2_0_EXTENSION
+ * \param usb_2_0_extension output location for the USB 2.0 Extension
+ * descriptor. Only valid if 0 was returned. Must be freed with
+ * libusb_free_usb_2_0_extension_descriptor() after use.
+ * \returns 0 on success
+ * \returns a LIBUSB_ERROR code on error
+ */
+int API_EXPORTED libusb_get_usb_2_0_extension_descriptor(
+ struct libusb_context *ctx,
+ struct libusb_bos_dev_capability_descriptor *dev_cap,
+ struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension)
+{
+ struct libusb_usb_2_0_extension_descriptor *_usb_2_0_extension;
+ const int host_endian = 0;
+
+ if (dev_cap->bDevCapabilityType != LIBUSB_BT_USB_2_0_EXTENSION) {
+ usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
+ dev_cap->bDevCapabilityType,
+ LIBUSB_BT_USB_2_0_EXTENSION);
+ return LIBUSB_ERROR_INVALID_PARAM;
+ }
+ if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) {
+ usbi_err(ctx, "short dev-cap descriptor read %d/%d",
+ dev_cap->bLength, LIBUSB_BT_USB_2_0_EXTENSION_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ _usb_2_0_extension = malloc(sizeof(*_usb_2_0_extension));
+ if (!_usb_2_0_extension)
+ return LIBUSB_ERROR_NO_MEM;
+
+ usbi_parse_descriptor((unsigned char *)dev_cap, "bbbd",
+ _usb_2_0_extension, host_endian);
+
+ *usb_2_0_extension = _usb_2_0_extension;
+ return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_desc
+ * Free a USB 2.0 Extension descriptor obtained from
+ * libusb_get_usb_2_0_extension_descriptor().
+ * It is safe to call this function with a NULL usb_2_0_extension parameter,
+ * in which case the function simply returns.
+ *
+ * \param usb_2_0_extension the USB 2.0 Extension descriptor to free
+ */
+void API_EXPORTED libusb_free_usb_2_0_extension_descriptor(
+ struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension)
+{
+ free(usb_2_0_extension);
+}
+
+/** \ingroup libusb_desc
+ * Get a SuperSpeed USB Device Capability descriptor
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
+ * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
+ * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
+ * \param ss_usb_device_cap output location for the SuperSpeed USB Device
+ * Capability descriptor. Only valid if 0 was returned. Must be freed with
+ * libusb_free_ss_usb_device_capability_descriptor() after use.
+ * \returns 0 on success
+ * \returns a LIBUSB_ERROR code on error
+ */
+int API_EXPORTED libusb_get_ss_usb_device_capability_descriptor(
+ struct libusb_context *ctx,
+ struct libusb_bos_dev_capability_descriptor *dev_cap,
+ struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap)
+{
+ struct libusb_ss_usb_device_capability_descriptor *_ss_usb_device_cap;
+ const int host_endian = 0;
+
+ if (dev_cap->bDevCapabilityType != LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) {
+ usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
+ dev_cap->bDevCapabilityType,
+ LIBUSB_BT_SS_USB_DEVICE_CAPABILITY);
+ return LIBUSB_ERROR_INVALID_PARAM;
+ }
+ if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) {
+ usbi_err(ctx, "short dev-cap descriptor read %d/%d",
+ dev_cap->bLength, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ _ss_usb_device_cap = malloc(sizeof(*_ss_usb_device_cap));
+ if (!_ss_usb_device_cap)
+ return LIBUSB_ERROR_NO_MEM;
+
+ usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbwbbw",
+ _ss_usb_device_cap, host_endian);
+
+ *ss_usb_device_cap = _ss_usb_device_cap;
+ return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_desc
+ * Free a SuperSpeed USB Device Capability descriptor obtained from
+ * libusb_get_ss_usb_device_capability_descriptor().
+ * It is safe to call this function with a NULL ss_usb_device_cap
+ * parameter, in which case the function simply returns.
+ *
+ * \param ss_usb_device_cap the USB 2.0 Extension descriptor to free
+ */
+void API_EXPORTED libusb_free_ss_usb_device_capability_descriptor(
+ struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap)
+{
+ free(ss_usb_device_cap);
+}
+
+/** \ingroup libusb_desc
+ * Get a Container ID descriptor
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param dev_cap Device Capability descriptor with a bDevCapabilityType of
+ * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID
+ * LIBUSB_BT_CONTAINER_ID
+ * \param container_id output location for the Container ID descriptor.
+ * Only valid if 0 was returned. Must be freed with
+ * libusb_free_container_id_descriptor() after use.
+ * \returns 0 on success
+ * \returns a LIBUSB_ERROR code on error
+ */
+int API_EXPORTED libusb_get_container_id_descriptor(struct libusb_context *ctx,
+ struct libusb_bos_dev_capability_descriptor *dev_cap,
+ struct libusb_container_id_descriptor **container_id)
+{
+ struct libusb_container_id_descriptor *_container_id;
+ const int host_endian = 0;
+
+ if (dev_cap->bDevCapabilityType != LIBUSB_BT_CONTAINER_ID) {
+ usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)",
+ dev_cap->bDevCapabilityType,
+ LIBUSB_BT_CONTAINER_ID);
+ return LIBUSB_ERROR_INVALID_PARAM;
+ }
+ if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) {
+ usbi_err(ctx, "short dev-cap descriptor read %d/%d",
+ dev_cap->bLength, LIBUSB_BT_CONTAINER_ID_SIZE);
+ return LIBUSB_ERROR_IO;
+ }
+
+ _container_id = malloc(sizeof(*_container_id));
+ if (!_container_id)
+ return LIBUSB_ERROR_NO_MEM;
+
+ usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbu",
+ _container_id, host_endian);
+
+ *container_id = _container_id;
+ return LIBUSB_SUCCESS;
+}
+
+/** \ingroup libusb_desc
+ * Free a Container ID descriptor obtained from
+ * libusb_get_container_id_descriptor().
+ * It is safe to call this function with a NULL container_id parameter,
+ * in which case the function simply returns.
+ *
+ * \param container_id the USB 2.0 Extension descriptor to free
+ */
+void API_EXPORTED libusb_free_container_id_descriptor(
+ struct libusb_container_id_descriptor *container_id)
+{
+ free(container_id);
+}
+
+/** \ingroup libusb_desc
+ * Retrieve a string descriptor in C style ASCII.
+ *
+ * Wrapper around libusb_get_string_descriptor(). Uses the first language
+ * supported by the device.
+ *
+ * \param dev_handle a device handle
+ * \param desc_index the index of the descriptor to retrieve
+ * \param data output buffer for ASCII string descriptor
+ * \param length size of data buffer
+ * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle,
+ uint8_t desc_index, unsigned char *data, int length)
+{
+ unsigned char tbuf[255]; /* Some devices choke on size > 255 */
+ int r, si, di;
+ uint16_t langid;
+
+ /* Asking for the zero'th index is special - it returns a string
+ * descriptor that contains all the language IDs supported by the
+ * device. Typically there aren't many - often only one. Language
+ * IDs are 16 bit numbers, and they start at the third byte in the
+ * descriptor. There's also no point in trying to read descriptor 0
+ * with this function. See USB 2.0 specification section 9.6.7 for
+ * more information.
+ */
+
+ if (desc_index == 0)
+ return LIBUSB_ERROR_INVALID_PARAM;
+
+ r = libusb_get_string_descriptor(dev_handle, 0, 0, tbuf, sizeof(tbuf));
+ if (r < 0)
+ return r;
+
+ if (r < 4)
+ return LIBUSB_ERROR_IO;
+
+ langid = tbuf[2] | (tbuf[3] << 8);
+
+ r = libusb_get_string_descriptor(dev_handle, desc_index, langid, tbuf,
+ sizeof(tbuf));
+ if (r < 0)
+ return r;
+
+ if (tbuf[1] != LIBUSB_DT_STRING)
+ return LIBUSB_ERROR_IO;
+
+ if (tbuf[0] > r)
+ return LIBUSB_ERROR_IO;
+
+ di = 0;
+ for (si = 2; si < tbuf[0]; si += 2) {
+ if (di >= (length - 1))
+ break;
+
+ if ((tbuf[si] & 0x80) || (tbuf[si + 1])) /* non-ASCII */
+ data[di++] = '?';
+ else
+ data[di++] = tbuf[si];
+ }
+
+ data[di] = 0;
+ return di;
+}
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/hotplug.c b/vendor/github.com/karalabe/usb/libusb/libusb/hotplug.c
new file mode 100644
index 000000000..a4320bc42
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/hotplug.c
@@ -0,0 +1,373 @@
+/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
+/*
+ * Hotplug functions for libusb
+ * Copyright © 2012-2013 Nathan Hjelm
+ * Copyright © 2012-2013 Peter Stuge
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include
+
+#include
+#include
+#include
+#include
+#ifdef HAVE_SYS_TYPES_H
+#include
+#endif
+#include
+
+#include "libusbi.h"
+#include "hotplug.h"
+
+/**
+ * @defgroup libusb_hotplug Device hotplug event notification
+ * This page details how to use the libusb hotplug interface, where available.
+ *
+ * Be mindful that not all platforms currently implement hotplug notification and
+ * that you should first call on \ref libusb_has_capability() with parameter
+ * \ref LIBUSB_CAP_HAS_HOTPLUG to confirm that hotplug support is available.
+ *
+ * \page libusb_hotplug Device hotplug event notification
+ *
+ * \section hotplug_intro Introduction
+ *
+ * Version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, has added support
+ * for hotplug events on some platforms (you should test if your platform
+ * supports hotplug notification by calling \ref libusb_has_capability() with
+ * parameter \ref LIBUSB_CAP_HAS_HOTPLUG).
+ *
+ * This interface allows you to request notification for the arrival and departure
+ * of matching USB devices.
+ *
+ * To receive hotplug notification you register a callback by calling
+ * \ref libusb_hotplug_register_callback(). This function will optionally return
+ * a callback handle that can be passed to \ref libusb_hotplug_deregister_callback().
+ *
+ * A callback function must return an int (0 or 1) indicating whether the callback is
+ * expecting additional events. Returning 0 will rearm the callback and 1 will cause
+ * the callback to be deregistered. Note that when callbacks are called from
+ * libusb_hotplug_register_callback() because of the \ref LIBUSB_HOTPLUG_ENUMERATE
+ * flag, the callback return value is ignored, iow you cannot cause a callback
+ * to be deregistered by returning 1 when it is called from
+ * libusb_hotplug_register_callback().
+ *
+ * Callbacks for a particular context are automatically deregistered by libusb_exit().
+ *
+ * As of 1.0.16 there are two supported hotplug events:
+ * - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: A device has arrived and is ready to use
+ * - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: A device has left and is no longer available
+ *
+ * A hotplug event can listen for either or both of these events.
+ *
+ * Note: If you receive notification that a device has left and you have any
+ * a libusb_device_handles for the device it is up to you to call libusb_close()
+ * on each device handle to free up any remaining resources associated with the device.
+ * Once a device has left any libusb_device_handle associated with the device
+ * are invalid and will remain so even if the device comes back.
+ *
+ * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED event it is considered
+ * safe to call any libusb function that takes a libusb_device. It also safe to
+ * open a device and submit asynchronous transfers. However, most other functions
+ * that take a libusb_device_handle are not safe to call. Examples of such
+ * functions are any of the \ref libusb_syncio "synchronous API" functions or the blocking
+ * functions that retrieve various \ref libusb_desc "USB descriptors". These functions must
+ * be used outside of the context of the hotplug callback.
+ *
+ * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT event the only safe function
+ * is libusb_get_device_descriptor().
+ *
+ * The following code provides an example of the usage of the hotplug interface:
+\code
+#include
+#include
+#include
+#include
+
+static int count = 0;
+
+int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
+ libusb_hotplug_event event, void *user_data) {
+ static libusb_device_handle *dev_handle = NULL;
+ struct libusb_device_descriptor desc;
+ int rc;
+
+ (void)libusb_get_device_descriptor(dev, &desc);
+
+ if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
+ rc = libusb_open(dev, &dev_handle);
+ if (LIBUSB_SUCCESS != rc) {
+ printf("Could not open USB device\n");
+ }
+ } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
+ if (dev_handle) {
+ libusb_close(dev_handle);
+ dev_handle = NULL;
+ }
+ } else {
+ printf("Unhandled event %d\n", event);
+ }
+ count++;
+
+ return 0;
+}
+
+int main (void) {
+ libusb_hotplug_callback_handle callback_handle;
+ int rc;
+
+ libusb_init(NULL);
+
+ rc = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
+ LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, 0x045a, 0x5005,
+ LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL,
+ &callback_handle);
+ if (LIBUSB_SUCCESS != rc) {
+ printf("Error creating a hotplug callback\n");
+ libusb_exit(NULL);
+ return EXIT_FAILURE;
+ }
+
+ while (count < 2) {
+ libusb_handle_events_completed(NULL, NULL);
+ nanosleep(&(struct timespec){0, 10000000UL}, NULL);
+ }
+
+ libusb_hotplug_deregister_callback(NULL, callback_handle);
+ libusb_exit(NULL);
+
+ return 0;
+}
+\endcode
+ */
+
+static int usbi_hotplug_match_cb(struct libusb_context *ctx,
+ struct libusb_device *dev, libusb_hotplug_event event,
+ struct libusb_hotplug_callback *hotplug_cb)
+{
+ if (!(hotplug_cb->flags & event)) {
+ return 0;
+ }
+
+ if ((hotplug_cb->flags & USBI_HOTPLUG_VENDOR_ID_VALID) &&
+ hotplug_cb->vendor_id != dev->device_descriptor.idVendor) {
+ return 0;
+ }
+
+ if ((hotplug_cb->flags & USBI_HOTPLUG_PRODUCT_ID_VALID) &&
+ hotplug_cb->product_id != dev->device_descriptor.idProduct) {
+ return 0;
+ }
+
+ if ((hotplug_cb->flags & USBI_HOTPLUG_DEV_CLASS_VALID) &&
+ hotplug_cb->dev_class != dev->device_descriptor.bDeviceClass) {
+ return 0;
+ }
+
+ return hotplug_cb->cb(ctx, dev, event, hotplug_cb->user_data);
+}
+
+void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev,
+ libusb_hotplug_event event)
+{
+ struct libusb_hotplug_callback *hotplug_cb, *next;
+ int ret;
+
+ usbi_mutex_lock(&ctx->hotplug_cbs_lock);
+
+ list_for_each_entry_safe(hotplug_cb, next, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) {
+ if (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE) {
+ /* process deregistration in usbi_hotplug_deregister() */
+ continue;
+ }
+
+ usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
+ ret = usbi_hotplug_match_cb(ctx, dev, event, hotplug_cb);
+ usbi_mutex_lock(&ctx->hotplug_cbs_lock);
+
+ if (ret) {
+ list_del(&hotplug_cb->list);
+ free(hotplug_cb);
+ }
+ }
+
+ usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
+}
+
+void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
+ libusb_hotplug_event event)
+{
+ int pending_events;
+ struct libusb_hotplug_message *message = calloc(1, sizeof(*message));
+
+ if (!message) {
+ usbi_err(ctx, "error allocating hotplug message");
+ return;
+ }
+
+ message->event = event;
+ message->device = dev;
+
+ /* Take the event data lock and add this message to the list.
+ * Only signal an event if there are no prior pending events. */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ pending_events = usbi_pending_events(ctx);
+ list_add_tail(&message->list, &ctx->hotplug_msgs);
+ if (!pending_events)
+ usbi_signal_event(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+}
+
+int API_EXPORTED libusb_hotplug_register_callback(libusb_context *ctx,
+ libusb_hotplug_event events, libusb_hotplug_flag flags,
+ int vendor_id, int product_id, int dev_class,
+ libusb_hotplug_callback_fn cb_fn, void *user_data,
+ libusb_hotplug_callback_handle *callback_handle)
+{
+ struct libusb_hotplug_callback *new_callback;
+
+ /* check for sane values */
+ if ((!events || (~(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) & events)) ||
+ (flags && (~LIBUSB_HOTPLUG_ENUMERATE & flags)) ||
+ (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id && (~0xffff & vendor_id)) ||
+ (LIBUSB_HOTPLUG_MATCH_ANY != product_id && (~0xffff & product_id)) ||
+ (LIBUSB_HOTPLUG_MATCH_ANY != dev_class && (~0xff & dev_class)) ||
+ !cb_fn) {
+ return LIBUSB_ERROR_INVALID_PARAM;
+ }
+
+ /* check for hotplug support */
+ if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ return LIBUSB_ERROR_NOT_SUPPORTED;
+ }
+
+ USBI_GET_CONTEXT(ctx);
+
+ new_callback = calloc(1, sizeof(*new_callback));
+ if (!new_callback) {
+ return LIBUSB_ERROR_NO_MEM;
+ }
+
+ new_callback->flags = (uint8_t)events;
+ if (LIBUSB_HOTPLUG_MATCH_ANY != vendor_id) {
+ new_callback->flags |= USBI_HOTPLUG_VENDOR_ID_VALID;
+ new_callback->vendor_id = (uint16_t)vendor_id;
+ }
+ if (LIBUSB_HOTPLUG_MATCH_ANY != product_id) {
+ new_callback->flags |= USBI_HOTPLUG_PRODUCT_ID_VALID;
+ new_callback->product_id = (uint16_t)product_id;
+ }
+ if (LIBUSB_HOTPLUG_MATCH_ANY != dev_class) {
+ new_callback->flags |= USBI_HOTPLUG_DEV_CLASS_VALID;
+ new_callback->dev_class = (uint8_t)dev_class;
+ }
+ new_callback->cb = cb_fn;
+ new_callback->user_data = user_data;
+
+ usbi_mutex_lock(&ctx->hotplug_cbs_lock);
+
+ /* protect the handle by the context hotplug lock */
+ new_callback->handle = ctx->next_hotplug_cb_handle++;
+
+ /* handle the unlikely case of overflow */
+ if (ctx->next_hotplug_cb_handle < 0)
+ ctx->next_hotplug_cb_handle = 1;
+
+ list_add(&new_callback->list, &ctx->hotplug_cbs);
+
+ usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
+
+ usbi_dbg("new hotplug cb %p with handle %d", new_callback, new_callback->handle);
+
+ if ((flags & LIBUSB_HOTPLUG_ENUMERATE) && (events & LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)) {
+ ssize_t i, len;
+ struct libusb_device **devs;
+
+ len = libusb_get_device_list(ctx, &devs);
+ if (len < 0) {
+ libusb_hotplug_deregister_callback(ctx,
+ new_callback->handle);
+ return (int)len;
+ }
+
+ for (i = 0; i < len; i++) {
+ usbi_hotplug_match_cb(ctx, devs[i],
+ LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
+ new_callback);
+ }
+
+ libusb_free_device_list(devs, 1);
+ }
+
+
+ if (callback_handle)
+ *callback_handle = new_callback->handle;
+
+ return LIBUSB_SUCCESS;
+}
+
+void API_EXPORTED libusb_hotplug_deregister_callback(struct libusb_context *ctx,
+ libusb_hotplug_callback_handle callback_handle)
+{
+ struct libusb_hotplug_callback *hotplug_cb;
+ int deregistered = 0;
+
+ /* check for hotplug support */
+ if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ return;
+ }
+
+ USBI_GET_CONTEXT(ctx);
+
+ usbi_dbg("deregister hotplug cb %d", callback_handle);
+
+ usbi_mutex_lock(&ctx->hotplug_cbs_lock);
+ list_for_each_entry(hotplug_cb, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) {
+ if (callback_handle == hotplug_cb->handle) {
+ /* Mark this callback for deregistration */
+ hotplug_cb->flags |= USBI_HOTPLUG_NEEDS_FREE;
+ deregistered = 1;
+ }
+ }
+ usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
+
+ if (deregistered) {
+ int pending_events;
+
+ usbi_mutex_lock(&ctx->event_data_lock);
+ pending_events = usbi_pending_events(ctx);
+ ctx->event_flags |= USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
+ if (!pending_events)
+ usbi_signal_event(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ }
+}
+
+void usbi_hotplug_deregister(struct libusb_context *ctx, int forced)
+{
+ struct libusb_hotplug_callback *hotplug_cb, *next;
+
+ usbi_mutex_lock(&ctx->hotplug_cbs_lock);
+ list_for_each_entry_safe(hotplug_cb, next, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) {
+ if (forced || (hotplug_cb->flags & USBI_HOTPLUG_NEEDS_FREE)) {
+ usbi_dbg("freeing hotplug cb %p with handle %d", hotplug_cb,
+ hotplug_cb->handle);
+ list_del(&hotplug_cb->list);
+ free(hotplug_cb);
+ }
+ }
+ usbi_mutex_unlock(&ctx->hotplug_cbs_lock);
+}
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/hotplug.h b/vendor/github.com/karalabe/usb/libusb/libusb/hotplug.h
new file mode 100644
index 000000000..dbadbcb93
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/hotplug.h
@@ -0,0 +1,99 @@
+/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
+/*
+ * Hotplug support for libusb
+ * Copyright © 2012-2013 Nathan Hjelm
+ * Copyright © 2012-2013 Peter Stuge
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef USBI_HOTPLUG_H
+#define USBI_HOTPLUG_H
+
+#include "libusbi.h"
+
+enum usbi_hotplug_flags {
+ /* This callback is interested in device arrivals */
+ USBI_HOTPLUG_DEVICE_ARRIVED = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
+
+ /* This callback is interested in device removals */
+ USBI_HOTPLUG_DEVICE_LEFT = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
+
+ /* IMPORTANT: The values for the below entries must start *after*
+ * the highest value of the above entries!!!
+ */
+
+ /* The vendor_id field is valid for matching */
+ USBI_HOTPLUG_VENDOR_ID_VALID = (1 << 3),
+
+ /* The product_id field is valid for matching */
+ USBI_HOTPLUG_PRODUCT_ID_VALID = (1 << 4),
+
+ /* The dev_class field is valid for matching */
+ USBI_HOTPLUG_DEV_CLASS_VALID = (1 << 5),
+
+ /* This callback has been unregistered and needs to be freed */
+ USBI_HOTPLUG_NEEDS_FREE = (1 << 6),
+};
+
+/** \ingroup hotplug
+ * The hotplug callback structure. The user populates this structure with
+ * libusb_hotplug_prepare_callback() and then calls libusb_hotplug_register_callback()
+ * to receive notification of hotplug events.
+ */
+struct libusb_hotplug_callback {
+ /** Flags that control how this callback behaves */
+ uint8_t flags;
+
+ /** Vendor ID to match (if flags says this is valid) */
+ uint16_t vendor_id;
+
+ /** Product ID to match (if flags says this is valid) */
+ uint16_t product_id;
+
+ /** Device class to match (if flags says this is valid) */
+ uint8_t dev_class;
+
+ /** Callback function to invoke for matching event/device */
+ libusb_hotplug_callback_fn cb;
+
+ /** Handle for this callback (used to match on deregister) */
+ libusb_hotplug_callback_handle handle;
+
+ /** User data that will be passed to the callback function */
+ void *user_data;
+
+ /** List this callback is registered in (ctx->hotplug_cbs) */
+ struct list_head list;
+};
+
+struct libusb_hotplug_message {
+ /** The hotplug event that occurred */
+ libusb_hotplug_event event;
+
+ /** The device for which this hotplug event occurred */
+ struct libusb_device *device;
+
+ /** List this message is contained in (ctx->hotplug_msgs) */
+ struct list_head list;
+};
+
+void usbi_hotplug_deregister(struct libusb_context *ctx, int forced);
+void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev,
+ libusb_hotplug_event event);
+void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
+ libusb_hotplug_event event);
+
+#endif
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/io.c b/vendor/github.com/karalabe/usb/libusb/libusb/io.c
new file mode 100644
index 000000000..a03bfaae1
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/io.c
@@ -0,0 +1,2822 @@
+/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
+/*
+ * I/O functions for libusb
+ * Copyright © 2007-2009 Daniel Drake
+ * Copyright © 2001 Johannes Erdfelt
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#ifdef HAVE_SYS_TIME_H
+#include
+#endif
+#ifdef USBI_TIMERFD_AVAILABLE
+#include
+#endif
+
+#include "libusbi.h"
+#include "hotplug.h"
+
+/**
+ * \page libusb_io Synchronous and asynchronous device I/O
+ *
+ * \section io_intro Introduction
+ *
+ * If you're using libusb in your application, you're probably wanting to
+ * perform I/O with devices - you want to perform USB data transfers.
+ *
+ * libusb offers two separate interfaces for device I/O. This page aims to
+ * introduce the two in order to help you decide which one is more suitable
+ * for your application. You can also choose to use both interfaces in your
+ * application by considering each transfer on a case-by-case basis.
+ *
+ * Once you have read through the following discussion, you should consult the
+ * detailed API documentation pages for the details:
+ * - \ref libusb_syncio
+ * - \ref libusb_asyncio
+ *
+ * \section theory Transfers at a logical level
+ *
+ * At a logical level, USB transfers typically happen in two parts. For
+ * example, when reading data from a endpoint:
+ * -# A request for data is sent to the device
+ * -# Some time later, the incoming data is received by the host
+ *
+ * or when writing data to an endpoint:
+ *
+ * -# The data is sent to the device
+ * -# Some time later, the host receives acknowledgement from the device that
+ * the data has been transferred.
+ *
+ * There may be an indefinite delay between the two steps. Consider a
+ * fictional USB input device with a button that the user can press. In order
+ * to determine when the button is pressed, you would likely submit a request
+ * to read data on a bulk or interrupt endpoint and wait for data to arrive.
+ * Data will arrive when the button is pressed by the user, which is
+ * potentially hours later.
+ *
+ * libusb offers both a synchronous and an asynchronous interface to performing
+ * USB transfers. The main difference is that the synchronous interface
+ * combines both steps indicated above into a single function call, whereas
+ * the asynchronous interface separates them.
+ *
+ * \section sync The synchronous interface
+ *
+ * The synchronous I/O interface allows you to perform a USB transfer with
+ * a single function call. When the function call returns, the transfer has
+ * completed and you can parse the results.
+ *
+ * If you have used the libusb-0.1 before, this I/O style will seem familar to
+ * you. libusb-0.1 only offered a synchronous interface.
+ *
+ * In our input device example, to read button presses you might write code
+ * in the following style:
+\code
+unsigned char data[4];
+int actual_length;
+int r = libusb_bulk_transfer(dev_handle, LIBUSB_ENDPOINT_IN, data, sizeof(data), &actual_length, 0);
+if (r == 0 && actual_length == sizeof(data)) {
+ // results of the transaction can now be found in the data buffer
+ // parse them here and report button press
+} else {
+ error();
+}
+\endcode
+ *
+ * The main advantage of this model is simplicity: you did everything with
+ * a single simple function call.
+ *
+ * However, this interface has its limitations. Your application will sleep
+ * inside libusb_bulk_transfer() until the transaction has completed. If it
+ * takes the user 3 hours to press the button, your application will be
+ * sleeping for that long. Execution will be tied up inside the library -
+ * the entire thread will be useless for that duration.
+ *
+ * Another issue is that by tieing up the thread with that single transaction
+ * there is no possibility of performing I/O with multiple endpoints and/or
+ * multiple devices simultaneously, unless you resort to creating one thread
+ * per transaction.
+ *
+ * Additionally, there is no opportunity to cancel the transfer after the
+ * request has been submitted.
+ *
+ * For details on how to use the synchronous API, see the
+ * \ref libusb_syncio "synchronous I/O API documentation" pages.
+ *
+ * \section async The asynchronous interface
+ *
+ * Asynchronous I/O is the most significant new feature in libusb-1.0.
+ * Although it is a more complex interface, it solves all the issues detailed
+ * above.
+ *
+ * Instead of providing which functions that block until the I/O has complete,
+ * libusb's asynchronous interface presents non-blocking functions which
+ * begin a transfer and then return immediately. Your application passes a
+ * callback function pointer to this non-blocking function, which libusb will
+ * call with the results of the transaction when it has completed.
+ *
+ * Transfers which have been submitted through the non-blocking functions
+ * can be cancelled with a separate function call.
+ *
+ * The non-blocking nature of this interface allows you to be simultaneously
+ * performing I/O to multiple endpoints on multiple devices, without having
+ * to use threads.
+ *
+ * This added flexibility does come with some complications though:
+ * - In the interest of being a lightweight library, libusb does not create
+ * threads and can only operate when your application is calling into it. Your
+ * application must call into libusb from it's main loop when events are ready
+ * to be handled, or you must use some other scheme to allow libusb to
+ * undertake whatever work needs to be done.
+ * - libusb also needs to be called into at certain fixed points in time in
+ * order to accurately handle transfer timeouts.
+ * - Memory handling becomes more complex. You cannot use stack memory unless
+ * the function with that stack is guaranteed not to return until the transfer
+ * callback has finished executing.
+ * - You generally lose some linearity from your code flow because submitting
+ * the transfer request is done in a separate function from where the transfer
+ * results are handled. This becomes particularly obvious when you want to
+ * submit a second transfer based on the results of an earlier transfer.
+ *
+ * Internally, libusb's synchronous interface is expressed in terms of function
+ * calls to the asynchronous interface.
+ *
+ * For details on how to use the asynchronous API, see the
+ * \ref libusb_asyncio "asynchronous I/O API" documentation pages.
+ */
+
+
+/**
+ * \page libusb_packetoverflow Packets and overflows
+ *
+ * \section packets Packet abstraction
+ *
+ * The USB specifications describe how data is transmitted in packets, with
+ * constraints on packet size defined by endpoint descriptors. The host must
+ * not send data payloads larger than the endpoint's maximum packet size.
+ *
+ * libusb and the underlying OS abstract out the packet concept, allowing you
+ * to request transfers of any size. Internally, the request will be divided
+ * up into correctly-sized packets. You do not have to be concerned with
+ * packet sizes, but there is one exception when considering overflows.
+ *
+ * \section overflow Bulk/interrupt transfer overflows
+ *
+ * When requesting data on a bulk endpoint, libusb requires you to supply a
+ * buffer and the maximum number of bytes of data that libusb can put in that
+ * buffer. However, the size of the buffer is not communicated to the device -
+ * the device is just asked to send any amount of data.
+ *
+ * There is no problem if the device sends an amount of data that is less than
+ * or equal to the buffer size. libusb reports this condition to you through
+ * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length"
+ * field.
+ *
+ * Problems may occur if the device attempts to send more data than can fit in
+ * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but
+ * other behaviour is largely undefined: actual_length may or may not be
+ * accurate, the chunk of data that can fit in the buffer (before overflow)
+ * may or may not have been transferred.
+ *
+ * Overflows are nasty, but can be avoided. Even though you were told to
+ * ignore packets above, think about the lower level details: each transfer is
+ * split into packets (typically small, with a maximum size of 512 bytes).
+ * Overflows can only happen if the final packet in an incoming data transfer
+ * is smaller than the actual packet that the device wants to transfer.
+ * Therefore, you will never see an overflow if your transfer buffer size is a
+ * multiple of the endpoint's packet size: the final packet will either
+ * fill up completely or will be only partially filled.
+ */
+
+/**
+ * @defgroup libusb_asyncio Asynchronous device I/O
+ *
+ * This page details libusb's asynchronous (non-blocking) API for USB device
+ * I/O. This interface is very powerful but is also quite complex - you will
+ * need to read this page carefully to understand the necessary considerations
+ * and issues surrounding use of this interface. Simplistic applications
+ * may wish to consider the \ref libusb_syncio "synchronous I/O API" instead.
+ *
+ * The asynchronous interface is built around the idea of separating transfer
+ * submission and handling of transfer completion (the synchronous model
+ * combines both of these into one). There may be a long delay between
+ * submission and completion, however the asynchronous submission function
+ * is non-blocking so will return control to your application during that
+ * potentially long delay.
+ *
+ * \section asyncabstraction Transfer abstraction
+ *
+ * For the asynchronous I/O, libusb implements the concept of a generic
+ * transfer entity for all types of I/O (control, bulk, interrupt,
+ * isochronous). The generic transfer object must be treated slightly
+ * differently depending on which type of I/O you are performing with it.
+ *
+ * This is represented by the public libusb_transfer structure type.
+ *
+ * \section asynctrf Asynchronous transfers
+ *
+ * We can view asynchronous I/O as a 5 step process:
+ * -# Allocation: allocate a libusb_transfer
+ * -# Filling: populate the libusb_transfer instance with information
+ * about the transfer you wish to perform
+ * -# Submission: ask libusb to submit the transfer
+ * -# Completion handling: examine transfer results in the
+ * libusb_transfer structure
+ * -# Deallocation: clean up resources
+ *
+ *
+ * \subsection asyncalloc Allocation
+ *
+ * This step involves allocating memory for a USB transfer. This is the
+ * generic transfer object mentioned above. At this stage, the transfer
+ * is "blank" with no details about what type of I/O it will be used for.
+ *
+ * Allocation is done with the libusb_alloc_transfer() function. You must use
+ * this function rather than allocating your own transfers.
+ *
+ * \subsection asyncfill Filling
+ *
+ * This step is where you take a previously allocated transfer and fill it
+ * with information to determine the message type and direction, data buffer,
+ * callback function, etc.
+ *
+ * You can either fill the required fields yourself or you can use the
+ * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
+ * and libusb_fill_interrupt_transfer().
+ *
+ * \subsection asyncsubmit Submission
+ *
+ * When you have allocated a transfer and filled it, you can submit it using
+ * libusb_submit_transfer(). This function returns immediately but can be
+ * regarded as firing off the I/O request in the background.
+ *
+ * \subsection asynccomplete Completion handling
+ *
+ * After a transfer has been submitted, one of four things can happen to it:
+ *
+ * - The transfer completes (i.e. some data was transferred)
+ * - The transfer has a timeout and the timeout expires before all data is
+ * transferred
+ * - The transfer fails due to an error
+ * - The transfer is cancelled
+ *
+ * Each of these will cause the user-specified transfer callback function to
+ * be invoked. It is up to the callback function to determine which of the
+ * above actually happened and to act accordingly.
+ *
+ * The user-specified callback is passed a pointer to the libusb_transfer
+ * structure which was used to setup and submit the transfer. At completion
+ * time, libusb has populated this structure with results of the transfer:
+ * success or failure reason, number of bytes of data transferred, etc. See
+ * the libusb_transfer structure documentation for more information.
+ *
+ * Important Note: The user-specified callback is called from an event
+ * handling context. It is therefore important that no calls are made into
+ * libusb that will attempt to perform any event handling. Examples of such
+ * functions are any listed in the \ref libusb_syncio "synchronous API" and any of
+ * the blocking functions that retrieve \ref libusb_desc "USB descriptors".
+ *
+ * \subsection Deallocation
+ *
+ * When a transfer has completed (i.e. the callback function has been invoked),
+ * you are advised to free the transfer (unless you wish to resubmit it, see
+ * below). Transfers are deallocated with libusb_free_transfer().
+ *
+ * It is undefined behaviour to free a transfer which has not completed.
+ *
+ * \section asyncresubmit Resubmission
+ *
+ * You may be wondering why allocation, filling, and submission are all
+ * separated above where they could reasonably be combined into a single
+ * operation.
+ *
+ * The reason for separation is to allow you to resubmit transfers without
+ * having to allocate new ones every time. This is especially useful for
+ * common situations dealing with interrupt endpoints - you allocate one
+ * transfer, fill and submit it, and when it returns with results you just
+ * resubmit it for the next interrupt.
+ *
+ * \section asynccancel Cancellation
+ *
+ * Another advantage of using the asynchronous interface is that you have
+ * the ability to cancel transfers which have not yet completed. This is
+ * done by calling the libusb_cancel_transfer() function.
+ *
+ * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
+ * cancellation actually completes, the transfer's callback function will
+ * be invoked, and the callback function should check the transfer status to
+ * determine that it was cancelled.
+ *
+ * Freeing the transfer after it has been cancelled but before cancellation
+ * has completed will result in undefined behaviour.
+ *
+ * When a transfer is cancelled, some of the data may have been transferred.
+ * libusb will communicate this to you in the transfer callback. Do not assume
+ * that no data was transferred.
+ *
+ * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints
+ *
+ * If your device does not have predictable transfer sizes (or it misbehaves),
+ * your application may submit a request for data on an IN endpoint which is
+ * smaller than the data that the device wishes to send. In some circumstances
+ * this will cause an overflow, which is a nasty condition to deal with. See
+ * the \ref libusb_packetoverflow page for discussion.
+ *
+ * \section asyncctrl Considerations for control transfers
+ *
+ * The libusb_transfer structure is generic and hence does not
+ * include specific fields for the control-specific setup packet structure.
+ *
+ * In order to perform a control transfer, you must place the 8-byte setup
+ * packet at the start of the data buffer. To simplify this, you could
+ * cast the buffer pointer to type struct libusb_control_setup, or you can
+ * use the helper function libusb_fill_control_setup().
+ *
+ * The wLength field placed in the setup packet must be the length you would
+ * expect to be sent in the setup packet: the length of the payload that
+ * follows (or the expected maximum number of bytes to receive). However,
+ * the length field of the libusb_transfer object must be the length of
+ * the data buffer - i.e. it should be wLength plus the size of
+ * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
+ *
+ * If you use the helper functions, this is simplified for you:
+ * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
+ * data you are sending/requesting.
+ * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
+ * request size as the wLength value (i.e. do not include the extra space you
+ * allocated for the control setup).
+ * -# If this is a host-to-device transfer, place the data to be transferred
+ * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
+ * -# Call libusb_fill_control_transfer() to associate the data buffer with
+ * the transfer (and to set the remaining details such as callback and timeout).
+ * - Note that there is no parameter to set the length field of the transfer.
+ * The length is automatically inferred from the wLength field of the setup
+ * packet.
+ * -# Submit the transfer.
+ *
+ * The multi-byte control setup fields (wValue, wIndex and wLength) must
+ * be given in little-endian byte order (the endianness of the USB bus).
+ * Endianness conversion is transparently handled by
+ * libusb_fill_control_setup() which is documented to accept host-endian
+ * values.
+ *
+ * Further considerations are needed when handling transfer completion in
+ * your callback function:
+ * - As you might expect, the setup packet will still be sitting at the start
+ * of the data buffer.
+ * - If this was a device-to-host transfer, the received data will be sitting
+ * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
+ * - The actual_length field of the transfer structure is relative to the
+ * wLength of the setup packet, rather than the size of the data buffer. So,
+ * if your wLength was 4, your transfer's length was 12, then you
+ * should expect an actual_length of 4 to indicate that the data was
+ * transferred in entirity.
+ *
+ * To simplify parsing of setup packets and obtaining the data from the
+ * correct offset, you may wish to use the libusb_control_transfer_get_data()
+ * and libusb_control_transfer_get_setup() functions within your transfer
+ * callback.
+ *
+ * Even though control endpoints do not halt, a completed control transfer
+ * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
+ * request was not supported.
+ *
+ * \section asyncintr Considerations for interrupt transfers
+ *
+ * All interrupt transfers are performed using the polling interval presented
+ * by the bInterval value of the endpoint descriptor.
+ *
+ * \section asynciso Considerations for isochronous transfers
+ *
+ * Isochronous transfers are more complicated than transfers to
+ * non-isochronous endpoints.
+ *
+ * To perform I/O to an isochronous endpoint, allocate the transfer by calling
+ * libusb_alloc_transfer() with an appropriate number of isochronous packets.
+ *
+ * During filling, set \ref libusb_transfer::type "type" to
+ * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
+ * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
+ * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
+ * or equal to the number of packets you requested during allocation.
+ * libusb_alloc_transfer() does not set either of these fields for you, given
+ * that you might not even use the transfer on an isochronous endpoint.
+ *
+ * Next, populate the length field for the first num_iso_packets entries in
+ * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
+ * 5.6.3 of the USB2 specifications describe how the maximum isochronous
+ * packet length is determined by the wMaxPacketSize field in the endpoint
+ * descriptor.
+ * Two functions can help you here:
+ *
+ * - libusb_get_max_iso_packet_size() is an easy way to determine the max
+ * packet size for an isochronous endpoint. Note that the maximum packet
+ * size is actually the maximum number of bytes that can be transmitted in
+ * a single microframe, therefore this function multiplies the maximum number
+ * of bytes per transaction by the number of transaction opportunities per
+ * microframe.
+ * - libusb_set_iso_packet_lengths() assigns the same length to all packets
+ * within a transfer, which is usually what you want.
+ *
+ * For outgoing transfers, you'll obviously fill the buffer and populate the
+ * packet descriptors in hope that all the data gets transferred. For incoming
+ * transfers, you must ensure the buffer has sufficient capacity for
+ * the situation where all packets transfer the full amount of requested data.
+ *
+ * Completion handling requires some extra consideration. The
+ * \ref libusb_transfer::actual_length "actual_length" field of the transfer
+ * is meaningless and should not be examined; instead you must refer to the
+ * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
+ * each individual packet.
+ *
+ * The \ref libusb_transfer::status "status" field of the transfer is also a
+ * little misleading:
+ * - If the packets were submitted and the isochronous data microframes
+ * completed normally, status will have value
+ * \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
+ * "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
+ * delays are not counted as transfer errors; the transfer.status field may
+ * indicate COMPLETED even if some or all of the packets failed. Refer to
+ * the \ref libusb_iso_packet_descriptor::status "status" field of each
+ * individual packet to determine packet failures.
+ * - The status field will have value
+ * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
+ * "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
+ * - Other transfer status codes occur with normal behaviour.
+ *
+ * The data for each packet will be found at an offset into the buffer that
+ * can be calculated as if each prior packet completed in full. The
+ * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
+ * functions may help you here.
+ *
+ * Note: Some operating systems (e.g. Linux) may impose limits on the
+ * length of individual isochronous packets and/or the total length of the
+ * isochronous transfer. Such limits can be difficult for libusb to detect,
+ * so the library will simply try and submit the transfer as set up by you.
+ * If the transfer fails to submit because it is too large,
+ * libusb_submit_transfer() will return
+ * \ref libusb_error::LIBUSB_ERROR_INVALID_PARAM "LIBUSB_ERROR_INVALID_PARAM".
+ *
+ * \section asyncmem Memory caveats
+ *
+ * In most circumstances, it is not safe to use stack memory for transfer
+ * buffers. This is because the function that fired off the asynchronous
+ * transfer may return before libusb has finished using the buffer, and when
+ * the function returns it's stack gets destroyed. This is true for both
+ * host-to-device and device-to-host transfers.
+ *
+ * The only case in which it is safe to use stack memory is where you can
+ * guarantee that the function owning the stack space for the buffer does not
+ * return until after the transfer's callback function has completed. In every
+ * other case, you need to use heap memory instead.
+ *
+ * \section asyncflags Fine control
+ *
+ * Through using this asynchronous interface, you may find yourself repeating
+ * a few simple operations many times. You can apply a bitwise OR of certain
+ * flags to a transfer to simplify certain things:
+ * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
+ * "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
+ * less than the requested amount of data being marked with status
+ * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
+ * (they would normally be regarded as COMPLETED)
+ * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
+ * "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
+ * buffer when freeing the transfer.
+ * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
+ * "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
+ * transfer after the transfer callback returns.
+ *
+ * \section asyncevent Event handling
+ *
+ * An asynchronous model requires that libusb perform work at various
+ * points in time - namely processing the results of previously-submitted
+ * transfers and invoking the user-supplied callback function.
+ *
+ * This gives rise to the libusb_handle_events() function which your
+ * application must call into when libusb has work do to. This gives libusb
+ * the opportunity to reap pending transfers, invoke callbacks, etc.
+ *
+ * There are 2 different approaches to dealing with libusb_handle_events:
+ *
+ * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
+ * thread.
+ * -# Integrate libusb with your application's main event loop. libusb
+ * exposes a set of file descriptors which allow you to do this.
+ *
+ * The first approach has the big advantage that it will also work on Windows
+ * were libusb' poll API for select / poll integration is not available. So
+ * if you want to support Windows and use the async API, you must use this
+ * approach, see the \ref eventthread "Using an event handling thread" section
+ * below for details.
+ *
+ * If you prefer a single threaded approach with a single central event loop,
+ * see the \ref libusb_poll "polling and timing" section for how to integrate libusb
+ * into your application's main event loop.
+ *
+ * \section eventthread Using an event handling thread
+ *
+ * Lets begin with stating the obvious: If you're going to use a separate
+ * thread for libusb event handling, your callback functions MUST be
+ * threadsafe.
+ *
+ * Other then that doing event handling from a separate thread, is mostly
+ * simple. You can use an event thread function as follows:
+\code
+void *event_thread_func(void *ctx)
+{
+ while (event_thread_run)
+ libusb_handle_events(ctx);
+
+ return NULL;
+}
+\endcode
+ *
+ * There is one caveat though, stopping this thread requires setting the
+ * event_thread_run variable to 0, and after that libusb_handle_events() needs
+ * to return control to event_thread_func. But unless some event happens,
+ * libusb_handle_events() will not return.
+ *
+ * There are 2 different ways of dealing with this, depending on if your
+ * application uses libusb' \ref libusb_hotplug "hotplug" support or not.
+ *
+ * Applications which do not use hotplug support, should not start the event
+ * thread until after their first call to libusb_open(), and should stop the
+ * thread when closing the last open device as follows:
+\code
+void my_close_handle(libusb_device_handle *dev_handle)
+{
+ if (open_devs == 1)
+ event_thread_run = 0;
+
+ libusb_close(dev_handle); // This wakes up libusb_handle_events()
+
+ if (open_devs == 1)
+ pthread_join(event_thread);
+
+ open_devs--;
+}
+\endcode
+ *
+ * Applications using hotplug support should start the thread at program init,
+ * after having successfully called libusb_hotplug_register_callback(), and
+ * should stop the thread at program exit as follows:
+\code
+void my_libusb_exit(void)
+{
+ event_thread_run = 0;
+ libusb_hotplug_deregister_callback(ctx, hotplug_cb_handle); // This wakes up libusb_handle_events()
+ pthread_join(event_thread);
+ libusb_exit(ctx);
+}
+\endcode
+ */
+
+/**
+ * @defgroup libusb_poll Polling and timing
+ *
+ * This page documents libusb's functions for polling events and timing.
+ * These functions are only necessary for users of the
+ * \ref libusb_asyncio "asynchronous API". If you are only using the simpler
+ * \ref libusb_syncio "synchronous API" then you do not need to ever call these
+ * functions.
+ *
+ * The justification for the functionality described here has already been
+ * discussed in the \ref asyncevent "event handling" section of the
+ * asynchronous API documentation. In summary, libusb does not create internal
+ * threads for event processing and hence relies on your application calling
+ * into libusb at certain points in time so that pending events can be handled.
+ *
+ * Your main loop is probably already calling poll() or select() or a
+ * variant on a set of file descriptors for other event sources (e.g. keyboard
+ * button presses, mouse movements, network sockets, etc). You then add
+ * libusb's file descriptors to your poll()/select() calls, and when activity
+ * is detected on such descriptors you know it is time to call
+ * libusb_handle_events().
+ *
+ * There is one final event handling complication. libusb supports
+ * asynchronous transfers which time out after a specified time period.
+ *
+ * On some platforms a timerfd is used, so the timeout handling is just another
+ * fd, on other platforms this requires that libusb is called into at or after
+ * the timeout to handle it. So, in addition to considering libusb's file
+ * descriptors in your main event loop, you must also consider that libusb
+ * sometimes needs to be called into at fixed points in time even when there
+ * is no file descriptor activity, see \ref polltime details.
+ *
+ * In order to know precisely when libusb needs to be called into, libusb
+ * offers you a set of pollable file descriptors and information about when
+ * the next timeout expires.
+ *
+ * If you are using the asynchronous I/O API, you must take one of the two
+ * following options, otherwise your I/O will not complete.
+ *
+ * \section pollsimple The simple option
+ *
+ * If your application revolves solely around libusb and does not need to
+ * handle other event sources, you can have a program structure as follows:
+\code
+// initialize libusb
+// find and open device
+// maybe fire off some initial async I/O
+
+while (user_has_not_requested_exit)
+ libusb_handle_events(ctx);
+
+// clean up and exit
+\endcode
+ *
+ * With such a simple main loop, you do not have to worry about managing
+ * sets of file descriptors or handling timeouts. libusb_handle_events() will
+ * handle those details internally.
+ *
+ * \section libusb_pollmain The more advanced option
+ *
+ * \note This functionality is currently only available on Unix-like platforms.
+ * On Windows, libusb_get_pollfds() simply returns NULL. Applications which
+ * want to support Windows are advised to use an \ref eventthread
+ * "event handling thread" instead.
+ *
+ * In more advanced applications, you will already have a main loop which
+ * is monitoring other event sources: network sockets, X11 events, mouse
+ * movements, etc. Through exposing a set of file descriptors, libusb is
+ * designed to cleanly integrate into such main loops.
+ *
+ * In addition to polling file descriptors for the other event sources, you
+ * take a set of file descriptors from libusb and monitor those too. When you
+ * detect activity on libusb's file descriptors, you call
+ * libusb_handle_events_timeout() in non-blocking mode.
+ *
+ * What's more, libusb may also need to handle events at specific moments in
+ * time. No file descriptor activity is generated at these times, so your
+ * own application needs to be continually aware of when the next one of these
+ * moments occurs (through calling libusb_get_next_timeout()), and then it
+ * needs to call libusb_handle_events_timeout() in non-blocking mode when
+ * these moments occur. This means that you need to adjust your
+ * poll()/select() timeout accordingly.
+ *
+ * libusb provides you with a set of file descriptors to poll and expects you
+ * to poll all of them, treating them as a single entity. The meaning of each
+ * file descriptor in the set is an internal implementation detail,
+ * platform-dependent and may vary from release to release. Don't try and
+ * interpret the meaning of the file descriptors, just do as libusb indicates,
+ * polling all of them at once.
+ *
+ * In pseudo-code, you want something that looks like:
+\code
+// initialise libusb
+
+libusb_get_pollfds(ctx)
+while (user has not requested application exit) {
+ libusb_get_next_timeout(ctx);
+ poll(on libusb file descriptors plus any other event sources of interest,
+ using a timeout no larger than the value libusb just suggested)
+ if (poll() indicated activity on libusb file descriptors)
+ libusb_handle_events_timeout(ctx, &zero_tv);
+ if (time has elapsed to or beyond the libusb timeout)
+ libusb_handle_events_timeout(ctx, &zero_tv);
+ // handle events from other sources here
+}
+
+// clean up and exit
+\endcode
+ *
+ * \subsection polltime Notes on time-based events
+ *
+ * The above complication with having to track time and call into libusb at
+ * specific moments is a bit of a headache. For maximum compatibility, you do
+ * need to write your main loop as above, but you may decide that you can
+ * restrict the supported platforms of your application and get away with
+ * a more simplistic scheme.
+ *
+ * These time-based event complications are \b not required on the following
+ * platforms:
+ * - Darwin
+ * - Linux, provided that the following version requirements are satisfied:
+ * - Linux v2.6.27 or newer, compiled with timerfd support
+ * - glibc v2.9 or newer
+ * - libusb v1.0.5 or newer
+ *
+ * Under these configurations, libusb_get_next_timeout() will \em always return
+ * 0, so your main loop can be simplified to:
+\code
+// initialise libusb
+
+libusb_get_pollfds(ctx)
+while (user has not requested application exit) {
+ poll(on libusb file descriptors plus any other event sources of interest,
+ using any timeout that you like)
+ if (poll() indicated activity on libusb file descriptors)
+ libusb_handle_events_timeout(ctx, &zero_tv);
+ // handle events from other sources here
+}
+
+// clean up and exit
+\endcode
+ *
+ * Do remember that if you simplify your main loop to the above, you will
+ * lose compatibility with some platforms (including legacy Linux platforms,
+ * and any future platforms supported by libusb which may have time-based
+ * event requirements). The resultant problems will likely appear as
+ * strange bugs in your application.
+ *
+ * You can use the libusb_pollfds_handle_timeouts() function to do a runtime
+ * check to see if it is safe to ignore the time-based event complications.
+ * If your application has taken the shortcut of ignoring libusb's next timeout
+ * in your main loop, then you are advised to check the return value of
+ * libusb_pollfds_handle_timeouts() during application startup, and to abort
+ * if the platform does suffer from these timing complications.
+ *
+ * \subsection fdsetchange Changes in the file descriptor set
+ *
+ * The set of file descriptors that libusb uses as event sources may change
+ * during the life of your application. Rather than having to repeatedly
+ * call libusb_get_pollfds(), you can set up notification functions for when
+ * the file descriptor set changes using libusb_set_pollfd_notifiers().
+ *
+ * \subsection mtissues Multi-threaded considerations
+ *
+ * Unfortunately, the situation is complicated further when multiple threads
+ * come into play. If two threads are monitoring the same file descriptors,
+ * the fact that only one thread will be woken up when an event occurs causes
+ * some headaches.
+ *
+ * The events lock, event waiters lock, and libusb_handle_events_locked()
+ * entities are added to solve these problems. You do not need to be concerned
+ * with these entities otherwise.
+ *
+ * See the extra documentation: \ref libusb_mtasync
+ */
+
+/** \page libusb_mtasync Multi-threaded applications and asynchronous I/O
+ *
+ * libusb is a thread-safe library, but extra considerations must be applied
+ * to applications which interact with libusb from multiple threads.
+ *
+ * The underlying issue that must be addressed is that all libusb I/O
+ * revolves around monitoring file descriptors through the poll()/select()
+ * system calls. This is directly exposed at the
+ * \ref libusb_asyncio "asynchronous interface" but it is important to note that the
+ * \ref libusb_syncio "synchronous interface" is implemented on top of the
+ * asynchonrous interface, therefore the same considerations apply.
+ *
+ * The issue is that if two or more threads are concurrently calling poll()
+ * or select() on libusb's file descriptors then only one of those threads
+ * will be woken up when an event arrives. The others will be completely
+ * oblivious that anything has happened.
+ *
+ * Consider the following pseudo-code, which submits an asynchronous transfer
+ * then waits for its completion. This style is one way you could implement a
+ * synchronous interface on top of the asynchronous interface (and libusb
+ * does something similar, albeit more advanced due to the complications
+ * explained on this page).
+ *
+\code
+void cb(struct libusb_transfer *transfer)
+{
+ int *completed = transfer->user_data;
+ *completed = 1;
+}
+
+void myfunc() {
+ struct libusb_transfer *transfer;
+ unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE] __attribute__ ((aligned (2)));
+ int completed = 0;
+
+ transfer = libusb_alloc_transfer(0);
+ libusb_fill_control_setup(buffer,
+ LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
+ libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
+ libusb_submit_transfer(transfer);
+
+ while (!completed) {
+ poll(libusb file descriptors, 120*1000);
+ if (poll indicates activity)
+ libusb_handle_events_timeout(ctx, &zero_tv);
+ }
+ printf("completed!");
+ // other code here
+}
+\endcode
+ *
+ * Here we are serializing completion of an asynchronous event
+ * against a condition - the condition being completion of a specific transfer.
+ * The poll() loop has a long timeout to minimize CPU usage during situations
+ * when nothing is happening (it could reasonably be unlimited).
+ *
+ * If this is the only thread that is polling libusb's file descriptors, there
+ * is no problem: there is no danger that another thread will swallow up the
+ * event that we are interested in. On the other hand, if there is another
+ * thread polling the same descriptors, there is a chance that it will receive
+ * the event that we were interested in. In this situation, myfunc()
+ * will only realise that the transfer has completed on the next iteration of
+ * the loop, up to 120 seconds later. Clearly a two-minute delay is
+ * undesirable, and don't even think about using short timeouts to circumvent
+ * this issue!
+ *
+ * The solution here is to ensure that no two threads are ever polling the
+ * file descriptors at the same time. A naive implementation of this would
+ * impact the capabilities of the library, so libusb offers the scheme
+ * documented below to ensure no loss of functionality.
+ *
+ * Before we go any further, it is worth mentioning that all libusb-wrapped
+ * event handling procedures fully adhere to the scheme documented below.
+ * This includes libusb_handle_events() and its variants, and all the
+ * synchronous I/O functions - libusb hides this headache from you.
+ *
+ * \section Using libusb_handle_events() from multiple threads
+ *
+ * Even when only using libusb_handle_events() and synchronous I/O functions,
+ * you can still have a race condition. You might be tempted to solve the
+ * above with libusb_handle_events() like so:
+ *
+\code
+ libusb_submit_transfer(transfer);
+
+ while (!completed) {
+ libusb_handle_events(ctx);
+ }
+ printf("completed!");
+\endcode
+ *
+ * This however has a race between the checking of completed and
+ * libusb_handle_events() acquiring the events lock, so another thread
+ * could have completed the transfer, resulting in this thread hanging
+ * until either a timeout or another event occurs. See also commit
+ * 6696512aade99bb15d6792af90ae329af270eba6 which fixes this in the
+ * synchronous API implementation of libusb.
+ *
+ * Fixing this race requires checking the variable completed only after
+ * taking the event lock, which defeats the concept of just calling
+ * libusb_handle_events() without worrying about locking. This is why
+ * libusb-1.0.9 introduces the new libusb_handle_events_timeout_completed()
+ * and libusb_handle_events_completed() functions, which handles doing the
+ * completion check for you after they have acquired the lock:
+ *
+\code
+ libusb_submit_transfer(transfer);
+
+ while (!completed) {
+ libusb_handle_events_completed(ctx, &completed);
+ }
+ printf("completed!");
+\endcode
+ *
+ * This nicely fixes the race in our example. Note that if all you want to
+ * do is submit a single transfer and wait for its completion, then using
+ * one of the synchronous I/O functions is much easier.
+ *
+ * \section eventlock The events lock
+ *
+ * The problem is when we consider the fact that libusb exposes file
+ * descriptors to allow for you to integrate asynchronous USB I/O into
+ * existing main loops, effectively allowing you to do some work behind
+ * libusb's back. If you do take libusb's file descriptors and pass them to
+ * poll()/select() yourself, you need to be aware of the associated issues.
+ *
+ * The first concept to be introduced is the events lock. The events lock
+ * is used to serialize threads that want to handle events, such that only
+ * one thread is handling events at any one time.
+ *
+ * You must take the events lock before polling libusb file descriptors,
+ * using libusb_lock_events(). You must release the lock as soon as you have
+ * aborted your poll()/select() loop, using libusb_unlock_events().
+ *
+ * \section threadwait Letting other threads do the work for you
+ *
+ * Although the events lock is a critical part of the solution, it is not
+ * enough on it's own. You might wonder if the following is sufficient...
+\code
+ libusb_lock_events(ctx);
+ while (!completed) {
+ poll(libusb file descriptors, 120*1000);
+ if (poll indicates activity)
+ libusb_handle_events_timeout(ctx, &zero_tv);
+ }
+ libusb_unlock_events(ctx);
+\endcode
+ * ...and the answer is that it is not. This is because the transfer in the
+ * code shown above may take a long time (say 30 seconds) to complete, and
+ * the lock is not released until the transfer is completed.
+ *
+ * Another thread with similar code that wants to do event handling may be
+ * working with a transfer that completes after a few milliseconds. Despite
+ * having such a quick completion time, the other thread cannot check that
+ * status of its transfer until the code above has finished (30 seconds later)
+ * due to contention on the lock.
+ *
+ * To solve this, libusb offers you a mechanism to determine when another
+ * thread is handling events. It also offers a mechanism to block your thread
+ * until the event handling thread has completed an event (and this mechanism
+ * does not involve polling of file descriptors).
+ *
+ * After determining that another thread is currently handling events, you
+ * obtain the event waiters lock using libusb_lock_event_waiters().
+ * You then re-check that some other thread is still handling events, and if
+ * so, you call libusb_wait_for_event().
+ *
+ * libusb_wait_for_event() puts your application to sleep until an event
+ * occurs, or until a thread releases the events lock. When either of these
+ * things happen, your thread is woken up, and should re-check the condition
+ * it was waiting on. It should also re-check that another thread is handling
+ * events, and if not, it should start handling events itself.
+ *
+ * This looks like the following, as pseudo-code:
+\code
+retry:
+if (libusb_try_lock_events(ctx) == 0) {
+ // we obtained the event lock: do our own event handling
+ while (!completed) {
+ if (!libusb_event_handling_ok(ctx)) {
+ libusb_unlock_events(ctx);
+ goto retry;
+ }
+ poll(libusb file descriptors, 120*1000);
+ if (poll indicates activity)
+ libusb_handle_events_locked(ctx, 0);
+ }
+ libusb_unlock_events(ctx);
+} else {
+ // another thread is doing event handling. wait for it to signal us that
+ // an event has completed
+ libusb_lock_event_waiters(ctx);
+
+ while (!completed) {
+ // now that we have the event waiters lock, double check that another
+ // thread is still handling events for us. (it may have ceased handling
+ // events in the time it took us to reach this point)
+ if (!libusb_event_handler_active(ctx)) {
+ // whoever was handling events is no longer doing so, try again
+ libusb_unlock_event_waiters(ctx);
+ goto retry;
+ }
+
+ libusb_wait_for_event(ctx, NULL);
+ }
+ libusb_unlock_event_waiters(ctx);
+}
+printf("completed!\n");
+\endcode
+ *
+ * A naive look at the above code may suggest that this can only support
+ * one event waiter (hence a total of 2 competing threads, the other doing
+ * event handling), because the event waiter seems to have taken the event
+ * waiters lock while waiting for an event. However, the system does support
+ * multiple event waiters, because libusb_wait_for_event() actually drops
+ * the lock while waiting, and reaquires it before continuing.
+ *
+ * We have now implemented code which can dynamically handle situations where
+ * nobody is handling events (so we should do it ourselves), and it can also
+ * handle situations where another thread is doing event handling (so we can
+ * piggyback onto them). It is also equipped to handle a combination of
+ * the two, for example, another thread is doing event handling, but for
+ * whatever reason it stops doing so before our condition is met, so we take
+ * over the event handling.
+ *
+ * Four functions were introduced in the above pseudo-code. Their importance
+ * should be apparent from the code shown above.
+ * -# libusb_try_lock_events() is a non-blocking function which attempts
+ * to acquire the events lock but returns a failure code if it is contended.
+ * -# libusb_event_handling_ok() checks that libusb is still happy for your
+ * thread to be performing event handling. Sometimes, libusb needs to
+ * interrupt the event handler, and this is how you can check if you have
+ * been interrupted. If this function returns 0, the correct behaviour is
+ * for you to give up the event handling lock, and then to repeat the cycle.
+ * The following libusb_try_lock_events() will fail, so you will become an
+ * events waiter. For more information on this, read \ref fullstory below.
+ * -# libusb_handle_events_locked() is a variant of
+ * libusb_handle_events_timeout() that you can call while holding the
+ * events lock. libusb_handle_events_timeout() itself implements similar
+ * logic to the above, so be sure not to call it when you are
+ * "working behind libusb's back", as is the case here.
+ * -# libusb_event_handler_active() determines if someone is currently
+ * holding the events lock
+ *
+ * You might be wondering why there is no function to wake up all threads
+ * blocked on libusb_wait_for_event(). This is because libusb can do this
+ * internally: it will wake up all such threads when someone calls
+ * libusb_unlock_events() or when a transfer completes (at the point after its
+ * callback has returned).
+ *
+ * \subsection fullstory The full story
+ *
+ * The above explanation should be enough to get you going, but if you're
+ * really thinking through the issues then you may be left with some more
+ * questions regarding libusb's internals. If you're curious, read on, and if
+ * not, skip to the next section to avoid confusing yourself!
+ *
+ * The immediate question that may spring to mind is: what if one thread
+ * modifies the set of file descriptors that need to be polled while another
+ * thread is doing event handling?
+ *
+ * There are 2 situations in which this may happen.
+ * -# libusb_open() will add another file descriptor to the poll set,
+ * therefore it is desirable to interrupt the event handler so that it
+ * restarts, picking up the new descriptor.
+ * -# libusb_close() will remove a file descriptor from the poll set. There
+ * are all kinds of race conditions that could arise here, so it is
+ * important that nobody is doing event handling at this time.
+ *
+ * libusb handles these issues internally, so application developers do not
+ * have to stop their event handlers while opening/closing devices. Here's how
+ * it works, focusing on the libusb_close() situation first:
+ *
+ * -# During initialization, libusb opens an internal pipe, and it adds the read
+ * end of this pipe to the set of file descriptors to be polled.
+ * -# During libusb_close(), libusb writes some dummy data on this event pipe.
+ * This immediately interrupts the event handler. libusb also records
+ * internally that it is trying to interrupt event handlers for this
+ * high-priority event.
+ * -# At this point, some of the functions described above start behaving
+ * differently:
+ * - libusb_event_handling_ok() starts returning 1, indicating that it is NOT
+ * OK for event handling to continue.
+ * - libusb_try_lock_events() starts returning 1, indicating that another
+ * thread holds the event handling lock, even if the lock is uncontended.
+ * - libusb_event_handler_active() starts returning 1, indicating that
+ * another thread is doing event handling, even if that is not true.
+ * -# The above changes in behaviour result in the event handler stopping and
+ * giving up the events lock very quickly, giving the high-priority
+ * libusb_close() operation a "free ride" to acquire the events lock. All
+ * threads that are competing to do event handling become event waiters.
+ * -# With the events lock held inside libusb_close(), libusb can safely remove
+ * a file descriptor from the poll set, in the safety of knowledge that
+ * nobody is polling those descriptors or trying to access the poll set.
+ * -# After obtaining the events lock, the close operation completes very
+ * quickly (usually a matter of milliseconds) and then immediately releases
+ * the events lock.
+ * -# At the same time, the behaviour of libusb_event_handling_ok() and friends
+ * reverts to the original, documented behaviour.
+ * -# The release of the events lock causes the threads that are waiting for
+ * events to be woken up and to start competing to become event handlers
+ * again. One of them will succeed; it will then re-obtain the list of poll
+ * descriptors, and USB I/O will then continue as normal.
+ *
+ * libusb_open() is similar, and is actually a more simplistic case. Upon a
+ * call to libusb_open():
+ *
+ * -# The device is opened and a file descriptor is added to the poll set.
+ * -# libusb sends some dummy data on the event pipe, and records that it
+ * is trying to modify the poll descriptor set.
+ * -# The event handler is interrupted, and the same behaviour change as for
+ * libusb_close() takes effect, causing all event handling threads to become
+ * event waiters.
+ * -# The libusb_open() implementation takes its free ride to the events lock.
+ * -# Happy that it has successfully paused the events handler, libusb_open()
+ * releases the events lock.
+ * -# The event waiter threads are all woken up and compete to become event
+ * handlers again. The one that succeeds will obtain the list of poll
+ * descriptors again, which will include the addition of the new device.
+ *
+ * \subsection concl Closing remarks
+ *
+ * The above may seem a little complicated, but hopefully I have made it clear
+ * why such complications are necessary. Also, do not forget that this only
+ * applies to applications that take libusb's file descriptors and integrate
+ * them into their own polling loops.
+ *
+ * You may decide that it is OK for your multi-threaded application to ignore
+ * some of the rules and locks detailed above, because you don't think that
+ * two threads can ever be polling the descriptors at the same time. If that
+ * is the case, then that's good news for you because you don't have to worry.
+ * But be careful here; remember that the synchronous I/O functions do event
+ * handling internally. If you have one thread doing event handling in a loop
+ * (without implementing the rules and locking semantics documented above)
+ * and another trying to send a synchronous USB transfer, you will end up with
+ * two threads monitoring the same descriptors, and the above-described
+ * undesirable behaviour occurring. The solution is for your polling thread to
+ * play by the rules; the synchronous I/O functions do so, and this will result
+ * in them getting along in perfect harmony.
+ *
+ * If you do have a dedicated thread doing event handling, it is perfectly
+ * legal for it to take the event handling lock for long periods of time. Any
+ * synchronous I/O functions you call from other threads will transparently
+ * fall back to the "event waiters" mechanism detailed above. The only
+ * consideration that your event handling thread must apply is the one related
+ * to libusb_event_handling_ok(): you must call this before every poll(), and
+ * give up the events lock if instructed.
+ */
+
+int usbi_io_init(struct libusb_context *ctx)
+{
+ int r;
+
+ usbi_mutex_init(&ctx->flying_transfers_lock);
+ usbi_mutex_init(&ctx->events_lock);
+ usbi_mutex_init(&ctx->event_waiters_lock);
+ usbi_cond_init(&ctx->event_waiters_cond);
+ usbi_mutex_init(&ctx->event_data_lock);
+ usbi_tls_key_create(&ctx->event_handling_key);
+ list_init(&ctx->flying_transfers);
+ list_init(&ctx->ipollfds);
+ list_init(&ctx->hotplug_msgs);
+ list_init(&ctx->completed_transfers);
+
+ /* FIXME should use an eventfd on kernels that support it */
+ r = usbi_pipe(ctx->event_pipe);
+ if (r < 0) {
+ r = LIBUSB_ERROR_OTHER;
+ goto err;
+ }
+
+ r = usbi_add_pollfd(ctx, ctx->event_pipe[0], POLLIN);
+ if (r < 0)
+ goto err_close_pipe;
+
+#ifdef USBI_TIMERFD_AVAILABLE
+ ctx->timerfd = timerfd_create(usbi_backend.get_timerfd_clockid(),
+ TFD_NONBLOCK | TFD_CLOEXEC);
+ if (ctx->timerfd >= 0) {
+ usbi_dbg("using timerfd for timeouts");
+ r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN);
+ if (r < 0)
+ goto err_close_timerfd;
+ } else {
+ usbi_dbg("timerfd not available (code %d error %d)", ctx->timerfd, errno);
+ ctx->timerfd = -1;
+ }
+#endif
+
+ return 0;
+
+#ifdef USBI_TIMERFD_AVAILABLE
+err_close_timerfd:
+ close(ctx->timerfd);
+ usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
+#endif
+err_close_pipe:
+ usbi_close(ctx->event_pipe[0]);
+ usbi_close(ctx->event_pipe[1]);
+err:
+ usbi_mutex_destroy(&ctx->flying_transfers_lock);
+ usbi_mutex_destroy(&ctx->events_lock);
+ usbi_mutex_destroy(&ctx->event_waiters_lock);
+ usbi_cond_destroy(&ctx->event_waiters_cond);
+ usbi_mutex_destroy(&ctx->event_data_lock);
+ usbi_tls_key_delete(ctx->event_handling_key);
+ return r;
+}
+
+void usbi_io_exit(struct libusb_context *ctx)
+{
+ usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
+ usbi_close(ctx->event_pipe[0]);
+ usbi_close(ctx->event_pipe[1]);
+#ifdef USBI_TIMERFD_AVAILABLE
+ if (usbi_using_timerfd(ctx)) {
+ usbi_remove_pollfd(ctx, ctx->timerfd);
+ close(ctx->timerfd);
+ }
+#endif
+ usbi_mutex_destroy(&ctx->flying_transfers_lock);
+ usbi_mutex_destroy(&ctx->events_lock);
+ usbi_mutex_destroy(&ctx->event_waiters_lock);
+ usbi_cond_destroy(&ctx->event_waiters_cond);
+ usbi_mutex_destroy(&ctx->event_data_lock);
+ usbi_tls_key_delete(ctx->event_handling_key);
+ if (ctx->pollfds)
+ free(ctx->pollfds);
+}
+
+static int calculate_timeout(struct usbi_transfer *transfer)
+{
+ int r;
+ struct timespec current_time;
+ unsigned int timeout =
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
+
+ if (!timeout) {
+ timerclear(&transfer->timeout);
+ return 0;
+ }
+
+ r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, ¤t_time);
+ if (r < 0) {
+ usbi_err(ITRANSFER_CTX(transfer),
+ "failed to read monotonic clock, errno=%d", errno);
+ return r;
+ }
+
+ current_time.tv_sec += timeout / 1000;
+ current_time.tv_nsec += (timeout % 1000) * 1000000;
+
+ while (current_time.tv_nsec >= 1000000000) {
+ current_time.tv_nsec -= 1000000000;
+ current_time.tv_sec++;
+ }
+
+ TIMESPEC_TO_TIMEVAL(&transfer->timeout, ¤t_time);
+ return 0;
+}
+
+/** \ingroup libusb_asyncio
+ * Allocate a libusb transfer with a specified number of isochronous packet
+ * descriptors. The returned transfer is pre-initialized for you. When the new
+ * transfer is no longer needed, it should be freed with
+ * libusb_free_transfer().
+ *
+ * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
+ * interrupt) should specify an iso_packets count of zero.
+ *
+ * For transfers intended for isochronous endpoints, specify an appropriate
+ * number of packet descriptors to be allocated as part of the transfer.
+ * The returned transfer is not specially initialized for isochronous I/O;
+ * you are still required to set the
+ * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
+ * \ref libusb_transfer::type "type" fields accordingly.
+ *
+ * It is safe to allocate a transfer with some isochronous packets and then
+ * use it on a non-isochronous endpoint. If you do this, ensure that at time
+ * of submission, num_iso_packets is 0 and that type is set appropriately.
+ *
+ * \param iso_packets number of isochronous packet descriptors to allocate
+ * \returns a newly allocated transfer, or NULL on error
+ */
+DEFAULT_VISIBILITY
+struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(
+ int iso_packets)
+{
+ struct libusb_transfer *transfer;
+ size_t os_alloc_size = usbi_backend.transfer_priv_size;
+ size_t alloc_size = sizeof(struct usbi_transfer)
+ + sizeof(struct libusb_transfer)
+ + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
+ + os_alloc_size;
+ struct usbi_transfer *itransfer = calloc(1, alloc_size);
+ if (!itransfer)
+ return NULL;
+
+ itransfer->num_iso_packets = iso_packets;
+ usbi_mutex_init(&itransfer->lock);
+ transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+ usbi_dbg("transfer %p", transfer);
+ return transfer;
+}
+
+/** \ingroup libusb_asyncio
+ * Free a transfer structure. This should be called for all transfers
+ * allocated with libusb_alloc_transfer().
+ *
+ * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
+ * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
+ * non-NULL, this function will also free the transfer buffer using the
+ * standard system memory allocator (e.g. free()).
+ *
+ * It is legal to call this function with a NULL transfer. In this case,
+ * the function will simply return safely.
+ *
+ * It is not legal to free an active transfer (one which has been submitted
+ * and has not yet completed).
+ *
+ * \param transfer the transfer to free
+ */
+void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
+{
+ struct usbi_transfer *itransfer;
+ if (!transfer)
+ return;
+
+ usbi_dbg("transfer %p", transfer);
+ if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
+ free(transfer->buffer);
+
+ itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
+ usbi_mutex_destroy(&itransfer->lock);
+ free(itransfer);
+}
+
+#ifdef USBI_TIMERFD_AVAILABLE
+static int disarm_timerfd(struct libusb_context *ctx)
+{
+ const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
+ int r;
+
+ usbi_dbg("");
+ r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
+ if (r < 0)
+ return LIBUSB_ERROR_OTHER;
+ else
+ return 0;
+}
+
+/* iterates through the flying transfers, and rearms the timerfd based on the
+ * next upcoming timeout.
+ * must be called with flying_list locked.
+ * returns 0 on success or a LIBUSB_ERROR code on failure.
+ */
+static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
+{
+ struct usbi_transfer *transfer;
+
+ list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
+ struct timeval *cur_tv = &transfer->timeout;
+
+ /* if we've reached transfers of infinite timeout, then we have no
+ * arming to do */
+ if (!timerisset(cur_tv))
+ goto disarm;
+
+ /* act on first transfer that has not already been handled */
+ if (!(transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))) {
+ int r;
+ const struct itimerspec it = { {0, 0},
+ { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
+ usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
+ r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
+ if (r < 0)
+ return LIBUSB_ERROR_OTHER;
+ return 0;
+ }
+ }
+
+disarm:
+ return disarm_timerfd(ctx);
+}
+#else
+static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
+{
+ UNUSED(ctx);
+ return 0;
+}
+#endif
+
+/* add a transfer to the (timeout-sorted) active transfers list.
+ * This function will return non 0 if fails to update the timer,
+ * in which case the transfer is *not* on the flying_transfers list. */
+static int add_to_flying_list(struct usbi_transfer *transfer)
+{
+ struct usbi_transfer *cur;
+ struct timeval *timeout = &transfer->timeout;
+ struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+ int r;
+ int first = 1;
+
+ r = calculate_timeout(transfer);
+ if (r)
+ return r;
+
+ /* if we have no other flying transfers, start the list with this one */
+ if (list_empty(&ctx->flying_transfers)) {
+ list_add(&transfer->list, &ctx->flying_transfers);
+ goto out;
+ }
+
+ /* if we have infinite timeout, append to end of list */
+ if (!timerisset(timeout)) {
+ list_add_tail(&transfer->list, &ctx->flying_transfers);
+ /* first is irrelevant in this case */
+ goto out;
+ }
+
+ /* otherwise, find appropriate place in list */
+ list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
+ /* find first timeout that occurs after the transfer in question */
+ struct timeval *cur_tv = &cur->timeout;
+
+ if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
+ (cur_tv->tv_sec == timeout->tv_sec &&
+ cur_tv->tv_usec > timeout->tv_usec)) {
+ list_add_tail(&transfer->list, &cur->list);
+ goto out;
+ }
+ first = 0;
+ }
+ /* first is 0 at this stage (list not empty) */
+
+ /* otherwise we need to be inserted at the end */
+ list_add_tail(&transfer->list, &ctx->flying_transfers);
+out:
+#ifdef USBI_TIMERFD_AVAILABLE
+ if (first && usbi_using_timerfd(ctx) && timerisset(timeout)) {
+ /* if this transfer has the lowest timeout of all active transfers,
+ * rearm the timerfd with this transfer's timeout */
+ const struct itimerspec it = { {0, 0},
+ { timeout->tv_sec, timeout->tv_usec * 1000 } };
+ usbi_dbg("arm timerfd for timeout in %dms (first in line)",
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
+ r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
+ if (r < 0) {
+ usbi_warn(ctx, "failed to arm first timerfd (errno %d)", errno);
+ r = LIBUSB_ERROR_OTHER;
+ }
+ }
+#else
+ UNUSED(first);
+#endif
+
+ if (r)
+ list_del(&transfer->list);
+
+ return r;
+}
+
+/* remove a transfer from the active transfers list.
+ * This function will *always* remove the transfer from the
+ * flying_transfers list. It will return a LIBUSB_ERROR code
+ * if it fails to update the timer for the next timeout. */
+static int remove_from_flying_list(struct usbi_transfer *transfer)
+{
+ struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+ int rearm_timerfd;
+ int r = 0;
+
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+ rearm_timerfd = (timerisset(&transfer->timeout) &&
+ list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == transfer);
+ list_del(&transfer->list);
+ if (usbi_using_timerfd(ctx) && rearm_timerfd)
+ r = arm_timerfd_for_next_timeout(ctx);
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+
+ return r;
+}
+
+/** \ingroup libusb_asyncio
+ * Submit a transfer. This function will fire off the USB transfer and then
+ * return immediately.
+ *
+ * \param transfer the transfer to submit
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted.
+ * \returns LIBUSB_ERROR_NOT_SUPPORTED if the transfer flags are not supported
+ * by the operating system.
+ * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
+ * the operating system and/or hardware can support
+ * \returns another LIBUSB_ERROR code on other failure
+ */
+int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
+{
+ struct usbi_transfer *itransfer =
+ LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
+ struct libusb_context *ctx = TRANSFER_CTX(transfer);
+ int r;
+
+ usbi_dbg("transfer %p", transfer);
+
+ /*
+ * Important note on locking, this function takes / releases locks
+ * in the following order:
+ * take flying_transfers_lock
+ * take itransfer->lock
+ * clear transfer
+ * add to flying_transfers list
+ * release flying_transfers_lock
+ * submit transfer
+ * release itransfer->lock
+ * if submit failed:
+ * take flying_transfers_lock
+ * remove from flying_transfers list
+ * release flying_transfers_lock
+ *
+ * Note that it takes locks in the order a-b and then releases them
+ * in the same order a-b. This is somewhat unusual but not wrong,
+ * release order is not important as long as *all* locks are released
+ * before re-acquiring any locks.
+ *
+ * This means that the ordering of first releasing itransfer->lock
+ * and then re-acquiring the flying_transfers_list on error is
+ * important and must not be changed!
+ *
+ * This is done this way because when we take both locks we must always
+ * take flying_transfers_lock first to avoid ab-ba style deadlocks with
+ * the timeout handling and usbi_handle_disconnect paths.
+ *
+ * And we cannot release itransfer->lock before the submission is
+ * complete otherwise timeout handling for transfers with short
+ * timeouts may run before submission.
+ */
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+ usbi_mutex_lock(&itransfer->lock);
+ if (itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT) {
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+ usbi_mutex_unlock(&itransfer->lock);
+ return LIBUSB_ERROR_BUSY;
+ }
+ itransfer->transferred = 0;
+ itransfer->state_flags = 0;
+ itransfer->timeout_flags = 0;
+ r = add_to_flying_list(itransfer);
+ if (r) {
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+ usbi_mutex_unlock(&itransfer->lock);
+ return r;
+ }
+ /*
+ * We must release the flying transfers lock here, because with
+ * some backends the submit_transfer method is synchroneous.
+ */
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+
+ r = usbi_backend.submit_transfer(itransfer);
+ if (r == LIBUSB_SUCCESS) {
+ itransfer->state_flags |= USBI_TRANSFER_IN_FLIGHT;
+ /* keep a reference to this device */
+ libusb_ref_device(transfer->dev_handle->dev);
+ }
+ usbi_mutex_unlock(&itransfer->lock);
+
+ if (r != LIBUSB_SUCCESS)
+ remove_from_flying_list(itransfer);
+
+ return r;
+}
+
+/** \ingroup libusb_asyncio
+ * Asynchronously cancel a previously submitted transfer.
+ * This function returns immediately, but this does not indicate cancellation
+ * is complete. Your callback function will be invoked at some later time
+ * with a transfer status of
+ * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
+ * "LIBUSB_TRANSFER_CANCELLED."
+ *
+ * \param transfer the transfer to cancel
+ * \returns 0 on success
+ * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is not in progress,
+ * already complete, or already cancelled.
+ * \returns a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
+{
+ struct usbi_transfer *itransfer =
+ LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
+ int r;
+
+ usbi_dbg("transfer %p", transfer );
+ usbi_mutex_lock(&itransfer->lock);
+ if (!(itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT)
+ || (itransfer->state_flags & USBI_TRANSFER_CANCELLING)) {
+ r = LIBUSB_ERROR_NOT_FOUND;
+ goto out;
+ }
+ r = usbi_backend.cancel_transfer(itransfer);
+ if (r < 0) {
+ if (r != LIBUSB_ERROR_NOT_FOUND &&
+ r != LIBUSB_ERROR_NO_DEVICE)
+ usbi_err(TRANSFER_CTX(transfer),
+ "cancel transfer failed error %d", r);
+ else
+ usbi_dbg("cancel transfer failed error %d", r);
+
+ if (r == LIBUSB_ERROR_NO_DEVICE)
+ itransfer->state_flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
+ }
+
+ itransfer->state_flags |= USBI_TRANSFER_CANCELLING;
+
+out:
+ usbi_mutex_unlock(&itransfer->lock);
+ return r;
+}
+
+/** \ingroup libusb_asyncio
+ * Set a transfers bulk stream id. Note users are advised to use
+ * libusb_fill_bulk_stream_transfer() instead of calling this function
+ * directly.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param transfer the transfer to set the stream id for
+ * \param stream_id the stream id to set
+ * \see libusb_alloc_streams()
+ */
+void API_EXPORTED libusb_transfer_set_stream_id(
+ struct libusb_transfer *transfer, uint32_t stream_id)
+{
+ struct usbi_transfer *itransfer =
+ LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
+
+ itransfer->stream_id = stream_id;
+}
+
+/** \ingroup libusb_asyncio
+ * Get a transfers bulk stream id.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param transfer the transfer to get the stream id for
+ * \returns the stream id for the transfer
+ */
+uint32_t API_EXPORTED libusb_transfer_get_stream_id(
+ struct libusb_transfer *transfer)
+{
+ struct usbi_transfer *itransfer =
+ LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
+
+ return itransfer->stream_id;
+}
+
+/* Handle completion of a transfer (completion might be an error condition).
+ * This will invoke the user-supplied callback function, which may end up
+ * freeing the transfer. Therefore you cannot use the transfer structure
+ * after calling this function, and you should free all backend-specific
+ * data before calling it.
+ * Do not call this function with the usbi_transfer lock held. User-specified
+ * callback functions may attempt to directly resubmit the transfer, which
+ * will attempt to take the lock. */
+int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
+ enum libusb_transfer_status status)
+{
+ struct libusb_transfer *transfer =
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+ struct libusb_device_handle *dev_handle = transfer->dev_handle;
+ uint8_t flags;
+ int r;
+
+ r = remove_from_flying_list(itransfer);
+ if (r < 0)
+ usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout, errno=%d", errno);
+
+ usbi_mutex_lock(&itransfer->lock);
+ itransfer->state_flags &= ~USBI_TRANSFER_IN_FLIGHT;
+ usbi_mutex_unlock(&itransfer->lock);
+
+ if (status == LIBUSB_TRANSFER_COMPLETED
+ && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
+ int rqlen = transfer->length;
+ if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
+ rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
+ if (rqlen != itransfer->transferred) {
+ usbi_dbg("interpreting short transfer as error");
+ status = LIBUSB_TRANSFER_ERROR;
+ }
+ }
+
+ flags = transfer->flags;
+ transfer->status = status;
+ transfer->actual_length = itransfer->transferred;
+ usbi_dbg("transfer %p has callback %p", transfer, transfer->callback);
+ if (transfer->callback)
+ transfer->callback(transfer);
+ /* transfer might have been freed by the above call, do not use from
+ * this point. */
+ if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
+ libusb_free_transfer(transfer);
+ libusb_unref_device(dev_handle->dev);
+ return r;
+}
+
+/* Similar to usbi_handle_transfer_completion() but exclusively for transfers
+ * that were asynchronously cancelled. The same concerns w.r.t. freeing of
+ * transfers exist here.
+ * Do not call this function with the usbi_transfer lock held. User-specified
+ * callback functions may attempt to directly resubmit the transfer, which
+ * will attempt to take the lock. */
+int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
+{
+ struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+ uint8_t timed_out;
+
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+ timed_out = transfer->timeout_flags & USBI_TRANSFER_TIMED_OUT;
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+
+ /* if the URB was cancelled due to timeout, report timeout to the user */
+ if (timed_out) {
+ usbi_dbg("detected timeout cancellation");
+ return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
+ }
+
+ /* otherwise its a normal async cancel */
+ return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
+}
+
+/* Add a completed transfer to the completed_transfers list of the
+ * context and signal the event. The backend's handle_transfer_completion()
+ * function will be called the next time an event handler runs. */
+void usbi_signal_transfer_completion(struct usbi_transfer *transfer)
+{
+ struct libusb_context *ctx = ITRANSFER_CTX(transfer);
+ int pending_events;
+
+ usbi_mutex_lock(&ctx->event_data_lock);
+ pending_events = usbi_pending_events(ctx);
+ list_add_tail(&transfer->completed_list, &ctx->completed_transfers);
+ if (!pending_events)
+ usbi_signal_event(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+}
+
+/** \ingroup libusb_poll
+ * Attempt to acquire the event handling lock. This lock is used to ensure that
+ * only one thread is monitoring libusb event sources at any one time.
+ *
+ * You only need to use this lock if you are developing an application
+ * which calls poll() or select() on libusb's file descriptors directly.
+ * If you stick to libusb's event handling loop functions (e.g.
+ * libusb_handle_events()) then you do not need to be concerned with this
+ * locking.
+ *
+ * While holding this lock, you are trusted to actually be handling events.
+ * If you are no longer handling events, you must call libusb_unlock_events()
+ * as soon as possible.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \returns 0 if the lock was obtained successfully
+ * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
+ * \ref libusb_mtasync
+ */
+int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
+{
+ int r;
+ unsigned int ru;
+ USBI_GET_CONTEXT(ctx);
+
+ /* is someone else waiting to close a device? if so, don't let this thread
+ * start event handling */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ ru = ctx->device_close;
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ if (ru) {
+ usbi_dbg("someone else is closing a device");
+ return 1;
+ }
+
+ r = usbi_mutex_trylock(&ctx->events_lock);
+ if (r)
+ return 1;
+
+ ctx->event_handler_active = 1;
+ return 0;
+}
+
+/** \ingroup libusb_poll
+ * Acquire the event handling lock, blocking until successful acquisition if
+ * it is contended. This lock is used to ensure that only one thread is
+ * monitoring libusb event sources at any one time.
+ *
+ * You only need to use this lock if you are developing an application
+ * which calls poll() or select() on libusb's file descriptors directly.
+ * If you stick to libusb's event handling loop functions (e.g.
+ * libusb_handle_events()) then you do not need to be concerned with this
+ * locking.
+ *
+ * While holding this lock, you are trusted to actually be handling events.
+ * If you are no longer handling events, you must call libusb_unlock_events()
+ * as soon as possible.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \ref libusb_mtasync
+ */
+void API_EXPORTED libusb_lock_events(libusb_context *ctx)
+{
+ USBI_GET_CONTEXT(ctx);
+ usbi_mutex_lock(&ctx->events_lock);
+ ctx->event_handler_active = 1;
+}
+
+/** \ingroup libusb_poll
+ * Release the lock previously acquired with libusb_try_lock_events() or
+ * libusb_lock_events(). Releasing this lock will wake up any threads blocked
+ * on libusb_wait_for_event().
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \ref libusb_mtasync
+ */
+void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
+{
+ USBI_GET_CONTEXT(ctx);
+ ctx->event_handler_active = 0;
+ usbi_mutex_unlock(&ctx->events_lock);
+
+ /* FIXME: perhaps we should be a bit more efficient by not broadcasting
+ * the availability of the events lock when we are modifying pollfds
+ * (check ctx->device_close)? */
+ usbi_mutex_lock(&ctx->event_waiters_lock);
+ usbi_cond_broadcast(&ctx->event_waiters_cond);
+ usbi_mutex_unlock(&ctx->event_waiters_lock);
+}
+
+/** \ingroup libusb_poll
+ * Determine if it is still OK for this thread to be doing event handling.
+ *
+ * Sometimes, libusb needs to temporarily pause all event handlers, and this
+ * is the function you should use before polling file descriptors to see if
+ * this is the case.
+ *
+ * If this function instructs your thread to give up the events lock, you
+ * should just continue the usual logic that is documented in \ref libusb_mtasync.
+ * On the next iteration, your thread will fail to obtain the events lock,
+ * and will hence become an event waiter.
+ *
+ * This function should be called while the events lock is held: you don't
+ * need to worry about the results of this function if your thread is not
+ * the current event handler.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \returns 1 if event handling can start or continue
+ * \returns 0 if this thread must give up the events lock
+ * \ref fullstory "Multi-threaded I/O: the full story"
+ */
+int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
+{
+ unsigned int r;
+ USBI_GET_CONTEXT(ctx);
+
+ /* is someone else waiting to close a device? if so, don't let this thread
+ * continue event handling */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ r = ctx->device_close;
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ if (r) {
+ usbi_dbg("someone else is closing a device");
+ return 0;
+ }
+
+ return 1;
+}
+
+
+/** \ingroup libusb_poll
+ * Determine if an active thread is handling events (i.e. if anyone is holding
+ * the event handling lock).
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \returns 1 if a thread is handling events
+ * \returns 0 if there are no threads currently handling events
+ * \ref libusb_mtasync
+ */
+int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
+{
+ unsigned int r;
+ USBI_GET_CONTEXT(ctx);
+
+ /* is someone else waiting to close a device? if so, don't let this thread
+ * start event handling -- indicate that event handling is happening */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ r = ctx->device_close;
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ if (r) {
+ usbi_dbg("someone else is closing a device");
+ return 1;
+ }
+
+ return ctx->event_handler_active;
+}
+
+/** \ingroup libusb_poll
+ * Interrupt any active thread that is handling events. This is mainly useful
+ * for interrupting a dedicated event handling thread when an application
+ * wishes to call libusb_exit().
+ *
+ * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \ref libusb_mtasync
+ */
+void API_EXPORTED libusb_interrupt_event_handler(libusb_context *ctx)
+{
+ int pending_events;
+ USBI_GET_CONTEXT(ctx);
+
+ usbi_dbg("");
+ usbi_mutex_lock(&ctx->event_data_lock);
+
+ pending_events = usbi_pending_events(ctx);
+ ctx->event_flags |= USBI_EVENT_USER_INTERRUPT;
+ if (!pending_events)
+ usbi_signal_event(ctx);
+
+ usbi_mutex_unlock(&ctx->event_data_lock);
+}
+
+/** \ingroup libusb_poll
+ * Acquire the event waiters lock. This lock is designed to be obtained under
+ * the situation where you want to be aware when events are completed, but
+ * some other thread is event handling so calling libusb_handle_events() is not
+ * allowed.
+ *
+ * You then obtain this lock, re-check that another thread is still handling
+ * events, then call libusb_wait_for_event().
+ *
+ * You only need to use this lock if you are developing an application
+ * which calls poll() or select() on libusb's file descriptors directly,
+ * and may potentially be handling events from 2 threads simultaenously.
+ * If you stick to libusb's event handling loop functions (e.g.
+ * libusb_handle_events()) then you do not need to be concerned with this
+ * locking.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \ref libusb_mtasync
+ */
+void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
+{
+ USBI_GET_CONTEXT(ctx);
+ usbi_mutex_lock(&ctx->event_waiters_lock);
+}
+
+/** \ingroup libusb_poll
+ * Release the event waiters lock.
+ * \param ctx the context to operate on, or NULL for the default context
+ * \ref libusb_mtasync
+ */
+void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
+{
+ USBI_GET_CONTEXT(ctx);
+ usbi_mutex_unlock(&ctx->event_waiters_lock);
+}
+
+/** \ingroup libusb_poll
+ * Wait for another thread to signal completion of an event. Must be called
+ * with the event waiters lock held, see libusb_lock_event_waiters().
+ *
+ * This function will block until any of the following conditions are met:
+ * -# The timeout expires
+ * -# A transfer completes
+ * -# A thread releases the event handling lock through libusb_unlock_events()
+ *
+ * Condition 1 is obvious. Condition 2 unblocks your thread after
+ * the callback for the transfer has completed. Condition 3 is important
+ * because it means that the thread that was previously handling events is no
+ * longer doing so, so if any events are to complete, another thread needs to
+ * step up and start event handling.
+ *
+ * This function releases the event waiters lock before putting your thread
+ * to sleep, and reacquires the lock as it is being woken up.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param tv maximum timeout for this blocking function. A NULL value
+ * indicates unlimited timeout.
+ * \returns 0 after a transfer completes or another thread stops event handling
+ * \returns 1 if the timeout expired
+ * \ref libusb_mtasync
+ */
+int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
+{
+ int r;
+
+ USBI_GET_CONTEXT(ctx);
+ if (tv == NULL) {
+ usbi_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
+ return 0;
+ }
+
+ r = usbi_cond_timedwait(&ctx->event_waiters_cond,
+ &ctx->event_waiters_lock, tv);
+
+ if (r < 0)
+ return r;
+ else
+ return (r == ETIMEDOUT);
+}
+
+static void handle_timeout(struct usbi_transfer *itransfer)
+{
+ struct libusb_transfer *transfer =
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+ int r;
+
+ itransfer->timeout_flags |= USBI_TRANSFER_TIMEOUT_HANDLED;
+ r = libusb_cancel_transfer(transfer);
+ if (r == LIBUSB_SUCCESS)
+ itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
+ else
+ usbi_warn(TRANSFER_CTX(transfer),
+ "async cancel failed %d errno=%d", r, errno);
+}
+
+static int handle_timeouts_locked(struct libusb_context *ctx)
+{
+ int r;
+ struct timespec systime_ts;
+ struct timeval systime;
+ struct usbi_transfer *transfer;
+
+ if (list_empty(&ctx->flying_transfers))
+ return 0;
+
+ /* get current time */
+ r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, &systime_ts);
+ if (r < 0)
+ return r;
+
+ TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
+
+ /* iterate through flying transfers list, finding all transfers that
+ * have expired timeouts */
+ list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
+ struct timeval *cur_tv = &transfer->timeout;
+
+ /* if we've reached transfers of infinite timeout, we're all done */
+ if (!timerisset(cur_tv))
+ return 0;
+
+ /* ignore timeouts we've already handled */
+ if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
+ continue;
+
+ /* if transfer has non-expired timeout, nothing more to do */
+ if ((cur_tv->tv_sec > systime.tv_sec) ||
+ (cur_tv->tv_sec == systime.tv_sec &&
+ cur_tv->tv_usec > systime.tv_usec))
+ return 0;
+
+ /* otherwise, we've got an expired timeout to handle */
+ handle_timeout(transfer);
+ }
+ return 0;
+}
+
+static int handle_timeouts(struct libusb_context *ctx)
+{
+ int r;
+ USBI_GET_CONTEXT(ctx);
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+ r = handle_timeouts_locked(ctx);
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+ return r;
+}
+
+#ifdef USBI_TIMERFD_AVAILABLE
+static int handle_timerfd_trigger(struct libusb_context *ctx)
+{
+ int r;
+
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+
+ /* process the timeout that just happened */
+ r = handle_timeouts_locked(ctx);
+ if (r < 0)
+ goto out;
+
+ /* arm for next timeout*/
+ r = arm_timerfd_for_next_timeout(ctx);
+
+out:
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+ return r;
+}
+#endif
+
+/* do the actual event handling. assumes that no other thread is concurrently
+ * doing the same thing. */
+static int handle_events(struct libusb_context *ctx, struct timeval *tv)
+{
+ int r;
+ struct usbi_pollfd *ipollfd;
+ POLL_NFDS_TYPE nfds = 0;
+ POLL_NFDS_TYPE internal_nfds;
+ struct pollfd *fds = NULL;
+ int i = -1;
+ int timeout_ms;
+
+ /* prevent attempts to recursively handle events (e.g. calling into
+ * libusb_handle_events() from within a hotplug or transfer callback) */
+ if (usbi_handling_events(ctx))
+ return LIBUSB_ERROR_BUSY;
+ usbi_start_event_handling(ctx);
+
+ /* there are certain fds that libusb uses internally, currently:
+ *
+ * 1) event pipe
+ * 2) timerfd
+ *
+ * the backend will never need to attempt to handle events on these fds, so
+ * we determine how many fds are in use internally for this context and when
+ * handle_events() is called in the backend, the pollfd list and count will
+ * be adjusted to skip over these internal fds */
+ if (usbi_using_timerfd(ctx))
+ internal_nfds = 2;
+ else
+ internal_nfds = 1;
+
+ /* only reallocate the poll fds when the list of poll fds has been modified
+ * since the last poll, otherwise reuse them to save the additional overhead */
+ usbi_mutex_lock(&ctx->event_data_lock);
+ if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED) {
+ usbi_dbg("poll fds modified, reallocating");
+
+ if (ctx->pollfds) {
+ free(ctx->pollfds);
+ ctx->pollfds = NULL;
+ }
+
+ /* sanity check - it is invalid for a context to have fewer than the
+ * required internal fds (memory corruption?) */
+ assert(ctx->pollfds_cnt >= internal_nfds);
+
+ ctx->pollfds = calloc(ctx->pollfds_cnt, sizeof(*ctx->pollfds));
+ if (!ctx->pollfds) {
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ r = LIBUSB_ERROR_NO_MEM;
+ goto done;
+ }
+
+ list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) {
+ struct libusb_pollfd *pollfd = &ipollfd->pollfd;
+ i++;
+ ctx->pollfds[i].fd = pollfd->fd;
+ ctx->pollfds[i].events = pollfd->events;
+ }
+
+ /* reset the flag now that we have the updated list */
+ ctx->event_flags &= ~USBI_EVENT_POLLFDS_MODIFIED;
+
+ /* if no further pending events, clear the event pipe so that we do
+ * not immediately return from poll */
+ if (!usbi_pending_events(ctx))
+ usbi_clear_event(ctx);
+ }
+ fds = ctx->pollfds;
+ nfds = ctx->pollfds_cnt;
+ usbi_mutex_unlock(&ctx->event_data_lock);
+
+ timeout_ms = (int)(tv->tv_sec * 1000) + (tv->tv_usec / 1000);
+
+ /* round up to next millisecond */
+ if (tv->tv_usec % 1000)
+ timeout_ms++;
+
+ usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
+ r = usbi_poll(fds, nfds, timeout_ms);
+ usbi_dbg("poll() returned %d", r);
+ if (r == 0) {
+ r = handle_timeouts(ctx);
+ goto done;
+ } else if (r == -1 && errno == EINTR) {
+ r = LIBUSB_ERROR_INTERRUPTED;
+ goto done;
+ } else if (r < 0) {
+ usbi_err(ctx, "poll failed %d err=%d", r, errno);
+ r = LIBUSB_ERROR_IO;
+ goto done;
+ }
+
+ /* fds[0] is always the event pipe */
+ if (fds[0].revents) {
+ struct list_head hotplug_msgs;
+ struct usbi_transfer *itransfer;
+ int hotplug_cb_deregistered = 0;
+ int ret = 0;
+
+ list_init(&hotplug_msgs);
+
+ usbi_dbg("caught a fish on the event pipe");
+
+ /* take the the event data lock while processing events */
+ usbi_mutex_lock(&ctx->event_data_lock);
+
+ /* check if someone added a new poll fd */
+ if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED)
+ usbi_dbg("someone updated the poll fds");
+
+ if (ctx->event_flags & USBI_EVENT_USER_INTERRUPT) {
+ usbi_dbg("someone purposely interrupted");
+ ctx->event_flags &= ~USBI_EVENT_USER_INTERRUPT;
+ }
+
+ if (ctx->event_flags & USBI_EVENT_HOTPLUG_CB_DEREGISTERED) {
+ usbi_dbg("someone unregistered a hotplug cb");
+ ctx->event_flags &= ~USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
+ hotplug_cb_deregistered = 1;
+ }
+
+ /* check if someone is closing a device */
+ if (ctx->device_close)
+ usbi_dbg("someone is closing a device");
+
+ /* check for any pending hotplug messages */
+ if (!list_empty(&ctx->hotplug_msgs)) {
+ usbi_dbg("hotplug message received");
+ list_cut(&hotplug_msgs, &ctx->hotplug_msgs);
+ }
+
+ /* complete any pending transfers */
+ while (ret == 0 && !list_empty(&ctx->completed_transfers)) {
+ itransfer = list_first_entry(&ctx->completed_transfers, struct usbi_transfer, completed_list);
+ list_del(&itransfer->completed_list);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ ret = usbi_backend.handle_transfer_completion(itransfer);
+ if (ret)
+ usbi_err(ctx, "backend handle_transfer_completion failed with error %d", ret);
+ usbi_mutex_lock(&ctx->event_data_lock);
+ }
+
+ /* if no further pending events, clear the event pipe */
+ if (!usbi_pending_events(ctx))
+ usbi_clear_event(ctx);
+
+ usbi_mutex_unlock(&ctx->event_data_lock);
+
+ if (hotplug_cb_deregistered)
+ usbi_hotplug_deregister(ctx, 0);
+
+ /* process the hotplug messages, if any */
+ while (!list_empty(&hotplug_msgs)) {
+ struct libusb_hotplug_message *message =
+ list_first_entry(&hotplug_msgs, struct libusb_hotplug_message, list);
+
+ usbi_hotplug_match(ctx, message->device, message->event);
+
+ /* the device left, dereference the device */
+ if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message->event)
+ libusb_unref_device(message->device);
+
+ list_del(&message->list);
+ free(message);
+ }
+
+ if (ret) {
+ /* return error code */
+ r = ret;
+ goto done;
+ }
+
+ if (0 == --r)
+ goto done;
+ }
+
+#ifdef USBI_TIMERFD_AVAILABLE
+ /* on timerfd configurations, fds[1] is the timerfd */
+ if (usbi_using_timerfd(ctx) && fds[1].revents) {
+ /* timerfd indicates that a timeout has expired */
+ int ret;
+ usbi_dbg("timerfd triggered");
+
+ ret = handle_timerfd_trigger(ctx);
+ if (ret < 0) {
+ /* return error code */
+ r = ret;
+ goto done;
+ }
+
+ if (0 == --r)
+ goto done;
+ }
+#endif
+
+ r = usbi_backend.handle_events(ctx, fds + internal_nfds, nfds - internal_nfds, r);
+ if (r)
+ usbi_err(ctx, "backend handle_events failed with error %d", r);
+
+done:
+ usbi_end_event_handling(ctx);
+ return r;
+}
+
+/* returns the smallest of:
+ * 1. timeout of next URB
+ * 2. user-supplied timeout
+ * returns 1 if there is an already-expired timeout, otherwise returns 0
+ * and populates out
+ */
+static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
+ struct timeval *out)
+{
+ struct timeval timeout;
+ int r = libusb_get_next_timeout(ctx, &timeout);
+ if (r) {
+ /* timeout already expired? */
+ if (!timerisset(&timeout))
+ return 1;
+
+ /* choose the smallest of next URB timeout or user specified timeout */
+ if (timercmp(&timeout, tv, <))
+ *out = timeout;
+ else
+ *out = *tv;
+ } else {
+ *out = *tv;
+ }
+ return 0;
+}
+
+/** \ingroup libusb_poll
+ * Handle any pending events.
+ *
+ * libusb determines "pending events" by checking if any timeouts have expired
+ * and by checking the set of file descriptors for activity.
+ *
+ * If a zero timeval is passed, this function will handle any already-pending
+ * events and then immediately return in non-blocking style.
+ *
+ * If a non-zero timeval is passed and no events are currently pending, this
+ * function will block waiting for events to handle up until the specified
+ * timeout. If an event arrives or a signal is raised, this function will
+ * return early.
+ *
+ * If the parameter completed is not NULL then after obtaining the event
+ * handling lock this function will return immediately if the integer
+ * pointed to is not 0. This allows for race free waiting for the completion
+ * of a specific transfer.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param tv the maximum time to block waiting for events, or an all zero
+ * timeval struct for non-blocking mode
+ * \param completed pointer to completion integer to check, or NULL
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
+ * \ref libusb_mtasync
+ */
+int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx,
+ struct timeval *tv, int *completed)
+{
+ int r;
+ struct timeval poll_timeout;
+
+ USBI_GET_CONTEXT(ctx);
+ r = get_next_timeout(ctx, tv, &poll_timeout);
+ if (r) {
+ /* timeout already expired */
+ return handle_timeouts(ctx);
+ }
+
+retry:
+ if (libusb_try_lock_events(ctx) == 0) {
+ if (completed == NULL || !*completed) {
+ /* we obtained the event lock: do our own event handling */
+ usbi_dbg("doing our own event handling");
+ r = handle_events(ctx, &poll_timeout);
+ }
+ libusb_unlock_events(ctx);
+ return r;
+ }
+
+ /* another thread is doing event handling. wait for thread events that
+ * notify event completion. */
+ libusb_lock_event_waiters(ctx);
+
+ if (completed && *completed)
+ goto already_done;
+
+ if (!libusb_event_handler_active(ctx)) {
+ /* we hit a race: whoever was event handling earlier finished in the
+ * time it took us to reach this point. try the cycle again. */
+ libusb_unlock_event_waiters(ctx);
+ usbi_dbg("event handler was active but went away, retrying");
+ goto retry;
+ }
+
+ usbi_dbg("another thread is doing event handling");
+ r = libusb_wait_for_event(ctx, &poll_timeout);
+
+already_done:
+ libusb_unlock_event_waiters(ctx);
+
+ if (r < 0)
+ return r;
+ else if (r == 1)
+ return handle_timeouts(ctx);
+ else
+ return 0;
+}
+
+/** \ingroup libusb_poll
+ * Handle any pending events
+ *
+ * Like libusb_handle_events_timeout_completed(), but without the completed
+ * parameter, calling this function is equivalent to calling
+ * libusb_handle_events_timeout_completed() with a NULL completed parameter.
+ *
+ * This function is kept primarily for backwards compatibility.
+ * All new code should call libusb_handle_events_completed() or
+ * libusb_handle_events_timeout_completed() to avoid race conditions.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param tv the maximum time to block waiting for events, or an all zero
+ * timeval struct for non-blocking mode
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_handle_events_timeout(libusb_context *ctx,
+ struct timeval *tv)
+{
+ return libusb_handle_events_timeout_completed(ctx, tv, NULL);
+}
+
+/** \ingroup libusb_poll
+ * Handle any pending events in blocking mode. There is currently a timeout
+ * hardcoded at 60 seconds but we plan to make it unlimited in future. For
+ * finer control over whether this function is blocking or non-blocking, or
+ * for control over the timeout, use libusb_handle_events_timeout_completed()
+ * instead.
+ *
+ * This function is kept primarily for backwards compatibility.
+ * All new code should call libusb_handle_events_completed() or
+ * libusb_handle_events_timeout_completed() to avoid race conditions.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
+ */
+int API_EXPORTED libusb_handle_events(libusb_context *ctx)
+{
+ struct timeval tv;
+ tv.tv_sec = 60;
+ tv.tv_usec = 0;
+ return libusb_handle_events_timeout_completed(ctx, &tv, NULL);
+}
+
+/** \ingroup libusb_poll
+ * Handle any pending events in blocking mode.
+ *
+ * Like libusb_handle_events(), with the addition of a completed parameter
+ * to allow for race free waiting for the completion of a specific transfer.
+ *
+ * See libusb_handle_events_timeout_completed() for details on the completed
+ * parameter.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param completed pointer to completion integer to check, or NULL
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
+ * \ref libusb_mtasync
+ */
+int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx,
+ int *completed)
+{
+ struct timeval tv;
+ tv.tv_sec = 60;
+ tv.tv_usec = 0;
+ return libusb_handle_events_timeout_completed(ctx, &tv, completed);
+}
+
+/** \ingroup libusb_poll
+ * Handle any pending events by polling file descriptors, without checking if
+ * any other threads are already doing so. Must be called with the event lock
+ * held, see libusb_lock_events().
+ *
+ * This function is designed to be called under the situation where you have
+ * taken the event lock and are calling poll()/select() directly on libusb's
+ * file descriptors (as opposed to using libusb_handle_events() or similar).
+ * You detect events on libusb's descriptors, so you then call this function
+ * with a zero timeout value (while still holding the event lock).
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param tv the maximum time to block waiting for events, or zero for
+ * non-blocking mode
+ * \returns 0 on success, or a LIBUSB_ERROR code on failure
+ * \ref libusb_mtasync
+ */
+int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx,
+ struct timeval *tv)
+{
+ int r;
+ struct timeval poll_timeout;
+
+ USBI_GET_CONTEXT(ctx);
+ r = get_next_timeout(ctx, tv, &poll_timeout);
+ if (r) {
+ /* timeout already expired */
+ return handle_timeouts(ctx);
+ }
+
+ return handle_events(ctx, &poll_timeout);
+}
+
+/** \ingroup libusb_poll
+ * Determines whether your application must apply special timing considerations
+ * when monitoring libusb's file descriptors.
+ *
+ * This function is only useful for applications which retrieve and poll
+ * libusb's file descriptors in their own main loop (\ref libusb_pollmain).
+ *
+ * Ordinarily, libusb's event handler needs to be called into at specific
+ * moments in time (in addition to times when there is activity on the file
+ * descriptor set). The usual approach is to use libusb_get_next_timeout()
+ * to learn about when the next timeout occurs, and to adjust your
+ * poll()/select() timeout accordingly so that you can make a call into the
+ * library at that time.
+ *
+ * Some platforms supported by libusb do not come with this baggage - any
+ * events relevant to timing will be represented by activity on the file
+ * descriptor set, and libusb_get_next_timeout() will always return 0.
+ * This function allows you to detect whether you are running on such a
+ * platform.
+ *
+ * Since v1.0.5.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \returns 0 if you must call into libusb at times determined by
+ * libusb_get_next_timeout(), or 1 if all timeout events are handled internally
+ * or through regular activity on the file descriptors.
+ * \ref libusb_pollmain "Polling libusb file descriptors for event handling"
+ */
+int API_EXPORTED libusb_pollfds_handle_timeouts(libusb_context *ctx)
+{
+#if defined(USBI_TIMERFD_AVAILABLE)
+ USBI_GET_CONTEXT(ctx);
+ return usbi_using_timerfd(ctx);
+#else
+ UNUSED(ctx);
+ return 0;
+#endif
+}
+
+/** \ingroup libusb_poll
+ * Determine the next internal timeout that libusb needs to handle. You only
+ * need to use this function if you are calling poll() or select() or similar
+ * on libusb's file descriptors yourself - you do not need to use it if you
+ * are calling libusb_handle_events() or a variant directly.
+ *
+ * You should call this function in your main loop in order to determine how
+ * long to wait for select() or poll() to return results. libusb needs to be
+ * called into at this timeout, so you should use it as an upper bound on
+ * your select() or poll() call.
+ *
+ * When the timeout has expired, call into libusb_handle_events_timeout()
+ * (perhaps in non-blocking mode) so that libusb can handle the timeout.
+ *
+ * This function may return 1 (success) and an all-zero timeval. If this is
+ * the case, it indicates that libusb has a timeout that has already expired
+ * so you should call libusb_handle_events_timeout() or similar immediately.
+ * A return code of 0 indicates that there are no pending timeouts.
+ *
+ * On some platforms, this function will always returns 0 (no pending
+ * timeouts). See \ref polltime.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param tv output location for a relative time against the current
+ * clock in which libusb must be called into in order to process timeout events
+ * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
+ * or LIBUSB_ERROR_OTHER on failure
+ */
+int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
+ struct timeval *tv)
+{
+ struct usbi_transfer *transfer;
+ struct timespec cur_ts;
+ struct timeval cur_tv;
+ struct timeval next_timeout = { 0, 0 };
+ int r;
+
+ USBI_GET_CONTEXT(ctx);
+ if (usbi_using_timerfd(ctx))
+ return 0;
+
+ usbi_mutex_lock(&ctx->flying_transfers_lock);
+ if (list_empty(&ctx->flying_transfers)) {
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+ usbi_dbg("no URBs, no timeout!");
+ return 0;
+ }
+
+ /* find next transfer which hasn't already been processed as timed out */
+ list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
+ if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
+ continue;
+
+ /* if we've reached transfers of infinte timeout, we're done looking */
+ if (!timerisset(&transfer->timeout))
+ break;
+
+ next_timeout = transfer->timeout;
+ break;
+ }
+ usbi_mutex_unlock(&ctx->flying_transfers_lock);
+
+ if (!timerisset(&next_timeout)) {
+ usbi_dbg("no URB with timeout or all handled by OS; no timeout!");
+ return 0;
+ }
+
+ r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, &cur_ts);
+ if (r < 0) {
+ usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
+ return 0;
+ }
+ TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
+
+ if (!timercmp(&cur_tv, &next_timeout, <)) {
+ usbi_dbg("first timeout already expired");
+ timerclear(tv);
+ } else {
+ timersub(&next_timeout, &cur_tv, tv);
+ usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
+ }
+
+ return 1;
+}
+
+/** \ingroup libusb_poll
+ * Register notification functions for file descriptor additions/removals.
+ * These functions will be invoked for every new or removed file descriptor
+ * that libusb uses as an event source.
+ *
+ * To remove notifiers, pass NULL values for the function pointers.
+ *
+ * Note that file descriptors may have been added even before you register
+ * these notifiers (e.g. at libusb_init() time).
+ *
+ * Additionally, note that the removal notifier may be called during
+ * libusb_exit() (e.g. when it is closing file descriptors that were opened
+ * and added to the poll set at libusb_init() time). If you don't want this,
+ * remove the notifiers immediately before calling libusb_exit().
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \param added_cb pointer to function for addition notifications
+ * \param removed_cb pointer to function for removal notifications
+ * \param user_data User data to be passed back to callbacks (useful for
+ * passing context information)
+ */
+void API_EXPORTED libusb_set_pollfd_notifiers(libusb_context *ctx,
+ libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
+ void *user_data)
+{
+ USBI_GET_CONTEXT(ctx);
+ ctx->fd_added_cb = added_cb;
+ ctx->fd_removed_cb = removed_cb;
+ ctx->fd_cb_user_data = user_data;
+}
+
+/*
+ * Interrupt the iteration of the event handling thread, so that it picks
+ * up the fd change. Callers of this function must hold the event_data_lock.
+ */
+static void usbi_fd_notification(struct libusb_context *ctx)
+{
+ int pending_events;
+
+ /* Record that there is a new poll fd.
+ * Only signal an event if there are no prior pending events. */
+ pending_events = usbi_pending_events(ctx);
+ ctx->event_flags |= USBI_EVENT_POLLFDS_MODIFIED;
+ if (!pending_events)
+ usbi_signal_event(ctx);
+}
+
+/* Add a file descriptor to the list of file descriptors to be monitored.
+ * events should be specified as a bitmask of events passed to poll(), e.g.
+ * POLLIN and/or POLLOUT. */
+int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
+{
+ struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
+ if (!ipollfd)
+ return LIBUSB_ERROR_NO_MEM;
+
+ usbi_dbg("add fd %d events %d", fd, events);
+ ipollfd->pollfd.fd = fd;
+ ipollfd->pollfd.events = events;
+ usbi_mutex_lock(&ctx->event_data_lock);
+ list_add_tail(&ipollfd->list, &ctx->ipollfds);
+ ctx->pollfds_cnt++;
+ usbi_fd_notification(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+
+ if (ctx->fd_added_cb)
+ ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
+ return 0;
+}
+
+/* Remove a file descriptor from the list of file descriptors to be polled. */
+void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
+{
+ struct usbi_pollfd *ipollfd;
+ int found = 0;
+
+ usbi_dbg("remove fd %d", fd);
+ usbi_mutex_lock(&ctx->event_data_lock);
+ list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
+ if (ipollfd->pollfd.fd == fd) {
+ found = 1;
+ break;
+ }
+
+ if (!found) {
+ usbi_dbg("couldn't find fd %d to remove", fd);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ return;
+ }
+
+ list_del(&ipollfd->list);
+ ctx->pollfds_cnt--;
+ usbi_fd_notification(ctx);
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ free(ipollfd);
+ if (ctx->fd_removed_cb)
+ ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
+}
+
+/** \ingroup libusb_poll
+ * Retrieve a list of file descriptors that should be polled by your main loop
+ * as libusb event sources.
+ *
+ * The returned list is NULL-terminated and should be freed with libusb_free_pollfds()
+ * when done. The actual list contents must not be touched.
+ *
+ * As file descriptors are a Unix-specific concept, this function is not
+ * available on Windows and will always return NULL.
+ *
+ * \param ctx the context to operate on, or NULL for the default context
+ * \returns a NULL-terminated list of libusb_pollfd structures
+ * \returns NULL on error
+ * \returns NULL on platforms where the functionality is not available
+ */
+DEFAULT_VISIBILITY
+const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
+ libusb_context *ctx)
+{
+#ifndef OS_WINDOWS
+ struct libusb_pollfd **ret = NULL;
+ struct usbi_pollfd *ipollfd;
+ size_t i = 0;
+ USBI_GET_CONTEXT(ctx);
+
+ usbi_mutex_lock(&ctx->event_data_lock);
+
+ ret = calloc(ctx->pollfds_cnt + 1, sizeof(struct libusb_pollfd *));
+ if (!ret)
+ goto out;
+
+ list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd)
+ ret[i++] = (struct libusb_pollfd *) ipollfd;
+ ret[ctx->pollfds_cnt] = NULL;
+
+out:
+ usbi_mutex_unlock(&ctx->event_data_lock);
+ return (const struct libusb_pollfd **) ret;
+#else
+ usbi_err(ctx, "external polling of libusb's internal descriptors "\
+ "is not yet supported on Windows platforms");
+ return NULL;
+#endif
+}
+
+/** \ingroup libusb_poll
+ * Free a list of libusb_pollfd structures. This should be called for all
+ * pollfd lists allocated with libusb_get_pollfds().
+ *
+ * Since version 1.0.20, \ref LIBUSB_API_VERSION >= 0x01000104
+ *
+ * It is legal to call this function with a NULL pollfd list. In this case,
+ * the function will simply return safely.
+ *
+ * \param pollfds the list of libusb_pollfd structures to free
+ */
+void API_EXPORTED libusb_free_pollfds(const struct libusb_pollfd **pollfds)
+{
+ if (!pollfds)
+ return;
+
+ free((void *)pollfds);
+}
+
+/* Backends may call this from handle_events to report disconnection of a
+ * device. This function ensures transfers get cancelled appropriately.
+ * Callers of this function must hold the events_lock.
+ */
+void usbi_handle_disconnect(struct libusb_device_handle *dev_handle)
+{
+ struct usbi_transfer *cur;
+ struct usbi_transfer *to_cancel;
+
+ usbi_dbg("device %d.%d",
+ dev_handle->dev->bus_number, dev_handle->dev->device_address);
+
+ /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
+ * status code.
+ *
+ * when we find a transfer for this device on the list, there are two
+ * possible scenarios:
+ * 1. the transfer is currently in-flight, in which case we terminate the
+ * transfer here
+ * 2. the transfer has been added to the flying transfer list by
+ * libusb_submit_transfer, has failed to submit and
+ * libusb_submit_transfer is waiting for us to release the
+ * flying_transfers_lock to remove it, so we ignore it
+ */
+
+ while (1) {
+ to_cancel = NULL;
+ usbi_mutex_lock(&HANDLE_CTX(dev_handle)->flying_transfers_lock);
+ list_for_each_entry(cur, &HANDLE_CTX(dev_handle)->flying_transfers, list, struct usbi_transfer)
+ if (USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == dev_handle) {
+ usbi_mutex_lock(&cur->lock);
+ if (cur->state_flags & USBI_TRANSFER_IN_FLIGHT)
+ to_cancel = cur;
+ usbi_mutex_unlock(&cur->lock);
+
+ if (to_cancel)
+ break;
+ }
+ usbi_mutex_unlock(&HANDLE_CTX(dev_handle)->flying_transfers_lock);
+
+ if (!to_cancel)
+ break;
+
+ usbi_dbg("cancelling transfer %p from disconnect",
+ USBI_TRANSFER_TO_LIBUSB_TRANSFER(to_cancel));
+
+ usbi_mutex_lock(&to_cancel->lock);
+ usbi_backend.clear_transfer_priv(to_cancel);
+ usbi_mutex_unlock(&to_cancel->lock);
+ usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);
+ }
+
+}
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/libusb.h b/vendor/github.com/karalabe/usb/libusb/libusb/libusb.h
new file mode 100644
index 000000000..430136b2e
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/libusb.h
@@ -0,0 +1,2039 @@
+/*
+ * Public libusb header file
+ * Copyright © 2001 Johannes Erdfelt
+ * Copyright © 2007-2008 Daniel Drake
+ * Copyright © 2012 Pete Batard
+ * Copyright © 2012 Nathan Hjelm
+ * For more information, please visit: http://libusb.info
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef LIBUSB_H
+#define LIBUSB_H
+
+#ifdef _MSC_VER
+/* on MS environments, the inline keyword is available in C++ only */
+#if !defined(__cplusplus)
+#define inline __inline
+#endif
+/* ssize_t is also not available (copy/paste from MinGW) */
+#ifndef _SSIZE_T_DEFINED
+#define _SSIZE_T_DEFINED
+#undef ssize_t
+#ifdef _WIN64
+ typedef __int64 ssize_t;
+#else
+ typedef int ssize_t;
+#endif /* _WIN64 */
+#endif /* _SSIZE_T_DEFINED */
+#endif /* _MSC_VER */
+
+/* stdint.h is not available on older MSVC */
+#if defined(_MSC_VER) && (_MSC_VER < 1600) && (!defined(_STDINT)) && (!defined(_STDINT_H))
+typedef unsigned __int8 uint8_t;
+typedef unsigned __int16 uint16_t;
+typedef unsigned __int32 uint32_t;
+#else
+#include
+#endif
+
+#if !defined(_WIN32_WCE)
+#include
+#endif
+
+#if defined(__linux__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__HAIKU__)
+#include
+#endif
+
+#include
+#include
+
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
+#define ZERO_SIZED_ARRAY /* [] - valid C99 code */
+#else
+#define ZERO_SIZED_ARRAY 0 /* [0] - non-standard, but usually working code */
+#endif
+
+/* 'interface' might be defined as a macro on Windows, so we need to
+ * undefine it so as not to break the current libusb API, because
+ * libusb_config_descriptor has an 'interface' member
+ * As this can be problematic if you include windows.h after libusb.h
+ * in your sources, we force windows.h to be included first. */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+#include
+#if defined(interface)
+#undef interface
+#endif
+#if !defined(__CYGWIN__)
+#include
+#endif
+#endif
+
+#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
+#define LIBUSB_DEPRECATED_FOR(f) \
+ __attribute__((deprecated("Use " #f " instead")))
+#elif __GNUC__ >= 3
+#define LIBUSB_DEPRECATED_FOR(f) __attribute__((deprecated))
+#else
+#define LIBUSB_DEPRECATED_FOR(f)
+#endif /* __GNUC__ */
+
+/** \def LIBUSB_CALL
+ * \ingroup libusb_misc
+ * libusb's Windows calling convention.
+ *
+ * Under Windows, the selection of available compilers and configurations
+ * means that, unlike other platforms, there is not one true calling
+ * convention (calling convention: the manner in which parameters are
+ * passed to functions in the generated assembly code).
+ *
+ * Matching the Windows API itself, libusb uses the WINAPI convention (which
+ * translates to the stdcall convention) and guarantees that the
+ * library is compiled in this way. The public header file also includes
+ * appropriate annotations so that your own software will use the right
+ * convention, even if another convention is being used by default within
+ * your codebase.
+ *
+ * The one consideration that you must apply in your software is to mark
+ * all functions which you use as libusb callbacks with this LIBUSB_CALL
+ * annotation, so that they too get compiled for the correct calling
+ * convention.
+ *
+ * On non-Windows operating systems, this macro is defined as nothing. This
+ * means that you can apply it to your code without worrying about
+ * cross-platform compatibility.
+ */
+/* LIBUSB_CALL must be defined on both definition and declaration of libusb
+ * functions. You'd think that declaration would be enough, but cygwin will
+ * complain about conflicting types unless both are marked this way.
+ * The placement of this macro is important too; it must appear after the
+ * return type, before the function name. See internal documentation for
+ * API_EXPORTED.
+ */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+#define LIBUSB_CALL WINAPI
+#else
+#define LIBUSB_CALL
+#endif
+
+/** \def LIBUSB_API_VERSION
+ * \ingroup libusb_misc
+ * libusb's API version.
+ *
+ * Since version 1.0.13, to help with feature detection, libusb defines
+ * a LIBUSB_API_VERSION macro that gets increased every time there is a
+ * significant change to the API, such as the introduction of a new call,
+ * the definition of a new macro/enum member, or any other element that
+ * libusb applications may want to detect at compilation time.
+ *
+ * The macro is typically used in an application as follows:
+ * \code
+ * #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01001234)
+ * // Use one of the newer features from the libusb API
+ * #endif
+ * \endcode
+ *
+ * Internally, LIBUSB_API_VERSION is defined as follows:
+ * (libusb major << 24) | (libusb minor << 16) | (16 bit incremental)
+ */
+#define LIBUSB_API_VERSION 0x01000106
+
+/* The following is kept for compatibility, but will be deprecated in the future */
+#define LIBUSBX_API_VERSION LIBUSB_API_VERSION
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \ingroup libusb_misc
+ * Convert a 16-bit value from host-endian to little-endian format. On
+ * little endian systems, this function does nothing. On big endian systems,
+ * the bytes are swapped.
+ * \param x the host-endian value to convert
+ * \returns the value in little-endian byte order
+ */
+static inline uint16_t libusb_cpu_to_le16(const uint16_t x)
+{
+ union {
+ uint8_t b8[2];
+ uint16_t b16;
+ } _tmp;
+ _tmp.b8[1] = (uint8_t) (x >> 8);
+ _tmp.b8[0] = (uint8_t) (x & 0xff);
+ return _tmp.b16;
+}
+
+/** \def libusb_le16_to_cpu
+ * \ingroup libusb_misc
+ * Convert a 16-bit value from little-endian to host-endian format. On
+ * little endian systems, this function does nothing. On big endian systems,
+ * the bytes are swapped.
+ * \param x the little-endian value to convert
+ * \returns the value in host-endian byte order
+ */
+#define libusb_le16_to_cpu libusb_cpu_to_le16
+
+/* standard USB stuff */
+
+/** \ingroup libusb_desc
+ * Device and/or Interface Class codes */
+enum libusb_class_code {
+ /** In the context of a \ref libusb_device_descriptor "device descriptor",
+ * this bDeviceClass value indicates that each interface specifies its
+ * own class information and all interfaces operate independently.
+ */
+ LIBUSB_CLASS_PER_INTERFACE = 0,
+
+ /** Audio class */
+ LIBUSB_CLASS_AUDIO = 1,
+
+ /** Communications class */
+ LIBUSB_CLASS_COMM = 2,
+
+ /** Human Interface Device class */
+ LIBUSB_CLASS_HID = 3,
+
+ /** Physical */
+ LIBUSB_CLASS_PHYSICAL = 5,
+
+ /** Printer class */
+ LIBUSB_CLASS_PRINTER = 7,
+
+ /** Image class */
+ LIBUSB_CLASS_PTP = 6, /* legacy name from libusb-0.1 usb.h */
+ LIBUSB_CLASS_IMAGE = 6,
+
+ /** Mass storage class */
+ LIBUSB_CLASS_MASS_STORAGE = 8,
+
+ /** Hub class */
+ LIBUSB_CLASS_HUB = 9,
+
+ /** Data class */
+ LIBUSB_CLASS_DATA = 10,
+
+ /** Smart Card */
+ LIBUSB_CLASS_SMART_CARD = 0x0b,
+
+ /** Content Security */
+ LIBUSB_CLASS_CONTENT_SECURITY = 0x0d,
+
+ /** Video */
+ LIBUSB_CLASS_VIDEO = 0x0e,
+
+ /** Personal Healthcare */
+ LIBUSB_CLASS_PERSONAL_HEALTHCARE = 0x0f,
+
+ /** Diagnostic Device */
+ LIBUSB_CLASS_DIAGNOSTIC_DEVICE = 0xdc,
+
+ /** Wireless class */
+ LIBUSB_CLASS_WIRELESS = 0xe0,
+
+ /** Application class */
+ LIBUSB_CLASS_APPLICATION = 0xfe,
+
+ /** Class is vendor-specific */
+ LIBUSB_CLASS_VENDOR_SPEC = 0xff
+};
+
+/** \ingroup libusb_desc
+ * Descriptor types as defined by the USB specification. */
+enum libusb_descriptor_type {
+ /** Device descriptor. See libusb_device_descriptor. */
+ LIBUSB_DT_DEVICE = 0x01,
+
+ /** Configuration descriptor. See libusb_config_descriptor. */
+ LIBUSB_DT_CONFIG = 0x02,
+
+ /** String descriptor */
+ LIBUSB_DT_STRING = 0x03,
+
+ /** Interface descriptor. See libusb_interface_descriptor. */
+ LIBUSB_DT_INTERFACE = 0x04,
+
+ /** Endpoint descriptor. See libusb_endpoint_descriptor. */
+ LIBUSB_DT_ENDPOINT = 0x05,
+
+ /** BOS descriptor */
+ LIBUSB_DT_BOS = 0x0f,
+
+ /** Device Capability descriptor */
+ LIBUSB_DT_DEVICE_CAPABILITY = 0x10,
+
+ /** HID descriptor */
+ LIBUSB_DT_HID = 0x21,
+
+ /** HID report descriptor */
+ LIBUSB_DT_REPORT = 0x22,
+
+ /** Physical descriptor */
+ LIBUSB_DT_PHYSICAL = 0x23,
+
+ /** Hub descriptor */
+ LIBUSB_DT_HUB = 0x29,
+
+ /** SuperSpeed Hub descriptor */
+ LIBUSB_DT_SUPERSPEED_HUB = 0x2a,
+
+ /** SuperSpeed Endpoint Companion descriptor */
+ LIBUSB_DT_SS_ENDPOINT_COMPANION = 0x30
+};
+
+/* Descriptor sizes per descriptor type */
+#define LIBUSB_DT_DEVICE_SIZE 18
+#define LIBUSB_DT_CONFIG_SIZE 9
+#define LIBUSB_DT_INTERFACE_SIZE 9
+#define LIBUSB_DT_ENDPOINT_SIZE 7
+#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */
+#define LIBUSB_DT_HUB_NONVAR_SIZE 7
+#define LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE 6
+#define LIBUSB_DT_BOS_SIZE 5
+#define LIBUSB_DT_DEVICE_CAPABILITY_SIZE 3
+
+/* BOS descriptor sizes */
+#define LIBUSB_BT_USB_2_0_EXTENSION_SIZE 7
+#define LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE 10
+#define LIBUSB_BT_CONTAINER_ID_SIZE 20
+
+/* We unwrap the BOS => define its max size */
+#define LIBUSB_DT_BOS_MAX_SIZE ((LIBUSB_DT_BOS_SIZE) +\
+ (LIBUSB_BT_USB_2_0_EXTENSION_SIZE) +\
+ (LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) +\
+ (LIBUSB_BT_CONTAINER_ID_SIZE))
+
+#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */
+#define LIBUSB_ENDPOINT_DIR_MASK 0x80
+
+/** \ingroup libusb_desc
+ * Endpoint direction. Values for bit 7 of the
+ * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme.
+ */
+enum libusb_endpoint_direction {
+ /** In: device-to-host */
+ LIBUSB_ENDPOINT_IN = 0x80,
+
+ /** Out: host-to-device */
+ LIBUSB_ENDPOINT_OUT = 0x00
+};
+
+#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */
+
+/** \ingroup libusb_desc
+ * Endpoint transfer type. Values for bits 0:1 of the
+ * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field.
+ */
+enum libusb_transfer_type {
+ /** Control endpoint */
+ LIBUSB_TRANSFER_TYPE_CONTROL = 0,
+
+ /** Isochronous endpoint */
+ LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1,
+
+ /** Bulk endpoint */
+ LIBUSB_TRANSFER_TYPE_BULK = 2,
+
+ /** Interrupt endpoint */
+ LIBUSB_TRANSFER_TYPE_INTERRUPT = 3,
+
+ /** Stream endpoint */
+ LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4,
+};
+
+/** \ingroup libusb_misc
+ * Standard requests, as defined in table 9-5 of the USB 3.0 specifications */
+enum libusb_standard_request {
+ /** Request status of the specific recipient */
+ LIBUSB_REQUEST_GET_STATUS = 0x00,
+
+ /** Clear or disable a specific feature */
+ LIBUSB_REQUEST_CLEAR_FEATURE = 0x01,
+
+ /* 0x02 is reserved */
+
+ /** Set or enable a specific feature */
+ LIBUSB_REQUEST_SET_FEATURE = 0x03,
+
+ /* 0x04 is reserved */
+
+ /** Set device address for all future accesses */
+ LIBUSB_REQUEST_SET_ADDRESS = 0x05,
+
+ /** Get the specified descriptor */
+ LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06,
+
+ /** Used to update existing descriptors or add new descriptors */
+ LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07,
+
+ /** Get the current device configuration value */
+ LIBUSB_REQUEST_GET_CONFIGURATION = 0x08,
+
+ /** Set device configuration */
+ LIBUSB_REQUEST_SET_CONFIGURATION = 0x09,
+
+ /** Return the selected alternate setting for the specified interface */
+ LIBUSB_REQUEST_GET_INTERFACE = 0x0A,
+
+ /** Select an alternate interface for the specified interface */
+ LIBUSB_REQUEST_SET_INTERFACE = 0x0B,
+
+ /** Set then report an endpoint's synchronization frame */
+ LIBUSB_REQUEST_SYNCH_FRAME = 0x0C,
+
+ /** Sets both the U1 and U2 Exit Latency */
+ LIBUSB_REQUEST_SET_SEL = 0x30,
+
+ /** Delay from the time a host transmits a packet to the time it is
+ * received by the device. */
+ LIBUSB_SET_ISOCH_DELAY = 0x31,
+};
+
+/** \ingroup libusb_misc
+ * Request type bits of the
+ * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
+ * transfers. */
+enum libusb_request_type {
+ /** Standard */
+ LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5),
+
+ /** Class */
+ LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5),
+
+ /** Vendor */
+ LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5),
+
+ /** Reserved */
+ LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5)
+};
+
+/** \ingroup libusb_misc
+ * Recipient bits of the
+ * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
+ * transfers. Values 4 through 31 are reserved. */
+enum libusb_request_recipient {
+ /** Device */
+ LIBUSB_RECIPIENT_DEVICE = 0x00,
+
+ /** Interface */
+ LIBUSB_RECIPIENT_INTERFACE = 0x01,
+
+ /** Endpoint */
+ LIBUSB_RECIPIENT_ENDPOINT = 0x02,
+
+ /** Other */
+ LIBUSB_RECIPIENT_OTHER = 0x03,
+};
+
+#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C
+
+/** \ingroup libusb_desc
+ * Synchronization type for isochronous endpoints. Values for bits 2:3 of the
+ * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
+ * libusb_endpoint_descriptor.
+ */
+enum libusb_iso_sync_type {
+ /** No synchronization */
+ LIBUSB_ISO_SYNC_TYPE_NONE = 0,
+
+ /** Asynchronous */
+ LIBUSB_ISO_SYNC_TYPE_ASYNC = 1,
+
+ /** Adaptive */
+ LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2,
+
+ /** Synchronous */
+ LIBUSB_ISO_SYNC_TYPE_SYNC = 3
+};
+
+#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30
+
+/** \ingroup libusb_desc
+ * Usage type for isochronous endpoints. Values for bits 4:5 of the
+ * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
+ * libusb_endpoint_descriptor.
+ */
+enum libusb_iso_usage_type {
+ /** Data endpoint */
+ LIBUSB_ISO_USAGE_TYPE_DATA = 0,
+
+ /** Feedback endpoint */
+ LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1,
+
+ /** Implicit feedback Data endpoint */
+ LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2,
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the standard USB device descriptor. This
+ * descriptor is documented in section 9.6.1 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_device_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this
+ * context. */
+ uint8_t bDescriptorType;
+
+ /** USB specification release number in binary-coded decimal. A value of
+ * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */
+ uint16_t bcdUSB;
+
+ /** USB-IF class code for the device. See \ref libusb_class_code. */
+ uint8_t bDeviceClass;
+
+ /** USB-IF subclass code for the device, qualified by the bDeviceClass
+ * value */
+ uint8_t bDeviceSubClass;
+
+ /** USB-IF protocol code for the device, qualified by the bDeviceClass and
+ * bDeviceSubClass values */
+ uint8_t bDeviceProtocol;
+
+ /** Maximum packet size for endpoint 0 */
+ uint8_t bMaxPacketSize0;
+
+ /** USB-IF vendor ID */
+ uint16_t idVendor;
+
+ /** USB-IF product ID */
+ uint16_t idProduct;
+
+ /** Device release number in binary-coded decimal */
+ uint16_t bcdDevice;
+
+ /** Index of string descriptor describing manufacturer */
+ uint8_t iManufacturer;
+
+ /** Index of string descriptor describing product */
+ uint8_t iProduct;
+
+ /** Index of string descriptor containing device serial number */
+ uint8_t iSerialNumber;
+
+ /** Number of possible configurations */
+ uint8_t bNumConfigurations;
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the standard USB endpoint descriptor. This
+ * descriptor is documented in section 9.6.6 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_endpoint_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in
+ * this context. */
+ uint8_t bDescriptorType;
+
+ /** The address of the endpoint described by this descriptor. Bits 0:3 are
+ * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction,
+ * see \ref libusb_endpoint_direction.
+ */
+ uint8_t bEndpointAddress;
+
+ /** Attributes which apply to the endpoint when it is configured using
+ * the bConfigurationValue. Bits 0:1 determine the transfer type and
+ * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for
+ * isochronous endpoints and correspond to \ref libusb_iso_sync_type.
+ * Bits 4:5 are also only used for isochronous endpoints and correspond to
+ * \ref libusb_iso_usage_type. Bits 6:7 are reserved.
+ */
+ uint8_t bmAttributes;
+
+ /** Maximum packet size this endpoint is capable of sending/receiving. */
+ uint16_t wMaxPacketSize;
+
+ /** Interval for polling endpoint for data transfers. */
+ uint8_t bInterval;
+
+ /** For audio devices only: the rate at which synchronization feedback
+ * is provided. */
+ uint8_t bRefresh;
+
+ /** For audio devices only: the address if the synch endpoint */
+ uint8_t bSynchAddress;
+
+ /** Extra descriptors. If libusb encounters unknown endpoint descriptors,
+ * it will store them here, should you wish to parse them. */
+ const unsigned char *extra;
+
+ /** Length of the extra descriptors, in bytes. */
+ int extra_length;
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the standard USB interface descriptor. This
+ * descriptor is documented in section 9.6.5 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_interface_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE
+ * in this context. */
+ uint8_t bDescriptorType;
+
+ /** Number of this interface */
+ uint8_t bInterfaceNumber;
+
+ /** Value used to select this alternate setting for this interface */
+ uint8_t bAlternateSetting;
+
+ /** Number of endpoints used by this interface (excluding the control
+ * endpoint). */
+ uint8_t bNumEndpoints;
+
+ /** USB-IF class code for this interface. See \ref libusb_class_code. */
+ uint8_t bInterfaceClass;
+
+ /** USB-IF subclass code for this interface, qualified by the
+ * bInterfaceClass value */
+ uint8_t bInterfaceSubClass;
+
+ /** USB-IF protocol code for this interface, qualified by the
+ * bInterfaceClass and bInterfaceSubClass values */
+ uint8_t bInterfaceProtocol;
+
+ /** Index of string descriptor describing this interface */
+ uint8_t iInterface;
+
+ /** Array of endpoint descriptors. This length of this array is determined
+ * by the bNumEndpoints field. */
+ const struct libusb_endpoint_descriptor *endpoint;
+
+ /** Extra descriptors. If libusb encounters unknown interface descriptors,
+ * it will store them here, should you wish to parse them. */
+ const unsigned char *extra;
+
+ /** Length of the extra descriptors, in bytes. */
+ int extra_length;
+};
+
+/** \ingroup libusb_desc
+ * A collection of alternate settings for a particular USB interface.
+ */
+struct libusb_interface {
+ /** Array of interface descriptors. The length of this array is determined
+ * by the num_altsetting field. */
+ const struct libusb_interface_descriptor *altsetting;
+
+ /** The number of alternate settings that belong to this interface */
+ int num_altsetting;
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the standard USB configuration descriptor. This
+ * descriptor is documented in section 9.6.3 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_config_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG
+ * in this context. */
+ uint8_t bDescriptorType;
+
+ /** Total length of data returned for this configuration */
+ uint16_t wTotalLength;
+
+ /** Number of interfaces supported by this configuration */
+ uint8_t bNumInterfaces;
+
+ /** Identifier value for this configuration */
+ uint8_t bConfigurationValue;
+
+ /** Index of string descriptor describing this configuration */
+ uint8_t iConfiguration;
+
+ /** Configuration characteristics */
+ uint8_t bmAttributes;
+
+ /** Maximum power consumption of the USB device from this bus in this
+ * configuration when the device is fully operation. Expressed in units
+ * of 2 mA when the device is operating in high-speed mode and in units
+ * of 8 mA when the device is operating in super-speed mode. */
+ uint8_t MaxPower;
+
+ /** Array of interfaces supported by this configuration. The length of
+ * this array is determined by the bNumInterfaces field. */
+ const struct libusb_interface *interface;
+
+ /** Extra descriptors. If libusb encounters unknown configuration
+ * descriptors, it will store them here, should you wish to parse them. */
+ const unsigned char *extra;
+
+ /** Length of the extra descriptors, in bytes. */
+ int extra_length;
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the superspeed endpoint companion
+ * descriptor. This descriptor is documented in section 9.6.7 of
+ * the USB 3.0 specification. All multiple-byte fields are represented in
+ * host-endian format.
+ */
+struct libusb_ss_endpoint_companion_descriptor {
+
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_SS_ENDPOINT_COMPANION in
+ * this context. */
+ uint8_t bDescriptorType;
+
+
+ /** The maximum number of packets the endpoint can send or
+ * receive as part of a burst. */
+ uint8_t bMaxBurst;
+
+ /** In bulk EP: bits 4:0 represents the maximum number of
+ * streams the EP supports. In isochronous EP: bits 1:0
+ * represents the Mult - a zero based value that determines
+ * the maximum number of packets within a service interval */
+ uint8_t bmAttributes;
+
+ /** The total number of bytes this EP will transfer every
+ * service interval. valid only for periodic EPs. */
+ uint16_t wBytesPerInterval;
+};
+
+/** \ingroup libusb_desc
+ * A generic representation of a BOS Device Capability descriptor. It is
+ * advised to check bDevCapabilityType and call the matching
+ * libusb_get_*_descriptor function to get a structure fully matching the type.
+ */
+struct libusb_bos_dev_capability_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
+ * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
+ uint8_t bDescriptorType;
+ /** Device Capability type */
+ uint8_t bDevCapabilityType;
+ /** Device Capability data (bLength - 3 bytes) */
+ uint8_t dev_capability_data[ZERO_SIZED_ARRAY];
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the Binary Device Object Store (BOS) descriptor.
+ * This descriptor is documented in section 9.6.2 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_bos_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_BOS LIBUSB_DT_BOS
+ * in this context. */
+ uint8_t bDescriptorType;
+
+ /** Length of this descriptor and all of its sub descriptors */
+ uint16_t wTotalLength;
+
+ /** The number of separate device capability descriptors in
+ * the BOS */
+ uint8_t bNumDeviceCaps;
+
+ /** bNumDeviceCap Device Capability Descriptors */
+ struct libusb_bos_dev_capability_descriptor *dev_capability[ZERO_SIZED_ARRAY];
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the USB 2.0 Extension descriptor
+ * This descriptor is documented in section 9.6.2.1 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_usb_2_0_extension_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
+ * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
+ uint8_t bDescriptorType;
+
+ /** Capability type. Will have value
+ * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION
+ * LIBUSB_BT_USB_2_0_EXTENSION in this context. */
+ uint8_t bDevCapabilityType;
+
+ /** Bitmap encoding of supported device level features.
+ * A value of one in a bit location indicates a feature is
+ * supported; a value of zero indicates it is not supported.
+ * See \ref libusb_usb_2_0_extension_attributes. */
+ uint32_t bmAttributes;
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the SuperSpeed USB Device Capability descriptor
+ * This descriptor is documented in section 9.6.2.2 of the USB 3.0 specification.
+ * All multiple-byte fields are represented in host-endian format.
+ */
+struct libusb_ss_usb_device_capability_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
+ * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
+ uint8_t bDescriptorType;
+
+ /** Capability type. Will have value
+ * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY
+ * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY in this context. */
+ uint8_t bDevCapabilityType;
+
+ /** Bitmap encoding of supported device level features.
+ * A value of one in a bit location indicates a feature is
+ * supported; a value of zero indicates it is not supported.
+ * See \ref libusb_ss_usb_device_capability_attributes. */
+ uint8_t bmAttributes;
+
+ /** Bitmap encoding of the speed supported by this device when
+ * operating in SuperSpeed mode. See \ref libusb_supported_speed. */
+ uint16_t wSpeedSupported;
+
+ /** The lowest speed at which all the functionality supported
+ * by the device is available to the user. For example if the
+ * device supports all its functionality when connected at
+ * full speed and above then it sets this value to 1. */
+ uint8_t bFunctionalitySupport;
+
+ /** U1 Device Exit Latency. */
+ uint8_t bU1DevExitLat;
+
+ /** U2 Device Exit Latency. */
+ uint16_t bU2DevExitLat;
+};
+
+/** \ingroup libusb_desc
+ * A structure representing the Container ID descriptor.
+ * This descriptor is documented in section 9.6.2.3 of the USB 3.0 specification.
+ * All multiple-byte fields, except UUIDs, are represented in host-endian format.
+ */
+struct libusb_container_id_descriptor {
+ /** Size of this descriptor (in bytes) */
+ uint8_t bLength;
+
+ /** Descriptor type. Will have value
+ * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY
+ * LIBUSB_DT_DEVICE_CAPABILITY in this context. */
+ uint8_t bDescriptorType;
+
+ /** Capability type. Will have value
+ * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID
+ * LIBUSB_BT_CONTAINER_ID in this context. */
+ uint8_t bDevCapabilityType;
+
+ /** Reserved field */
+ uint8_t bReserved;
+
+ /** 128 bit UUID */
+ uint8_t ContainerID[16];
+};
+
+/** \ingroup libusb_asyncio
+ * Setup packet for control transfers. */
+struct libusb_control_setup {
+ /** Request type. Bits 0:4 determine recipient, see
+ * \ref libusb_request_recipient. Bits 5:6 determine type, see
+ * \ref libusb_request_type. Bit 7 determines data transfer direction, see
+ * \ref libusb_endpoint_direction.
+ */
+ uint8_t bmRequestType;
+
+ /** Request. If the type bits of bmRequestType are equal to
+ * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD
+ * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to
+ * \ref libusb_standard_request. For other cases, use of this field is
+ * application-specific. */
+ uint8_t bRequest;
+
+ /** Value. Varies according to request */
+ uint16_t wValue;
+
+ /** Index. Varies according to request, typically used to pass an index
+ * or offset */
+ uint16_t wIndex;
+
+ /** Number of bytes to transfer */
+ uint16_t wLength;
+};
+
+#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup))
+
+/* libusb */
+
+struct libusb_context;
+struct libusb_device;
+struct libusb_device_handle;
+
+/** \ingroup libusb_lib
+ * Structure providing the version of the libusb runtime
+ */
+struct libusb_version {
+ /** Library major version. */
+ const uint16_t major;
+
+ /** Library minor version. */
+ const uint16_t minor;
+
+ /** Library micro version. */
+ const uint16_t micro;
+
+ /** Library nano version. */
+ const uint16_t nano;
+
+ /** Library release candidate suffix string, e.g. "-rc4". */
+ const char *rc;
+
+ /** For ABI compatibility only. */
+ const char* describe;
+};
+
+/** \ingroup libusb_lib
+ * Structure representing a libusb session. The concept of individual libusb
+ * sessions allows for your program to use two libraries (or dynamically
+ * load two modules) which both independently use libusb. This will prevent
+ * interference between the individual libusb users - for example
+ * libusb_set_option() will not affect the other user of the library, and
+ * libusb_exit() will not destroy resources that the other user is still
+ * using.
+ *
+ * Sessions are created by libusb_init() and destroyed through libusb_exit().
+ * If your application is guaranteed to only ever include a single libusb
+ * user (i.e. you), you do not have to worry about contexts: pass NULL in
+ * every function call where a context is required. The default context
+ * will be used.
+ *
+ * For more information, see \ref libusb_contexts.
+ */
+typedef struct libusb_context libusb_context;
+
+/** \ingroup libusb_dev
+ * Structure representing a USB device detected on the system. This is an
+ * opaque type for which you are only ever provided with a pointer, usually
+ * originating from libusb_get_device_list().
+ *
+ * Certain operations can be performed on a device, but in order to do any
+ * I/O you will have to first obtain a device handle using libusb_open().
+ *
+ * Devices are reference counted with libusb_ref_device() and
+ * libusb_unref_device(), and are freed when the reference count reaches 0.
+ * New devices presented by libusb_get_device_list() have a reference count of
+ * 1, and libusb_free_device_list() can optionally decrease the reference count
+ * on all devices in the list. libusb_open() adds another reference which is
+ * later destroyed by libusb_close().
+ */
+typedef struct libusb_device libusb_device;
+
+
+/** \ingroup libusb_dev
+ * Structure representing a handle on a USB device. This is an opaque type for
+ * which you are only ever provided with a pointer, usually originating from
+ * libusb_open().
+ *
+ * A device handle is used to perform I/O and other operations. When finished
+ * with a device handle, you should call libusb_close().
+ */
+typedef struct libusb_device_handle libusb_device_handle;
+
+/** \ingroup libusb_dev
+ * Speed codes. Indicates the speed at which the device is operating.
+ */
+enum libusb_speed {
+ /** The OS doesn't report or know the device speed. */
+ LIBUSB_SPEED_UNKNOWN = 0,
+
+ /** The device is operating at low speed (1.5MBit/s). */
+ LIBUSB_SPEED_LOW = 1,
+
+ /** The device is operating at full speed (12MBit/s). */
+ LIBUSB_SPEED_FULL = 2,
+
+ /** The device is operating at high speed (480MBit/s). */
+ LIBUSB_SPEED_HIGH = 3,
+
+ /** The device is operating at super speed (5000MBit/s). */
+ LIBUSB_SPEED_SUPER = 4,
+
+ /** The device is operating at super speed plus (10000MBit/s). */
+ LIBUSB_SPEED_SUPER_PLUS = 5,
+};
+
+/** \ingroup libusb_dev
+ * Supported speeds (wSpeedSupported) bitfield. Indicates what
+ * speeds the device supports.
+ */
+enum libusb_supported_speed {
+ /** Low speed operation supported (1.5MBit/s). */
+ LIBUSB_LOW_SPEED_OPERATION = 1,
+
+ /** Full speed operation supported (12MBit/s). */
+ LIBUSB_FULL_SPEED_OPERATION = 2,
+
+ /** High speed operation supported (480MBit/s). */
+ LIBUSB_HIGH_SPEED_OPERATION = 4,
+
+ /** Superspeed operation supported (5000MBit/s). */
+ LIBUSB_SUPER_SPEED_OPERATION = 8,
+};
+
+/** \ingroup libusb_dev
+ * Masks for the bits of the
+ * \ref libusb_usb_2_0_extension_descriptor::bmAttributes "bmAttributes" field
+ * of the USB 2.0 Extension descriptor.
+ */
+enum libusb_usb_2_0_extension_attributes {
+ /** Supports Link Power Management (LPM) */
+ LIBUSB_BM_LPM_SUPPORT = 2,
+};
+
+/** \ingroup libusb_dev
+ * Masks for the bits of the
+ * \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field
+ * field of the SuperSpeed USB Device Capability descriptor.
+ */
+enum libusb_ss_usb_device_capability_attributes {
+ /** Supports Latency Tolerance Messages (LTM) */
+ LIBUSB_BM_LTM_SUPPORT = 2,
+};
+
+/** \ingroup libusb_dev
+ * USB capability types
+ */
+enum libusb_bos_type {
+ /** Wireless USB device capability */
+ LIBUSB_BT_WIRELESS_USB_DEVICE_CAPABILITY = 1,
+
+ /** USB 2.0 extensions */
+ LIBUSB_BT_USB_2_0_EXTENSION = 2,
+
+ /** SuperSpeed USB device capability */
+ LIBUSB_BT_SS_USB_DEVICE_CAPABILITY = 3,
+
+ /** Container ID type */
+ LIBUSB_BT_CONTAINER_ID = 4,
+};
+
+/** \ingroup libusb_misc
+ * Error codes. Most libusb functions return 0 on success or one of these
+ * codes on failure.
+ * You can call libusb_error_name() to retrieve a string representation of an
+ * error code or libusb_strerror() to get an end-user suitable description of
+ * an error code.
+ */
+enum libusb_error {
+ /** Success (no error) */
+ LIBUSB_SUCCESS = 0,
+
+ /** Input/output error */
+ LIBUSB_ERROR_IO = -1,
+
+ /** Invalid parameter */
+ LIBUSB_ERROR_INVALID_PARAM = -2,
+
+ /** Access denied (insufficient permissions) */
+ LIBUSB_ERROR_ACCESS = -3,
+
+ /** No such device (it may have been disconnected) */
+ LIBUSB_ERROR_NO_DEVICE = -4,
+
+ /** Entity not found */
+ LIBUSB_ERROR_NOT_FOUND = -5,
+
+ /** Resource busy */
+ LIBUSB_ERROR_BUSY = -6,
+
+ /** Operation timed out */
+ LIBUSB_ERROR_TIMEOUT = -7,
+
+ /** Overflow */
+ LIBUSB_ERROR_OVERFLOW = -8,
+
+ /** Pipe error */
+ LIBUSB_ERROR_PIPE = -9,
+
+ /** System call interrupted (perhaps due to signal) */
+ LIBUSB_ERROR_INTERRUPTED = -10,
+
+ /** Insufficient memory */
+ LIBUSB_ERROR_NO_MEM = -11,
+
+ /** Operation not supported or unimplemented on this platform */
+ LIBUSB_ERROR_NOT_SUPPORTED = -12,
+
+ /* NB: Remember to update LIBUSB_ERROR_COUNT below as well as the
+ message strings in strerror.c when adding new error codes here. */
+
+ /** Other error */
+ LIBUSB_ERROR_OTHER = -99,
+};
+
+/* Total number of error codes in enum libusb_error */
+#define LIBUSB_ERROR_COUNT 14
+
+/** \ingroup libusb_asyncio
+ * Transfer status codes */
+enum libusb_transfer_status {
+ /** Transfer completed without error. Note that this does not indicate
+ * that the entire amount of requested data was transferred. */
+ LIBUSB_TRANSFER_COMPLETED,
+
+ /** Transfer failed */
+ LIBUSB_TRANSFER_ERROR,
+
+ /** Transfer timed out */
+ LIBUSB_TRANSFER_TIMED_OUT,
+
+ /** Transfer was cancelled */
+ LIBUSB_TRANSFER_CANCELLED,
+
+ /** For bulk/interrupt endpoints: halt condition detected (endpoint
+ * stalled). For control endpoints: control request not supported. */
+ LIBUSB_TRANSFER_STALL,
+
+ /** Device was disconnected */
+ LIBUSB_TRANSFER_NO_DEVICE,
+
+ /** Device sent more data than requested */
+ LIBUSB_TRANSFER_OVERFLOW,
+
+ /* NB! Remember to update libusb_error_name()
+ when adding new status codes here. */
+};
+
+/** \ingroup libusb_asyncio
+ * libusb_transfer.flags values */
+enum libusb_transfer_flags {
+ /** Report short frames as errors */
+ LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0,
+
+ /** Automatically free() transfer buffer during libusb_free_transfer().
+ * Note that buffers allocated with libusb_dev_mem_alloc() should not
+ * be attempted freed in this way, since free() is not an appropriate
+ * way to release such memory. */
+ LIBUSB_TRANSFER_FREE_BUFFER = 1<<1,
+
+ /** Automatically call libusb_free_transfer() after callback returns.
+ * If this flag is set, it is illegal to call libusb_free_transfer()
+ * from your transfer callback, as this will result in a double-free
+ * when this flag is acted upon. */
+ LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2,
+
+ /** Terminate transfers that are a multiple of the endpoint's
+ * wMaxPacketSize with an extra zero length packet. This is useful
+ * when a device protocol mandates that each logical request is
+ * terminated by an incomplete packet (i.e. the logical requests are
+ * not separated by other means).
+ *
+ * This flag only affects host-to-device transfers to bulk and interrupt
+ * endpoints. In other situations, it is ignored.
+ *
+ * This flag only affects transfers with a length that is a multiple of
+ * the endpoint's wMaxPacketSize. On transfers of other lengths, this
+ * flag has no effect. Therefore, if you are working with a device that
+ * needs a ZLP whenever the end of the logical request falls on a packet
+ * boundary, then it is sensible to set this flag on every
+ * transfer (you do not have to worry about only setting it on transfers
+ * that end on the boundary).
+ *
+ * This flag is currently only supported on Linux.
+ * On other systems, libusb_submit_transfer() will return
+ * LIBUSB_ERROR_NOT_SUPPORTED for every transfer where this flag is set.
+ *
+ * Available since libusb-1.0.9.
+ */
+ LIBUSB_TRANSFER_ADD_ZERO_PACKET = 1 << 3,
+};
+
+/** \ingroup libusb_asyncio
+ * Isochronous packet descriptor. */
+struct libusb_iso_packet_descriptor {
+ /** Length of data to request in this packet */
+ unsigned int length;
+
+ /** Amount of data that was actually transferred */
+ unsigned int actual_length;
+
+ /** Status code for this packet */
+ enum libusb_transfer_status status;
+};
+
+struct libusb_transfer;
+
+/** \ingroup libusb_asyncio
+ * Asynchronous transfer callback function type. When submitting asynchronous
+ * transfers, you pass a pointer to a callback function of this type via the
+ * \ref libusb_transfer::callback "callback" member of the libusb_transfer
+ * structure. libusb will call this function later, when the transfer has
+ * completed or failed. See \ref libusb_asyncio for more information.
+ * \param transfer The libusb_transfer struct the callback function is being
+ * notified about.
+ */
+typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer);
+
+/** \ingroup libusb_asyncio
+ * The generic USB transfer structure. The user populates this structure and
+ * then submits it in order to request a transfer. After the transfer has
+ * completed, the library populates the transfer with the results and passes
+ * it back to the user.
+ */
+struct libusb_transfer {
+ /** Handle of the device that this transfer will be submitted to */
+ libusb_device_handle *dev_handle;
+
+ /** A bitwise OR combination of \ref libusb_transfer_flags. */
+ uint8_t flags;
+
+ /** Address of the endpoint where this transfer will be sent. */
+ unsigned char endpoint;
+
+ /** Type of the endpoint from \ref libusb_transfer_type */
+ unsigned char type;
+
+ /** Timeout for this transfer in milliseconds. A value of 0 indicates no
+ * timeout. */
+ unsigned int timeout;
+
+ /** The status of the transfer. Read-only, and only for use within
+ * transfer callback function.
+ *
+ * If this is an isochronous transfer, this field may read COMPLETED even
+ * if there were errors in the frames. Use the
+ * \ref libusb_iso_packet_descriptor::status "status" field in each packet
+ * to determine if errors occurred. */
+ enum libusb_transfer_status status;
+
+ /** Length of the data buffer */
+ int length;
+
+ /** Actual length of data that was transferred. Read-only, and only for
+ * use within transfer callback function. Not valid for isochronous
+ * endpoint transfers. */
+ int actual_length;
+
+ /** Callback function. This will be invoked when the transfer completes,
+ * fails, or is cancelled. */
+ libusb_transfer_cb_fn callback;
+
+ /** User context data to pass to the callback function. */
+ void *user_data;
+
+ /** Data buffer */
+ unsigned char *buffer;
+
+ /** Number of isochronous packets. Only used for I/O with isochronous
+ * endpoints. */
+ int num_iso_packets;
+
+ /** Isochronous packet descriptors, for isochronous transfers only. */
+ struct libusb_iso_packet_descriptor iso_packet_desc[ZERO_SIZED_ARRAY];
+};
+
+/** \ingroup libusb_misc
+ * Capabilities supported by an instance of libusb on the current running
+ * platform. Test if the loaded library supports a given capability by calling
+ * \ref libusb_has_capability().
+ */
+enum libusb_capability {
+ /** The libusb_has_capability() API is available. */
+ LIBUSB_CAP_HAS_CAPABILITY = 0x0000,
+ /** Hotplug support is available on this platform. */
+ LIBUSB_CAP_HAS_HOTPLUG = 0x0001,
+ /** The library can access HID devices without requiring user intervention.
+ * Note that before being able to actually access an HID device, you may
+ * still have to call additional libusb functions such as
+ * \ref libusb_detach_kernel_driver(). */
+ LIBUSB_CAP_HAS_HID_ACCESS = 0x0100,
+ /** The library supports detaching of the default USB driver, using
+ * \ref libusb_detach_kernel_driver(), if one is set by the OS kernel */
+ LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101
+};
+
+/** \ingroup libusb_lib
+ * Log message levels.
+ * - LIBUSB_LOG_LEVEL_NONE (0) : no messages ever printed by the library (default)
+ * - LIBUSB_LOG_LEVEL_ERROR (1) : error messages are printed to stderr
+ * - LIBUSB_LOG_LEVEL_WARNING (2) : warning and error messages are printed to stderr
+ * - LIBUSB_LOG_LEVEL_INFO (3) : informational messages are printed to stderr
+ * - LIBUSB_LOG_LEVEL_DEBUG (4) : debug and informational messages are printed to stderr
+ */
+enum libusb_log_level {
+ LIBUSB_LOG_LEVEL_NONE = 0,
+ LIBUSB_LOG_LEVEL_ERROR = 1,
+ LIBUSB_LOG_LEVEL_WARNING = 2,
+ LIBUSB_LOG_LEVEL_INFO = 3,
+ LIBUSB_LOG_LEVEL_DEBUG = 4,
+};
+
+int LIBUSB_CALL libusb_init(libusb_context **ctx);
+void LIBUSB_CALL libusb_exit(libusb_context *ctx);
+LIBUSB_DEPRECATED_FOR(libusb_set_option)
+void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level);
+const struct libusb_version * LIBUSB_CALL libusb_get_version(void);
+int LIBUSB_CALL libusb_has_capability(uint32_t capability);
+const char * LIBUSB_CALL libusb_error_name(int errcode);
+int LIBUSB_CALL libusb_setlocale(const char *locale);
+const char * LIBUSB_CALL libusb_strerror(enum libusb_error errcode);
+
+ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx,
+ libusb_device ***list);
+void LIBUSB_CALL libusb_free_device_list(libusb_device **list,
+ int unref_devices);
+libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev);
+void LIBUSB_CALL libusb_unref_device(libusb_device *dev);
+
+int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev,
+ int *config);
+int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev,
+ struct libusb_device_descriptor *desc);
+int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev,
+ struct libusb_config_descriptor **config);
+int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev,
+ uint8_t config_index, struct libusb_config_descriptor **config);
+int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev,
+ uint8_t bConfigurationValue, struct libusb_config_descriptor **config);
+void LIBUSB_CALL libusb_free_config_descriptor(
+ struct libusb_config_descriptor *config);
+int LIBUSB_CALL libusb_get_ss_endpoint_companion_descriptor(
+ struct libusb_context *ctx,
+ const struct libusb_endpoint_descriptor *endpoint,
+ struct libusb_ss_endpoint_companion_descriptor **ep_comp);
+void LIBUSB_CALL libusb_free_ss_endpoint_companion_descriptor(
+ struct libusb_ss_endpoint_companion_descriptor *ep_comp);
+int LIBUSB_CALL libusb_get_bos_descriptor(libusb_device_handle *dev_handle,
+ struct libusb_bos_descriptor **bos);
+void LIBUSB_CALL libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos);
+int LIBUSB_CALL libusb_get_usb_2_0_extension_descriptor(
+ struct libusb_context *ctx,
+ struct libusb_bos_dev_capability_descriptor *dev_cap,
+ struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension);
+void LIBUSB_CALL libusb_free_usb_2_0_extension_descriptor(
+ struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension);
+int LIBUSB_CALL libusb_get_ss_usb_device_capability_descriptor(
+ struct libusb_context *ctx,
+ struct libusb_bos_dev_capability_descriptor *dev_cap,
+ struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap);
+void LIBUSB_CALL libusb_free_ss_usb_device_capability_descriptor(
+ struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap);
+int LIBUSB_CALL libusb_get_container_id_descriptor(struct libusb_context *ctx,
+ struct libusb_bos_dev_capability_descriptor *dev_cap,
+ struct libusb_container_id_descriptor **container_id);
+void LIBUSB_CALL libusb_free_container_id_descriptor(
+ struct libusb_container_id_descriptor *container_id);
+uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev);
+uint8_t LIBUSB_CALL libusb_get_port_number(libusb_device *dev);
+int LIBUSB_CALL libusb_get_port_numbers(libusb_device *dev, uint8_t* port_numbers, int port_numbers_len);
+LIBUSB_DEPRECATED_FOR(libusb_get_port_numbers)
+int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_length);
+libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev);
+uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev);
+int LIBUSB_CALL libusb_get_device_speed(libusb_device *dev);
+int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev,
+ unsigned char endpoint);
+int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev,
+ unsigned char endpoint);
+
+int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **dev_handle);
+void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle);
+libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle);
+
+int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev_handle,
+ int configuration);
+int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev_handle,
+ int interface_number);
+int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev_handle,
+ int interface_number);
+
+libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
+ libusb_context *ctx, uint16_t vendor_id, uint16_t product_id);
+
+int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
+ int interface_number, int alternate_setting);
+int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev_handle,
+ unsigned char endpoint);
+int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev_handle);
+
+int LIBUSB_CALL libusb_alloc_streams(libusb_device_handle *dev_handle,
+ uint32_t num_streams, unsigned char *endpoints, int num_endpoints);
+int LIBUSB_CALL libusb_free_streams(libusb_device_handle *dev_handle,
+ unsigned char *endpoints, int num_endpoints);
+
+unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
+ size_t length);
+int LIBUSB_CALL libusb_dev_mem_free(libusb_device_handle *dev_handle,
+ unsigned char *buffer, size_t length);
+
+int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev_handle,
+ int interface_number);
+int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
+ int interface_number);
+int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
+ int interface_number);
+int LIBUSB_CALL libusb_set_auto_detach_kernel_driver(
+ libusb_device_handle *dev_handle, int enable);
+
+/* async I/O */
+
+/** \ingroup libusb_asyncio
+ * Get the data section of a control transfer. This convenience function is here
+ * to remind you that the data does not start until 8 bytes into the actual
+ * buffer, as the setup packet comes first.
+ *
+ * Calling this function only makes sense from a transfer callback function,
+ * or situations where you have already allocated a suitably sized buffer at
+ * transfer->buffer.
+ *
+ * \param transfer a transfer
+ * \returns pointer to the first byte of the data section
+ */
+static inline unsigned char *libusb_control_transfer_get_data(
+ struct libusb_transfer *transfer)
+{
+ return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
+}
+
+/** \ingroup libusb_asyncio
+ * Get the control setup packet of a control transfer. This convenience
+ * function is here to remind you that the control setup occupies the first
+ * 8 bytes of the transfer data buffer.
+ *
+ * Calling this function only makes sense from a transfer callback function,
+ * or situations where you have already allocated a suitably sized buffer at
+ * transfer->buffer.
+ *
+ * \param transfer a transfer
+ * \returns a casted pointer to the start of the transfer data buffer
+ */
+static inline struct libusb_control_setup *libusb_control_transfer_get_setup(
+ struct libusb_transfer *transfer)
+{
+ return (struct libusb_control_setup *)(void *) transfer->buffer;
+}
+
+/** \ingroup libusb_asyncio
+ * Helper function to populate the setup packet (first 8 bytes of the data
+ * buffer) for a control transfer. The wIndex, wValue and wLength values should
+ * be given in host-endian byte order.
+ *
+ * \param buffer buffer to output the setup packet into
+ * This pointer must be aligned to at least 2 bytes boundary.
+ * \param bmRequestType see the
+ * \ref libusb_control_setup::bmRequestType "bmRequestType" field of
+ * \ref libusb_control_setup
+ * \param bRequest see the
+ * \ref libusb_control_setup::bRequest "bRequest" field of
+ * \ref libusb_control_setup
+ * \param wValue see the
+ * \ref libusb_control_setup::wValue "wValue" field of
+ * \ref libusb_control_setup
+ * \param wIndex see the
+ * \ref libusb_control_setup::wIndex "wIndex" field of
+ * \ref libusb_control_setup
+ * \param wLength see the
+ * \ref libusb_control_setup::wLength "wLength" field of
+ * \ref libusb_control_setup
+ */
+static inline void libusb_fill_control_setup(unsigned char *buffer,
+ uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
+ uint16_t wLength)
+{
+ struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer;
+ setup->bmRequestType = bmRequestType;
+ setup->bRequest = bRequest;
+ setup->wValue = libusb_cpu_to_le16(wValue);
+ setup->wIndex = libusb_cpu_to_le16(wIndex);
+ setup->wLength = libusb_cpu_to_le16(wLength);
+}
+
+struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets);
+int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer);
+int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer);
+void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer);
+void LIBUSB_CALL libusb_transfer_set_stream_id(
+ struct libusb_transfer *transfer, uint32_t stream_id);
+uint32_t LIBUSB_CALL libusb_transfer_get_stream_id(
+ struct libusb_transfer *transfer);
+
+/** \ingroup libusb_asyncio
+ * Helper function to populate the required \ref libusb_transfer fields
+ * for a control transfer.
+ *
+ * If you pass a transfer buffer to this function, the first 8 bytes will
+ * be interpreted as a control setup packet, and the wLength field will be
+ * used to automatically populate the \ref libusb_transfer::length "length"
+ * field of the transfer. Therefore the recommended approach is:
+ * -# Allocate a suitably sized data buffer (including space for control setup)
+ * -# Call libusb_fill_control_setup()
+ * -# If this is a host-to-device transfer with a data stage, put the data
+ * in place after the setup packet
+ * -# Call this function
+ * -# Call libusb_submit_transfer()
+ *
+ * It is also legal to pass a NULL buffer to this function, in which case this
+ * function will not attempt to populate the length field. Remember that you
+ * must then populate the buffer and length fields later.
+ *
+ * \param transfer the transfer to populate
+ * \param dev_handle handle of the device that will handle the transfer
+ * \param buffer data buffer. If provided, this function will interpret the
+ * first 8 bytes as a setup packet and infer the transfer length from that.
+ * This pointer must be aligned to at least 2 bytes boundary.
+ * \param callback callback function to be invoked on transfer completion
+ * \param user_data user data to pass to callback function
+ * \param timeout timeout for the transfer in milliseconds
+ */
+static inline void libusb_fill_control_transfer(
+ struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
+ unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data,
+ unsigned int timeout)
+{
+ struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer;
+ transfer->dev_handle = dev_handle;
+ transfer->endpoint = 0;
+ transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL;
+ transfer->timeout = timeout;
+ transfer->buffer = buffer;
+ if (setup)
+ transfer->length = (int) (LIBUSB_CONTROL_SETUP_SIZE
+ + libusb_le16_to_cpu(setup->wLength));
+ transfer->user_data = user_data;
+ transfer->callback = callback;
+}
+
+/** \ingroup libusb_asyncio
+ * Helper function to populate the required \ref libusb_transfer fields
+ * for a bulk transfer.
+ *
+ * \param transfer the transfer to populate
+ * \param dev_handle handle of the device that will handle the transfer
+ * \param endpoint address of the endpoint where this transfer will be sent
+ * \param buffer data buffer
+ * \param length length of data buffer
+ * \param callback callback function to be invoked on transfer completion
+ * \param user_data user data to pass to callback function
+ * \param timeout timeout for the transfer in milliseconds
+ */
+static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer,
+ libusb_device_handle *dev_handle, unsigned char endpoint,
+ unsigned char *buffer, int length, libusb_transfer_cb_fn callback,
+ void *user_data, unsigned int timeout)
+{
+ transfer->dev_handle = dev_handle;
+ transfer->endpoint = endpoint;
+ transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
+ transfer->timeout = timeout;
+ transfer->buffer = buffer;
+ transfer->length = length;
+ transfer->user_data = user_data;
+ transfer->callback = callback;
+}
+
+/** \ingroup libusb_asyncio
+ * Helper function to populate the required \ref libusb_transfer fields
+ * for a bulk transfer using bulk streams.
+ *
+ * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
+ *
+ * \param transfer the transfer to populate
+ * \param dev_handle handle of the device that will handle the transfer
+ * \param endpoint address of the endpoint where this transfer will be sent
+ * \param stream_id bulk stream id for this transfer
+ * \param buffer data buffer
+ * \param length length of data buffer
+ * \param callback callback function to be invoked on transfer completion
+ * \param user_data user data to pass to callback function
+ * \param timeout timeout for the transfer in milliseconds
+ */
+static inline void libusb_fill_bulk_stream_transfer(
+ struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
+ unsigned char endpoint, uint32_t stream_id,
+ unsigned char *buffer, int length, libusb_transfer_cb_fn callback,
+ void *user_data, unsigned int timeout)
+{
+ libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer,
+ length, callback, user_data, timeout);
+ transfer->type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
+ libusb_transfer_set_stream_id(transfer, stream_id);
+}
+
+/** \ingroup libusb_asyncio
+ * Helper function to populate the required \ref libusb_transfer fields
+ * for an interrupt transfer.
+ *
+ * \param transfer the transfer to populate
+ * \param dev_handle handle of the device that will handle the transfer
+ * \param endpoint address of the endpoint where this transfer will be sent
+ * \param buffer data buffer
+ * \param length length of data buffer
+ * \param callback callback function to be invoked on transfer completion
+ * \param user_data user data to pass to callback function
+ * \param timeout timeout for the transfer in milliseconds
+ */
+static inline void libusb_fill_interrupt_transfer(
+ struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
+ unsigned char endpoint, unsigned char *buffer, int length,
+ libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
+{
+ transfer->dev_handle = dev_handle;
+ transfer->endpoint = endpoint;
+ transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
+ transfer->timeout = timeout;
+ transfer->buffer = buffer;
+ transfer->length = length;
+ transfer->user_data = user_data;
+ transfer->callback = callback;
+}
+
+/** \ingroup libusb_asyncio
+ * Helper function to populate the required \ref libusb_transfer fields
+ * for an isochronous transfer.
+ *
+ * \param transfer the transfer to populate
+ * \param dev_handle handle of the device that will handle the transfer
+ * \param endpoint address of the endpoint where this transfer will be sent
+ * \param buffer data buffer
+ * \param length length of data buffer
+ * \param num_iso_packets the number of isochronous packets
+ * \param callback callback function to be invoked on transfer completion
+ * \param user_data user data to pass to callback function
+ * \param timeout timeout for the transfer in milliseconds
+ */
+static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer,
+ libusb_device_handle *dev_handle, unsigned char endpoint,
+ unsigned char *buffer, int length, int num_iso_packets,
+ libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
+{
+ transfer->dev_handle = dev_handle;
+ transfer->endpoint = endpoint;
+ transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
+ transfer->timeout = timeout;
+ transfer->buffer = buffer;
+ transfer->length = length;
+ transfer->num_iso_packets = num_iso_packets;
+ transfer->user_data = user_data;
+ transfer->callback = callback;
+}
+
+/** \ingroup libusb_asyncio
+ * Convenience function to set the length of all packets in an isochronous
+ * transfer, based on the num_iso_packets field in the transfer structure.
+ *
+ * \param transfer a transfer
+ * \param length the length to set in each isochronous packet descriptor
+ * \see libusb_get_max_packet_size()
+ */
+static inline void libusb_set_iso_packet_lengths(
+ struct libusb_transfer *transfer, unsigned int length)
+{
+ int i;
+ for (i = 0; i < transfer->num_iso_packets; i++)
+ transfer->iso_packet_desc[i].length = length;
+}
+
+/** \ingroup libusb_asyncio
+ * Convenience function to locate the position of an isochronous packet
+ * within the buffer of an isochronous transfer.
+ *
+ * This is a thorough function which loops through all preceding packets,
+ * accumulating their lengths to find the position of the specified packet.
+ * Typically you will assign equal lengths to each packet in the transfer,
+ * and hence the above method is sub-optimal. You may wish to use
+ * libusb_get_iso_packet_buffer_simple() instead.
+ *
+ * \param transfer a transfer
+ * \param packet the packet to return the address of
+ * \returns the base address of the packet buffer inside the transfer buffer,
+ * or NULL if the packet does not exist.
+ * \see libusb_get_iso_packet_buffer_simple()
+ */
+static inline unsigned char *libusb_get_iso_packet_buffer(
+ struct libusb_transfer *transfer, unsigned int packet)
+{
+ int i;
+ size_t offset = 0;
+ int _packet;
+
+ /* oops..slight bug in the API. packet is an unsigned int, but we use
+ * signed integers almost everywhere else. range-check and convert to
+ * signed to avoid compiler warnings. FIXME for libusb-2. */
+ if (packet > INT_MAX)
+ return NULL;
+ _packet = (int) packet;
+
+ if (_packet >= transfer->num_iso_packets)
+ return NULL;
+
+ for (i = 0; i < _packet; i++)
+ offset += transfer->iso_packet_desc[i].length;
+
+ return transfer->buffer + offset;
+}
+
+/** \ingroup libusb_asyncio
+ * Convenience function to locate the position of an isochronous packet
+ * within the buffer of an isochronous transfer, for transfers where each
+ * packet is of identical size.
+ *
+ * This function relies on the assumption that every packet within the transfer
+ * is of identical size to the first packet. Calculating the location of
+ * the packet buffer is then just a simple calculation:
+ * buffer + (packet_size * packet)
+ *
+ * Do not use this function on transfers other than those that have identical
+ * packet lengths for each packet.
+ *
+ * \param transfer a transfer
+ * \param packet the packet to return the address of
+ * \returns the base address of the packet buffer inside the transfer buffer,
+ * or NULL if the packet does not exist.
+ * \see libusb_get_iso_packet_buffer()
+ */
+static inline unsigned char *libusb_get_iso_packet_buffer_simple(
+ struct libusb_transfer *transfer, unsigned int packet)
+{
+ int _packet;
+
+ /* oops..slight bug in the API. packet is an unsigned int, but we use
+ * signed integers almost everywhere else. range-check and convert to
+ * signed to avoid compiler warnings. FIXME for libusb-2. */
+ if (packet > INT_MAX)
+ return NULL;
+ _packet = (int) packet;
+
+ if (_packet >= transfer->num_iso_packets)
+ return NULL;
+
+ return transfer->buffer + ((int) transfer->iso_packet_desc[0].length * _packet);
+}
+
+/* sync I/O */
+
+int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle,
+ uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
+ unsigned char *data, uint16_t wLength, unsigned int timeout);
+
+int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle,
+ unsigned char endpoint, unsigned char *data, int length,
+ int *actual_length, unsigned int timeout);
+
+int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle,
+ unsigned char endpoint, unsigned char *data, int length,
+ int *actual_length, unsigned int timeout);
+
+/** \ingroup libusb_desc
+ * Retrieve a descriptor from the default control pipe.
+ * This is a convenience function which formulates the appropriate control
+ * message to retrieve the descriptor.
+ *
+ * \param dev_handle a device handle
+ * \param desc_type the descriptor type, see \ref libusb_descriptor_type
+ * \param desc_index the index of the descriptor to retrieve
+ * \param data output buffer for descriptor
+ * \param length size of data buffer
+ * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
+ */
+static inline int libusb_get_descriptor(libusb_device_handle *dev_handle,
+ uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length)
+{
+ return libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
+ LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t) ((desc_type << 8) | desc_index),
+ 0, data, (uint16_t) length, 1000);
+}
+
+/** \ingroup libusb_desc
+ * Retrieve a descriptor from a device.
+ * This is a convenience function which formulates the appropriate control
+ * message to retrieve the descriptor. The string returned is Unicode, as
+ * detailed in the USB specifications.
+ *
+ * \param dev_handle a device handle
+ * \param desc_index the index of the descriptor to retrieve
+ * \param langid the language ID for the string descriptor
+ * \param data output buffer for descriptor
+ * \param length size of data buffer
+ * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
+ * \see libusb_get_string_descriptor_ascii()
+ */
+static inline int libusb_get_string_descriptor(libusb_device_handle *dev_handle,
+ uint8_t desc_index, uint16_t langid, unsigned char *data, int length)
+{
+ return libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
+ LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t)((LIBUSB_DT_STRING << 8) | desc_index),
+ langid, data, (uint16_t) length, 1000);
+}
+
+int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle,
+ uint8_t desc_index, unsigned char *data, int length);
+
+/* polling and timeouts */
+
+int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx);
+void LIBUSB_CALL libusb_lock_events(libusb_context *ctx);
+void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx);
+int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx);
+int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx);
+void LIBUSB_CALL libusb_interrupt_event_handler(libusb_context *ctx);
+void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx);
+void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx);
+int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv);
+
+int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx,
+ struct timeval *tv);
+int LIBUSB_CALL libusb_handle_events_timeout_completed(libusb_context *ctx,
+ struct timeval *tv, int *completed);
+int LIBUSB_CALL libusb_handle_events(libusb_context *ctx);
+int LIBUSB_CALL libusb_handle_events_completed(libusb_context *ctx, int *completed);
+int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx,
+ struct timeval *tv);
+int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx);
+int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx,
+ struct timeval *tv);
+
+/** \ingroup libusb_poll
+ * File descriptor for polling
+ */
+struct libusb_pollfd {
+ /** Numeric file descriptor */
+ int fd;
+
+ /** Event flags to poll for from . POLLIN indicates that you
+ * should monitor this file descriptor for becoming ready to read from,
+ * and POLLOUT indicates that you should monitor this file descriptor for
+ * nonblocking write readiness. */
+ short events;
+};
+
+/** \ingroup libusb_poll
+ * Callback function, invoked when a new file descriptor should be added
+ * to the set of file descriptors monitored for events.
+ * \param fd the new file descriptor
+ * \param events events to monitor for, see \ref libusb_pollfd for a
+ * description
+ * \param user_data User data pointer specified in
+ * libusb_set_pollfd_notifiers() call
+ * \see libusb_set_pollfd_notifiers()
+ */
+typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events,
+ void *user_data);
+
+/** \ingroup libusb_poll
+ * Callback function, invoked when a file descriptor should be removed from
+ * the set of file descriptors being monitored for events. After returning
+ * from this callback, do not use that file descriptor again.
+ * \param fd the file descriptor to stop monitoring
+ * \param user_data User data pointer specified in
+ * libusb_set_pollfd_notifiers() call
+ * \see libusb_set_pollfd_notifiers()
+ */
+typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data);
+
+const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
+ libusb_context *ctx);
+void LIBUSB_CALL libusb_free_pollfds(const struct libusb_pollfd **pollfds);
+void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx,
+ libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
+ void *user_data);
+
+/** \ingroup libusb_hotplug
+ * Callback handle.
+ *
+ * Callbacks handles are generated by libusb_hotplug_register_callback()
+ * and can be used to deregister callbacks. Callback handles are unique
+ * per libusb_context and it is safe to call libusb_hotplug_deregister_callback()
+ * on an already deregisted callback.
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ *
+ * For more information, see \ref libusb_hotplug.
+ */
+typedef int libusb_hotplug_callback_handle;
+
+/** \ingroup libusb_hotplug
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ *
+ * Flags for hotplug events */
+typedef enum {
+ /** Default value when not using any flags. */
+ LIBUSB_HOTPLUG_NO_FLAGS = 0,
+
+ /** Arm the callback and fire it for all matching currently attached devices. */
+ LIBUSB_HOTPLUG_ENUMERATE = 1<<0,
+} libusb_hotplug_flag;
+
+/** \ingroup libusb_hotplug
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ *
+ * Hotplug events */
+typedef enum {
+ /** A device has been plugged in and is ready to use */
+ LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01,
+
+ /** A device has left and is no longer available.
+ * It is the user's responsibility to call libusb_close on any handle associated with a disconnected device.
+ * It is safe to call libusb_get_device_descriptor on a device that has left */
+ LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT = 0x02,
+} libusb_hotplug_event;
+
+/** \ingroup libusb_hotplug
+ * Wildcard matching for hotplug events */
+#define LIBUSB_HOTPLUG_MATCH_ANY -1
+
+/** \ingroup libusb_hotplug
+ * Hotplug callback function type. When requesting hotplug event notifications,
+ * you pass a pointer to a callback function of this type.
+ *
+ * This callback may be called by an internal event thread and as such it is
+ * recommended the callback do minimal processing before returning.
+ *
+ * libusb will call this function later, when a matching event had happened on
+ * a matching device. See \ref libusb_hotplug for more information.
+ *
+ * It is safe to call either libusb_hotplug_register_callback() or
+ * libusb_hotplug_deregister_callback() from within a callback function.
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ *
+ * \param ctx context of this notification
+ * \param device libusb_device this event occurred on
+ * \param event event that occurred
+ * \param user_data user data provided when this callback was registered
+ * \returns bool whether this callback is finished processing events.
+ * returning 1 will cause this callback to be deregistered
+ */
+typedef int (LIBUSB_CALL *libusb_hotplug_callback_fn)(libusb_context *ctx,
+ libusb_device *device,
+ libusb_hotplug_event event,
+ void *user_data);
+
+/** \ingroup libusb_hotplug
+ * Register a hotplug callback function
+ *
+ * Register a callback with the libusb_context. The callback will fire
+ * when a matching event occurs on a matching device. The callback is
+ * armed until either it is deregistered with libusb_hotplug_deregister_callback()
+ * or the supplied callback returns 1 to indicate it is finished processing events.
+ *
+ * If the \ref LIBUSB_HOTPLUG_ENUMERATE is passed the callback will be
+ * called with a \ref LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED for all devices
+ * already plugged into the machine. Note that libusb modifies its internal
+ * device list from a separate thread, while calling hotplug callbacks from
+ * libusb_handle_events(), so it is possible for a device to already be present
+ * on, or removed from, its internal device list, while the hotplug callbacks
+ * still need to be dispatched. This means that when using \ref
+ * LIBUSB_HOTPLUG_ENUMERATE, your callback may be called twice for the arrival
+ * of the same device, once from libusb_hotplug_register_callback() and once
+ * from libusb_handle_events(); and/or your callback may be called for the
+ * removal of a device for which an arrived call was never made.
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ *
+ * \param[in] ctx context to register this callback with
+ * \param[in] events bitwise or of events that will trigger this callback. See \ref
+ * libusb_hotplug_event
+ * \param[in] flags hotplug callback flags. See \ref libusb_hotplug_flag
+ * \param[in] vendor_id the vendor id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY
+ * \param[in] product_id the product id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY
+ * \param[in] dev_class the device class to match or \ref LIBUSB_HOTPLUG_MATCH_ANY
+ * \param[in] cb_fn the function to be invoked on a matching event/device
+ * \param[in] user_data user data to pass to the callback function
+ * \param[out] callback_handle pointer to store the handle of the allocated callback (can be NULL)
+ * \returns LIBUSB_SUCCESS on success LIBUSB_ERROR code on failure
+ */
+int LIBUSB_CALL libusb_hotplug_register_callback(libusb_context *ctx,
+ libusb_hotplug_event events,
+ libusb_hotplug_flag flags,
+ int vendor_id, int product_id,
+ int dev_class,
+ libusb_hotplug_callback_fn cb_fn,
+ void *user_data,
+ libusb_hotplug_callback_handle *callback_handle);
+
+/** \ingroup libusb_hotplug
+ * Deregisters a hotplug callback.
+ *
+ * Deregister a callback from a libusb_context. This function is safe to call from within
+ * a hotplug callback.
+ *
+ * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
+ *
+ * \param[in] ctx context this callback is registered with
+ * \param[in] callback_handle the handle of the callback to deregister
+ */
+void LIBUSB_CALL libusb_hotplug_deregister_callback(libusb_context *ctx,
+ libusb_hotplug_callback_handle callback_handle);
+
+/** \ingroup libusb_lib
+ * Available option values for libusb_set_option().
+ */
+enum libusb_option {
+ /** Set the log message verbosity.
+ *
+ * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
+ * printed. If you choose to increase the message verbosity level, ensure
+ * that your application does not close the stderr file descriptor.
+ *
+ * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
+ * with its message logging and most of the time, will only log messages that
+ * explain error conditions and other oddities. This will help you debug
+ * your software.
+ *
+ * If the LIBUSB_DEBUG environment variable was set when libusb was
+ * initialized, this function does nothing: the message verbosity is fixed
+ * to the value in the environment variable.
+ *
+ * If libusb was compiled without any message logging, this function does
+ * nothing: you'll never get any messages.
+ *
+ * If libusb was compiled with verbose debug message logging, this function
+ * does nothing: you'll always get messages from all levels.
+ */
+ LIBUSB_OPTION_LOG_LEVEL,
+
+ /** Use the UsbDk backend for a specific context, if available.
+ *
+ * This option should be set immediately after calling libusb_init(), otherwise
+ * unspecified behavior may occur.
+ *
+ * Only valid on Windows.
+ */
+ LIBUSB_OPTION_USE_USBDK,
+};
+
+int LIBUSB_CALL libusb_set_option(libusb_context *ctx, enum libusb_option option, ...);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/vendor/github.com/karalabe/usb/libusb/libusb/libusbi.h b/vendor/github.com/karalabe/usb/libusb/libusb/libusbi.h
new file mode 100644
index 000000000..31d6ce98d
--- /dev/null
+++ b/vendor/github.com/karalabe/usb/libusb/libusb/libusbi.h
@@ -0,0 +1,1165 @@
+/*
+ * Internal header for libusb
+ * Copyright © 2007-2009 Daniel Drake
+ * Copyright © 2001 Johannes Erdfelt