一、源碼
該代碼實現了一個類型級(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` 會 panicfn from(b: bool) -> Self {assert!(b);True}
}impl From<bool> for False {/// 從 `false` 創建 `False` 實例////// # Panics/// 如果輸入為 `true` 會 panicfn 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()));}
}
二、主要組件
- Boolean trait
-
定義了類型級布爾值的基本行為和操作
-
包含編譯時常量BOOL表示布爾值
-
提供構造方法new()和轉換方法to_bool()/as_bool()
-
標記為Sealed防止外部實現
- 布爾類型
-
False: 表示邏輯假/0
-
True: 表示邏輯真/1
類型別名:
B0 = False (零)
B1 = True (正一)
- 實現的操作
-
邏輯運算:
-
Not(非): !
-
BitAnd(與): &
-
BitOr(或): |
-
BitXor(異或): ^
-
-
比較: PartialEq, Eq
-
轉換: From, Into
三、關鍵實現細節
- 常量值:
-
False::BOOL = false
-
True::BOOL = true
- 邏輯運算實現:
-
每種運算都為所有可能的組合提供了具體實現
-
例如True & False返回False
- 轉換操作:
-
可以從運行時bool轉換為類型級布爾值
-
也可以從類型級布爾值轉換回運行時bool
- 性能優化:
-
使用#[inline(always)]確保零運行時開銷
-
所有操作都在編譯時完成
四、使用示例
use your_crate::{B1, B0};let t = B1::new(); // True
let f = B0::new(); // Falseassert_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
五、測試用例
-
代碼包含了全面的測試:
-
測試類型別名是否正確
-
測試所有邏輯運算
-
測試與運行時布爾值的轉換
這種類型級編程技術在需要編譯時計算和驗證的場景中非常有用,如類型狀態機、維度檢查等。