【PhysUnits】4.1 类型级比特位实现解释(boolean.rs)

发布于:2025-05-17 ⋅ 阅读:(16) ⋅ 点赞:(0)

一、源码

该代码实现了一个类型级(type-level)的布尔系统,允许在编译时进行布尔运算。

//! 类型级比特位实现
//!
//! 这些是基础的比特位类型,作为本库中其他数值类型的构建基础
//!
//! 已实现的**类型运算符**:
//!
//! - 来自 `core::ops` 的:`BitAnd`(与), `BitOr`(或), `BitXor`(异或) 和 `Not`(非)
//! - 比较操作:`PartialEq`, `Eq`
//! - 转换操作:`From<bool>`, `Into<bool>`
//!
//! 别名定义:
//! - `B1` = `True` (逻辑真/正一)
//! - `B0` = `False` (逻辑假/零)
//!
//! 示例:
//! ```
//! use your_crate::{B1, B0, Boolean};
//!
//! let t = B1::new();
//! let f = B0::new();
//!
//! assert_eq!(t & t, B1);
//! assert_eq!(t | f, B1);
//! assert_eq!(t ^ t, B0);
//! assert_eq!(!t, B0);
//! ```

use core::ops::{BitAnd, BitOr, BitXor, Not};
use crate::sealed::Sealed;

/// 编译时比特位的标记特征
///
/// 这个 trait 定义了类型级布尔值的基本操作和行为,
/// 包括构造、转换和常量值访问。
pub trait Boolean: Sealed + Copy + Default + 'static {
    /// 布尔值的编译时常量表示
    const BOOL: bool;

    /// 创建一个该类型的新实例
    fn new() -> Self;

    /// 将类型级布尔值转换为运行时布尔值
    fn to_bool() -> bool {
        Self::BOOL
    }

    /// 获取当前实例对应的运行时布尔值
    fn as_bool(&self) -> bool {
        Self::BOOL
    }
}

/// 类型级比特位0(逻辑假)
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct False;

// 类型级比特位0的别名(零) zero.rs文件实现
//pub type B0 = False;

impl False {
    /// 创建一个新的 `False` 实例
    #[inline(always)]
    pub const fn new() -> Self {
        False
    }
}

/// 类型级比特位1(逻辑真)
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)]
pub struct True;

/// 类型级比特位1的别名(正一)
pub type B1 = True;

impl True {
    /// 创建一个新的 `True` 实例
    #[inline(always)]
    pub const fn new() -> Self {
        True
    }
}

// 为布尔类型实现密封标记
impl Sealed for False {}
impl Sealed for True {}

impl Boolean for False {
    const BOOL: bool = false;
    #[inline(always)] fn new() -> Self { Self }
}

impl Boolean for True {
    const BOOL: bool = true;
    #[inline(always)] fn new() -> Self { Self }
}

// 实现所有逻辑运算

/// 实现逻辑非运算
impl Not for False {
    type Output = True;
    #[inline(always)]
    fn not(self) -> Self::Output {
        True
    }
}

impl Not for True {
    type Output = False;
    #[inline(always)]
    fn not(self) -> Self::Output {
        False
    }
}

/// 实现逻辑与运算
impl<Rhs: Boolean> BitAnd<Rhs> for False {
    type Output = Self;
    #[inline(always)]
    fn bitand(self, _: Rhs) -> Self::Output {
        Self
    }
}

impl BitAnd<False> for True {
    type Output = False;
    #[inline(always)]
    fn bitand(self, _: False) -> Self::Output {
        False
    }
}

impl BitAnd<True> for True {
    type Output = True;
    #[inline(always)]
    fn bitand(self, _: True) -> Self::Output {
        True
    }
}

/// 实现逻辑或运算
impl BitOr<False> for False {
    type Output = False;
    #[inline(always)]
    fn bitor(self, _: False) -> Self::Output {
        False
    }
}

impl BitOr<True> for False {
    type Output = True;
    #[inline(always)]
    fn bitor(self, _: True) -> Self::Output {
        True
    }
}

impl<Rhs: Boolean> BitOr<Rhs> for True {
    type Output = True;
    #[inline(always)]
    fn bitor(self, _: Rhs) -> Self::Output {
        True
    }
}

/// 实现逻辑异或运算
impl BitXor<False> for False {
    type Output = False;
    #[inline(always)]
    fn bitxor(self, _: False) -> Self::Output {
        False
    }
}

impl BitXor<False> for True {
    type Output = True;
    #[inline(always)]
    fn bitxor(self, _: False) -> Self::Output {
        True
    }
}

