cast.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. use core::mem::size_of;
  2. use core::num::Wrapping;
  3. use core::{f32, f64};
  4. #[cfg(has_i128)]
  5. use core::{i128, u128};
  6. use core::{i16, i32, i64, i8, isize};
  7. use core::{u16, u32, u64, u8, usize};
  8. /// A generic trait for converting a value to a number.
  9. ///
  10. /// A value can be represented by the target type when it lies within
  11. /// the range of scalars supported by the target type.
  12. /// For example, a negative integer cannot be represented by an unsigned
  13. /// integer type, and an `i64` with a very high magnitude might not be
  14. /// convertible to an `i32`.
  15. /// On the other hand, conversions with possible precision loss or truncation
  16. /// are admitted, like an `f32` with a decimal part to an integer type, or
  17. /// even a large `f64` saturating to `f32` infinity.
  18. pub trait ToPrimitive {
  19. /// Converts the value of `self` to an `isize`. If the value cannot be
  20. /// represented by an `isize`, then `None` is returned.
  21. #[inline]
  22. fn to_isize(&self) -> Option<isize> {
  23. self.to_i64().as_ref().and_then(ToPrimitive::to_isize)
  24. }
  25. /// Converts the value of `self` to an `i8`. If the value cannot be
  26. /// represented by an `i8`, then `None` is returned.
  27. #[inline]
  28. fn to_i8(&self) -> Option<i8> {
  29. self.to_i64().as_ref().and_then(ToPrimitive::to_i8)
  30. }
  31. /// Converts the value of `self` to an `i16`. If the value cannot be
  32. /// represented by an `i16`, then `None` is returned.
  33. #[inline]
  34. fn to_i16(&self) -> Option<i16> {
  35. self.to_i64().as_ref().and_then(ToPrimitive::to_i16)
  36. }
  37. /// Converts the value of `self` to an `i32`. If the value cannot be
  38. /// represented by an `i32`, then `None` is returned.
  39. #[inline]
  40. fn to_i32(&self) -> Option<i32> {
  41. self.to_i64().as_ref().and_then(ToPrimitive::to_i32)
  42. }
  43. /// Converts the value of `self` to an `i64`. If the value cannot be
  44. /// represented by an `i64`, then `None` is returned.
  45. fn to_i64(&self) -> Option<i64>;
  46. /// Converts the value of `self` to an `i128`. If the value cannot be
  47. /// represented by an `i128` (`i64` under the default implementation), then
  48. /// `None` is returned.
  49. ///
  50. /// This method is only available with feature `i128` enabled on Rust >= 1.26.
  51. ///
  52. /// The default implementation converts through `to_i64()`. Types implementing
  53. /// this trait should override this method if they can represent a greater range.
  54. #[inline]
  55. #[cfg(has_i128)]
  56. fn to_i128(&self) -> Option<i128> {
  57. self.to_i64().map(From::from)
  58. }
  59. /// Converts the value of `self` to a `usize`. If the value cannot be
  60. /// represented by a `usize`, then `None` is returned.
  61. #[inline]
  62. fn to_usize(&self) -> Option<usize> {
  63. self.to_u64().as_ref().and_then(ToPrimitive::to_usize)
  64. }
  65. /// Converts the value of `self` to a `u8`. If the value cannot be
  66. /// represented by a `u8`, then `None` is returned.
  67. #[inline]
  68. fn to_u8(&self) -> Option<u8> {
  69. self.to_u64().as_ref().and_then(ToPrimitive::to_u8)
  70. }
  71. /// Converts the value of `self` to a `u16`. If the value cannot be
  72. /// represented by a `u16`, then `None` is returned.
  73. #[inline]
  74. fn to_u16(&self) -> Option<u16> {
  75. self.to_u64().as_ref().and_then(ToPrimitive::to_u16)
  76. }
  77. /// Converts the value of `self` to a `u32`. If the value cannot be
  78. /// represented by a `u32`, then `None` is returned.
  79. #[inline]
  80. fn to_u32(&self) -> Option<u32> {
  81. self.to_u64().as_ref().and_then(ToPrimitive::to_u32)
  82. }
  83. /// Converts the value of `self` to a `u64`. If the value cannot be
  84. /// represented by a `u64`, then `None` is returned.
  85. fn to_u64(&self) -> Option<u64>;
  86. /// Converts the value of `self` to a `u128`. If the value cannot be
  87. /// represented by a `u128` (`u64` under the default implementation), then
  88. /// `None` is returned.
  89. ///
  90. /// This method is only available with feature `i128` enabled on Rust >= 1.26.
  91. ///
  92. /// The default implementation converts through `to_u64()`. Types implementing
  93. /// this trait should override this method if they can represent a greater range.
  94. #[inline]
  95. #[cfg(has_i128)]
  96. fn to_u128(&self) -> Option<u128> {
  97. self.to_u64().map(From::from)
  98. }
  99. /// Converts the value of `self` to an `f32`. Overflows may map to positive
  100. /// or negative inifinity, otherwise `None` is returned if the value cannot
  101. /// be represented by an `f32`.
  102. #[inline]
  103. fn to_f32(&self) -> Option<f32> {
  104. self.to_f64().as_ref().and_then(ToPrimitive::to_f32)
  105. }
  106. /// Converts the value of `self` to an `f64`. Overflows may map to positive
  107. /// or negative inifinity, otherwise `None` is returned if the value cannot
  108. /// be represented by an `f64`.
  109. ///
  110. /// The default implementation tries to convert through `to_i64()`, and
  111. /// failing that through `to_u64()`. Types implementing this trait should
  112. /// override this method if they can represent a greater range.
  113. #[inline]
  114. fn to_f64(&self) -> Option<f64> {
  115. match self.to_i64() {
  116. Some(i) => i.to_f64(),
  117. None => self.to_u64().as_ref().and_then(ToPrimitive::to_f64),
  118. }
  119. }
  120. }
  121. macro_rules! impl_to_primitive_int_to_int {
  122. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  123. #[inline]
  124. $(#[$cfg])*
  125. fn $method(&self) -> Option<$DstT> {
  126. let min = $DstT::MIN as $SrcT;
  127. let max = $DstT::MAX as $SrcT;
  128. if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) {
  129. Some(*self as $DstT)
  130. } else {
  131. None
  132. }
  133. }
  134. )*}
  135. }
  136. macro_rules! impl_to_primitive_int_to_uint {
  137. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  138. #[inline]
  139. $(#[$cfg])*
  140. fn $method(&self) -> Option<$DstT> {
  141. let max = $DstT::MAX as $SrcT;
  142. if 0 <= *self && (size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max) {
  143. Some(*self as $DstT)
  144. } else {
  145. None
  146. }
  147. }
  148. )*}
  149. }
  150. macro_rules! impl_to_primitive_int {
  151. ($T:ident) => {
  152. impl ToPrimitive for $T {
  153. impl_to_primitive_int_to_int! { $T:
  154. fn to_isize -> isize;
  155. fn to_i8 -> i8;
  156. fn to_i16 -> i16;
  157. fn to_i32 -> i32;
  158. fn to_i64 -> i64;
  159. #[cfg(has_i128)]
  160. fn to_i128 -> i128;
  161. }
  162. impl_to_primitive_int_to_uint! { $T:
  163. fn to_usize -> usize;
  164. fn to_u8 -> u8;
  165. fn to_u16 -> u16;
  166. fn to_u32 -> u32;
  167. fn to_u64 -> u64;
  168. #[cfg(has_i128)]
  169. fn to_u128 -> u128;
  170. }
  171. #[inline]
  172. fn to_f32(&self) -> Option<f32> {
  173. Some(*self as f32)
  174. }
  175. #[inline]
  176. fn to_f64(&self) -> Option<f64> {
  177. Some(*self as f64)
  178. }
  179. }
  180. };
  181. }
  182. impl_to_primitive_int!(isize);
  183. impl_to_primitive_int!(i8);
  184. impl_to_primitive_int!(i16);
  185. impl_to_primitive_int!(i32);
  186. impl_to_primitive_int!(i64);
  187. #[cfg(has_i128)]
  188. impl_to_primitive_int!(i128);
  189. macro_rules! impl_to_primitive_uint_to_int {
  190. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  191. #[inline]
  192. $(#[$cfg])*
  193. fn $method(&self) -> Option<$DstT> {
  194. let max = $DstT::MAX as $SrcT;
  195. if size_of::<$SrcT>() < size_of::<$DstT>() || *self <= max {
  196. Some(*self as $DstT)
  197. } else {
  198. None
  199. }
  200. }
  201. )*}
  202. }
  203. macro_rules! impl_to_primitive_uint_to_uint {
  204. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  205. #[inline]
  206. $(#[$cfg])*
  207. fn $method(&self) -> Option<$DstT> {
  208. let max = $DstT::MAX as $SrcT;
  209. if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max {
  210. Some(*self as $DstT)
  211. } else {
  212. None
  213. }
  214. }
  215. )*}
  216. }
  217. macro_rules! impl_to_primitive_uint {
  218. ($T:ident) => {
  219. impl ToPrimitive for $T {
  220. impl_to_primitive_uint_to_int! { $T:
  221. fn to_isize -> isize;
  222. fn to_i8 -> i8;
  223. fn to_i16 -> i16;
  224. fn to_i32 -> i32;
  225. fn to_i64 -> i64;
  226. #[cfg(has_i128)]
  227. fn to_i128 -> i128;
  228. }
  229. impl_to_primitive_uint_to_uint! { $T:
  230. fn to_usize -> usize;
  231. fn to_u8 -> u8;
  232. fn to_u16 -> u16;
  233. fn to_u32 -> u32;
  234. fn to_u64 -> u64;
  235. #[cfg(has_i128)]
  236. fn to_u128 -> u128;
  237. }
  238. #[inline]
  239. fn to_f32(&self) -> Option<f32> {
  240. Some(*self as f32)
  241. }
  242. #[inline]
  243. fn to_f64(&self) -> Option<f64> {
  244. Some(*self as f64)
  245. }
  246. }
  247. };
  248. }
  249. impl_to_primitive_uint!(usize);
  250. impl_to_primitive_uint!(u8);
  251. impl_to_primitive_uint!(u16);
  252. impl_to_primitive_uint!(u32);
  253. impl_to_primitive_uint!(u64);
  254. #[cfg(has_i128)]
  255. impl_to_primitive_uint!(u128);
  256. macro_rules! impl_to_primitive_float_to_float {
  257. ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
  258. #[inline]
  259. fn $method(&self) -> Option<$DstT> {
  260. // We can safely cast all values, whether NaN, +-inf, or finite.
  261. // Finite values that are reducing size may saturate to +-inf.
  262. Some(*self as $DstT)
  263. }
  264. )*}
  265. }
  266. #[cfg(has_to_int_unchecked)]
  267. macro_rules! float_to_int_unchecked {
  268. // SAFETY: Must not be NaN or infinite; must be representable as the integer after truncating.
  269. // We already checked that the float is in the exclusive range `(MIN-1, MAX+1)`.
  270. ($float:expr => $int:ty) => {
  271. unsafe { $float.to_int_unchecked::<$int>() }
  272. };
  273. }
  274. #[cfg(not(has_to_int_unchecked))]
  275. macro_rules! float_to_int_unchecked {
  276. ($float:expr => $int:ty) => {
  277. $float as $int
  278. };
  279. }
  280. macro_rules! impl_to_primitive_float_to_signed_int {
  281. ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
  282. #[inline]
  283. $(#[$cfg])*
  284. fn $method(&self) -> Option<$i> {
  285. // Float as int truncates toward zero, so we want to allow values
  286. // in the exclusive range `(MIN-1, MAX+1)`.
  287. if size_of::<$f>() > size_of::<$i>() {
  288. // With a larger size, we can represent the range exactly.
  289. const MIN_M1: $f = $i::MIN as $f - 1.0;
  290. const MAX_P1: $f = $i::MAX as $f + 1.0;
  291. if *self > MIN_M1 && *self < MAX_P1 {
  292. return Some(float_to_int_unchecked!(*self => $i));
  293. }
  294. } else {
  295. // We can't represent `MIN-1` exactly, but there's no fractional part
  296. // at this magnitude, so we can just use a `MIN` inclusive boundary.
  297. const MIN: $f = $i::MIN as $f;
  298. // We can't represent `MAX` exactly, but it will round up to exactly
  299. // `MAX+1` (a power of two) when we cast it.
  300. const MAX_P1: $f = $i::MAX as $f;
  301. if *self >= MIN && *self < MAX_P1 {
  302. return Some(float_to_int_unchecked!(*self => $i));
  303. }
  304. }
  305. None
  306. }
  307. )*}
  308. }
  309. macro_rules! impl_to_primitive_float_to_unsigned_int {
  310. ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $u:ident ; )*) => {$(
  311. #[inline]
  312. $(#[$cfg])*
  313. fn $method(&self) -> Option<$u> {
  314. // Float as int truncates toward zero, so we want to allow values
  315. // in the exclusive range `(-1, MAX+1)`.
  316. if size_of::<$f>() > size_of::<$u>() {
  317. // With a larger size, we can represent the range exactly.
  318. const MAX_P1: $f = $u::MAX as $f + 1.0;
  319. if *self > -1.0 && *self < MAX_P1 {
  320. return Some(float_to_int_unchecked!(*self => $u));
  321. }
  322. } else {
  323. // We can't represent `MAX` exactly, but it will round up to exactly
  324. // `MAX+1` (a power of two) when we cast it.
  325. // (`u128::MAX as f32` is infinity, but this is still ok.)
  326. const MAX_P1: $f = $u::MAX as $f;
  327. if *self > -1.0 && *self < MAX_P1 {
  328. return Some(float_to_int_unchecked!(*self => $u));
  329. }
  330. }
  331. None
  332. }
  333. )*}
  334. }
  335. macro_rules! impl_to_primitive_float {
  336. ($T:ident) => {
  337. impl ToPrimitive for $T {
  338. impl_to_primitive_float_to_signed_int! { $T:
  339. fn to_isize -> isize;
  340. fn to_i8 -> i8;
  341. fn to_i16 -> i16;
  342. fn to_i32 -> i32;
  343. fn to_i64 -> i64;
  344. #[cfg(has_i128)]
  345. fn to_i128 -> i128;
  346. }
  347. impl_to_primitive_float_to_unsigned_int! { $T:
  348. fn to_usize -> usize;
  349. fn to_u8 -> u8;
  350. fn to_u16 -> u16;
  351. fn to_u32 -> u32;
  352. fn to_u64 -> u64;
  353. #[cfg(has_i128)]
  354. fn to_u128 -> u128;
  355. }
  356. impl_to_primitive_float_to_float! { $T:
  357. fn to_f32 -> f32;
  358. fn to_f64 -> f64;
  359. }
  360. }
  361. };
  362. }
  363. impl_to_primitive_float!(f32);
  364. impl_to_primitive_float!(f64);
  365. /// A generic trait for converting a number to a value.
  366. ///
  367. /// A value can be represented by the target type when it lies within
  368. /// the range of scalars supported by the target type.
  369. /// For example, a negative integer cannot be represented by an unsigned
  370. /// integer type, and an `i64` with a very high magnitude might not be
  371. /// convertible to an `i32`.
  372. /// On the other hand, conversions with possible precision loss or truncation
  373. /// are admitted, like an `f32` with a decimal part to an integer type, or
  374. /// even a large `f64` saturating to `f32` infinity.
  375. pub trait FromPrimitive: Sized {
  376. /// Converts an `isize` to return an optional value of this type. If the
  377. /// value cannot be represented by this type, then `None` is returned.
  378. #[inline]
  379. fn from_isize(n: isize) -> Option<Self> {
  380. n.to_i64().and_then(FromPrimitive::from_i64)
  381. }
  382. /// Converts an `i8` to return an optional value of this type. If the
  383. /// value cannot be represented by this type, then `None` is returned.
  384. #[inline]
  385. fn from_i8(n: i8) -> Option<Self> {
  386. FromPrimitive::from_i64(From::from(n))
  387. }
  388. /// Converts an `i16` to return an optional value of this type. If the
  389. /// value cannot be represented by this type, then `None` is returned.
  390. #[inline]
  391. fn from_i16(n: i16) -> Option<Self> {
  392. FromPrimitive::from_i64(From::from(n))
  393. }
  394. /// Converts an `i32` to return an optional value of this type. If the
  395. /// value cannot be represented by this type, then `None` is returned.
  396. #[inline]
  397. fn from_i32(n: i32) -> Option<Self> {
  398. FromPrimitive::from_i64(From::from(n))
  399. }
  400. /// Converts an `i64` to return an optional value of this type. If the
  401. /// value cannot be represented by this type, then `None` is returned.
  402. fn from_i64(n: i64) -> Option<Self>;
  403. /// Converts an `i128` to return an optional value of this type. If the
  404. /// value cannot be represented by this type, then `None` is returned.
  405. ///
  406. /// This method is only available with feature `i128` enabled on Rust >= 1.26.
  407. ///
  408. /// The default implementation converts through `from_i64()`. Types implementing
  409. /// this trait should override this method if they can represent a greater range.
  410. #[inline]
  411. #[cfg(has_i128)]
  412. fn from_i128(n: i128) -> Option<Self> {
  413. n.to_i64().and_then(FromPrimitive::from_i64)
  414. }
  415. /// Converts a `usize` to return an optional value of this type. If the
  416. /// value cannot be represented by this type, then `None` is returned.
  417. #[inline]
  418. fn from_usize(n: usize) -> Option<Self> {
  419. n.to_u64().and_then(FromPrimitive::from_u64)
  420. }
  421. /// Converts an `u8` to return an optional value of this type. If the
  422. /// value cannot be represented by this type, then `None` is returned.
  423. #[inline]
  424. fn from_u8(n: u8) -> Option<Self> {
  425. FromPrimitive::from_u64(From::from(n))
  426. }
  427. /// Converts an `u16` to return an optional value of this type. If the
  428. /// value cannot be represented by this type, then `None` is returned.
  429. #[inline]
  430. fn from_u16(n: u16) -> Option<Self> {
  431. FromPrimitive::from_u64(From::from(n))
  432. }
  433. /// Converts an `u32` to return an optional value of this type. If the
  434. /// value cannot be represented by this type, then `None` is returned.
  435. #[inline]
  436. fn from_u32(n: u32) -> Option<Self> {
  437. FromPrimitive::from_u64(From::from(n))
  438. }
  439. /// Converts an `u64` to return an optional value of this type. If the
  440. /// value cannot be represented by this type, then `None` is returned.
  441. fn from_u64(n: u64) -> Option<Self>;
  442. /// Converts an `u128` to return an optional value of this type. If the
  443. /// value cannot be represented by this type, then `None` is returned.
  444. ///
  445. /// This method is only available with feature `i128` enabled on Rust >= 1.26.
  446. ///
  447. /// The default implementation converts through `from_u64()`. Types implementing
  448. /// this trait should override this method if they can represent a greater range.
  449. #[inline]
  450. #[cfg(has_i128)]
  451. fn from_u128(n: u128) -> Option<Self> {
  452. n.to_u64().and_then(FromPrimitive::from_u64)
  453. }
  454. /// Converts a `f32` to return an optional value of this type. If the
  455. /// value cannot be represented by this type, then `None` is returned.
  456. #[inline]
  457. fn from_f32(n: f32) -> Option<Self> {
  458. FromPrimitive::from_f64(From::from(n))
  459. }
  460. /// Converts a `f64` to return an optional value of this type. If the
  461. /// value cannot be represented by this type, then `None` is returned.
  462. ///
  463. /// The default implementation tries to convert through `from_i64()`, and
  464. /// failing that through `from_u64()`. Types implementing this trait should
  465. /// override this method if they can represent a greater range.
  466. #[inline]
  467. fn from_f64(n: f64) -> Option<Self> {
  468. match n.to_i64() {
  469. Some(i) => FromPrimitive::from_i64(i),
  470. None => n.to_u64().and_then(FromPrimitive::from_u64),
  471. }
  472. }
  473. }
  474. macro_rules! impl_from_primitive {
  475. ($T:ty, $to_ty:ident) => {
  476. #[allow(deprecated)]
  477. impl FromPrimitive for $T {
  478. #[inline]
  479. fn from_isize(n: isize) -> Option<$T> {
  480. n.$to_ty()
  481. }
  482. #[inline]
  483. fn from_i8(n: i8) -> Option<$T> {
  484. n.$to_ty()
  485. }
  486. #[inline]
  487. fn from_i16(n: i16) -> Option<$T> {
  488. n.$to_ty()
  489. }
  490. #[inline]
  491. fn from_i32(n: i32) -> Option<$T> {
  492. n.$to_ty()
  493. }
  494. #[inline]
  495. fn from_i64(n: i64) -> Option<$T> {
  496. n.$to_ty()
  497. }
  498. #[cfg(has_i128)]
  499. #[inline]
  500. fn from_i128(n: i128) -> Option<$T> {
  501. n.$to_ty()
  502. }
  503. #[inline]
  504. fn from_usize(n: usize) -> Option<$T> {
  505. n.$to_ty()
  506. }
  507. #[inline]
  508. fn from_u8(n: u8) -> Option<$T> {
  509. n.$to_ty()
  510. }
  511. #[inline]
  512. fn from_u16(n: u16) -> Option<$T> {
  513. n.$to_ty()
  514. }
  515. #[inline]
  516. fn from_u32(n: u32) -> Option<$T> {
  517. n.$to_ty()
  518. }
  519. #[inline]
  520. fn from_u64(n: u64) -> Option<$T> {
  521. n.$to_ty()
  522. }
  523. #[cfg(has_i128)]
  524. #[inline]
  525. fn from_u128(n: u128) -> Option<$T> {
  526. n.$to_ty()
  527. }
  528. #[inline]
  529. fn from_f32(n: f32) -> Option<$T> {
  530. n.$to_ty()
  531. }
  532. #[inline]
  533. fn from_f64(n: f64) -> Option<$T> {
  534. n.$to_ty()
  535. }
  536. }
  537. };
  538. }
  539. impl_from_primitive!(isize, to_isize);
  540. impl_from_primitive!(i8, to_i8);
  541. impl_from_primitive!(i16, to_i16);
  542. impl_from_primitive!(i32, to_i32);
  543. impl_from_primitive!(i64, to_i64);
  544. #[cfg(has_i128)]
  545. impl_from_primitive!(i128, to_i128);
  546. impl_from_primitive!(usize, to_usize);
  547. impl_from_primitive!(u8, to_u8);
  548. impl_from_primitive!(u16, to_u16);
  549. impl_from_primitive!(u32, to_u32);
  550. impl_from_primitive!(u64, to_u64);
  551. #[cfg(has_i128)]
  552. impl_from_primitive!(u128, to_u128);
  553. impl_from_primitive!(f32, to_f32);
  554. impl_from_primitive!(f64, to_f64);
  555. macro_rules! impl_to_primitive_wrapping {
  556. ($( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
  557. #[inline]
  558. $(#[$cfg])*
  559. fn $method(&self) -> Option<$i> {
  560. (self.0).$method()
  561. }
  562. )*}
  563. }
  564. impl<T: ToPrimitive> ToPrimitive for Wrapping<T> {
  565. impl_to_primitive_wrapping! {
  566. fn to_isize -> isize;
  567. fn to_i8 -> i8;
  568. fn to_i16 -> i16;
  569. fn to_i32 -> i32;
  570. fn to_i64 -> i64;
  571. #[cfg(has_i128)]
  572. fn to_i128 -> i128;
  573. fn to_usize -> usize;
  574. fn to_u8 -> u8;
  575. fn to_u16 -> u16;
  576. fn to_u32 -> u32;
  577. fn to_u64 -> u64;
  578. #[cfg(has_i128)]
  579. fn to_u128 -> u128;
  580. fn to_f32 -> f32;
  581. fn to_f64 -> f64;
  582. }
  583. }
  584. macro_rules! impl_from_primitive_wrapping {
  585. ($( $(#[$cfg:meta])* fn $method:ident ( $i:ident ); )*) => {$(
  586. #[inline]
  587. $(#[$cfg])*
  588. fn $method(n: $i) -> Option<Self> {
  589. T::$method(n).map(Wrapping)
  590. }
  591. )*}
  592. }
  593. impl<T: FromPrimitive> FromPrimitive for Wrapping<T> {
  594. impl_from_primitive_wrapping! {
  595. fn from_isize(isize);
  596. fn from_i8(i8);
  597. fn from_i16(i16);
  598. fn from_i32(i32);
  599. fn from_i64(i64);
  600. #[cfg(has_i128)]
  601. fn from_i128(i128);
  602. fn from_usize(usize);
  603. fn from_u8(u8);
  604. fn from_u16(u16);
  605. fn from_u32(u32);
  606. fn from_u64(u64);
  607. #[cfg(has_i128)]
  608. fn from_u128(u128);
  609. fn from_f32(f32);
  610. fn from_f64(f64);
  611. }
  612. }
  613. /// Cast from one machine scalar to another.
  614. ///
  615. /// # Examples
  616. ///
  617. /// ```
  618. /// # use num_traits as num;
  619. /// let twenty: f32 = num::cast(0x14).unwrap();
  620. /// assert_eq!(twenty, 20f32);
  621. /// ```
  622. ///
  623. #[inline]
  624. pub fn cast<T: NumCast, U: NumCast>(n: T) -> Option<U> {
  625. NumCast::from(n)
  626. }
  627. /// An interface for casting between machine scalars.
  628. pub trait NumCast: Sized + ToPrimitive {
  629. /// Creates a number from another value that can be converted into
  630. /// a primitive via the `ToPrimitive` trait. If the source value cannot be
  631. /// represented by the target type, then `None` is returned.
  632. ///
  633. /// A value can be represented by the target type when it lies within
  634. /// the range of scalars supported by the target type.
  635. /// For example, a negative integer cannot be represented by an unsigned
  636. /// integer type, and an `i64` with a very high magnitude might not be
  637. /// convertible to an `i32`.
  638. /// On the other hand, conversions with possible precision loss or truncation
  639. /// are admitted, like an `f32` with a decimal part to an integer type, or
  640. /// even a large `f64` saturating to `f32` infinity.
  641. fn from<T: ToPrimitive>(n: T) -> Option<Self>;
  642. }
  643. macro_rules! impl_num_cast {
  644. ($T:ty, $conv:ident) => {
  645. impl NumCast for $T {
  646. #[inline]
  647. #[allow(deprecated)]
  648. fn from<N: ToPrimitive>(n: N) -> Option<$T> {
  649. // `$conv` could be generated using `concat_idents!`, but that
  650. // macro seems to be broken at the moment
  651. n.$conv()
  652. }
  653. }
  654. };
  655. }
  656. impl_num_cast!(u8, to_u8);
  657. impl_num_cast!(u16, to_u16);
  658. impl_num_cast!(u32, to_u32);
  659. impl_num_cast!(u64, to_u64);
  660. #[cfg(has_i128)]
  661. impl_num_cast!(u128, to_u128);
  662. impl_num_cast!(usize, to_usize);
  663. impl_num_cast!(i8, to_i8);
  664. impl_num_cast!(i16, to_i16);
  665. impl_num_cast!(i32, to_i32);
  666. impl_num_cast!(i64, to_i64);
  667. #[cfg(has_i128)]
  668. impl_num_cast!(i128, to_i128);
  669. impl_num_cast!(isize, to_isize);
  670. impl_num_cast!(f32, to_f32);
  671. impl_num_cast!(f64, to_f64);
  672. impl<T: NumCast> NumCast for Wrapping<T> {
  673. fn from<U: ToPrimitive>(n: U) -> Option<Self> {
  674. T::from(n).map(Wrapping)
  675. }
  676. }
  677. /// A generic interface for casting between machine scalars with the
  678. /// `as` operator, which admits narrowing and precision loss.
  679. /// Implementers of this trait `AsPrimitive` should behave like a primitive
  680. /// numeric type (e.g. a newtype around another primitive), and the
  681. /// intended conversion must never fail.
  682. ///
  683. /// # Examples
  684. ///
  685. /// ```
  686. /// # use num_traits::AsPrimitive;
  687. /// let three: i32 = (3.14159265f32).as_();
  688. /// assert_eq!(three, 3);
  689. /// ```
  690. ///
  691. /// # Safety
  692. ///
  693. /// **In Rust versions before 1.45.0**, some uses of the `as` operator were not entirely safe.
  694. /// In particular, it was undefined behavior if
  695. /// a truncated floating point value could not fit in the target integer
  696. /// type ([#10184](https://github.com/rust-lang/rust/issues/10184)).
  697. ///
  698. /// ```ignore
  699. /// # use num_traits::AsPrimitive;
  700. /// let x: u8 = (1.04E+17).as_(); // UB
  701. /// ```
  702. ///
  703. pub trait AsPrimitive<T>: 'static + Copy
  704. where
  705. T: 'static + Copy,
  706. {
  707. /// Convert a value to another, using the `as` operator.
  708. fn as_(self) -> T;
  709. }
  710. macro_rules! impl_as_primitive {
  711. (@ $T: ty => $(#[$cfg:meta])* impl $U: ty ) => {
  712. $(#[$cfg])*
  713. impl AsPrimitive<$U> for $T {
  714. #[inline] fn as_(self) -> $U { self as $U }
  715. }
  716. };
  717. (@ $T: ty => { $( $U: ty ),* } ) => {$(
  718. impl_as_primitive!(@ $T => impl $U);
  719. )*};
  720. ($T: ty => { $( $U: ty ),* } ) => {
  721. impl_as_primitive!(@ $T => { $( $U ),* });
  722. impl_as_primitive!(@ $T => { u8, u16, u32, u64, usize });
  723. impl_as_primitive!(@ $T => #[cfg(has_i128)] impl u128);
  724. impl_as_primitive!(@ $T => { i8, i16, i32, i64, isize });
  725. impl_as_primitive!(@ $T => #[cfg(has_i128)] impl i128);
  726. };
  727. }
  728. impl_as_primitive!(u8 => { char, f32, f64 });
  729. impl_as_primitive!(i8 => { f32, f64 });
  730. impl_as_primitive!(u16 => { f32, f64 });
  731. impl_as_primitive!(i16 => { f32, f64 });
  732. impl_as_primitive!(u32 => { f32, f64 });
  733. impl_as_primitive!(i32 => { f32, f64 });
  734. impl_as_primitive!(u64 => { f32, f64 });
  735. impl_as_primitive!(i64 => { f32, f64 });
  736. #[cfg(has_i128)]
  737. impl_as_primitive!(u128 => { f32, f64 });
  738. #[cfg(has_i128)]
  739. impl_as_primitive!(i128 => { f32, f64 });
  740. impl_as_primitive!(usize => { f32, f64 });
  741. impl_as_primitive!(isize => { f32, f64 });
  742. impl_as_primitive!(f32 => { f32, f64 });
  743. impl_as_primitive!(f64 => { f32, f64 });
  744. impl_as_primitive!(char => { char });
  745. impl_as_primitive!(bool => {});