源码
这段代码实现了类型系统中的"按位取反"操作(Not trait),对应于Rust中的!运算符。
use super::basic::{B0, B1, Z0, P1, N1, NonZero, NonNegOne};
use core::ops::Not;
// ==================== 按位取反(!运算符) ====================
// ========== 基础类型实现 / Basic Type Implementations ==========
impl Not for Z0 { // Z0 (0) 的按位取反
type Output = N1;
fn not(self) -> Self::Output {
N1
}
}
impl Not for N1 { // N1 (-1) 的按位取反
type Output = Z0;
fn not(self) -> Self::Output {
Z0
}
}
impl Not for P1 { // P1 (+1) 的按位取反
type Output = B0<N1>;
fn not(self) -> Self::Output {
B0::new()
}
}
// ========== 递归类型实现 / Recursive Type Implementations ==========
impl<H: NonZero + NonNegOne + Not> Not for B0<H> { // B0<H> (...0) 的按位取反
type Output = B1<H::Output>;
fn not(self) -> Self::Output {
B0::new()
}
}
impl<H: NonZero+Not> Not for B1<H> { // B1<H> (...1) 的按位取反
type Output = B0<H::Output>;
fn not(self) -> Self::Output {
B1::new()
}
}
// ========== 特化实现 ==========
//与P1对应的B0<N1>需要特化
impl Not for B0<N1> { // B0<N1> (-2) 的按位取反
type Output = P1;
fn not(self) -> Self::Output {
P1
}
}
二、核心设计
Not trait:来自core::ops::Not,定义了关联类型Output和not()方法
实现策略:
基础类型实现(Z0, P1, N1)
递归类型实现(B0, B1)
特化实现(处理特定边界情况)
三、基础类型实现
- Z0 (零) 取反
impl Not for Z0 {
type Output = N1; // !0 = -1 (二进制全1)
fn not(self) -> Self::Output { N1 }
}
- 对应数学上的!0 = -1(在二进制补码表示中)
- N1 (负一) 取反
impl Not for N1 {
type Output = Z0; // !(-1) = 0
fn not(self) -> Self::Output { Z0 }
}
- 负一在二进制中是全1,取反后为全0
- P1 (正一) 取反
impl Not for P1 {
type Output = B0<N1>; // !1 = -2
fn not(self) -> Self::Output { B0::new() }
}
这里B0表示-2(二进制…1110)
注意构造函数返回的是B0类型,但值不重要(类型层面计算)
四、递归类型实现
- B0 (…0) 取反
impl<H: NonZero + NonNegOne + Not> Not for B0<H> {
type Output = B1<H::Output>; // !...0 = ...1 (高位也取反)
fn not(self) -> Self::Output { B0::new() }
}
最低位0变1,高位递归取反
约束H必须可取反且符合特定条件
- B1 (…1) 取反
impl<H: NonZero + Not> Not for B1<H> {
type Output = B0<H::Output>; // !...1 = ...0 (高位也取反)
fn not(self) -> Self::Output { B1::new() }
}
最低位1变0,高位递归取反
约束H必须可取反
五、特化实现
B0 (-2) 取反
impl Not for B0<N1> {
type Output = P1; // !(-2) = +1
fn not(self) -> Self::Output { P1 }
}
直接返回P1而不是B1,保持规范化
对应计算:!..1110 = …0001
六、关键点说明
- 二进制补码逻辑:
按位取反相当于-(x + 1)
例如!1 = -2,!(-2) = 1
- 递归处理:
对于复合类型B0/B1,递归处理高位
例如!B0(即!2):
!B0<P1> => B1<!P1> => B1<B0<N1>> (表示-3)
- 规范化处理:
特化实现确保结果使用最简形式
避免出现B1,用P1代替
- 类型约束:
NonZero:P1代替B1后,高位不存在Z0
NonNegOne:确保特例的实施
七、示例计算
- P1 (1) 取反:
!P1 => B0<N1> (-2)
- B0 (2) 取反:
!B0<P1> => B1<!P1> => B1<B0<N1>> (-3)
- B0 (-2) 取反:
!B0<N1> => P1 (1)
这种设计使得类型系统可以在编译期完成按位运算,配合加减法可以实现更复杂的类型级算术运算。注意实现中构造函数返回的值并不重要,重要的是类型级别的计算。