Skip to content

Commit

Permalink
Fix f64 dec limit edge case (#678)
Browse files Browse the repository at this point in the history
---
Co-authored-by: Paul Mason <paul@paulmason.me>
  • Loading branch information
finnbear authored Sep 18, 2024
1 parent dfd84a5 commit ca982d6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2190,6 +2190,9 @@ fn base2_to_decimal(
exponent10 -= 1;
exponent5 += 1;
ops::array::shl1_internal(bits, 0);
} else if exponent10 * 2 > -exponent5 {
// Multiplying by >=2 which, due to the previous condition, means an overflow.
return None;
} else {
// The mantissa would overflow if shifted. Therefore it should be
// directly divided by 5. This will lose significant digits, unless
Expand Down
24 changes: 24 additions & 0 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3136,6 +3136,30 @@ fn it_converts_from_f64_limits() {
assert!(Decimal::try_from(f64::MIN).is_err(), "try_from(f64::MAX)");
}

#[test]
fn it_converts_from_f64_dec_limits() {
use num_traits::FromPrimitive;

// Note Decimal MAX is: 79_228_162_514_264_337_593_543_950_335
let over_max = 79_228_162_514_264_355_185_729_994_752_f64;
let max_plus_one = 79_228_162_514_264_337_593_543_950_336_f64;
let under_max = 79_228_162_514_264_328_797_450_928_128_f64;

assert!(
Decimal::from_f64(over_max).is_none(),
"from_f64(79_228_162_514_264_355_185_729_994_752_f64) -> none (too large)"
);
assert!(
Decimal::from_f64(max_plus_one).is_none(),
"from_f64(79_228_162_514_264_337_593_543_950_336_f64) -> none (too large)"
);
assert_eq!(
"79228162514264328797450928128",
Decimal::from_f64(under_max).unwrap().to_string(),
"from_f64(79_228_162_514_264_328_797_450_928_128_f64) -> some (inside limits)"
);
}

#[test]
fn it_converts_from_f64_retaining_bits() {
let tests = [
Expand Down

0 comments on commit ca982d6

Please sign in to comment.