Impl BitOr And Not Build Flags

Implement BitOr, BitAnd, and Not for a newtype over u8 so permission sets compose with | and & and complement with ! under a 3-bit mask.

RustData Integrity

Code

rustsnippet
42 lines
use std::ops::{BitAnd, BitOr, Not};

#[derive(Clone, Copy)]
struct Perms(u8);

const READ: Perms = Perms(0b100);
const WRITE: Perms = Perms(0b010);
const EXEC: Perms = Perms(0b001);

// operator impls build the bitflags: compose with |, intersect with &
impl BitOr for Perms {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Perms(self.0 | rhs.0)
    }
}

impl BitAnd for Perms {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self {
        Perms(self.0 & rhs.0)
    }
}

impl Not for Perms {
    type Output = Self;
    fn not(self) -> Self {
        Perms(!self.0 & 0b111)
    }
}

fn main() {
    let granted = READ | EXEC;
    println!("granted: {:03b}", granted.0);

    // intersection: which requested bits were actually granted
    let requested = READ | WRITE;
    println!("common: {:03b}", (granted & requested).0);

    // complement: the ungranted bits within the 3-bit mask
    println!("missing: {:03b}", (!granted).0);
}

What the demo composes

Perms is a newtype over u8 with READ, WRITE and EXEC constants. BitOr lets granted = READ | EXEC compose a set, printing 101 in the three-bit rendering; BitAnd intersects it with the requested READ | WRITE, printing the single bit both sides hold.

Not completes the flag toolkit: !granted inverts and masks with 0b111, printing 010, the permission bits that were not granted. Every operator returns Perms, so results stay typed instead of falling back to a bare u8.

Practical notes

  • type Output = Self keeps expressions chainable and typed.
  • The mask in Not bounds the complement to the three real flags.

Interactive Tools for This Topic

FAQ

Why mask the Not result with 0b111?
Inverting a u8 flips all eight bits; masking to the three flag bits prints 010, exactly the ungranted permissions, instead of a wide unrelated value.