当前位置: 首页 > ds >正文

【PhysUnits】2.2 Scalar<T> 标量元组结构体(scalar/mod.rs)

一、源码

这段代码定义了一个通用的有符号整数(Signed Integer)抽象系统。

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 / 检查加法 - 溢出时返回Nonefn checked_add(self, rhs: Self) -> Option<Self>;/// Checked subtraction - returns None on overflow / 检查减法 - 溢出时返回Nonefn checked_sub(self, rhs: Self) -> Option<Self>;/// Checked multiplication - returns None on overflow / 检查乘法 - 溢出时返回Nonefn 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转换到Selffn 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 / 创建一个新的Scalarpub 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 whereT: 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> whereU: 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_(环绕运算)
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(后导零)
pub trait BitOps: MathOps+ ops::BitAnd<Output = Self>+ ops::BitOr<Output = Self>
{fn count_ones(self) -> u32;fn leading_zeros(self) -> u32;
}

CastFrom 类型转换特性

提供不同类型之间的转换功能

pub trait CastFrom<T>: Sized {fn cast_from(val: T) -> Self;
}

SignedInt 有符号整数特性

组合了上述所有特性,并为i16、i32、i64原生类型实现了该特性

2. 具体实现

为三种原生有符号整数类型(i16、i32、i64)实现了上述所有特性:

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特性。

pub struct Scalar<T: SignedInt>(T);impl<T: SignedInt> Scalar<T> {pub fn new(value: T) -> Self {Self(value)}
}
http://www.xdnf.cn/news/4662.html

相关文章:

  • 文章记单词 | 第66篇(六级)
  • 数据库 postgresql 修改密码 sh
  • 大模型赋能:2D 写实数字人开启实时交互新时代
  • 利用并行处理提高LabVIEW程序执行速度
  • 详解0-1背包的状态转移表
  • 前端实现文件下载
  • 案例分享 | 攻克ADAS开发测试难题,实现单元动态测试新突破
  • 力扣刷题Day 34:随机链表的复制(138)
  • MySQL大数据量查询优化
  • angular的cdk组件库
  • 苍穹外卖(订单状态定时处理、来单提醒和客户催单)
  • hadoop中的序列化和反序列化(4)
  • 快连LetsVPN安装指南
  • LeetCode20_有效的括号
  • 第2章 算法分析基础
  • 记录一下spring-cloud-starter-alibaba-nacos-config 2023.0.3.2与springboot版本及配置问题
  • 如何创建RDD
  • 【AI News | 20250507】每日AI进展
  • MySQL中为什么使用B+树结构、B+树和普通的平衡树的区别
  • Spark jdbc写入崖山等国产数据库失败问题
  • Linux/AndroidOS中进程间的通信线程间的同步 - 共享内存
  • AI 实践探索:辅助生成测试用例
  • 高性能轻量级Rust HTTP服务器框架Hyperlane:开启网络服务开发新体验
  • NLP核心技术解析:大模型与分词工具的协同工作原理
  • 排序算法——桶排序
  • 注意力机制(Attention)
  • 【关于ESP8266下载固件库的问题】
  • C++ 析构函数
  • 【Ollama】docker离线部署Ollama+deepseek
  • 从机器人到调度平台:超低延迟RTMP|RTSP播放器系统级部署之道