1 unstable release

Uses old Rust 2015

0.1.0 Aug 8, 2024

#705 in Procedural macros

Download history 34/week @ 2024-08-26 34/week @ 2024-09-02 8/week @ 2024-09-09 111/week @ 2024-09-16 93/week @ 2024-09-23 25/week @ 2024-09-30 29/week @ 2024-10-07 24/week @ 2024-10-14 2/week @ 2024-10-21 4/week @ 2024-11-04 15/week @ 2024-11-11 92/week @ 2024-11-18 21/week @ 2024-12-09

114 downloads per month

MIT license

24KB
298 lines

rbitpack

The rbitpack crate provides a procedural macro for packing and unpacking boolean fields of a struct into various bit sizes. This can be particularly useful for reducing memory usage or performing bit-level operations.

Features

  • Efficient Packing and Unpacking: Pack multiple boolean fields into a single integer type (u8, u16, u32, u64) or a Vec<u64>.
  • Overflow Handling: Control whether an overflow error should be triggered when the number of boolean fields exceeds the available bits.
  • Dynamic Bitfield Size: Support for packing into a dynamic bitfield size with the Bitfield type from the bitval crate.

Usage

To use the rbitpack macro, add it to your struct as follows:

use rbitpack::BitwisePackable;

#[derive(BitwisePackable)]
#[rbitpack(size = "i8", overflow = false)]
struct MyStruct {
    field1: bool,
    field2: bool,
    // Add more fields as needed
}

Attributes

  • size: Specifies the bit size for packing (i8, i16, i32, i64, or auto for dynamic sizing).
  • overflow: Controls whether to panic on overflow (defaults to false).

Auto Size

If you use auto for the size attribute, you need to install and import the Bitfield type from the bitval crate. Add bitval to your Cargo.toml:

[dependencies]
bitval = "0.1"

Then, import Bitfield in your Rust code:

use bitval::Bitfield;

Examples

Packing and Unpacking with u8

#[derive(BitwisePackable)]
#[rbitpack(size = "i8")]
struct Example {
    a: bool,
    b: bool,
    c: bool,
}

let example = Example { a: true, b: false, c: true };
let packed = Example::pack(&example);
let unpacked = Example::unpack(packed);

Using Dynamic Bitfield Size

#[derive(BitwisePackable)]
#[rbitpack(size = "auto")]
struct DynamicExample {
    x: bool,
    y: bool,
    z: bool,
}

let example = DynamicExample { x: true, y: false, z: true };
let packed = DynamicExample::pack(&example);
let unpacked = DynamicExample::unpack(packed);

License

This crate is licensed under the MIT License. See the LICENSE file for details.

Dependencies

~1.5MB
~37K SLoC