Coverage Report

Created: 2023-06-07 06:45

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