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