cast.rs 12 KB

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