From c32cb5c65b18750cfb6476cdc879fa3ca3a80f5a Mon Sep 17 00:00:00 2001 From: Alexander Popiak Date: Mon, 29 Jan 2018 19:15:56 -0500 Subject: [PATCH] Patch in apopiak@'s changes from github.com/rust-num/num/pull/135/. --- src/cast.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 51 insertions(+), 9 deletions(-) diff --git a/src/cast.rs b/src/cast.rs index 288acf4..94230ae 100644 --- a/src/cast.rs +++ b/src/cast.rs @@ -240,17 +240,11 @@ macro_rules! impl_to_primitive_float_to_float { macro_rules! impl_to_primitive_float_to_signed_int { ($SrcT:ident, $DstT:ident, $slf:expr) => ( - if size_of::<$SrcT>() <= size_of::<$DstT>() { + let t = $slf.trunc(); + if t >= $DstT::MIN as $SrcT && t <= $DstT::MAX as $SrcT { Some($slf as $DstT) } else { - // Make sure the value is in range for the cast. - let n = $slf as $DstT; - let max_value: $DstT = ::std::$DstT::MAX; - if -max_value as $DstT <= n && n <= max_value as $DstT { - Some($slf as $DstT) - } else { - None - } + None } ) } @@ -658,3 +652,51 @@ fn float_to_integer_checks_overflow() { // Expect the overflow to be caught assert_eq!(cast::(source), None); } + +#[test] +fn test_cast_to_int() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as isize), cast::(normal_f)); + assert_eq!(Some(normal_f as i8), cast::(normal_f)); + assert_eq!(Some(normal_f as i16), cast::(normal_f)); + assert_eq!(Some(normal_f as i32), cast::(normal_f)); + assert_eq!(Some(normal_f as i64), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +} + +#[test] +fn test_cast_to_unsigned_int() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as usize), cast::(normal_f)); + assert_eq!(Some(normal_f as u8), cast::(normal_f)); + assert_eq!(Some(normal_f as u16), cast::(normal_f)); + assert_eq!(Some(normal_f as u32), cast::(normal_f)); + assert_eq!(Some(normal_f as u64), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +}