proto

package
v1.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2022 License: BSD-3-Clause Imports: 16 Imported by: 21,564

Documentation

Overview

Package proto provides functions operating on protocol buffer messages.

For documentation on protocol buffers in general, see:

https://developers.google.com/protocol-buffers

For a tutorial on using protocol buffers with Go, see:

https://developers.google.com/protocol-buffers/docs/gotutorial

For a guide to generated Go protocol buffer code, see:

https://developers.google.com/protocol-buffers/docs/reference/go-generated

Binary serialization

This package contains functions to convert to and from the wire format, an efficient binary serialization of protocol buffers.

• Size reports the size of a message in the wire format.

• Marshal converts a message to the wire format. The MarshalOptions type provides more control over wire marshaling.

• Unmarshal converts a message from the wire format. The UnmarshalOptions type provides more control over wire unmarshaling.

Basic message operations

• Clone makes a deep copy of a message.

• Merge merges the content of a message into another.

• Equal compares two messages. For more control over comparisons and detailed reporting of differences, see package "google.golang.org/protobuf/testing/protocmp".

• Reset clears the content of a message.

• CheckInitialized reports whether all required fields in a message are set.

Optional scalar constructors

The API for some generated messages represents optional scalar fields as pointers to a value. For example, an optional string field has the Go type *string.

• Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, and String take a value and return a pointer to a new instance of it, to simplify construction of optional field values.

Generated enum types usually have an Enum method which performs the same operation.

Optional scalar fields are only supported in proto2.

Extension accessors

• HasExtension, GetExtension, SetExtension, and ClearExtension access extension field values in a protocol buffer message.

Extension fields are only supported in proto2.

• Package "google.golang.org/protobuf/encoding/protojson" converts messages to and from JSON.

• Package "google.golang.org/protobuf/encoding/prototext" converts messages to and from the text format.

• Package "google.golang.org/protobuf/reflect/protoreflect" provides a reflection interface for protocol buffer data types.

• Package "google.golang.org/protobuf/testing/protocmp" provides features to compare protocol buffer messages with the "github.com/google/go-cmp/cmp" package.

• Package "google.golang.org/protobuf/types/dynamicpb" provides a dynamic message type, suitable for working with messages where the protocol buffer type is only known at runtime.

This module contains additional packages for more specialized use cases. Consult the individual package documentation for details.

Index

Constants

This section is empty.

Variables

View Source
var Error error

Error matches all errors produced by packages in the protobuf module.

That is, errors.Is(err, Error) reports whether an error is produced by this module.

Functions

func Bool

func Bool(v bool) *bool

Bool stores v in a new bool value and returns a pointer to it.

func CheckInitialized

func CheckInitialized(m Message) error

CheckInitialized returns an error if any required fields in m are not set.

func ClearExtension

func ClearExtension(m Message, xt protoreflect.ExtensionType)

ClearExtension clears an extension field such that subsequent HasExtension calls return false. It panics if m is invalid or if xt does not extend m.

func Equal

func Equal(x, y Message) bool

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 belong to the same message descriptor, have the same set of populated known and extension field values, and the same set of unknown fields values. If either of the top-level messages are invalid, then Equal reports true only if both are invalid.

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 Float32

func Float32(v float32) *float32

Float32 stores v in a new float32 value and returns a pointer to it.

func Float64

func Float64(v float64) *float64

Float64 stores v in a new float64 value and returns a pointer to it.

func GetExtension

func GetExtension(m Message, xt protoreflect.ExtensionType) interface{}

GetExtension retrieves the value for an extension field. If the field is unpopulated, it returns the default value for scalars and an immutable, empty value for lists or messages. It panics if xt does not extend m.

func HasExtension

func HasExtension(m Message, xt protoreflect.ExtensionType) bool

HasExtension reports whether an extension field is populated. It returns false if m is invalid or if xt does not extend m.

func Int32

func Int32(v int32) *int32

Int32 stores v in a new int32 value and returns a pointer to it.

func Int64

func Int64(v int64) *int64

Int64 stores v in a new int64 value and returns a pointer to it.

func Marshal

func Marshal(m Message) ([]byte, error)

Marshal returns the wire-format encoding of m.

func Merge

func Merge(dst, src Message)

Merge merges src into dst, which must be a message with the same descriptor.

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.

It is semantically equivalent to unmarshaling the encoded form of src into dst with the UnmarshalOptions.Merge option specified.

func MessageName added in v1.26.0

func MessageName(m Message) protoreflect.FullName

MessageName returns the full name of m. If m is nil, it returns an empty string.

func RangeExtensions added in v1.22.0

func RangeExtensions(m Message, f func(protoreflect.ExtensionType, interface{}) bool)

RangeExtensions iterates over every populated extension field in m in an undefined order, calling f for each extension type and value encountered. It returns immediately if f returns false. While iterating, mutating operations may only be performed on the current extension field.

func Reset

func Reset(m Message)

Reset clears every field in the message. The resulting message shares no observable memory with its previous state other than the memory for the message itself.

