cast.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. use std::mem::size_of;
  2. use std::num::Wrapping;
  3. use identities::Zero;
  4. use bounds::Bounded;
  5. /// A generic trait for converting a value to a number.
  6. pub trait ToPrimitive {
  7. /// Converts the value of `self` to an `isize`.
  8. #[inline]
  9. fn to_isize(&self) -> Option<isize> {
  10. self.to_i64().and_then(|x| x.to_isize())
  11. }
  12. /// Converts the value of `self` to an `i8`.
  13. #[inline]
  14. fn to_i8(&self) -> Option<i8> {
  15. self.to_i64().and_then(|x| x.to_i8())
  16. }
  17. /// Converts the value of `self` to an `i16`.
  18. #[inline]
  19. fn to_i16(&self) -> Option<i16> {
  20. self.to_i64().and_then(|x| x.to_i16())
  21. }
  22. /// Converts the value of `self` to an `i32`.
  23. #[inline]
  24. fn to_i32(&self) -> Option<i32> {
  25. self.to_i64().and_then(|x| x.to_i32())
  26. }
  27. /// Converts the value of `self` to an `i64`.
  28. fn to_i64(&self) -> Option<i64>;
  29. /// Converts the value of `self` to a `usize`.
  30. #[inline]
  31. fn to_usize(&self) -> Option<usize> {
  32. self.to_u64().and_then(|x| x.to_usize())
  33. }
  34. /// Converts the value of `self` to an `u8`.
  35. #[inline]
  36. fn to_u8(&self) -> Option<u8> {
  37. self.to_u64().and_then(|x| x.to_u8())
  38. }
  39. /// Converts the value of `self` to an `u16`.
  40. #[inline]
  41. fn to_u16(&self) -> Option<u16> {
  42. self.to_u64().and_then(|x| x.to_u16())
  43. }
  44. /// Converts the value of `self` to an `u32`.
  45. #[inline]
  46. fn to_u32(&self) -> Option<u32> {
  47. self.to_u64().and_then(|x| x.to_u32())
  48. }
  49. /// Converts the value of `self` to an `u64`.
  50. #[inline]
  51. fn to_u64(&self) -> Option<u64>;
  52. /// Converts the value of `self` to an `f32`.
  53. #[inline]
  54. fn to_f32(&self) -> Option<f32> {
  55. self.to_f64().and_then(|x| x.to_f32())
  56. }
  57. /// Converts the value of `self` to an `f64`.
  58. #[inline]
  59. fn to_f64(&self) -> Option<f64> {
  60. self.to_i64().and_then(|x| x.to_f64())
  61. }
  62. }
  63. macro_rules! impl_to_primitive_int_to_int {
  64. ($SrcT:ty, $DstT:ty, $slf:expr) => (
  65. {
  66. if size_of::<$SrcT>() <= size_of::<$DstT>() {
  67. Some($slf as $DstT)
  68. } else {
  69. let n = $slf as i64;
  70. let min_value: $DstT = Bounded::min_value();
  71. let max_value: $DstT = Bounded::max_value();
  72. if min_value as i64 <= n && n <= max_value as i64 {
  73. Some($slf as $DstT)
  74. } else {
  75. None
  76. }
  77. }
  78. }
  79. )
  80. }
  81. macro_rules! impl_to_primitive_int_to_uint {
  82. ($SrcT:ty, $DstT:ty, $slf:expr) => (
  83. {
  84. let zero: $SrcT = Zero::zero();
  85. let max_value: $DstT = Bounded::max_value();
  86. if zero <= $slf && $slf as u64 <= max_value as u64 {
  87. Some($slf as $DstT)
  88. } else {
  89. None
  90. }
  91. }
  92. )
  93. }
  94. macro_rules! impl_to_primitive_int {
  95. ($T:ty) => (
  96. impl ToPrimitive for $T {
  97. #[inline]
  98. fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) }
  99. #[inline]
  100. fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
  101. #[inline]
  102. fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
  103. #[inline]
  104. fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
  105. #[inline]
  106. fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
  107. #[inline]
  108. fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) }
  109. #[inline]
  110. fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
  111. #[inline]
  112. fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
  113. #[inline]
  114. fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
  115. #[inline]
  116. fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
  117. #[inline]
  118. fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
  119. #[inline]
  120. fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
  121. }
  122. )
  123. }
  124. impl_to_primitive_int!(isize);
  125. impl_to_primitive_int!(i8);
  126. impl_to_primitive_int!(i16);
  127. impl_to_primitive_int!(i32);
  128. impl_to_primitive_int!(i64);
  129. macro_rules! impl_to_primitive_uint_to_int {
  130. ($DstT:ty, $slf:expr) => (
  131. {
  132. let max_value: $DstT = Bounded::max_value();
  133. if $slf as u64 <= max_value as u64 {
  134. Some($slf as $DstT)
  135. } else {
  136. None
  137. }
  138. }
  139. )
  140. }
  141. macro_rules! impl_to_primitive_uint_to_uint {
  142. ($SrcT:ty, $DstT:ty, $slf:expr) => (
  143. {
  144. if size_of::<$SrcT>() <= size_of::<$DstT>() {
  145. Some($slf as $DstT)
  146. } else {
  147. let zero: $SrcT = Zero::zero();
  148. let max_value: $DstT = Bounded::max_value();
  149. if zero <= $slf && $slf as u64 <= max_value as u64 {
  150. Some($slf as $DstT)
  151. } else {
  152. None
  153. }
  154. }
  155. }
  156. )
  157. }
  158. macro_rules! impl_to_primitive_uint {
  159. ($T:ty) => (
  160. impl ToPrimitive for $T {
  161. #[inline]
  162. fn to_isize(&self) -> Option<isize> { impl_to_primitive_uint_to_int!(isize, *self) }
  163. #[inline]
  164. fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
  165. #[inline]
  166. fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
  167. #[inline]
  168. fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
  169. #[inline]
  170. fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
  171. #[inline]
  172. fn to_usize(&self) -> Option<usize> {
  173. impl_to_primitive_uint_to_uint!($T, usize, *self)
  174. }
  175. #[inline]
  176. fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
  177. #[inline]
  178. fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
  179. #[inline]
  180. fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
  181. #[inline]
  182. fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
  183. #[inline]
  184. fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
  185. #[inline]
  186. fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
  187. }
  188. )
  189. }
  190. impl_to_primitive_uint!(usize);
  191. impl_to_primitive_uint!(u8);
  192. impl_to_primitive_uint!(u16);
  193. impl_to_primitive_uint!(u32);
  194. impl_to_primitive_uint!(u64);
  195. macro_rules! impl_to_primitive_float_to_float {
  196. ($SrcT:ident, $DstT:ident, $slf:expr) => (
  197. if size_of::<$SrcT>() <= size_of::<$DstT>() {
  198. Some($slf as $DstT)
  199. } else {
  200. // Make sure the value is in range for the cast.
  201. // NaN and +-inf are cast as they are.
  202. let n = $slf as f64;
  203. let max_value: $DstT = ::std::$DstT::MAX;
  204. if !n.is_finite() || (-max_value as f64 <= n && n <= max_value as f64) {
  205. Some($slf as $DstT)
  206. } else {
  207. None
  208. }
  209. }
  210. )
  211. }
  212. macro_rules! impl_to_primitive_float {
  213. ($T:ident) => (
  214. impl ToPrimitive for $T {
  215. #[inline]
  216. fn to_isize(&self) -> Option<isize> { Some(*self as isize) }
  217. #[inline]
  218. fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
  219. #[inline]
  220. fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
  221. #[inline]
  222. fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
  223. #[inline]
  224. fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
  225. #[inline]
  226. fn to_usize(&self) -> Option<usize> { Some(*self as usize) }
  227. #[inline]
  228. fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
  229. #[inline]
  230. fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
  231. #[inline]
  232. fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
  233. #[inline]
  234. fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
  235. #[inline]
  236. fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
  237. #[inline]
  238. fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
  239. }
  240. )
  241. }
  242. impl_to_primitive_float!(f32);
  243. impl_to_primitive_float!(f64);
  244. /// A generic trait for converting a number to a value.
  245. pub trait FromPrimitive: Sized {
  246. /// Convert an `isize` to return an optional value of this type. If the
  247. /// value cannot be represented by this value, the `None` is returned.
  248. #[inline]
  249. fn from_isize(n: isize) -> Option<Self> {
  250. FromPrimitive::from_i64(n as i64)
  251. }
  252. /// Convert an `i8` to return an optional value of this type. If the
  253. /// type cannot be represented by this value, the `None` is returned.
  254. #[inline]
  255. fn from_i8(n: i8) -> Option<Self> {
  256. FromPrimitive::from_i64(n as i64)
  257. }
  258. /// Convert an `i16` to return an optional value of this type. If the
  259. /// type cannot be represented by this value, the `None` is returned.
  260. #[inline]
  261. fn from_i16(n: i16) -> Option<Self> {
  262. FromPrimitive::from_i64(n as i64)
  263. }
  264. /// Convert an `i32` to return an optional value of this type. If the
  265. /// type cannot be represented by this value, the `None` is returned.
  266. #[inline]
  267. fn from_i32(n: i32) -> Option<Self> {
  268. FromPrimitive::from_i64(n as i64)
  269. }
  270. /// Convert an `i64` to return an optional value of this type. If the
  271. /// type cannot be represented by this value, the `None` is returned.
  272. fn from_i64(n: i64) -> Option<Self>;
  273. /// Convert a `usize` to return an optional value of this type. If the
  274. /// type cannot be represented by this value, the `None` is returned.
  275. #[inline]
  276. fn from_usize(n: usize) -> Option<Self> {
  277. FromPrimitive::from_u64(n as u64)
  278. }
  279. /// Convert an `u8` to return an optional value of this type. If the
  280. /// type cannot be represented by this value, the `None` is returned.
  281. #[inline]
  282. fn from_u8(n: u8) -> Option<Self> {
  283. FromPrimitive::from_u64(n as u64)
  284. }
  285. /// Convert an `u16` to return an optional value of this type. If the
  286. /// type cannot be represented by this value, the `None` is returned.
  287. #[inline]
  288. fn from_u16(n: u16) -> Option<Self> {
  289. FromPrimitive::from_u64(n as u64)
  290. }
  291. /// Convert an `u32` to return an optional value of this type. If the
  292. /// type cannot be represented by this value, the `None` is returned.
  293. #[inline]
  294. fn from_u32(n: u32) -> Option<Self> {
  295. FromPrimitive::from_u64(n as u64)
  296. }
  297. /// Convert an `u64` to return an optional value of this type. If the
  298. /// type cannot be represented by this value, the `None` is returned.
  299. fn from_u64(n: u64) -> Option<Self>;
  300. /// Convert a `f32` to return an optional value of this type. If the
  301. /// type cannot be represented by this value, the `None` is returned.
  302. #[inline]
  303. fn from_f32(n: f32) -> Option<Self> {
  304. FromPrimitive::from_f64(n as f64)
  305. }
  306. /// Convert a `f64` to return an optional value of this type. If the
  307. /// type cannot be represented by this value, the `None` is returned.
  308. #[inline]
  309. fn from_f64(n: f64) -> Option<Self> {
  310. FromPrimitive::from_i64(n as i64)
  311. }
  312. }
  313. macro_rules! impl_from_primitive {
  314. ($T:ty, $to_ty:ident) => (
  315. #[allow(deprecated)]
  316. impl FromPrimitive for $T {
  317. #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
  318. #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
  319. #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
  320. #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
  321. #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
  322. #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
  323. #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
  324. #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
  325. #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
  326. #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
  327. }
  328. )
  329. }
  330. impl_from_primitive!(isize, to_isize);
  331. impl_from_primitive!(i8, to_i8);
  332. impl_from_primitive!(i16, to_i16);
  333. impl_from_primitive!(i32, to_i32);
  334. impl_from_primitive!(i64, to_i64);
  335. impl_from_primitive!(usize, to_usize);
  336. impl_from_primitive!(u8, to_u8);
  337. impl_from_primitive!(u16, to_u16);
  338. impl_from_primitive!(u32, to_u32);
  339. impl_from_primitive!(u64, to_u64);
  340. impl_from_primitive!(f32, to_f32);
  341. impl_from_primitive!(f64, to_f64);
  342. impl<T: ToPrimitive> ToPrimitive for Wrapping<T> {
  343. fn to_i64(&self) -> Option<i64> { self.0.to_i64() }
  344. fn to_u64(&self) -> Option<u64> { self.0.to_u64() }
  345. }
  346. impl<T: FromPrimitive> FromPrimitive for Wrapping<T> {
  347. fn from_u64(n: u64) -> Option<Self> { T::from_u64(n).map(Wrapping) }
  348. fn from_i64(n: i64) -> Option<Self> { T::from_i64(n).map(Wrapping) }
  349. }
  350. /// Cast from one machine scalar to another.
  351. ///
  352. /// # Examples
  353. ///
  354. /// ```
  355. /// # use num_traits as num;
  356. /// let twenty: f32 = num::cast(0x14).unwrap();
  357. /// assert_eq!(twenty, 20f32);
  358. /// ```
  359. ///
  360. #[inline]
  361. pub fn cast<T: NumCast, U: NumCast>(n: T) -> Option<U> {
  362. NumCast::from(n)
  363. }
  364. /// An interface for casting between machine scalars.
  365. pub trait NumCast: Sized + ToPrimitive {
  366. /// Creates a number from another value that can be converted into
  367. /// a primitive via the `ToPrimitive` trait.
  368. fn from<T: ToPrimitive>(n: T) -> Option<Self>;
  369. }
  370. macro_rules! impl_num_cast {
  371. ($T:ty, $conv:ident) => (
  372. impl NumCast for $T {
  373. #[inline]
  374. #[allow(deprecated)]
  375. fn from<N: ToPrimitive>(n: N) -> Option<$T> {
  376. // `$conv` could be generated using `concat_idents!`, but that
  377. // macro seems to be broken at the moment
  378. n.$conv()
  379. }
  380. }
  381. )
  382. }
  383. impl_num_cast!(u8, to_u8);
  384. impl_num_cast!(u16, to_u16);
  385. impl_num_cast!(u32, to_u32);
  386. impl_num_cast!(u64, to_u64);
  387. impl_num_cast!(usize, to_usize);
  388. impl_num_cast!(i8, to_i8);
  389. impl_num_cast!(i16, to_i16);
  390. impl_num_cast!(i32, to_i32);
  391. impl_num_cast!(i64, to_i64);
  392. impl_num_cast!(isize, to_isize);
  393. impl_num_cast!(f32, to_f32);
  394. impl_num_cast!(f64, to_f64);
  395. impl<T: NumCast> NumCast for Wrapping<T> {
  396. fn from<U: ToPrimitive>(n: U) -> Option<Self> {
  397. T::from(n).map(Wrapping)
  398. }
  399. }
  400. #[test]
  401. fn to_primitive_float() {
  402. use std::f32;
  403. use std::f64;
  404. let f32_toolarge = 1e39f64;
  405. assert_eq!(f32_toolarge.to_f32(), None);
  406. assert_eq!((f32::MAX as f64).to_f32(), Some(f32::MAX));
  407. assert_eq!((-f32::MAX as f64).to_f32(), Some(-f32::MAX));
  408. assert_eq!(f64::INFINITY.to_f32(), Some(f32::INFINITY));
  409. assert_eq!((f64::NEG_INFINITY).to_f32(), Some(f32::NEG_INFINITY));
  410. assert!((f64::NAN).to_f32().map_or(false, |f| f.is_nan()));
  411. }
  412. macro_rules! test_wrapping_to_primitive {
  413. ($($t:ty)+) => {
  414. $({
  415. let i: $t = 0;
  416. let w = Wrapping(i);
  417. assert_eq!(i.to_u8(), w.to_u8());
  418. assert_eq!(i.to_u16(), w.to_u16());
  419. assert_eq!(i.to_u32(), w.to_u32());
  420. assert_eq!(i.to_u64(), w.to_u64());
  421. assert_eq!(i.to_usize(), w.to_usize());
  422. assert_eq!(i.to_i8(), w.to_i8());
  423. assert_eq!(i.to_i16(), w.to_i16());
  424. assert_eq!(i.to_i32(), w.to_i32());
  425. assert_eq!(i.to_i64(), w.to_i64());
  426. assert_eq!(i.to_isize(), w.to_isize());
  427. assert_eq!(i.to_f32(), w.to_f32());
  428. assert_eq!(i.to_f64(), w.to_f64());
  429. })+
  430. };
  431. }
  432. #[test]
  433. fn wrapping_to_primitive() {
  434. test_wrapping_to_primitive!(usize u8 u16 u32 u64 isize i8 i16 i32 i64);
  435. }
  436. #[test]
  437. fn wrapping_is_toprimitive() {
  438. fn require_toprimitive<T: ToPrimitive>(_: &T) {}
  439. require_toprimitive(&Wrapping(42));
  440. }
  441. #[test]
  442. fn wrapping_is_fromprimitive() {
  443. fn require_fromprimitive<T: FromPrimitive>(_: &T) {}
  444. require_fromprimitive(&Wrapping(42));
  445. }
  446. #[test]
  447. fn wrapping_is_numcast() {
  448. fn require_numcast<T: NumCast>(_: &T) {}
  449. require_numcast(&Wrapping(42));
  450. }