Derive Macro parity_scale_codec::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.
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.#[codec(encode_bound(T: Encode))]
: a custom where bound that will be used when deriving theEncode
trait.#[codec(decode_bound(T: Encode))]
: a custom where bound that will be used when deriving theDecode
trait.
#[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 discrimant (like 3 in
enum T { A = 3 }
) then the discrimant. - else its position in the variant set, excluding skipped variants, but including variant with discrimant or attribute. Warning this position does collision with discrimant 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]);