impl BitXor<True> for False {
    type Output = True;
    #[inline(always)]
    fn bitxor(self, _: True) -> Self::Output {
        True
    }
}

impl BitXor<True> for True {
    type Output = False;
    #[inline(always)]
    fn bitxor(self, _: True) -> Self::Output {
        False
    }
}

// 实现转换操作

impl From<bool> for &'static dyn Boolean {
    /// 从运行时布尔值创建类型级布尔值的引用
    fn from(b: bool) -> Self {
        if b { &True } else { &False }
    }
}

impl From<bool> for True {
    /// 从 `true` 创建 `True` 实例
    ///
    /// # Panics
    /// 如果输入为 `false` 会 panic
    fn from(b: bool) -> Self {
        assert!(b);
        True
    }
}

impl From<bool> for False {
    /// 从 `false` 创建 `False` 实例
    ///
    /// # Panics
    /// 如果输入为 `true` 会 panic
    fn from(b: bool) -> Self {
        assert!(!b);
        False
    }
}

impl<T: Boolean> From<T> for bool {
    /// 将类型级布尔值转换为运行时布尔值
    fn from(b: T) -> Self {
        b.as_bool()
    }
}

impl std::fmt::Display for dyn Boolean {
    /// 实现格式化输出,显示布尔值
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_bool())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_aliases() {
        let p1 = B1::new();
        let z0 = B0::new();
        
        assert_eq!(p1, True);
        assert_eq!(z0, False);
        assert!(B1::BOOL);
        assert!(!B0::BOOL);
    }

    #[test]
    fn test_boolean_ops_with_aliases() {
        let p1 = B1::new();
        let z0 = B0::new();

        assert_eq!(p1 & p1, B1);
        assert_eq!(p1 | z0, B1);
        assert_eq!(p1 ^ p1, B0);
        assert_eq!(!p1, B0);
    }
    
    #[test]
    fn test_boolean_ops() {
        let t = True::new();
        let f = False::new();

        assert_eq!(t & t, True);
        assert_eq!(t & f, False);
        assert_eq!(f & t, False);
        assert_eq!(f & f, False);

        assert_eq!(t | t, True);
        assert_eq!(t | f, True);
        assert_eq!(f | t, True);
        assert_eq!(f | f, False);

        assert_eq!(t ^ t, False);
        assert_eq!(t ^ f, True);
        assert_eq!(f ^ t, True);
        assert_eq!(f ^ f, False);

        assert_eq!(!t, False);
        assert_eq!(!f, True);
    }

    #[test]
    fn test_conversions() {
        let t: &dyn Boolean = true.into();
        assert!(t.as_bool());
        
        let f: &dyn Boolean = false.into();
        assert!(!f.as_bool());

        assert!(bool::from(True::new()));
        assert!(!bool::from(False::new()));
    }
}

二、主要组件

  1. Boolean trait
  • 定义了类型级布尔值的基本行为和操作

  • 包含编译时常量BOOL表示布尔值

  • 提供构造方法new()和转换方法to_bool()/as_bool()

  • 标记为Sealed防止外部实现

  1. 布尔类型
  • False: 表示逻辑假/0

  • True: 表示逻辑真/1

类型别名:

B0 = False (零)

B1 = True (正一)

  1. 实现的操作
  • 逻辑运算:

    • Not(非): !

    • BitAnd(与): &

    • BitOr(或): |

    • BitXor(异或): ^

  • 比较: PartialEq, Eq

  • 转换: From, Into

三、关键实现细节

  1. 常量值:
  • False::BOOL = false

  • True::BOOL = true

  1. 逻辑运算实现:
  • 每种运算都为所有可能的组合提供了具体实现

  • 例如True & False返回False

  1. 转换操作:
  • 可以从运行时bool转换为类型级布尔值

  • 也可以从类型级布尔值转换回运行时bool

  1. 性能优化:
  • 使用#[inline(always)]确保零运行时开销

  • 所有操作都在编译时完成

四、使用示例

use your_crate::{B1, B0};

let t = B1::new();  // True
let f = B0::new();  // False

assert_eq!(t & t, B1);  // True AND True = True
assert_eq!(t | f, B1);  // True OR False = True
assert_eq!(t ^ t, B0);  // True XOR True = False
assert_eq!(!t, B0);     // NOT True = False

五、测试用例

  1. 代码包含了全面的测试:

  2. 测试类型别名是否正确

  3. 测试所有逻辑运算

  4. 测试与运行时布尔值的转换

这种类型级编程技术在需要编译时计算和验证的场景中非常有用,如类型状态机、维度检查等。


网站公告

今日签到

点亮在社区的每一天
去签到