How to declare typed bitflags in Rust?

后端 未结 4 1996
-上瘾入骨i
-上瘾入骨i 2021-01-26 05:48

It\'s possible to declare flags in Rust - similar to how it would be done in C.

pub const FOO: u32 = (1 << 0);
pub const BAR: u32 = (1 << 1);

let fl         


        
4条回答
  •  时光取名叫无心
    2021-01-26 06:22

    You could (I don't know if it is in any way idiomatic) just use Rust's enums :

    pub enum MyFlags {
        Meaning1,
        Meaning2,
        Meaning3,
        ...,
        MeaningX
    }
    

    This way you have a clear meaning for your flags. Once done, you can write some helper functions around this enum for Rust-to-C conversion.

    fn to_u32(flag: &MyFlags) -> u32 {
        match flag {
            &MyFlags::Meaning1 => return (1 << 0),
            &MyFlags::Meaning2 => return (1 << 1),
            &MyFlags::Meaning3 => return (1 << 2),
            &MyFlags::MeaningX => return (1 << 3),
        }
    }
    
    fn to_bitflags_flags(flags: &Vec) -> u32 {
        let mut bitflags = 0u32;
    
        for flag in flags {
            bitflags |= to_u32(flag);
        }
        return bitflags;
    }
    

提交回复
热议问题