Derive Macro parity_scale_codec_derive::Encode
source · #[derive(Encode)]
{
// Attributes available to this derive:
#[codec]
}
Expand description
Derive parity_scale_codec::Encode
and parity_scale_codec::EncodeLike
for struct and enum.
§Top level attributes
By default the macro will add Encode
and Decode
bounds to all types, but the bounds can
be specified manually with the top level attributes:
#[codec(encode_bound(T: Encode))]
: a custom bound added to thewhere
-clause when deriving theEncode
trait, overriding the default.#[codec(decode_bound(T: Decode))]
: a custom bound added to thewhere
-clause when deriving theDecode
trait, overriding the default.
§Struct
A struct is encoded by encoding each of its fields successively.
Fields can have some attributes:
#[codec(skip)]
: the field is not encoded. It must deriveDefault
if Decode is derived.#[codec(compact)]
: the field is encoded in its compact representation i.e. the field must implementparity_scale_codec::HasCompact
and will be encoded asHasCompact::Type
.#[codec(encoded_as = "$EncodeAs")]
: the field is encoded as an alternative type. $EncodedAs type must implementparity_scale_codec::EncodeAsRef<'_, $FieldType>
with $FieldType the type of the field with the attribute. This is intended to be used for types implementingHasCompact
as shown in the example.
#[derive(Encode)]
struct StructType {
#[codec(skip)]
a: u32,
#[codec(compact)]
b: u32,
#[codec(encoded_as = "<u32 as HasCompact>::Type")]
c: u32,
}
§Enum
The variable is encoded with one byte for the variant and then the variant struct encoding. The variant number is:
- if variant has attribute:
#[codec(index = "$n")]
then n - else if variant has discriminant (like 3 in
enum T { A = 3 }
) then the discriminant. - else its position in the variant set, excluding skipped variants, but including variant with discriminant or attribute. Warning this position does collision with discriminant or attribute index.
variant attributes:
#[codec(skip)]
: the variant is not encoded.#[codec(index = "$n")]
: override variant index.
field attributes: same as struct fields attributes.
#[derive(Encode)]
enum EnumType {
#[codec(index = 15)]
A,
#[codec(skip)]
B,
C = 3,
D,
}
assert_eq!(EnumType::A.encode(), vec![15]);
assert_eq!(EnumType::B.encode(), vec![]);
assert_eq!(EnumType::C.encode(), vec![3]);
assert_eq!(EnumType::D.encode(), vec![2]);