Skip to content

Commit 190e89c

Browse files
committed
Fix ToPrimitive for f64 -> f32 conversion.
It should use the destination type and not the source type to check if the conversion would be to a value that's in range. Previously, too large f64 values would produce inf f32 values.
1 parent 1e192c3 commit 190e89c

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

traits/src/cast.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ macro_rules! impl_to_primitive_float_to_float {
223223
Some($slf as $DstT)
224224
} else {
225225
let n = $slf as f64;
226-
let max_value: $SrcT = ::std::$SrcT::MAX;
226+
let max_value: $DstT = ::std::$DstT::MAX;
227227
if -max_value as f64 <= n && n <= max_value as f64 {
228228
Some($slf as $DstT)
229229
} else {
@@ -431,3 +431,12 @@ impl_num_cast!(i64, to_i64);
431431
impl_num_cast!(isize, to_isize);
432432
impl_num_cast!(f32, to_f32);
433433
impl_num_cast!(f64, to_f64);
434+
435+
436+
#[test]
437+
fn to_primitive_float() {
438+
let f32_max = ::std::f32::MAX;
439+
let f32_toolarge = 1e39f64;
440+
assert_eq!((f32_max as f64).to_f32(), Some(f32_max));
441+
assert_eq!(f32_toolarge.to_f32(), None);
442+
}

0 commit comments

Comments
 (0)