danlehmann / bitfield

Rust crate for bitfields and bit-enums
MIT License
47 stars 9 forks source link

Suggest: some error should be ok #55

Open pbl-pw opened 9 months ago

pbl-pw commented 9 months ago
use arbitrary_int::{u2, u4};
use bitbybit::bitfield;
use custom::Custom1;

mod custom {
    pub struct Custom1<T>(T);
    impl<T: Copy> Custom1<T> {
        pub const fn raw_value(&self) -> T {
            self.0
        }
        pub const fn new_with_raw_value(raw: T) -> Self {
            Self(raw)
        }
    }

    pub struct Custom2<T>(T);
    impl<T: Copy> Custom2<T> {
        pub const fn raw_value(&self) -> T {
            self.0
        }
        pub const fn new_with_raw_value(raw: T) -> Result<Self, T> {
            Ok(Self(raw))
        }
    }
}

#[bitfield(u8)]
#[derive(Debug)]
#[rustfmt::skip]
pub struct Flags {
    #[bits(0..=7, rw)] cus1: Option<custom::Custom2<u8>>, // error, ok if Option<custom::Custom2::<u8>>
    #[bits(2..=5, rw)] cus2: Option<custom::Custom2::<u4>>, // error because require Result<Self, u8> but provide Result<Self, u4>, maybe latter is better especially when used with generic

    #[bits(6..=7, rw)] cus3: custom::Custom1<u2>, // error because '::'
    #[bits(6..=7, rw)] cus4: Custom1<u2>, // error, ok if Custom1::<u2>
}
danlehmann commented 9 months ago

Hey, thanks for the bugreport.

I think the namespace issues can be resolved by some parser improvements. I'll take a look.

The issue about Option, vs Result (and the size of the Result) is an ugly wart. I had a fix for the size of the Result at some point, but it is a major breaking change.

https://github.com/danlehmann/bitfield/issues/35 has some overlap with your second issue. I also attempted to fix the second part of cus2 at some point (Result<, u4> instead of Result<, u8>) in https://github.com/danlehmann/bitfield/pull/47, but it is a major breaking change, so I wanted to postpone that a bit until more major breaking changes pile up. But there wasn't really that much, so maybe it makes sense to do that now

danlehmann commented 9 months ago

For cus2, I had an idea how this could be improved. See https://github.com/danlehmann/bitfield/issues/35#issuecomment-1977248113. Let's use this task to discuss the other issues

pbl-pw commented 9 months ago

Maybe the solution for cus1,cus3,cus4 is simple and no breakchange: just change generated method like https://github.com/danlehmann/bitfield/blob/056a50b83a28e0903f834fcac788a690fe447332/bitbybit/src/bitfield/codegen.rs#L37 to <#convert_type>::new_with_raw_value(extracted_bits) the key point is use <> to force get type