Skip to content

Commit

Permalink
factor in lossless representation in integer to float conversion check
Browse files Browse the repository at this point in the history
closes #23
  • Loading branch information
japaric committed Sep 4, 2021
1 parent 67aa147 commit c618d87
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,10 +281,19 @@ macro_rules! from_float {
src == $src::NEG_INFINITY {
Error::Infinite
} else if {
// we subtract 1 ULP (unit of least precision) here because some
// lossy conversions like `u64::MAX as f64` round *up* and we want
// to avoid this evaluating to false in that case
let max = $src::from_bits(($dst::MAX as $src).to_bits() - 1);
// this '$dst::BITS' works on 1.31.0 (MSRV)
let dst_bits = core::mem::size_of::<$dst>() as u32 * 8;
let lossless = dst_bits < core::$src::MANTISSA_DIGITS;

let max = if lossless {
$dst::MAX as $src
} else {
// we subtract 1 ULP (unit of least precision) here because some
// lossy conversions like `u64::MAX as f64` round *up* and we want
// to avoid the check below evaluating to false in that case
$src::from_bits(($dst::MAX as $src).to_bits() - 1)
};

src > max
} {
Error::Overflow
Expand Down
20 changes: 20 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,23 @@ fn gh15() {
assert_eq!(super::u16(16_f32.exp2()), Err(super::Error::Overflow));
assert_eq!(super::u16(16_f64.exp2()), Err(super::Error::Overflow));
}

#[test]
fn gh23_lossless_integer_max_min_to_float() {
// f32::MANTISSA_DIGITS = 24
assert_eq!(Ok(u8::MAX), super::u8(255f32));
assert_eq!(Ok(u16::MAX), super::u16(65_535f32));

// f64::MANTISSA_DIGITS = 53
assert_eq!(Ok(u8::MAX), super::u8(255f64));
assert_eq!(Ok(u16::MAX), super::u16(65_535f64));
assert_eq!(Ok(u32::MAX), super::u32(4_294_967_295f64));

// also check negative values (not part of the original bug)
assert_eq!(Ok(i8::MIN), super::i8(-128f32));
assert_eq!(Ok(i16::MIN), super::i16(-32_768f32));

assert_eq!(Ok(i8::MIN), super::i8(-128f64));
assert_eq!(Ok(i16::MIN), super::i16(-32_768f64));
assert_eq!(Ok(i32::MIN), super::i32(-2_147_483_648f64));
}

0 comments on commit c618d87

Please sign in to comment.