cast.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. use float::FloatCore;
  9. /// A generic trait for converting a value to a number.
  10. ///
  11. /// A value can be represented by the target type when it lies within
  12. /// the range of scalars supported by the target type.
  13. /// For example, a negative integer cannot be represented by an unsigned
  14. /// integer type, and an `f64` with a very high magnitude might not be
  15. /// convertible to an `f32`.
  16. /// On the other hand, conversions with possible precision loss or truncation
  17. /// (e.g. an `f32` with a decimal part to an integer type) are admitted.
  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`. If the value cannot be
  100. /// represented by an `f32`, then `None` is returned.
  101. #[inline]
  102. fn to_f32(&self) -> Option<f32> {
  103. self.to_f64().as_ref().and_then(ToPrimitive::to_f32)
  104. }
  105. /// Converts the value of `self` to an `f64`. If the value cannot be
  106. /// represented by an `f64`, then `None` is returned.
  107. #[inline]
  108. fn to_f64(&self) -> Option<f64> {
  109. match self.to_i64() {
  110. Some(i) => i.to_f64(),
  111. None => self.to_u64().as_ref().and_then(ToPrimitive::to_f64),
  112. }
  113. }
  114. }
  115. macro_rules! impl_to_primitive_int_to_int {
  116. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  117. #[inline]
  118. $(#[$cfg])*
  119. fn $method(&self) -> Option<$DstT> {
  120. let min = $DstT::MIN as $SrcT;
  121. let max = $DstT::MAX as $SrcT;
  122. if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) {
  123. Some(*self as $DstT)
  124. } else {
  125. None
  126. }
  127. }
  128. )*}
  129. }
  130. macro_rules! impl_to_primitive_int_to_uint {
  131. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  132. #[inline]
  133. $(#[$cfg])*
  134. fn $method(&self) -> Option<$DstT> {
  135. let max = $DstT::MAX as $SrcT;
  136. if 0 <= *self && (size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max) {
  137. Some(*self as $DstT)
  138. } else {
  139. None
  140. }
  141. }
  142. )*}
  143. }
  144. macro_rules! impl_to_primitive_int {
  145. ($T:ident) => {
  146. impl ToPrimitive for $T {
  147. impl_to_primitive_int_to_int! { $T:
  148. fn to_isize -> isize;
  149. fn to_i8 -> i8;
  150. fn to_i16 -> i16;
  151. fn to_i32 -> i32;
  152. fn to_i64 -> i64;
  153. #[cfg(has_i128)]
  154. fn to_i128 -> i128;
  155. }
  156. impl_to_primitive_int_to_uint! { $T:
  157. fn to_usize -> usize;
  158. fn to_u8 -> u8;
  159. fn to_u16 -> u16;
  160. fn to_u32 -> u32;
  161. fn to_u64 -> u64;
  162. #[cfg(has_i128)]
  163. fn to_u128 -> u128;
  164. }
  165. #[inline]
  166. fn to_f32(&self) -> Option<f32> {
  167. Some(*self as f32)
  168. }
  169. #[inline]
  170. fn to_f64(&self) -> Option<f64> {
  171. Some(*self as f64)
  172. }
  173. }
  174. };
  175. }
  176. impl_to_primitive_int!(isize);
  177. impl_to_primitive_int!(i8);
  178. impl_to_primitive_int!(i16);
  179. impl_to_primitive_int!(i32);
  180. impl_to_primitive_int!(i64);
  181. #[cfg(has_i128)]
  182. impl_to_primitive_int!(i128);
  183. macro_rules! impl_to_primitive_uint_to_int {
  184. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  185. #[inline]
  186. $(#[$cfg])*
  187. fn $method(&self) -> Option<$DstT> {
  188. let max = $DstT::MAX as $SrcT;
  189. if size_of::<$SrcT>() < size_of::<$DstT>() || *self <= max {
  190. Some(*self as $DstT)
  191. } else {
  192. None
  193. }
  194. }
  195. )*}
  196. }
  197. macro_rules! impl_to_primitive_uint_to_uint {
  198. ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
  199. #[inline]
  200. $(#[$cfg])*
  201. fn $method(&self) -> Option<$DstT> {
  202. let max = $DstT::MAX as $SrcT;
  203. if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max {
  204. Some(*self as $DstT)
  205. } else {
  206. None
  207. }
  208. }
  209. )*}
  210. }
  211. macro_rules! impl_to_primitive_uint {
  212. ($T:ident) => {
  213. impl ToPrimitive for $T {
  214. impl_to_primitive_uint_to_int! { $T:
  215. fn to_isize -> isize;
  216. fn to_i8 -> i8;
  217. fn to_i16 -> i16;
  218. fn to_i32 -> i32;
  219. fn to_i64 -> i64;
  220. #[cfg(has_i128)]
  221. fn to_i128 -> i128;
  222. }
  223. impl_to_primitive_uint_to_uint! { $T:
  224. fn to_usize -> usize;
  225. fn to_u8 -> u8;
  226. fn to_u16 -> u16;
  227. fn to_u32 -> u32;
  228. fn to_u64 -> u64;
  229. #[cfg(has_i128)]
  230. fn to_u128 -> u128;
  231. }
  232. #[inline]
  233. fn to_f32(&self) -> Option<f32> {
  234. Some(*self as f32)
  235. }
  236. #[inline]
  237. fn to_f64(&self) -> Option<f64> {
  238. Some(*self as f64)
  239. }
  240. }
  241. };
  242. }
  243. impl_to_primitive_uint!(usize);
  244. impl_to_primitive_uint!(u8);
  245. impl_to_primitive_uint!(u16);
  246. impl_to_primitive_uint!(u32);
  247. impl_to_primitive_uint!(u64);
  248. #[cfg(has_i128)]
  249. impl_to_primitive_uint!(u128);
  250. macro_rules! impl_to_primitive_float_to_float {
  251. ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
  252. #[inline]
  253. fn $method(&self) -> Option<$DstT> {
  254. // Only finite values that are reducing size need to worry about overflow.
  255. if size_of::<$SrcT>() > size_of::<$DstT>() && FloatCore::is_finite(*self) {
  256. let n = *self as f64;
  257. if n < $DstT::MIN as f64 || n > $DstT::MAX as f64 {
  258. return None;
  259. }
  260. }
  261. // We can safely cast NaN, +-inf, and finite values in range.
  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 `f64` with a very high magnitude might not be
  371. /// convertible to an `f32`.
  372. /// On the other hand, conversions with possible precision loss or truncation
  373. /// (e.g. an `f32` with a decimal part to an integer type) are admitted.
  374. pub trait FromPrimitive: Sized {
  375. /// Converts an `isize` to return an optional value of this type. If the
  376. /// value cannot be represented by this type, then `None` is returned.
  377. #[inline]
  378. fn from_isize(n: isize) -> Option<Self> {
  379. n.to_i64().and_then(FromPrimitive::from_i64)
  380. }
  381. /// Converts an `i8` to return an optional value of this type. If the
  382. /// value cannot be represented by this type, then `None` is returned.
  383. #[inline]
  384. fn from_i8(n: i8) -> Option<Self> {
  385. FromPrimitive::from_i64(From::from(n))
  386. }
  387. /// Converts an `i16` to return an optional value of this type. If the
  388. /// value cannot be represented by this type, then `None` is returned.
  389. #[inline]
  390. fn from_i16(n: i16) -> Option<Self> {
  391. FromPrimitive::from_i64(From::from(n))
  392. }
  393. /// Converts an `i32` to return an optional value of this type. If the
  394. /// value cannot be represented by this type, then `None` is returned.
  395. #[inline]
  396. fn from_i32(n: i32) -> Option<Self> {
  397. FromPrimitive::from_i64(From::from(n))
  398. }
  399. /// Converts an `i64` to return an optional value of this type. If the
  400. /// value cannot be represented by this type, then `None` is returned.
  401. fn from_i64(n: i64) -> Option<Self>;
  402. /// Converts an `i128` to return an optional value of this type. If the
  403. /// value cannot be represented by this type, then `None` is returned.
  404. ///
  405. /// This method is only available with feature `i128` enabled on Rust >= 1.26.
  406. ///
  407. /// The default implementation converts through `from_i64()`. Types implementing
  408. /// this trait should override this method if they can represent a greater range.
  409. #[inline]
  410. #[cfg(has_i128)]
  411. fn from_i128(n: i128) -> Option<Self> {
  412. n.to_i64().and_then(FromPrimitive::from_i64)
  413. }
  414. /// Converts a `usize` to return an optional value of this type. If the
  415. /// value cannot be represented by this type, then `None` is returned.
  416. #[inline]
  417. fn from_usize(n: usize) -> Option<Self> {
  418. n.to_u64().and_then(FromPrimitive::from_u64)
  419. }
  420. /// Converts an `u8` to return an optional value of this type. If the
  421. /// value cannot be represented by this type, then `None` is returned.
  422. #[inline]
  423. fn from_u8(n: u8) -> Option<Self> {
  424. FromPrimitive::from_u64(From::from(n))
  425. }
  426. /// Converts an `u16` to return an optional value of this type. If the
  427. /// value cannot be represented by this type, then `None` is returned.
  428. #[inline]
  429. fn from_u16(n: u16) -> Option<Self> {
  430. FromPrimitive::from_u64(From::from(n))
  431. }
  432. /// Converts an `u32` to return an optional value of this type. If the
  433. /// value cannot be represented by this type, then `None` is returned.
  434. #[inline]
  435. fn from_u32(n: u32) -> Option<Self> {
  436. FromPrimitive::from_u64(From::from(n))
  437. }
  438. /// Converts an `u64` to return an optional value of this type. If the
  439. /// value cannot be represented by this type, then `None` is returned.
  440. fn from_u64(n: u64) -> Option<Self>;
  441. /// Converts an `u128` to return an optional value of this type. If the
  442. /// value cannot be represented by this type, then `None` is returned.
  443. ///
  444. /// This method is only available with feature `i128` enabled on Rust >= 1.26.
  445. ///
  446. /// The default implementation converts through `from_u64()`. Types implementing
  447. /// this trait should override this method if they can represent a greater range.
  448. #[inline]
  449. #[cfg(has_i128)]
  450. fn from_u128(n: u128) -> Option<Self> {
  451. n.to_u64().and_then(FromPrimitive::from_u64)
  452. }
  453. /// Converts a `f32` to return an optional value of this type. If the
  454. /// value cannot be represented by this type, then `None` is returned.
  455. #[inline]
  456. fn from_f32(n: f32) -> Option<Self> {
  457. FromPrimitive::from_f64(From::from(n))
  458. }
  459. /// Converts a `f64` to return an optional value of this type. If the
  460. /// value cannot be represented by this type, then `None` is returned.
  461. #[inline]
  462. fn from_f64(n: f64) -> Option<Self> {
  463. match n.to_i64() {
  464. Some(i) => FromPrimitive::from_i64(i),
  465. None => n.to_u64().and_then(FromPrimitive::from_u64),
  466. }
  467. }
  468. }
  469. macro_rules! impl_from_primitive {
  470. ($T:ty, $to_ty:ident) => {
  471. #[allow(deprecated)]
  472. impl FromPrimitive for $T {
  473. #[inline]
  474. fn from_isize(n: isize) -> Option<$T> {
  475. n.$to_ty()
  476. }
  477. #[inline]
  478. fn from_i8(n: i8) -> Option<$T> {
  479. n.$to_ty()
  480. }
  481. #[inline]
  482. fn from_i16(n: i16) -> Option<$T> {
  483. n.$to_ty()
  484. }
  485. #[inline]
  486. fn from_i32(n: i32) -> Option<$T> {
  487. n.$to_ty()
  488. }
  489. #[inline]
  490. fn from_i64(n: i64) -> Option<$T> {
  491. n.$to_ty()
  492. }
  493. #[cfg(has_i128)]
  494. #[inline]
  495. fn from_i128(n: i128) -> Option<$T> {
  496. n.$to_ty()
  497. }
  498. #[inline]
  499. fn from_usize(n: usize) -> Option<$T> {
  500. n.$to_ty()
  501. }
  502. #[inline]
  503. fn from_u8(n: u8) -> Option<$T> {
  504. n.$to_ty()
  505. }
  506. #[inline]
  507. fn from_u16(n: u16) -> Option<$T> {
  508. n.$to_ty()
  509. }
  510. #[inline]
  511. fn from_u32(n: u32) -> Option<$T> {
  512. n.$to_ty()
  513. }
  514. #[inline]
  515. fn from_u64(n: u64) -> Option<$T> {
  516. n.$to_ty()
  517. }
  518. #[cfg(has_i128)]
  519. #[inline]
  520. fn from_u128(n: u128) -> Option<$T> {
  521. n.$to_ty()
  522. }
  523. #[inline]
  524. fn from_f32(n: f32) -> Option<$T> {
  525. n.$to_ty()
  526. }
  527. #[inline]
  528. fn from_f64(n: f64) -> Option<$T> {
  529. n.$to_ty()
  530. }
  531. }
  532. };
  533. }
  534. impl_from_primitive!(isize, to_isize);
  535. impl_from_primitive!(i8, to_i8);
  536. impl_from_primitive!(i16, to_i16);
  537. impl_from_primitive!(i32, to_i32);
  538. impl_from_primitive!(i64, to_i64);
  539. #[cfg(has_i128)]
  540. impl_from_primitive!(i128, to_i128);
  541. impl_from_primitive!(usize, to_usize);
  542. impl_from_primitive!(u8, to_u8);
  543. impl_from_primitive!(u16, to_u16);
  544. impl_from_primitive!(u32, to_u32);
  545. impl_from_primitive!(u64, to_u64);
  546. #[cfg(has_i128)]
  547. impl_from_primitive!(u128, to_u128);
  548. impl_from_primitive!(f32, to_f32);
  549. impl_from_primitive!(f64, to_f64);
  550. macro_rules! impl_to_primitive_wrapping {
  551. ($( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
  552. #[inline]
  553. $(#[$cfg])*
  554. fn $method(&self) -> Option<$i> {
  555. (self.0).$method()
  556. }
  557. )*}
  558. }
  559. impl<T: ToPrimitive> ToPrimitive for Wrapping<T> {
  560. impl_to_primitive_wrapping! {
  561. fn to_isize -> isize;
  562. fn to_i8 -> i8;
  563. fn to_i16 -> i16;
  564. fn to_i32 -> i32;
  565. fn to_i64 -> i64;
  566. #[cfg(has_i128)]
  567. fn to_i128 -> i128;
  568. fn to_usize -> usize;
  569. fn to_u8 -> u8;
  570. fn to_u16 -> u16;
  571. fn to_u32 -> u32;
  572. fn to_u64 -> u64;
  573. #[cfg(has_i128)]
  574. fn to_u128 -> u128;
  575. fn to_f32 -> f32;
  576. fn to_f64 -> f64;
  577. }
  578. }
  579. macro_rules! impl_from_primitive_wrapping {
  580. ($( $(#[$cfg:meta])* fn $method:ident ( $i:ident ); )*) => {$(
  581. #[inline]
  582. $(#[$cfg])*
  583. fn $method(n: $i) -> Option<Self> {
  584. T::$method(n).map(Wrapping)
  585. }
  586. )*}
  587. }
  588. impl<T: FromPrimitive> FromPrimitive for Wrapping<T> {
  589. impl_from_primitive_wrapping! {
  590. fn from_isize(isize);
  591. fn from_i8(i8);
  592. fn from_i16(i16);
  593. fn from_i32(i32);
  594. fn from_i64(i64);
  595. #[cfg(has_i128)]
  596. fn from_i128(i128);
  597. fn from_usize(usize);
  598. fn from_u8(u8);
  599. fn from_u16(u16);
  600. fn from_u32(u32);
  601. fn from_u64(u64);
  602. #[cfg(has_i128)]
  603. fn from_u128(u128);
  604. fn from_f32(f32);
  605. fn from_f64(f64);
  606. }
  607. }
  608. /// Cast from one machine scalar to another.
  609. ///
  610. /// # Examples
  611. ///
  612. /// ```
  613. /// # use num_traits as num;
  614. /// let twenty: f32 = num::cast(0x14).unwrap();
  615. /// assert_eq!(twenty, 20f32);
  616. /// ```
  617. ///
  618. #[inline]
  619. pub fn cast<T: NumCast, U: NumCast>(n: T) -> Option<U> {
  620. NumCast::from(n)
  621. }
  622. /// An interface for casting between machine scalars.
  623. pub trait NumCast: Sized + ToPrimitive {
  624. /// Creates a number from another value that can be converted into
  625. /// a primitive via the `ToPrimitive` trait. If the source value cannot be
  626. /// represented by the target type, then `None` is returned.
  627. ///
  628. /// A value can be represented by the target type when it lies within
  629. /// the range of scalars supported by the target type.
  630. /// For example, a negative integer cannot be represented by an unsigned
  631. /// integer type, and an `f64` with a very high magnitude might not be
  632. /// convertible to an `f32`.
  633. /// On the other hand, conversions with possible precision loss or truncation
  634. /// (e.g. an `f32` with a decimal part to an integer type) are admitted.
  635. fn from<T: ToPrimitive>(n: T) -> Option<Self>;
  636. }
  637. macro_rules! impl_num_cast {
  638. ($T:ty, $conv:ident) => {
  639. impl NumCast for $T {
  640. #[inline]
  641. #[allow(deprecated)]
  642. fn from<N: ToPrimitive>(n: N) -> Option<$T> {
  643. // `$conv` could be generated using `concat_idents!`, but that
  644. // macro seems to be broken at the moment
  645. n.$conv()
  646. }
  647. }
  648. };
  649. }
  650. impl_num_cast!(u8, to_u8);
  651. impl_num_cast!(u16, to_u16);
  652. impl_num_cast!(u32, to_u32);
  653. impl_num_cast!(u64, to_u64);
  654. #[cfg(has_i128)]
  655. impl_num_cast!(u128, to_u128);
  656. impl_num_cast!(usize, to_usize);
  657. impl_num_cast!(i8, to_i8);
  658. impl_num_cast!(i16, to_i16);
  659. impl_num_cast!(i32, to_i32);
  660. impl_num_cast!(i64, to_i64);
  661. #[cfg(has_i128)]
  662. impl_num_cast!(i128, to_i128);
  663. impl_num_cast!(isize, to_isize);
  664. impl_num_cast!(f32, to_f32);
  665. impl_num_cast!(f64, to_f64);
  666. impl<T: NumCast> NumCast for Wrapping<T> {
  667. fn from<U: ToPrimitive>(n: U) -> Option<Self> {
  668. T::from(n).map(Wrapping)
  669. }
  670. }
  671. /// A generic interface for casting between machine scalars with the
  672. /// `as` operator, which admits narrowing and precision loss.
  673. /// Implementers of this trait `AsPrimitive` should behave like a primitive
  674. /// numeric type (e.g. a newtype around another primitive), and the
  675. /// intended conversion must never fail.
  676. ///
  677. /// # Examples
  678. ///
  679. /// ```
  680. /// # use num_traits::AsPrimitive;
  681. /// let three: i32 = (3.14159265f32).as_();
  682. /// assert_eq!(three, 3);
  683. /// ```
  684. ///
  685. /// # Safety
  686. ///
  687. /// Currently, some uses of the `as` operator are not entirely safe.
  688. /// In particular, it is undefined behavior if:
  689. ///
  690. /// - A truncated floating point value cannot fit in the target integer
  691. /// type ([#10184](https://github.com/rust-lang/rust/issues/10184));
  692. ///
  693. /// ```ignore
  694. /// # use num_traits::AsPrimitive;
  695. /// let x: u8 = (1.04E+17).as_(); // UB
  696. /// ```
  697. ///
  698. /// - Or a floating point value does not fit in another floating
  699. /// point type ([#15536](https://github.com/rust-lang/rust/issues/15536)).
  700. ///
  701. /// ```ignore
  702. /// # use num_traits::AsPrimitive;
  703. /// let x: f32 = (1e300f64).as_(); // UB
  704. /// ```
  705. ///
  706. pub trait AsPrimitive<T>: 'static + Copy
  707. where
  708. T: 'static + Copy,
  709. {
  710. /// Convert a value to another, using the `as` operator.
  711. fn as_(self) -> T;
  712. }
  713. macro_rules! impl_as_primitive {
  714. (@ $T: ty => $(#[$cfg:meta])* impl $U: ty ) => {
  715. $(#[$cfg])*
  716. impl AsPrimitive<$U> for $T {
  717. #[inline] fn as_(self) -> $U { self as $U }
  718. }
  719. };
  720. (@ $T: ty => { $( $U: ty ),* } ) => {$(
  721. impl_as_primitive!(@ $T => impl $U);
  722. )*};
  723. ($T: ty => { $( $U: ty ),* } ) => {
  724. impl_as_primitive!(@ $T => { $( $U ),* });
  725. impl_as_primitive!(@ $T => { u8, u16, u32, u64, usize });
  726. impl_as_primitive!(@ $T => #[cfg(has_i128)] impl u128);
  727. impl_as_primitive!(@ $T => { i8, i16, i32, i64, isize });
  728. impl_as_primitive!(@ $T => #[cfg(has_i128)] impl i128);
  729. };
  730. }
  731. impl_as_primitive!(u8 => { char, f32, f64 });
  732. impl_as_primitive!(i8 => { f32, f64 });
  733. impl_as_primitive!(u16 => { f32, f64 });
  734. impl_as_primitive!(i16 => { f32, f64 });
  735. impl_as_primitive!(u32 => { f32, f64 });
  736. impl_as_primitive!(i32 => { f32, f64 });
  737. impl_as_primitive!(u64 => { f32, f64 });
  738. impl_as_primitive!(i64 => { f32, f64 });
  739. #[cfg(has_i128)]
  740. impl_as_primitive!(u128 => { f32, f64 });
  741. #[cfg(has_i128)]
  742. impl_as_primitive!(i128 => { f32, f64 });
  743. impl_as_primitive!(usize => { f32, f64 });
  744. impl_as_primitive!(isize => { f32, f64 });
  745. impl_as_primitive!(f32 => { f32, f64 });
  746. impl_as_primitive!(f64 => { f32, f64 });
  747. impl_as_primitive!(char => { char });
  748. impl_as_primitive!(bool => {});