Skip to content

Commit fc5f6c4

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 7eb666f commit fc5f6c4

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/traits.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1216,7 +1216,7 @@ macro_rules! impl_to_primitive_float_to_float {
12161216
Some($slf as $DstT)
12171217
} else {
12181218
let n = $slf as f64;
1219-
let max_value: $SrcT = ::std::$SrcT::MAX;
1219+
let max_value: $DstT = ::std::$DstT::MAX;
12201220
if -max_value as f64 <= n && n <= max_value as f64 {
12211221
Some($slf as $DstT)
12221222
} else {
@@ -2550,3 +2550,11 @@ fn from_str_radix_unwrap() {
25502550
let f: f32 = Num::from_str_radix("0.0", 10).unwrap();
25512551
assert_eq!(f, 0.0);
25522552
}
2553+
2554+
#[test]
2555+
fn to_primitive_float() {
2556+
let f32_max = ::std::f32::MAX;
2557+
let f32_toolarge = 1e39f64;
2558+
assert_eq!((f32_max as f64).to_f32(), Some(f32_max));
2559+
assert_eq!(f32_toolarge.to_f32(), None);
2560+
}

0 commit comments

Comments
 (0)