Skip to main content

core/num/imp/flt2dec/strategy/
grisu.rs

1//! Rust adaptation of the Grisu3 algorithm described in "Printing Floating-Point Numbers Quickly
2//! and Accurately with Integers"[^1]. It uses about 1KB of precomputed table, and in turn, it's
3//! very quick for most inputs.
4//!
5//! [^1]: Florian Loitsch. 2010. Printing floating-point numbers quickly and
6//!   accurately with integers. SIGPLAN Not. 45, 6 (June 2010), 233-243.
7
8use flt2dec::{Decoded, MAX_SIG_DIGITS, round_up};
9
10use crate::mem::MaybeUninit;
11use crate::num::imp::diy_float::Fp;
12use crate::num::imp::flt2dec;
13
14// see the comments in `format_shortest_opt` for the rationale.
15#[doc(hidden)]
16pub const ALPHA: i16 = -60;
17#[doc(hidden)]
18pub const GAMMA: i16 = -32;
19
20/*
21# the following Python code generates this table:
22for i in xrange(-308, 333, 8):
23    if i >= 0: f = 10**i; e = 0
24    else: f = 2**(80-4*i) // 10**-i; e = 4 * i - 80
25    l = f.bit_length()
26    f = ((f << 64 >> (l-1)) + 1) >> 1; e += l - 64
27    print '    (%#018x, %5d, %4d),' % (f, e, i)
28*/
29
30#[doc(hidden)]
31pub static CACHED_POW10: [(u64, i16, i16); 81] = [
32    // (f, e, k)
33    (0xe61acf033d1a45df, -1087, -308),
34    (0xab70fe17c79ac6ca, -1060, -300),
35    (0xff77b1fcbebcdc4f, -1034, -292),
36    (0xbe5691ef416bd60c, -1007, -284),
37    (0x8dd01fad907ffc3c, -980, -276),
38    (0xd3515c2831559a83, -954, -268),
39    (0x9d71ac8fada6c9b5, -927, -260),
40    (0xea9c227723ee8bcb, -901, -252),
41    (0xaecc49914078536d, -874, -244),
42    (0x823c12795db6ce57, -847, -236),
43    (0xc21094364dfb5637, -821, -228),
44    (0x9096ea6f3848984f, -794, -220),
45    (0xd77485cb25823ac7, -768, -212),
46    (0xa086cfcd97bf97f4, -741, -204),
47    (0xef340a98172aace5, -715, -196),
48    (0xb23867fb2a35b28e, -688, -188),
49    (0x84c8d4dfd2c63f3b, -661, -180),
50    (0xc5dd44271ad3cdba, -635, -172),
51    (0x936b9fcebb25c996, -608, -164),
52    (0xdbac6c247d62a584, -582, -156),
53    (0xa3ab66580d5fdaf6, -555, -148),
54    (0xf3e2f893dec3f126, -529, -140),
55    (0xb5b5ada8aaff80b8, -502, -132),
56    (0x87625f056c7c4a8b, -475, -124),
57    (0xc9bcff6034c13053, -449, -116),
58    (0x964e858c91ba2655, -422, -108),
59    (0xdff9772470297ebd, -396, -100),
60    (0xa6dfbd9fb8e5b88f, -369, -92),
61    (0xf8a95fcf88747d94, -343, -84),
62    (0xb94470938fa89bcf, -316, -76),
63    (0x8a08f0f8bf0f156b, -289, -68),
64    (0xcdb02555653131b6, -263, -60),
65    (0x993fe2c6d07b7fac, -236, -52),
66    (0xe45c10c42a2b3b06, -210, -44),
67    (0xaa242499697392d3, -183, -36),
68    (0xfd87b5f28300ca0e, -157, -28),
69    (0xbce5086492111aeb, -130, -20),
70    (0x8cbccc096f5088cc, -103, -12),
71    (0xd1b71758e219652c, -77, -4),
72    (0x9c40000000000000, -50, 4),
73    (0xe8d4a51000000000, -24, 12),
74    (0xad78ebc5ac620000, 3, 20),
75    (0x813f3978f8940984, 30, 28),
76    (0xc097ce7bc90715b3, 56, 36),
77    (0x8f7e32ce7bea5c70, 83, 44),
78    (0xd5d238a4abe98068, 109, 52),
79    (0x9f4f2726179a2245, 136, 60),
80    (0xed63a231d4c4fb27, 162, 68),
81    (0xb0de65388cc8ada8, 189, 76),
82    (0x83c7088e1aab65db, 216, 84),
83    (0xc45d1df942711d9a, 242, 92),
84    (0x924d692ca61be758, 269, 100),
85    (0xda01ee641a708dea, 295, 108),
86    (0xa26da3999aef774a, 322, 116),
87    (0xf209787bb47d6b85, 348, 124),
88    (0xb454e4a179dd1877, 375, 132),
89    (0x865b86925b9bc5c2, 402, 140),
90    (0xc83553c5c8965d3d, 428, 148),
91    (0x952ab45cfa97a0b3, 455, 156),
92    (0xde469fbd99a05fe3, 481, 164),
93    (0xa59bc234db398c25, 508, 172),
94    (0xf6c69a72a3989f5c, 534, 180),
95    (0xb7dcbf5354e9bece, 561, 188),
96    (0x88fcf317f22241e2, 588, 196),
97    (0xcc20ce9bd35c78a5, 614, 204),
98    (0x98165af37b2153df, 641, 212),
99    (0xe2a0b5dc971f303a, 667, 220),
100    (0xa8d9d1535ce3b396, 694, 228),
101    (0xfb9b7cd9a4a7443c, 720, 236),
102    (0xbb764c4ca7a44410, 747, 244),
103    (0x8bab8eefb6409c1a, 774, 252),
104    (0xd01fef10a657842c, 800, 260),
105    (0x9b10a4e5e9913129, 827, 268),
106    (0xe7109bfba19c0c9d, 853, 276),
107    (0xac2820d9623bf429, 880, 284),
108    (0x80444b5e7aa7cf85, 907, 292),
109    (0xbf21e44003acdd2d, 933, 300),
110    (0x8e679c2f5e44ff8f, 960, 308),
111    (0xd433179d9c8cb841, 986, 316),
112    (0x9e19db92b4e31ba9, 1013, 324),
113    (0xeb96bf6ebadf77d9, 1039, 332),
114];
115
116#[doc(hidden)]
117pub const CACHED_POW10_FIRST_E: i16 = -1087;
118#[doc(hidden)]
119pub const CACHED_POW10_LAST_E: i16 = 1039;
120
121#[doc(hidden)]
122#[ferrocene::prevalidated]
123pub fn cached_power(alpha: i16, gamma: i16) -> (i16, Fp) {
124    let offset = CACHED_POW10_FIRST_E as i32;
125    let range = (CACHED_POW10.len() as i32) - 1;
126    let domain = (CACHED_POW10_LAST_E - CACHED_POW10_FIRST_E) as i32;
127    let idx = ((gamma as i32) - offset) * range / domain;
128    let (f, e, k) = CACHED_POW10[idx as usize];
129    debug_assert!(alpha <= e && e <= gamma);
130    (k, Fp { f, e })
131}
132
133/// Given `x > 0`, returns `(k, 10^k)` such that `10^k <= x < 10^(k+1)`.
134#[doc(hidden)]
135#[ferrocene::prevalidated]
136pub fn max_pow10_no_more_than(x: u32) -> (u8, u32) {
137    debug_assert!(x > 0);
138
139    const X9: u32 = 10_0000_0000;
140    const X8: u32 = 1_0000_0000;
141    const X7: u32 = 1000_0000;
142    const X6: u32 = 100_0000;
143    const X5: u32 = 10_0000;
144    const X4: u32 = 1_0000;
145    const X3: u32 = 1000;
146    const X2: u32 = 100;
147    const X1: u32 = 10;
148
149    if x < X4 {
150        if x < X2 {
151            if x < X1 { (0, 1) } else { (1, X1) }
152        } else {
153            if x < X3 { (2, X2) } else { (3, X3) }
154        }
155    } else {
156        if x < X6 {
157            if x < X5 { (4, X4) } else { (5, X5) }
158        } else if x < X8 {
159            if x < X7 { (6, X6) } else { (7, X7) }
160        } else {
161            if x < X9 { (8, X8) } else { (9, X9) }
162        }
163    }
164}
165
166/// The shortest mode implementation for Grisu.
167///
168/// It returns `None` when it would return an inexact representation otherwise.
169#[ferrocene::prevalidated]
170pub fn format_shortest_opt<'a>(
171    d: &Decoded,
172    buf: &'a mut [MaybeUninit<u8>],
173) -> Option<(/*digits*/ &'a [u8], /*exp*/ i16)> {
174    assert!(d.mant > 0);
175    assert!(d.minus > 0);
176    assert!(d.plus > 0);
177    assert!(d.mant.checked_add(d.plus).is_some());
178    assert!(d.mant.checked_sub(d.minus).is_some());
179    assert!(buf.len() >= MAX_SIG_DIGITS);
180    assert!(d.mant + d.plus < (1 << 61)); // we need at least three bits of additional precision
181
182    // start with the normalized values with the shared exponent
183    let plus = Fp { f: d.mant + d.plus, e: d.exp }.normalize();
184    let minus = Fp { f: d.mant - d.minus, e: d.exp }.normalize_to(plus.e);
185    let v = Fp { f: d.mant, e: d.exp }.normalize_to(plus.e);
186
187    // find any `cached = 10^minusk` such that `ALPHA <= minusk + plus.e + 64 <= GAMMA`.
188    // since `plus` is normalized, this means `2^(62 + ALPHA) <= plus * cached < 2^(64 + GAMMA)`;
189    // given our choices of `ALPHA` and `GAMMA`, this puts `plus * cached` into `[4, 2^32)`.
190    //
191    // it is obviously desirable to maximize `GAMMA - ALPHA`,
192    // so that we don't need many cached powers of 10, but there are some considerations:
193    //
194    // 1. we want to keep `floor(plus * cached)` within `u32` since it needs a costly division.
195    //    (this is not really avoidable, remainder is required for accuracy estimation.)
196    // 2. the remainder of `floor(plus * cached)` repeatedly gets multiplied by 10,
197    //    and it should not overflow.
198    //
199    // the first gives `64 + GAMMA <= 32`, while the second gives `10 * 2^-ALPHA <= 2^64`;
200    // -60 and -32 is the maximal range with this constraint, and V8 also uses them.
201    let (minusk, cached) = cached_power(ALPHA - plus.e - 64, GAMMA - plus.e - 64);
202
203    // scale fps. this gives the maximal error of 1 ulp (proved from Theorem 5.1).
204    let plus = plus.mul(cached);
205    let minus = minus.mul(cached);
206    let v = v.mul(cached);
207    debug_assert_eq!(plus.e, minus.e);
208    debug_assert_eq!(plus.e, v.e);
209
210    //         +- actual range of minus
211    //   | <---|---------------------- unsafe region --------------------------> |
212    //   |     |                                                                 |
213    //   |  |<--->|  | <--------------- safe region ---------------> |           |
214    //   |  |     |  |                                               |           |
215    //   |1 ulp|1 ulp|                 |1 ulp|1 ulp|                 |1 ulp|1 ulp|
216    //   |<--->|<--->|                 |<--->|<--->|                 |<--->|<--->|
217    //   |-----|-----|-------...-------|-----|-----|-------...-------|-----|-----|
218    //   |   minus   |                 |     v     |                 |   plus    |
219    // minus1     minus0           v - 1 ulp   v + 1 ulp           plus0       plus1
220    //
221    // above `minus`, `v` and `plus` are *quantized* approximations (error < 1 ulp).
222    // as we don't know the error is positive or negative, we use two approximations spaced equally
223    // and have the maximal error of 2 ulps.
224    //
225    // the "unsafe region" is a liberal interval which we initially generate.
226    // the "safe region" is a conservative interval which we only accept.
227    // we start with the correct repr within the unsafe region, and try to find the closest repr
228    // to `v` which is also within the safe region. if we can't, we give up.
229    let plus1 = plus.f + 1;
230    //  let plus0 = plus.f - 1; // only for explanation
231    //  let minus0 = minus.f + 1; // only for explanation
232    let minus1 = minus.f - 1;
233    let e = -plus.e as usize; // shared exponent
234
235    // divide `plus1` into integral and fractional parts.
236    // integral parts are guaranteed to fit in u32, since cached power guarantees `plus < 2^32`
237    // and normalized `plus.f` is always less than `2^64 - 2^4` due to the precision requirement.
238    let plus1int = (plus1 >> e) as u32;
239    let plus1frac = plus1 & ((1 << e) - 1);
240
241    // calculate the largest `10^max_kappa` no more than `plus1` (thus `plus1 < 10^(max_kappa+1)`).
242    // this is an upper bound of `kappa` below.
243    let (max_kappa, max_ten_kappa) = max_pow10_no_more_than(plus1int);
244
245    let mut i = 0;
246    let exp = max_kappa as i16 - minusk + 1;
247
248    // Theorem 6.2: if `k` is the greatest integer s.t. `0 <= y mod 10^k <= y - x`,
249    //              then `V = floor(y / 10^k) * 10^k` is in `[x, y]` and one of the shortest
250    //              representations (with the minimal number of significant digits) in that range.
251    //
252    // find the digit length `kappa` between `(minus1, plus1)` as per Theorem 6.2.
253    // Theorem 6.2 can be adopted to exclude `x` by requiring `y mod 10^k < y - x` instead.
254    // (e.g., `x` = 32000, `y` = 32777; `kappa` = 2 since `y mod 10^3 = 777 < y - x = 777`.)
255    // the algorithm relies on the later verification phase to exclude `y`.
256    let delta1 = plus1 - minus1;
257    //  let delta1int = (delta1 >> e) as usize; // only for explanation
258    let delta1frac = delta1 & ((1 << e) - 1);
259
260    // render integral parts, while checking for the accuracy at each step.
261    let mut ten_kappa = max_ten_kappa; // 10^kappa
262    let mut remainder = plus1int; // digits yet to be rendered
263    loop {
264        // we always have at least one digit to render, as `plus1 >= 10^kappa`
265        // invariants:
266        // - `delta1int <= remainder < 10^(kappa+1)`
267        // - `plus1int = d[0..n-1] * 10^(kappa+1) + remainder`
268        //   (it follows that `remainder = plus1int % 10^(kappa+1)`)
269
270        // divide `remainder` by `10^kappa`. both are scaled by `2^-e`.
271        let q = remainder / ten_kappa;
272        let r = remainder % ten_kappa;
273        debug_assert!(q < 10);
274        buf[i] = MaybeUninit::new(b'0' + q as u8);
275        i += 1;
276
277        let plus1rem = ((r as u64) << e) + plus1frac; // == (plus1 % 10^kappa) * 2^e
278        if plus1rem < delta1 {
279            // `plus1 % 10^kappa < delta1 = plus1 - minus1`; we've found the correct `kappa`.
280            let ten_kappa = (ten_kappa as u64) << e; // scale 10^kappa back to the shared exponent
281            return round_and_weed(
282                // SAFETY: we initialized that memory above.
283                unsafe { buf[..i].assume_init_mut() },
284                exp,
285                plus1rem,
286                delta1,
287                plus1 - v.f,
288                ten_kappa,
289                1,
290            );
291        }
292
293        // break the loop when we have rendered all integral digits.
294        // the exact number of digits is `max_kappa + 1` as `plus1 < 10^(max_kappa+1)`.
295        if i > max_kappa as usize {
296            debug_assert_eq!(ten_kappa, 1);
297            break;
298        }
299
300        // restore invariants
301        ten_kappa /= 10;
302        remainder = r;
303    }
304
305    // render fractional parts, while checking for the accuracy at each step.
306    // this time we rely on repeated multiplications, as division will lose the precision.
307    let mut remainder = plus1frac;
308    let mut threshold = delta1frac;
309    let mut ulp = 1;
310    loop {
311        // the next digit should be significant as we've tested that before breaking out
312        // invariants, where `m = max_kappa + 1` (# of digits in the integral part):
313        // - `remainder < 2^e`
314        // - `plus1frac * 10^(n-m) = d[m..n-1] * 2^e + remainder`
315
316        remainder *= 10; // won't overflow, `2^e * 10 < 2^64`
317        threshold *= 10;
318        ulp *= 10;
319
320        // divide `remainder` by `10^kappa`.
321        // both are scaled by `2^e / 10^kappa`, so the latter is implicit here.
322        let q = remainder >> e;
323        let r = remainder & ((1 << e) - 1);
324        debug_assert!(q < 10);
325        buf[i] = MaybeUninit::new(b'0' + q as u8);
326        i += 1;
327
328        if r < threshold {
329            let ten_kappa = 1 << e; // implicit divisor
330            return round_and_weed(
331                // SAFETY: we initialized that memory above.
332                unsafe { buf[..i].assume_init_mut() },
333                exp,
334                r,
335                threshold,
336                (plus1 - v.f) * ulp,
337                ten_kappa,
338                ulp,
339            );
340        }
341
342        // restore invariants
343        remainder = r;
344    }
345
346    // we've generated all significant digits of `plus1`, but not sure if it's the optimal one.
347    // for example, if `minus1` is 3.14153... and `plus1` is 3.14158..., there are 5 different
348    // shortest representation from 3.14154 to 3.14158 but we only have the greatest one.
349    // we have to successively decrease the last digit and check if this is the optimal repr.
350    // there are at most 9 candidates (..1 to ..9), so this is fairly quick. ("rounding" phase)
351    //
352    // the function checks if this "optimal" repr is actually within the ulp ranges,
353    // and also, it is possible that the "second-to-optimal" repr can actually be optimal
354    // due to the rounding error. in either cases this returns `None`. ("weeding" phase)
355    //
356    // all arguments here are scaled by the common (but implicit) value `k`, so that:
357    // - `remainder = (plus1 % 10^kappa) * k`
358    // - `threshold = (plus1 - minus1) * k` (and also, `remainder < threshold`)
359    // - `plus1v = (plus1 - v) * k` (and also, `threshold > plus1v` from prior invariants)
360    // - `ten_kappa = 10^kappa * k`
361    // - `ulp = 2^-e * k`
362    #[ferrocene::prevalidated]
363    fn round_and_weed(
364        buf: &mut [u8],
365        exp: i16,
366        remainder: u64,
367        threshold: u64,
368        plus1v: u64,
369        ten_kappa: u64,
370        ulp: u64,
371    ) -> Option<(&[u8], i16)> {
372        assert!(!buf.is_empty());
373
374        // produce two approximations to `v` (actually `plus1 - v`) within 1.5 ulps.
375        // the resulting representation should be the closest representation to both.
376        //
377        // here `plus1 - v` is used since calculations are done with respect to `plus1`
378        // in order to avoid overflow/underflow (hence the seemingly swapped names).
379        let plus1v_down = plus1v + ulp; // plus1 - (v - 1 ulp)
380        let plus1v_up = plus1v - ulp; // plus1 - (v + 1 ulp)
381
382        // decrease the last digit and stop at the closest representation to `v + 1 ulp`.
383        let mut plus1w = remainder; // plus1w(n) = plus1 - w(n)
384        {
385            let last = buf.last_mut().unwrap();
386
387            // we work with the approximated digits `w(n)`, which is initially equal to `plus1 -
388            // plus1 % 10^kappa`. after running the loop body `n` times, `w(n) = plus1 -
389            // plus1 % 10^kappa - n * 10^kappa`. we set `plus1w(n) = plus1 - w(n) =
390            // plus1 % 10^kappa + n * 10^kappa` (thus `remainder = plus1w(0)`) to simplify checks.
391            // note that `plus1w(n)` is always increasing.
392            //
393            // we have three conditions to terminate. any of them will make the loop unable to
394            // proceed, but we then have at least one valid representation known to be closest to
395            // `v + 1 ulp` anyway. we will denote them as TC1 through TC3 for brevity.
396            //
397            // TC1: `w(n) <= v + 1 ulp`, i.e., this is the last repr that can be the closest one.
398            // this is equivalent to `plus1 - w(n) = plus1w(n) >= plus1 - (v + 1 ulp) = plus1v_up`.
399            // combined with TC2 (which checks if `w(n+1)` is valid), this prevents the possible
400            // overflow on the calculation of `plus1w(n)`.
401            //
402            // TC2: `w(n+1) < minus1`, i.e., the next repr definitely does not round to `v`.
403            // this is equivalent to `plus1 - w(n) + 10^kappa = plus1w(n) + 10^kappa >
404            // plus1 - minus1 = threshold`. the left hand side can overflow, but we know
405            // `threshold > plus1v`, so if TC1 is false, `threshold - plus1w(n) >
406            // threshold - (plus1v - 1 ulp) > 1 ulp` and we can safely test if
407            // `threshold - plus1w(n) < 10^kappa` instead.
408            //
409            // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e., the next repr is
410            // no closer to `v + 1 ulp` than the current repr. given `z(n) = plus1v_up - plus1w(n)`,
411            // this becomes `abs(z(n)) <= abs(z(n+1))`. again assuming that TC1 is false, we have
412            // `z(n) > 0`. we have two cases to consider:
413            //
414            // - when `z(n+1) >= 0`: TC3 becomes `z(n) <= z(n+1)`. as `plus1w(n)` is increasing,
415            //   `z(n)` should be decreasing and this is clearly false.
416            // - when `z(n+1) < 0`:
417            //   - TC3a: the precondition is `plus1v_up < plus1w(n) + 10^kappa`. assuming TC2 is
418            //     false, `threshold >= plus1w(n) + 10^kappa` so it cannot overflow.
419            //   - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e., `plus1v_up - plus1w(n) >=
420            //     plus1w(n+1) - plus1v_up = plus1w(n) + 10^kappa - plus1v_up`. the negated TC1
421            //     gives `plus1v_up > plus1w(n)`, so it cannot overflow or underflow when
422            //     combined with TC3a.
423            //
424            // consequently, we should stop when `TC1 || TC2 || (TC3a && TC3b)`. the following is
425            // equal to its inverse, `!TC1 && !TC2 && (!TC3a || !TC3b)`.
426            while plus1w < plus1v_up
427                && threshold - plus1w >= ten_kappa
428                && (plus1w + ten_kappa < plus1v_up
429                    || plus1v_up - plus1w >= plus1w + ten_kappa - plus1v_up)
430            {
431                *last -= 1;
432                debug_assert!(*last > b'0'); // the shortest repr cannot end with `0`
433                plus1w += ten_kappa;
434            }
435        }
436
437        // check if this representation is also the closest representation to `v - 1 ulp`.
438        //
439        // this is simply same to the terminating conditions for `v + 1 ulp`, with all `plus1v_up`
440        // replaced by `plus1v_down` instead. overflow analysis equally holds.
441        if plus1w < plus1v_down
442            && threshold - plus1w >= ten_kappa
443            && (plus1w + ten_kappa < plus1v_down
444                || plus1v_down - plus1w >= plus1w + ten_kappa - plus1v_down)
445        {
446            return None;
447        }
448
449        // now we have the closest representation to `v` between `plus1` and `minus1`.
450        // this is too liberal, though, so we reject any `w(n)` not between `plus0` and `minus0`,
451        // i.e., `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts
452        // that `threshold = plus1 - minus1` and `plus1 - plus0 = minus0 - minus1 = 2 ulp`.
453        if 2 * ulp <= plus1w && plus1w <= threshold - 4 * ulp { Some((buf, exp)) } else { None }
454    }
455}
456
457/// The shortest mode implementation for Grisu with Dragon fallback.
458///
459/// This should be used for most cases.
460#[ferrocene::prevalidated]
461pub fn format_shortest<'a>(
462    d: &Decoded,
463    buf: &'a mut [MaybeUninit<u8>],
464) -> (/*digits*/ &'a [u8], /*exp*/ i16) {
465    use flt2dec::strategy::dragon::format_shortest as fallback;
466    // SAFETY: The borrow checker is not smart enough to let us use `buf`
467    // in the second branch, so we launder the lifetime here. But we only re-use
468    // `buf` if `format_shortest_opt` returned `None` so this is okay.
469    match format_shortest_opt(d, unsafe { &mut *(buf as *mut _) }) {
470        Some(ret) => ret,
471        None => fallback(d, buf),
472    }
473}
474
475/// The exact and fixed mode implementation for Grisu.
476///
477/// It returns `None` when it would return an inexact representation otherwise.
478#[ferrocene::prevalidated]
479pub fn format_exact_opt<'a>(
480    d: &Decoded,
481    buf: &'a mut [MaybeUninit<u8>],
482    limit: i16,
483) -> Option<(/*digits*/ &'a [u8], /*exp*/ i16)> {
484    assert!(d.mant > 0);
485    assert!(d.mant < (1 << 61)); // we need at least three bits of additional precision
486    assert!(!buf.is_empty());
487
488    // normalize and scale `v`.
489    let v = Fp { f: d.mant, e: d.exp }.normalize();
490    let (minusk, cached) = cached_power(ALPHA - v.e - 64, GAMMA - v.e - 64);
491    let v = v.mul(cached);
492
493    // divide `v` into integral and fractional parts.
494    let e = -v.e as usize;
495    let vint = (v.f >> e) as u32;
496    let vfrac = v.f & ((1 << e) - 1);
497
498    let requested_digits = buf.len();
499
500    const POW10_UP_TO_9: [u32; 10] =
501        [1, 10, 100, 1000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000, 1_000_000_000];
502
503    // We deviate from the original algorithm here and do some early checks to determine if we can satisfy requested_digits.
504    // If we determine that we can't, we exit early and avoid most of the heavy lifting that the algorithm otherwise does.
505    //
506    // When vfrac is zero, we can easily determine if vint can satisfy requested digits:
507    //      If requested_digits >= 11, vint is not able to exhaust the count by itself since 10^(11 -1) > u32 max value >= vint.
508    //      If vint < 10^(requested_digits - 1), vint cannot exhaust the count.
509    //      Otherwise, vint might be able to exhaust the count and we need to execute the rest of the code.
510    if (vfrac == 0) && ((requested_digits >= 11) || (vint < POW10_UP_TO_9[requested_digits - 1])) {
511        return None;
512    }
513
514    // both old `v` and new `v` (scaled by `10^-k`) has an error of < 1 ulp (Theorem 5.1).
515    // as we don't know the error is positive or negative, we use two approximations
516    // spaced equally and have the maximal error of 2 ulps (same to the shortest case).
517    //
518    // the goal is to find the exactly rounded series of digits that are common to
519    // both `v - 1 ulp` and `v + 1 ulp`, so that we are maximally confident.
520    // if this is not possible, we don't know which one is the correct output for `v`,
521    // so we give up and fall back.
522    //
523    // `err` is defined as `1 ulp * 2^e` here (same to the ulp in `vfrac`),
524    // and we will scale it whenever `v` gets scaled.
525    let mut err = 1;
526
527    // calculate the largest `10^max_kappa` no more than `v` (thus `v < 10^(max_kappa+1)`).
528    // this is an upper bound of `kappa` below.
529    let (max_kappa, max_ten_kappa) = max_pow10_no_more_than(vint);
530
531    let mut i = 0;
532    let exp = max_kappa as i16 - minusk + 1;
533
534    // if we are working with the last-digit limitation, we need to shorten the buffer
535    // before the actual rendering in order to avoid double rounding.
536    // note that we have to enlarge the buffer again when rounding up happens!
537    let len = if exp <= limit {
538        // oops, we cannot even produce *one* digit.
539        // this is possible when, say, we've got something like 9.5 and it's being rounded to 10.
540        //
541        // in principle we can immediately call `possibly_round` with an empty buffer,
542        // but scaling `max_ten_kappa << e` by 10 can result in overflow.
543        // thus we are being sloppy here and widen the error range by a factor of 10.
544        // this will increase the false negative rate, but only very, *very* slightly;
545        // it can only matter noticeably when the mantissa is bigger than 60 bits.
546        //
547        // SAFETY: `len=0`, so the obligation of having initialized this memory is trivial.
548        return unsafe {
549            possibly_round(buf, 0, exp, limit, v.f / 10, (max_ten_kappa as u64) << e, err << e)
550        };
551    } else if ((exp as i32 - limit as i32) as usize) < buf.len() {
552        (exp - limit) as usize
553    } else {
554        buf.len()
555    };
556    debug_assert!(len > 0);
557
558    // render integral parts.
559    // the error is entirely fractional, so we don't need to check it in this part.
560    let mut kappa = max_kappa as i16;
561    let mut ten_kappa = max_ten_kappa; // 10^kappa
562    let mut remainder = vint; // digits yet to be rendered
563    loop {
564        // we always have at least one digit to render
565        // invariants:
566        // - `remainder < 10^(kappa+1)`
567        // - `vint = d[0..n-1] * 10^(kappa+1) + remainder`
568        //   (it follows that `remainder = vint % 10^(kappa+1)`)
569
570        // divide `remainder` by `10^kappa`. both are scaled by `2^-e`.
571        let q = remainder / ten_kappa;
572        let r = remainder % ten_kappa;
573        debug_assert!(q < 10);
574        buf[i] = MaybeUninit::new(b'0' + q as u8);
575        i += 1;
576
577        // is the buffer full? run the rounding pass with the remainder.
578        if i == len {
579            let vrem = ((r as u64) << e) + vfrac; // == (v % 10^kappa) * 2^e
580            // SAFETY: we have initialized `len` many bytes.
581            return unsafe {
582                possibly_round(buf, len, exp, limit, vrem, (ten_kappa as u64) << e, err << e)
583            };
584        }
585
586        // break the loop when we have rendered all integral digits.
587        // the exact number of digits is `max_kappa + 1` as `plus1 < 10^(max_kappa+1)`.
588        if i > max_kappa as usize {
589            debug_assert_eq!(ten_kappa, 1);
590            debug_assert_eq!(kappa, 0);
591            break;
592        }
593
594        // restore invariants
595        kappa -= 1;
596        ten_kappa /= 10;
597        remainder = r;
598    }
599
600    // render fractional parts.
601    //
602    // in principle we can continue to the last available digit and check for the accuracy.
603    // unfortunately we are working with the finite-sized integers, so we need some criterion
604    // to detect the overflow. V8 uses `remainder > err`, which becomes false when
605    // the first `i` significant digits of `v - 1 ulp` and `v` differ. however this rejects
606    // too many otherwise valid input.
607    //
608    // since the later phase has a correct overflow detection, we instead use tighter criterion:
609    // we continue til `err` exceeds `10^kappa / 2`, so that the range between `v - 1 ulp` and
610    // `v + 1 ulp` definitely contains two or more rounded representations. this is same to
611    // the first two comparisons from `possibly_round`, for the reference.
612    let mut remainder = vfrac;
613    let maxerr = 1 << (e - 1);
614    while err < maxerr {
615        // invariants, where `m = max_kappa + 1` (# of digits in the integral part):
616        // - `remainder < 2^e`
617        // - `vfrac * 10^(n-m) = d[m..n-1] * 2^e + remainder`
618        // - `err = 10^(n-m)`
619
620        remainder *= 10; // won't overflow, `2^e * 10 < 2^64`
621        err *= 10; // won't overflow, `err * 10 < 2^e * 5 < 2^64`
622
623        // divide `remainder` by `10^kappa`.
624        // both are scaled by `2^e / 10^kappa`, so the latter is implicit here.
625        let q = remainder >> e;
626        let r = remainder & ((1 << e) - 1);
627        debug_assert!(q < 10);
628        buf[i] = MaybeUninit::new(b'0' + q as u8);
629        i += 1;
630
631        // is the buffer full? run the rounding pass with the remainder.
632        if i == len {
633            // SAFETY: we have initialized `len` many bytes.
634            return unsafe { possibly_round(buf, len, exp, limit, r, 1 << e, err) };
635        }
636
637        // restore invariants
638        remainder = r;
639    }
640
641    // further calculation is useless (`possibly_round` definitely fails), so we give up.
642    return None;
643
644    // we've generated all requested digits of `v`, which should be also same to corresponding
645    // digits of `v - 1 ulp`. now we check if there is a unique representation shared by
646    // both `v - 1 ulp` and `v + 1 ulp`; this can be either same to generated digits, or
647    // to the rounded-up version of those digits. if the range contains multiple representations
648    // of the same length, we cannot be sure and should return `None` instead.
649    //
650    // all arguments here are scaled by the common (but implicit) value `k`, so that:
651    // - `remainder = (v % 10^kappa) * k`
652    // - `ten_kappa = 10^kappa * k`
653    // - `ulp = 2^-e * k`
654    //
655    // SAFETY: the first `len` bytes of `buf` must be initialized.
656    #[ferrocene::prevalidated]
657    unsafe fn possibly_round(
658        buf: &mut [MaybeUninit<u8>],
659        mut len: usize,
660        mut exp: i16,
661        limit: i16,
662        remainder: u64,
663        ten_kappa: u64,
664        ulp: u64,
665    ) -> Option<(&[u8], i16)> {
666        debug_assert!(remainder < ten_kappa);
667
668        //           10^kappa
669        //    :   :   :<->:   :
670        //    :   :   :   :   :
671        //    :|1 ulp|1 ulp|  :
672        //    :|<--->|<--->|  :
673        // ----|-----|-----|----
674        //     |     v     |
675        // v - 1 ulp   v + 1 ulp
676        //
677        // (for the reference, the dotted line indicates the exact value for
678        // possible representations in given number of digits.)
679        //
680        // error is too large that there are at least three possible representations
681        // between `v - 1 ulp` and `v + 1 ulp`. we cannot determine which one is correct.
682        if ulp >= ten_kappa {
683            return None;
684        }
685
686        //    10^kappa
687        //   :<------->:
688        //   :         :
689        //   : |1 ulp|1 ulp|
690        //   : |<--->|<--->|
691        // ----|-----|-----|----
692        //     |     v     |
693        // v - 1 ulp   v + 1 ulp
694        //
695        // in fact, 1/2 ulp is enough to introduce two possible representations.
696        // (remember that we need a unique representation for both `v - 1 ulp` and `v + 1 ulp`.)
697        // this won't overflow, as `ulp < ten_kappa` from the first check.
698        if ten_kappa - ulp <= ulp {
699            return None;
700        }
701
702        //     remainder
703        //       :<->|                           :
704        //       :   |                           :
705        //       :<--------- 10^kappa ---------->:
706        //     | :   |                           :
707        //     |1 ulp|1 ulp|                     :
708        //     |<--->|<--->|                     :
709        // ----|-----|-----|------------------------
710        //     |     v     |
711        // v - 1 ulp   v + 1 ulp
712        //
713        // if `v + 1 ulp` is closer to the rounded-down representation (which is already in `buf`),
714        // then we can safely return. note that `v - 1 ulp` *can* be less than the current
715        // representation, but as `1 ulp < 10^kappa / 2`, this condition is enough:
716        // the distance between `v - 1 ulp` and the current representation
717        // cannot exceed `10^kappa / 2`.
718        //
719        // the condition equals to `remainder + ulp < 10^kappa / 2`.
720        // since this can easily overflow, first check if `remainder < 10^kappa / 2`.
721        // we've already verified that `ulp < 10^kappa / 2`, so as long as
722        // `10^kappa` did not overflow after all, the second check is fine.
723        if ten_kappa - remainder > remainder && ten_kappa - 2 * remainder >= 2 * ulp {
724            // SAFETY: our caller initialized that memory.
725            return Some((unsafe { buf[..len].assume_init_ref() }, exp));
726        }
727
728        //   :<------- remainder ------>|   :
729        //   :                          |   :
730        //   :<--------- 10^kappa --------->:
731        //   :                    |     |   : |
732        //   :                    |1 ulp|1 ulp|
733        //   :                    |<--->|<--->|
734        // -----------------------|-----|-----|-----
735        //                        |     v     |
736        //                    v - 1 ulp   v + 1 ulp
737        //
738        // on the other hands, if `v - 1 ulp` is closer to the rounded-up representation,
739        // we should round up and return. for the same reason we don't need to check `v + 1 ulp`.
740        //
741        // the condition equals to `remainder - ulp >= 10^kappa / 2`.
742        // again we first check if `remainder > ulp` (note that this is not `remainder >= ulp`,
743        // as `10^kappa` is never zero). also note that `remainder - ulp <= 10^kappa`,
744        // so the second check does not overflow.
745        if remainder > ulp && ten_kappa - (remainder - ulp) <= remainder - ulp {
746            if let Some(c) =
747                // SAFETY: our caller must have initialized that memory.
748                round_up(unsafe { buf[..len].assume_init_mut() })
749            {
750                // only add an additional digit when we've been requested the fixed precision.
751                // we also need to check that, if the original buffer was empty,
752                // the additional digit can only be added when `exp == limit` (edge case).
753                exp += 1;
754                if exp > limit && len < buf.len() {
755                    buf[len] = MaybeUninit::new(c);
756                    len += 1;
757                }
758            }
759            // SAFETY: we and our caller initialized that memory.
760            return Some((unsafe { buf[..len].assume_init_ref() }, exp));
761        }
762
763        // otherwise we are doomed (i.e., some values between `v - 1 ulp` and `v + 1 ulp` are
764        // rounding down and others are rounding up) and give up.
765        None
766    }
767}
768
769/// The exact and fixed mode implementation for Grisu with Dragon fallback.
770///
771/// This should be used for most cases.
772#[ferrocene::prevalidated]
773pub fn format_exact<'a>(
774    d: &Decoded,
775    buf: &'a mut [MaybeUninit<u8>],
776    limit: i16,
777) -> (/*digits*/ &'a [u8], /*exp*/ i16) {
778    use flt2dec::strategy::dragon::format_exact as fallback;
779    // SAFETY: The borrow checker is not smart enough to let us use `buf`
780    // in the second branch, so we launder the lifetime here. But we only re-use
781    // `buf` if `format_exact_opt` returned `None` so this is okay.
782    match format_exact_opt(d, unsafe { &mut *(buf as *mut _) }, limit) {
783        Some(ret) => ret,
784        None => fallback(d, buf, limit),
785    }
786}