canoto

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause Imports: 13 Imported by: 11

README

Canoto

Canoto is a serialization format designed to be:

  1. Fast
  2. Compact
  3. Canonical
  4. Backwards compatible
  5. Read compatible with Protocol Buffers.

Install

go install github.com/StephenButtolph/canoto/canoto@latest

The installed version can be displayed with the --version flag.

canoto --version

32-bit architectures are not supported.

Define Messages

Canoto messages are defined as normal golang structs:

type ExampleStruct0 struct {
	Int32              int32           `canoto:"int,1"`
	Int64              int64           `canoto:"int,2"`
	Uint32             uint32          `canoto:"uint,3"`
	Uint64             uint64          `canoto:"uint,4"`
	Sfixed32           int32           `canoto:"fint32,5"`
	Fixed32            uint32          `canoto:"fint32,6"`
	Sfixed64           int64           `canoto:"fint64,7"`
	Fixed64            uint64          `canoto:"fint64,8"`
	Bool               bool            `canoto:"bool,9"`
	String             string          `canoto:"string,10"`
	Bytes              []byte          `canoto:"bytes,11"`
	OtherStruct        ExampleStruct1  `canoto:"value,12"`
	OtherStructPointer *ExampleStruct1 `canoto:"pointer,13"`

	canotoData canotoData_ExampleStruct0
}

type ExampleStruct1 struct {
	Int32 int32 `canoto:"int,536870911"`

	canotoData canotoData_ExampleStruct1
}

All structs must include a field called canotoData, which caches the struct's size and OneOf selections. The cache is populated by CacheCanoto and during unmarshaling.

The type canotoData_${structName} is automatically generated by Canoto.

For a given Struct, Canoto automatically implements the Message interface:

// Message defines a type that can be a stand-alone Canoto message.
type Message interface {
	Field
	// ValidCanoto validates that the message can be correctly marshaled
	// into the Canoto format.
	ValidCanoto() bool
	// MarshalCanoto returns the Canoto representation of this message.
	//
	// It is assumed that this message is ValidCanoto.
	MarshalCanoto() []byte
	// UnmarshalCanoto unmarshals a Canoto-encoded byte slice into the
	// message.
	//
	// The memory allocated and the depth of nested messages are not
	// limited. bytes should only be untrusted if the message is not
	// recursive and has no variable-length repeated fields. Otherwise,
	// UnmarshalCanotoFrom should be used.
	UnmarshalCanoto(bytes []byte) error
}

// Field defines a type that can be included in a Canoto message.
type Field interface {
	// DescribeCanoto returns a [Spec] describing the Canoto encoding of
	// this type.
	//
	// types is used as a stack of ancestor messages to detect recursive
	// specs.
	//
	// If this type does not have a valid specification, it returns nil and
	// the type is treated as opaque bytes.
	DescribeCanoto(types ...reflect.Type) *Spec
	// CacheCanoto populates internal caches based on the current values in
	// the struct.
	CacheCanoto()
	// SizeCanoto returns the previously calculated size of the Canoto
	// representation from CacheCanoto.
	//
	// If CacheCanoto has not yet been called, or the field has been
	// modified since the last call to CacheCanoto, the returned size may be
	// incorrect.
	SizeCanoto() uint64
	// CheckCanoto validates that the field can be correctly marshaled into
	// the Canoto format.
	//
	// It is assumed that CacheCanoto has been called since the last
	// modification to this field.
	CheckCanoto() bool
	// AppendCanoto appends the field to a [Writer] and returns the
	// resulting [Writer].
	//
	// It is assumed that CacheCanoto has been called since the last
	// modification to this field.
	//
	// It is assumed that this field passes CheckCanoto.
	AppendCanoto(w Writer) Writer
	// UnmarshalCanotoFrom populates the field from a [Reader].
	//
	// [Reader.B] may be untrusted, as long as [Reader.MemoryRemaining] and
	// [Reader.DepthLimit] are bounded.
	//
	// On success, the returned [UnmarshalResult] must be r.Result(), called
	// after charging r for memory allocated by this call.
	UnmarshalCanotoFrom(r Reader) (UnmarshalResult, error)
}

Generate

In order to generate canoto information for all of the structs in a file, simply run the canoto command with one or more files.

canoto example0.go example1.go

The above example will generate example0.canoto.go and example1.canoto.go.

The corresponding proto file for a canoto file can also be generated by adding the --proto flag.

canoto --proto example.go

The above example will generate example.canoto.go and example.proto.

Generating the .canoto.go file can be disabled with --canoto=false.

canoto --canoto=false --proto example.go

The above example will only generate example.proto.

go:generate

To automatically generate the .canoto.go version of a file, it is recommended to use go:generate. By using go run inside the go:generate, the version of the command being run will be taken from the local go.mod.

Place

//go:generate go run github.com/StephenButtolph/canoto/canoto $GOFILE

at the top of a file to update the .canoto.go version of the file every time go generate ./... is run.

Best Practices

canoto only inspects a single golang file at a time, so it is recommended to define nested messages in the same file to be able to generate the most useful proto file.

Additionally, while fully supported in the canoto output, type aliases and generic types will result in proto files with default types. It is still guaranteed for the generated proto file to be able to parse canoto data, but the types may not be as specific as they could be.

If type aliases are needed, it may make sense to modify the generated proto file to specify the most specific proto type possible.

Generics

Canoto supports generic structs through the canoto.FieldPointer[T] constraint. To guarantee safe usage of a struct, type constraints can be used to implement a struct with a generic field T. Canoto inspects the generic types, so the struct must include a type parameter of canoto.FieldPointer[T]. For example:

type GenericField[T any, _ canoto.FieldPointer[T]] struct {
	Value   T  `canoto:"value,1"`
	Pointer *T `canoto:"pointer,2"`

	canotoData canotoData_GenericField
}

If canoto.FieldPointer is aliased to a different type or is otherwise re-implemented, Canoto will not be able to correctly tie the type constraints together.

Concurrency

It is safe to marshal the same message from multiple goroutines at the same time, and to pass a message by value while another goroutine is marshaling it. The same applies to canoto.Codec.Marshal and canoto.Any, as long as an Any is marshaled with the same Spec.

Modifying a message, including by calling UnmarshalCanoto, while another goroutine is marshaling or copying it is a data race.

Untrusted Input

Canoto distinguishes between two kinds of input:

  • Untrusted input is bytes that came from outside of your program, such as from the network.
  • Trusted data is anything that your program built itself, such as a message, Spec, or Any, or that Canoto read from untrusted input.

Reading untrusted input is safe when the memory allocated and the depth of nested messages are bounded. A message bounds both by its structure when it:

  • Is not recursive.
  • Has no variable-length repeated fields.
  • Only contains custom canoto.Fields that bound their own allocations.

Such a message can safely be read from untrusted input with UnmarshalCanoto. To read untrusted input into any other message, use UnmarshalCanotoFrom with a canoto.Reader whose MemoryRemaining and DepthLimit are bounded.

Which inputs each function accepts

Limiting Memory

The memory allocated while unmarshaling a message can greatly exceed the size of the message. For example, an empty entry of a repeated message field is encoded in 2 bytes, but allocates an entire message.

When unmarshaling untrusted input, the memory allocated is limited with MemoryRemaining. If an allocation would exceed the remaining memory, unmarshaling fails with canoto.ErrMemoryLimitExceeded before performing the allocation. The returned canoto.UnmarshalResult contains the remaining memory.

var msg Message
result, err := msg.UnmarshalCanotoFrom(canoto.Reader{
	B:               bytes,
	MemoryRemaining: 1 << 20,
	DepthLimit:      100,
})

Allocations are charged their Go size, which depends on the platform and the compiler. Allocator overhead, such as rounding up to a size class, is not charged, so the memory actually allocated may slightly exceed the limit.

When Unsafe is set, strings and bytes alias the input rather than being copied, so they are not charged.

Codec.Unmarshal charges the memory of the returned Any. It may also use temporary memory that is not charged, but it is at most proportional to the memory that is charged.

Limiting Depth

The stack used to unmarshal nested messages is not charged against the memory limit. Deeply nested input can exhaust the stack, which would crash the process rather than returning an error. Use DepthLimit to bound the stack usage.

Custom Fields

UnmarshalCanotoFrom on a custom canoto.Field may be given untrusted input. Implementations should charge any memory they allocate with r.UseMemory or r.UseSliceMemory, and must return r.Result() on success. When unmarshaling a nested field, its result should be applied to the parent reader with r.ApplyResult(result).

Standalone Implementations

In some instances, it may be desirable for the generated code to avoid introducing the dependency on this repo into the go.mod file. As an example, if the user must support having multiple versions of canoto utilized in the same application.

There are two CLI flags that enable using canoto without impacting the go.mod.

  1. --library when specified generates the canoto library in the provided folder. For example --library="./internal" generates the canoto library in the ./internal/canoto package.
  2. --import specifies the canoto library to depend on in any generated code.

For example:

canoto --library="./internal" --import="github.com/StephenButtolph/canoto/internal/canoto" ./canoto.go

Will generate the canoto library in ./internal/canoto and will import "github.com/StephenButtolph/canoto/internal/canoto" rather than the default "github.com/StephenButtolph/canoto" when generating ./canoto.canoto.go.

Custom Identifiers

Six CLI flags control the naming of generated Go identifiers:

Flag Default Scope Description
--format-cache canotoData_{struct} Message Name of the generated cache struct type
--format-number canotoNumber_{cStruct}__{cField} Field Name of generated field number constants
--format-tag canotoTag_{cStruct}__{cField} Field Name of generated field tag constants
--format-oneof-type canotoOneOfType_{cStruct}__{cOneOf} OneOf Name of generated oneOf enum types
--format-oneof-unset canotoOneOfUnset_{cStruct}__{cOneOf} OneOf Name of generated unset oneOf constants
--format-oneof-field canotoOneOf_{cStruct}__{cField} Field Name of generated oneOf field constants

Each flag accepts a template string. The available variables depend on the flag's scope, and each scope extends the one above it:

Scope Variables
Message {struct}, {cStruct}
OneOf {struct}, {cStruct}, {oneOf}, {cOneOf}
Field {struct}, {cStruct}, {oneOf}, {cOneOf}, {field}, {cField}
Variable Description
{struct} Original struct name (e.g. My_Struct)
{cStruct} Canonicalized struct name: _ replaced with _1 (e.g. My_1Struct)
{oneOf} Original oneOf name
{cOneOf} Canonicalized oneOf name: _ replaced with _1
{field} Original field name
{cField} Canonicalized field name: _ replaced with _1

The _ → _1 canonicalization prevents ambiguity with __, which can be used as a separator between variables.

For example:

canoto \
  --format-cache="cache_{struct}" \
  --format-number="fieldNum_{cStruct}__{cField}" \
  --format-tag="fieldTag_{cStruct}__{cField}" \
  --format-oneof-type="{struct}{oneOf}" \
  --format-oneof-unset="{struct}{oneOf}__Unset" \
  --format-oneof-field="{struct}{oneOf}__{field}" \
  example.go

For a struct Foo with a OneOf Type and a field Bar, this would generate:

type cache_Foo struct { ... }

const (
    fieldNum_Foo__Bar = 1
    fieldTag_Foo__Bar = "\x0a"
)

type FooType uint32

const (
    FooType__Unset FooType = 0
    FooType__Bar   FooType = fieldNum_Foo__Bar
)
Reserved Identifiers
Package-level identifiers
Message names
  • c
  • r
  • types
  • T${n}, for the nth type parameter of a generic message, starting at T1
Message field and method names
  • AppendCanoto
  • CacheCanoto
  • CheckCanoto
  • DescribeCanoto
  • MarshalCanoto
  • SizeCanoto
  • UnmarshalCanoto
  • UnmarshalCanotoFrom
  • ValidCanoto
  • WhichCanoto${oneOf}, for each OneOf

Supported Types

go type canoto type proto type wire type
int8 int sint32 varint
int16 int sint32 varint
int32 int sint32 varint
int64 int sint64 varint
uint8 uint uint32 varint
uint16 uint uint32 varint
uint32 uint uint32 varint
uint64 uint uint64 varint
int32 fint32 sfixed32 i32
uint32 fint32 fixed32 i32
int64 fint64 sfixed64 i64
uint64 fint64 fixed64 i64
bool bool bool varint
string string string len
[]byte bytes bytes len
[x]byte fixed bytes bytes len
T Message value message len
*T Message pointer message len
[]int8 repeated int repeated sint32 len
[]int16 repeated int repeated sint32 len
[]int32 repeated int repeated sint32 len
[]int64 repeated int repeated sint64 len
[]uint8 repeated uint repeated uint32 len
[]uint16 repeated uint repeated uint32 len
[]uint32 repeated uint repeated uint32 len
[]uint64 repeated uint repeated uint64 len
[]int32 repeated fint32 repeated sfixed32 len
[]uint32 repeated fint32 repeated fixed32 len
[]int64 repeated fint64 repeated sfixed64 len
[]uint64 repeated fint64 repeated fixed64 len
[]bool repeated bool repeated bool len
[]string repeated string repeated string len
[][]byte repeated bytes repeated bytes len
[][x]byte repeated fixed bytes repeated bytes len
[]T Message repeated value repeated message len
[]*T Message repeated pointer repeated message_pointer len
[x]int8 fixed repeated int repeated sint32 len
[x]int16 fixed repeated int repeated sint32 len
[x]int32 fixed repeated int repeated sint32 len
[x]int64 fixed repeated int repeated sint64 len
[x]uint8 fixed repeated uint repeated uint32 len
[x]uint16 fixed repeated uint repeated uint32 len
[x]uint32 fixed repeated uint repeated uint32 len
[x]uint64 fixed repeated uint repeated uint64 len
[x]int32 fixed repeated fint32 repeated sfixed32 len
[x]uint32 fixed repeated fint32 repeated fixed32 len
[x]int64 fixed repeated fint64 repeated sfixed64 len
[x]uint64 fixed repeated fint64 repeated fixed64 len
[x]bool fixed repeated bool repeated bool len
[x]string fixed repeated string repeated string len
[x][]byte fixed repeated bytes repeated bytes len
[x][y]byte fixed repeated fixed bytes repeated bytes len
[x]T Message fixed repeated value repeated message len
[x]*T Message fixed repeated pointer repeated message_pointer len
OneOf Fields

OneOfs allow message definitions to declare that a set of fields are mutually exclusive. When serialized, Canoto ensures that at most one field in each OneOf group appears on the wire.

Each OneOf has a group name, specified as an additional option after the field number in the struct tag:

type OneOf struct {
	Int  int64 `canoto:"int,1,Type"`
	Bool bool  `canoto:"bool,2,Type"`

	canotoData canotoData_OneOf
}

For every OneOf group, the generated code includes a helper method that lets you quickly determine which field was populated.

In the example above, the method WhichCanotoType will be generated. It returns the field number of the populated field in the Type OneOf.

All OneOf accessor methods follow the naming pattern:

WhichCanoto<GroupName>

For every OneOf group, the generated code also includes a typed enum. The accessor method returns this enum type, unless the struct is exported but the enum type is not. Because exported methods should not return unexported types, the method returns a uint32 in that case.

By default, the enum type and its constants use unexported, collision-resistant canoto... identifiers, so WhichCanotoType in the example above returns a uint32. To return the typed enum from an exported struct, customize --format-oneof-type to produce an exported name. --format-oneof-unset and --format-oneof-field can similarly be customized to export the enum's constants.

In either case, the returned values match the generated field number constants, so the field number constants can be used in comparisons.

After the cache has been initialized by calling one of UnmarshalCanoto, UnmarshalCanotoFrom, or CacheCanoto, the method returns the field number of the populated field. If no field in the OneOf group was set, the method returns 0.

Non-standard encoding

It is valid to define a Field that implements a non-standard format. However, this format should still be canonical and the corresponding Proto file should report opaque bytes. Such a Field should return nil from DescribeCanoto, so that it is treated as opaque bytes.

Why not Proto?

Proto is a fast, compact encoding format with extensive language support. However, Proto is not canonical.

Proto is designed to be forwards-compatible. Almost by definition, a forwards-compatible serialization format cannot be canonical. The format of a field cannot be validated to be canonical if the expected type of the field is not known during decoding.

Why is being canonical important?

In some cases, non-canonical serialization formats are subtle to work with.

For example, if the hash of the serialized data is important or if the serialized data is cryptographically signed.

In order to ensure that the hash of the serialized data does not change, it is important to carefully avoid re-serializing a message that was previously serialized.

For canonical serialization formats, the hash of the serialized data is guaranteed never to change. Every correct implementation of the format will produce the same hash.

Why be read compatible with Proto?

By being read compatible with Proto, users of the Canoto format inherit some of Proto's cross-language support.

If an application only needs to read Canoto messages, but not write them, it can simply treat the Canoto message as a Proto message.

Is Canoto Fast?

Canoto is typically more performant for both serialization and deserialization than Proto. However, Proto does not typically validate that fields are canonical. If a field is expensive to inspect, it's possible Canoto can be slightly slower.

Canoto is optimized to perform no unnecessary memory allocations, so careful management to ensure messages are stack allocated can significantly improve performance over Proto.

Is Canoto Forwards Compatible?

No. Canoto chooses to be a canonical serialization format rather than being forwards compatible.

Documentation

Overview

Package canoto implements a canonical, compact, and fast serialization format that is read-compatible with Protocol Buffers. It provides both low-level primitives for reading and writing the wire format and high-level interfaces for marshaling and unmarshaling structured messages.

Index

Examples

Constants

View Source
const (
	// Version is the current version of the canoto library.
	Version = "v1.0.1"

	// MaxVersion is the maximum supported version for generated code. It is
	// always the minor version of [Version].
	MaxVersion = 0
	// GenVersion is the library version required by generated code. It is
	// incremented when generated code relies on new functionality in the
	// library.
	GenVersion = 0
	// MinVersion is the minimum supported version for generated code. It is
	// incremented when the library drops support for old generated code.
	MinVersion = 0
)

Versions of this library and of the generated code it supports.

View Source
const (
	// MaxFieldNumber is the maximum field number allowed to be used in a Tag.
	MaxFieldNumber = 1<<29 - 1
	// FirstReservedFieldNumber is the first field number reserved by protobuf.
	// Field numbers in [FirstReservedFieldNumber, LastReservedFieldNumber] may
	// not be used.
	FirstReservedFieldNumber = 19000
	// LastReservedFieldNumber is the last field number reserved by protobuf.
	LastReservedFieldNumber = 19999
)

Limits on the field numbers that may be used in a Tag.

View Source
const (
	// SizeFint32 is the size of a 32-bit fixed size integer in bytes.
	SizeFint32 = 4
	// SizeFint64 is the size of a 64-bit fixed size integer in bytes.
	SizeFint64 = 8
	// SizeBool is the size of a boolean in bytes.
	SizeBool = 1

	// EmptyBytes is the length-prefixed encoding of empty bytes.
	EmptyBytes = "\x00" // (&Writer{}).AppendBytes([]byte{}).B

	// PointerPresenceTag is the tag used to encode the presence of a non-nil
	// pointer element within repeated pointer fields. It encodes field number 1
	// with the Len wire type.
	PointerPresenceTag = "\x0a" // Tag(1, Len)

	// SizePointerPresenceTag is the size of [PointerPresenceTag] in bytes.
	SizePointerPresenceTag = uint64(len(PointerPresenceTag))
)

Encodings and sizes of fixed-size values.

View Source
const (
	// DefaultMemoryLimit is the [Reader.MemoryRemaining] used by
	// UnmarshalCanoto.
	DefaultMemoryLimit uint64 = math.MaxUint64
	// DefaultDepthLimit is the [Reader.DepthLimit] used by UnmarshalCanoto.
	DefaultDepthLimit uint64 = math.MaxUint64
)

Default limits applied when unmarshaling with Message.UnmarshalCanoto.

Variables

View Source
var (
	//go:embed canoto.go
	Code string
	//go:embed canoto.canoto.go
	GeneratedCode string
	//go:embed race.go
	RaceCode string
	//go:embed norace.go
	NoRaceCode string
)

The source files of this library, embedded as strings. They can be used during code generation to produce standalone copies of this library.

These variables are not referenced internally, so the compiler omits them from the binary if unused.

