field

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package field bridges the wire-level encoder/decoder and concrete message types by providing optional field presence tracking via Go generics, repeated field encoding/decoding with append semantics, and packed repeated encoding for numeric types.

The Optional[T] generic type tracks explicit field presence for proto3 optional fields and proto2 scalar fields. It distinguishes between an explicitly set zero value and an unset field, enabling correct serialization behavior where zero values are emitted only when explicitly set.

Repeated field functions follow the append pattern: encode functions accept a byte slice b, append encoded bytes, and return the extended slice. Decode functions accept a destination slice, append the decoded value, and return the extended slice. This matches Go idioms like append(slice, elem) and allows callers to accumulate values across multiple calls as DecodeMessage delivers fields with the same field number.

Packed repeated encoding concatenates all scalar values into a single length-delimited field, reducing per-element tag overhead for numeric types. The package validates packability via scalar.Kind.IsPackable and returns ErrNotPackable or panics for unsupported kinds.

Map field encoding and decoding represents map entries as repeated key-value message entries per the protobuf wire format specification. Each entry is a length-delimited field containing an inner key at field number 1 and an inner value at field number 2. The package supports integral and bool key types (validated by ValidMapKeyKind) as well as string key types, with scalar, bytes, string, and message value types. Decode functions return ErrInvalidMapKeyKind when an unsupported key kind is passed. Ordering- independent equality functions (EqualMapScalarScalar, EqualMapStringString, etc.) compare Go maps directly, providing semantic equality regardless of serialization order.

Oneof field support uses a sealed interface variant type system with four concrete types: OneofScalar (covering all 14 scalar kinds), OneofBytes, OneofString, and OneofMessage. The OneofField container enforces mutual exclusivity by holding a single OneofValue at a time; setting a new variant implicitly clears the previous one. The zero value of OneofField represents an unset oneof, requiring no constructor. Encode, decode, size, and equality functions follow the existing append-style, stateless codec patterns.

Package-level enc and dec instances (var enc = encode.NewEncoder(), var dec = decode.NewDecoder()) follow the var sc = scalar.NewCodec() pattern established in encode/size.go and decode/decoder.go, avoiding repeated allocation of stateless codec structs.

This package depends on errors and fmt from the standard library, and on wire/, scalar/, encode/, and decode/ from the module.

Package field -- mapfield_decode.go contains map field decoding functions that decode wire-format map entries into typed Go maps.

Package field -- mapfield_encode.go contains map field encoding functions, shared validation helpers, and the map key kind lookup table.

Package field -- mapfield_reflect.go contains map field equality comparison functions used for deep comparison of protobuf map fields.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidMapKeyKind = errors.New("field: invalid map key kind")

ErrInvalidMapKeyKind indicates that the given scalar kind is not a valid protobuf map key type. It is returned by DecodeMap* functions when an unsupported key kind is passed.

View Source
var ErrNotPackable = errors.New("field: kind does not support packed encoding")

ErrNotPackable indicates that the given scalar kind does not support packed encoding. It is returned by DecodePackedScalar when an unsupported kind is passed.

View Source
var ErrUnsupportedOneofGroup = errors.New("field: DecodeOneofVariant does not support kind group")

ErrUnsupportedOneofGroup indicates that DecodeOneofVariant was called with KindGroup, which is not supported.

Functions

func DecodeMapScalarBytes

func DecodeMapScalarBytes(dest map[uint64][]byte, keyKind scalar.Kind, entryData []byte) (map[uint64][]byte, error)

DecodeMapScalarBytes decodes a single map entry with scalar key and bytes value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. Missing value fields default to nil. It returns ErrInvalidMapKeyKind if keyKind is not a valid map key type.

func DecodeMapScalarMessage

func DecodeMapScalarMessage(dest map[uint64][]byte, keyKind scalar.Kind, entryData []byte) (map[uint64][]byte, error)

DecodeMapScalarMessage decodes a single map entry with scalar key and pre-encoded message value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. The value bytes are raw message bytes; the caller is responsible for further decoding the nested message. Missing value fields default to nil. It returns ErrInvalidMapKeyKind if keyKind is not a valid map key type.

func DecodeMapScalarScalar

func DecodeMapScalarScalar(dest map[uint64]uint64, keyKind scalar.Kind, valueKind scalar.Kind, entryData []byte) (map[uint64]uint64, error)

DecodeMapScalarScalar decodes a single map entry from entryData (the payload after the outer length prefix has been consumed) and inserts the key-value pair into dest. If dest is nil, a new map is allocated. Missing key fields default to 0; missing value fields default to 0. It returns ErrInvalidMapKeyKind if keyKind is not a valid map key type.

