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 2010 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#include <climits>
38#include <cstdarg>
39
40// ICU PATCH: Customize header file paths for ICU.
41
42#include "double-conversion-bignum.h"
43#include "double-conversion-cached-powers.h"
44#include "double-conversion-ieee.h"
45#include "double-conversion-strtod.h"
46
47// ICU PATCH: Wrap in ICU namespace
48U_NAMESPACE_BEGIN
49
50namespace double_conversion {
51
52#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
53// 2^53 = 9007199254740992.
54// Any integer with at most 15 decimal digits will hence fit into a double
55// (which has a 53bit significand) without loss of precision.
56static const int kMaxExactDoubleIntegerDecimalDigits = 15;
57#endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
58// 2^64 = 18446744073709551616 > 10^19
59static const int kMaxUint64DecimalDigits = 19;
60
61// Max double: 1.7976931348623157 x 10^308
62// Min non-zero double: 4.9406564584124654 x 10^-324
63// Any x >= 10^309 is interpreted as +infinity.
64// Any x <= 10^-324 is interpreted as 0.
65// Note that 2.5e-324 (despite being smaller than the min double) will be read
66// as non-zero (equal to the min non-zero double).
67static const int kMaxDecimalPower = 309;
68static const int kMinDecimalPower = -324;
69
70// 2^64 = 18446744073709551616
71static const uint64_t kMaxUint64 = DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
72
73
74#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
75static const double exact_powers_of_ten[] = {
76 1.0, // 10^0
77 10.0,
78 100.0,
79 1000.0,
80 10000.0,
81 100000.0,
82 1000000.0,
83 10000000.0,
84 100000000.0,
85 1000000000.0,
86 10000000000.0, // 10^10
87 100000000000.0,
88 1000000000000.0,
89 10000000000000.0,
90 100000000000000.0,
91 1000000000000000.0,
92 10000000000000000.0,
93 100000000000000000.0,
94 1000000000000000000.0,
95 10000000000000000000.0,
96 100000000000000000000.0, // 10^20
97 1000000000000000000000.0,
98 // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
99 10000000000000000000000.0
100};
101static const int kExactPowersOfTenSize = DOUBLE_CONVERSION_ARRAY_SIZE(exact_powers_of_ten);
102#endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
103
104// Maximum number of significant digits in the decimal representation.
105// In fact the value is 772 (see conversions.cc), but to give us some margin
106// we round up to 780.
107static const int kMaxSignificantDecimalDigits = 780;
108
109static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
110 for (int i = 0; i < buffer.length(); i++) {
111 if (buffer[i] != '0') {
112 return buffer.SubVector(i, buffer.length());
113 }
114 }
115 return Vector<const char>(buffer.start(), 0);
116}
117
118
119static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
120 for (int i = buffer.length() - 1; i >= 0; --i) {
121 if (buffer[i] != '0') {
122 return buffer.SubVector(0, i + 1);
123 }
124 }
125 return Vector<const char>(buffer.start(), 0);
126}
127
128
129static void CutToMaxSignificantDigits(Vector<const char> buffer,
130 int exponent,
131 char* significant_buffer,
132 int* significant_exponent) {
133 for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
134 significant_buffer[i] = buffer[i];
135 }
136 // The input buffer has been trimmed. Therefore the last digit must be
137 // different from '0'.
138 DOUBLE_CONVERSION_ASSERT(buffer[buffer.length() - 1] != '0');
139 // Set the last digit to be non-zero. This is sufficient to guarantee
140 // correct rounding.
141 significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
142 *significant_exponent =
143 exponent + (buffer.length() - kMaxSignificantDecimalDigits);
144}
145
146
147// Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits.
148// If possible the input-buffer is reused, but if the buffer needs to be
149// modified (due to cutting), then the input needs to be copied into the
150// buffer_copy_space.
151static void TrimAndCut(Vector<const char> buffer, int exponent,
152 char* buffer_copy_space, int space_size,
153 Vector<const char>* trimmed, int* updated_exponent) {
154 Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
155 Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed);
156 exponent += left_trimmed.length() - right_trimmed.length();
157 if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
158 (void) space_size; // Mark variable as used.
159 DOUBLE_CONVERSION_ASSERT(space_size >= kMaxSignificantDecimalDigits);
160 CutToMaxSignificantDigits(right_trimmed, exponent,
161 buffer_copy_space, updated_exponent);
162 *trimmed = Vector<const char>(buffer_copy_space,
163 kMaxSignificantDecimalDigits);
164 } else {
165 *trimmed = right_trimmed;
166 *updated_exponent = exponent;
167 }
168}
169
170
171// Reads digits from the buffer and converts them to a uint64.
172// Reads in as many digits as fit into a uint64.
173// When the string starts with "1844674407370955161" no further digit is read.
174// Since 2^64 = 18446744073709551616 it would still be possible read another
175// digit if it was less or equal than 6, but this would complicate the code.
176static uint64_t ReadUint64(Vector<const char> buffer,
177 int* number_of_read_digits) {
178 uint64_t result = 0;
179 int i = 0;
180 while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
181 int digit = buffer[i++] - '0';
182 DOUBLE_CONVERSION_ASSERT(0 <= digit && digit <= 9);
183 result = 10 * result + digit;
184 }
185 *number_of_read_digits = i;
186 return result;
187}
188
189
190// Reads a DiyFp from the buffer.
191// The returned DiyFp is not necessarily normalized.
192// If remaining_decimals is zero then the returned DiyFp is accurate.
193// Otherwise it has been rounded and has error of at most 1/2 ulp.
194static void ReadDiyFp(Vector<const char> buffer,
195 DiyFp* result,
196 int* remaining_decimals) {
197 int read_digits;
198 uint64_t significand = ReadUint64(buffer, &read_digits);
199 if (buffer.length() == read_digits) {
200 *result = DiyFp(significand, 0);
201 *remaining_decimals = 0;
202 } else {
203 // Round the significand.
204 if (buffer[read_digits] >= '5') {
205 significand++;
206 }
207 // Compute the binary exponent.
208 int exponent = 0;
209 *result = DiyFp(significand, exponent);
210 *remaining_decimals = buffer.length() - read_digits;
211 }
212}
213
214
215static bool DoubleStrtod(Vector<const char> trimmed,
216 int exponent,
217 double* result) {
218#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
219 // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
220 // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
221 // result is not accurate.
222 // We know that Windows32 uses 64 bits and is therefore accurate.
223 // Note that the ARM simulator is compiled for 32bits. It therefore exhibits
224 // the same problem.
225 return false;
226#else
227 if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
228 int read_digits;
229 // The trimmed input fits into a double.
230 // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
231 // can compute the result-double simply by multiplying (resp. dividing) the
232 // two numbers.
233 // This is possible because IEEE guarantees that floating-point operations
234 // return the best possible approximation.
235 if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
236 // 10^-exponent fits into a double.
237 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
238 DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length());
239 *result /= exact_powers_of_ten[-exponent];
240 return true;
241 }
242 if (0 <= exponent && exponent < kExactPowersOfTenSize) {
243 // 10^exponent fits into a double.
244 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
245 DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length());
246 *result *= exact_powers_of_ten[exponent];
247 return true;
248 }
249 int remaining_digits =
250 kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
251 if ((0 <= exponent) &&
252 (exponent - remaining_digits < kExactPowersOfTenSize)) {
253 // The trimmed string was short and we can multiply it with
254 // 10^remaining_digits. As a result the remaining exponent now fits
255 // into a double too.
256 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
257 DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length());
258 *result *= exact_powers_of_ten[remaining_digits];
259 *result *= exact_powers_of_ten[exponent - remaining_digits];
260 return true;
261 }
262 }
263 return false;
264#endif
265}
266
267
268// Returns 10^exponent as an exact DiyFp.
269// The given exponent must be in the range [1; kDecimalExponentDistance[.
270static DiyFp AdjustmentPowerOfTen(int exponent) {
271 DOUBLE_CONVERSION_ASSERT(0 < exponent);
272 DOUBLE_CONVERSION_ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
273 // Simply hardcode the remaining powers for the given decimal exponent
274 // distance.
275 DOUBLE_CONVERSION_ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
276 switch (exponent) {
277 case 1: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xa0000000, 00000000), -60);
278 case 2: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xc8000000, 00000000), -57);
279 case 3: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xfa000000, 00000000), -54);
280 case 4: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0x9c400000, 00000000), -50);
281 case 5: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xc3500000, 00000000), -47);
282 case 6: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xf4240000, 00000000), -44);
283 case 7: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0x98968000, 00000000), -40);
284 default:
285 DOUBLE_CONVERSION_UNREACHABLE();
286 }
287}
288
289
290// If the function returns true then the result is the correct double.
291// Otherwise it is either the correct double or the double that is just below
292// the correct double.
293static bool DiyFpStrtod(Vector<const char> buffer,
294 int exponent,
295 double* result) {
296 DiyFp input;
297 int remaining_decimals;
298 ReadDiyFp(buffer, &input, &remaining_decimals);
299 // Since we may have dropped some digits the input is not accurate.
300 // If remaining_decimals is different than 0 than the error is at most
301 // .5 ulp (unit in the last place).
302 // We don't want to deal with fractions and therefore keep a common
303 // denominator.
304 const int kDenominatorLog = 3;
305 const int kDenominator = 1 << kDenominatorLog;
306 // Move the remaining decimals into the exponent.
307 exponent += remaining_decimals;
308 uint64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
309
310 int old_e = input.e();
311 input.Normalize();
312 error <<= old_e - input.e();
313
314 DOUBLE_CONVERSION_ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
315 if (exponent < PowersOfTenCache::kMinDecimalExponent) {
316 *result = 0.0;
317 return true;
318 }
319 DiyFp cached_power;
320 int cached_decimal_exponent;
321 PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
322 &cached_power,
323 &cached_decimal_exponent);
324
325 if (cached_decimal_exponent != exponent) {
326 int adjustment_exponent = exponent - cached_decimal_exponent;
327 DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
328 input.Multiply(adjustment_power);
329 if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
330 // The product of input with the adjustment power fits into a 64 bit
331 // integer.
332 DOUBLE_CONVERSION_ASSERT(DiyFp::kSignificandSize == 64);
333 } else {
334 // The adjustment power is exact. There is hence only an error of 0.5.
335 error += kDenominator / 2;
336 }
337 }
338
339 input.Multiply(cached_power);
340 // The error introduced by a multiplication of a*b equals
341 // error_a + error_b + error_a*error_b/2^64 + 0.5
342 // Substituting a with 'input' and b with 'cached_power' we have
343 // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
344 // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
345 int error_b = kDenominator / 2;
346 int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
347 int fixed_error = kDenominator / 2;
348 error += error_b + error_ab + fixed_error;
349
350 old_e = input.e();
351 input.Normalize();
352 error <<= old_e - input.e();
353
354 // See if the double's significand changes if we add/subtract the error.
355 int order_of_magnitude = DiyFp::kSignificandSize + input.e();
356 int effective_significand_size =
357 Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
358 int precision_digits_count =
359 DiyFp::kSignificandSize - effective_significand_size;
360 if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
361 // This can only happen for very small denormals. In this case the
362 // half-way multiplied by the denominator exceeds the range of an uint64.
363 // Simply shift everything to the right.
364 int shift_amount = (precision_digits_count + kDenominatorLog) -
365 DiyFp::kSignificandSize + 1;
366 input.set_f(input.f() >> shift_amount);
367 input.set_e(input.e() + shift_amount);
368 // We add 1 for the lost precision of error, and kDenominator for
369 // the lost precision of input.f().
370 error = (error >> shift_amount) + 1 + kDenominator;
371 precision_digits_count -= shift_amount;
372 }
373 // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
374 DOUBLE_CONVERSION_ASSERT(DiyFp::kSignificandSize == 64);
375 DOUBLE_CONVERSION_ASSERT(precision_digits_count < 64);
376 uint64_t one64 = 1;
377 uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
378 uint64_t precision_bits = input.f() & precision_bits_mask;
379 uint64_t half_way = one64 << (precision_digits_count - 1);
380 precision_bits *= kDenominator;
381 half_way *= kDenominator;
382 DiyFp rounded_input(input.f() >> precision_digits_count,
383 input.e() + precision_digits_count);
384 if (precision_bits >= half_way + error) {
385 rounded_input.set_f(rounded_input.f() + 1);
386 }
387 // If the last_bits are too close to the half-way case than we are too
388 // inaccurate and round down. In this case we return false so that we can
389 // fall back to a more precise algorithm.
390
391 *result = Double(rounded_input).value();
392 if (half_way - error < precision_bits && precision_bits < half_way + error) {
393 // Too imprecise. The caller will have to fall back to a slower version.
394 // However the returned number is guaranteed to be either the correct
395 // double, or the next-lower double.
396 return false;
397 } else {
398 return true;
399 }
400}
401
402
403// Returns
404// - -1 if buffer*10^exponent < diy_fp.
405// - 0 if buffer*10^exponent == diy_fp.
406// - +1 if buffer*10^exponent > diy_fp.
407// Preconditions:
408// buffer.length() + exponent <= kMaxDecimalPower + 1
409// buffer.length() + exponent > kMinDecimalPower
410// buffer.length() <= kMaxDecimalSignificantDigits
411static int CompareBufferWithDiyFp(Vector<const char> buffer,
412 int exponent,
413 DiyFp diy_fp) {
414 DOUBLE_CONVERSION_ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
415 DOUBLE_CONVERSION_ASSERT(buffer.length() + exponent > kMinDecimalPower);
416 DOUBLE_CONVERSION_ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
417 // Make sure that the Bignum will be able to hold all our numbers.
418 // Our Bignum implementation has a separate field for exponents. Shifts will
419 // consume at most one bigit (< 64 bits).
420 // ln(10) == 3.3219...
421 DOUBLE_CONVERSION_ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
422 Bignum buffer_bignum;
423 Bignum diy_fp_bignum;
424 buffer_bignum.AssignDecimalString(buffer);
425 diy_fp_bignum.AssignUInt64(diy_fp.f());
426 if (exponent >= 0) {
427 buffer_bignum.MultiplyByPowerOfTen(exponent);
428 } else {
429 diy_fp_bignum.MultiplyByPowerOfTen(-exponent);
430 }
431 if (diy_fp.e() > 0) {
432 diy_fp_bignum.ShiftLeft(diy_fp.e());
433 } else {
434 buffer_bignum.ShiftLeft(-diy_fp.e());
435 }
436 return Bignum::Compare(buffer_bignum, diy_fp_bignum);
437}
438
439
440// Returns true if the guess is the correct double.
441// Returns false, when guess is either correct or the next-lower double.
442static bool ComputeGuess(Vector<const char> trimmed, int exponent,
443 double* guess) {
444 if (trimmed.length() == 0) {
445 *guess = 0.0;
446 return true;
447 }
448 if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
449 *guess = Double::Infinity();
450 return true;
451 }
452 if (exponent + trimmed.length() <= kMinDecimalPower) {
453 *guess = 0.0;
454 return true;
455 }
456
457 if (DoubleStrtod(trimmed, exponent, guess) ||
458 DiyFpStrtod(trimmed, exponent, guess)) {
459 return true;
460 }
461 if (*guess == Double::Infinity()) {
462 return true;
463 }
464 return false;
465}
466
467#if U_DEBUG // needed for ICU only in debug mode
468static bool IsDigit(const char d) {
469 return ('0' <= d) && (d <= '9');
470}
471
472static bool IsNonZeroDigit(const char d) {
473 return ('1' <= d) && (d <= '9');
474}
475
476static bool AssertTrimmedDigits(const Vector<const char>& buffer) {
477 for(int i = 0; i < buffer.length(); ++i) {
478 if(!IsDigit(buffer[i])) {
479 return false;
480 }
481 }
482 return (buffer.length() == 0) || (IsNonZeroDigit(buffer[0]) && IsNonZeroDigit(buffer[buffer.length()-1]));
483}
484#endif // needed for ICU only in debug mode
485
486double StrtodTrimmed(Vector<const char> trimmed, int exponent) {
487 DOUBLE_CONVERSION_ASSERT(trimmed.length() <= kMaxSignificantDecimalDigits);
488 DOUBLE_CONVERSION_ASSERT(AssertTrimmedDigits(trimmed));
489 double guess;
490 const bool is_correct = ComputeGuess(trimmed, exponent, &guess);
491 if (is_correct) {
492 return guess;
493 }
494 DiyFp upper_boundary = Double(guess).UpperBoundary();
495 int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
496 if (comparison < 0) {
497 return guess;
498 } else if (comparison > 0) {
499 return Double(guess).NextDouble();
500 } else if ((Double(guess).Significand() & 1) == 0) {
501 // Round towards even.
502 return guess;
503 } else {
504 return Double(guess).NextDouble();
505 }
506}
507
508double Strtod(Vector<const char> buffer, int exponent) {
509 char copy_buffer[kMaxSignificantDecimalDigits];
510 Vector<const char> trimmed;
511 int updated_exponent;
512 TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
513 &trimmed, &updated_exponent);
514 return StrtodTrimmed(trimmed, updated_exponent);
515}
516
517static float SanitizedDoubletof(double d) {
518 DOUBLE_CONVERSION_ASSERT(d >= 0.0);
519 // ASAN has a sanitize check that disallows casting doubles to floats if
520 // they are too big.
521 // https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks
522 // The behavior should be covered by IEEE 754, but some projects use this
523 // flag, so work around it.
524 float max_finite = 3.4028234663852885981170418348451692544e+38;
525 // The half-way point between the max-finite and infinity value.
526 // Since infinity has an even significand everything equal or greater than
527 // this value should become infinity.
528 double half_max_finite_infinity =
529 3.40282356779733661637539395458142568448e+38;
530 if (d >= max_finite) {
531 if (d >= half_max_finite_infinity) {
532 return Single::Infinity();
533 } else {
534 return max_finite;
535 }
536 } else {
537 return static_cast<float>(d);
538 }
539}
540
541float Strtof(Vector<const char> buffer, int exponent) {
542 char copy_buffer[kMaxSignificantDecimalDigits];
543 Vector<const char> trimmed;
544 int updated_exponent;
545 TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
546 &trimmed, &updated_exponent);
547 exponent = updated_exponent;
548
549 double double_guess;
550 bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
551
552 float float_guess = SanitizedDoubletof(double_guess);
553 if (float_guess == double_guess) {
554 // This shortcut triggers for integer values.
555 return float_guess;
556 }
557
558 // We must catch double-rounding. Say the double has been rounded up, and is
559 // now a boundary of a float, and rounds up again. This is why we have to
560 // look at previous too.
561 // Example (in decimal numbers):
562 // input: 12349
563 // high-precision (4 digits): 1235
564 // low-precision (3 digits):
565 // when read from input: 123
566 // when rounded from high precision: 124.
567 // To do this we simply look at the neigbors of the correct result and see
568 // if they would round to the same float. If the guess is not correct we have
569 // to look at four values (since two different doubles could be the correct
570 // double).
571
572 double double_next = Double(double_guess).NextDouble();
573 double double_previous = Double(double_guess).PreviousDouble();
574
575 float f1 = SanitizedDoubletof(double_previous);
576 float f2 = float_guess;
577 float f3 = SanitizedDoubletof(double_next);
578 float f4;
579 if (is_correct) {
580 f4 = f3;
581 } else {
582 double double_next2 = Double(double_next).NextDouble();
583 f4 = SanitizedDoubletof(double_next2);
584 }
585 (void) f2; // Mark variable as used.
586 DOUBLE_CONVERSION_ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
587
588 // If the guess doesn't lie near a single-precision boundary we can simply
589 // return its float-value.
590 if (f1 == f4) {
591 return float_guess;
592 }
593
594 DOUBLE_CONVERSION_ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
595 (f1 == f2 && f2 != f3 && f3 == f4) ||
596 (f1 == f2 && f2 == f3 && f3 != f4));
597
598 // guess and next are the two possible candidates (in the same way that
599 // double_guess was the lower candidate for a double-precision guess).
600 float guess = f1;
601 float next = f4;
602 DiyFp upper_boundary;
603 if (guess == 0.0f) {
604 float min_float = 1e-45f;
605 upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp();
606 } else {
607 upper_boundary = Single(guess).UpperBoundary();
608 }
609 int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
610 if (comparison < 0) {
611 return guess;
612 } else if (comparison > 0) {
613 return next;
614 } else if ((Single(guess).Significand() & 1) == 0) {
615 // Round towards even.
616 return guess;
617 } else {
618 return next;
619 }
620}
621
622} // namespace double_conversion
623
624// ICU PATCH: Close ICU namespace
625U_NAMESPACE_END
626#endif // ICU PATCH: close #if !UCONFIG_NO_FORMATTING
627