capnp

package module
v3.0.0-alpha-29 Latest Latest
Warning

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

Go to latest
Published: May 16, 2023 License: MIT Imports: 19 Imported by: 205

README

Cap'n Proto bindings for Go

License CodeQuality Go GoDoc Matrix

Cap’n Proto is an insanely fast data interchange format similar to Protocol Buffers, but much faster.

It also includes a sophisticated RPC system based on Object Capabilities, ideal for secure, low-latency applications.

This package provides:

  • Go code-generation for Cap'n Proto
  • Runtime support for the Go language
  • Level 1 support for the Cap'n Proto RPC protocol

Support for Level 3 RPC is planned.

Getting Started

Read the "Getting Started" guide for a high-level introduction to the package API and workflow.

Help and Support

You can find us on Matrix: Go Cap'n Proto

API Reference

Available on pkg.go.dev

API Compatibility

Until the official Cap'n Proto spec is finalized, this repository should be considered beta software.

We use semantic versioning to track compatibility and signal breaking changes. In the spirit of the Go 1 compatibility guarantee, we will make every effort to avoid making breaking API changes within major version numbers, but nevertheless reserve the right to introduce breaking changes for reasons related to:

  • Security.
  • Changes in the Cap'n Proto specification.
  • Bugs.

An exception to this rule is currently in place for the pogs package, which is relatively new and may change over time. However, its functionality has been well-tested, and breaking changes are relatively unlikely.

Note also we may merge breaking changes to the main branch without notice. Users are encouraged to pin their dependencies to a major version, e.g. using the semver-aware features of go get.

License

MIT - see LICENSE file

Documentation

Overview

Package capnp is a Cap'n Proto library for Go. https://capnproto.org/

Read the Getting Started guide for a tutorial on how to use this package. https://github.com/capnproto/go-capnproto2/wiki/Getting-Started

Generating code

capnpc-go provides the compiler backend for capnp.

# First, install capnpc-go to $PATH.
go install capnproto.org/go/capnp/v3/capnpc-go
# Then, check out the go-capnp source code:
git clone https://github.com/capnproto/go-capnp /desired/path/to/go-capnp
# Then, generate Go files.
capnp compile -I /desired/path/to/go-capnp/std -ogo *.capnp

capnpc-go requires two annotations for all files: package and import. package is needed to know what package to place at the head of the generated file and what identifier to use when referring to the type from another package. import should be the fully qualified import path and is used to generate import statement from other packages and to detect when two types are in the same package. For example:

using Go = import "/go.capnp";
$Go.package("main");
$Go.import("capnproto.org/go/capnp/v3/example");

For adding documentation comments to the generated code, there's the doc annotation. This annotation adds the comment to a struct, enum or field so that godoc will pick it up. For example:

struct Zdate $Go.doc("Zdate represents a calendar date") {
  year  @0   :Int16;
  month @1   :UInt8;
  day   @2   :UInt8 ;
}

Messages and Segments

In Cap'n Proto, the unit of communication is a message. A message consists of one or more segments -- contiguous blocks of memory. This allows large messages to be split up and loaded independently or lazily. Typically you will use one segment per message. Logically, a message is organized in a tree of objects, with the root always being a struct (as opposed to a list or primitive). Messages can be read from and written to a stream.

The Message and Segment types are the main types that application code will use from this package. The Message type has methods for marshaling and unmarshaling its segments to the wire format. If the application needs to read or write from a stream, it should use the Encoder and Decoder types.

Pointers

The type for a generic reference to a Cap'n Proto object is Ptr. A Ptr can refer to a struct, a list, or an interface. Ptr, Struct, List, and Interface (the pointer types) have value semantics and refer to data in a single segment. All of the pointer types have a notion of "valid". An invalid pointer will return the default value from any accessor and panic when any setter is called.

In previous versions of this package, the Pointer interface was used instead of the Ptr struct. This interface and functions that use it are now deprecated. See https://github.com/capnproto/go-capnproto2/wiki/New-Ptr-Type for details about this API change.

Data accessors and setters (i.e. struct primitive fields and list elements) do not return errors, but pointer accessors and setters do. There are a few reasons that a read or write of a pointer can fail, but the most common are bad pointers or allocation failures. For accessors, an invalid object will be returned in case of an error.

Since Go doesn't have generics, wrapper types provide type safety on lists. This package provides lists of basic types, and capnpc-go generates list wrappers for named types. However, if you need to use deeper nesting of lists (e.g. List(List(UInt8))), you will need to use a PointerList and wrap the elements.

Structs

For the following schema:

struct Foo @0x8423424e9b01c0af {
  num @0 :UInt32;
  bar @1 :Foo;
}

capnpc-go will generate:

// Foo is a pointer to a Foo struct in a segment.
// Member functions are provided to get/set members in the
// struct.
type Foo struct{ capnp.Struct }

// Foo_TypeID is the unique identifier for the type Foo.
// It remains the same across languages and schema changes.
const Foo_TypeID = 0x8423424e9b01c0af

// NewFoo creates a new orphaned Foo struct, preferring placement in
// s.  If there isn't enough space, then another segment in the
// message will be used or allocated.  You can set a field of type Foo
// to this new message, but usually you will want to use the
// NewBar()-style method shown below.
func NewFoo(s *capnp.Segment) (Foo, error)

// NewRootFoo creates a new Foo struct and sets the message's root to
// it.
func NewRootFoo(s *capnp.Segment) (Foo, error)

// ReadRootFoo reads the message's root pointer and converts it to a
// Foo struct.
func ReadRootFoo(msg *capnp.Message) (Foo, error)

// Num returns the value of the num field.
func (s Foo) Num() uint32

// SetNum sets the value of the num field to v.
func (s Foo) SetNum(v uint32)

// Bar returns the value of the bar field.  This can return an error
// if the pointer goes beyond the segment's range, the segment fails
// to load, or the pointer recursion limit has been reached.
func (s Foo) Bar() (Foo, error)

// HasBar reports whether the bar field was initialized (non-null).
func (s Foo) HasBar() bool

// SetBar sets the value of the bar field to v.
func (s Foo) SetBar(v Foo) error

// NewBar sets the bar field to a newly allocated Foo struct,
// preferring placement in s's segment.
func (s Foo) NewBar() (Foo, error)

// Foo_List is a value with pointer semantics. It is created for all
// structs, and is used for List(Foo) in the capnp file.
type Foo_List struct{ capnp.List }

// NewFoo_List creates a new orphaned List(Foo), preferring placement
// in s. This can then be added to a message by using a Set function
// which takes a Foo_List. sz specifies the number of elements in the
// list.  The list's size cannot be changed after creation.
func NewFoo_List(s *capnp.Segment, sz int32) Foo_List

// Len returns the number of elements in the list.
func (s Foo_List) Len() int

// At returns a pointer to the i'th element. If i is an invalid index,
// this will return an invalid Foo (all getters will return default
// values, setters will fail).
func (s Foo_List) At(i int) Foo

// Foo_Promise is a promise for a Foo.  Methods are provided to get
// promises of struct and interface fields.
type Foo_Promise struct{ *capnp.Pipeline }

// Get waits until the promise is resolved and returns the result.
func (p Foo_Promise) Get() (Foo, error)

// Bar returns a promise for that bar field.
func (p Foo_Promise) Bar() Foo_Promise

Groups

For each group a typedef is created with a different method set for just the groups fields:

struct Foo {
	group :Group {
		field @0 :Bool;
	}
}

generates the following:

type Foo struct{ capnp.Struct }
type Foo_group Foo

func (s Foo) Group() Foo_group
func (s Foo_group) Field() bool

That way the following may be used to access a field in a group:

var f Foo
value := f.Group().Field()

Note that group accessors just convert the type and so have no overhead.

Unions

Named unions are treated as a group with an inner unnamed union. Unnamed unions generate an enum Type_Which and a corresponding Which() function:

struct Foo {
	union {
		a @0 :Bool;
		b @1 :Bool;
	}
}

generates the following:

type Foo_Which uint16

const (
	Foo_Which_a Foo_Which = 0
	Foo_Which_b Foo_Which = 1
)

func (s Foo) A() bool
func (s Foo) B() bool
func (s Foo) SetA(v bool)
func (s Foo) SetB(v bool)
func (s Foo) Which() Foo_Which

Which() should be checked before using the getters, and the default case must always be handled.

Setters for single values will set the union discriminator as well as set the value.

For voids in unions, there is a void setter that just sets the discriminator. For example:

struct Foo {
	union {
		a @0 :Void;
		b @1 :Void;
	}
}

generates the following:

func (s Foo) SetA() // Set that we are using A
func (s Foo) SetB() // Set that we are using B

Similarly, for groups in unions, there is a group setter that just sets the discriminator. This must be called before the group getter can be used to set values. For example:

struct Foo {
	union {
		a :group {
			v :Bool
		}
		b :group {
			v :Bool
		}
	}
}

and in usage:

f.SetA()         // Set that we are using group A
f.A().SetV(true) // then we can use the group A getter to set the inner values

Enums

capnpc-go generates enum values as constants. For example in the capnp file:

enum ElementSize {
  empty @0;
  bit @1;
  byte @2;
  twoBytes @3;
  fourBytes @4;
  eightBytes @5;
  pointer @6;
  inlineComposite @7;
}

In the generated capnp.go file:

type ElementSize uint16

const (
	ElementSize_empty           ElementSize = 0
	ElementSize_bit             ElementSize = 1
	ElementSize_byte            ElementSize = 2
	ElementSize_twoBytes        ElementSize = 3
	ElementSize_fourBytes       ElementSize = 4
	ElementSize_eightBytes      ElementSize = 5
	ElementSize_pointer         ElementSize = 6
	ElementSize_inlineComposite ElementSize = 7
)

In addition an enum.String() function is generated that will convert the constants to a string for debugging or logging purposes. By default, the enum name is used as the tag value, but the tags can be customized with a $Go.tag or $Go.notag annotation.

For example:

enum ElementSize {
	empty @0           $Go.tag("void");
	bit @1             $Go.tag("1 bit");
	byte @2            $Go.tag("8 bits");
	inlineComposite @7 $Go.notag;
}

In the generated go file:

func (c ElementSize) String() string {
	switch c {
	case ElementSize_empty:
		return "void"
	case ElementSize_bit:
		return "1 bit"
	case ElementSize_byte:
		return "8 bits"
	default:
		return ""
	}
}

Interfaces

capnpc-go generates type-safe Client wrappers for interfaces. For parameter lists and result lists, structs are generated as described above with the names Interface_method_Params and Interface_method_Results, unless a single struct type is used. For example, for this interface:

interface Calculator {
	evaluate @0 (expression :Expression) -> (value :Value);
}

capnpc-go generates the following Go code (along with the structs Calculator_evaluate_Params and Calculator_evaluate_Results):

// Calculator is a client to a Calculator interface.
type Calculator struct{ Client capnp.Client }

// Evaluate calls `evaluate` on the client.  params is called on a newly
// allocated Calculator_evaluate_Params struct to fill in the parameters.
func (c Calculator) Evaluate(
	ctx context.Context,
	params func(Calculator_evaluate_Params) error,
	opts ...capnp.CallOption) *Calculator_evaluate_Results_Promise

capnpc-go also generates code to implement the interface:

// A Calculator_Server implements the Calculator interface.
type Calculator_Server interface {
	Evaluate(context.Context, Calculator_evaluate_Call) error
}

// Calculator_evaluate_Call holds the arguments for a Calculator.evaluate server call.
type Calculator_evaluate_Call struct {
	Params  Calculator_evaluate_Params
	Results Calculator_evaluate_Results
	Options capnp.CallOptions
}

// Calculator_ServerToClient is equivalent to calling:
// NewCalculator(capnp.NewServer(Calculator_Methods(nil, s), s))
// If s does not implement the Close method, then nil is used.
func Calculator_ServerToClient(s Calculator_Server) Calculator

// Calculator_Methods appends methods from Calculator that call to server and
// returns the methods.  If methods is nil or the capacity of the underlying
// slice is too small, a new slice is returned.
func Calculator_Methods(methods []server.Method, s Calculator_Server) []server.Method

Since a single capability may want to implement many interfaces, you can use multiple *_Methods functions to build a single slice to send to NewServer.

An example of combining the client/server code to communicate with a locally implemented Calculator:

var srv Calculator_Server
calc := Calculator_ServerToClient(srv)
result := calc.Evaluate(ctx, func(params Calculator_evaluate_Params) {
	params.SetExpression(expr)
})
val := result.Value().Get()

A note about message ordering: by default, only one method per server will be invoked at a time; when implementing a server method which blocks or takes a long time, you calling the server.Go function to unblock future calls.

Example
// Make a brand new empty message.
msg, seg, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
	panic(err)
}

// If you want runtime-type identification, this is easily obtained. Just
// wrap everything in a struct that contains a single anoymous union (e.g. struct Z).
// Then always set a Z as the root object in you message/first segment.
// The cost of the extra word of storage is usually worth it, as
// then human readable output is easily obtained via a shell command such as
//
// $ cat binary.cpz | capnp decode aircraft.capnp Z
//
// If you need to conserve space, and know your content in advance, it
// isn't necessary to use an anonymous union. Just supply the type name
// in place of 'Z' in the decode command above.

// There can only be one root.  Subsequent NewRoot* calls will set the root
// pointer and orphan the previous root.
z, err := air.NewRootZ(seg)
if err != nil {
	panic(err)
}

// then non-root objects:
aircraft, err := z.NewAircraft()
if err != nil {
	panic(err)
}
b737, err := aircraft.NewB737()
if err != nil {
	panic(err)
}
planebase, err := b737.NewBase()
if err != nil {
	panic(err)
}

// Set primitive fields
planebase.SetCanFly(true)
planebase.SetName("Henrietta")
planebase.SetRating(100)
planebase.SetMaxSpeed(876) // km/hr
// if we don't set capacity, it will get the default value, in this case 0.
//planebase.SetCapacity(26020) // Liters fuel

// Creating a list
homes, err := planebase.NewHomes(2)
if err != nil {
	panic(err)
}
homes.Set(0, air.Airport_jfk)
homes.Set(1, air.Airport_lax)

// Ready to write!

// You can write to memory...
buf, err := msg.Marshal()
if err != nil {
	panic(err)
}
_ = buf