func DecodeMapScalarString

func DecodeMapScalarString(dest map[uint64]string, keyKind scalar.Kind, entryData []byte) (map[uint64]string, error)

DecodeMapScalarString decodes a single map entry with scalar key and string value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. Missing value fields default to empty string. It returns ErrInvalidMapKeyKind if keyKind is not a valid map key type.

func DecodeMapStringBytes

func DecodeMapStringBytes(dest map[string][]byte, entryData []byte) (map[string][]byte, error)

DecodeMapStringBytes decodes a single map entry with string key and bytes value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. Missing key fields default to empty string; missing value fields default to nil.

func DecodeMapStringMessage

func DecodeMapStringMessage(dest map[string][]byte, entryData []byte) (map[string][]byte, error)

DecodeMapStringMessage decodes a single map entry with string key and pre-encoded message value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. The value bytes are raw message bytes; the caller is responsible for further decoding the nested message. Missing key fields default to empty string; missing value fields default to nil.

func DecodeMapStringScalar

func DecodeMapStringScalar(dest map[string]uint64, valueKind scalar.Kind, entryData []byte) (map[string]uint64, error)

DecodeMapStringScalar decodes a single map entry with string key and scalar value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. Missing key fields default to empty string; missing value fields default to 0. It returns an error if valueKind is not a valid scalar value kind.

func DecodeMapStringString

func DecodeMapStringString(dest map[string]string, entryData []byte) (map[string]string, error)

DecodeMapStringString decodes a single map entry with string key and string value from entryData and inserts the key-value pair into dest. If dest is nil, a new map is allocated. Missing key fields default to empty string; missing value fields default to empty string.

func DecodePackedScalar

func DecodePackedScalar(values []uint64, kind scalar.Kind, packedData []byte) ([]uint64, error)

DecodePackedScalar decodes a packed field by consuming scalar values from packedData until all bytes are exhausted, appending each to values. The packedData parameter is the raw payload after the length prefix has been consumed by the caller. It returns ErrNotPackable if kind is not packable, and decode.ErrTruncated if the packed data ends mid-value.

func DecodeRepeatedBytes

func DecodeRepeatedBytes(values [][]byte, fieldData []byte) ([][]byte, int, error)

DecodeRepeatedBytes decodes a single length-delimited bytes value from fieldData and appends it to values. It returns the extended slice, the number of bytes consumed, and any error.

func DecodeRepeatedScalar

func DecodeRepeatedScalar(values []uint64, kind scalar.Kind, fieldData []byte) ([]uint64, int, error)

DecodeRepeatedScalar decodes a single scalar value from fieldData and appends it to values. It returns the extended slice, the number of bytes consumed, and any error.

func DecodeRepeatedString

func DecodeRepeatedString(values []string, fieldData []byte) ([]string, int, error)

DecodeRepeatedString decodes a single length-delimited string value from fieldData and appends it to values. It returns the extended slice, the number of bytes consumed, and any error.

func EncodeMapScalarBytes

func EncodeMapScalarBytes(b []byte, fieldNumber uint32, keyKind scalar.Kind, entries map[uint64][]byte) []byte

EncodeMapScalarBytes encodes a map with scalar key and bytes value types. Each entry is written as a length-delimited field at fieldNumber. Zero keys and nil/empty values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapScalarMessage

func EncodeMapScalarMessage(b []byte, fieldNumber uint32, keyKind scalar.Kind, entries map[uint64][]byte) []byte

EncodeMapScalarMessage encodes a map with scalar key and pre-encoded message value bytes. Each entry is written as a length-delimited field at fieldNumber. The value []byte is a pre-encoded message blob; the caller is responsible for encoding the nested message before calling this function. Zero keys and nil/empty values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapScalarScalar

func EncodeMapScalarScalar(b []byte, fieldNumber uint32, keyKind scalar.Kind, valueKind scalar.Kind, entries map[uint64]uint64) []byte

EncodeMapScalarScalar encodes a map with scalar key and scalar value types. Each entry is written as a length-delimited field at fieldNumber containing inner key (field 1) and value (field 2) fields. Zero keys and zero values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapScalarString

func EncodeMapScalarString(b []byte, fieldNumber uint32, keyKind scalar.Kind, entries map[uint64]string) []byte

EncodeMapScalarString encodes a map with scalar key and string value types. Each entry is written as a length-delimited field at fieldNumber. Zero keys and empty string values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapStringBytes

func EncodeMapStringBytes(b []byte, fieldNumber uint32, entries map[string][]byte) []byte

EncodeMapStringBytes encodes a map with string key and bytes value types. Each entry is written as a length-delimited field at fieldNumber. Empty keys and nil/empty values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapStringMessage

func EncodeMapStringMessage(b []byte, fieldNumber uint32, entries map[string][]byte) []byte

EncodeMapStringMessage encodes a map with string key and pre-encoded message value bytes. Each entry is written as a length-delimited field at fieldNumber. The value []byte is a pre-encoded message blob; the caller is responsible for encoding the nested message before calling this function. Empty keys and nil/empty values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapStringScalar

func EncodeMapStringScalar(b []byte, fieldNumber uint32, valueKind scalar.Kind, entries map[string]uint64) []byte

EncodeMapStringScalar encodes a map with string key and scalar value types. Each entry is written as a length-delimited field at fieldNumber containing inner key (field 1) and value (field 2) fields. Empty keys and zero values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeMapStringString

func EncodeMapStringString(b []byte, fieldNumber uint32, entries map[string]string) []byte

EncodeMapStringString encodes a map with string key and string value types. Each entry is written as a length-delimited field at fieldNumber. Empty keys and empty values are omitted from the inner payload. It returns b unchanged when entries is nil or empty.

func EncodeOneofField

func EncodeOneofField(b []byte, value OneofValue) []byte

EncodeOneofField encodes the currently-set variant as a regular tagged field and appends the result to b. It returns b unchanged when value is nil. The OneofValue interface is sealed to this package, so the type switch exhaustively covers all possible implementations. The default case handles *OneofMessage, the only remaining variant after the explicit cases.

func EncodePackedScalar

func EncodePackedScalar(b []byte, fieldNumber uint32, kind scalar.Kind, values []uint64) []byte

EncodePackedScalar encodes all values as a single length-delimited field: one tag with wire.WireBytes, one varint length prefix, then all scalar values concatenated back-to-back. It returns b unchanged when values is nil or empty. It panics if kind is not packable (matching the scalar.Codec panic pattern for unsupported kinds on the encode path).

func EncodeRepeatedBytes

func EncodeRepeatedBytes(b []byte, fieldNumber uint32, values [][]byte) []byte

EncodeRepeatedBytes encodes each element of values as a separate tagged length-delimited bytes field and appends the result to b. It returns b unchanged when values is nil or empty.

func EncodeRepeatedScalar

func EncodeRepeatedScalar(b []byte, fieldNumber uint32, kind scalar.Kind, values []uint64) []byte

EncodeRepeatedScalar encodes each element of values as a separate tagged scalar field and appends the result to b. It returns b unchanged when values is nil or empty.

func EncodeRepeatedString

func EncodeRepeatedString(b []byte, fieldNumber uint32, values []string) []byte

EncodeRepeatedString encodes each element of values as a separate tagged length-delimited string field and appends the result to b. It returns b unchanged when values is nil or empty.

func EqualMapScalarBytes

func EqualMapScalarBytes(a, b map[uint64][]byte) bool

EqualMapScalarBytes reports whether maps a and b have the same keys and byte-slice values. Nil and empty maps are considered equal. For the same key, a nil value slice and an empty value slice are considered equal, matching protobuf semantics where both represent the default value.

func EqualMapScalarScalar

func EqualMapScalarScalar(a, b map[uint64]uint64) bool

EqualMapScalarScalar reports whether maps a and b have the same keys and values. Nil and empty maps are considered equal.

func EqualMapScalarString

func EqualMapScalarString(a, b map[uint64]string) bool

EqualMapScalarString reports whether maps a and b have the same keys and string values. Nil and empty maps are considered equal.

func EqualMapStringBytes

func EqualMapStringBytes(a, b map[string][]byte) bool

EqualMapStringBytes reports whether maps a and b have the same keys and byte-slice values. Nil and empty maps are considered equal. For the same key, a nil value slice and an empty value slice are considered equal, matching protobuf semantics where both represent the default value.

func EqualMapStringScalar

func EqualMapStringScalar(a, b map[string]uint64) bool

EqualMapStringScalar reports whether maps a and b have the same keys and values. Nil and empty maps are considered equal.

func EqualMapStringString

func EqualMapStringString(a, b map[string]string) bool

EqualMapStringString reports whether maps a and b have the same keys and string values. Nil and empty maps are considered equal.

func EqualOneof

func EqualOneof(a, b OneofValue) bool

EqualOneof compares two oneof values for equality. It returns true if both are nil, false if exactly one is nil, and compares field numbers and values for matching concrete types. The OneofValue interface is sealed to this package, so the type switch exhaustively covers all possible implementations. The default case handles *OneofMessage, the only remaining variant after the explicit cases.

func SizeMapScalarBytes

func SizeMapScalarBytes(fieldNumber uint32, keyKind scalar.Kind, entries map[uint64][]byte) int

SizeMapScalarBytes returns the total number of bytes required to encode all map entries with scalar keys and bytes values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapScalarMessage

func SizeMapScalarMessage(fieldNumber uint32, keyKind scalar.Kind, entries map[uint64][]byte) int

SizeMapScalarMessage returns the total number of bytes required to encode all map entries with scalar keys and pre-encoded message values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapScalarScalar

func SizeMapScalarScalar(fieldNumber uint32, keyKind scalar.Kind, valueKind scalar.Kind, entries map[uint64]uint64) int

SizeMapScalarScalar returns the total number of bytes required to encode all map entries with scalar keys and scalar values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapScalarString

func SizeMapScalarString(fieldNumber uint32, keyKind scalar.Kind, entries map[uint64]string) int

SizeMapScalarString returns the total number of bytes required to encode all map entries with scalar keys and string values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapStringBytes

func SizeMapStringBytes(fieldNumber uint32, entries map[string][]byte) int

SizeMapStringBytes returns the total number of bytes required to encode all map entries with string keys and bytes values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapStringMessage

func SizeMapStringMessage(fieldNumber uint32, entries map[string][]byte) int

SizeMapStringMessage returns the total number of bytes required to encode all map entries with string keys and pre-encoded message values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapStringScalar

func SizeMapStringScalar(fieldNumber uint32, valueKind scalar.Kind, entries map[string]uint64) int

SizeMapStringScalar returns the total number of bytes required to encode all map entries with string keys and scalar values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeMapStringString

func SizeMapStringString(fieldNumber uint32, entries map[string]string) int

SizeMapStringString returns the total number of bytes required to encode all map entries with string keys and string values. Each entry is framed as a length-delimited field at fieldNumber. It returns 0 when entries is nil or empty.

func SizeOneofField

func SizeOneofField(value OneofValue) int

SizeOneofField returns the encoded size of the variant including its tag, or 0 if value is nil. The OneofValue interface is sealed to this package, so the type switch exhaustively covers all possible implementations. The default case handles *OneofMessage, the only remaining variant after the explicit cases.

func SizePackedScalar

func SizePackedScalar(fieldNumber uint32, kind scalar.Kind, values []uint64) int

SizePackedScalar returns the total number of bytes required to encode all values as a single packed length-delimited field. It returns 0 when values is nil or empty. The result includes the tag, the varint length prefix, and the concatenated scalar payload.

func SizeRepeatedBytes

func SizeRepeatedBytes(fieldNumber uint32, values [][]byte) int

SizeRepeatedBytes returns the total number of bytes required to encode each element of values as a separate tagged length-delimited bytes field. It returns 0 when values is nil or empty.

func SizeRepeatedScalar

func SizeRepeatedScalar(fieldNumber uint32, kind scalar.Kind, values []uint64) int

SizeRepeatedScalar returns the total number of bytes required to encode each element of values as a separate tagged scalar field. It returns 0 when values is nil or empty.

func SizeRepeatedString

func SizeRepeatedString(fieldNumber uint32, values []string) int

SizeRepeatedString returns the total number of bytes required to encode each element of values as a separate tagged length-delimited string field. It returns 0 when values is nil or empty.

func ValidMapKeyKind

func ValidMapKeyKind(kind scalar.Kind) bool

ValidMapKeyKind reports whether kind is a valid protobuf map key type. Valid map key kinds are the 11 integral and bool types: KindInt32, KindInt64, KindUint32, KindUint64, KindSint32, KindSint64, KindFixed32, KindFixed64, KindSfixed32, KindSfixed64, and KindBool. String keys are valid in protobuf maps but are handled by separate dedicated functions rather than through this validator, because string keys use length-delimited wire encoding.

Types

type OneofBytes

type OneofBytes struct {
	Num uint32
	Val []byte
}

OneofBytes is a oneof variant holding a bytes value.

func (*OneofBytes) FieldNumber

func (s *OneofBytes) FieldNumber() uint32

FieldNumber returns the protobuf field number of this bytes variant.

type OneofField

type OneofField struct {
	// contains filtered or unexported fields
}

OneofField holds the currently-set variant of a protobuf oneof group. Its zero value represents an unset oneof, requiring no constructor.

func (*OneofField) Clear

func (o *OneofField) Clear()

Clear resets the oneof to the unset state.

func (*OneofField) Get

func (o *OneofField) Get() OneofValue

Get returns the currently-set variant, or nil if the oneof is unset.

func (*OneofField) Has

func (o *OneofField) Has() bool

Has reports whether a variant is currently set.

func (*OneofField) Set

func (o *OneofField) Set(v OneofValue)

Set stores v as the current variant. Passing nil clears the oneof, which is equivalent to calling Clear. Setting a new variant implicitly replaces the previous one, enforcing mutual exclusivity.

func (*OneofField) WhichField

func (o *OneofField) WhichField() uint32

WhichField returns the field number of the currently-set variant, or 0 if the oneof is unset.

type OneofMessage

type OneofMessage struct {
	Num uint32
	Val []byte
}

OneofMessage is a oneof variant holding pre-encoded message bytes. The caller is responsible for encoding the nested message before storing it in Val.

func (*OneofMessage) FieldNumber

func (s *OneofMessage) FieldNumber() uint32

FieldNumber returns the protobuf field number of this message variant.

type OneofScalar

type OneofScalar struct {
	Num  uint32
	Kind scalar.Kind
	Val  uint64
}

OneofScalar is a oneof variant holding a scalar value. It covers all 14 scalar kinds (int32 through enum) because they all encode as a single uint64 through scalar.Codec.

fieldalignment: fields ordered as (field number, kind, value) for clarity

func (*OneofScalar) FieldNumber

func (s *OneofScalar) FieldNumber() uint32

FieldNumber returns the protobuf field number of this scalar variant.

type OneofString

type OneofString struct {
	Num uint32
	Val string
}

OneofString is a oneof variant holding a string value.

func (*OneofString) FieldNumber

func (s *OneofString) FieldNumber() uint32

FieldNumber returns the protobuf field number of this string variant.

type OneofValue

type OneofValue interface {
	FieldNumber() uint32
	// contains filtered or unexported methods
}

OneofValue is the sealed interface implemented by all oneof variant types. Only types defined in this package may implement it.

func DecodeOneofVariant

func DecodeOneofVariant(fieldNumber uint32, wireType wire.WireType, kind scalar.Kind, fieldData []byte) (OneofValue, int, error)

DecodeOneofVariant constructs the appropriate OneofValue from decoded wire data. The caller passes the field number, wire type, scalar kind, and raw field data. The kind parameter determines which variant type is returned.

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional is a generic type that tracks explicit field presence for proto3 optional fields and proto2 scalar fields. It distinguishes between an explicitly set zero value and an unset field, enabling correct serialization behavior where zero values are emitted only when explicitly set.

func Some

func Some[T any](v T) Optional[T]

Some returns an Optional[T] with the given value and presence marked true.

func (*Optional[T]) Clear

func (o *Optional[T]) Clear()

Clear resets the value to its zero value and marks the field as not present.

func (Optional[T]) Has

func (o Optional[T]) Has() bool

Has reports whether the field has been explicitly set.

func (*Optional[T]) Set

func (o *Optional[T]) Set(v T)

Set sets the value and marks the field as present.

func (Optional[T]) Value

func (o Optional[T]) Value() T

Value returns the current value. If the field is not present, it returns the zero value of T.

func (Optional[T]) ValueOr

func (o Optional[T]) ValueOr(def T) T

ValueOr returns the current value if the field is present, otherwise it returns def.

type UnsupportedKeyKindError

type UnsupportedKeyKindError struct {
	Operation string
	KindName  string
}

UnsupportedKeyKindError indicates that a map encode function was called with a key kind it does not support.

func (*UnsupportedKeyKindError) Error

func (e *UnsupportedKeyKindError) Error() string

Error returns a human-readable message describing the unsupported key kind.

type UnsupportedPackedKindError

type UnsupportedPackedKindError struct {
	KindName string
}

UnsupportedPackedKindError indicates that EncodePackedScalar was called with a kind that does not support packed encoding.

func (*UnsupportedPackedKindError) Error

Error returns a human-readable message describing the unsupported packed kind.

type UnsupportedValueKindError

type UnsupportedValueKindError struct {
	Operation string
	KindName  string
}

UnsupportedValueKindError indicates that a map decode or encode function was called with a scalar value kind it does not support.

func (*UnsupportedValueKindError) Error

func (e *UnsupportedValueKindError) Error() string

Error returns a human-readable message describing the unsupported value kind.

Jump to

Keyboard shortcuts

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