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 ¶
- Constants
- Variables
- func CacheUint32(addr *uint32, val uint32)
- func CacheUint64(addr *uint64, val uint64)
- func CountBytes[T Bytes](bytes []byte, tag T) (uint64, error)
- func HasPrefix[T Bytes](bytes []byte, prefix T) bool
- func IsZero[T comparable](v *T) bool
- func MakeEntry[S ~[]E, E any](S) (_ E)
- func MakeEntryNilPointer[S ~[]E, E any](S) (_ *E)
- func SizeBytes[T Bytes](v T) uint64
- func SizeInt[T Int](v T) uint64
- func SizeUint[T Uint](v T) uint64
- func Tag(fieldNumber uint32, wireType WireType) []byte
- func ValidString[T ~string](v T) bool
- type Any
- type AnyField
- type Bytes
- type Codec
- type Field
- type FieldPointer
- type FieldType
- func (c *FieldType) AppendCanoto(w Writer) Writer
- func (c *FieldType) CacheCanoto()
- func (c *FieldType) CheckCanoto() bool
- func (*FieldType) DescribeCanoto(types ...reflect.Type) *Spec
- func (c *FieldType) MarshalCanoto() []byte
- func (c *FieldType) SizeCanoto() uint64
- func (c *FieldType) UnmarshalCanoto(bytes []byte) error
- func (c *FieldType) UnmarshalCanotoFrom(r Reader) (UnmarshalResult, error)
- func (c *FieldType) ValidCanoto() bool
- func (c *FieldType) WhichCanotoType() FieldTypeOneOf
- type FieldTypeOneOf
- type Int
- type Int32
- type Int64
- type Message
- type Reader
- func (r *Reader) ApplyResult(result UnmarshalResult)
- func (r *Reader) HasNext() bool
- func (r *Reader) MakePointer[T any](p **T) error
- func (r *Reader) MakeSlice[S ~[]E, E any](s *S, length uint64) error
- func (r *Reader) ReadBool[T ~bool](v *T) error
- func (r *Reader) ReadBools[S ~[]E, E ~bool](v *S) error
- func (r *Reader) ReadBoolsInto[S ~[]E, E ~bool](vs S) error
- func (r *Reader) ReadBytes[T ~[]byte](v *T) error
- func (r *Reader) ReadFint32[T Int32](v *T) error
- func (r *Reader) ReadFint32s[S ~[]E, E Int32](v *S) error
- func (r *Reader) ReadFint32sInto[S ~[]E, E Int32](vs S) error
- func (r *Reader) ReadFint64[T Int64](v *T) error
- func (r *Reader) ReadFint64s[S ~[]E, E Int64](v *S) error
- func (r *Reader) ReadFint64sInto[S ~[]E, E Int64](vs S) error
- func (r *Reader) ReadInt[T Int](v *T) error
- func (r *Reader) ReadInts[S ~[]E, E Int](v *S) (uint64, error)
- func (r *Reader) ReadIntsInto[S ~[]E, E Int](vs S) (uint64, error)
- func (r *Reader) ReadString[T ~string](v *T) error
- func (r *Reader) ReadTag() (uint32, WireType, error)
- func (r *Reader) ReadUint[T Uint](v *T) error
- func (r *Reader) ReadUints[S ~[]E, E Uint](v *S) (uint64, error)
- func (r *Reader) ReadUintsInto[S ~[]E, E Uint](vs S) (uint64, error)
- func (r *Reader) Result() UnmarshalResult
- func (r *Reader) SkipBytes() error
- func (r *Reader) SubReader(sub *Reader) error
- func (r *Reader) UnwrapPointer() error
- func (r *Reader) UseMemory(n uint64) error
- func (r *Reader) UseSliceMemory[E any](length uint64) error
- type SizeEnum
- type Spec
- func (c *Spec) AppendCanoto(w Writer) Writer
- func (c *Spec) CacheCanoto()
- func (c *Spec) CheckCanoto() bool
- func (*Spec) DescribeCanoto(types ...reflect.Type) *Spec
- func (c *Spec) MarshalCanoto() []byte
- func (c *Spec) SizeCanoto() uint64
- func (c *Spec) UnmarshalCanoto(bytes []byte) error
- func (c *Spec) UnmarshalCanotoFrom(r Reader) (UnmarshalResult, error)
- func (c *Spec) ValidCanoto() bool
- type Uint
- type UnmarshalResult
- type WireType
- type Writer
- func (w *Writer) Append[T Bytes](v T)
- func (w *Writer) AppendBool[T ~bool](b T)
- func (w *Writer) AppendBools[S ~[]E, E ~bool](vs S)
- func (w *Writer) AppendBytes[T Bytes](v T)
- func (w *Writer) AppendFint32[T Int32](v T)
- func (w *Writer) AppendFint32s[S ~[]E, E Int32](vs S)
- func (w *Writer) AppendFint64[T Int64](v T)
- func (w *Writer) AppendFint64s[S ~[]E, E Int64](vs S)
- func (w *Writer) AppendInt[T Int](v T)
- func (w *Writer) AppendInts[S ~[]E, E Int](vs S)
- func (w *Writer) AppendUint[T Uint](v T)
- func (w *Writer) AppendUints[S ~[]E, E Uint](vs S)
Examples ¶
Constants ¶
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.
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.
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.
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 ¶
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.
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
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
CacheUint64 atomically stores val into *addr.
When built with -race, the store is hidden from the race detector.
func CountBytes ¶
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 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 SizeUint ¶ added in v0.13.1
SizeUint calculates the size of an unsigned integer when encoded as a varint.
func Tag ¶
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
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
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 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
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
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
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
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 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
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
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) ReadBools ¶ added in v1.0.0
ReadBools reads a length-prefixed packed repeated boolean field from the reader.
func (*Reader) ReadBoolsInto ¶ added in v1.0.0
ReadBoolsInto reads a length-prefixed packed repeated boolean field from the reader into vs. The field must contain exactly len(vs) values.
func (*Reader) ReadFint32 ¶ added in v1.0.0
ReadFint32 reads a 32-bit fixed size integer from the reader.
func (*Reader) ReadFint32s ¶ added in v1.0.0
ReadFint32s reads a length-prefixed packed repeated 32-bit fixed size integer field from the reader.
func (*Reader) ReadFint32sInto ¶ added in v1.0.0
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
ReadFint64 reads a 64-bit fixed size integer from the reader.
func (*Reader) ReadFint64s ¶ added in v1.0.0
ReadFint64s reads a length-prefixed packed repeated 64-bit fixed size integer field from the reader.
func (*Reader) ReadFint64sInto ¶ added in v1.0.0
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) ReadInts ¶ added in v1.0.0
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
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
ReadString reads a string from the reader. The string is verified to be valid UTF-8.
func (*Reader) ReadTag ¶ added in v1.0.0
ReadTag reads the next field number and wire type from the reader.
func (*Reader) ReadUint ¶ added in v1.0.0
ReadUint reads a varint encoded unsigned integer from the reader.
func (*Reader) ReadUints ¶ added in v1.0.0
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
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
UseMemory charges n bytes against Reader.MemoryRemaining. If the remaining memory is insufficient, ErrMemoryLimitExceeded is returned.
func (*Reader) UseSliceMemory ¶ added in v1.0.0
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 )
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
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
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 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 )
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
|
|
|
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. |