View Source
var (
	// Err is wrapped by every error returned by this package and by code
	// generated by canoto.
	Err = errors.New("canoto")

	// ErrUnexpectedEOF is returned when the input ends before the encoding is
	// complete. It additionally wraps [io.ErrUnexpectedEOF].
	ErrUnexpectedEOF = fmt.Errorf("%w: %w", Err, io.ErrUnexpectedEOF)

	// ErrInvalidFieldOrder is returned when fields are not encoded in ascending
	// field number order.
	ErrInvalidFieldOrder = fmt.Errorf("%w: invalid field order", Err)
	// ErrUnexpectedWireType is returned when a field's wire type does not match
	// the expected wire type.
	ErrUnexpectedWireType = fmt.Errorf("%w: unexpected wire type", Err)
	// ErrDuplicateOneOf is returned when multiple fields in the same OneOf
	// group are set.
	ErrDuplicateOneOf = fmt.Errorf("%w: duplicate oneof field", Err)
	// ErrInvalidLength is returned when a decoded length is invalid.
	ErrInvalidLength = fmt.Errorf("%w: decoded length is invalid", Err)
	// ErrZeroValue is returned when a field contains a zero value, which is not
	// permitted in canoto encoding.
	ErrZeroValue = fmt.Errorf("%w: zero value", Err)
	// ErrUnknownField is returned when a field number is not recognized by the
	// message specification.
	ErrUnknownField = fmt.Errorf("%w: unknown field", Err)
	// ErrPaddedZeroes is returned when a varint contains unnecessary leading
	// zero bytes, violating canonical encoding.
	ErrPaddedZeroes = fmt.Errorf("%w: padded zeroes", Err)

	// ErrInvalidSpec is returned when a [Spec] does not describe a message that
	// could have been described by generated code.
	ErrInvalidSpec = fmt.Errorf("%w: invalid spec", Err)
	// ErrInvalidRecursiveDepth is returned when a recursive type references a
	// depth that exceeds the available specification stack.
	ErrInvalidRecursiveDepth = fmt.Errorf("%w: invalid recursive depth", ErrInvalidSpec)
	// ErrUnknownFieldType is returned when a field type is not recognized.
	ErrUnknownFieldType = fmt.Errorf("%w: unknown field type", ErrInvalidSpec)
	// ErrUnexpectedFieldSize is returned when a field's size does not match the
	// expected size for its type.
	ErrUnexpectedFieldSize = fmt.Errorf("%w: unexpected field size", ErrInvalidSpec)
	// ErrInvalidFieldType is returned when the value provided for a field does
	// not match the expected Go type.
	ErrInvalidFieldType = fmt.Errorf("%w: invalid field type", Err)

	// ErrOverflow is returned when a decoded integer overflows the target type.
	ErrOverflow = fmt.Errorf("%w: overflow", Err)
	// ErrInvalidWireType is returned when a wire type value is not valid.
	ErrInvalidWireType = fmt.Errorf("%w: invalid wire type", Err)
	// ErrInvalidBool is returned when a decoded boolean is neither 0 nor 1.
	ErrInvalidBool = fmt.Errorf("%w: decoded bool is neither true nor false", Err)
	// ErrStringNotUTF8 is returned when a decoded string is not valid UTF-8.
	ErrStringNotUTF8 = fmt.Errorf("%w: decoded string is not UTF-8", Err)
	// ErrMemoryLimitExceeded is returned when unmarshaling would allocate more
	// memory than permitted by [Reader.MemoryRemaining].
	ErrMemoryLimitExceeded = fmt.Errorf("%w: memory limit exceeded", Err)
	// ErrDepthLimitExceeded is returned when messages are nested deeper than
	// permitted by [Reader.DepthLimit].
	ErrDepthLimitExceeded = fmt.Errorf("%w: depth limit exceeded", Err)
)

Errors returned when a message or its encoding is invalid.

Functions

func CacheUint32 added in v0.20.0

func CacheUint32(addr *uint32, val uint32)

CacheUint32 atomically stores val into *addr.

When built with -race, the store is hidden from the race detector.

func CacheUint64 added in v0.20.0

func CacheUint64(addr *uint64, val uint64)

CacheUint64 atomically stores val into *addr.

When built with -race, the store is hidden from the race detector.

func CountBytes

func CountBytes[T Bytes](bytes []byte, tag T) (uint64, error)

CountBytes counts the consecutive number of length-prefixed fields with the given tag. If a field is malformed, the number of fields before it is returned along with the error.

func HasPrefix

func HasPrefix[T Bytes](bytes []byte, prefix T) bool

HasPrefix returns true if the bytes start with the given prefix.

func IsZero

func IsZero[T comparable](v *T) bool

IsZero returns true if the value pointed to by v is the zero value for its type.

func MakeEntry added in v0.13.1

func MakeEntry[S ~[]E, E any](S) (_ E)

MakeEntry returns the zero value of an element in the provided slice.

This function is useful to use in auto-generated code, when the type of a variable is unknown. For example, if we have a variable `v` which we know to be a slice, but we do not know the type of the elements, we can use this function to leverage golang's type inference to create an element.

func MakeEntryNilPointer added in v0.15.0

func MakeEntryNilPointer[S ~[]E, E any](S) (_ *E)

MakeEntryNilPointer returns a nil pointer to an element in the provided slice.

This function is useful to use in auto-generated code, when the type of a variable is unknown. For example, if we have a variable `v` which we know to be a slice, but we do not know the type of the elements, we can use this function to leverage golang's type inference to create the pointer.

func SizeBytes

func SizeBytes[T Bytes](v T) uint64

SizeBytes calculates the size the length-prefixed bytes would take if written.

func SizeInt

func SizeInt[T Int](v T) uint64

SizeInt calculates the size of an integer when zigzag encoded as a varint.

func SizeUint added in v0.13.1

func SizeUint[T Uint](v T) uint64

SizeUint calculates the size of an unsigned integer when encoded as a varint.

func Tag

func Tag(fieldNumber uint32, wireType WireType) []byte

Tag calculates the tag for a field number and wire type.

This function should not typically be used during marshaling, as tags can be precomputed.

func ValidString added in v0.14.0

func ValidString[T ~string](v T) bool

ValidString returns true if it is valid to encode the provided string. A string is valid to encode if it is valid UTF-8.

Types

type Any added in v0.13.1

type Any struct {
	Fields []AnyField
	// contains filtered or unexported fields
}

Any is a generic representation of a Canoto message.

func (Any) MarshalJSON added in v0.13.1

func (a Any) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

type AnyField added in v0.13.1

type AnyField struct {
	Name string

	// Value is the value of the field.
	//
	// It can be any of the following types:
	//   - int8,   []int8
	//   - int16,  []int16
	//   - int32,  []int32
	//   - int64,  []int64
	//   - uint8,  []uint8
	//   - uint16, []uint16
	//   - uint32, []uint32
	//   - uint64, []uint64
	//   - bool,   []bool
	//   - string, []string
	//   - []byte, [][]byte
	//   - Any,    []Any
	//   - []*[]byte
	//   - []*Any
	//
	// Integers must use the type matching the size of their field.
	//
	// Notice that *Any and *[]byte are not allowed. A nil pointer should
	// not have any field entry.
	Value any
	// contains filtered or unexported fields
}

AnyField is a generic representation of a field in a Canoto message.

type Bytes

type Bytes interface{ ~string | ~[]byte }

Bytes is a constraint that permits string and byte slice types.

type Codec added in v0.20.0

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

Codec marshals and unmarshals messages described by a Spec.

func NewCodec added in v0.20.0

func NewCodec(s *Spec) (*Codec, error)

NewCodec returns a Codec for messages described by s.

s may be read from untrusted input. If s is invalid, an error is returned.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/StephenButtolph/canoto"
)

