一、源码
这段代码定义了一个通用的有符号整数(Signed Integer)抽象系统。
rust
use core::{cmp, fmt, ops};
/// Mathematical operations trait / 数学运算特性
///
/// Provides basic arithmetic operations for signed integers / 为有符号整数提供基本算术运算
pub trait MathOps:
Copy
+ fmt::Debug // For debugging purposes / 用于调试
+ fmt::Display
+ PartialEq
+ PartialOrd
+ Ord
+ From<bool>
+ ops::Add<Output = Self>
+ ops::Sub<Output = Self>
+ ops::Mul<Output = Self>
+ ops::Div<Output = Self>
+ ops::AddAssign
+ ops::SubAssign
+ ops::MulAssign
+ ops::DivAssign
{
/// Bit width of the integer (fixed to u32) / 整数位宽(固定使用u32)
const BITS: u32;
/// Constant values / 常数值
const MIN: Self; // Minimum value / 最小值
const MAX: Self; // Maximum value / 最大值
/// Absolute value / 绝对值
fn abs(self) -> Self;
/// Checked addition - returns None on overflow / 检查加法 - 溢出时返回None
fn checked_add(self, rhs: Self) -> Option<Self>;
/// Checked subtraction - returns None on overflow / 检查减法 - 溢出时返回None
fn checked_sub(self, rhs: Self) -> Option<Self>;
/// Checked multiplication - returns None on overflow / 检查乘法 - 溢出时返回None
fn checked_mul(self, rhs: Self) -> Option<Self>;
/// Wrapping addition / 环绕加法
fn wrapping_add(self, rhs: Self) -> Self;
/// Wrapping subtraction / 环绕减法
fn wrapping_sub(self, rhs: Self) -> Self;
/// Wrapping multiplication / 环绕乘法
fn wrapping_mul(self, rhs: Self) -> Self;
}
/// Bitwise operations trait / 位运算特性
///
/// Provides bit manipulation operations / 提供位操作功能
pub trait BitOps:
MathOps
+ ops::BitAnd<Output = Self>
+ ops::BitOr<Output = Self>
+ ops::BitXor<Output = Self>
+ ops::Not<Output = Self>
+ ops::BitAndAssign
+ ops::BitOrAssign
+ ops::BitXorAssign
{
/// Count the number of ones in binary representation / 计算二进制表示中1的个数
fn count_ones(self) -> u32;
/// Count the number of zeros in binary representation / 计算二进制表示中0的个数
fn count_zeros(self) -> u32;
/// Count leading zeros / 计算前导零的数量
fn leading_zeros(self) -> u32;
/// Count trailing zeros / 计算后导零的数量
fn trailing_zeros(self) -> u32;
}
/// Type casting system / 类型转换系统
///
/// Provides type conversion between different integer types / 提供不同整数类型之间的转换
pub trait CastFrom<T>: Sized {
/// Cast from type T to Self / 从类型T转换到Self
fn cast_from(val: T) -> Self;
}
/// Signed integer trait / 有符号整数特性
///
/// Combines all traits needed for signed integer operations / 组合了有符号整数操作所需的所有特性
pub trait SignedInt: BitOps + CastFrom<i16> + CastFrom<i32> + CastFrom<i64> {}
// Implement SignedInt for primitive types / 为基本类型实现SignedInt
impl SignedInt for i16 {}
impl SignedInt for i32 {}
impl SignedInt for i64 {}
// ========== i16 Implementation ==========
// ========== i16 实现 ==========
impl MathOps for i16 {
const BITS: u32 = 16;
const MIN: Self = i16::MIN;
const MAX: Self = i16::MAX;
fn abs(self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Calculating abs for i16: {}", self);
self.abs()
}
fn checked_add(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked add: {} + {}", self, rhs);
self.checked_add(rhs)
}
fn checked_sub(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked sub: {} - {}", self, rhs);
self.checked_sub(rhs)
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked mul: {} * {}", self, rhs);
self.checked_mul(rhs)
}
fn wrapping_add(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping add: {} + {}", self, rhs);
self.wrapping_add(rhs)
}
fn wrapping_sub(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping sub: {} - {}", self, rhs);
self.wrapping_sub(rhs)
}
fn wrapping_mul(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping mul: {} * {}", self, rhs);
self.wrapping_mul(rhs)
}
}
impl BitOps for i16 {
fn count_ones(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting ones in i16: {:016b}", self);
self.count_ones()
}
fn count_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting zeros in i16: {:016b}", self);
self.count_zeros()
}
fn leading_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting leading zeros in i16: {:016b}", self);
self.leading_zeros()
}
fn trailing_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting trailing zeros in i16: {:016b}", self);
self.trailing_zeros()
}
}
// ========== i32 Implementation ==========
// ========== i32 实现 ==========
impl MathOps for i32 {
const BITS: u32 = 32;
const MIN: Self = i32::MIN;
const MAX: Self = i32::MAX;
fn abs(self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Calculating abs for i32: {}", self);
self.abs()
}
fn checked_add(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked add: {} + {}", self, rhs);
self.checked_add(rhs)
}
fn checked_sub(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked sub: {} - {}", self, rhs);
self.checked_sub(rhs)
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked mul: {} * {}", self, rhs);
self.checked_mul(rhs)
}
fn wrapping_add(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping add: {} + {}", self, rhs);
self.wrapping_add(rhs)
}
fn wrapping_sub(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping sub: {} - {}", self, rhs);
self.wrapping_sub(rhs)
}
fn wrapping_mul(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping mul: {} * {}", self, rhs);
self.wrapping_mul(rhs)
}
}
impl BitOps for i32 {
fn count_ones(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting ones in i32: {:032b}", self);
self.count_ones()
}
fn count_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting zeros in i32: {:032b}", self);
self.count_zeros()
}
fn leading_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting leading zeros in i32: {:032b}", self);
self.leading_zeros()
}
fn trailing_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting trailing zeros in i32: {:032b}", self);
self.trailing_zeros()
}
}
// ========== i64 Implementation ==========
// ========== i64 实现 ==========
impl MathOps for i64 {
const BITS: u32 = 64;
const MIN: Self = i64::MIN;
const MAX: Self = i64::MAX;
fn abs(self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Calculating abs for i64: {}", self);
self.abs()
}
fn checked_add(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked add: {} + {}", self, rhs);
self.checked_add(rhs)
}
fn checked_sub(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked sub: {} - {}", self, rhs);
self.checked_sub(rhs)
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked mul: {} * {}", self, rhs);
self.checked_mul(rhs)
}
fn wrapping_add(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping add: {} + {}", self, rhs);
self.wrapping_add(rhs)
}
fn wrapping_sub(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping sub: {} - {}", self, rhs);
self.wrapping_sub(rhs)
}
fn wrapping_mul(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping mul: {} * {}", self, rhs);
self.wrapping_mul(rhs)
}
}
impl BitOps for i64 {
fn count_ones(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting ones in i64: {:064b}", self);
self.count_ones()
}
fn count_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting zeros in i64: {:064b}", self);
self.count_zeros()
}
fn leading_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting leading zeros in i64: {:064b}", self);
self.leading_zeros()
}
fn trailing_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting trailing zeros in i64: {:064b}", self);
self.trailing_zeros()
}
}
// Implement CastFrom for primitive type conversions / 为原生类型转换实现CastFrom
impl CastFrom<i16> for i32 {
fn cast_from(val: i16) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Casting i16 to i32: {}", val);
val as i32
}
}
impl CastFrom<i16> for i64 {
fn cast_from(val: i16) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Casting i16 to i64: {}", val);
val as i64
}
}
impl CastFrom<i32> for i64 {
fn cast_from(val: i32) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Casting i32 to i64: {}", val);
val as i64
}
}
// Scalar implementation / Scalar实现
use super::Scalar;
impl<T: SignedInt> Scalar<T> {
/// Zero value / 零值
pub const ZERO: Self = Scalar(T::cast_from(0));
/// One value / 一值
pub const ONE: Self = Scalar(T::cast_from(1));
/// Negative one value / 负一值
pub const NEG_ONE: Self = Scalar(T::cast_from(-1));
/// Create a new Scalar / 创建一个新的Scalar
pub fn new(value: T) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Creating new Scalar with value: {}", value);
Self(value)
}
/// Get inner value / 获取内部值
pub fn get(self) -> T {
#[cfg(debug_assertions)]
println!("[DEBUG] Getting inner value of Scalar");
self.0
}
// ========== Common methods ==========
// ========== 通用方法 ==========
/// Absolute value / 绝对值
pub fn abs(self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Calculating abs for Scalar");
Self(self.0.abs())
}
/// Checked addition / 检查加法
pub fn checked_add(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked add for Scalar: {} + {}", self.0, rhs.0);
self.0.checked_add(rhs.0).map(Self)
}
/// Checked subtraction / 检查减法
pub fn checked_sub(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked sub for Scalar: {} - {}", self.0, rhs.0);
self.0.checked_sub(rhs.0).map(Self)
}
/// Checked multiplication / 检查乘法
pub fn checked_mul(self, rhs: Self) -> Option<Self> {
#[cfg(debug_assertions)]
println!("[DEBUG] Checked mul for Scalar: {} * {}", self.0, rhs.0);
self.0.checked_mul(rhs.0).map(Self)
}
/// Wrapping addition / 环绕加法
pub fn wrapping_add(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping add for Scalar: {} + {}", self.0, rhs.0);
Self(self.0.wrapping_add(rhs.0))
}
/// Wrapping subtraction / 环绕减法
pub fn wrapping_sub(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping sub for Scalar: {} - {}", self.0, rhs.0);
Self(self.0.wrapping_sub(rhs.0))
}
/// Wrapping multiplication / 环绕乘法
pub fn wrapping_mul(self, rhs: Self) -> Self {
#[cfg(debug_assertions)]
println!("[DEBUG] Wrapping mul for Scalar: {} * {}", self.0, rhs.0);
Self(self.0.wrapping_mul(rhs.0))
}
/// Count ones in binary representation / 计算二进制表示中1的个数
pub fn count_ones(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting ones in Scalar");
self.0.count_ones()
}
/// Count zeros in binary representation / 计算二进制表示中0的个数
pub fn count_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting zeros in Scalar");
self.0.count_zeros()
}
/// Count leading zeros / 计算前导零的数量
pub fn leading_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting leading zeros in Scalar");
self.0.leading_zeros()
}
/// Count trailing zeros / 计算后导零的数量
pub fn trailing_zeros(self) -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Counting trailing zeros in Scalar");
self.0.trailing_zeros()
}
// ========== Type conversion methods ==========
// ========== 类型转换方法 ==========
/// Cast from another type / 从其他类型转换
pub fn cast_from<U: SignedInt>(val: U) -> Self
where
T: CastFrom<U>,
{
#[cfg(debug_assertions)]
println!("[DEBUG] Casting to Scalar from value: {}", val);
Self(T::cast_from(val))
}
/// Cast to another type / 转换为其他类型
pub fn cast_to<U: SignedInt>(self) -> Scalar<U>
where
U: CastFrom<T>,
{
#[cfg(debug_assertions)]
println!("[DEBUG] Casting Scalar to another type");
Scalar(U::cast_from(self.0))
}
}
// ========== Operator Overloading ==========
// ========== 运算符重载 ==========
impl<T: SignedInt> ops::Add for Scalar<T> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] Adding Scalars: {} + {}", self.0, rhs.0);
Self(self.0 + rhs.0)
}
}
impl<T: SignedInt> ops::Sub for Scalar<T> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] Subtracting Scalars: {} - {}", self.0, rhs.0);
Self(self.0 - rhs.0)
}
}
impl<T: SignedInt> ops::Mul for Scalar<T> {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] Multiplying Scalars: {} * {}", self.0, rhs.0);
Self(self.0 * rhs.0)
}
}
impl<T: SignedInt> ops::Div for Scalar<T> {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] Dividing Scalars: {} / {}", self.0, rhs.0);
Self(self.0 / rhs.0)
}
}
impl<T: SignedInt> ops::AddAssign for Scalar<T> {
fn add_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] AddAssign for Scalars: {} += {}", self.0, rhs.0);
self.0 += rhs.0;
}
}
impl<T: SignedInt> ops::SubAssign for Scalar<T> {
fn sub_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] SubAssign for Scalars: {} -= {}", self.0, rhs.0);
self.0 -= rhs.0;
}
}
impl<T: SignedInt> ops::MulAssign for Scalar<T> {
fn mul_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] MulAssign for Scalars: {} *= {}", self.0, rhs.0);
self.0 *= rhs.0;
}
}
impl<T: SignedInt> ops::DivAssign for Scalar<T> {
fn div_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] DivAssign for Scalars: {} /= {}", self.0, rhs.0);
self.0 /= rhs.0;
}
}
impl<T: SignedInt> ops::BitAnd for Scalar<T> {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] BitAnd for Scalars: {:b} & {:b}", self.0, rhs.0);
Self(self.0 & rhs.0)
}
}
impl<T: SignedInt> ops::BitOr for Scalar<T> {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] BitOr for Scalars: {:b} | {:b}", self.0, rhs.0);
Self(self.0 | rhs.0)
}
}
impl<T: SignedInt> ops::BitXor for Scalar<T> {
type Output = Self;
fn bitxor(self, rhs: Self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] BitXor for Scalars: {:b} ^ {:b}", self.0, rhs.0);
Self(self.0 ^ rhs.0)
}
}
impl<T: SignedInt> ops::Not for Scalar<T> {
type Output = Self;
fn not(self) -> Self::Output {
#[cfg(debug_assertions)]
println!("[DEBUG] Not for Scalar: !{:b}", self.0);
Self(!self.0)
}
}
impl<T: SignedInt> ops::BitAndAssign for Scalar<T> {
fn bitand_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] BitAndAssign for Scalars: {:b} &= {:b}", self.0, rhs.0);
self.0 &= rhs.0;
}
}
impl<T: SignedInt> ops::BitOrAssign for Scalar<T> {
fn bitor_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] BitOrAssign for Scalars: {:b} |= {:b}", self.0, rhs.0);
self.0 |= rhs.0;
}
}
impl<T: SignedInt> ops::BitXorAssign for Scalar<T> {
fn bitxor_assign(&mut self, rhs: Self) {
#[cfg(debug_assertions)]
println!("[DEBUG] BitXorAssign for Scalars: {:b} ^= {:b}", self.0, rhs.0);
self.0 ^= rhs.0;
}
}
// ========== Formatting ==========
// ========== 格式化输出 ==========
impl<T: SignedInt + fmt::Display> fmt::Display for Scalar<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[cfg(debug_assertions)]
println!("[DEBUG] Formatting Scalar for display");
write!(f, "{}", self.0)
}
}
// ========== Constant implementations ==========
// ========== 常量实现 ==========
impl<T: SignedInt> Scalar<T> {
/// Minimum value / 最小值
pub const MIN: Self = Self(T::MIN);
/// Maximum value / 最大值
pub const MAX: Self = Self(T::MAX);
/// Get bit width / 获取位宽
pub fn bits() -> u32 {
#[cfg(debug_assertions)]
println!("[DEBUG] Getting bit width for Scalar type");
T::BITS
}
}
二、代码分析
1. 核心特性(Traits)
MathOps
数学运算特性
为有符号整数提供基本算术运算,要求实现以下功能:
- 基本运算:加、减、乘、除
- 赋值运算:+=、-=、*=、/=
- 常量:BITS(位宽)、MIN(最小值)、MAX(最大值)
- 方法:abs(绝对值)、checked_(检查运算)、wrapping_(环绕运算)
rust
pub trait MathOps:
Copy
+ fmt::Debug
+ ops::Add<Output = Self>
+ ops::Sub<Output = Self>
{
const BITS: u32;
const MIN: Self;
const MAX: Self;
fn abs(self) -> Self;
fn checked_add(self, rhs: Self) -> Option<Self>;
}
BitOps
位运算特性
扩展MathOps
,提供位操作功能:
- 位运算:与、或、异或、非
- 位赋值运算:&=、|=、^=
- 方法:count_ones(计算1的个数)、count_zeros(计算0的个数)、leading_zeros(前导零)、trailing_zeros(后导零)
rust
pub trait BitOps: MathOps
+ ops::BitAnd<Output = Self>
+ ops::BitOr<Output = Self>
{
fn count_ones(self) -> u32;
fn leading_zeros(self) -> u32;
}
CastFrom
类型转换特性
提供不同类型之间的转换功能
rust
pub trait CastFrom<T>: Sized {
fn cast_from(val: T) -> Self;
}
SignedInt
有符号整数特性
组合了上述所有特性,并为i16、i32、i64原生类型实现了该特性
2. 具体实现
为三种原生有符号整数类型(i16、i32、i64)实现了上述所有特性:
rust
impl MathOps for i32 {
const BITS: u32 = 32;
const MIN: Self = i32::MIN;
const MAX: Self = i32::MAX;
fn abs(self) -> Self {
self.abs()
}
}
3. Scalar
包装类型
Scalar<T>
是一个泛型包装结构,其中T必须实现SignedInt
特性。
rust
pub struct Scalar<T: SignedInt>(T);
impl<T: SignedInt> Scalar<T> {
pub fn new(value: T) -> Self {
Self(value)
}
}