【unitrix数间混合计算】2.4 二进制整数标准化处理(src/number/normalize/int_normalize.rs)
一、源码
这段代码定义了二进制整数的标准化处理逻辑,使用Rust的trait系统在编译期完成数值规范化。
use crate::number::{Null, O, I, BinInt, Bit, IsBinInt};
// ============== 整数标准化 ==============
pub trait IntNormalize<L: Bit> {type Output: Default + IsBinInt;fn int_normalize(self, bit: L) -> Self::Output;
}// 基础情况:Null + X → BinInt<Null, X>
impl<X: Bit> IntNormalize<X> for Null {type Output = BinInt<Null, X>;fn int_normalize(self, _: X) -> Self::Output {Default::default()}
}// H = BinInt<Null,X> + L=X → 保持B<Null,X> (X 可以是 O 或 I)
impl<X: Bit> IntNormalize<X> for BinInt<Null, X>
whereBinInt<Null, X>: Default,
{type Output = Self;fn int_normalize(self, _: X) -> Self::Output {self}
}// H = BinInt<Null,I> + L=O → BinInt<BinInt<Null,I>,O>
impl IntNormalize<O> for BinInt<Null, I> {type Output = BinInt<Self, O>;fn int_normalize(self, _: O) -> Self::Output {Default::default()}
}// H = BinInt<Null,O> + L=I → BinInt<BinInt<Null,O>,I>
impl IntNormalize<I> for BinInt<Null, O> {type Output = BinInt<Self, I>;fn int_normalize(self, _: I) -> Self::Output {Default::default()}
}// 通用整数情况:保持原结构 (H已标准化)
impl<HH, HL: Bit, L: Bit, LL: Bit> IntNormalize<LL> for BinInt<BinInt<HH, HL>, L>
where Self: IsBinInt,
{type Output = BinInt<Self, LL>;fn int_normalize(self, rhs: LL) -> Self::Output {Default::default()}
}pub type IfB0<H> = <H as IntNormalize<O>>::Output; // L=0时的标准化结果
pub type IfB1<H> = <H as IntNormalize<I>>::Output; // L=1时的标准化结果
二、基本结构:
pub trait IntNormalize<L: Bit> {type Output: Default + IsBinInt;fn int_normalize(self, bit: L) -> Self::Output;
}
-
定义IntNormalize trait,泛型参数L必须是Bit类型(O或I)
-
关联类型Output必须实现Default和IsBinInt
-
int_normalize方法接收一个bit位,返回标准化后的整数
三、基础标准化规则:
impl<X: Bit> IntNormalize<X> for Null {type Output = BinInt<Null, X>;fn int_normalize(self, _: X) -> Self::Output {Default::default()}
}
-
将Null + bit转换为BinInt<Null, bit>
-
这是构建二进制整数的起点
四、整数保持规则:
impl<X: Bit> IntNormalize<X> for BinInt<Null, X> {type Output = Self;fn int_normalize(self, _: X) -> Self::Output { self }
}
- 已标准化的整数(如BinInt<Null, I>)追加相同bit时保持原样
五、位扩展规则:
impl IntNormalize<O> for BinInt<Null, I> {type Output = BinInt<Self, O>;fn int_normalize(self, _: O) -> Self::Output { Default::default() }
}
- BinInt<Null, I> + O → BinInt<BinInt<Null,I>, O>
- 例如:1(I)追加0变为10(2)
六、通用情况处理:
impl<HH, HL: Bit, L: Bit, LL: Bit> IntNormalize<LL> for BinInt<BinInt<HH, HL>, L> {type Output = BinInt<Self, LL>;fn int_normalize(self, _: LL) -> Self::Output { Default::default() }
}
-
对已标准化的多bit整数,直接追加新bit位
-
保持原有的二进制结构
七、类型别名:
pub type IfB0<H> = <H as IntNormalize<O>>::Output;
pub type IfB1<H> = <H as IntNormalize<I>>::Output;
-
IfB0:类型H追加0后的结果类型
-
IfB1:类型H追加1后的结果类型
八、典型用例:
type P1 = BinInt<Null, I>; // 1
type P2 = IfB0<P1>; // 10 (2)
type P3 = IfB1<P1>; // 11 (3)
这段代码实现了:
-
二进制整数的类型安全构造
-
自动标准化处理(无冗余表示)
-
编译期数值计算
-
支持任意长度的二进制数扩展