【PhysUnits】9 取负重载(negation.rs)
一、源码
这段代码是类型级二进制数(包括正数和负数)的取反和取负操作。它使用了类型系统来表示二进制数,并通过特质(trait)和泛型来实现递归操作。
use super::basic::{B0, B1, Z0, N1};
use core::ops::Neg;// ==================== 反码特质 ====================
pub(crate) trait Invert {type Output;
}impl Invert for Z0 { // Z0 (0) 的取反type Output = N1;
}impl Invert for N1 { // N1 (-1) 的取反type Output = Z0;
}impl<H: Invert> Invert for B0<H> { // B0<H> (...0) 的取反type Output = B1<H::Output>;
}impl<H: Invert> Invert for B1<H> { // B1<H> (...1) 的取反type Output = B0<H::Output>;
}// ==================== 运算符重载 ====================
impl Neg for Z0 { // Z0 (0) 的取负type Output = Z0;fn neg(self) -> Self::Output {Z0}
}impl Neg for N1 { // N1 (-1) 的取负type Output = B1<Z0>;fn neg(self) -> Self::Output {B1::new()}
}impl Neg for B1<Z0> { // 特化B1<Z0> (1) 的取负,防止负数最高位有B1type Output = N1;fn neg(self) -> Self::Output {N1}
}impl<H> Neg for B0<H>
whereH: Neg, // 只需要递归取负
{type Output = B0<<H as Neg>::Output>; // 递归调用Negfn neg(self) -> Self::Output {B0::new() // 递归调用Neg}
}impl<H> Neg for B1<H>
whereH: Invert,
{type Output = B1<<H as Invert>::Output>; // 没有进位了,高位取反fn neg(self) -> Self::Output {B1::new() }
}
二、基本类型导入
use super::basic::{B0, B1, Z0, N1};
use core::ops::Neg;
-
B0和B1表示二进制位0和1
-
Z0表示数值0,同时表示正数高位停止符
-
N1表示数值-1,同时表示负数高位停止符
-
Neg是Rust的标准负号运算符特质
三、反码特质Invert
pub(crate) trait Invert {type Output;
}
这个特质定义了类型级别的取反操作(按位取反),关联类型Output表示取反后的结果类型。
具体实现:
- Z0的取反:0的按位取反是-1
impl Invert for Z0 {type Output = N1;
}
- N1的取反:-1的按位取反是0
impl Invert for N1 {type Output = Z0;
}
- B0的取反:以0结尾的数取反后变为以1结尾,高位继续取反
impl<H: Invert> Invert for B0<H> {type Output = B1<H::Output>;
}
- B1的取反:以1结尾的数取反后变为以0结尾,高位继续取反
impl<H: Invert> Invert for B1<H> {type Output = B0<H::Output>;
}
四、负号运算符重载Neg
这部分实现了数值的取负操作(补码表示)。
具体实现:
- Z0的取负:0的负数还是0
impl Neg for Z0 {type Output = Z0;fn neg(self) -> Self::Output {Z0}
}
- N1的取负:-1的负数是1(用B1表示)
impl Neg for N1 {type Output = B1<Z0>;fn neg(self) -> Self::Output {B1::new()}
}
- B1的特化处理:1的负数是-1(防止负数最高位出现B1)
impl Neg for B1<Z0> {type Output = N1;fn neg(self) -> Self::Output {N1}
}
- B0的取负:以0结尾的数取负,高位直接取负,低位保持0
impl<H> Neg for B0<H>
whereH: Neg,
{type Output = B0<<H as Neg>::Output>;fn neg(self) -> Self::Output {B0::new()}
}
- B1的取负:以1结尾的数取负,高位取反(不需要进位)
impl<H> Neg for B1<H>
whereH: Invert,
{type Output = B1<<H as Invert>::Output>;fn neg(self) -> Self::Output {B1::new() }
}
五、关键点说明:
-
类型级编程:这是在编译期通过类型系统进行的计算,没有运行时开销。
-
二进制表示:
-
B0表示在类型H表示的二进制数后面加个0
-
B1表示在类型H表示的二进制数后面加个1
-
负数表示:使用补码形式,N1表示负号位及该位及更高位全1。
-
递归处理:通过泛型和特质约束实现递归操作。
六、示例说明:
-
取反操作(按位非):
-
!0 (Z0) → -1 (N1)
-
!-1 (N1) → 0 (Z0)
-
!B0 (2) → B1 (-3)
-
-
取负操作:
-
-0 (Z0) → 0 (Z0)
-
–1 (N1) → 1 (B1)
-
-B1 (1) → -1 (N1)
-
这段代码展示了Rust强大的类型系统能力,可以在编译期完成复杂的数值运算类型推导。