func SetExtension

func SetExtension(m Message, xt protoreflect.ExtensionType, v interface{})

SetExtension stores the value of an extension field. It panics if m is invalid, xt does not extend m, or if type of v is invalid for the specified extension field.

func Size

func Size(m Message) int

Size returns the size in bytes of the wire-format encoding of m.

func String

func String(v string) *string

String stores v in a new string value and returns a pointer to it.

func Uint32

func Uint32(v uint32) *uint32

Uint32 stores v in a new uint32 value and returns a pointer to it.

func Uint64

func Uint64(v uint64) *uint64

Uint64 stores v in a new uint64 value and returns a pointer to it.

func Unmarshal

func Unmarshal(b []byte, m Message) error

Unmarshal parses the wire-format message in b and places the result in m. The provided message must be mutable (e.g., a non-nil pointer to a message).

Types

type MarshalOptions

type MarshalOptions struct {
	pragma.NoUnkeyedLiterals

	// AllowPartial allows messages that have missing required fields to marshal
	// without returning an error. If AllowPartial is false (the default),
	// Marshal will return an error if there are any missing required fields.
	AllowPartial bool

	// Deterministic controls whether the same message will always be
	// serialized to the same bytes within the same binary.
	//
	// Setting this option guarantees that repeated serialization of
	// the same message will return the same bytes, and that different
	// processes of the same binary (which may be executing on different
	// machines) will serialize equal messages to the same bytes.
	// It has no effect on the resulting size of the encoded message compared
	// to a non-deterministic marshal.
	//
	// 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.) must 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.
	Deterministic bool

	// UseCachedSize indicates that the result of a previous Size call
	// may be reused.
	//
	// Setting this option asserts that:
	//
	// 1. Size has previously been called on this message with identical
	// options (except for UseCachedSize itself).
	//
	// 2. The message and all its submessages have not changed in any
	// way since the Size call.
	//
	// If either of these invariants is violated,
	// the results are undefined and may include panics or corrupted output.
	//
	// Implementations MAY take this option into account to provide
	// better performance, but there is no guarantee that they will do so.
	// There is absolutely no guarantee that Size followed by Marshal with
	// UseCachedSize set will perform equivalently to Marshal alone.
	UseCachedSize bool
}

MarshalOptions configures the marshaler.

Example usage:

b, err := MarshalOptions{Deterministic: true}.Marshal(m)

func (MarshalOptions) Marshal

func (o MarshalOptions) Marshal(m Message) ([]byte, error)

Marshal returns the wire-format encoding of m.

func (MarshalOptions) MarshalAppend

func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error)

MarshalAppend appends the wire-format encoding of m to b, returning the result.

func (MarshalOptions) MarshalState

MarshalState returns the wire-format encoding of a message.

This method permits fine-grained control over the marshaler. Most users should use Marshal instead.

func (MarshalOptions) Size

func (o MarshalOptions) Size(m Message) int

Size returns the size in bytes of the wire-format encoding of m.

type Message

type Message = protoreflect.ProtoMessage

Message is the top-level interface that all messages must implement. It provides access to a reflective view of a message. Any implementation of this interface may be used with all functions in the protobuf module that accept a Message, except where otherwise specified.

This is the v2 interface definition for protobuf messages. The v1 interface definition is "github.com/golang/protobuf/proto".Message.

To convert a v1 message to a v2 message, use "github.com/golang/protobuf/proto".MessageV2. To convert a v2 message to a v1 message, use "github.com/golang/protobuf/proto".MessageV1.

func Clone

func Clone(m Message) Message

Clone returns a deep copy of m. If the top-level message is invalid, it returns an invalid message as well.

type UnmarshalOptions

type UnmarshalOptions struct {
	pragma.NoUnkeyedLiterals

	// Merge merges the input into the destination message.
	// The default behavior is to always reset the message before unmarshaling,
	// unless Merge is specified.
	Merge bool

	// AllowPartial accepts input for messages that will result in missing
	// required fields. If AllowPartial is false (the default), Unmarshal will
	// return an error if there are any missing required fields.
	AllowPartial bool

	// If DiscardUnknown is set, unknown fields are ignored.
	DiscardUnknown bool

	// Resolver is used for looking up types when unmarshaling extension fields.
	// If nil, this defaults to using protoregistry.GlobalTypes.
	Resolver interface {
		FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error)
		FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error)
	}

	// RecursionLimit limits how deeply messages may be nested.
	// If zero, a default limit is applied.
	RecursionLimit int
}

UnmarshalOptions configures the unmarshaler.

Example usage:

err := UnmarshalOptions{DiscardUnknown: true}.Unmarshal(b, m)

func (UnmarshalOptions) Unmarshal

func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error

Unmarshal parses the wire-format message in b and places the result in m. The provided message must be mutable (e.g., a non-nil pointer to a message).

func (UnmarshalOptions) UnmarshalState

UnmarshalState parses a wire-format message and places the result in m.

This method permits fine-grained control over the unmarshaler. Most users should use Unmarshal instead.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL