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