func main() {
	// The sender encodes a message along with the Spec describing it. Any
	// generated type works; Spec is used here because it is itself a canoto
	// message.
	msg := &canoto.Spec{
		Name: "Point",
		Fields: []canoto.FieldType{
			{FieldNumber: 1, Name: "x", TypeInt: canoto.SizeEnum64},
			{FieldNumber: 2, Name: "y", TypeInt: canoto.SizeEnum64},
		},
	}
	msgBytes := msg.MarshalCanoto()
	specBytes := msg.DescribeCanoto().MarshalCanoto()

	// The receiver decodes the message without knowing its Go type. Both
	// inputs may be untrusted, so memory usage and nesting depth are limited.
	const (
		memoryLimit = 1 << 20
		depthLimit  = 16
	)

	var spec canoto.Spec
	_, err := spec.UnmarshalCanotoFrom(canoto.Reader{
		B:               specBytes,
		MemoryRemaining: memoryLimit,
		DepthLimit:      depthLimit,
	})
	if err != nil {
		log.Fatal(err)
	}

	codec, err := canoto.NewCodec(&spec)
	if err != nil {
		log.Fatal(err)
	}

	decoded, _, err := codec.Unmarshal(canoto.Reader{
		B:               msgBytes,
		MemoryRemaining: memoryLimit,
		DepthLimit:      depthLimit,
	})
	if err != nil {
		log.Fatal(err)
	}

	jsonBytes, err := json.MarshalIndent(decoded, "", "  ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(jsonBytes))
}
Output:
{
  "Name": "Point",
  "Fields": [
    {
      "FieldNumber": 1,
      "Name": "x",
      "TypeInt": 4
    },
    {
      "FieldNumber": 2,
      "Name": "y",
      "TypeInt": 4
    }
  ]
}

func (*Codec) Marshal added in v0.20.0

func (c *Codec) Marshal(a Any) ([]byte, error)

Marshal marshals a into bytes based on the Codec's Spec.

Any values, including nested values, must be tied to a single Spec to ensure consistently cached values during marshaling.

This function is significantly slower than calling MarshalCanoto on the type directly. This function should only be used when the concrete type can not be known ahead of time.

func (*Codec) Unmarshal added in v0.20.0

func (c *Codec) Unmarshal(r Reader) (Any, UnmarshalResult, error)

Unmarshal parses r.B as the message described by the Codec's Spec.

Reader.B may be untrusted, as long as Reader.MemoryRemaining and Reader.DepthLimit are bounded.

The returned UnmarshalResult contains the memory remaining in r after charging for the memory of the returned Any. Unmarshal may also use temporary memory that is not charged, but it is at most proportional to the memory that is charged.

This function is slower than calling Field.UnmarshalCanotoFrom on the type directly. This function should only be used when the concrete type can not be known ahead of time.

type Field

type Field interface {
	// DescribeCanoto returns a [Spec] describing the Canoto encoding of
	// this type.
	//
	// types is used as a stack of ancestor messages to detect recursive
	// specs.
	//
	// If this type does not have a valid specification, it returns nil and
	// the type is treated as opaque bytes.
	DescribeCanoto(types ...reflect.Type) *Spec
	// CacheCanoto populates internal caches based on the current values in
	// the struct.
	CacheCanoto()
	// SizeCanoto returns the previously calculated size of the Canoto
	// representation from CacheCanoto.
	//
	// If CacheCanoto has not yet been called, or the field has been
	// modified since the last call to CacheCanoto, the returned size may be
	// incorrect.
	SizeCanoto() uint64
	// CheckCanoto validates that the field can be correctly marshaled into
	// the Canoto format.
	//
	// It is assumed that CacheCanoto has been called since the last
	// modification to this field.
	CheckCanoto() bool
	// AppendCanoto appends the field to a [Writer] and returns the
	// resulting [Writer].
	//
	// It is assumed that CacheCanoto has been called since the last
	// modification to this field.
	//
	// It is assumed that this field passes CheckCanoto.
	AppendCanoto(w Writer) Writer
	// UnmarshalCanotoFrom populates the field from a [Reader].
	//
	// [Reader.B] may be untrusted, as long as [Reader.MemoryRemaining] and
	// [Reader.DepthLimit] are bounded.
	//
	// On success, the returned [UnmarshalResult] must be r.Result(), called
	// after charging r for memory allocated by this call.
	UnmarshalCanotoFrom(r Reader) (UnmarshalResult, error)
}

Field defines a type that can be included in a Canoto message.

type FieldPointer added in v0.4.0

type FieldPointer[T any] interface {
	Field
	*T
}

FieldPointer is a constraint that requires *T to implement Field.

This must be used as a type parameter when defining a generic struct that contains a Field value.

type FieldType added in v0.13.1

type FieldType struct {
	FieldNumber    uint32   `canoto:"uint,1"          json:"fieldNumber"`
	Name           string   `canoto:"string,2"        json:"name"`
	FixedLength    uint64   `canoto:"uint,3"          json:"fixedLength,omitempty"`
	Repeated       bool     `canoto:"bool,4"          json:"repeated,omitempty"`
	OneOf          string   `canoto:"string,5"        json:"oneOf,omitempty"`
	Pointer        bool     `canoto:"bool,6"          json:"pointer,omitempty"`
	TypeInt        SizeEnum `canoto:"uint,7,Type"     json:"typeInt,omitempty"`        // can be any of [SizeEnum8], [SizeEnum16], [SizeEnum32], or [SizeEnum64].
	TypeUint       SizeEnum `canoto:"uint,8,Type"     json:"typeUint,omitempty"`       // can be any of [SizeEnum8], [SizeEnum16], [SizeEnum32], or [SizeEnum64].
	TypeFixedInt   SizeEnum `canoto:"uint,9,Type"     json:"typeFixedInt,omitempty"`   // can be either [SizeEnum32] or [SizeEnum64].
	TypeFixedUint  SizeEnum `canoto:"uint,10,Type"    json:"typeFixedUint,omitempty"`  // can be either [SizeEnum32] or [SizeEnum64].
	TypeBool       bool     `canoto:"bool,11,Type"    json:"typeBool,omitempty"`       // can only be true.
	TypeString     bool     `canoto:"bool,12,Type"    json:"typeString,omitempty"`     // can only be true.
	TypeBytes      bool     `canoto:"bool,13,Type"    json:"typeBytes,omitempty"`      // can only be true.
	TypeFixedBytes uint64   `canoto:"uint,14,Type"    json:"typeFixedBytes,omitempty"` // length of the fixed bytes.
	TypeMessage    *Spec    `canoto:"pointer,15,Type" json:"typeMessage,omitempty"`
	TypeRecursive  uint64   `canoto:"uint,16,Type"    json:"typeRecursive,omitempty"` // depth of the recursion.
	// contains filtered or unexported fields
}

FieldType is the specification of a field in a Canoto message.

func FieldTypeFromField added in v0.13.1

func FieldTypeFromField[T any, PT FieldPointer[T]](
	_ PT,
	fieldNumber uint32,
	name string,
	fixedLength uint64,
	repeated bool,
	oneOf string,
	pointer bool,
	types []reflect.Type,
) FieldType

FieldTypeFromField creates a FieldType specification for a message or custom Field type. This is primarily used by generated code to build Spec values.

The first argument is only used for type inference.

func FieldTypeFromFint added in v0.13.1

func FieldTypeFromFint[T integer](
	field T,
	fieldNumber uint32,
	name string,
	fixedLength uint64,
	repeated bool,
	oneOf string,
) FieldType

FieldTypeFromFint creates a FieldType specification for a fixed-size integer field. This is primarily used by generated code to build Spec values.

func (*FieldType) AppendCanoto added in v0.20.0

func (c *FieldType) AppendCanoto(w Writer) Writer

AppendCanoto appends the struct to a Writer and returns the resulting Writer. Most users should just use MarshalCanoto.

It is assumed that CacheCanoto has been called since the last modification to this struct.

It is assumed that this struct is ValidCanoto.

func (*FieldType) CacheCanoto added in v0.20.0

func (c *FieldType) CacheCanoto()

CacheCanoto populates size and OneOf caches based on the current values in the struct.

func (*FieldType) CheckCanoto added in v0.20.0

func (c *FieldType) CheckCanoto() bool

CheckCanoto validates that the struct can be correctly marshaled into the Canoto format. Most users should just use ValidCanoto.

It is assumed that CacheCanoto has been called since the last modification to this struct.

func (*FieldType) DescribeCanoto added in v0.20.0

func (*FieldType) DescribeCanoto(types ...reflect.Type) *Spec

DescribeCanoto returns a Spec describing the fields of this message and their wire types.

types is used as a stack of ancestor messages to detect recursive specs.

func (*FieldType) MarshalCanoto added in v0.13.1

func (c *FieldType) MarshalCanoto() []byte

MarshalCanoto returns the Canoto representation of this struct.

It is assumed that this struct is ValidCanoto.

func (*FieldType) SizeCanoto added in v0.20.0

func (c *FieldType) SizeCanoto() uint64

SizeCanoto returns the previously calculated size of the Canoto representation from CacheCanoto.

If CacheCanoto has not yet been called, or the struct has been modified since the last call to CacheCanoto, the returned size may be incorrect.

func (*FieldType) UnmarshalCanoto added in v0.13.1

func (c *FieldType) UnmarshalCanoto(bytes []byte) error

UnmarshalCanoto unmarshals a Canoto-encoded byte slice into the struct.

During parsing, the canoto cache is saved.

func (*FieldType) UnmarshalCanotoFrom added in v0.13.1

func (c *FieldType) UnmarshalCanotoFrom(r Reader) (UnmarshalResult, error)

UnmarshalCanotoFrom populates the struct from a Reader. Most users should just use UnmarshalCanoto.

During parsing, the canoto cache is saved.

This function enables configuration of reader options.

func (*FieldType) ValidCanoto added in v0.13.1

func (c *FieldType) ValidCanoto() bool

ValidCanoto validates that the struct can be correctly marshaled into the Canoto format.

func (*FieldType) WhichCanotoType added in v0.20.0

func (c *FieldType) WhichCanotoType() FieldTypeOneOf

WhichCanotoType returns the previously calculated field number used to represent Type.

This value is cached by UnmarshalCanoto, UnmarshalCanotoFrom, and CacheCanoto.

If the value has not yet been cached, or the struct has been modified since it was last cached, the returned field number may be incorrect.

type FieldTypeOneOf added in v0.20.0

type FieldTypeOneOf uint32

FieldTypeOneOf identifies the field in FieldType populating the Type oneOf.

const (
	FieldTypeUnset      FieldTypeOneOf = 0
	FieldTypeInt        FieldTypeOneOf = canotoNumber_FieldType__TypeInt
	FieldTypeUint       FieldTypeOneOf = canotoNumber_FieldType__TypeUint
	FieldTypeFixedInt   FieldTypeOneOf = canotoNumber_FieldType__TypeFixedInt
	FieldTypeFixedUint  FieldTypeOneOf = canotoNumber_FieldType__TypeFixedUint
	FieldTypeBool       FieldTypeOneOf = canotoNumber_FieldType__TypeBool
	FieldTypeString     FieldTypeOneOf = canotoNumber_FieldType__TypeString
	FieldTypeBytes      FieldTypeOneOf = canotoNumber_FieldType__TypeBytes
	FieldTypeFixedBytes FieldTypeOneOf = canotoNumber_FieldType__TypeFixedBytes
	FieldTypeMessage    FieldTypeOneOf = canotoNumber_FieldType__TypeMessage
	FieldTypeRecursive  FieldTypeOneOf = canotoNumber_FieldType__TypeRecursive
)

type Int

type Int interface {
	~int8 | ~int16 | ~int32 | ~int64
}

Int is a constraint that permits any sized signed integer type.

type Int32

type Int32 interface{ ~int32 | ~uint32 }

Int32 is a constraint that permits 32-bit int types.

type Int64

type Int64 interface{ ~int64 | ~uint64 }

Int64 is a constraint that permits 64-bit int types.

type Message

type Message interface {
	Field
	// ValidCanoto validates that the message can be correctly marshaled
	// into the Canoto format.
	ValidCanoto() bool
	// MarshalCanoto returns the Canoto representation of this message.
	//
	// It is assumed that this message is ValidCanoto.
	MarshalCanoto() []byte
	// UnmarshalCanoto unmarshals a Canoto-encoded byte slice into the
	// message.
	//
	// The memory allocated and the depth of nested messages are not
	// limited. bytes should only be untrusted if the message is not
	// recursive and has no variable-length repeated fields. Otherwise,
	// UnmarshalCanotoFrom should be used.
	UnmarshalCanoto(bytes []byte) error
}

Message defines a type that can be a stand-alone Canoto message.

type Reader

type Reader struct {
	// B is the remaining bytes to be read.
	B []byte
	// Unsafe, when true, avoids copying during unmarshaling. Decoded
	// strings and byte slices will alias the original input buffer,
	// which must not be modified after unmarshaling.
	Unsafe bool
	// MemoryRemaining is the number of bytes that may be allocated during
	// unmarshaling.
	//
	// Each allocation is charged the in-memory size of the allocated value,
	// which may vary between builds.
	//
	// Allocator overhead, such as size class rounding, is not charged.
	MemoryRemaining uint64
	// DepthLimit is the number of nested messages that may be read.
	//
	// The stack used by nested messages is not charged against
	// MemoryRemaining, so DepthLimit should be limited when unmarshaling
	// recursive messages from untrusted input.
	DepthLimit uint64
	// Context is a user-defined value that can be used to pass additional
	// state during the unmarshaling process.
	Context any
}

Reader contains all the state needed to unmarshal a Canoto type.

func (*Reader) ApplyResult added in v1.0.1

func (r *Reader) ApplyResult(result UnmarshalResult)

ApplyResult updates r with the state from an UnmarshalResult returned by unmarshaling a nested Field.

func (*Reader) HasNext added in v1.0.0

func (r *Reader) HasNext() bool

HasNext returns true if there are more bytes to read.

func (*Reader) MakePointer added in v1.0.0

func (r *Reader) MakePointer[T any](p **T) error

MakePointer sets *p to a new pointer after charging its size against the remaining memory of r. Other than charging memory, it is equivalent to `*p = new(T)`.

This method is useful to use in auto-generated code, when the type of a variable is unknown.

func (*Reader) MakeSlice added in v1.0.0

func (r *Reader) MakeSlice[S ~[]E, E any](s *S, length uint64) error

MakeSlice sets *s to a new slice with the given length after charging its size against the remaining memory of r. Other than charging memory, it is equivalent to `*s = make(S, length)`.

This method is useful to use in auto-generated code, when the type of a variable is unknown.

func (*Reader) ReadBool added in v1.0.0

func (r *Reader) ReadBool[T ~bool](v *T) error

ReadBool reads a boolean from the reader.

func (*Reader) ReadBools added in v1.0.0

func (r *Reader) ReadBools[S ~[]E, E ~bool](v *S) error

ReadBools reads a length-prefixed packed repeated boolean field from the reader.

func (*Reader) ReadBoolsInto added in v1.0.0

func (r *Reader) ReadBoolsInto[S ~[]E, E ~bool](vs S) error

ReadBoolsInto reads a length-prefixed packed repeated boolean field from the reader into vs. The field must contain exactly len(vs) values.

func (*Reader) ReadBytes added in v1.0.0

func (r *Reader) ReadBytes[T ~[]byte](v *T) error

ReadBytes reads a byte slice from the reader.

func (*Reader) ReadFint32 added in v1.0.0

func (r *Reader) ReadFint32[T Int32](v *T) error

ReadFint32 reads a 32-bit fixed size integer from the reader.

func (*Reader) ReadFint32s added in v1.0.0

func (r *Reader) ReadFint32s[S ~[]E, E Int32](v *S) error

ReadFint32s reads a length-prefixed packed repeated 32-bit fixed size integer field from the reader.

func (*Reader) ReadFint32sInto added in v1.0.0

func (r *Reader) ReadFint32sInto[S ~[]E, E Int32](vs S) error

ReadFint32sInto reads a length-prefixed packed repeated 32-bit fixed size integer field from the reader into vs. The field must contain exactly len(vs) values.

func (*Reader) ReadFint64 added in v1.0.0

func (r *Reader) ReadFint64[T Int64](v *T) error

ReadFint64 reads a 64-bit fixed size integer from the reader.

func (*Reader) ReadFint64s added in v1.0.0

func (r *Reader) ReadFint64s[S ~[]E, E Int64](v *S) error

ReadFint64s reads a length-prefixed packed repeated 64-bit fixed size integer field from the reader.

func (*Reader) ReadFint64sInto added in v1.0.0

func (r *Reader) ReadFint64sInto[S ~[]E, E Int64](vs S) error

ReadFint64sInto reads a length-prefixed packed repeated 64-bit fixed size integer field from the reader into vs. The field must contain exactly len(vs) values.

func (*Reader) ReadInt added in v1.0.0

func (r *Reader) ReadInt[T Int](v *T) error

ReadInt reads a zigzag encoded integer from the reader.

func (*Reader) ReadInts added in v1.0.0

func (r *Reader) ReadInts[S ~[]E, E Int](v *S) (uint64, error)

ReadInts reads a length-prefixed packed repeated zigzag encoded varint field from the reader. It returns the size of the packed field in bytes.

func (*Reader) ReadIntsInto added in v1.0.0

func (r *Reader) ReadIntsInto[S ~[]E, E Int](vs S) (uint64, error)

ReadIntsInto reads a length-prefixed packed repeated zigzag encoded varint field from the reader into vs. The field must contain exactly len(vs) values. It returns the size of the packed field in bytes.

func (*Reader) ReadString added in v1.0.0

func (r *Reader) ReadString[T ~string](v *T) error

ReadString reads a string from the reader. The string is verified to be valid UTF-8.

func (*Reader) ReadTag added in v1.0.0

func (r *Reader) ReadTag() (uint32, WireType, error)

ReadTag reads the next field number and wire type from the reader.

func (*Reader) ReadUint added in v1.0.0

func (r *Reader) ReadUint[T Uint](v *T) error

ReadUint reads a varint encoded unsigned integer from the reader.

func (*Reader) ReadUints added in v1.0.0

func (r *Reader) ReadUints[S ~[]E, E Uint](v *S) (uint64, error)

ReadUints reads a length-prefixed packed repeated varint field from the reader. It returns the size of the packed field in bytes.

func (*Reader) ReadUintsInto added in v1.0.0

func (r *Reader) ReadUintsInto[S ~[]E, E Uint](vs S) (uint64, error)

ReadUintsInto reads a length-prefixed packed repeated varint field from the reader into vs. The field must contain exactly len(vs) values. It returns the size of the packed field in bytes.

func (*Reader) Result added in v1.0.1

func (r *Reader) Result() UnmarshalResult

Result returns the UnmarshalResult describing the current state of r.

func (*Reader) SkipBytes added in v1.0.0

func (r *Reader) SkipBytes() error

SkipBytes advances the reader past a byte slice without reading it.

func (*Reader) SubReader added in v1.0.0

func (r *Reader) SubReader(sub *Reader) error

SubReader reads a length-prefixed byte slice from r and sets sub to a Reader over those bytes. The bytes are never copied, regardless of r.Unsafe.

All configuration of sub is inherited from r, except that sub.DepthLimit is one less than r.DepthLimit. If r.DepthLimit is 0, ErrDepthLimitExceeded is returned.

func (*Reader) UnwrapPointer added in v1.0.0

func (r *Reader) UnwrapPointer() error

UnwrapPointer strips the presence prefix from a non-nil repeated pointer element, leaving r.B as the encoded value.

func (*Reader) UseMemory added in v1.0.0

func (r *Reader) UseMemory(n uint64) error

UseMemory charges n bytes against Reader.MemoryRemaining. If the remaining memory is insufficient, ErrMemoryLimitExceeded is returned.

func (*Reader) UseSliceMemory added in v1.0.0

func (r *Reader) UseSliceMemory[E any](length uint64) error

UseSliceMemory charges the memory of a slice of length elements of type E, as Reader.UseMemory does.

type SizeEnum added in v0.13.1

type SizeEnum uint8

SizeEnum indicates the size of an integer type in FieldType.

const (
	// SizeEnum8 indicates an [int8] or [uint8] type.
	SizeEnum8 SizeEnum = 1
	// SizeEnum16 indicates an [int16] or [uint16] type.
	SizeEnum16 SizeEnum = 2
	// SizeEnum32 indicates an [Int32].
	SizeEnum32 SizeEnum = 3
	// SizeEnum64 indicates an [Int64].
	SizeEnum64 SizeEnum = 4
)

func SizeOf added in v0.13.1

func SizeOf[T integer](v T) SizeEnum

SizeOf returns the size of the integer type.

type Spec added in v0.13.1

type Spec struct {
	Name   string      `canoto:"string,1"         json:"name"`
	Fields []FieldType `canoto:"repeated value,2" json:"fields"`
	// contains filtered or unexported fields
}

Spec is the specification of a Canoto message.

Given a message specification, a Codec can be used to parse bytes into an Any.

Spec is itself a message, to allow for implementations of universal canoto message interpreters.

func (*Spec) AppendCanoto added in v0.20.0

func (c *Spec) AppendCanoto(w Writer) Writer

AppendCanoto appends the struct to a Writer and returns the resulting Writer. Most users should just use MarshalCanoto.

It is assumed that CacheCanoto has been called since the last modification to this struct.

It is assumed that this struct is ValidCanoto.

func (*Spec) CacheCanoto added in v0.20.0

func (c *Spec) CacheCanoto()

CacheCanoto populates size and OneOf caches based on the current values in the struct.

func (*Spec) CheckCanoto added in v0.20.0

func (c *Spec) CheckCanoto() bool

CheckCanoto validates that the struct can be correctly marshaled into the Canoto format. Most users should just use ValidCanoto.

It is assumed that CacheCanoto has been called since the last modification to this struct.

func (*Spec) DescribeCanoto added in v0.20.0

func (*Spec) DescribeCanoto(types ...reflect.Type) *Spec

DescribeCanoto returns a Spec describing the fields of this message and their wire types.

types is used as a stack of ancestor messages to detect recursive specs.

func (*Spec) MarshalCanoto added in v0.13.1

func (c *Spec) MarshalCanoto() []byte

MarshalCanoto returns the Canoto representation of this struct.

It is assumed that this struct is ValidCanoto.

func (*Spec) SizeCanoto added in v0.20.0

func (c *Spec) SizeCanoto() uint64

SizeCanoto returns the previously calculated size of the Canoto representation from CacheCanoto.

If CacheCanoto has not yet been called, or the struct has been modified since the last call to CacheCanoto, the returned size may be incorrect.

func (*Spec) UnmarshalCanoto added in v0.13.1

func (c *Spec) UnmarshalCanoto(bytes []byte) error

UnmarshalCanoto unmarshals a Canoto-encoded byte slice into the struct.

During parsing, the canoto cache is saved.

func (*Spec) UnmarshalCanotoFrom added in v0.13.1

func (c *Spec) UnmarshalCanotoFrom(r Reader) (UnmarshalResult, error)

UnmarshalCanotoFrom populates the struct from a Reader. Most users should just use UnmarshalCanoto.

During parsing, the canoto cache is saved.

This function enables configuration of reader options.

func (*Spec) ValidCanoto added in v0.13.1

func (c *Spec) ValidCanoto() bool

ValidCanoto validates that the struct can be correctly marshaled into the Canoto format.

type Uint

type Uint interface {
	~uint8 | ~uint16 | ~uint32 | ~uint64
}

Uint is a constraint that permits any sized unsigned integer type.

type UnmarshalResult added in v0.20.0

type UnmarshalResult struct {
	// MemoryRemaining is the remaining [Reader.MemoryRemaining].
	MemoryRemaining uint64
}

UnmarshalResult is the state returned after successfully unmarshaling a Field.

UnmarshalResult should be created with Reader.Result and consumed with Reader.ApplyResult.

type WireType

type WireType byte

WireType represents the Proto wire description of a field. Within Proto it is used to provide forwards compatibility. For Canoto, it exists to provide compatibility with Proto.

const (
	// Varint represents the variable-length integer wire type.
	Varint WireType = iota
	// I64 represents the 64-bit fixed-length wire type.
	I64
	// Len represents the length-delimited wire type.
	Len

	// I32 represents the 32-bit fixed-length wire type.
	I32
)

func (WireType) String

func (w WireType) String() string

String returns the string representation of the wire type.

type Writer

type Writer struct {
	// B is the accumulated output bytes.
	B []byte
}

Writer contains all the state needed to marshal a Canoto type.

func (*Writer) Append added in v1.0.0

func (w *Writer) Append[T Bytes](v T)

Append writes raw bytes to the writer without a length prefix.

func (*Writer) AppendBool added in v1.0.0

func (w *Writer) AppendBool[T ~bool](b T)

AppendBool writes a boolean to the writer.

func (*Writer) AppendBools added in v1.0.0

func (w *Writer) AppendBools[S ~[]E, E ~bool](vs S)

AppendBools writes a length-prefixed packed repeated boolean field to the writer.

func (*Writer) AppendBytes added in v1.0.0

func (w *Writer) AppendBytes[T Bytes](v T)

AppendBytes writes a length-prefixed byte slice to the writer.

func (*Writer) AppendFint32 added in v1.0.0

func (w *Writer) AppendFint32[T Int32](v T)

AppendFint32 writes a 32-bit fixed size integer to the writer.

func (*Writer) AppendFint32s added in v1.0.0

func (w *Writer) AppendFint32s[S ~[]E, E Int32](vs S)

AppendFint32s writes a length-prefixed packed repeated 32-bit fixed size integer field to the writer.

func (*Writer) AppendFint64 added in v1.0.0

func (w *Writer) AppendFint64[T Int64](v T)

AppendFint64 writes a 64-bit fixed size integer to the writer.

func (*Writer) AppendFint64s added in v1.0.0

func (w *Writer) AppendFint64s[S ~[]E, E Int64](vs S)

AppendFint64s writes a length-prefixed packed repeated 64-bit fixed size integer field to the writer.

func (*Writer) AppendInt added in v1.0.0

func (w *Writer) AppendInt[T Int](v T)

AppendInt writes an integer to the writer as a zigzag encoded varint.

func (*Writer) AppendInts added in v1.0.0

func (w *Writer) AppendInts[S ~[]E, E Int](vs S)

AppendInts writes integers to the writer as packed zigzag encoded varints.

Unlike the fixed size variants, this method does NOT write a length prefix. This allows the caller to more efficiently compute the total size of the packed field in advance.

func (*Writer) AppendUint added in v1.0.0

func (w *Writer) AppendUint[T Uint](v T)

AppendUint writes an unsigned integer to the writer as a varint.

func (*Writer) AppendUints added in v1.0.0

func (w *Writer) AppendUints[S ~[]E, E Uint](vs S)

AppendUints writes unsigned integers to the writer as packed varints.

Unlike the fixed size variants, this method does NOT write a length prefix. This allows the caller to more efficiently compute the total size of the packed field in advance.

Directories

Path Synopsis
Canoto is a command to generate code for reading and writing the canoto format.
Canoto is a command to generate code for reading and writing the canoto format.
cli module
generate module
big
canoto
Package canoto implements a canonical, compact, and fast serialization format that is read-compatible with Protocol Buffers.
Package canoto implements a canonical, compact, and fast serialization format that is read-compatible with Protocol Buffers.
generate
Package generate produces canoto serialization code, proto definitions, and standalone library copies from Go source files.
Package generate produces canoto serialization code, proto definitions, and standalone library copies from Go source files.
imported
Package imported declares messages whose names collide with identifiers in the examples package, to verify that imported types are not confused with local messages or type parameters.
Package imported declares messages whose names collide with identifiers in the examples package, to verify that imported types are not confused with local messages or type parameters.
pb

Jump to

Keyboard shortcuts

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