5 releases

0.3.2 Nov 7, 2022
0.3.1 Aug 3, 2022
0.2.1 Jul 20, 2022
0.1.2 Jul 14, 2022

#74 in No standard library

MIT license

14KB
122 lines

Superbitty

A bitfields crate.

use superbitty::{bitfields, BitFieldCompatible};

#[derive(BitFieldCompatible, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Enum {
    A,
    B,
    C,
    D,
}

#[derive(Clone, Copy)]
pub struct Rest(pub u8);

// SAFETY: We only set this via `Bitfields`, and thus the values are guaranteed
// to stay in range.
unsafe impl BitFieldCompatible for Rest {
    const SHIFT: u32 = 0;
    const BITS_LEN: u32 = 6;
    fn into_raw(self) -> u128 { self.0 as u128 }
    unsafe fn from_raw(v: u128) -> Self { Self(v as u8) }
}

bitfields! {
    pub struct Bitfields : u8 {
        pub e: Enum,
        pub r: Rest,
    }
}

fn main() {
    let mut instance = Bitfields::new(Enum::B, Rest(0b010));
    assert_eq!(instance.e(), Enum::B);
    instance.set_r(Rest(0b101));
    assert_eq!(instance.r().0, 0b101);
}

lib.rs:

A bitfields crate.

use superbitty::{bitfields, BitFieldCompatible};

#[derive(BitFieldCompatible, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Enum {
    A,
    B,
    C,
    D,
}

#[derive(Clone, Copy)]
pub struct Rest(pub u8);

// SAFETY: We only set this via `Bitfields`, and thus the values are guaranteed
// to stay in range.
unsafe impl BitFieldCompatible for Rest {
    const SHIFT: u32 = 0;
    const BITS_LEN: u32 = 6;
    fn into_raw(self) -> u128 { self.0 as u128 }
    unsafe fn from_raw(v: u128) -> Self { Self(v as u8) }
}

bitfields! {
    pub struct Bitfields : u8 {
        pub e: Enum,
        pub r: Rest,
    }
}

fn main() {
    let mut instance = Bitfields::new(Enum::B, Rest(0b010));
    assert_eq!(instance.e(), Enum::B);
    instance.set_r(Rest(0b101));
    assert_eq!(instance.r().0, 0b101);
}

Dependencies

~195–590KB
~14K SLoC