Derive Macro byte_struct_derive::ByteStruct

source ·
#[derive(ByteStruct)]
{
    // Attributes available to this derive:
    #[byte_struct_le]
    #[byte_struct_be]
}
Expand description

Derives trait ByteStruct for a data structure.

Requires all members to implement ByteStructUnspecifiedByteOrder. This includes most primitive types and nested structures with ByteStruct derived (because ByteStructUnspecifiedByteOrder is automatically implemented for ByteStruct types)

Byte order attributes #[byte_struct_le] or #[byte_struct_be] can be attached to individual fields and/or the entire structure.

When a byte order attribute are attached to a field, it selects which byte order version of ByteStructUnspecifiedByteOrder member functions to use on the field In other words, the attribute specifies the byte order on an byte-order-unspecified type. These attributes have no effect on fields that implements ByteStruct, because they always have the same byte packing method regardless of externally specified byte order.

When a byte order attribute is attached to the entire struct, it works as if it is attached to all fields that don’t have byte order attributes.

If a field has no byte order attribute specified (either explicitly attached to the field or implicitly by the attribute on the entire structure), it must implement ByteStruct as well, so that its packing method is not byte-order-dependent. This is true for all ByteStruct-derived structures, but not for primitive types.

Example

#[derive(ByteStruct)]
#[byte_struct_le]
struct Struct1 {
    // Packed as little-endian.
    a: u32,

    // Packed as little-endian as well.
    // Redundant attributes doesn't hurt.
    #[byte_struct_le]
    b: i16,

    // Packed as big-endian.
    // Attributes on fields override top-level attributes.
    #[byte_struct_be]
    c: u16,
}

// This struct has no top-level byte order attribute
#[derive(ByteStruct)]
struct Struct2 {
    // Packed as big-endian.
    // If the attribute is missing here, it won't compile.
    #[byte_struct_be]
    d: i64,

    // Packed as little-endian.
    #[byte_struct_le]
    e: f32,
}

// This struct has no top-level byte order attribute either
#[derive(ByteStruct)]
struct Struct3 {
    // Nested structures don't need attributes.
    f: Struct1,

    // Even if you give one, it has no effect.
    // The endianness of fields inside Struct2 still remain as specified above.
    #[byte_struct_le]
    g: Struct2,
}