cast.rs 12 KB

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