Robbepop / modular-bitfield

Macro to generate bitfields for structs that allow for modular use of enums.
Apache License 2.0
160 stars 42 forks source link

Support for `to_u32()` conversion to `u32` and similar #102

Open hacknus opened 1 year ago

hacknus commented 1 year ago

Hello First of all; thank you for this very useful library! I created the additional trait modular-bitfield-to-value ToValue which can be implemented for all structs annotated with #[bitfield]. It allows to then convert the struct to a u32 which can be useful for debugging.

Add the following imports:

use modular_bitfield::bitfield;
use modular_bitfield_to_value::ToValue;

A basic example:

#[bitfield(bits = 32)]
#[derive(ToValue)]
pub struct Field {
    pub test: u32,
}

{
    let field = Field::from_bytes(0x100C3_u32.to_be_bytes());
    let value = field.to_u32().unwrap();
    assert!(0x100C3 == value, "constructed = {}, to_u32() = {}", 0x100C3, 0x100C3);
}

We could keep this separate as is, then I'd push it to crates.io, but if you want, we could also implement it in the modular-bitfield crate (maybe through a feature)?

Let me know what you think!

EDIT: If this would be implemented in modular-bitfield it would not need to be a trait, we could merely copy the functions over...