How to declare typed bitflags in Rust?

后端 未结 4 1992
-上瘾入骨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:33

    There is an unstable EnumSet collection in the standard library that works with the also unstable CLike trait. It works like this: you define an enum, whose members take a bit number (not a mask!) as their value, and EnumSet uses the bit at the position designated by the enum value to store whether the enum member is part of the set or not. At runtime, an EnumSet is represented by a single usize. EnumSet is parameterized on the enum type, so sets based on different enums will not have the same type.

    #![feature(collections)]
    #![feature(enumset)]
    
    extern crate collections;
    
    use collections::enum_set::{CLike, EnumSet};
    use std::mem;
    
    #[derive(Clone, Copy, Debug)]
    #[repr(usize)]
    enum MyFlag {
        Foo,
        Bar,
    }
    
    impl CLike for MyFlag {
        fn to_usize(&self) -> usize {
            *self as usize
        }
    
        fn from_usize(v: usize) -> MyFlag {
            unsafe { mem::transmute(v) }
        }
    }
    
    fn main() {
        let mut flags = EnumSet::new();
        flags.insert(MyFlag::Foo);
        flags.insert(MyFlag::Bar);
        println!("{:?}", flags);
    }
    

提交回复
热议问题