cast.rs 12 KB

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