Serialize

Derive Macro Serialize 

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

Derives the Encodable trait, generating implementations for serializing a struct into an encoded format, including methods for field serialization, calculating the encoded size, and handling cases where the struct is already sized.

This procedural macro generates the Encodable trait for a struct, allowing each field to be converted into an EncodableField, with support for recursive field encoding. The macro also includes an implementation of the GetSize trait to calculate the encoded size of the struct, depending on the already_sized attribute.

§Example

Given a struct:

struct Test {
    a: u32,
    b: u8,
    c: U24,
}

Using #[derive(Encodable)] on Test generates the following implementations:

mod impl_parse_encodable_test {
    use super::binary_codec_sv2::{encodable::EncodableField, GetSize};
    extern crate alloc;
    use alloc::vec::Vec;

    struct Test {
        a: u32,
        b: u8,
        c: U24,
    }

    impl<'decoder> From<Test> for EncodableField<'decoder> {
        fn from(v: Test) -> Self {
            let mut fields: Vec<EncodableField> = Vec::new();

            let val = v.a;
            fields.push(val.into());

            let val = v.b;
            fields.push(val.into());

            let val = v.c;
            fields.push(val.into());

            Self::Struct(fields)
        }
    }

    impl<'decoder> GetSize for Test {
        fn get_size(&self) -> usize {
            let mut size = 0;

            size += self.a.get_size();
            size += self.b.get_size();
            size += self.c.get_size();

            size
        }
    }
}

This generated code enables Test to be serialized into an encoded format, defines how each field should be converted, and calculates the total encoded size of the struct, depending on whether it is marked as already_sized.