Skip to main content

FieldType

Trait FieldType 

Source
pub trait FieldType {
    // Required methods
    fn ty(&self) -> Type;
    fn read<'a>(&self, any: Reader<'a>) -> Result<Reader<'a>>;
    fn init<'a>(&self, any: Builder<'a>, len: u32) -> Result<Builder<'a>>;
}
Expand description

Declares what an AnyPointer field really holds, so it encodes and decodes as if the schema had said so.

An AnyPointer carries no type information — Cap’n Proto pointers are deliberately schema-external, and a struct pointer records its size but not which struct it is. So the type cannot be recovered from the message and has to be supplied from outside; that is all this trait does.

You do not normally name this trait. Codec::with_anypointer_field_as takes the type as a parameter and builds the implementation for you:

use capnp_json::Codec;

// `field` is `Value.anyPointer`, which here always holds a `node`.
let codec = Codec::new()
  .with_anypointer_field_as::<capnp::schema_capnp::node::Owned>(field);

Once declared, the field takes exactly the same path as a field the schema declares with that type: the mapped type’s own $Json.* annotations apply, as do any FieldCodecs registered for the types within it. Nothing about the JSON representation is invented here — use a FieldCodec for that.

§Lifetimes

read and init are generic over 'a rather than taking Reader<'_>, because what they return borrows from the message, not from the FieldType. Written with an elided lifetime, &self would capture the output under Rust’s elision rules and the result would not outlive the registration.

Required Methods§

Source

fn ty(&self) -> Type

The type the field is to be treated as, from T::introspect().

This is what the decoder dispatches on in place of the field’s declared type, which is how the mapped field reaches the same code a declared field of this type would.

Source

fn read<'a>(&self, any: Reader<'a>) -> Result<Reader<'a>>

Read the pointer as this type, during encoding.

Source

fn init<'a>(&self, any: Builder<'a>, len: u32) -> Result<Builder<'a>>

Initialise the pointer as this type, during decoding.

len is the element count the JSON implies — an array’s length, a string’s length in bytes — and is ignored for struct types, which take their size from the schema. The returned builder writes through to the pointer, so decoding into it populates the message.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§