Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix f64 dec limit edge case #678

Merged
merged 5 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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