Skip to content

rfc: Proc Macros #14

@john-bv

Description

@john-bv

Binary Utils Macro Derive

BinaryUtils provides one derive macro BinaryIo.

This macro will implement both the Read and Write traits from interfaces. By default, this macro will read and write in the order the fields are declared in. In the future it may be possible to change this with an attribute, but this is not marked as a priority.

Require attribute

The require attribute allows you to require a previous field. This attribute requires the type to be that of the field must be Option<T<dyn Reader + dyn Writer>>.

Syntax:

#[require(<IDENT>)]

Example:

The following example requires field B to exist in order to try and decode C

pub struct ABC {
    a: u8,
    b: Option<u8>,
    #[require(B)]
    c: Option<u8>
}

Satisfy Attribute

This attribute provides functionality which allows you to optionally decode or encode a field or type. Conditionals are useful if you want to avoid using enums as wrapper types to support conditional logic.

Syntax:

#[satisfy(<EXPR>)]

Example:

The following is an example of a conditional attribute with the BinaryIo macro.

#[BinaryIo]
pub struct FramePacket {
    pub id: u16,
    // split_channel will only be read if the following condition
    // is specified
    #[satisfy(((self.id & 224) >> 5) == 3)]
    pub split_channel: Option<u8>,
}

Skip Attribute

This attribute does as the name implies; it skips the given field on both encoding and decoding. This field will not be used in encoding or decoding.

Syntax:

#[skip]

Example:

The following example skips field B and only encodes both A and C in the binary stream.

#[derive(BinaryIo)]
pub AC {
    A: u8,
    #[skip]
    B: u8,
    C: u8
}

pub fn test_ac() {
    let ac = AC { A: 1, B: 2, C: 3 };
    assert_eq!(ac.write_init().as_slice(), &[1, 3]);
}

Edit: Identifiers and expressions are now their literal types, not a string.

Metadata

Metadata

Assignees

Labels

APIThis issue is related to the APICompletedThis issue has been completed.Feature RequestRequests a feature or change.

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions