← 中文资源

简体中文版本

为新类型实现位运算符

为 u8 新类型实现 BitOr、BitAnd、Not 等 std::ops 运算符:权限集用 | 组合、& 求交集、! 在 3 位掩码内取反,运算结果仍是同一类型。

阅读英文原文

运行说明

Perms 是 u8 的新类型,带 READ、WRITE、EXEC 常量。BitOr 让 granted = READ | EXEC 组合出集合,三位渲染打印 101;BitAnd 与请求的 READ | WRITE 求交集,打印双方共有的那一位。

Not 补全标志工具箱:!granted 取反后与 0b111 掩码,打印 010——未授予的权限位。每个运算符都返回 Perms,结果保持类型化,不会退回裸 u8。

要点提示

  • type Output = Self 让表达式可链式且类型安全。
  • Not 里的掩码把取反限制在三个真实标志位内。

核心语句

Perms(!self.0 & 0b111)

代码示例

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);
}