Skip to content

0.5.1

Compare
Choose a tag to compare
@wrenger wrenger released this 27 Jun 20:17
· 60 commits to main since this release

This release redesigned the support for custom types.
They are now also const (compile time evaluated) but require conversion functions (from_bits/into_bits; this can be changed in the attribute parameters). Beware, this breaks compatibility with the previous From/Into based implementation.

Similarly, the fields can now specify custom defaults in the bits attribute like #[bits(7, default = 42)]. This also works for padding.

Both features are shown below:

#[bitfield(u16)]
#[derive(PartialEq, Eq)]
struct MyBitfield {
    /// Interpreted as 1-bit flag, with custom default
    #[bits(default = true)]
    flag: bool,
    /// Supports any type, with default/to/from expressions (that are const eval)
    /// - into/from call #ty::into_bits/#ty::from_bits if nothing else is specified
    #[bits(13, default = CustomEnum::B, from = CustomEnum::my_from_bits)]
    custom: CustomEnum,
    // Padding with default
    #[bits(2, default = 0b10)]
    __: (),
}

/// A custom enum
#[derive(Debug, PartialEq, Eq)]
#[repr(u16)]
enum CustomEnum {
    A, B, C,
}
impl CustomEnum {
    // This has to be const eval
    const fn into_bits(self) -> u16 {
        self as _
    }
    const fn my_from_bits(value: u16) -> Self {
        match value {
            0 => Self::A,
            1 => Self::B,
            _ => Self::C,
        }
    }
}

// New sets defaults
let val = MyBitfield::new();

assert_eq!(val.flag(), true);
assert_eq!(val.custom(), CustomEnum::B);
assert_eq!(val.0 >> 14, 0b10); // padding
  • 0.5.1 fixes an oversight in the Default implementation