DecodeAsType

Derive Macro DecodeAsType 

Source
#[derive(DecodeAsType)]
{
    // Attributes available to this derive:
    #[decode_as_type]
    #[codec]
}
Expand description

The DecodeAsType derive macro can be used to implement DecodeAsType on structs and enums whose fields all implement DecodeAsType. Under the hood, the macro generates scale_decode::visitor::Visitor and scale_decode::IntoVisitor implementations for each type (as well as an associated Visitor struct), which in turn means that the type will automatically implement scale_decode::DecodeAsType.

§Examples

This can be applied to structs and enums:

use scale_decode::DecodeAsType;

#[derive(DecodeAsType)]
struct Foo(String);

#[derive(DecodeAsType)]
struct Bar {
    a: u64,
    b: bool
}

#[derive(DecodeAsType)]
enum Wibble<T> {
    A(usize, bool, T),
    B { value: String },
    C
}

If you aren’t directly depending on scale_decode, you must tell the macro what the path to it is so that it knows how to generate the relevant impls:

use alt_path::DecodeAsType;

#[derive(DecodeAsType)]
#[decode_as_type(crate_path = "alt_path")]
struct Foo<T> {
   a: u64,
   b: T
}

If you use generics, the macro will assume that each of them also implements EncodeAsType. This can be overridden when it’s not the case (the compiler will ensure that you can’t go wrong here):

use scale_decode::DecodeAsType;

#[derive(DecodeAsType)]
#[decode_as_type(trait_bounds = "")]
struct Foo<T> {
   a: u64,
   b: bool,
   #[decode_as_type(skip)]
   c: std::marker::PhantomData<T>
}

You’ll note that we can also opt to skip fields that we don’t want to decode into; such fields will receive their default value and no attempt to decode SCALE bytes into them will occur.

§Attributes

  • #[decode_as_type(crate_path = "::path::to::scale_decode")]: By default, the macro expects scale_decode to be a top level dependency, available as ::scale_decode. If this is not the case, you can provide the crate path here.
  • #[decode_as_type(trait_bounds = "T: Foo, U::Input: DecodeAsType")]: By default, for each generate type parameter, the macro will add trait bounds such that these type parameters must implement DecodeAsType too. You can override this behaviour and provide your own trait bounds instead using this option.
  • #[decode_as_type(skip)] (or #[codec(skip)]): Any fields annotated with this will be skipped when attempting to decode into the type, and instead will be populated with their default value (and therefore must implement core::default::Default).