1 // © 2018 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 //
4 // From the double-conversion library. Original license:
5 //
6 // Copyright 2012 the V8 project authors. All rights reserved.
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions are
9 // met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 //       notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 //       copyright notice, this list of conditions and the following
15 //       disclaimer in the documentation and/or other materials provided
16 //       with the distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 //       contributors may be used to endorse or promote products derived
19 //       from this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 
33 // ICU PATCH: ifdef around UCONFIG_NO_FORMATTING
34 #include "unicode/utypes.h"
35 #if !UCONFIG_NO_FORMATTING
36 
37 // ICU PATCH: Customize header file paths for ICU.
38 
39 #include "double-conversion-fast-dtoa.h"
40 
41 #include "double-conversion-cached-powers.h"
42 #include "double-conversion-diy-fp.h"
43 #include "double-conversion-ieee.h"
44 
45 // ICU PATCH: Wrap in ICU namespace
46 U_NAMESPACE_BEGIN
47 
48 namespace double_conversion {
49 
50 // The minimal and maximal target exponent define the range of w's binary
51 // exponent, where 'w' is the result of multiplying the input by a cached power
52 // of ten.
53 //
54 // A different range might be chosen on a different platform, to optimize digit
55 // generation, but a smaller range requires more powers of ten to be cached.
56 static const int kMinimalTargetExponent = -60;
57 static const int kMaximalTargetExponent = -32;
58 
59 
60 // Adjusts the last digit of the generated number, and screens out generated
61 // solutions that may be inaccurate. A solution may be inaccurate if it is
62 // outside the safe interval, or if we cannot prove that it is closer to the
63 // input than a neighboring representation of the same length.
64 //
65 // Input: * buffer containing the digits of too_high / 10^kappa
66 //        * the buffer's length
67 //        * distance_too_high_w == (too_high - w).f() * unit
68 //        * unsafe_interval == (too_high - too_low).f() * unit
69 //        * rest = (too_high - buffer * 10^kappa).f() * unit
70 //        * ten_kappa = 10^kappa * unit
71 //        * unit = the common multiplier
72 // Output: returns true if the buffer is guaranteed to contain the closest
73 //    representable number to the input.
74 //  Modifies the generated digits in the buffer to approach (round towards) w.
RoundWeed(Vector<char> buffer,int length,uint64_t distance_too_high_w,uint64_t unsafe_interval,uint64_t rest,uint64_t ten_kappa,uint64_t unit)75 static bool RoundWeed(Vector<char> buffer,
76                       int length,
77                       uint64_t distance_too_high_w,
78                       uint64_t unsafe_interval,
79                       uint64_t rest,
80                       uint64_t ten_kappa,
81                       uint64_t unit) {
82   uint64_t small_distance = distance_too_high_w - unit;
83   uint64_t big_distance = distance_too_high_w + unit;
84   // Let w_low  = too_high - big_distance, and
85   //     w_high = too_high - small_distance.
86   // Note: w_low < w < w_high
87   //
88   // The real w (* unit) must lie somewhere inside the interval
89   // ]w_low; w_high[ (often written as "(w_low; w_high)")
90 
91   // Basically the buffer currently contains a number in the unsafe interval
92   // ]too_low; too_high[ with too_low < w < too_high
93   //
94   //  too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
95   //                     ^v 1 unit            ^      ^                 ^      ^
96   //  boundary_high ---------------------     .      .                 .      .
97   //                     ^v 1 unit            .      .                 .      .
98   //   - - - - - - - - - - - - - - - - - - -  +  - - + - - - - - -     .      .
99   //                                          .      .         ^       .      .
100   //                                          .  big_distance  .       .      .
101   //                                          .      .         .       .    rest
102   //                              small_distance     .         .       .      .
103   //                                          v      .         .       .      .
104   //  w_high - - - - - - - - - - - - - - - - - -     .         .       .      .
105   //                     ^v 1 unit                   .         .       .      .
106   //  w ----------------------------------------     .         .       .      .
107   //                     ^v 1 unit                   v         .       .      .
108   //  w_low  - - - - - - - - - - - - - - - - - - - - -         .       .      .
109   //                                                           .       .      v
110   //  buffer --------------------------------------------------+-------+--------
111   //                                                           .       .
112   //                                                  safe_interval    .
113   //                                                           v       .
114   //   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -     .
115   //                     ^v 1 unit                                     .
116   //  boundary_low -------------------------                     unsafe_interval
117   //                     ^v 1 unit                                     v
118   //  too_low  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
119   //
120   //
121   // Note that the value of buffer could lie anywhere inside the range too_low
122   // to too_high.
123   //
124   // boundary_low, boundary_high and w are approximations of the real boundaries
125   // and v (the input number). They are guaranteed to be precise up to one unit.
126   // In fact the error is guaranteed to be strictly less than one unit.
127   //
128   // Anything that lies outside the unsafe interval is guaranteed not to round
129   // to v when read again.
130   // Anything that lies inside the safe interval is guaranteed to round to v
131   // when read again.
132   // If the number inside the buffer lies inside the unsafe interval but not
133   // inside the safe interval then we simply do not know and bail out (returning
134   // false).
135   //
136   // Similarly we have to take into account the imprecision of 'w' when finding
137   // the closest representation of 'w'. If we have two potential
138   // representations, and one is closer to both w_low and w_high, then we know
139   // it is closer to the actual value v.
140   //
141   // By generating the digits of too_high we got the largest (closest to
142   // too_high) buffer that is still in the unsafe interval. In the case where
143   // w_high < buffer < too_high we try to decrement the buffer.
144   // This way the buffer approaches (rounds towards) w.
145   // There are 3 conditions that stop the decrementation process:
146   //   1) the buffer is already below w_high
147   //   2) decrementing the buffer would make it leave the unsafe interval
148   //   3) decrementing the buffer would yield a number below w_high and farther
149   //      away than the current number. In other words:
150   //              (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
151   // Instead of using the buffer directly we use its distance to too_high.
152   // Conceptually rest ~= too_high - buffer
153   // We need to do the following tests in this order to avoid over- and
154   // underflows.
155   DOUBLE_CONVERSION_ASSERT(rest <= unsafe_interval);
156   while (rest < small_distance &&  // Negated condition 1
157          unsafe_interval - rest >= ten_kappa &&  // Negated condition 2
158          (rest + ten_kappa < small_distance ||  // buffer{-1} > w_high
159           small_distance - rest >= rest + ten_kappa - small_distance)) {
160     buffer[length - 1]--;
161     rest += ten_kappa;
162   }
163 
164   // We have approached w+ as much as possible. We now test if approaching w-
165   // would require changing the buffer. If yes, then we have two possible
166   // representations close to w, but we cannot decide which one is closer.
167   if (rest < big_distance &&
168       unsafe_interval - rest >= ten_kappa &&
169       (rest + ten_kappa < big_distance ||
170        big_distance - rest > rest + ten_kappa - big_distance)) {
171     return false;
172   }
173 
174   // Weeding test.
175   //   The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
176   //   Since too_low = too_high - unsafe_interval this is equivalent to
177   //      [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
178   //   Conceptually we have: rest ~= too_high - buffer
179   return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
180 }
181 
182 
183 // Rounds the buffer upwards if the result is closer to v by possibly adding
184 // 1 to the buffer. If the precision of the calculation is not sufficient to
185 // round correctly, return false.
186 // The rounding might shift the whole buffer in which case the kappa is
187 // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
188 //
189 // If 2*rest > ten_kappa then the buffer needs to be round up.
190 // rest can have an error of +/- 1 unit. This function accounts for the
191 // imprecision and returns false, if the rounding direction cannot be
192 // unambiguously determined.
193 //
194 // Precondition: rest < ten_kappa.
RoundWeedCounted(Vector<char> buffer,int length,uint64_t rest,uint64_t ten_kappa,uint64_t unit,int * kappa)195 static bool RoundWeedCounted(Vector<char> buffer,
196                              int length,
197                              uint64_t rest,
198                              uint64_t ten_kappa,
199                              uint64_t unit,
200                              int* kappa) {
201   DOUBLE_CONVERSION_ASSERT(rest < ten_kappa);
202   // The following tests are done in a specific order to avoid overflows. They
203   // will work correctly with any uint64 values of rest < ten_kappa and unit.
204   //
205   // If the unit is too big, then we don't know which way to round. For example
206   // a unit of 50 means that the real number lies within rest +/- 50. If
207   // 10^kappa == 40 then there is no way to tell which way to round.
208   if (unit >= ten_kappa) return false;
209   // Even if unit is just half the size of 10^kappa we are already completely
210   // lost. (And after the previous test we know that the expression will not
211   // over/underflow.)
212   if (ten_kappa - unit <= unit) return false;
213   // If 2 * (rest + unit) <= 10^kappa we can safely round down.
214   if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
215     return true;
216   }
217   // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
218   if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
219     // Increment the last digit recursively until we find a non '9' digit.
220     buffer[length - 1]++;
221     for (int i = length - 1; i > 0; --i) {
222       if (buffer[i] != '0' + 10) break;
223       buffer[i] = '0';
224       buffer[i - 1]++;
225     }
226     // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
227     // exception of the first digit all digits are now '0'. Simply switch the
228     // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
229     // the power (the kappa) is increased.
230     if (buffer[0] == '0' + 10) {
231       buffer[0] = '1';
232       (*kappa) += 1;
233     }
234     return true;
235   }
236   return false;
237 }
238 
239 // Returns the biggest power of ten that is less than or equal to the given
240 // number. We furthermore receive the maximum number of bits 'number' has.
241 //
242 // Returns power == 10^(exponent_plus_one-1) such that
243 //    power <= number < power * 10.
244 // If number_bits == 0 then 0^(0-1) is returned.
245 // The number of bits must be <= 32.
246 // Precondition: number < (1 << (number_bits + 1)).
247 
248 // Inspired by the method for finding an integer log base 10 from here:
249 // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
250 static unsigned int const kSmallPowersOfTen[] =
251     {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
252      1000000000};
253 
BiggestPowerTen(uint32_t number,int number_bits,uint32_t * power,int * exponent_plus_one)254 static void BiggestPowerTen(uint32_t number,
255                             int number_bits,
256                             uint32_t* power,
257                             int* exponent_plus_one) {
258   DOUBLE_CONVERSION_ASSERT(number < (1u << (number_bits + 1)));
259   // 1233/4096 is approximately 1/lg(10).
260   int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
261   // We increment to skip over the first entry in the kPowersOf10 table.
262   // Note: kPowersOf10[i] == 10^(i-1).
263   exponent_plus_one_guess++;
264   // We don't have any guarantees that 2^number_bits <= number.
265   if (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
266     exponent_plus_one_guess--;
267   }
268   *power = kSmallPowersOfTen[exponent_plus_one_guess];
269   *exponent_plus_one = exponent_plus_one_guess;
270 }
271 
272 // Generates the digits of input number w.
273 // w is a floating-point number (DiyFp), consisting of a significand and an
274 // exponent. Its exponent is bounded by kMinimalTargetExponent and
275 // kMaximalTargetExponent.
276 //       Hence -60 <= w.e() <= -32.
277 //
278 // Returns false if it fails, in which case the generated digits in the buffer
279 // should not be used.
280 // Preconditions:
281 //  * low, w and high are correct up to 1 ulp (unit in the last place). That
282 //    is, their error must be less than a unit of their last digits.
283 //  * low.e() == w.e() == high.e()
284 //  * low < w < high, and taking into account their error: low~ <= high~
285 //  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
286 // Postconditions: returns false if procedure fails.
287 //   otherwise:
288 //     * buffer is not null-terminated, but len contains the number of digits.
289 //     * buffer contains the shortest possible decimal digit-sequence
290 //       such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
291 //       correct values of low and high (without their error).
292 //     * if more than one decimal representation gives the minimal number of
293 //       decimal digits then the one closest to W (where W is the correct value
294 //       of w) is chosen.
295 // Remark: this procedure takes into account the imprecision of its input
296 //   numbers. If the precision is not enough to guarantee all the postconditions
297 //   then false is returned. This usually happens rarely (~0.5%).
298 //
299 // Say, for the sake of example, that
300 //   w.e() == -48, and w.f() == 0x1234567890abcdef
301 // w's value can be computed by w.f() * 2^w.e()
302 // We can obtain w's integral digits by simply shifting w.f() by -w.e().
303 //  -> w's integral part is 0x1234
304 //  w's fractional part is therefore 0x567890abcdef.
305 // Printing w's integral part is easy (simply print 0x1234 in decimal).
306 // In order to print its fraction we repeatedly multiply the fraction by 10 and
307 // get each digit. Example the first digit after the point would be computed by
308 //   (0x567890abcdef * 10) >> 48. -> 3
309 // The whole thing becomes slightly more complicated because we want to stop
310 // once we have enough digits. That is, once the digits inside the buffer
311 // represent 'w' we can stop. Everything inside the interval low - high
312 // represents w. However we have to pay attention to low, high and w's
313 // imprecision.
DigitGen(DiyFp low,DiyFp w,DiyFp high,Vector<char> buffer,int * length,int * kappa)314 static bool DigitGen(DiyFp low,
315                      DiyFp w,
316                      DiyFp high,
317                      Vector<char> buffer,
318                      int* length,
319                      int* kappa) {
320   DOUBLE_CONVERSION_ASSERT(low.e() == w.e() && w.e() == high.e());
321   DOUBLE_CONVERSION_ASSERT(low.f() + 1 <= high.f() - 1);
322   DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
323   // low, w and high are imprecise, but by less than one ulp (unit in the last
324   // place).
325   // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
326   // the new numbers are outside of the interval we want the final
327   // representation to lie in.
328   // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
329   // numbers that are certain to lie in the interval. We will use this fact
330   // later on.
331   // We will now start by generating the digits within the uncertain
332   // interval. Later we will weed out representations that lie outside the safe
333   // interval and thus _might_ lie outside the correct interval.
334   uint64_t unit = 1;
335   DiyFp too_low = DiyFp(low.f() - unit, low.e());
336   DiyFp too_high = DiyFp(high.f() + unit, high.e());
337   // too_low and too_high are guaranteed to lie outside the interval we want the
338   // generated number in.
339   DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
340   // We now cut the input number into two parts: the integral digits and the
341   // fractionals. We will not write any decimal separator though, but adapt
342   // kappa instead.
343   // Reminder: we are currently computing the digits (stored inside the buffer)
344   // such that:   too_low < buffer * 10^kappa < too_high
345   // We use too_high for the digit_generation and stop as soon as possible.
346   // If we stop early we effectively round down.
347   DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
348   // Division by one is a shift.
349   uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
350   // Modulo by one is an and.
351   uint64_t fractionals = too_high.f() & (one.f() - 1);
352   uint32_t divisor;
353   int divisor_exponent_plus_one;
354   BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
355                   &divisor, &divisor_exponent_plus_one);
356   *kappa = divisor_exponent_plus_one;
357   *length = 0;
358   // Loop invariant: buffer = too_high / 10^kappa  (integer division)
359   // The invariant holds for the first iteration: kappa has been initialized
360   // with the divisor exponent + 1. And the divisor is the biggest power of ten
361   // that is smaller than integrals.
362   while (*kappa > 0) {
363     int digit = integrals / divisor;
364     DOUBLE_CONVERSION_ASSERT(digit <= 9);
365     buffer[*length] = static_cast<char>('0' + digit);
366     (*length)++;
367     integrals %= divisor;
368     (*kappa)--;
369     // Note that kappa now equals the exponent of the divisor and that the
370     // invariant thus holds again.
371     uint64_t rest =
372         (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
373     // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
374     // Reminder: unsafe_interval.e() == one.e()
375     if (rest < unsafe_interval.f()) {
376       // Rounding down (by not emitting the remaining digits) yields a number
377       // that lies within the unsafe interval.
378       return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
379                        unsafe_interval.f(), rest,
380                        static_cast<uint64_t>(divisor) << -one.e(), unit);
381     }
382     divisor /= 10;
383   }
384 
385   // The integrals have been generated. We are at the point of the decimal
386   // separator. In the following loop we simply multiply the remaining digits by
387   // 10 and divide by one. We just need to pay attention to multiply associated
388   // data (like the interval or 'unit'), too.
389   // Note that the multiplication by 10 does not overflow, because w.e >= -60
390   // and thus one.e >= -60.
391   DOUBLE_CONVERSION_ASSERT(one.e() >= -60);
392   DOUBLE_CONVERSION_ASSERT(fractionals < one.f());
393   DOUBLE_CONVERSION_ASSERT(DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
394   for (;;) {
395     fractionals *= 10;
396     unit *= 10;
397     unsafe_interval.set_f(unsafe_interval.f() * 10);
398     // Integer division by one.
399     int digit = static_cast<int>(fractionals >> -one.e());
400     DOUBLE_CONVERSION_ASSERT(digit <= 9);
401     buffer[*length] = static_cast<char>('0' + digit);
402     (*length)++;
403     fractionals &= one.f() - 1;  // Modulo by one.
404     (*kappa)--;
405     if (fractionals < unsafe_interval.f()) {
406       return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
407                        unsafe_interval.f(), fractionals, one.f(), unit);
408     }
409   }
410 }
411 
412 
413 
414 // Generates (at most) requested_digits digits of input number w.
415 // w is a floating-point number (DiyFp), consisting of a significand and an
416 // exponent. Its exponent is bounded by kMinimalTargetExponent and
417 // kMaximalTargetExponent.
418 //       Hence -60 <= w.e() <= -32.
419 //
420 // Returns false if it fails, in which case the generated digits in the buffer
421 // should not be used.
422 // Preconditions:
423 //  * w is correct up to 1 ulp (unit in the last place). That
424 //    is, its error must be strictly less than a unit of its last digit.
425 //  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
426 //
427 // Postconditions: returns false if procedure fails.
428 //   otherwise:
429 //     * buffer is not null-terminated, but length contains the number of
430 //       digits.
431 //     * the representation in buffer is the most precise representation of
432 //       requested_digits digits.
433 //     * buffer contains at most requested_digits digits of w. If there are less
434 //       than requested_digits digits then some trailing '0's have been removed.
435 //     * kappa is such that
436 //            w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
437 //
438 // Remark: This procedure takes into account the imprecision of its input
439 //   numbers. If the precision is not enough to guarantee all the postconditions
440 //   then false is returned. This usually happens rarely, but the failure-rate
441 //   increases with higher requested_digits.
DigitGenCounted(DiyFp w,int requested_digits,Vector<char> buffer,int * length,int * kappa)442 static bool DigitGenCounted(DiyFp w,
443                             int requested_digits,
444                             Vector<char> buffer,
445                             int* length,
446                             int* kappa) {
447   DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
448   DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent >= -60);
449   DOUBLE_CONVERSION_ASSERT(kMaximalTargetExponent <= -32);
450   // w is assumed to have an error less than 1 unit. Whenever w is scaled we
451   // also scale its error.
452   uint64_t w_error = 1;
453   // We cut the input number into two parts: the integral digits and the
454   // fractional digits. We don't emit any decimal separator, but adapt kappa
455   // instead. Example: instead of writing "1.2" we put "12" into the buffer and
456   // increase kappa by 1.
457   DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
458   // Division by one is a shift.
459   uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
460   // Modulo by one is an and.
461   uint64_t fractionals = w.f() & (one.f() - 1);
462   uint32_t divisor;
463   int divisor_exponent_plus_one;
464   BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
465                   &divisor, &divisor_exponent_plus_one);
466   *kappa = divisor_exponent_plus_one;
467   *length = 0;
468 
469   // Loop invariant: buffer = w / 10^kappa  (integer division)
470   // The invariant holds for the first iteration: kappa has been initialized
471   // with the divisor exponent + 1. And the divisor is the biggest power of ten
472   // that is smaller than 'integrals'.
473   while (*kappa > 0) {
474     int digit = integrals / divisor;
475     DOUBLE_CONVERSION_ASSERT(digit <= 9);
476     buffer[*length] = static_cast<char>('0' + digit);
477     (*length)++;
478     requested_digits--;
479     integrals %= divisor;
480     (*kappa)--;
481     // Note that kappa now equals the exponent of the divisor and that the
482     // invariant thus holds again.
483     if (requested_digits == 0) break;
484     divisor /= 10;
485   }
486 
487   if (requested_digits == 0) {
488     uint64_t rest =
489         (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
490     return RoundWeedCounted(buffer, *length, rest,
491                             static_cast<uint64_t>(divisor) << -one.e(), w_error,
492                             kappa);
493   }
494 
495   // The integrals have been generated. We are at the point of the decimal
496   // separator. In the following loop we simply multiply the remaining digits by
497   // 10 and divide by one. We just need to pay attention to multiply associated
498   // data (the 'unit'), too.
499   // Note that the multiplication by 10 does not overflow, because w.e >= -60
500   // and thus one.e >= -60.
501   DOUBLE_CONVERSION_ASSERT(one.e() >= -60);
502   DOUBLE_CONVERSION_ASSERT(fractionals < one.f());
503   DOUBLE_CONVERSION_ASSERT(DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
504   while (requested_digits > 0 && fractionals > w_error) {
505     fractionals *= 10;
506     w_error *= 10;
507     // Integer division by one.
508     int digit = static_cast<int>(fractionals >> -one.e());
509     DOUBLE_CONVERSION_ASSERT(digit <= 9);
510     buffer[*length] = static_cast<char>('0' + digit);
511     (*length)++;
512     requested_digits--;
513     fractionals &= one.f() - 1;  // Modulo by one.
514     (*kappa)--;
515   }
516   if (requested_digits != 0) return false;
517   return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
518                           kappa);
519 }
520 
521 
522 // Provides a decimal representation of v.
523 // Returns true if it succeeds, otherwise the result cannot be trusted.
524 // There will be *length digits inside the buffer (not null-terminated).
525 // If the function returns true then
526 //        v == (double) (buffer * 10^decimal_exponent).
527 // The digits in the buffer are the shortest representation possible: no
528 // 0.09999999999999999 instead of 0.1. The shorter representation will even be
529 // chosen even if the longer one would be closer to v.
530 // The last digit will be closest to the actual v. That is, even if several
531 // digits might correctly yield 'v' when read again, the closest will be
532 // computed.
Grisu3(double v,FastDtoaMode mode,Vector<char> buffer,int * length,int * decimal_exponent)533 static bool Grisu3(double v,
534                    FastDtoaMode mode,
535                    Vector<char> buffer,
536                    int* length,
537                    int* decimal_exponent) {
538   DiyFp w = Double(v).AsNormalizedDiyFp();
539   // boundary_minus and boundary_plus are the boundaries between v and its
540   // closest floating-point neighbors. Any number strictly between
541   // boundary_minus and boundary_plus will round to v when convert to a double.
542   // Grisu3 will never output representations that lie exactly on a boundary.
543   DiyFp boundary_minus, boundary_plus;
544   if (mode == FAST_DTOA_SHORTEST) {
545     Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
546   } else {
547     DOUBLE_CONVERSION_ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
548     float single_v = static_cast<float>(v);
549     Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
550   }
551   DOUBLE_CONVERSION_ASSERT(boundary_plus.e() == w.e());
552   DiyFp ten_mk;  // Cached power of ten: 10^-k
553   int mk;        // -k
554   int ten_mk_minimal_binary_exponent =
555      kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
556   int ten_mk_maximal_binary_exponent =
557      kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
558   PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
559       ten_mk_minimal_binary_exponent,
560       ten_mk_maximal_binary_exponent,
561       &ten_mk, &mk);
562   DOUBLE_CONVERSION_ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
563           DiyFp::kSignificandSize) &&
564          (kMaximalTargetExponent >= w.e() + ten_mk.e() +
565           DiyFp::kSignificandSize));
566   // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
567   // 64 bit significand and ten_mk is thus only precise up to 64 bits.
568 
569   // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
570   // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
571   // off by a small amount.
572   // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
573   // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
574   //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
575   DiyFp scaled_w = DiyFp::Times(w, ten_mk);
576   DOUBLE_CONVERSION_ASSERT(scaled_w.e() ==
577          boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
578   // In theory it would be possible to avoid some recomputations by computing
579   // the difference between w and boundary_minus/plus (a power of 2) and to
580   // compute scaled_boundary_minus/plus by subtracting/adding from
581   // scaled_w. However the code becomes much less readable and the speed
582   // enhancements are not terriffic.
583   DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
584   DiyFp scaled_boundary_plus  = DiyFp::Times(boundary_plus,  ten_mk);
585 
586   // DigitGen will generate the digits of scaled_w. Therefore we have
587   // v == (double) (scaled_w * 10^-mk).
588   // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
589   // integer than it will be updated. For instance if scaled_w == 1.23 then
590   // the buffer will be filled with "123" und the decimal_exponent will be
591   // decreased by 2.
592   int kappa;
593   bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
594                          buffer, length, &kappa);
595   *decimal_exponent = -mk + kappa;
596   return result;
597 }
598 
599 
600 // The "counted" version of grisu3 (see above) only generates requested_digits
601 // number of digits. This version does not generate the shortest representation,
602 // and with enough requested digits 0.1 will at some point print as 0.9999999...
603 // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
604 // therefore the rounding strategy for halfway cases is irrelevant.
Grisu3Counted(double v,int requested_digits,Vector<char> buffer,int * length,int * decimal_exponent)605 static bool Grisu3Counted(double v,
606                           int requested_digits,
607                           Vector<char> buffer,
608                           int* length,
609                           int* decimal_exponent) {
610   DiyFp w = Double(v).AsNormalizedDiyFp();
611   DiyFp ten_mk;  // Cached power of ten: 10^-k
612   int mk;        // -k
613   int ten_mk_minimal_binary_exponent =
614      kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
615   int ten_mk_maximal_binary_exponent =
616      kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
617   PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
618       ten_mk_minimal_binary_exponent,
619       ten_mk_maximal_binary_exponent,
620       &ten_mk, &mk);
621   DOUBLE_CONVERSION_ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
622           DiyFp::kSignificandSize) &&
623          (kMaximalTargetExponent >= w.e() + ten_mk.e() +
624           DiyFp::kSignificandSize));
625   // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
626   // 64 bit significand and ten_mk is thus only precise up to 64 bits.
627 
628   // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
629   // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
630   // off by a small amount.
631   // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
632   // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
633   //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
634   DiyFp scaled_w = DiyFp::Times(w, ten_mk);
635 
636   // We now have (double) (scaled_w * 10^-mk).
637   // DigitGen will generate the first requested_digits digits of scaled_w and
638   // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
639   // will not always be exactly the same since DigitGenCounted only produces a
640   // limited number of digits.)
641   int kappa;
642   bool result = DigitGenCounted(scaled_w, requested_digits,
643                                 buffer, length, &kappa);
644   *decimal_exponent = -mk + kappa;
645   return result;
646 }
647 
648 
FastDtoa(double v,FastDtoaMode mode,int requested_digits,Vector<char> buffer,int * length,int * decimal_point)649 bool FastDtoa(double v,
650               FastDtoaMode mode,
651               int requested_digits,
652               Vector<char> buffer,
653               int* length,
654               int* decimal_point) {
655   DOUBLE_CONVERSION_ASSERT(v > 0);
656   DOUBLE_CONVERSION_ASSERT(!Double(v).IsSpecial());
657 
658   bool result = false;
659   int decimal_exponent = 0;
660   switch (mode) {
661     case FAST_DTOA_SHORTEST:
662     case FAST_DTOA_SHORTEST_SINGLE:
663       result = Grisu3(v, mode, buffer, length, &decimal_exponent);
664       break;
665     case FAST_DTOA_PRECISION:
666       result = Grisu3Counted(v, requested_digits,
667                              buffer, length, &decimal_exponent);
668       break;
669     default:
670       DOUBLE_CONVERSION_UNREACHABLE();
671   }
672   if (result) {
673     *decimal_point = *length + decimal_exponent;
674     buffer[*length] = '\0';
675   }
676   return result;
677 }
678 
679 }  // namespace double_conversion
680 
681 // ICU PATCH: Close ICU namespace
682 U_NAMESPACE_END
683 #endif // ICU PATCH: close #if !UCONFIG_NO_FORMATTING
684