triton_vm::prelude

Derive Macro BFieldCodec

Source
#[derive(BFieldCodec)]
{
    // Attributes available to this derive:
    #[bfield_codec]
}
Expand description

Derives BFieldCodec for structs and enums.

Fields that should not be serialized can be ignored by annotating them with #[bfield_codec(ignore)]. Ignored fields must implement [Default].

For enums, the discriminant used for serialization can be accessed through method bfield_codec_discriminant.

§Example

#[derive(BFieldCodec)]
struct Foo {
   bar: u64,
   #[bfield_codec(ignore)]
   ignored: usize,
}
let foo = Foo { bar: 42, ignored: 7 };
let encoded = foo.encode();
let decoded = Foo::decode(&encoded).unwrap();
assert_eq!(foo.bar, decoded.bar);

Accessing the discriminant of an enum’s variant:

#[derive(BFieldCodec)]
enum Bar {
    Baz,
    Qux(u64),
}
let _discriminant = Bar::Baz.bfield_codec_discriminant();

§Known limitations

  • Enums whith variants that have named fields are currently not supported. Example:

    #[derive(BFieldCodec)]  // Currently not supported.
    enum Foo {
      Bar { baz: u64 },
    }
  • Enums with no variants are currently not supported. Consider using a unit struct instead. Example:

    #[derive(BFieldCodec)]  // Currently not supported.
    enum Foo {}             // Consider `struct Foo;` instead.