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