cast.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. //! Tests of `num_traits::cast`.
  2. #![no_std]
  3. #[cfg(feature = "std")]
  4. #[macro_use]
  5. extern crate std;
  6. extern crate num_traits;
  7. use num_traits::cast::*;
  8. use num_traits::Bounded;
  9. use core::{f32, f64};
  10. #[cfg(has_i128)]
  11. use core::{i128, u128};
  12. use core::{i16, i32, i64, i8, isize};
  13. use core::{u16, u32, u64, u8, usize};
  14. use core::fmt::Debug;
  15. use core::mem;
  16. use core::num::Wrapping;
  17. #[test]
  18. fn to_primitive_float() {
  19. let f32_toolarge = 1e39f64;
  20. assert_eq!(f32_toolarge.to_f32(), Some(f32::INFINITY));
  21. assert_eq!((-f32_toolarge).to_f32(), Some(f32::NEG_INFINITY));
  22. assert_eq!((f32::MAX as f64).to_f32(), Some(f32::MAX));
  23. assert_eq!((-f32::MAX as f64).to_f32(), Some(-f32::MAX));
  24. assert_eq!(f64::INFINITY.to_f32(), Some(f32::INFINITY));
  25. assert_eq!((f64::NEG_INFINITY).to_f32(), Some(f32::NEG_INFINITY));
  26. assert!((f64::NAN).to_f32().map_or(false, |f| f.is_nan()));
  27. }
  28. #[test]
  29. fn wrapping_to_primitive() {
  30. macro_rules! test_wrapping_to_primitive {
  31. ($($t:ty)+) => {
  32. $({
  33. let i: $t = 0;
  34. let w = Wrapping(i);
  35. assert_eq!(i.to_u8(), w.to_u8());
  36. assert_eq!(i.to_u16(), w.to_u16());
  37. assert_eq!(i.to_u32(), w.to_u32());
  38. assert_eq!(i.to_u64(), w.to_u64());
  39. assert_eq!(i.to_usize(), w.to_usize());
  40. assert_eq!(i.to_i8(), w.to_i8());
  41. assert_eq!(i.to_i16(), w.to_i16());
  42. assert_eq!(i.to_i32(), w.to_i32());
  43. assert_eq!(i.to_i64(), w.to_i64());
  44. assert_eq!(i.to_isize(), w.to_isize());
  45. assert_eq!(i.to_f32(), w.to_f32());
  46. assert_eq!(i.to_f64(), w.to_f64());
  47. })+
  48. };
  49. }
  50. test_wrapping_to_primitive!(usize u8 u16 u32 u64 isize i8 i16 i32 i64);
  51. }
  52. #[test]
  53. fn wrapping_is_toprimitive() {
  54. fn require_toprimitive<T: ToPrimitive>(_: &T) {}
  55. require_toprimitive(&Wrapping(42));
  56. }
  57. #[test]
  58. fn wrapping_is_fromprimitive() {
  59. fn require_fromprimitive<T: FromPrimitive>(_: &T) {}
  60. require_fromprimitive(&Wrapping(42));
  61. }
  62. #[test]
  63. fn wrapping_is_numcast() {
  64. fn require_numcast<T: NumCast>(_: &T) {}
  65. require_numcast(&Wrapping(42));
  66. }
  67. #[test]
  68. fn as_primitive() {
  69. let x: f32 = (1.625f64).as_();
  70. assert_eq!(x, 1.625f32);
  71. let x: f32 = (3.14159265358979323846f64).as_();
  72. assert_eq!(x, 3.1415927f32);
  73. let x: u8 = (768i16).as_();
  74. assert_eq!(x, 0);
  75. }
  76. #[test]
  77. fn float_to_integer_checks_overflow() {
  78. // This will overflow an i32
  79. let source: f64 = 1.0e+123f64;
  80. // Expect the overflow to be caught
  81. assert_eq!(cast::<f64, i32>(source), None);
  82. }
  83. #[test]
  84. fn cast_to_int_checks_overflow() {
  85. let big_f: f64 = 1.0e123;
  86. let normal_f: f64 = 1.0;
  87. let small_f: f64 = -1.0e123;
  88. assert_eq!(None, cast::<f64, isize>(big_f));
  89. assert_eq!(None, cast::<f64, i8>(big_f));
  90. assert_eq!(None, cast::<f64, i16>(big_f));
  91. assert_eq!(None, cast::<f64, i32>(big_f));
  92. assert_eq!(None, cast::<f64, i64>(big_f));
  93. assert_eq!(Some(normal_f as isize), cast::<f64, isize>(normal_f));
  94. assert_eq!(Some(normal_f as i8), cast::<f64, i8>(normal_f));
  95. assert_eq!(Some(normal_f as i16), cast::<f64, i16>(normal_f));
  96. assert_eq!(Some(normal_f as i32), cast::<f64, i32>(normal_f));
  97. assert_eq!(Some(normal_f as i64), cast::<f64, i64>(normal_f));
  98. assert_eq!(None, cast::<f64, isize>(small_f));
  99. assert_eq!(None, cast::<f64, i8>(small_f));
  100. assert_eq!(None, cast::<f64, i16>(small_f));
  101. assert_eq!(None, cast::<f64, i32>(small_f));
  102. assert_eq!(None, cast::<f64, i64>(small_f));
  103. }
  104. #[test]
  105. fn cast_to_unsigned_int_checks_overflow() {
  106. let big_f: f64 = 1.0e123;
  107. let normal_f: f64 = 1.0;
  108. let small_f: f64 = -1.0e123;
  109. assert_eq!(None, cast::<f64, usize>(big_f));
  110. assert_eq!(None, cast::<f64, u8>(big_f));
  111. assert_eq!(None, cast::<f64, u16>(big_f));
  112. assert_eq!(None, cast::<f64, u32>(big_f));
  113. assert_eq!(None, cast::<f64, u64>(big_f));
  114. assert_eq!(Some(normal_f as usize), cast::<f64, usize>(normal_f));
  115. assert_eq!(Some(normal_f as u8), cast::<f64, u8>(normal_f));
  116. assert_eq!(Some(normal_f as u16), cast::<f64, u16>(normal_f));
  117. assert_eq!(Some(normal_f as u32), cast::<f64, u32>(normal_f));
  118. assert_eq!(Some(normal_f as u64), cast::<f64, u64>(normal_f));
  119. assert_eq!(None, cast::<f64, usize>(small_f));
  120. assert_eq!(None, cast::<f64, u8>(small_f));
  121. assert_eq!(None, cast::<f64, u16>(small_f));
  122. assert_eq!(None, cast::<f64, u32>(small_f));
  123. assert_eq!(None, cast::<f64, u64>(small_f));
  124. }
  125. #[test]
  126. #[cfg(has_i128)]
  127. fn cast_to_i128_checks_overflow() {
  128. let big_f: f64 = 1.0e123;
  129. let normal_f: f64 = 1.0;
  130. let small_f: f64 = -1.0e123;
  131. assert_eq!(None, cast::<f64, i128>(big_f));
  132. assert_eq!(None, cast::<f64, u128>(big_f));
  133. assert_eq!(Some(normal_f as i128), cast::<f64, i128>(normal_f));
  134. assert_eq!(Some(normal_f as u128), cast::<f64, u128>(normal_f));
  135. assert_eq!(None, cast::<f64, i128>(small_f));
  136. assert_eq!(None, cast::<f64, u128>(small_f));
  137. }
  138. #[cfg(feature = "std")]
  139. fn dbg(args: ::core::fmt::Arguments) {
  140. println!("{}", args);
  141. }
  142. #[cfg(not(feature = "std"))]
  143. fn dbg(_: ::core::fmt::Arguments) {}
  144. // Rust 1.8 doesn't handle cfg on macros correctly
  145. macro_rules! dbg { ($($tok:tt)*) => { dbg(format_args!($($tok)*)) } }
  146. macro_rules! float_test_edge {
  147. ($f:ident -> $($t:ident)+) => { $({
  148. dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t));
  149. let small = if $t::MIN == 0 || mem::size_of::<$t>() < mem::size_of::<$f>() {
  150. $t::MIN as $f - 1.0
  151. } else {
  152. ($t::MIN as $f).raw_offset(1).floor()
  153. };
  154. let fmin = small.raw_offset(-1);
  155. dbg!(" testing min {}\n\tvs. {:.0}\n\tand {:.0}", $t::MIN, fmin, small);
  156. assert_eq!(Some($t::MIN), cast::<$f, $t>($t::MIN as $f));
  157. assert_eq!(Some($t::MIN), cast::<$f, $t>(fmin));
  158. assert_eq!(None, cast::<$f, $t>(small));
  159. let (max, large) = if mem::size_of::<$t>() < mem::size_of::<$f>() {
  160. ($t::MAX, $t::MAX as $f + 1.0)
  161. } else {
  162. let large = $t::MAX as $f; // rounds up!
  163. let max = large.raw_offset(-1) as $t; // the next smallest possible
  164. assert_eq!(max.count_ones(), $f::MANTISSA_DIGITS);
  165. (max, large)
  166. };
  167. let fmax = large.raw_offset(-1);
  168. dbg!(" testing max {}\n\tvs. {:.0}\n\tand {:.0}", max, fmax, large);
  169. assert_eq!(Some(max), cast::<$f, $t>(max as $f));
  170. assert_eq!(Some(max), cast::<$f, $t>(fmax));
  171. assert_eq!(None, cast::<$f, $t>(large));
  172. dbg!(" testing non-finite values");
  173. assert_eq!(None, cast::<$f, $t>($f::NAN));
  174. assert_eq!(None, cast::<$f, $t>($f::INFINITY));
  175. assert_eq!(None, cast::<$f, $t>($f::NEG_INFINITY));
  176. })+}
  177. }
  178. trait RawOffset: Sized {
  179. type Raw;
  180. fn raw_offset(self, offset: Self::Raw) -> Self;
  181. }
  182. impl RawOffset for f32 {
  183. type Raw = i32;
  184. fn raw_offset(self, offset: Self::Raw) -> Self {
  185. unsafe {
  186. let raw: Self::Raw = mem::transmute(self);
  187. mem::transmute(raw + offset)
  188. }
  189. }
  190. }
  191. impl RawOffset for f64 {
  192. type Raw = i64;
  193. fn raw_offset(self, offset: Self::Raw) -> Self {
  194. unsafe {
  195. let raw: Self::Raw = mem::transmute(self);
  196. mem::transmute(raw + offset)
  197. }
  198. }
  199. }
  200. #[test]
  201. fn cast_float_to_int_edge_cases() {
  202. float_test_edge!(f32 -> isize i8 i16 i32 i64);
  203. float_test_edge!(f32 -> usize u8 u16 u32 u64);
  204. float_test_edge!(f64 -> isize i8 i16 i32 i64);
  205. float_test_edge!(f64 -> usize u8 u16 u32 u64);
  206. }
  207. #[test]
  208. #[cfg(has_i128)]
  209. fn cast_float_to_i128_edge_cases() {
  210. float_test_edge!(f32 -> i128 u128);
  211. float_test_edge!(f64 -> i128 u128);
  212. }
  213. macro_rules! int_test_edge {
  214. ($f:ident -> { $($t:ident)+ } with $BigS:ident $BigU:ident ) => { $({
  215. fn test_edge() {
  216. dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t));
  217. match ($f::MIN as $BigS).cmp(&($t::MIN as $BigS)) {
  218. Greater => {
  219. assert_eq!(Some($f::MIN as $t), cast::<$f, $t>($f::MIN));
  220. }
  221. Equal => {
  222. assert_eq!(Some($t::MIN), cast::<$f, $t>($f::MIN));
  223. }
  224. Less => {
  225. let min = $t::MIN as $f;
  226. assert_eq!(Some($t::MIN), cast::<$f, $t>(min));
  227. assert_eq!(None, cast::<$f, $t>(min - 1));
  228. }
  229. }
  230. match ($f::MAX as $BigU).cmp(&($t::MAX as $BigU)) {
  231. Greater => {
  232. let max = $t::MAX as $f;
  233. assert_eq!(Some($t::MAX), cast::<$f, $t>(max));
  234. assert_eq!(None, cast::<$f, $t>(max + 1));
  235. }
  236. Equal => {
  237. assert_eq!(Some($t::MAX), cast::<$f, $t>($f::MAX));
  238. }
  239. Less => {
  240. assert_eq!(Some($f::MAX as $t), cast::<$f, $t>($f::MAX));
  241. }
  242. }
  243. }
  244. test_edge();
  245. })+}
  246. }
  247. #[test]
  248. fn cast_int_to_int_edge_cases() {
  249. use core::cmp::Ordering::*;
  250. macro_rules! test_edge {
  251. ($( $from:ident )+) => { $({
  252. int_test_edge!($from -> { isize i8 i16 i32 i64 } with i64 u64);
  253. int_test_edge!($from -> { usize u8 u16 u32 u64 } with i64 u64);
  254. })+}
  255. }
  256. test_edge!(isize i8 i16 i32 i64);
  257. test_edge!(usize u8 u16 u32 u64);
  258. }
  259. #[test]
  260. #[cfg(has_i128)]
  261. fn cast_int_to_128_edge_cases() {
  262. use core::cmp::Ordering::*;
  263. macro_rules! test_edge {
  264. ($( $t:ident )+) => {
  265. $(
  266. int_test_edge!($t -> { i128 u128 } with i128 u128);
  267. )+
  268. int_test_edge!(i128 -> { $( $t )+ } with i128 u128);
  269. int_test_edge!(u128 -> { $( $t )+ } with i128 u128);
  270. }
  271. }
  272. test_edge!(isize i8 i16 i32 i64 i128);
  273. test_edge!(usize u8 u16 u32 u64 u128);
  274. }
  275. #[test]
  276. fn newtype_from_primitive() {
  277. #[derive(PartialEq, Debug)]
  278. struct New<T>(T);
  279. // minimal impl
  280. impl<T: FromPrimitive> FromPrimitive for New<T> {
  281. fn from_i64(n: i64) -> Option<Self> {
  282. T::from_i64(n).map(New)
  283. }
  284. fn from_u64(n: u64) -> Option<Self> {
  285. T::from_u64(n).map(New)
  286. }
  287. }
  288. macro_rules! assert_eq_from {
  289. ($( $from:ident )+) => {$(
  290. assert_eq!(T::$from(Bounded::min_value()).map(New),
  291. New::<T>::$from(Bounded::min_value()));
  292. assert_eq!(T::$from(Bounded::max_value()).map(New),
  293. New::<T>::$from(Bounded::max_value()));
  294. )+}
  295. }
  296. fn check<T: PartialEq + Debug + FromPrimitive>() {
  297. assert_eq_from!(from_i8 from_i16 from_i32 from_i64 from_isize);
  298. assert_eq_from!(from_u8 from_u16 from_u32 from_u64 from_usize);
  299. assert_eq_from!(from_f32 from_f64);
  300. }
  301. macro_rules! check {
  302. ($( $ty:ty )+) => {$( check::<$ty>(); )+}
  303. }
  304. check!(i8 i16 i32 i64 isize);
  305. check!(u8 u16 u32 u64 usize);
  306. }
  307. #[test]
  308. fn newtype_to_primitive() {
  309. #[derive(PartialEq, Debug)]
  310. struct New<T>(T);
  311. // minimal impl
  312. impl<T: ToPrimitive> ToPrimitive for New<T> {
  313. fn to_i64(&self) -> Option<i64> {
  314. self.0.to_i64()
  315. }
  316. fn to_u64(&self) -> Option<u64> {
  317. self.0.to_u64()
  318. }
  319. }
  320. macro_rules! assert_eq_to {
  321. ($( $to:ident )+) => {$(
  322. assert_eq!(T::$to(&Bounded::min_value()),
  323. New::<T>::$to(&New(Bounded::min_value())));
  324. assert_eq!(T::$to(&Bounded::max_value()),
  325. New::<T>::$to(&New(Bounded::max_value())));
  326. )+}
  327. }
  328. fn check<T: PartialEq + Debug + Bounded + ToPrimitive>() {
  329. assert_eq_to!(to_i8 to_i16 to_i32 to_i64 to_isize);
  330. assert_eq_to!(to_u8 to_u16 to_u32 to_u64 to_usize);
  331. assert_eq_to!(to_f32 to_f64);
  332. }
  333. macro_rules! check {
  334. ($( $ty:ty )+) => {$( check::<$ty>(); )+}
  335. }
  336. check!(i8 i16 i32 i64 isize);
  337. check!(u8 u16 u32 u64 usize);
  338. }