Skip to content

Commit b0a85d6

Browse files
committed
Add shortcut for Grisu3 algorithm.
Check requested digit length and the fractional or integral parts of the number. Falls back earlier without trying the Grisu algorithm if the specific condition meets. Fix #110129
1 parent fd57c6b commit b0a85d6

File tree

2 files changed

+43
-0
lines changed
  • library/core

2 files changed

+43
-0
lines changed

library/core/benches/num/flt2dec/strategy/grisu.rs

+27
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,30 @@ fn bench_big_exact_inf(b: &mut Bencher) {
8181
format_exact(black_box(&decoded), &mut buf, i16::MIN);
8282
});
8383
}
84+
85+
#[bench]
86+
fn bench_one_exact_inf(b: &mut Bencher) {
87+
let decoded = decode_finite(1.0);
88+
let mut buf = [MaybeUninit::new(0); 1024];
89+
b.iter(|| {
90+
format_exact(black_box(&decoded), &mut buf, i16::MIN);
91+
});
92+
}
93+
94+
#[bench]
95+
fn bench_trailing_zero_exact_inf(b: &mut Bencher) {
96+
let decoded = decode_finite(250.000000000000000000000000);
97+
let mut buf = [MaybeUninit::new(0); 1024];
98+
b.iter(|| {
99+
format_exact(black_box(&decoded), &mut buf, i16::MIN);
100+
});
101+
}
102+
103+
#[bench]
104+
fn bench_halfway_point_exact_inf(b: &mut Bencher) {
105+
let decoded = decode_finite(1.00000000000000011102230246251565404236316680908203125);
106+
let mut buf = [MaybeUninit::new(0); 1024];
107+
b.iter(|| {
108+
format_exact(black_box(&decoded), &mut buf, i16::MIN);
109+
});
110+
}

library/core/src/num/flt2dec/strategy/grisu.rs

+16
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,22 @@ pub fn format_exact_opt<'a>(
487487
let vint = (v.f >> e) as u32;
488488
let vfrac = v.f & ((1 << e) - 1);
489489

490+
let requested_digits = buf.len();
491+
492+
const POW10_UP_TO_9: [u32; 10] =
493+
[1, 10, 100, 1000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000, 1_000_000_000];
494+
495+
// We deviate from the original algorithm here and do some early checks to determine if we can satisfy requested_digits.
496+
// If we determine that we can't, we exit early and avoid most of the heavy lifting that the algorithm otherwise does.
497+
//
498+
// When vfrac is zero, we can easily determine if vint can satisfy requested digits:
499+
// If requested_digits >= 11, vint is not able to exhaust the count by itself since 10^(11 -1) > u32 max value >= vint.
500+
// If vint < 10^(requested_digits - 1), vint cannot exhaust the count.
501+
// Otherwise, vint might be able to exhaust the count and we need to execute the rest of the code.
502+
if (vfrac == 0) && ((requested_digits >= 11) || (vint < POW10_UP_TO_9[requested_digits - 1])) {
503+
return None;
504+
}
505+
490506
// both old `v` and new `v` (scaled by `10^-k`) has an error of < 1 ulp (Theorem 5.1).
491507
// as we don't know the error is positive or negative, we use two approximations
492508
// spaced equally and have the maximal error of 2 ulps (same to the shortest case).

0 commit comments

Comments
 (0)