#bit #parser #parsing

macro bitwrap_derive

derive for bitwrap

18 releases (4 breaking)

✓ Uses Rust 2018 edition

0.5.11 Jan 2, 2020
0.5.10 Jan 1, 2020
0.5.9 Dec 31, 2019
0.4.1 Dec 16, 2019
0.1.1 Nov 28, 2019

#181 in Rust patterns

Download history 36/week @ 2020-03-05 26/week @ 2020-03-12 72/week @ 2020-03-19 36/week @ 2020-03-26 3/week @ 2020-04-02 85/week @ 2020-04-09 62/week @ 2020-04-16 14/week @ 2020-04-23 3/week @ 2020-04-30 1/week @ 2020-05-07 1/week @ 2020-05-21 38/week @ 2020-05-28 36/week @ 2020-06-04 21/week @ 2020-06-11 1/week @ 2020-06-18

165 downloads per month
Used in bitwrap

MIT license

15KB
376 lines

BitWrap

docs

BitWrap is a derive macro and trait to declare a struct data member with explicit size, in bits.


BitWrap Trait

BitWrap trait declares 2 methods:

fn pack(&self, dst: &mut [u8]) -> Result<usize, BitWrapError>

pack method serialize struct fields into dst array

fn unpack(&mut self, src: &[u8]) -> Result<usize, BitWrapError>

unpack method deserialize struct fields from src array

BitWrap Macro

use bitwrap::BitWrap;

#[derive(BitWrap)]
struct Packet {
    // Get/Set bit
    #[bits(1)]
    flag_1: u8,

    // Get/Set bit and convert into bool:
    // - 0 - false
    // - 1 - true
    #[bits(1)]
    flag_2: bool,

    // Fixed 6 bits
    // on 'pack()' set 6 bits with defined value
    // on 'unpack()' skip 6 bits
    #[bits(6, skip = 0b111111)]

    // Get 8 bits and convert them to Enum
    // on 'pack()' call 'into(Enum) -> T'
    // on 'unpack()' call 'from(T) -> Enum'
    // T is a unsigned depends of the bit field size
    #[bits(8, from = Enum::from, into = Enum::into)]
    variant: Enum,

    // call BitWrap methods for Ipv4Addr
    #[bits]
    ip: std::net::Ipv4Addr

    // byte array
    #[bytes]
    mac: [u8; 6],

    // virtual field for the bytes option
    #[bits(8, name = data_len, value = self.data.len())]

    // call BitWrap method for Vec<T> with defined
    // buffer length where T is u8 or with implemented
    // BitWrap + Default traits
    #[bytes(data_len)]
    data: Vec<u8>,
}

Dependencies

~390–720KB
~17K SLoC