【unitrix】 4.13 类型级加一计算(add1.rs)
一、源码
这段代码实现了一个类型系统中的"加一"操作,通过Rust的特性(trait)和泛型编程来实现。
//! 类型级别的加一实现
//! 编制人: $ource
//! 修改版次:0版完成版
//! 本版次创建时间: 2025年7月2日
//! 最后修改时间: 无
//! 待完善问题:Float + 1 未实现
//! 实现规则:
//! 1. 基础类型:Z0(0)→P1(1), P1(1)→B0<P1>(2), N1(-1)→Z0(0)
//! 2. B0<H>→B1<H>,但当H=N1时特化为N1
//! 3. B1<H>→B0<H+1>(H+1不能为Z0)
//! 4. FixedPoint直接对整数部分加一
//! use crate::number::{Z0, P1, N1, B0, B1,FixedPoint,NonNegOne, NonZero, TypedInt,
};/// 类型加一操作特质
pub trait Add1: Copy + Default + 'static {type Output;
}// 基础类型实现
impl Add1 for Z0 {type Output = P1; // 0 + 1 = 1
}impl Add1 for P1 {type Output = B0<P1>; // 1 + 1 = 2
}impl Add1 for N1 {type Output = Z0; // -1 + 1 = 0
}// 二进制类型实现
impl<H: NonZero + NonNegOne> Add1 for B0<H> {type Output = B1<H>;
}impl Add1 for B0<N1> {type Output = N1; // -2 + 1 = -1
}impl<H: NonZero + NonNegOne + Add1<Output: NonZero>> Add1 for B1<H> {type Output = B0<H::Output>;
}// FixedPoint实现
impl<IntPart: TypedInt + Add1, FracPart: TypedInt> Add1 for FixedPoint<IntPart, FracPart> {type Output = FixedPoint< <IntPart as Add1>::Output, FracPart>;
}
二、源码分析
- 基本概念
-
这是一个类型级别的数字系统,支持正数、负数和二进制表示
-
实现了Add1 trait的类型可以执行"加一"操作
-
操作结果通过关联类型Output表示
- 类型定义
代码中使用了以下类型(来自crate::number):
-
Z0 - 表示数字0
-
P1 - 表示正1
-
N1 - 表示负1
-
B0, B1 - 二进制表示的数字,H是更高位的数字
-
FixedPoint<IntPart, FracPart> - 定点数,由整数部分和小数部分组成
- 实现规则
基础类型实现:
impl Add1 for Z0 {type Output = P1; // 0 + 1 = 1
}impl Add1 for P1 {type Output = B0<P1>; // 1 + 1 = 2 (二进制表示为10)
}impl Add1 for N1 {type Output = Z0; // -1 + 1 = 0
}
二进制类型实现:
- 对于B0(以0结尾的二进制数):
impl<H: NonZero + NonNegOne> Add1 for B0<H> {type Output = B1<H>; // 例如: 10(2) + 1 = 11(3)
}// 特例:当H是N1时
impl Add1 for B0<N1> {type Output = N1; // 10(二进制表示-2) + 1 = -1
}
- 对于B1(以1结尾的二进制数):
impl<H: NonZero + NonNegOne + Add1<Output: NonZero>> Add1 for B1<H> {type Output = B0<H::Output>; // 例如: 11(3) + 1 = 100(4)// 这里要求H加一的结果不能是Z0}
定点数实现:
impl<IntPart: Add1, FracPart> Add1 for FixedPoint<IntPart, FracPart> {type Output = FixedPoint<IntPart::Output, FracPart>;// 只对整数部分加一,小数部分保持不变
}
- Trait约束
-
NonZero - 表示非零类型
-
NonNegOne - 表示不是负一的类型(用于排除特殊情况)
-
Add1<Output: NonZero> - 表示加一操作的结果不是零
- 示例
-
Z0 + 1 = P1 (0 → 1)
-
P1 + 1 = B0 (1 → 2)
-
N1 + 1 = Z0 (-1 → 0)
-
B0 + 1 = B1 (2 → 3)
-
B1 + 1 = B0<B0> (3 → 4)
-
B0 + 1 = N1 (-2 → -1)
这个实现展示了如何在Rust类型系统上构建一个简单的数字系统,并通过trait实现类型级别的计算。这种技术常用于需要编译时计算或验证的场景。