Coverage Report

Created: 2025-09-05 07:16

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