Derive Macro bin_proto::Protocol

source ·
#[derive(Protocol)]
{
    // Attributes available to this derive:
    #[protocol]
}
Expand description

Derive the Protocol trait.

§Attributes

§#[protocol(discriminant_type = "<type>")]

  • Applies to: enum with #[derive(Protocol)].
  • <type>: an arbitrary type that implements Protocol

Specify if enum variant should be determined by a string or interger representation of its discriminant.

#[derive(Protocol)]
#[protocol(discriminant_type = "u8")]
enum Example {
    Variant1 = 1,
    Variant5 = 5,
}

§#[protocol(discriminant = "<value>")]

  • Applies to: enum variant
  • <value>: unique value of the discriminant’s type
#[derive(Protocol)]
#[protocol(discriminant_type = "u8")]
enum Example {
    #[protocol(discriminant = "1")]
    Variant1,
    Variant5 = 5,
}

Specify the discriminant for a variant.

§#[protocol(bits = <width>)]

  • Applies to: impl BitField, enum with discriminant that impl BitField

Determine width of field in bits.

WARNING: Bitfields disregard ByteOrder and instead have the same endianness as the underlying BitRead / BitWrite instance. If you’re using bitfields, you almost always want a big endian stream.

#[derive(Protocol)]
struct Nibble(#[protocol(bits = 4)] u8);

§#[protocol(flexible_array_member)]

  • Applies to: impl FlexibleArrayMember

Variable-length field is final field in container, hence lacks a length prefix and should be read until eof.

#[derive(Protocol)]
struct ReadToEnd(#[protocol(flexible_array_member)] Vec<u8>);

§#[protocol(length = "<expr>")]

  • Applies to: impl ExternallyLengthPrefixed
  • <expr>: arbitrary usize expression. Fields in parent container can be used without prefixing them with self.

Specify length of variable-length field.

#[derive(Protocol)]
pub struct WithElementsLength {
    pub count: u32,
    pub foo: bool,
    #[protocol(length = "count as usize")]
    pub data: Vec<u32>,
}

§#[protocol(write_value = "<expr>")]

  • Applies to: fields
  • <expr>: An expression that can be coerced to the field type, potentially using self

Specify an expression that should be used as the field’s value for writing.

#[derive(Protocol)]
pub struct WithElementsLengthAuto {
    #[protocol(write_value = "self.data.len() as u32")]
    pub count: u32,
    pub foo: bool,
    #[protocol(length = "count as usize")]
    pub data: Vec<u32>,
}