MaikKlein / enumflags

24 stars 7 forks source link

Add `field_val` method #6

Closed jmi2k closed 7 years ago

jmi2k commented 7 years ago

WIP! I came across the need of accessing bit ranges, and I thought it could be a good idea. What's your opinion? For example:

The idea

#[macro_use]
extern crate enumflags_derive;
extern crate enumflags;

#[derive(EnumFlags)]
#[repr(u8)]
enum Flag {
    FlagA = 0b00000001,
    FlagB = 0b00000010,
    FlagC = 0b00000100,
    Field = 0b11111000
}

fn main() {
    let mask = Flag::Field;
    let val: BitFlags<Flag> = BitFlags::from_bits_truncate(0b01010001);
    let result = val.field_val(mask);

    // 0b00001010
    println!("{:08b}", result);
}

Drawbacks

It has for me one drawback (at least with the current implementation). If bits are scattered, they aren't joined. Instead, separation between them is kept.

Other ideas

Maybe adding a setter is a good idea, but I think it's a bit out of the scope of this project.

I opened the PR just for discussion, to have an implementation to back the idea. Neither the name or the implementation are definitive.

MaikKlein commented 7 years ago

I don't see the use case here. Could give me an example where this would be useful?

jmi2k commented 7 years ago

It could be useful for types with flags and values scattered in the same place, to provide C-like bit fields. Now that I thought a bit more about it, I see it's better to implement it outside of this project, and keep the project simpler.

Sorry for bothering you and changing my mind so quickly, I'm tinkering a lot with the library these days.

MaikKlein commented 7 years ago

Don't be sorry, I always want to see possible improvements.