github.com/nuvolaris/goja@v0.0.0-20230825100449-967811910c6d/ftoa/internal/fast/dtoa.go (about)

     1  package fast
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  )
     7  
     8  const (
     9  	kMinimalTargetExponent = -60
    10  	kMaximalTargetExponent = -32
    11  
    12  	kTen4 = 10000
    13  	kTen5 = 100000
    14  	kTen6 = 1000000
    15  	kTen7 = 10000000
    16  	kTen8 = 100000000
    17  	kTen9 = 1000000000
    18  )
    19  
    20  type Mode int
    21  
    22  const (
    23  	ModeShortest Mode = iota
    24  	ModePrecision
    25  )
    26  
    27  // Adjusts the last digit of the generated number, and screens out generated
    28  // solutions that may be inaccurate. A solution may be inaccurate if it is
    29  // outside the safe interval, or if we cannot prove that it is closer to the
    30  // input than a neighboring representation of the same length.
    31  //
    32  // Input: * buffer containing the digits of too_high / 10^kappa
    33  //   - distance_too_high_w == (too_high - w).f() * unit
    34  //   - unsafe_interval == (too_high - too_low).f() * unit
    35  //   - rest = (too_high - buffer * 10^kappa).f() * unit
    36  //   - ten_kappa = 10^kappa * unit
    37  //   - unit = the common multiplier
    38  //
    39  // Output: returns true if the buffer is guaranteed to contain the closest
    40  //
    41  //	  representable number to the input.
    42  //	Modifies the generated digits in the buffer to approach (round towards) w.
    43  func roundWeed(buffer []byte, distance_too_high_w, unsafe_interval, rest, ten_kappa, unit uint64) bool {
    44  	small_distance := distance_too_high_w - unit
    45  	big_distance := distance_too_high_w + unit
    46  
    47  	// Let w_low  = too_high - big_distance, and
    48  	//     w_high = too_high - small_distance.
    49  	// Note: w_low < w < w_high
    50  	//
    51  	// The real w (* unit) must lie somewhere inside the interval
    52  	// ]w_low; w_high[ (often written as "(w_low; w_high)")
    53  
    54  	// Basically the buffer currently contains a number in the unsafe interval
    55  	// ]too_low; too_high[ with too_low < w < too_high
    56  	//
    57  	//  too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    58  	//                     ^v 1 unit            ^      ^                 ^      ^
    59  	//  boundary_high ---------------------     .      .                 .      .
    60  	//                     ^v 1 unit            .      .                 .      .
    61  	//   - - - - - - - - - - - - - - - - - - -  +  - - + - - - - - -     .      .
    62  	//                                          .      .         ^       .      .
    63  	//                                          .  big_distance  .       .      .
    64  	//                                          .      .         .       .    rest
    65  	//                              small_distance     .         .       .      .
    66  	//                                          v      .         .       .      .
    67  	//  w_high - - - - - - - - - - - - - - - - - -     .         .       .      .
    68  	//                     ^v 1 unit                   .         .       .      .
    69  	//  w ----------------------------------------     .         .       .      .
    70  	//                     ^v 1 unit                   v         .       .      .
    71  	//  w_low  - - - - - - - - - - - - - - - - - - - - -         .       .      .
    72  	//                                                           .       .      v
    73  	//  buffer --------------------------------------------------+-------+--------
    74  	//                                                           .       .
    75  	//                                                  safe_interval    .
    76  	//                                                           v       .
    77  	//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -     .
    78  	//                     ^v 1 unit                                     .
    79  	//  boundary_low -------------------------                     unsafe_interval
    80  	//                     ^v 1 unit                                     v
    81  	//  too_low  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    82  	//
    83  	//
    84  	// Note that the value of buffer could lie anywhere inside the range too_low
    85  	// to too_high.
    86  	//
    87  	// boundary_low, boundary_high and w are approximations of the real boundaries
    88  	// and v (the input number). They are guaranteed to be precise up to one unit.
    89  	// In fact the error is guaranteed to be strictly less than one unit.
    90  	//
    91  	// Anything that lies outside the unsafe interval is guaranteed not to round
    92  	// to v when read again.
    93  	// Anything that lies inside the safe interval is guaranteed to round to v
    94  	// when read again.
    95  	// If the number inside the buffer lies inside the unsafe interval but not
    96  	// inside the safe interval then we simply do not know and bail out (returning
    97  	// false).
    98  	//
    99  	// Similarly we have to take into account the imprecision of 'w' when finding
   100  	// the closest representation of 'w'. If we have two potential
   101  	// representations, and one is closer to both w_low and w_high, then we know
   102  	// it is closer to the actual value v.
   103  	//
   104  	// By generating the digits of too_high we got the largest (closest to
   105  	// too_high) buffer that is still in the unsafe interval. In the case where
   106  	// w_high < buffer < too_high we try to decrement the buffer.
   107  	// This way the buffer approaches (rounds towards) w.
   108  	// There are 3 conditions that stop the decrementation process:
   109  	//   1) the buffer is already below w_high
   110  	//   2) decrementing the buffer would make it leave the unsafe interval
   111  	//   3) decrementing the buffer would yield a number below w_high and farther
   112  	//      away than the current number. In other words:
   113  	//              (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
   114  	// Instead of using the buffer directly we use its distance to too_high.
   115  	// Conceptually rest ~= too_high - buffer
   116  	// We need to do the following tests in this order to avoid over- and
   117  	// underflows.
   118  	_DCHECK(rest <= unsafe_interval)
   119  	for rest < small_distance && // Negated condition 1
   120  		unsafe_interval-rest >= ten_kappa && // Negated condition 2
   121  		(rest+ten_kappa < small_distance || // buffer{-1} > w_high
   122  			small_distance-rest >= rest+ten_kappa-small_distance) {
   123  		buffer[len(buffer)-1]--
   124  		rest += ten_kappa
   125  	}
   126  
   127  	// We have approached w+ as much as possible. We now test if approaching w-
   128  	// would require changing the buffer. If yes, then we have two possible
   129  	// representations close to w, but we cannot decide which one is closer.
   130  	if rest < big_distance && unsafe_interval-rest >= ten_kappa &&
   131  		(rest+ten_kappa < big_distance ||
   132  			big_distance-rest > rest+ten_kappa-big_distance) {
   133  		return false
   134  	}
   135  
   136  	// Weeding test.
   137  	//   The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
   138  	//   Since too_low = too_high - unsafe_interval this is equivalent to
   139  	//      [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
   140  	//   Conceptually we have: rest ~= too_high - buffer
   141  	return (2*unit <= rest) && (rest <= unsafe_interval-4*unit)
   142  }
   143  
   144  // Rounds the buffer upwards if the result is closer to v by possibly adding
   145  // 1 to the buffer. If the precision of the calculation is not sufficient to
   146  // round correctly, return false.
   147  // The rounding might shift the whole buffer in which case the kappa is
   148  // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
   149  //
   150  // If 2*rest > ten_kappa then the buffer needs to be round up.
   151  // rest can have an error of +/- 1 unit. This function accounts for the
   152  // imprecision and returns false, if the rounding direction cannot be
   153  // unambiguously determined.
   154  //
   155  // Precondition: rest < ten_kappa.
   156  func roundWeedCounted(buffer []byte, rest, ten_kappa, unit uint64, kappa *int) bool {
   157  	_DCHECK(rest < ten_kappa)
   158  	// The following tests are done in a specific order to avoid overflows. They
   159  	// will work correctly with any uint64 values of rest < ten_kappa and unit.
   160  	//
   161  	// If the unit is too big, then we don't know which way to round. For example
   162  	// a unit of 50 means that the real number lies within rest +/- 50. If
   163  	// 10^kappa == 40 then there is no way to tell which way to round.
   164  	if unit >= ten_kappa {
   165  		return false
   166  	}
   167  	// Even if unit is just half the size of 10^kappa we are already completely
   168  	// lost. (And after the previous test we know that the expression will not
   169  	// over/underflow.)
   170  	if ten_kappa-unit <= unit {
   171  		return false
   172  	}
   173  	// If 2 * (rest + unit) <= 10^kappa we can safely round down.
   174  	if (ten_kappa-rest > rest) && (ten_kappa-2*rest >= 2*unit) {
   175  		return true
   176  	}
   177  
   178  	// If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
   179  	if (rest > unit) && (ten_kappa-(rest-unit) <= (rest - unit)) {
   180  		// Increment the last digit recursively until we find a non '9' digit.
   181  		buffer[len(buffer)-1]++
   182  		for i := len(buffer) - 1; i > 0; i-- {
   183  			if buffer[i] != '0'+10 {
   184  				break
   185  			}
   186  			buffer[i] = '0'
   187  			buffer[i-1]++
   188  		}
   189  		// If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
   190  		// exception of the first digit all digits are now '0'. Simply switch the
   191  		// first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
   192  		// the power (the kappa) is increased.
   193  		if buffer[0] == '0'+10 {
   194  			buffer[0] = '1'
   195  			*kappa += 1
   196  		}
   197  		return true
   198  	}
   199  	return false
   200  }
   201  
   202  // Returns the biggest power of ten that is less than or equal than the given
   203  // number. We furthermore receive the maximum number of bits 'number' has.
   204  // If number_bits == 0 then 0^-1 is returned
   205  // The number of bits must be <= 32.
   206  // Precondition: number < (1 << (number_bits + 1)).
   207  func biggestPowerTen(number uint32, number_bits int) (power uint32, exponent int) {
   208  	switch number_bits {
   209  	case 32, 31, 30:
   210  		if kTen9 <= number {
   211  			power = kTen9
   212  			exponent = 9
   213  			break
   214  		}
   215  		fallthrough
   216  	case 29, 28, 27:
   217  		if kTen8 <= number {
   218  			power = kTen8
   219  			exponent = 8
   220  			break
   221  		}
   222  		fallthrough
   223  	case 26, 25, 24:
   224  		if kTen7 <= number {
   225  			power = kTen7
   226  			exponent = 7
   227  			break
   228  		}
   229  		fallthrough
   230  	case 23, 22, 21, 20:
   231  		if kTen6 <= number {
   232  			power = kTen6
   233  			exponent = 6
   234  			break
   235  		}
   236  		fallthrough
   237  	case 19, 18, 17:
   238  		if kTen5 <= number {
   239  			power = kTen5
   240  			exponent = 5
   241  			break
   242  		}
   243  		fallthrough
   244  	case 16, 15, 14:
   245  		if kTen4 <= number {
   246  			power = kTen4
   247  			exponent = 4
   248  			break
   249  		}
   250  		fallthrough
   251  	case 13, 12, 11, 10:
   252  		if 1000 <= number {
   253  			power = 1000
   254  			exponent = 3
   255  			break
   256  		}
   257  		fallthrough
   258  	case 9, 8, 7:
   259  		if 100 <= number {
   260  			power = 100
   261  			exponent = 2
   262  			break
   263  		}
   264  		fallthrough
   265  	case 6, 5, 4:
   266  		if 10 <= number {
   267  			power = 10
   268  			exponent = 1
   269  			break
   270  		}
   271  		fallthrough
   272  	case 3, 2, 1:
   273  		if 1 <= number {
   274  			power = 1
   275  			exponent = 0
   276  			break
   277  		}
   278  		fallthrough
   279  	case 0:
   280  		power = 0
   281  		exponent = -1
   282  	}
   283  	return
   284  }
   285  
   286  // Generates the digits of input number w.
   287  // w is a floating-point number (DiyFp), consisting of a significand and an
   288  // exponent. Its exponent is bounded by kMinimalTargetExponent and
   289  // kMaximalTargetExponent.
   290  //
   291  //	Hence -60 <= w.e() <= -32.
   292  //
   293  // Returns false if it fails, in which case the generated digits in the buffer
   294  // should not be used.
   295  // Preconditions:
   296  //   - low, w and high are correct up to 1 ulp (unit in the last place). That
   297  //     is, their error must be less than a unit of their last digits.
   298  //   - low.e() == w.e() == high.e()
   299  //   - low < w < high, and taking into account their error: low~ <= high~
   300  //   - kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
   301  //
   302  // Postconditions: returns false if procedure fails.
   303  //
   304  //	otherwise:
   305  //	  * buffer is not null-terminated, but len contains the number of digits.
   306  //	  * buffer contains the shortest possible decimal digit-sequence
   307  //	    such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
   308  //	    correct values of low and high (without their error).
   309  //	  * if more than one decimal representation gives the minimal number of
   310  //	    decimal digits then the one closest to W (where W is the correct value
   311  //	    of w) is chosen.
   312  //
   313  // Remark: this procedure takes into account the imprecision of its input
   314  //
   315  //	numbers. If the precision is not enough to guarantee all the postconditions
   316  //	then false is returned. This usually happens rarely (~0.5%).
   317  //
   318  // Say, for the sake of example, that
   319  //
   320  //	w.e() == -48, and w.f() == 0x1234567890ABCDEF
   321  //
   322  // w's value can be computed by w.f() * 2^w.e()
   323  // We can obtain w's integral digits by simply shifting w.f() by -w.e().
   324  //
   325  //	-> w's integral part is 0x1234
   326  //	w's fractional part is therefore 0x567890ABCDEF.
   327  //
   328  // Printing w's integral part is easy (simply print 0x1234 in decimal).
   329  // In order to print its fraction we repeatedly multiply the fraction by 10 and
   330  // get each digit. Example the first digit after the point would be computed by
   331  //
   332  //	(0x567890ABCDEF * 10) >> 48. -> 3
   333  //
   334  // The whole thing becomes slightly more complicated because we want to stop
   335  // once we have enough digits. That is, once the digits inside the buffer
   336  // represent 'w' we can stop. Everything inside the interval low - high
   337  // represents w. However we have to pay attention to low, high and w's
   338  // imprecision.
   339  func digitGen(low, w, high diyfp, buffer []byte) (kappa int, buf []byte, res bool) {
   340  	_DCHECK(low.e == w.e && w.e == high.e)
   341  	_DCHECK(low.f+1 <= high.f-1)
   342  	_DCHECK(kMinimalTargetExponent <= w.e && w.e <= kMaximalTargetExponent)
   343  	// low, w and high are imprecise, but by less than one ulp (unit in the last
   344  	// place).
   345  	// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
   346  	// the new numbers are outside of the interval we want the final
   347  	// representation to lie in.
   348  	// Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
   349  	// numbers that are certain to lie in the interval. We will use this fact
   350  	// later on.
   351  	// We will now start by generating the digits within the uncertain
   352  	// interval. Later we will weed out representations that lie outside the safe
   353  	// interval and thus _might_ lie outside the correct interval.
   354  	unit := uint64(1)
   355  	too_low := diyfp{f: low.f - unit, e: low.e}
   356  	too_high := diyfp{f: high.f + unit, e: high.e}
   357  	// too_low and too_high are guaranteed to lie outside the interval we want the
   358  	// generated number in.
   359  	unsafe_interval := too_high.minus(too_low)
   360  	// We now cut the input number into two parts: the integral digits and the
   361  	// fractionals. We will not write any decimal separator though, but adapt
   362  	// kappa instead.
   363  	// Reminder: we are currently computing the digits (stored inside the buffer)
   364  	// such that:   too_low < buffer * 10^kappa < too_high
   365  	// We use too_high for the digit_generation and stop as soon as possible.
   366  	// If we stop early we effectively round down.
   367  	one := diyfp{f: 1 << -w.e, e: w.e}
   368  	// Division by one is a shift.
   369  	integrals := uint32(too_high.f >> -one.e)
   370  	// Modulo by one is an and.
   371  	fractionals := too_high.f & (one.f - 1)
   372  	divisor, divisor_exponent := biggestPowerTen(integrals, diyFpKSignificandSize-(-one.e))
   373  	kappa = divisor_exponent + 1
   374  	buf = buffer
   375  	for kappa > 0 {
   376  		digit := int(integrals / divisor)
   377  		buf = append(buf, byte('0'+digit))
   378  		integrals %= divisor
   379  		kappa--
   380  		// Note that kappa now equals the exponent of the divisor and that the
   381  		// invariant thus holds again.
   382  		rest := uint64(integrals)<<-one.e + fractionals
   383  		// Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e)
   384  		// Reminder: unsafe_interval.e == one.e
   385  		if rest < unsafe_interval.f {
   386  			// Rounding down (by not emitting the remaining digits) yields a number
   387  			// that lies within the unsafe interval.
   388  			res = roundWeed(buf, too_high.minus(w).f,
   389  				unsafe_interval.f, rest,
   390  				uint64(divisor)<<-one.e, unit)
   391  			return
   392  		}
   393  		divisor /= 10
   394  	}
   395  	// The integrals have been generated. We are at the point of the decimal
   396  	// separator. In the following loop we simply multiply the remaining digits by
   397  	// 10 and divide by one. We just need to pay attention to multiply associated
   398  	// data (like the interval or 'unit'), too.
   399  	// Note that the multiplication by 10 does not overflow, because w.e >= -60
   400  	// and thus one.e >= -60.
   401  	_DCHECK(one.e >= -60)
   402  	_DCHECK(fractionals < one.f)
   403  	_DCHECK(0xFFFFFFFFFFFFFFFF/10 >= one.f)
   404  	for {
   405  		fractionals *= 10
   406  		unit *= 10
   407  		unsafe_interval.f *= 10
   408  		// Integer division by one.
   409  		digit := byte(fractionals >> -one.e)
   410  		buf = append(buf, '0'+digit)
   411  		fractionals &= one.f - 1 // Modulo by one.
   412  		kappa--
   413  		if fractionals < unsafe_interval.f {
   414  			res = roundWeed(buf, too_high.minus(w).f*unit, unsafe_interval.f, fractionals, one.f, unit)
   415  			return
   416  		}
   417  	}
   418  }
   419  
   420  // Generates (at most) requested_digits of input number w.
   421  // w is a floating-point number (DiyFp), consisting of a significand and an
   422  // exponent. Its exponent is bounded by kMinimalTargetExponent and
   423  // kMaximalTargetExponent.
   424  //
   425  //	Hence -60 <= w.e() <= -32.
   426  //
   427  // Returns false if it fails, in which case the generated digits in the buffer
   428  // should not be used.
   429  // Preconditions:
   430  //   - w is correct up to 1 ulp (unit in the last place). That
   431  //     is, its error must be strictly less than a unit of its last digit.
   432  //   - kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
   433  //
   434  // Postconditions: returns false if procedure fails.
   435  //
   436  //	otherwise:
   437  //	  * buffer is not null-terminated, but length contains the number of
   438  //	    digits.
   439  //	  * the representation in buffer is the most precise representation of
   440  //	    requested_digits digits.
   441  //	  * buffer contains at most requested_digits digits of w. If there are less
   442  //	    than requested_digits digits then some trailing '0's have been removed.
   443  //	  * kappa is such that
   444  //	         w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
   445  //
   446  // Remark: This procedure takes into account the imprecision of its input
   447  //
   448  //	numbers. If the precision is not enough to guarantee all the postconditions
   449  //	then false is returned. This usually happens rarely, but the failure-rate
   450  //	increases with higher requested_digits.
   451  func digitGenCounted(w diyfp, requested_digits int, buffer []byte) (kappa int, buf []byte, res bool) {
   452  	_DCHECK(kMinimalTargetExponent <= w.e && w.e <= kMaximalTargetExponent)
   453  
   454  	// w is assumed to have an error less than 1 unit. Whenever w is scaled we
   455  	// also scale its error.
   456  	w_error := uint64(1)
   457  	// We cut the input number into two parts: the integral digits and the
   458  	// fractional digits. We don't emit any decimal separator, but adapt kappa
   459  	// instead. Example: instead of writing "1.2" we put "12" into the buffer and
   460  	// increase kappa by 1.
   461  	one := diyfp{f: 1 << -w.e, e: w.e}
   462  	// Division by one is a shift.
   463  	integrals := uint32(w.f >> -one.e)
   464  	// Modulo by one is an and.
   465  	fractionals := w.f & (one.f - 1)
   466  	divisor, divisor_exponent := biggestPowerTen(integrals, diyFpKSignificandSize-(-one.e))
   467  	kappa = divisor_exponent + 1
   468  	buf = buffer
   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  	for kappa > 0 {
   474  		digit := byte(integrals / divisor)
   475  		buf = append(buf, '0'+digit)
   476  		requested_digits--
   477  		integrals %= divisor
   478  		kappa--
   479  		// Note that kappa now equals the exponent of the divisor and that the
   480  		// invariant thus holds again.
   481  		if requested_digits == 0 {
   482  			break
   483  		}
   484  		divisor /= 10
   485  	}
   486  
   487  	if requested_digits == 0 {
   488  		rest := uint64(integrals)<<-one.e + fractionals
   489  		res = roundWeedCounted(buf, rest, uint64(divisor)<<-one.e, w_error, &kappa)
   490  		return
   491  	}
   492  
   493  	// The integrals have been generated. We are at the point of the decimal
   494  	// separator. In the following loop we simply multiply the remaining digits by
   495  	// 10 and divide by one. We just need to pay attention to multiply associated
   496  	// data (the 'unit'), too.
   497  	// Note that the multiplication by 10 does not overflow, because w.e >= -60
   498  	// and thus one.e >= -60.
   499  	_DCHECK(one.e >= -60)
   500  	_DCHECK(fractionals < one.f)
   501  	_DCHECK(0xFFFFFFFFFFFFFFFF/10 >= one.f)
   502  	for requested_digits > 0 && fractionals > w_error {
   503  		fractionals *= 10
   504  		w_error *= 10
   505  		// Integer division by one.
   506  		digit := byte(fractionals >> -one.e)
   507  		buf = append(buf, '0'+digit)
   508  		requested_digits--
   509  		fractionals &= one.f - 1 // Modulo by one.
   510  		kappa--
   511  	}
   512  	if requested_digits != 0 {
   513  		res = false
   514  	} else {
   515  		res = roundWeedCounted(buf, fractionals, one.f, w_error, &kappa)
   516  	}
   517  	return
   518  }
   519  
   520  // Provides a decimal representation of v.
   521  // Returns true if it succeeds, otherwise the result cannot be trusted.
   522  // There will be *length digits inside the buffer (not null-terminated).
   523  // If the function returns true then
   524  //
   525  //	v == (double) (buffer * 10^decimal_exponent).
   526  //
   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.
   533  func grisu3(f float64, buffer []byte) (digits []byte, decimal_exponent int, result bool) {
   534  	v := double(f)
   535  	w := v.toNormalizedDiyfp()
   536  
   537  	// boundary_minus and boundary_plus are the boundaries between v and its
   538  	// closest floating-point neighbors. Any number strictly between
   539  	// boundary_minus and boundary_plus will round to v when convert to a double.
   540  	// Grisu3 will never output representations that lie exactly on a boundary.
   541  	boundary_minus, boundary_plus := v.normalizedBoundaries()
   542  	ten_mk_minimal_binary_exponent := kMinimalTargetExponent - (w.e + diyFpKSignificandSize)
   543  	ten_mk_maximal_binary_exponent := kMaximalTargetExponent - (w.e + diyFpKSignificandSize)
   544  	ten_mk, mk := getCachedPowerForBinaryExponentRange(ten_mk_minimal_binary_exponent, ten_mk_maximal_binary_exponent)
   545  
   546  	_DCHECK(
   547  		(kMinimalTargetExponent <=
   548  			w.e+ten_mk.e+diyFpKSignificandSize) &&
   549  			(kMaximalTargetExponent >= w.e+ten_mk.e+diyFpKSignificandSize))
   550  	// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
   551  	// 64 bit significand and ten_mk is thus only precise up to 64 bits.
   552  
   553  	// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
   554  	// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
   555  	// off by a small amount.
   556  	// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
   557  	// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
   558  	//           (f-1) * 2^e < w*10^k < (f+1) * 2^e
   559  	scaled_w := w.times(ten_mk)
   560  	_DCHECK(scaled_w.e ==
   561  		boundary_plus.e+ten_mk.e+diyFpKSignificandSize)
   562  	// In theory it would be possible to avoid some recomputations by computing
   563  	// the difference between w and boundary_minus/plus (a power of 2) and to
   564  	// compute scaled_boundary_minus/plus by subtracting/adding from
   565  	// scaled_w. However the code becomes much less readable and the speed
   566  	// enhancements are not terrific.
   567  	scaled_boundary_minus := boundary_minus.times(ten_mk)
   568  	scaled_boundary_plus := boundary_plus.times(ten_mk)
   569  	// DigitGen will generate the digits of scaled_w. Therefore we have
   570  	// v == (double) (scaled_w * 10^-mk).
   571  	// Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
   572  	// integer than it will be updated. For instance if scaled_w == 1.23 then
   573  	// the buffer will be filled with "123" und the decimal_exponent will be
   574  	// decreased by 2.
   575  	var kappa int
   576  	kappa, digits, result = digitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus, buffer)
   577  	decimal_exponent = -mk + kappa
   578  	return
   579  }
   580  
   581  // The "counted" version of grisu3 (see above) only generates requested_digits
   582  // number of digits. This version does not generate the shortest representation,
   583  // and with enough requested digits 0.1 will at some point print as 0.9999999...
   584  // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
   585  // therefore the rounding strategy for halfway cases is irrelevant.
   586  func grisu3Counted(v float64, requested_digits int, buffer []byte) (digits []byte, decimal_exponent int, result bool) {
   587  	w := double(v).toNormalizedDiyfp()
   588  	ten_mk_minimal_binary_exponent := kMinimalTargetExponent - (w.e + diyFpKSignificandSize)
   589  	ten_mk_maximal_binary_exponent := kMaximalTargetExponent - (w.e + diyFpKSignificandSize)
   590  	ten_mk, mk := getCachedPowerForBinaryExponentRange(ten_mk_minimal_binary_exponent, ten_mk_maximal_binary_exponent)
   591  
   592  	_DCHECK(
   593  		(kMinimalTargetExponent <=
   594  			w.e+ten_mk.e+diyFpKSignificandSize) &&
   595  			(kMaximalTargetExponent >= w.e+ten_mk.e+diyFpKSignificandSize))
   596  	// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
   597  	// 64 bit significand and ten_mk is thus only precise up to 64 bits.
   598  
   599  	// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
   600  	// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
   601  	// off by a small amount.
   602  	// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
   603  	// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
   604  	//           (f-1) * 2^e < w*10^k < (f+1) * 2^e
   605  	scaled_w := w.times(ten_mk)
   606  	// We now have (double) (scaled_w * 10^-mk).
   607  	// DigitGen will generate the first requested_digits digits of scaled_w and
   608  	// return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
   609  	// will not always be exactly the same since DigitGenCounted only produces a
   610  	// limited number of digits.)
   611  	var kappa int
   612  	kappa, digits, result = digitGenCounted(scaled_w, requested_digits, buffer)
   613  	decimal_exponent = -mk + kappa
   614  
   615  	return
   616  }
   617  
   618  // v must be > 0 and must not be Inf or NaN
   619  func Dtoa(v float64, mode Mode, requested_digits int, buffer []byte) (digits []byte, decimal_point int, result bool) {
   620  	defer func() {
   621  		if x := recover(); x != nil {
   622  			if x == dcheckFailure {
   623  				panic(fmt.Errorf("DCHECK assertion failed while formatting %s in mode %d", strconv.FormatFloat(v, 'e', 50, 64), mode))
   624  			}
   625  			panic(x)
   626  		}
   627  	}()
   628  	var decimal_exponent int
   629  	startPos := len(buffer)
   630  	switch mode {
   631  	case ModeShortest:
   632  		digits, decimal_exponent, result = grisu3(v, buffer)
   633  	case ModePrecision:
   634  		digits, decimal_exponent, result = grisu3Counted(v, requested_digits, buffer)
   635  	}
   636  	if result {
   637  		decimal_point = len(digits) - startPos + decimal_exponent
   638  	} else {
   639  		digits = digits[:startPos]
   640  	}
   641  	return
   642  }