【libm】2整数接口(int_traits.rs)

一、源码

int_traits.rs文件定义了两个核心 trait MinInt 和 Int,为整数类型提供统一的抽象接口,并通过宏为所有原生整数类型(i8 ~ i128/u8 ~ u128)实现这些 trait。

use core::{cmp, fmt, ops};/// Minimal integer implementations needed on all integer types, including wide integers.
pub trait MinInt:Copy+ fmt::Debug+ ops::BitOr<Output = Self>+ ops::Not<Output = Self>+ ops::Shl<u32, Output = Self>
{/// Type with the same width but other signednesstype OtherSign: MinInt;/// Unsigned version of Selftype Unsigned: MinInt;/// If `Self` is a signed integerconst SIGNED: bool;/// The bitwidth of the int typeconst BITS: u32;const ZERO: Self;const ONE: Self;const MIN: Self;const MAX: Self;
}/// Access the associated `OtherSign` type from an int (helper to avoid ambiguous associated
/// types).
pub type OtherSign<I> = <I as MinInt>::OtherSign;/// Trait for some basic operations on integers
#[allow(dead_code)]
pub trait Int:MinInt+ fmt::Display+ fmt::Binary+ fmt::LowerHex+ PartialEq+ PartialOrd+ ops::AddAssign+ ops::SubAssign+ ops::BitAndAssign+ ops::BitOrAssign+ ops::BitXorAssign+ ops::ShlAssign<i32>+ ops::ShlAssign<u32>+ ops::ShrAssign<u32>+ ops::ShrAssign<i32>+ ops::Add<Output = Self>+ ops::Sub<Output = Self>+ ops::Mul<Output = Self>+ ops::Div<Output = Self>+ ops::Shl<i32, Output = Self>+ ops::Shl<u32, Output = Self>+ ops::Shr<i32, Output = Self>+ ops::Shr<u32, Output = Self>+ ops::BitXor<Output = Self>+ ops::BitAnd<Output = Self>+ cmp::Ord+ From<bool>+ CastFrom<i32>+ CastFrom<u16>+ CastFrom<u32>+ CastFrom<u8>+ CastFrom<usize>+ CastInto<i32>+ CastInto<u16>+ CastInto<u32>+ CastInto<u8>+ CastInto<usize>
{fn signed(self) -> OtherSign<Self::Unsigned>;fn unsigned(self) -> Self::Unsigned;fn from_unsigned(unsigned: Self::Unsigned) -> Self;fn abs(self) -> Self;fn from_bool(b: bool) -> Self;/// Prevents the need for excessive conversions between signed and unsignedfn logical_shr(self, other: u32) -> Self;/// Absolute difference between two integers.fn abs_diff(self, other: Self) -> Self::Unsigned;// copied from primitive integers, but put in a traitfn is_zero(self) -> bool;fn checked_add(self, other: Self) -> Option<Self>;fn checked_sub(self, other: Self) -> Option<Self>;fn wrapping_neg(self) -> Self;fn wrapping_add(self, other: Self) -> Self;fn wrapping_mul(self, other: Self) -> Self;fn wrapping_sub(self, other: Self) -> Self;fn wrapping_shl(self, other: u32) -> Self;fn wrapping_shr(self, other: u32) -> Self;fn rotate_left(self, other: u32) -> Self;fn overflowing_add(self, other: Self) -> (Self, bool);fn overflowing_sub(self, other: Self) -> (Self, bool);fn leading_zeros(self) -> u32;fn ilog2(self) -> u32;
}macro_rules! int_impl_common {($ty:ty) => {fn from_bool(b: bool) -> Self {b as $ty}fn logical_shr(self, other: u32) -> Self {Self::from_unsigned(self.unsigned().wrapping_shr(other))}fn is_zero(self) -> bool {self == Self::ZERO}fn checked_add(self, other: Self) -> Option<Self> {self.checked_add(other)}fn checked_sub(self, other: Self) -> Option<Self> {self.checked_sub(other)}fn wrapping_neg(self) -> Self {<Self>::wrapping_neg(self)}fn wrapping_add(self, other: Self) -> Self {<Self>::wrapping_add(self, other)}fn wrapping_mul(self, other: Self) -> Self {<Self>::wrapping_mul(self, other)}fn wrapping_sub(self, other: Self) -> Self {<Self>::wrapping_sub(self, other)}fn wrapping_shl(self, other: u32) -> Self {<Self>::wrapping_shl(self, other)}fn wrapping_shr(self, other: u32) -> Self {<Self>::wrapping_shr(self, other)}fn rotate_left(self, other: u32) -> Self {<Self>::rotate_left(self, other)}fn overflowing_add(self, other: Self) -> (Self, bool) {<Self>::overflowing_add(self, other)}fn overflowing_sub(self, other: Self) -> (Self, bool) {<Self>::overflowing_sub(self, other)}fn leading_zeros(self) -> u32 {<Self>::leading_zeros(self)}fn ilog2(self) -> u32 {// On our older MSRV, this resolves to the trait method. Which won't actually work,// but this is only called behind other gates.#[allow(clippy::incompatible_msrv)]<Self>::ilog2(self)}};
}macro_rules! int_impl {($ity:ty, $uty:ty) => {impl MinInt for $uty {type OtherSign = $ity;type Unsigned = $uty;const BITS: u32 = <Self as MinInt>::ZERO.count_zeros();const SIGNED: bool = Self::MIN != Self::ZERO;const ZERO: Self = 0;const ONE: Self = 1;const MIN: Self = <Self>::MIN;const MAX: Self = <Self>::MAX;}impl Int for $uty {fn signed(self) -> $ity {self as $ity}fn unsigned(self) -> Self {self}fn abs(self) -> Self {unimplemented!()}// It makes writing macros easier if this is implemented for both signed and unsigned#[allow(clippy::wrong_self_convention)]fn from_unsigned(me: $uty) -> Self {me}fn abs_diff(self, other: Self) -> Self {self.abs_diff(other)}int_impl_common!($uty);}impl MinInt for $ity {type OtherSign = $uty;type Unsigned = $uty;const BITS: u32 = <Self as MinInt>::ZERO.count_zeros();const SIGNED: bool = Self::MIN != Self::ZERO;const ZERO: Self = 0;const ONE: Self = 1;const MIN: Self = <Self>::MIN;const MAX: Self = <Self>::MAX;}impl Int for $ity {fn signed(self) -> Self {self}fn unsigned(self) -> $uty {self as $uty}fn abs(self) -> Self {self.abs()}fn from_unsigned(me: $uty) -> Self {me as $ity}fn abs_diff(self, other: Self) -> $uty {self.abs_diff(other)}int_impl_common!($ity);}};
}int_impl!(isize, usize);
int_impl!(i8, u8);
int_impl!(i16, u16);
int_impl!(i32, u32);
int_impl!(i64, u64);
int_impl!(i128, u128);/// Trait for integers twice the bit width of another integer. This is implemented for all
/// primitives except for `u8`, because there is not a smaller primitive.
pub trait DInt: MinInt {/// Integer that is half the bit width of the integer this trait is implemented fortype H: HInt<D = Self>;/// Returns the low half of `self`fn lo(self) -> Self::H;/// Returns the high half of `self`fn hi(self) -> Self::H;/// Returns the low and high halves of `self` as a tuplefn lo_hi(self) -> (Self::H, Self::H) {(self.lo(), self.hi())}/// Constructs an integer using lower and higher half parts#[allow(unused)]fn from_lo_hi(lo: Self::H, hi: Self::H) -> Self {lo.zero_widen() | hi.widen_hi()}
}/// Trait for integers half the bit width of another integer. This is implemented for all
/// primitives except for `u128`, because it there is not a larger primitive.
pub trait HInt: Int {/// Integer that is double the bit width of the integer this trait is implemented fortype D: DInt<H = Self> + MinInt;// NB: some of the below methods could have default implementations (e.g. `widen_hi`), but for// unknown reasons this can cause infinite recursion when optimizations are disabled. See// <https://github.com/rust-lang/compiler-builtins/pull/707> for context./// Widens (using default extension) the integer to have double bit widthfn widen(self) -> Self::D;/// Widens (zero extension only) the integer to have double bit width. This is needed to get/// around problems with associated type bounds (such as `Int<Othersign: DInt>`) being unstablefn zero_widen(self) -> Self::D;/// Widens the integer to have double bit width and shifts the integer into the higher bits#[allow(unused)]fn widen_hi(self) -> Self::D;/// Widening multiplication with zero widening. This cannot overflow.fn zero_widen_mul(self, rhs: Self) -> Self::D;/// Widening multiplication. This cannot overflow.fn widen_mul(self, rhs: Self) -> Self::D;
}macro_rules! impl_d_int {($($X:ident $D:ident),*) => {$(impl DInt for $D {type H = $X;fn lo(self) -> Self::H {self as $X}fn hi(self) -> Self::H {(self >> <$X as MinInt>::BITS) as $X}})*};
}macro_rules! impl_h_int {($($H:ident $uH:ident $X:ident),*) => {$(impl HInt for $H {type D = $X;fn widen(self) -> Self::D {self as $X}fn zero_widen(self) -> Self::D {(self as $uH) as $X}fn zero_widen_mul(self, rhs: Self) -> Self::D {self.zero_widen().wrapping_mul(rhs.zero_widen())}fn widen_mul(self, rhs: Self) -> Self::D {self.widen().wrapping_mul(rhs.widen())}fn widen_hi(self) -> Self::D {(self as $X) << <Self as MinInt>::BITS}})*};
}impl_d_int!(u8 u16, u16 u32, u32 u64, u64 u128, i8 i16, i16 i32, i32 i64, i64 i128);
impl_h_int!(u8 u8 u16,u16 u16 u32,u32 u32 u64,u64 u64 u128,i8 u8 i16,i16 u16 i32,i32 u32 i64,i64 u64 i128
);/// Trait to express (possibly lossy) casting of integers
pub trait CastInto<T: Copy>: Copy {/// By default, casts should be exact.fn cast(self) -> T;/// Call for casts that are expected to truncate.fn cast_lossy(self) -> T;
}pub trait CastFrom<T: Copy>: Copy {/// By default, casts should be exact.fn cast_from(value: T) -> Self;/// Call for casts that are expected to truncate.fn cast_from_lossy(value: T) -> Self;
}impl<T: Copy, U: CastInto<T> + Copy> CastFrom<U> for T {fn cast_from(value: U) -> Self {value.cast()}fn cast_from_lossy(value: U) -> Self {value.cast_lossy()}
}macro_rules! cast_into {($ty:ty) => {cast_into!($ty; usize, isize, u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);};($ty:ty; $($into:ty),*) => {$(impl CastInto<$into> for $ty {fn cast(self) -> $into {// All we can really do to enforce casting rules is check the rules when in// debug mode.#[cfg(not(feature = "compiler-builtins"))]debug_assert!(<$into>::try_from(self).is_ok(), "failed cast from {self}");self as $into}fn cast_lossy(self) -> $into {self as $into}})*};
}macro_rules! cast_into_float {($ty:ty) => {#[cfg(f16_enabled)]cast_into_float!($ty; f16);cast_into_float!($ty; f32, f64);#[cfg(f128_enabled)]cast_into_float!($ty; f128);};($ty:ty; $($into:ty),*) => {$(impl CastInto<$into> for $ty {fn cast(self) -> $into {#[cfg(not(feature = "compiler-builtins"))]debug_assert_eq!(self as $into as $ty, self, "inexact float cast");self as $into}fn cast_lossy(self) -> $into {self as $into}})*};
}cast_into!(usize);
cast_into!(isize);
cast_into!(u8);
cast_into!(i8);
cast_into!(u16);
cast_into!(i16);
cast_into!(u32);
cast_into!(i32);
cast_into!(u64);
cast_into!(i64);
cast_into!(u128);
cast_into!(i128);cast_into_float!(i8);
cast_into_float!(i16);
cast_into_float!(i32);
cast_into_float!(i64);
cast_into_float!(i128);
  1. 核心 Trait:MinInt
    定义整数类型的最小通用操作集合:
pub trait MinInt: Copy + Debug + BitOr + Not + Shl<u32> {type OtherSign: MinInt;  // 同宽度的相反符号类型(如 `i32` 的 `OtherSign` 是 `u32`)type Unsigned: MinInt;   // 无符号版本const SIGNED: bool;      // 是否为有符号整数const BITS: u32;         // 位数(如 `i32` 是 32)const ZERO: Self;        // 0 值const ONE: Self;         // 1 值const MIN: Self;         // 最小值const MAX: Self;         // 最大值
}
  1. 扩展 Trait:Int
    在 MinInt 基础上扩展更多操作:
pub trait Int: MinInt + Display + Binary + AddAssign + ... {fn signed(self) -> OtherSign<Self::Unsigned>;  // 转为有符号类型fn unsigned(self) -> Self::Unsigned;           // 转为无符号类型fn abs(self) -> Self;                          // 绝对值// 位操作fn logical_shr(self, other: u32) -> Self;      // 逻辑右移(高位补 0)fn rotate_left(self, other: u32) -> Self;      // 循环左移// 溢出安全运算fn wrapping_add(self, other: Self) -> Self;fn checked_mul(self, other: Self) -> Option<Self>;// 工具方法fn leading_zeros(self) -> u32;fn ilog2(self) -> u32;
}
  1. 宏实现
    通过宏 int_impl! 为所有原生整数类型实现 MinInt 和 Int:
int_impl!(i32, u32);  // 为 i32/u32 生成实现

宏展开后:

  • 为 u32 实现 MinInt,关联 OtherSign = i32。

  • 为 i32 实现 MinInt,关联 OtherSign = u32。

  • 实现所有 Int 方法(委托给原生整数的方法,如 u32::wrapping_add)。

  1. 宽/窄整数 Trait
    DInt(双宽度整数)
pub trait DInt: MinInt {type H: HInt<D = Self>;  // 半宽度类型(如 `u64` 的 `H` 是 `u32`)fn lo(self) -> Self::H;   // 取低半部分fn hi(self) -> Self::H;   // 取高半部分fn from_lo_hi(lo: Self::H, hi: Self::H) -> Self;  // 合并高低部分
}

HInt(半宽度整数)

pub trait HInt: Int {type D: DInt<H = Self>;  // 双宽度类型(如 `u32` 的 `D` 是 `u64`)fn widen(self) -> Self::D;       // 符号扩展fn zero_widen(self) -> Self::D;  // 零扩展fn widen_mul(self, rhs: Self) -> Self::D;  // 扩展乘法
}

宏实现

impl_d_int!(u32 u64);  // 为 u64 实现 DInt,关联 H = u32
impl_h_int!(u32 u32 u64);  // 为 u32 实现 HInt,关联 D = u64
  1. 类型转换 Trait
    CastInto/CastFrom
    提供安全的类型转换接口:
pub trait CastInto<T: Copy>: Copy {fn cast(self) -> T;          // 精确转换(失败时 debug 断言)fn cast_lossy(self) -> T;    // 允许截断
}// 为所有整数实现 CastInto
cast_into!(u32; u8, u16, u64);  // u32 可转换为 u8/u16/u64

二、设计亮点

  1. 统一抽象:通过 trait 为所有整数类型提供一致接口。

  2. 零成本:宏展开后直接调用原生整数操作,无运行时开销。

  3. 类型安全:

  • 严格区分有/无符号类型(通过 OtherSign)。

  • 转换方法提供编译时检查。

  1. 扩展性:支持自定义整数类型实现这些 trait。

###三、使用示例

let x: u32 = 42;
let y: i32 = x.signed();  // 转为有符号
let z: u64 = x.zero_widen();  // 零扩展为 u64let (lo, hi) = 0x12345678u32.lo_hi();  // 拆分为低 16 位和高 16 位

三、总结

这段代码是数学库的基础设施,通过 trait 和宏实现了:

  • 整数类型的通用操作抽象。

  • 安全且高效的类型转换。

  • 宽/窄整数的互操作。
    为上层算法(如浮点数解析、大数运算)提供了类型安全的底层支持。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/81762.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WebSocket实战经验

WebSocket实战经验详解 WebSocket基础概念 #mermaid-svg-sdkZP4UrWBpk2Hco {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-sdkZP4UrWBpk2Hco .error-icon{fill:#552222;}#mermaid-svg-sdkZP4UrWBpk2Hco .error-tex…

【C/C++】MQTT

文章目录 MQTT 协议1 基本概念2 核心特性3 核心组件4 C 简易实现&#xff08;基于 Paho MQTT 库&#xff09;环境准备示例代码 不同mqtt对比关键差异说明 MQTT 协议 1 基本概念 MQTT&#xff08;Message Queuing Telemetry Transport&#xff09;是一种轻量级的发布/订阅模式…

《Java 高并发程序设计》笔记

&#x1f4a1; 根据 遗忘曲线&#xff1a;如果没有记录和回顾&#xff0c;6天后便会忘记75%的内容 读书笔记正是帮助你记录和回顾的工具&#xff0c;不必拘泥于形式&#xff0c;其核心是&#xff1a;记录、翻看、思考 ::: 书名Java 高并发程序设计作者葛一鸣、郭超状态已读完简…

Fine Structure-Aware Sampling(AAAI 2024)论文笔记和启发

文章目录 本文解决的问题本文提出的方法以及启发 本文解决的问题 传统的基于Pifu的人体三维重建一般通过采样来进行学习。一般选择的采样方法是空间采样&#xff0c;具体是在surface的表面随机位移进行样本的生成。这里的采样是同时要在XYZ三个方向上进行。所以这导致了一个问…

【AI面试准备】性能测试与AI模型结合应用指南

面试题&#xff1a; 性能测试&#xff1a;AI模型预测系统瓶颈&#xff08;如LoadRunnerAI模块&#xff09;。 性能测试与AI模型预测系统瓶颈的结合是当前软件工程和运维领域的重要趋势&#xff0c;能够显著提升系统优化效率和问题预测能力。以下从核心概念、技术实现、快速掌握…

Spring MVC 与 FreeMarker 整合

以下是 Spring MVC 与 FreeMarker 整合的详细步骤&#xff0c;包含配置和代码示例&#xff1a; 1. 添加依赖 在 pom.xml 中引入 Spring MVC 和 FreeMarker 的依赖&#xff08;以 Maven 为例&#xff09;&#xff1a; <!-- Spring Web MVC --> <dependency><gr…

Redis分布式锁使用以及对接支付宝,paypal,strip跨境支付

本章重点在于如何使用redis的分布式锁来锁定库存。减少超卖&#xff0c;同时也对接了支付宝&#xff0c;paypal&#xff0c;strip跨境支付 第一步先建立一个商品表 CREATE TABLE sys_product (id bigint(20) NOT NULL AUTO_INCREMENT COMMENT 主键,code varchar(60) DEFAUL…

使用frpc链接内网的mysql

以下是配置 frpc 连接内网 MySQL 服务的详细步骤&#xff1a; 1. 准备工作 frps 服务器&#xff1a;已部署在公网 IP 11.117.11.245&#xff0c;假设 frps 的默认端口为 7000。 内网 MySQL 服务&#xff1a;运行在内网机器的 3306 端口。 目标&#xff1a;通过公网 IP 11.117…

2025信息安全网络安全意识培训资料汇编(24份)

最新整理&#xff1a;2025信息安全网络安全意识培训资料汇编&#xff0c;共24份资料&#xff0c;供学习参考。 互联网信息安全意识培训.pptx100个网络安全风险防范知识.pptx亚信信息安全意识培训.pptx网络安全法规及意识培训.pptx网络安全意识与案例分析.pptx绿盟-安全意识培训…

JAVA:使用 XStream 实现对象与XML转换的技术指南

1、简述 XStream 是一个简单便捷的 Java 库,用于对象与 XML 的相互转换。其主要特点是: 易于使用:无需复杂的配置即可直接使用。支持自定义:可以灵活地定制对象的序列化和反序列化规则。强大的功能:支持注解、自定义转换器等。本文将详细介绍 XStream 的基本使用方法,并…

VITA STANDARDS LIST,VITA 标准清单下载

VITA STANDARDS LIST&#xff0c;VITA 标准清单下载 DesignationTitleAbstractStatusVMEbus Handbook, 4th EditionA users guide to the VME, VME64 and VME64x bus specifications - features over 70 product photos and over 160 circuit diagrams, tables and graphs. The…

Assetto Corsa 神力科莎 [DLC 解锁] [Steam] [Windows]

Assetto Corsa 神力科莎 [DLC 解锁] [Steam] [Windows] 需要有游戏正版基础本体&#xff0c;安装路径不能带有中文&#xff0c;或其它非常规拉丁字符&#xff1b; DLC 版本 至最新全部 DLC 后续可能无法及时更新文章&#xff0c;具体最新版本见下载文件说明 DLC 解锁列表&…

【Java idea配置】

IntelliJ IDEA创建类时自动生成注释 /** * program: ${PROJECT_NAME} * * since: jdk1.8 * * description: ${description} * * author: ${USER} * * create: ${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE} **/自动导入和自动移除无用导入 idea彩色日志不生效 调试日志输出 在…

计算方法实验六 数值积分

【实验性质】综合性实验。 【实验目的】理解插值型积分法&#xff1b;掌握复化积分法算法。 【实验内容】 1对 &#xff0c;用复化梯形积分和变步长梯形积分求值&#xff08;截断误差不超过&#xff09;。 【理论基础】 积分在工程中有重要的应用&#xff0c;数值积分…

Webug4.0靶场通关笔记11- 第15关任意文件下载与第16关MySQL配置文件下载

目录 一、文件下载 二、第15关 任意文件下载 1.打开靶场 2.源码分析 3.渗透实战 三、第16关 MySQL配置文件下载 1.打开靶场 2.源码分析 3.渗透实战 &#xff08;1&#xff09;Windows系统 &#xff08;2&#xff09;Linux系统 四、渗透防御 一、文件下载 本文通过…

小土堆pytorch--tensorboard的使用

小土堆pytorch--tensorboard的使用 小土堆pytorch--tensorboard的使用0.介绍1.使用tensorboard绘制 y x 等简单函数1.1 相应的代码1.2 对上述代码的解释1.3 可能遇到的问题1.3.1 问题1.3.2 解决方法 2.使用tensorboard加载数据集中的图片2.1 相应代码2.2 对上述代码的解释2.2.…

大模型(LLMs)RAG 版面分析——文本分块面

大模型&#xff08;LLMs&#xff09;RAG 版面分析——文本分块面 一、为什么需要对文本分块&#xff1f; 二、能不能介绍一下常见的文本分块方法&#xff1f; 2.1 一般的文本分块方法 2.2 正则拆分的文本分块方法 2.3 Spacy Text Splitter 方法 2.4 基于 langchain 的 Cha…

解构区块链身份认证:从ID到零知识证明的实战指南

引言 在数字经济高速发展的今天&#xff0c;数字身份已成为个人与数字世界交互的核心凭证。传统中心化身份系统存在数据孤岛、隐私泄露、单点故障等痛点&#xff0c;而区块链技术凭借​​去中心化、不可篡改、可追溯​​的特性&#xff0c;为数字身份验证提供了革命性解决方案…

c#数据结构 线性表篇 非常用线性集合总结

本人能力有限,使用了一些Ai的结论,如有不足还请斧正 目录 1.HashSet <> Dictionary 2.SortedSet <>提供升序方法的List 3.ArrayList<>List 4.BitArray <> Bit[] array 5.StringCollection <>List 6.StringDictionary<>Dictionary 1…

爬虫管理平台-最新版本发布

TaskPyro 是什么&#xff1f; TaskPyro 是一个轻量级的 Python 任务调度平台&#xff0c;专注于提供简单易用的任务管理和爬虫调度解决方案。它能够帮助您轻松管理和调度 Python 任务&#xff0c;特别适合需要定时执行的爬虫任务和数据处理任务。 官方文档&#xff1a;https:/…