// ... or write to an io.Writer.
file, err := os.CreateTemp("", "go-capnproto")
if err != nil {
	panic(err)
}
defer file.Close()
defer os.Remove(file.Name())
err = capnp.NewEncoder(file).Encode(msg)
if err != nil {
	panic(err)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Canonicalize

func Canonicalize(s Struct) ([]byte, error)

Canonicalize encodes a struct into its canonical form: a single- segment blob without a segment table. The result will be identical for equivalent structs, even as the schema evolves. The blob is suitable for hashing or signing.

func Disconnected

func Disconnected(s string) error

Disconnected returns an error that formats as the given text and will report true when passed to IsDisconnected.

func Equal

func Equal(p1, p2 Ptr) (bool, error)

Equal returns true iff p1 and p2 are equal.

Equality is defined to be:

  • Two structs are equal iff all of their fields are equal. If one struct has more fields than the other, the extra fields must all be zero.
  • Two lists are equal iff they have the same length and their corresponding elements are equal. If one list is a list of primitives and the other is a list of structs, then the list of primitives is treated as if it was a list of structs with the element value as the sole field.
  • Two interfaces are equal iff they point to a capability created by the same call to NewClient or they are referring to the same capability table index in the same message. The latter is significant when the message's capability table has not been populated.
  • Two null pointers are equal.
  • All other combinations of things are not equal.

func IsDisconnected

func IsDisconnected(e error) bool

IsDisconnected reports whether e indicates a failure due to loss of a necessary capability.

func IsUnimplemented

func IsUnimplemented(e error) bool

IsUnimplemented reports whether e indicates that functionality is unimplemented.

func NewMessage

func NewMessage(arena Arena) (*Message, *Segment, error)

NewMessage creates a message with a new root and returns the first segment. It is an error to call NewMessage on an arena with data in it.

func NewMultiSegmentMessage

func NewMultiSegmentMessage(b [][]byte) (msg *Message, first *Segment)

Analogous to NewSingleSegmentMessage, but using MultiSegment.

func NewPromisedClient

func NewPromisedClient(hook ClientHook) (Client, Resolver[Client])

NewPromisedClient creates the first reference to a capability that can resolve to a different capability. The hook will be shut down when the promise is resolved or the client has no more references, whichever comes first.

Typically the RPC system will create a client for the application. Most applications will not need to use this directly.

func NewSingleSegmentMessage

func NewSingleSegmentMessage(b []byte) (msg *Message, first *Segment)

NewSingleSegmentMessage(b) is equivalent to NewMessage(SingleSegment(b)), except that it panics instead of returning an error. This can only happen if the passed slice contains data, so the caller is responsible for ensuring that it has a length of zero.

func SamePtr

func SamePtr(p, q Ptr) bool

SamePtr reports whether p and q refer to the same object.

func SetClientLeakFunc

func SetClientLeakFunc(clientLeakFunc func(msg string))

SetClientLeakFunc sets a callback for reporting Clients that went out of scope without being released. The callback is not guaranteed to be called and must be safe to call concurrently from multiple goroutines. The exact format of the message is unspecified.

SetClientLeakFunc must not be called after any calls to NewClient or NewPromisedClient.

func Unimplemented

func Unimplemented(s string) error

Unimplemented returns an error that formats as the given text and will report true when passed to IsUnimplemented.

Types

type Answer

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

An Answer is a deferred result of a client call. Conceptually, this is a future. It is safe to use from multiple goroutines.

func ErrorAnswer

func ErrorAnswer(m Method, e error) *Answer

ErrorAnswer returns a Answer that always returns error e.

func ImmediateAnswer

func ImmediateAnswer(m Method, ptr Ptr) *Answer

ImmediateAnswer returns an Answer that accesses ptr.

func (*Answer) Client

func (ans *Answer) Client() Client

Client returns the answer as a client. If the answer's originating call has not completed, then calls will be queued until the original call's completion. The client reference is borrowed: the caller should not call Close.

func (*Answer) Done

func (ans *Answer) Done() <-chan struct{}

Done returns a channel that is closed when the answer's call is finished.

func (*Answer) Field

func (ans *Answer) Field(off uint16, def []byte) *Future

Field returns a derived future which yields the pointer field given, defaulting to the value given.

func (*Answer) Future

func (ans *Answer) Future() *Future

Future returns a future that is equivalent to ans.

func (*Answer) List

func (ans *Answer) List() (List, error)

List waits until the answer is resolved and returns the list this answer represents.

func (*Answer) Metadata

func (ans *Answer) Metadata() *Metadata

Metadata returns a metadata map where callers can store information about the answer

func (*Answer) PipelineRecv

func (ans *Answer) PipelineRecv(ctx context.Context, transform []PipelineOp, r Recv) PipelineCaller

PipelineRecv starts a pipelined call.

func (*Answer) PipelineSend

func (ans *Answer) PipelineSend(ctx context.Context, transform []PipelineOp, s Send) (*Answer, ReleaseFunc)

PipelineSend starts a pipelined call.

func (*Answer) Struct

func (ans *Answer) Struct() (Struct, error)

Struct waits until the answer is resolved and returns the struct this answer represents.

type AnswerQueue

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

AnswerQueue is a queue of method calls to make after an earlier method call finishes. The queue is unbounded; it is the caller's responsibility to manage/impose backpressure.

An AnswerQueue can be in one of three states:

  1. Queueing. Incoming method calls will be added to the queue.
  2. Draining, entered by calling Fulfill or Reject. Queued method calls will be delivered in sequence, and new incoming method calls will block until the AnswerQueue enters the Drained state.
  3. Drained, entered once all queued methods have been delivered. Incoming methods are passthrough.

func NewAnswerQueue

func NewAnswerQueue(m Method) *AnswerQueue

NewAnswerQueue creates a new answer queue.

func (*AnswerQueue) Fulfill

func (aq *AnswerQueue) Fulfill(ptr Ptr)

Fulfill empties the queue, delivering the method calls on the given pointer. After fulfill returns, pipeline calls will be immediately delivered instead of being queued.

func (*AnswerQueue) PipelineRecv

func (aq *AnswerQueue) PipelineRecv(ctx context.Context, transform []PipelineOp, r Recv) PipelineCaller

func (*AnswerQueue) PipelineSend

func (aq *AnswerQueue) PipelineSend(ctx context.Context, transform []PipelineOp, r Send) (*Answer, ReleaseFunc)

func (*AnswerQueue) Reject

func (aq *AnswerQueue) Reject(e error)

Reject empties the queue, returning errors on all the method calls.

type Arena

type Arena interface {
	// NumSegments returns the number of segments in the arena.
	// This must not be larger than 1<<32.
	NumSegments() int64

	// Data loads the data for the segment with the given ID.  IDs are in
	// the range [0, NumSegments()).
	// must be tightly packed in the range [0, NumSegments()).
	Data(id SegmentID) ([]byte, error)

	// Allocate selects a segment to place a new object in, creating a
	// segment or growing the capacity of a previously loaded segment if
	// necessary.  If Allocate does not return an error, then the
	// difference of the capacity and the length of the returned slice
	// must be at least minsz.  segs is a map of segments keyed by ID
	// using arrays returned by the Data method (although the length of
	// these slices may have changed by previous allocations).  Allocate
	// must not modify segs.
	//
	// If Allocate creates a new segment, the ID must be one larger than
	// the last segment's ID or zero if it is the first segment.
	//
	// If Allocate returns an previously loaded segment's ID, then the
	// arena is responsible for preserving the existing data in the
	// returned byte slice.
	Allocate(minsz Size, segs map[SegmentID]*Segment) (SegmentID, []byte, error)

	// Release all resources associated with the Arena. Callers MUST NOT
	// use the Arena after it has been released.
	//
	// Calling Release() is OPTIONAL, but may reduce allocations.
	//
	// Implementations MAY use Release() as a signal to return resources
	// to free lists, or otherwise reuse the Arena.   However, they MUST
	// NOT assume Release() will be called.
	Release()
}

An Arena loads and allocates segments for a Message.

type BitList

type BitList List

A BitList is a reference to a list of booleans.

func NewBitList

func NewBitList(s *Segment, n int32) (BitList, error)

NewBitList creates a new bit list, preferring placement in s.

func (BitList) At

func (p BitList) At(i int) bool

At returns the i'th bit.

func (BitList) DecodeFromPtr

func (BitList) DecodeFromPtr(p Ptr) BitList

func (BitList) EncodeAsPtr

func (l BitList) EncodeAsPtr(seg *Segment) Ptr

func (BitList) IsValid

func (l BitList) IsValid() bool

func (BitList) Len

func (l BitList) Len() int

func (BitList) Message

func (l BitList) Message() *Message

func (BitList) Segment

func (l BitList) Segment() *Segment

func (BitList) Set

func (p BitList) Set(i int, v bool)

Set sets the i'th bit to v.

func (BitList) String

func (p BitList) String() string

String returns the list in Cap'n Proto schema format (e.g. "[true, false]").

func (BitList) ToPtr

func (l BitList) ToPtr() Ptr

type BitOffset

type BitOffset uint32

BitOffset is an offset in bits from the beginning of a struct's data section. It is bounded to [0, 1<<22).

func (BitOffset) GoString

func (bit BitOffset) GoString() string

GoString returns the offset as a Go expression.

func (BitOffset) String

func (bit BitOffset) String() string

String returns the offset in the format "bit X".

type Brand

type Brand struct {
	Value any
}

A Brand is an opaque value used to identify a capability.

type CapList

type CapList[T ~ClientKind] PointerList

A list of some Cap'n Proto capability type T.

func (CapList[T]) At

func (c CapList[T]) At(i int) (T, error)

func (CapList[T]) DecodeFromPtr

func (CapList[T]) DecodeFromPtr(p Ptr) CapList[T]

func (CapList[T]) EncodeAsPtr

func (l CapList[T]) EncodeAsPtr(seg *Segment) Ptr

func (CapList[T]) IsValid

func (l CapList[T]) IsValid() bool

func (CapList[T]) Len

func (l CapList[T]) Len() int

func (CapList[T]) Message

func (l CapList[T]) Message() *Message

func (CapList[T]) Segment

func (l CapList[T]) Segment() *Segment

func (CapList[T]) Set

func (c CapList[T]) Set(i int, v T) error

func (CapList[T]) ToPtr

func (l CapList[T]) ToPtr() Ptr

type CapTable

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

CapTable is the indexed list of the clients referenced in the message. Capability pointers inside the message will use this table to map pointers to Clients. The table is populated by the RPC system.

https://capnproto.org/encoding.html#capabilities-interfaces

func (*CapTable) Add

func (ct *CapTable) Add(c Client) CapabilityID

Add appends a capability to the message's capability table and returns its ID. It "steals" c's reference: the Message will release the client when calling Reset.

func (CapTable) At

func (ct CapTable) At(i int) Client

At returns the capability at the given index of the table.

func (CapTable) Contains

func (ct CapTable) Contains(ifc Interface) bool

Contains returns true if the supplied interface corresponds to a client already present in the table.

func (CapTable) Get

func (ct CapTable) Get(ifc Interface) (c Client)

Get the client corresponding to the supplied interface. It returns a null client if the interface's CapabilityID isn't in the table.

func (CapTable) Len

func (ct CapTable) Len() int

Len returns the number of capabilities in the table.

func (*CapTable) Reset

func (ct *CapTable) Reset(cs ...Client)

Reset the cap table, releasing all capabilities and setting the length to zero. Clients passed as arguments are added to the table after zeroing, such that ct.Len() == len(cs).

func (CapTable) Set

func (ct CapTable) Set(id CapabilityID, c Client)

Set the client for the supplied capability ID. If a client for the given ID already exists, it will be replaced without releasing.

type CapabilityID

type CapabilityID uint32

A CapabilityID is an index into a message's capability table.

func (CapabilityID) GoString

func (id CapabilityID) GoString() string

GoString returns the ID as a Go expression.

func (CapabilityID) String

func (id CapabilityID) String() string

String returns the ID in the format "capability X".

type Client

type Client ClientKind

A Client is a reference to a Cap'n Proto capability. The zero value is a null capability reference. It is safe to use from multiple goroutines.

func ErrorClient

func ErrorClient(e error) Client

ErrorClient returns a Client that always returns error e. An ErrorClient does not need to be released: it is a sentinel like a nil Client.

The returned client's State() method returns a State with its Brand.Value set to e.

func NewClient

func NewClient(hook ClientHook) Client

NewClient creates the first reference to a capability. If hook is nil, then NewClient returns nil.

Typically the RPC system will create a client for the application. Most applications will not need to use this directly.

func (Client) AddRef

func (c Client) AddRef() Client

AddRef creates a new Client that refers to the same capability as c. If c is nil or has resolved to null, then AddRef returns nil.

func (Client) DecodeFromPtr

func (Client) DecodeFromPtr(p Ptr) Client

func (Client) EncodeAsPtr

func (c Client) EncodeAsPtr(seg *Segment) Ptr

func (Client) GetFlowLimiter

func (c Client) GetFlowLimiter() flowcontrol.FlowLimiter

Get the current flowcontrol.FlowLimiter used to manage flow control for this client.

func (Client) IsSame

func (c Client) IsSame(c2 Client) bool

IsSame reports whether c and c2 refer to a capability created by the same call to NewClient. This can return false negatives if c or c2 are not fully resolved: use Resolve if this is an issue. If either c or c2 are released, then IsSame panics.

func (Client) IsValid

func (c Client) IsValid() bool

IsValid reports whether c is a valid reference to a capability. A reference is invalid if it is nil, has resolved to null, or has been released.

func (Client) RecvCall

func (c Client) RecvCall(ctx context.Context, r Recv) PipelineCaller

RecvCall starts executing a method with the referenced arguments and returns an answer that will hold the result. The hook will call a.Release when it no longer needs to reference the parameters. The caller must call the returned release function when it no longer needs the answer's data.

Note that unlike SendCall, this method does *not* respect the flow control policy configured with SetFlowLimiter.

func (Client) Release

func (c Client) Release()

Release releases a capability reference. If this is the last reference to the capability, then the underlying resources associated with the capability will be released.

Release has no effect if c has already been released, or if c is nil or resolved to null.

func (Client) Resolve

func (c Client) Resolve(ctx context.Context) error

Resolve blocks until the capability is fully resolved or the Context is Done. Resolve only returns an error if the context is canceled; it returns nil even if the capability resolves to an error.

func (Client) SendCall

func (c Client) SendCall(ctx context.Context, s Send) (*Answer, ReleaseFunc)

SendCall allocates space for parameters, calls args.Place to fill out the parameters, then starts executing a method, returning an answer that will hold the result. The caller must call the returned release function when it no longer needs the answer's data.

This method respects the flow control policy configured with SetFlowLimiter; it may block if the sender is sending too fast.

func (Client) SendStreamCall

func (c Client) SendStreamCall(ctx context.Context, s Send) error

SendStreamCall is like SendCall except that:

  1. It does not return an answer for the eventual result.
  2. If the call returns an error, all future calls on this client will return the same error (without starting the method or calling PlaceArgs).

func (Client) SetFlowLimiter

func (c Client) SetFlowLimiter(lim flowcontrol.FlowLimiter)

Update the flowcontrol.FlowLimiter used to manage flow control for this client. This affects all future calls, but not calls already waiting to send. Passing nil sets the value to flowcontrol.NopLimiter, which is also the default.

When .Release() is called on the client, it will call .Release() on the FlowLimiter in turn.

func (Client) State

func (c Client) State() ClientState

State reads the current state of the client. It returns the zero ClientState if c is nil, has resolved to null, or has been released.

func (Client) String

func (c Client) String() string

String returns a string that identifies this capability for debugging purposes. Its format should not be depended on: in particular, it should not be used to compare clients. Use IsSame to compare clients for equality.

func (Client) WaitStreaming

func (c Client) WaitStreaming() error

WaitStreaming waits for all outstanding streaming calls (i.e. calls started with SendStreamCall) to complete, and then returns an error if any streaming call has failed.

func (Client) WeakRef

func (c Client) WeakRef() *WeakClient

WeakRef creates a new WeakClient that refers to the same capability as c. If c is nil or has resolved to null, then WeakRef returns nil.

type ClientHook

type ClientHook interface {
	// Send allocates space for parameters, calls s.PlaceArgs to fill out
	// the arguments, then starts executing a method, returning an answer
	// that will hold the result.  The hook must call s.PlaceArgs at most
	// once, and if it does call s.PlaceArgs, it must return before Send
	// returns.  The caller must call the returned release function when
	// it no longer needs the answer's data.
	//
	// Send is typically used when application code is making a call.
	Send(ctx context.Context, s Send) (*Answer, ReleaseFunc)

	// Recv starts executing a method with the referenced arguments
	// and places the result in a message controlled by the caller.
	// The hook will call r.ReleaseArgs when it no longer needs to
	// reference the parameters and use r.Returner to complete the method
	// call.  If Recv does not call r.Returner.Return before it returns,
	// then it must return a non-nil PipelineCaller.
	//
	// Recv is typically used when the RPC system has received a call.
	Recv(ctx context.Context, r Recv) PipelineCaller

	// Brand returns an implementation-specific value.  This can be used
	// to introspect and identify kinds of clients.
	Brand() Brand

	// Shutdown releases any resources associated with this capability.
	// The behavior of calling any methods on the receiver after calling
	// Shutdown is undefined.  It is expected for the ClientHook to reject
	// any outstanding call futures.
	Shutdown()

	// String formats the hook as a string (same as fmt.Stringer)
	String() string
}

A ClientHook represents a Cap'n Proto capability. Application code should not pass around ClientHooks; applications should pass around Clients. A ClientHook must be safe to use from multiple goroutines.

Calls must be delivered to the capability in the order they are made. This guarantee is based on the concept of a capability acknowledging delivery of a call: this is specific to an implementation of ClientHook. A type that implements ClientHook must guarantee that if foo() then bar() is called on a client, then the capability acknowledging foo() happens before the capability observing bar().

ClientHook is an internal interface. Users generally SHOULD NOT supply their own implementations.

type ClientKind

type ClientKind = struct {
	// contains filtered or unexported fields
}

The underlying type of Client. We expose this so that we can use ~ClientKind as a constraint in generics to capture any capability type.

type ClientState

type ClientState struct {
	// Brand is the value returned from the hook's Brand method.
	Brand Brand
	// IsPromise is true if the client has not resolved yet.
	IsPromise bool
	// Arbitrary metadata. Note that, if a Client is a promise,
	// when it resolves its metadata will be replaced with that
	// of its resolution.
	//
	// TODO: this might change before the v3 API is stabilized;
	// we are not sure the above is the correct semantics.
	Metadata *Metadata
}

ClientState is a snapshot of a client's identity.

type DataList

type DataList List

DataList is an array of pointers to data.

func NewDataList

func NewDataList(s *Segment, n int32) (DataList, error)

NewDataList allocates a new list of data pointers, preferring placement in s.

func (DataList) At

func (l DataList) At(i int) ([]byte, error)

At returns the i'th data in the list.

func (DataList) DecodeFromPtr

func (DataList) DecodeFromPtr(p Ptr) DataList

func (DataList) EncodeAsPtr

func (l DataList) EncodeAsPtr(seg *Segment) Ptr

func (DataList) IsValid

func (l DataList) IsValid() bool

func (DataList) Len

func (l DataList) Len() int

func (DataList) Message

func (l DataList) Message() *Message

func (DataList) Segment

func (l DataList) Segment() *Segment

func (DataList) Set

func (l DataList) Set(i int, v []byte) error

Set sets the i'th data in the list to v.

func (DataList) String

func (l DataList) String() string

String returns the list in Cap'n Proto schema format (e.g. `["foo", "bar"]`).

func (DataList) ToPtr

func (l DataList) ToPtr() Ptr

type DataOffset

type DataOffset uint32

DataOffset is an offset in bytes from the beginning of a struct's data section. It is bounded to [0, 1<<19).

func (DataOffset) GoString

func (off DataOffset) GoString() string

GoString returns the offset as a Go expression.

func (DataOffset) String

func (off DataOffset) String() string

String returns the offset in the format "+X bytes".

type Decoder

type Decoder struct {

	// Maximum number of bytes that can be read per call to Decode.
	// If not set, a reasonable default is used.
	MaxMessageSize uint64
	// contains filtered or unexported fields
}

A Decoder represents a framer that deserializes a particular Cap'n Proto input stream.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder creates a new Cap'n Proto framer that reads from r. The returned decoder will only read as much data as necessary to decode the message.

func NewPackedDecoder

func NewPackedDecoder(r io.Reader) *Decoder

NewPackedDecoder creates a new Cap'n Proto framer that reads from a packed stream r. The returned decoder may read more data than necessary from r.

func (*Decoder) Decode

func (d *Decoder) Decode() (*Message, error)

Decode reads a message from the decoder stream. The error is io.EOF only if no bytes were read.

type Encoder

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

An Encoder represents a framer for serializing a particular Cap'n Proto stream.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder creates a new Cap'n Proto framer that writes to w.

func NewPackedEncoder

func NewPackedEncoder(w io.Writer) *Encoder

NewPackedEncoder creates a new Cap'n Proto framer that writes to a packed stream w.

func (*Encoder) Encode

func (e *Encoder) Encode(m *Message) error

Encode writes a message to the encoder stream.

type EnumList

type EnumList[T ~uint16] UInt16List

A list of some Cap'n Proto enum type T.

func NewEnumList

func NewEnumList[T ~uint16](s *Segment, n int32) (EnumList[T], error)

NewEnumList creates a new list of T, preferring placement in s.

func (EnumList[T]) At

func (l EnumList[T]) At(i int) T

At returns the i'th element.

func (EnumList[T]) DecodeFromPtr

func (EnumList[T]) DecodeFromPtr(p Ptr) EnumList[T]

func (EnumList[T]) EncodeAsPtr

func (l EnumList[T]) EncodeAsPtr(seg *Segment) Ptr

func (EnumList[T]) IsValid

func (l EnumList[T]) IsValid() bool

func (EnumList[T]) Len

func (l EnumList[T]) Len() int

func (EnumList[T]) Message

func (l EnumList[T]) Message() *Message

func (EnumList[T]) Segment

func (l EnumList[T]) Segment() *Segment

func (EnumList[T]) Set

func (l EnumList[T]) Set(i int, v T)

Set sets the i'th element to v.

func (EnumList[T]) String

func (l EnumList[T]) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (EnumList[T]) ToPtr

func (l EnumList[T]) ToPtr() Ptr

type Float32List

type Float32List List

Float32List is an array of Float32 values.

func NewFloat32List

func NewFloat32List(s *Segment, n int32) (Float32List, error)

NewFloat32List creates a new list of Float32, preferring placement in s.

func (Float32List) At

func (l Float32List) At(i int) float32

At returns the i'th element.

func (Float32List) DecodeFromPtr

func (Float32List) DecodeFromPtr(p Ptr) Float32List

func (Float32List) EncodeAsPtr

func (l Float32List) EncodeAsPtr(seg *Segment) Ptr

func (Float32List) IsValid

func (l Float32List) IsValid() bool

func (Float32List) Len

func (l Float32List) Len() int

func (Float32List) Message

func (l Float32List) Message() *Message

func (Float32List) Segment

func (l Float32List) Segment() *Segment

func (Float32List) Set

func (l Float32List) Set(i int, v float32)

Set sets the i'th element to v.

func (Float32List) String

func (l Float32List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (Float32List) ToPtr

func (l Float32List) ToPtr() Ptr

type Float64List

type Float64List List

Float64List is an array of Float64 values.

func NewFloat64List

func NewFloat64List(s *Segment, n int32) (Float64List, error)

NewFloat64List creates a new list of Float64, preferring placement in s.

func (Float64List) At

func (l Float64List) At(i int) float64

At returns the i'th element.

func (Float64List) DecodeFromPtr

func (Float64List) DecodeFromPtr(p Ptr) Float64List

func (Float64List) EncodeAsPtr

func (l Float64List) EncodeAsPtr(seg *Segment) Ptr

func (Float64List) IsValid

func (l Float64List) IsValid() bool

func (Float64List) Len

func (l Float64List) Len() int

func (Float64List) Message

func (l Float64List) Message() *Message

func (Float64List) Segment

func (l Float64List) Segment() *Segment

func (Float64List) Set

func (l Float64List) Set(i int, v float64)

Set sets the i'th element to v.

func (Float64List) String

func (l Float64List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (Float64List) ToPtr

func (l Float64List) ToPtr() Ptr

type Future

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

A Future accesses a portion of an Answer. It is safe to use from multiple goroutines.

func (*Future) Client

func (f *Future) Client() Client

Client returns the future as a client. If the answer's originating call has not completed, then calls will be queued until the original call's completion. The client reference is borrowed: the caller should not call Release.

func (*Future) Done

func (f *Future) Done() <-chan struct{}

Done returns a channel that is closed when the answer's call is finished.

func (*Future) Field

func (f *Future) Field(off uint16, def []byte) *Future

Field returns a derived future which yields the pointer field given, defaulting to the value given.

func (*Future) List

func (f *Future) List() (List, error)

List waits until the answer is resolved and returns the list this answer represents.

func (*Future) Ptr

func (f *Future) Ptr() (Ptr, error)

Ptr waits until the answer is resolved and returns the pointer this future represents.

func (*Future) Struct

func (f *Future) Struct() (Struct, error)

Struct waits until the answer is resolved and returns the struct this answer represents.

type Int16List

type Int16List List

Int16List is an array of Int16 values.

func NewInt16List

func NewInt16List(s *Segment, n int32) (Int16List, error)

NewInt16List creates a new list of Int16, preferring placement in s.

func (Int16List) At

func (l Int16List) At(i int) int16

At returns the i'th element.

func (Int16List) DecodeFromPtr

func (Int16List) DecodeFromPtr(p Ptr) Int16List

func (Int16List) EncodeAsPtr

func (l Int16List) EncodeAsPtr(seg *Segment) Ptr

func (Int16List) IsValid

func (l Int16List) IsValid() bool

func (Int16List) Len

func (l Int16List) Len() int

func (Int16List) Message

func (l Int16List) Message() *Message

func (Int16List) Segment

func (l Int16List) Segment() *Segment

func (Int16List) Set

func (l Int16List) Set(i int, v int16)

Set sets the i'th element to v.

func (Int16List) String

func (l Int16List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (Int16List) ToPtr

func (l Int16List) ToPtr() Ptr

type Int32List

type Int32List List

Int32List is an array of Int32 values.

func NewInt32List

func NewInt32List(s *Segment, n int32) (Int32List, error)

NewInt32List creates a new list of Int32, preferring placement in s.

func (Int32List) At

func (l Int32List) At(i int) int32

At returns the i'th element.

func (Int32List) DecodeFromPtr

func (Int32List) DecodeFromPtr(p Ptr) Int32List

func (Int32List) EncodeAsPtr

func (l Int32List) EncodeAsPtr(seg *Segment) Ptr

func (Int32List) IsValid

func (l Int32List) IsValid() bool

func (Int32List) Len

func (l Int32List) Len() int

func (Int32List) Message

func (l Int32List) Message() *Message

func (Int32List) Segment

func (l Int32List) Segment() *Segment

func (Int32List) Set

func (l Int32List) Set(i int, v int32)

Set sets the i'th element to v.

func (Int32List) String

func (l Int32List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (Int32List) ToPtr

func (l Int32List) ToPtr() Ptr

type Int64List

type Int64List List

Int64List is an array of Int64 values.

func NewInt64List

func NewInt64List(s *Segment, n int32) (Int64List, error)

NewInt64List creates a new list of Int64, preferring placement in s.

func (Int64List) At

func (l Int64List) At(i int) int64

At returns the i'th element.

func (Int64List) DecodeFromPtr

func (Int64List) DecodeFromPtr(p Ptr) Int64List

func (Int64List) EncodeAsPtr

func (l Int64List) EncodeAsPtr(seg *Segment) Ptr

func (Int64List) IsValid

func (l Int64List) IsValid() bool

func (Int64List) Len

func (l Int64List) Len() int

func (Int64List) Message

func (l Int64List) Message() *Message

func (Int64List) Segment

func (l Int64List) Segment() *Segment

func (Int64List) Set

func (l Int64List) Set(i int, v int64)

Set sets the i'th element to v.

func (Int64List) String

func (l Int64List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (Int64List) ToPtr

func (l Int64List) ToPtr() Ptr

type Int8List

type Int8List List

Int8List is an array of Int8 values.

func NewInt8List

func NewInt8List(s *Segment, n int32) (Int8List, error)

NewInt8List creates a new list of Int8, preferring placement in s.

func (Int8List) At

func (l Int8List) At(i int) int8

At returns the i'th element.

func (Int8List) DecodeFromPtr

func (Int8List) DecodeFromPtr(p Ptr) Int8List

func (Int8List) EncodeAsPtr

func (l Int8List) EncodeAsPtr(seg *Segment) Ptr

func (Int8List) IsValid

func (l Int8List) IsValid() bool

func (Int8List) Len

func (l Int8List) Len() int

func (Int8List) Message

func (l Int8List) Message() *Message

func (Int8List) Segment

func (l Int8List) Segment() *Segment

func (Int8List) Set

func (l Int8List) Set(i int, v int8)

Set sets the i'th element to v.

func (Int8List) String

func (l Int8List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (Int8List) ToPtr

func (l Int8List) ToPtr() Ptr

type Interface

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

An Interface is a reference to a client in a message's capability table.

func NewInterface

func NewInterface(s *Segment, cap CapabilityID) Interface

NewInterface creates a new interface pointer.

No allocation is performed in the given segment: it is used purely to associate the interface pointer with a message.

func (Interface) Capability

func (i Interface) Capability() CapabilityID

Capability returns the capability ID of the interface.

func (Interface) Client

func (i Interface) Client() (c Client)

Client returns the client stored in the message's capability table or nil if the pointer is invalid.

func (Interface) DecodeFromPtr

func (Interface) DecodeFromPtr(p Ptr) Interface

DecodeFromPtr(p) is equivalent to p.Interface(); for implementing TypeParam.

func (Interface) EncodeAsPtr

func (i Interface) EncodeAsPtr(*Segment) Ptr

i.EncodeAsPtr is equivalent to i.ToPtr(); for implementing TypeParam. The segment argument is ignored.

func (Interface) IsValid

func (i Interface) IsValid() bool

IsValid returns whether the interface is valid.

func (Interface) Message

func (i Interface) Message() *Message

Message returns the message whose capability table the interface references or nil if the pointer is invalid.

func (Interface) ToPtr

func (i Interface) ToPtr() Ptr

ToPtr converts the interface to a generic pointer.

type List

type List ListKind

A List is a reference to an array of values.

func NewCompositeList

func NewCompositeList(s *Segment, sz ObjectSize, n int32) (List, error)

NewCompositeList creates a new composite list, preferring placement in s.

func (List) DecodeFromPtr

func (List) DecodeFromPtr(p Ptr) List

DecodeFromPtr(p) is equivalent to p.List; for implementing TypeParam.

func (List) EncodeAsPtr

func (l List) EncodeAsPtr(*Segment) Ptr

l.EncodeAsPtr is equivalent to l.ToPtr(); for implementing TypeParam. The segment argument is ignored.

func (List) IsValid

func (p List) IsValid() bool

IsValid returns whether the list is valid.

func (List) Len

func (p List) Len() int

Len returns the length of the list.

func (List) Message

func (p List) Message() *Message

Message returns the message the referenced list is stored in or nil if the pointer is invalid.

func (List) Segment

func (p List) Segment() *Segment

Segment returns the segment the referenced list is stored in or nil if the pointer is invalid.

func (List) SetStruct

func (p List) SetStruct(i int, s Struct) error

SetStruct set the i'th element to the value in s.

func (List) Struct

func (p List) Struct(i int) Struct

Struct returns the i'th element as a struct.

func (List) ToPtr

func (p List) ToPtr() Ptr

ToPtr converts the list to a generic pointer.

type ListKind

type ListKind = struct {
	// contains filtered or unexported fields
}

The underlying type of List. We expose this so that we can use ~ListKind as a constraint in generics to capture any list type.

type Message

type Message struct {
	Arena Arena

	// TraverseLimit limits how many total bytes of data are allowed to be
	// traversed while reading.  Traversal is counted when a Struct or
	// List is obtained.  This means that calling a getter for the same
	// sub-struct multiple times will cause it to be double-counted.  Once
	// the traversal limit is reached, pointer accessors will report
	// errors. See https://capnproto.org/encoding.html#amplification-attack
	// for more details on this security measure.
	//
	// If not set, this defaults to 64 MiB.
	TraverseLimit uint64

	// DepthLimit limits how deeply-nested a message structure can be.
	// If not set, this defaults to 64.
	DepthLimit uint
	// contains filtered or unexported fields
}

A Message is a tree of Cap'n Proto objects, split into one or more segments of contiguous memory. The only required field is Arena. A Message is safe to read from multiple goroutines.

func Unmarshal

func Unmarshal(data []byte) (*Message, error)

Unmarshal reads an unpacked serialized stream into a message. No copying is performed, so the objects in the returned message read directly from data.

Example
msg, s, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
	fmt.Printf("allocation error %v\n", err)
	return
}
d, err := air.NewRootZdate(s)
if err != nil {
	fmt.Printf("root error %v\n", err)
	return
}
d.SetYear(2004)
d.SetMonth(12)
d.SetDay(7)
data, err := msg.Marshal()
if err != nil {
	fmt.Printf("marshal error %v\n", err)
	return
}

// Read
msg, err = capnp.Unmarshal(data)
if err != nil {
	fmt.Printf("unmarshal error %v\n", err)
	return
}
d, err = air.ReadRootZdate(msg)
if err != nil {
	fmt.Printf("read root error %v\n", err)
	return
}
fmt.Printf("year %d, month %d, day %d\n", d.Year(), d.Month(), d.Day())
Output:

year 2004, month 12, day 7

func UnmarshalPacked

func UnmarshalPacked(data []byte) (*Message, error)

UnmarshalPacked reads a packed serialized stream into a message.

func (*Message) CapTable

func (m *Message) CapTable() *CapTable

CapTable is the indexed list of the clients referenced in the message. Capability pointers inside the message will use this table to map pointers to Clients. The table is populated by the RPC system.

https://capnproto.org/encoding.html#capabilities-interfaces

func (*Message) Marshal

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

Marshal concatenates the segments in the message into a single byte slice including framing.

func (*Message) MarshalPacked

func (m *Message) MarshalPacked() ([]byte, error)

MarshalPacked marshals the message in packed form.

func (*Message) NumSegments

func (m *Message) NumSegments() int64

NumSegments returns the number of segments in the message.

func (*Message) Release

func (m *Message) Release()

Release is syntactic sugar for Message.Reset(nil). See docstring for Reset for an important warning.

func (*Message) Reset

func (m *Message) Reset(arena Arena) (first *Segment, err error)

Reset the message to use a different arena, allowing it to be reused. This invalidates any existing pointers in the Message, releases all clients in the cap table, and releases the current Arena, so use with caution.

func (*Message) ResetReadLimit

func (m *Message) ResetReadLimit(limit uint64)

ResetReadLimit sets the number of bytes allowed to be read from this message.

func (*Message) Root

func (m *Message) Root() (Ptr, error)

Root returns the pointer to the message's root object.

func (*Message) Segment

func (m *Message) Segment(id SegmentID) (*Segment, error)

Segment returns the segment with the given ID.

func (*Message) SetRoot

func (m *Message) SetRoot(p Ptr) error

SetRoot sets the message's root object to p.

func (*Message) TotalSize

func (m *Message) TotalSize() (uint64, error)

Compute the total size of the message in bytes, when serialized as a stream. This is the same as the length of the slice returned by m.Marshal()

func (*Message) Unread

func (m *Message) Unread(sz Size)

Unread increases the read limit by sz.

func (*Message) WriteTo

func (m *Message) WriteTo(w io.Writer) (int64, error)

type Metadata

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

Metadata is a morally a map[any]any which implements sync.Locker; it is used by the rpc system to attach bookkeeping information to various objects.

The zero value is not meaningful, and the Metadata must not be copied after its first use.

func NewMetadata

func NewMetadata() *Metadata

Allocate and return a freshly initialized Metadata.

func (*Metadata) Delete

func (m *Metadata) Delete(key any)

Delete the key from the map.

func (*Metadata) Get

func (m *Metadata) Get(key any) (value any, ok bool)

Look up key in the map. Returns the value, and a boolean which is false if the key was not present.

func (*Metadata) Lock

func (m *Metadata) Lock()

Lock the metadata map.

func (*Metadata) Put

func (m *Metadata) Put(key, value any)

Insert the key, value pair into the map.

func (*Metadata) Unlock

func (m *Metadata) Unlock()

Unlock the metadata map.

type Method

type Method struct {
	InterfaceID uint64
	MethodID    uint16

	// Canonical name of the interface.  May be empty.
	InterfaceName string
	// Method name as it appears in the schema.  May be empty.
	MethodName string
}

A Method identifies a method along with an optional human-readable description of the method.

func (*Method) String

func (m *Method) String() string

String returns a formatted string containing the interface name or the method name if present, otherwise it uses the raw IDs. This is suitable for use in error messages and logs.

type MultiSegmentArena

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

MultiSegment is an arena that stores object data across multiple []byte buffers, allocating new buffers of exponentially-increasing size when full. This avoids the potentially-expensive slice copying of SingleSegment.

func MultiSegment

func MultiSegment(b [][]byte) *MultiSegmentArena

MultiSegment returns a new arena that allocates new segments when they are full. b MAY be nil. Callers MAY use b to populate the buffer for reading or to reserve memory of a specific size.

func (*MultiSegmentArena) Allocate

func (msa *MultiSegmentArena) Allocate(sz Size, segs map[SegmentID]*Segment) (SegmentID, []byte, error)

func (*MultiSegmentArena) Data

func (msa *MultiSegmentArena) Data(id SegmentID) ([]byte, error)

func (*MultiSegmentArena) NumSegments

func (msa *MultiSegmentArena) NumSegments() int64

func (*MultiSegmentArena) Release

func (msa *MultiSegmentArena) Release()

Return this arena to an internal sync.Pool of arenas that can be re-used. Any time MultiSegment(nil) is called, arenas from this pool will be used if available, which can help reduce memory allocations.

All segments will be zeroed before re-use.

Calling Release is optional; if not done the garbage collector will release the memory per usual.

func (*MultiSegmentArena) String

func (msa *MultiSegmentArena) String() string

type ObjectSize

type ObjectSize struct {
	DataSize     Size // must be <= 1<<19 - 8
	PointerCount uint16
}

ObjectSize records section sizes for a struct or list.

func (ObjectSize) GoString

func (sz ObjectSize) GoString() string

GoString formats the ObjectSize as a keyed struct literal.

func (ObjectSize) String

func (sz ObjectSize) String() string

String returns a short, human readable representation of the object size.

type PipelineCaller

type PipelineCaller interface {
	PipelineSend(ctx context.Context, transform []PipelineOp, s Send) (*Answer, ReleaseFunc)
	PipelineRecv(ctx context.Context, transform []PipelineOp, r Recv) PipelineCaller
}

A PipelineCaller implements promise pipelining.

See the counterpart methods in ClientHook for a description.

type PipelineClient

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

PipelineClient implements ClientHook by calling to the pipeline's answer.

func (PipelineClient) Answer

func (pc PipelineClient) Answer() *Answer

func (PipelineClient) Brand

func (pc PipelineClient) Brand() Brand

func (PipelineClient) Recv

func (PipelineClient) Send

func (pc PipelineClient) Send(ctx context.Context, s Send) (*Answer, ReleaseFunc)

func (PipelineClient) Shutdown

func (pc PipelineClient) Shutdown()

func (PipelineClient) String

func (pc PipelineClient) String() string

func (PipelineClient) Transform

func (pc PipelineClient) Transform() []PipelineOp

type PipelineOp

type PipelineOp struct {
	Field        uint16
	DefaultValue []byte
}

A PipelineOp describes a step in transforming a pipeline. It maps closely with the PromisedAnswer.Op struct in rpc.capnp.

func (PipelineOp) String

func (op PipelineOp) String() string

String returns a human-readable description of op.

type PointerList

type PointerList List

A PointerList is a reference to an array of pointers.

func NewPointerList

func NewPointerList(s *Segment, n int32) (PointerList, error)

NewPointerList allocates a new list of pointers, preferring placement in s.

func (PointerList) At

func (p PointerList) At(i int) (Ptr, error)

At returns the i'th pointer in the list.

func (PointerList) DecodeFromPtr

func (PointerList) DecodeFromPtr(p Ptr) PointerList

func (PointerList) EncodeAsPtr

func (l PointerList) EncodeAsPtr(seg *Segment) Ptr

func (PointerList) IsValid

func (l PointerList) IsValid() bool

func (PointerList) Len

func (l PointerList) Len() int

func (PointerList) Message

func (l PointerList) Message() *Message

func (PointerList) Segment

func (l PointerList) Segment() *Segment

func (PointerList) Set

func (p PointerList) Set(i int, v Ptr) error

Set sets the i'th pointer in the list to v.

func (PointerList) ToPtr

func (l PointerList) ToPtr() Ptr

type Promise

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

A Promise holds the result of an RPC call. Only one of Fulfill or Reject can be called on a Promise. Before the result is written, calls can be queued up using the Answer methods — this is promise pipelining.

Promise is most useful for implementing ClientHook. Most applications will use Answer, since that what is returned by a Client.

func NewPromise

func NewPromise(m Method, pc PipelineCaller) *Promise

NewPromise creates a new unresolved promise. The PipelineCaller will be used to make pipelined calls before the promise resolves.

func (*Promise) Answer

func (p *Promise) Answer() *Answer

Answer returns a read-only view of the promise. Answer may be called concurrently by multiple goroutines.

func (*Promise) Fulfill

func (p *Promise) Fulfill(result Ptr)

Fulfill resolves the promise with a successful result.

Fulfill will wait for any outstanding calls to the underlying PipelineCaller to yield Answers and any pipelined clients to be fulfilled.

func (*Promise) Reject

func (p *Promise) Reject(e error)

Reject resolves the promise with a failure.

Reject will wait for any outstanding calls to the underlying PipelineCaller to yield Answers and any pipelined clients to be fulfilled.

func (*Promise) ReleaseClients

func (p *Promise) ReleaseClients()

ReleaseClients waits until p is resolved and then closes any proxy clients created by the promise's answer. Failure to call this method will result in capability leaks. After the first call, subsequent calls to ReleaseClients do nothing. It is safe to call ReleaseClients concurrently from multiple goroutines.

This method is typically used in a ReleaseFunc.

func (*Promise) Resolve

func (p *Promise) Resolve(r Ptr, e error)

Resolve resolves the promise.

If e != nil, then this is equivalent to p.Reject(e). Otherwise, it is equivalent to p.Fulfill(r).

type Ptr

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

A Ptr is a reference to a Cap'n Proto struct, list, or interface. The zero value is a null pointer.

func MustUnmarshalRoot

func MustUnmarshalRoot(data []byte) Ptr

MustUnmarshalRoot reads an unpacked serialized stream and returns its root pointer. If there is any error, it panics.

func Transform

func Transform(p Ptr, transform []PipelineOp) (Ptr, error)

Transform applies a sequence of pipeline operations to a pointer and returns the result.

func (Ptr) Data

func (p Ptr) Data() []byte

Data attempts to convert p into Data, returning nil if p is not a valid 1-byte list pointer.

func (Ptr) DataDefault

func (p Ptr) DataDefault(def []byte) []byte

DataDefault attempts to convert p into Data, returning def if p is not a valid 1-byte list pointer.

func (Ptr) DecodeFromPtr

func (Ptr) DecodeFromPtr(p Ptr) Ptr

DecodeFromPtr returns its argument; for implementing TypeParam.

func (Ptr) Default

func (p Ptr) Default(def []byte) (Ptr, error)

Default returns p if it is valid, otherwise it unmarshals def.

func (Ptr) EncodeAsPtr

func (p Ptr) EncodeAsPtr(*Segment) Ptr

EncodeAsPtr returns the receiver; for implementing TypeParam. The segment argument is ignored.

func (Ptr) Interface

func (p Ptr) Interface() Interface

Interface converts p to an Interface. If p does not hold a List pointer, the zero value is returned.

func (Ptr) IsValid

func (p Ptr) IsValid() bool

IsValid reports whether p is valid.

func (Ptr) List

func (p Ptr) List() List

List converts p to a List. If p does not hold a List pointer, the zero value is returned.

func (Ptr) ListDefault

func (p Ptr) ListDefault(def []byte) (List, error)

ListDefault attempts to convert p into a list, reading the default value from def if p is not a list.

func (Ptr) Message

func (p Ptr) Message() *Message

Message returns the message the referenced data is stored in or nil if the pointer is invalid.

func (Ptr) Segment

func (p Ptr) Segment() *Segment

Segment returns the segment that the referenced data is stored in or nil if the pointer is invalid.

func (Ptr) Struct

func (p Ptr) Struct() Struct

Struct converts p to a Struct. If p does not hold a Struct pointer, the zero value is returned.

func (Ptr) StructDefault

func (p Ptr) StructDefault(def []byte) (Struct, error)

StructDefault attempts to convert p into a struct, reading the default value from def if p is not a struct.

func (Ptr) Text

func (p Ptr) Text() string

Text attempts to convert p into Text, returning an empty string if p is not a valid 1-byte list pointer.

func (Ptr) TextBytes

func (p Ptr) TextBytes() []byte

TextBytes attempts to convert p into Text, returning nil if p is not a valid 1-byte list pointer. It returns a slice directly into the segment.

func (Ptr) TextBytesDefault

func (p Ptr) TextBytesDefault(def string) []byte

TextBytesDefault attempts to convert p into Text, returning def if p is not a valid 1-byte list pointer. It returns a slice directly into the segment.

func (Ptr) TextDefault

func (p Ptr) TextDefault(def string) string

TextDefault attempts to convert p into Text, returning def if p is not a valid 1-byte list pointer.

type Recv

type Recv struct {
	// Method must have InterfaceID and MethodID filled in.
	Method Method

	// Args is the set of arguments for the RPC.
	Args Struct

	// ReleaseArgs is called after Args is no longer referenced.
	// Must not be nil. If called more than once, subsequent calls
	// must silently no-op.
	ReleaseArgs ReleaseFunc

	// Returner manages the results.
	Returner Returner
}

Recv is the input to ClientHook.Recv.

func (Recv) AllocResults

func (r Recv) AllocResults(sz ObjectSize) (Struct, error)

AllocResults allocates a result struct. It is the same as calling r.Returner.AllocResults(sz).

func (Recv) Reject

func (r Recv) Reject(e error)

Reject ends the method call with an error, releasing the arguments.

func (Recv) Return

func (r Recv) Return()

Return ends the method call successfully, releasing the arguments.

type ReleaseFunc

type ReleaseFunc func()

A ReleaseFunc tells the RPC system that a parameter or result struct is no longer in use and may be reclaimed. After the first call, subsequent calls to a ReleaseFunc do nothing. A ReleaseFunc should not be called concurrently.

type Request

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

A Request is a method call to be sent. Create one with NewReqeust, and send it with Request.Send().

func NewRequest

func NewRequest(client Client, method Method, argsSize ObjectSize) (*Request, error)

NewRequest creates a new request calling the specified method on the specified client. argsSize is the size of the arguments struct.

func (*Request) Args

func (r *Request) Args() Struct

Args returns the arguments struct for this request. The arguments must not be accessed after the request is sent.

func (*Request) Future

func (r *Request) Future() *Future

Future returns a future for the requests results. Returns nil if called before the request is sent.

func (*Request) Release

func (r *Request) Release()

Release resources associated with the request. In particular:

  • Release the arguments if they have not yet been released.
  • If the request has been sent, wait for the result and release the results.

func (*Request) Send

func (r *Request) Send(ctx context.Context) *Future

Send sends the request, returning a future for its results.

func (*Request) SendStream

func (r *Request) SendStream(ctx context.Context) error

SendStream is to send as Client.SendStreamCall is to Client.SendCall

type Resolver

type Resolver[T any] interface {
	// Fulfill supplies the value for the corresponding
	// Promise
	Fulfill(T)

	// Reject rejects the corresponding promise, with
	// the specified error.
	Reject(error)
}

A Resolver supplies a value for a pending promise.

func NewLocalPromise

func NewLocalPromise[C ~ClientKind]() (C, Resolver[C])

NewLocalPromise returns a client that will eventually resolve to a capability, supplied via the fulfiller.

type Returner

type Returner interface {
	// AllocResults allocates the results struct that will be sent using
	// Return.  It can be called at most once, and only before calling
	// Return.  The struct returned by AllocResults must not be mutated
	// after Return is called, and may not be accessed after
	// ReleaseResults is called.
	AllocResults(sz ObjectSize) (Struct, error)

	// PrepareReturn finalizes the return message. The method call will
	// resolve successfully if e is nil, or otherwise it will return an
	// exception to the caller.
	//
	// PrepareReturn must be called once.
	//
	// After PrepareReturn is invoked, no goroutine may modify the message
	// containing the results.
	PrepareReturn(e error)

	// Return resolves the method call, using the results finalized in
	// PrepareReturn. Return must be called once.
	//
	// Return must wait for all ongoing pipelined calls to be delivered,
	// and after it returns, no new calls can be sent to the PipelineCaller
	// returned from Recv.
	Return()

	// ReleaseResults relinquishes the caller's access to the message
	// containing the results; once this is called the message may be
	// released or reused, and it is not safe to access.
	//
	// If AllocResults has not been called, then this is a no-op.
	ReleaseResults()
}

A Returner allocates and sends the results from a received capability method call.

type Segment

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

A Segment is an allocation arena for Cap'n Proto objects. It is part of a Message, which can contain other segments that reference each other.

func (*Segment) Data

func (s *Segment) Data() []byte

Data returns the raw byte slice for the segment.

func (*Segment) ID

func (s *Segment) ID() SegmentID

ID returns the segment's ID.

func (*Segment) Message

func (s *Segment) Message() *Message

Message returns the message that contains s.

type SegmentID

type SegmentID uint32

A SegmentID is a numeric identifier for a Segment.

type Send

type Send struct {
	// Method must have InterfaceID and MethodID filled in.
	Method Method

	// PlaceArgs is a function that will be called at most once before Send
	// returns to populate the arguments for the RPC.  PlaceArgs may be nil.
	PlaceArgs func(Struct) error

	// ArgsSize specifies the size of the struct to pass to PlaceArgs.
	ArgsSize ObjectSize
}

Send is the input to ClientHook.Send.

type SingleSegmentArena

type SingleSegmentArena []byte

SingleSegmentArena is an Arena implementation that stores message data in a continguous slice. Allocation is performed by first allocating a new slice and copying existing data. SingleSegment arena does not fail unless the caller attempts to access another segment.

func SingleSegment

func SingleSegment(b []byte) *SingleSegmentArena

SingleSegment constructs a SingleSegmentArena from b. b MAY be nil. Callers MAY use b to populate the segment for reading, or to reserve memory of a specific size.

func (*SingleSegmentArena) Allocate

func (ssa *SingleSegmentArena) Allocate(sz Size, segs map[SegmentID]*Segment) (SegmentID, []byte, error)

func (SingleSegmentArena) Data

func (ssa SingleSegmentArena) Data(id SegmentID) ([]byte, error)

func (SingleSegmentArena) NumSegments

func (ssa SingleSegmentArena) NumSegments() int64

func (*SingleSegmentArena) Release

func (ssa *SingleSegmentArena) Release()

Return this arena to an internal sync.Pool of arenas that can be re-used. Any time SingleSegment(nil) is called, arenas from this pool will be used if available, which can help reduce memory allocations.

All segments will be zeroed before re-use.

Calling Release is optional; if not done the garbage collector will release the memory per usual.

func (SingleSegmentArena) String

func (ssa SingleSegmentArena) String() string

type Size

type Size uint32

A Size is a size (in bytes).

func (Size) GoString

func (sz Size) GoString() string

GoString returns the size as a Go expression.

func (Size) String

func (sz Size) String() string

String returns the size in the format "X bytes".

type Struct

type Struct StructKind

Struct is a pointer to a struct.

func NewRootStruct

func NewRootStruct(s *Segment, sz ObjectSize) (Struct, error)

NewRootStruct creates a new struct, preferring placement in s, then sets the message's root to the new struct.

func NewStruct

func NewStruct(s *Segment, sz ObjectSize) (Struct, error)

NewStruct creates a new struct, preferring placement in s.

func (Struct) Bit

func (p Struct) Bit(n BitOffset) bool

Bit returns the bit that is n bits from the start of the struct.

func (Struct) CopyFrom

func (p Struct) CopyFrom(other Struct) error

CopyFrom copies content from another struct. If the other struct's sections are larger than this struct's, the extra data is not copied, meaning there is a risk of data loss when copying from messages built with future versions of the protocol.

func (Struct) DecodeFromPtr

func (Struct) DecodeFromPtr(p Ptr) Struct

DecodeFromPtr(p) is equivalent to p.Struct() (the receiver is ignored). for implementing TypeParam.

func (Struct) EncodeAsPtr

func (s Struct) EncodeAsPtr(*Segment) Ptr

s.EncodeAsPtr is equivalent to s.ToPtr(); for implementing TypeParam. The segment argument is ignored.

func (Struct) HasPtr

func (p Struct) HasPtr(i uint16) bool

HasPtr reports whether the i'th pointer in the struct is non-null. It does not affect the read limit.

func (Struct) IsValid

func (p Struct) IsValid() bool

IsValid returns whether the struct is valid.

func (Struct) Message

func (p Struct) Message() *Message

Message returns the message the referenced struct is stored in or nil if the pointer is invalid.

func (Struct) Ptr

func (p Struct) Ptr(i uint16) (Ptr, error)

Ptr returns the i'th pointer in the struct.

func (Struct) Segment

func (p Struct) Segment() *Segment

Segment returns the segment the referenced struct is stored in or nil if the pointer is invalid.

func (Struct) SetBit

func (p Struct) SetBit(n BitOffset, v bool)

SetBit sets the bit that is n bits from the start of the struct to v.

func (Struct) SetData

func (p Struct) SetData(i uint16, v []byte) error

SetData sets the i'th pointer to a newly allocated data or null if v is nil.

func (Struct) SetNewText

func (p Struct) SetNewText(i uint16, v string) error

SetNewText sets the i'th pointer to a newly allocated text.

func (Struct) SetPtr

func (p Struct) SetPtr(i uint16, src Ptr) error

SetPtr sets the i'th pointer in the struct to src.

func (Struct) SetText

func (p Struct) SetText(i uint16, v string) error

SetText sets the i'th pointer to a newly allocated text or null if v is empty.

func (Struct) SetTextFromBytes

func (p Struct) SetTextFromBytes(i uint16, v []byte) error

SetTextFromBytes sets the i'th pointer to a newly allocated text or null if v is nil.

func (Struct) SetUint16

func (p Struct) SetUint16(off DataOffset, v uint16)

SetUint16 sets the 16-bit integer that is off bytes from the start of the struct to v.

func (Struct) SetUint32

func (p Struct) SetUint32(off DataOffset, v uint32)

SetUint32 sets the 32-bit integer that is off bytes from the start of the struct to v.

func (Struct) SetUint64

func (p Struct) SetUint64(off DataOffset, v uint64)

SetUint64 sets the 64-bit integer that is off bytes from the start of the struct to v.

func (Struct) SetUint8

func (p Struct) SetUint8(off DataOffset, v uint8)

SetUint8 sets the 8-bit integer that is off bytes from the start of the struct to v.

func (Struct) Size

func (p Struct) Size() ObjectSize

Size returns the size of the struct.

func (Struct) ToPtr

func (p Struct) ToPtr() Ptr

ToPtr converts the struct to a generic pointer.

func (Struct) Uint16

func (p Struct) Uint16(off DataOffset) uint16

Uint16 returns a 16-bit integer from the struct's data section.

func (Struct) Uint32

func (p Struct) Uint32(off DataOffset) uint32

Uint32 returns a 32-bit integer from the struct's data section.

func (Struct) Uint64

func (p Struct) Uint64(off DataOffset) uint64

Uint64 returns a 64-bit integer from the struct's data section.

func (Struct) Uint8

func (p Struct) Uint8(off DataOffset) uint8

Uint8 returns an 8-bit integer from the struct's data section.

type StructKind

type StructKind = struct {
	// contains filtered or unexported fields
}

The underlying type of Struct. We expose this so that we can use ~StructKind as a constraint in generics to capture any struct type.

type StructList

type StructList[T ~StructKind] List

A list of some Cap'n Proto struct type T.

func (StructList[T]) At

func (s StructList[T]) At(i int) T

At returns the i'th element.

func (StructList[T]) DecodeFromPtr

func (StructList[T]) DecodeFromPtr(p Ptr) StructList[T]

func (StructList[T]) EncodeAsPtr

func (l StructList[T]) EncodeAsPtr(seg *Segment) Ptr

func (StructList[T]) IsValid

func (l StructList[T]) IsValid() bool

func (StructList[T]) Len

func (l StructList[T]) Len() int

func (StructList[T]) Message

func (l StructList[T]) Message() *Message

func (StructList[T]) Segment

func (l StructList[T]) Segment() *Segment

func (StructList[T]) Set

func (s StructList[T]) Set(i int, v T) error

Set sets the i'th element to v.

func (StructList[T]) ToPtr

func (l StructList[T]) ToPtr() Ptr

type StructReturner

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

A StructReturner implements Returner by allocating an in-memory message. It is safe to use from multiple goroutines. The zero value is a Returner in its initial state.

func (*StructReturner) AllocResults

func (sr *StructReturner) AllocResults(sz ObjectSize) (Struct, error)

func (*StructReturner) Answer

func (sr *StructReturner) Answer(m Method, pcall PipelineCaller) (*Answer, ReleaseFunc)

Answer returns an Answer that will be resolved when Return is called. answer must only be called once per StructReturner.

func (*StructReturner) PrepareReturn

func (sr *StructReturner) PrepareReturn(e error)

func (*StructReturner) ReleaseResults

func (sr *StructReturner) ReleaseResults()

func (*StructReturner) Return

func (sr *StructReturner) Return()

type TextList

type TextList List

TextList is an array of pointers to strings.

func NewTextList

func NewTextList(s *Segment, n int32) (TextList, error)

NewTextList allocates a new list of text pointers, preferring placement in s.

func (TextList) At

func (l TextList) At(i int) (string, error)

At returns the i'th string in the list.

func (TextList) BytesAt

func (l TextList) BytesAt(i int) ([]byte, error)

BytesAt returns the i'th element in the list as a byte slice. The underlying array of the slice is the segment data.

func (TextList) DecodeFromPtr

func (TextList) DecodeFromPtr(p Ptr) TextList

func (TextList) EncodeAsPtr

func (l TextList) EncodeAsPtr(seg *Segment) Ptr

func (TextList) IsValid

func (l TextList) IsValid() bool

func (TextList) Len

func (l TextList) Len() int

func (TextList) Message

func (l TextList) Message() *Message

func (TextList) Segment

func (l TextList) Segment() *Segment

func (TextList) Set

func (l TextList) Set(i int, v string) error

Set sets the i'th string in the list to v.

func (TextList) String

func (l TextList) String() string

String returns the list in Cap'n Proto schema format (e.g. `["foo", "bar"]`).

func (TextList) ToPtr

func (l TextList) ToPtr() Ptr

type TypeParam

type TypeParam[T any] interface {
	// Convert the receiver to a Ptr, storing it in seg if it is not
	// already associated with some message (only true for Clients and
	// wrappers around them.
	EncodeAsPtr(seg *Segment) Ptr

	// Decode the pointer as the type of the receiver. Generally,
	// the receiver will be the zero value for the type.
	DecodeFromPtr(p Ptr) T
}

The TypeParam interface must be satisified by a type to be used as a capnproto type parameter. This is satisified by all capnproto pointer types. T should be instantiated by the type itself; in type parameter lists you will typically see parameter/constraints like T TypeParam[T].

type UInt16List

type UInt16List List

A UInt16List is an array of UInt16 values.

func NewUInt16List

func NewUInt16List(s *Segment, n int32) (UInt16List, error)

NewUInt16List creates a new list of UInt16, preferring placement in s.

func (UInt16List) At

func (l UInt16List) At(i int) uint16

At returns the i'th element.

func (UInt16List) DecodeFromPtr

func (UInt16List) DecodeFromPtr(p Ptr) UInt16List

func (UInt16List) EncodeAsPtr

func (l UInt16List) EncodeAsPtr(seg *Segment) Ptr

func (UInt16List) IsValid

func (l UInt16List) IsValid() bool

func (UInt16List) Len

func (l UInt16List) Len() int

func (UInt16List) Message

func (l UInt16List) Message() *Message

func (UInt16List) Segment

func (l UInt16List) Segment() *Segment

func (UInt16List) Set

func (l UInt16List) Set(i int, v uint16)

Set sets the i'th element to v.

func (UInt16List) String

func (l UInt16List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (UInt16List) ToPtr

func (l UInt16List) ToPtr() Ptr

type UInt32List

type UInt32List List

UInt32List is an array of UInt32 values.

func NewUInt32List

func NewUInt32List(s *Segment, n int32) (UInt32List, error)

NewUInt32List creates a new list of UInt32, preferring placement in s.

func (UInt32List) At

func (l UInt32List) At(i int) uint32

At returns the i'th element.

func (UInt32List) DecodeFromPtr

func (UInt32List) DecodeFromPtr(p Ptr) UInt32List

func (UInt32List) EncodeAsPtr

func (l UInt32List) EncodeAsPtr(seg *Segment) Ptr

func (UInt32List) IsValid

func (l UInt32List) IsValid() bool

func (UInt32List) Len

func (l UInt32List) Len() int

func (UInt32List) Message

func (l UInt32List) Message() *Message

func (UInt32List) Segment

func (l UInt32List) Segment() *Segment

func (UInt32List) Set

func (l UInt32List) Set(i int, v uint32)

Set sets the i'th element to v.

func (UInt32List) String

func (l UInt32List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (UInt32List) ToPtr

func (l UInt32List) ToPtr() Ptr

type UInt64List

type UInt64List List

UInt64List is an array of UInt64 values.

func NewUInt64List

func NewUInt64List(s *Segment, n int32) (UInt64List, error)

NewUInt64List creates a new list of UInt64, preferring placement in s.

func (UInt64List) At

func (l UInt64List) At(i int) uint64

At returns the i'th element.

func (UInt64List) DecodeFromPtr

func (UInt64List) DecodeFromPtr(p Ptr) UInt64List

func (UInt64List) EncodeAsPtr

func (l UInt64List) EncodeAsPtr(seg *Segment) Ptr

func (UInt64List) IsValid

func (l UInt64List) IsValid() bool

func (UInt64List) Len

func (l UInt64List) Len() int

func (UInt64List) Message

func (l UInt64List) Message() *Message

func (UInt64List) Segment

func (l UInt64List) Segment() *Segment

func (UInt64List) Set

func (l UInt64List) Set(i int, v uint64)

Set sets the i'th element to v.

func (UInt64List) String

func (l UInt64List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (UInt64List) ToPtr

func (l UInt64List) ToPtr() Ptr

type UInt8List

type UInt8List List

A UInt8List is an array of UInt8 values.

func NewData

func NewData(s *Segment, v []byte) (UInt8List, error)

NewData creates a new list of UInt8 from a byte slice.

func NewText

func NewText(s *Segment, v string) (UInt8List, error)

NewText creates a new list of UInt8 from a string.

func NewTextFromBytes

func NewTextFromBytes(s *Segment, v []byte) (UInt8List, error)

NewTextFromBytes creates a NUL-terminated list of UInt8 from a byte slice.

func NewUInt8List

func NewUInt8List(s *Segment, n int32) (UInt8List, error)

NewUInt8List creates a new list of UInt8, preferring placement in s.

func (UInt8List) At

func (l UInt8List) At(i int) uint8

At returns the i'th element.

func (UInt8List) DecodeFromPtr

func (UInt8List) DecodeFromPtr(p Ptr) UInt8List

func (UInt8List) EncodeAsPtr

func (l UInt8List) EncodeAsPtr(seg *Segment) Ptr

func (UInt8List) IsValid

func (l UInt8List) IsValid() bool

func (UInt8List) Len

func (l UInt8List) Len() int

func (UInt8List) Message

func (l UInt8List) Message() *Message

func (UInt8List) Segment

func (l UInt8List) Segment() *Segment

func (UInt8List) Set

func (l UInt8List) Set(i int, v uint8)

Set sets the i'th element to v.

func (UInt8List) String

func (l UInt8List) String() string

String returns the list in Cap'n Proto schema format (e.g. "[1, 2, 3]").

func (UInt8List) ToPtr

func (l UInt8List) ToPtr() Ptr

type VoidList

type VoidList List

A VoidList is a list of zero-sized elements.

func NewVoidList

func NewVoidList(s *Segment, n int32) VoidList

NewVoidList creates a list of voids. No allocation is performed; s is only used for Segment()'s return value.

func (VoidList) DecodeFromPtr

func (VoidList) DecodeFromPtr(p Ptr) VoidList

func (VoidList) EncodeAsPtr

func (l VoidList) EncodeAsPtr(seg *Segment) Ptr

func (VoidList) IsValid

func (l VoidList) IsValid() bool

func (VoidList) Len

func (l VoidList) Len() int

func (VoidList) Message

func (l VoidList) Message() *Message

func (VoidList) Segment

func (l VoidList) Segment() *Segment

func (VoidList) String

func (l VoidList) String() string

String returns the list in Cap'n Proto schema format (e.g. "[void, void, void]").

func (VoidList) ToPtr

func (l VoidList) ToPtr() Ptr

type WeakClient

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

A WeakClient is a weak reference to a capability: it refers to a capability without preventing it from being shut down. The zero value is a null reference.

func (*WeakClient) AddRef

func (wc *WeakClient) AddRef() (c Client, ok bool)

AddRef creates a new Client that refers to the same capability as c as long as the capability hasn't already been shut down.

Directories

Path Synopsis
capnpc-go is the Cap'n proto code generator for Go.
capnpc-go is the Cap'n proto code generator for Go.
encoding
text
Package text supports marshaling Cap'n Proto messages as text based on a schema.
Package text supports marshaling Cap'n Proto messages as text based on a schema.
Package exc provides an error type for capnp exceptions.
Package exc provides an error type for capnp exceptions.
exp
bufferpool
Package bufferpool supports object pooling for byte buffers.
Package bufferpool supports object pooling for byte buffers.
clock
Package clock provides an interface for clocks.
Package clock provides an interface for clocks.
mpsc
Package mpsc implements a multiple-producer, single-consumer queue.
Package mpsc implements a multiple-producer, single-consumer queue.
spsc
Package spsc implements a single-producer, single-consumer queue.
Package spsc implements a single-producer, single-consumer queue.
Package flowcontrol provides support code for per-object flow control.
Package flowcontrol provides support code for per-object flow control.
bbr
package bbr implements the BBR congestion control algorithm, as described in:
package bbr implements the BBR congestion control algorithm, as described in:
internal/test-tool
test-tool is a useful command line tool for testing flow limiters.
test-tool is a useful command line tool for testing flow limiters.
tracing
Package tracing implements support for tracing the behavior of a FlowLimiter.
Package tracing implements support for tracing the behavior of a FlowLimiter.
internal
capnptool
Package capnptool provides an API for calling the capnp tool in tests.
Package capnptool provides an API for calling the capnp tool in tests.
demo
Package demo contains example tests.
Package demo contains example tests.
gen
This program generates some repetative method implementations for the many types of list capnp provides.
This program generates some repetative method implementations for the many types of list capnp provides.
nodemap
Package nodemap provides a schema registry index type.
Package nodemap provides a schema registry index type.
rc
str
Helpers for formatting strings.
Helpers for formatting strings.
strquote
Package strquote provides a function for formatting a string as a Cap'n Proto string literal.
Package strquote provides a function for formatting a string as a Cap'n Proto string literal.
syncutil
misc.
misc.
Package packed provides functions to read and write the "packed" compression scheme described at https://capnproto.org/encoding.html#packing.
Package packed provides functions to read and write the "packed" compression scheme described at https://capnproto.org/encoding.html#packing.
Package pogs provides functions to convert Cap'n Proto messages to and from Go structs.
Package pogs provides functions to convert Cap'n Proto messages to and from Go structs.
rpc
Package rpc implements the Cap'n Proto RPC protocol.
Package rpc implements the Cap'n Proto RPC protocol.
internal/testnetwork
Package testnetwork provides an in-memory implementation of rpc.Network for testing purposes.
Package testnetwork provides an in-memory implementation of rpc.Network for testing purposes.
transport
Package transport defines an interface for sending and receiving rpc messages.
Package transport defines an interface for sending and receiving rpc messages.
Package schemas provides a container for Cap'n Proto reflection data.
Package schemas provides a container for Cap'n Proto reflection data.
Package server provides runtime support for implementing Cap'n Proto interfaces locally.
Package server provides runtime support for implementing Cap'n Proto interfaces locally.
std
go

Jump to

Keyboard shortcuts

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