How to implement bitwise operations on enumeration of bitflags?

I have an enumeration that looks like this:

#[repr(u8)]
pub enum PublicFlags {
    PublicFlagVersion = 0x01,
    PublicFlagReset = 0x02,
    NoncePresent = 0x04,
    IdPresent = 0x08,
    PktNumLen4 = 0x30,
    PktNumLen2 = 0x20,
    PktNumLen1 = 0x10,
    Multipath = 0x40,
}

I want a bitwise operation on multiple enumeration values. However, the Rust compiler complains:

an implementation of `std::ops::BitAnd` might be missing for `PublicFlags`.
+6
source share
1 answer

An enumin Rust is not intended to be used as bit flags. PublicFlagscan take only the values ​​indicated in the enumeration (and not in combination). So, for example, the following match operator is exhaustive:

let flags: PublicFlags;
...
match flags {
    PublicFlagVersion => {...}
    PublicFlagReset => {...}
    NoncePresent => {...}
    IdPresent => {...}
    PktNumLen4 => {...}
    PktNumLen2 => {...}
    PktNumLen1 => {...}
    Multipath => {...}
}

It is not possible to have a variable PublicFlagswith a combination of flags.

, u8, . , , , bitflags . , -:

#[macro_use]
extern crate bitflags;

bitflags! {
    flags PublicFlags: u8 {
        const PUBLIC_FLAG_VERSION = 0x01,
        const PUBLIC_FLAG_RESET = 0x02,
        const NONCE_PRESENT = 0x04,
        const ID_PRESENT = 0x08,
        const PKT_NUM_LEN_4 = 0x30,
        const PKT_NUM_LEN_2 = 0x20,
        const PKT_NUM_LEN_1 = 0x10,
        const MULTIPATH = 0x40,
    }
}

fn main() {
    let flag = PUBLIC_FLAG_VERSION | ID_PRESENT;
    assert!((flag & MULTIPATH).is_empty()); 
    assert!(flag.contains(ID_PRESENT));
} 
+9

Source: https://habr.com/ru/post/1016647/


All Articles