cast.rs 23 KB

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