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_inc().floor()
  146. };
  147. let fmin = small.raw_dec();
  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_dec() as $t; // the next smallest possible
  157. assert_eq!(max.count_ones(), $f::MANTISSA_DIGITS);
  158. (max, large)
  159. };
  160. let fmax = large.raw_dec();
  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. fn raw_inc(self) -> Self;
  173. fn raw_dec(self) -> Self;
  174. }
  175. impl RawOffset for f32 {
  176. fn raw_inc(self) -> Self {
  177. Self::from_bits(self.to_bits() + 1)
  178. }
  179. fn raw_dec(self) -> Self {
  180. Self::from_bits(self.to_bits() - 1)
  181. }
  182. }
  183. impl RawOffset for f64 {
  184. fn raw_inc(self) -> Self {
  185. Self::from_bits(self.to_bits() + 1)
  186. }
  187. fn raw_dec(self) -> Self {
  188. Self::from_bits(self.to_bits() - 1)
  189. }
  190. }
  191. #[test]
  192. fn cast_float_to_int_edge_cases() {
  193. float_test_edge!(f32 -> isize i8 i16 i32 i64);
  194. float_test_edge!(f32 -> usize u8 u16 u32 u64);
  195. float_test_edge!(f64 -> isize i8 i16 i32 i64);
  196. float_test_edge!(f64 -> usize u8 u16 u32 u64);
  197. }
  198. #[test]
  199. fn cast_float_to_i128_edge_cases() {
  200. float_test_edge!(f32 -> i128 u128);
  201. float_test_edge!(f64 -> i128 u128);
  202. }
  203. macro_rules! int_test_edge {
  204. ($f:ident -> { $($t:ident)+ } with $BigS:ident $BigU:ident ) => { $({
  205. fn test_edge() {
  206. dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t));
  207. match ($f::MIN as $BigS).cmp(&($t::MIN as $BigS)) {
  208. Greater => {
  209. assert_eq!(Some($f::MIN as $t), cast::<$f, $t>($f::MIN));
  210. }
  211. Equal => {
  212. assert_eq!(Some($t::MIN), cast::<$f, $t>($f::MIN));
  213. }
  214. Less => {
  215. let min = $t::MIN as $f;
  216. assert_eq!(Some($t::MIN), cast::<$f, $t>(min));
  217. assert_eq!(None, cast::<$f, $t>(min - 1));
  218. }
  219. }
  220. match ($f::MAX as $BigU).cmp(&($t::MAX as $BigU)) {
  221. Greater => {
  222. let max = $t::MAX as $f;
  223. assert_eq!(Some($t::MAX), cast::<$f, $t>(max));
  224. assert_eq!(None, cast::<$f, $t>(max + 1));
  225. }
  226. Equal => {
  227. assert_eq!(Some($t::MAX), cast::<$f, $t>($f::MAX));
  228. }
  229. Less => {
  230. assert_eq!(Some($f::MAX as $t), cast::<$f, $t>($f::MAX));
  231. }
  232. }
  233. }
  234. test_edge();
  235. })+}
  236. }
  237. #[test]
  238. fn cast_int_to_int_edge_cases() {
  239. use core::cmp::Ordering::*;
  240. macro_rules! test_edge {
  241. ($( $from:ident )+) => { $({
  242. int_test_edge!($from -> { isize i8 i16 i32 i64 } with i64 u64);
  243. int_test_edge!($from -> { usize u8 u16 u32 u64 } with i64 u64);
  244. })+}
  245. }
  246. test_edge!(isize i8 i16 i32 i64);
  247. test_edge!(usize u8 u16 u32 u64);
  248. }
  249. #[test]
  250. fn cast_int_to_128_edge_cases() {
  251. use core::cmp::Ordering::*;
  252. macro_rules! test_edge {
  253. ($( $t:ident )+) => {
  254. $(
  255. int_test_edge!($t -> { i128 u128 } with i128 u128);
  256. )+
  257. int_test_edge!(i128 -> { $( $t )+ } with i128 u128);
  258. int_test_edge!(u128 -> { $( $t )+ } with i128 u128);
  259. }
  260. }
  261. test_edge!(isize i8 i16 i32 i64 i128);
  262. test_edge!(usize u8 u16 u32 u64 u128);
  263. }
  264. #[test]
  265. fn newtype_from_primitive() {
  266. #[derive(PartialEq, Debug)]
  267. struct New<T>(T);
  268. // minimal impl
  269. impl<T: FromPrimitive> FromPrimitive for New<T> {
  270. fn from_i64(n: i64) -> Option<Self> {
  271. T::from_i64(n).map(New)
  272. }
  273. fn from_u64(n: u64) -> Option<Self> {
  274. T::from_u64(n).map(New)
  275. }
  276. }
  277. macro_rules! assert_eq_from {
  278. ($( $from:ident )+) => {$(
  279. assert_eq!(T::$from(Bounded::min_value()).map(New),
  280. New::<T>::$from(Bounded::min_value()));
  281. assert_eq!(T::$from(Bounded::max_value()).map(New),
  282. New::<T>::$from(Bounded::max_value()));
  283. )+}
  284. }
  285. fn check<T: PartialEq + Debug + FromPrimitive>() {
  286. assert_eq_from!(from_i8 from_i16 from_i32 from_i64 from_isize);
  287. assert_eq_from!(from_u8 from_u16 from_u32 from_u64 from_usize);
  288. assert_eq_from!(from_f32 from_f64);
  289. }
  290. macro_rules! check {
  291. ($( $ty:ty )+) => {$( check::<$ty>(); )+}
  292. }
  293. check!(i8 i16 i32 i64 isize);
  294. check!(u8 u16 u32 u64 usize);
  295. }
  296. #[test]
  297. fn newtype_to_primitive() {
  298. #[derive(PartialEq, Debug)]
  299. struct New<T>(T);
  300. // minimal impl
  301. impl<T: ToPrimitive> ToPrimitive for New<T> {
  302. fn to_i64(&self) -> Option<i64> {
  303. self.0.to_i64()
  304. }
  305. fn to_u64(&self) -> Option<u64> {
  306. self.0.to_u64()
  307. }
  308. }
  309. macro_rules! assert_eq_to {
  310. ($( $to:ident )+) => {$(
  311. assert_eq!(T::$to(&Bounded::min_value()),
  312. New::<T>::$to(&New(Bounded::min_value())));
  313. assert_eq!(T::$to(&Bounded::max_value()),
  314. New::<T>::$to(&New(Bounded::max_value())));
  315. )+}
  316. }
  317. fn check<T: PartialEq + Debug + Bounded + ToPrimitive>() {
  318. assert_eq_to!(to_i8 to_i16 to_i32 to_i64 to_isize);
  319. assert_eq_to!(to_u8 to_u16 to_u32 to_u64 to_usize);
  320. assert_eq_to!(to_f32 to_f64);
  321. }
  322. macro_rules! check {
  323. ($( $ty:ty )+) => {$( check::<$ty>(); )+}
  324. }
  325. check!(i8 i16 i32 i64 isize);
  326. check!(u8 u16 u32 u64 usize);
  327. }