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