File: double-conversion.cc

package info (click to toggle)
webkit2gtk 2.48.3-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 429,620 kB
  • sloc: cpp: 3,696,936; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,276; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (686 lines) | stat: -rw-r--r-- 24,552 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// Copyright 2010 the V8 project authors. All rights reserved.
// Copyright (C) 2011-2024 Apple Inc. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"

#include <climits>
#include <locale>
#include <cmath>

#include <wtf/dtoa/double-conversion.h>

#include <wtf/dtoa/bignum-dtoa.h>
#include <wtf/dtoa/fast-dtoa.h>
#include <wtf/dtoa/fixed-dtoa.h>
#include <wtf/dtoa/ieee.h>
#include <wtf/dtoa/strtod.h>
#include <wtf/dtoa/utils.h>

#include <wtf/ASCIICType.h>


namespace WTF {
namespace double_conversion {

const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
  constexpr int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
  static constexpr DoubleToStringConverter converter(flags, "Infinity", "NaN", 'e', default_decimal_in_shortest_low, default_decimal_in_shortest_high, 6, 0);
  return converter;
}

const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverterWithTrailingPoint() {
  constexpr int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN | EMIT_TRAILING_DECIMAL_POINT;
  static constexpr DoubleToStringConverter converter(flags, "Infinity", "NaN", 'e', default_decimal_in_shortest_low, default_decimal_in_shortest_high, 6, 0);
  return converter;
}

const DoubleToStringConverter& DoubleToStringConverter::CSSConverter() {
  constexpr int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
  static constexpr DoubleToStringConverter converter(flags, "infinity", "NaN", 'e', default_decimal_in_shortest_low, default_decimal_in_shortest_high, 6, 0);
  return converter;
}


bool DoubleToStringConverter::HandleSpecialValues(
    double value,
    StringBuilder* result_builder) const {
  Double double_inspect(value);
  if (double_inspect.IsInfinite()) {
    if (infinity_symbol_ == nullptr) return false;
    if (value < 0) {
      result_builder->AddCharacter('-');
    }
    result_builder->AddString(infinity_symbol_);
    return true;
  }
  if (double_inspect.IsNan()) {
    if (nan_symbol_ == nullptr) return false;
    result_builder->AddString(nan_symbol_);
    return true;
  }
  return false;
}


void DoubleToStringConverter::CreateExponentialRepresentation(
    std::span<const char> decimal_digits,
    int exponent,
    StringBuilder* result_builder) const {
  ASSERT_WITH_SECURITY_IMPLICATION(!decimal_digits.empty());
  result_builder->AddCharacter(decimal_digits[0]);
  if (decimal_digits.size() > 1) {
    result_builder->AddCharacter('.');
    result_builder->AddSubstring(&decimal_digits[1], decimal_digits.size() - 1);
  }
  result_builder->AddCharacter(exponent_character_);
  if (exponent < 0) {
    result_builder->AddCharacter('-');
    exponent = -exponent;
  } else {
    if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
      result_builder->AddCharacter('+');
    }
  }
  if (exponent == 0) {
    result_builder->AddCharacter('0');
    return;
  }
  ASSERT_WITH_SECURITY_IMPLICATION(exponent < 1e4);
  constexpr int kMaxExponentLength = 5;
  std::array<char, kMaxExponentLength + 1> buffer;
  buffer[kMaxExponentLength] = '\0';
  size_t first_char_pos = kMaxExponentLength;
  while (exponent > 0 && first_char_pos > 0) {
    buffer[--first_char_pos] = '0' + (exponent % 10);
    exponent /= 10;
  }
  result_builder->AddSubstring(&buffer[first_char_pos],
                               kMaxExponentLength - first_char_pos);
}


void DoubleToStringConverter::CreateDecimalRepresentation(
    std::span<const char> decimal_digits,
    int decimal_point,
    int digits_after_point,
    StringBuilder* result_builder) const {
  // Create a representation that is padded with zeros if needed.
  if (decimal_point <= 0) {
      // "0.00000decimal_rep" or "0.000decimal_rep00".
    result_builder->AddCharacter('0');
    if (digits_after_point > 0) {
      result_builder->AddCharacter('.');
      result_builder->AddPadding('0', -decimal_point);
      ASSERT_WITH_SECURITY_IMPLICATION(static_cast<int>(decimal_digits.size()) <= digits_after_point - (-decimal_point));
      result_builder->AddSubstring(decimal_digits.data(), decimal_digits.size());
      int remaining_digits = digits_after_point - (-decimal_point) - decimal_digits.size();
      result_builder->AddPadding('0', remaining_digits);
    }
  } else if (decimal_point >= static_cast<int>(decimal_digits.size())) {
    // "decimal_rep0000.00000" or "decimal_rep.0000".
    result_builder->AddSubstring(decimal_digits.data(), decimal_digits.size());
    result_builder->AddPadding('0', decimal_point - decimal_digits.size());
    if (digits_after_point > 0) {
      result_builder->AddCharacter('.');
      result_builder->AddPadding('0', digits_after_point);
    }
  } else {
    // "decima.l_rep000".
    ASSERT_WITH_SECURITY_IMPLICATION(digits_after_point > 0);
    result_builder->AddSubstring(decimal_digits.data(), decimal_point);
    result_builder->AddCharacter('.');
    ASSERT_WITH_SECURITY_IMPLICATION(static_cast<int>(decimal_digits.size()) - decimal_point <= digits_after_point);
    result_builder->AddSubstring(&decimal_digits[decimal_point],
                                 decimal_digits.size() - decimal_point);
    int remaining_digits = digits_after_point - (decimal_digits.size() - decimal_point);
    result_builder->AddPadding('0', remaining_digits);
  }
  if (digits_after_point == 0) {
    if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
      result_builder->AddCharacter('.');
    }
    if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
      result_builder->AddCharacter('0');
    }
  }
}


bool DoubleToStringConverter::ToShortestIeeeNumber(
    double value,
    StringBuilder* result_builder,
    DoubleToStringConverter::DtoaMode mode) const {
  ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
  if (Double(value).IsSpecial()) {
    return HandleSpecialValues(value, result_builder);
  }

  int decimal_point;
  bool sign;
  constexpr size_t kDecimalRepCapacity = kBase10MaximalLength + 1;
  std::array<char, kDecimalRepCapacity> decimal_rep;
  int decimal_rep_length;

  DoubleToAscii(value, mode, 0, std::span<char> { decimal_rep }, sign, decimal_rep_length, decimal_point);

  bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
  if (sign && (value != 0.0 || !unique_zero)) {
    result_builder->AddCharacter('-');
  }

  int exponent = decimal_point - 1;
  if (validShortestRepresentation(exponent, decimal_in_shortest_low_, decimal_in_shortest_high_)) {
    CreateDecimalRepresentation(std::span<const char> { decimal_rep }.first(decimal_rep_length),
                                decimal_point,
                                Max(0, decimal_rep_length - decimal_point),
                                result_builder);
  } else {
    CreateExponentialRepresentation(std::span<const char> { decimal_rep }.first(decimal_rep_length), exponent,
                                    result_builder);
  }
  return true;
}

bool DoubleToStringConverter::ToFixedInternal(double value,
                                              int requested_digits,
                                              std::span<char> buffer,
                                              StringBuilder* result_builder) const {
  // Find a sufficiently precise decimal representation of n.
  int decimal_point;
  bool sign;
  int decimal_rep_length;
  DoubleToAscii(value, FIXED, requested_digits, buffer, sign, decimal_rep_length, decimal_point);

  bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
  if (sign && (value != 0.0 || !unique_zero)) {
    result_builder->AddCharacter('-');
  }

  CreateDecimalRepresentation(std::span<const char> { buffer }.first(decimal_rep_length), decimal_point,
                              requested_digits, result_builder);
  return true;
}


bool DoubleToStringConverter::ToFixed(double value,
                                      int requested_digits,
                                      StringBuilder* result_builder) const {
  static_assert(kMaxFixedDigitsBeforePoint == 21);
  const double kFirstNonFixed = 1e21;

  if (Double(value).IsSpecial()) {
    return HandleSpecialValues(value, result_builder);
  }

  if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
  if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;

  // Add space for the '\0' byte.
  constexpr size_t kDecimalRepCapacity =
      kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
  std::array<char, kDecimalRepCapacity> decimal_rep;
  return ToFixedInternal(value, requested_digits, std::span<char> { decimal_rep }, result_builder);
}

bool DoubleToStringConverter::ToFixedUncapped(double value,
                                              int requested_digits,
                                              StringBuilder* result_builder) const {
  // Max double is 1e308, so we could have 310 digits including a negative sign.
  const int kMaxPossibleDigitsBeforePoint = 310;

  if (Double(value).IsSpecial()) {
    return HandleSpecialValues(value, result_builder);
  }

  if (requested_digits > kMaxFixedDigitsAfterPoint) return false;

  // Add space for the '\0' byte.
  constexpr size_t kDecimalRepCapacity =
      kMaxPossibleDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
  std::array<char, kDecimalRepCapacity> decimal_rep;
  return ToFixedInternal(value, requested_digits, std::span<char> { decimal_rep }, result_builder);
}


bool DoubleToStringConverter::ToExponential(
    double value,
    int requested_digits,
    StringBuilder* result_builder) const {
  if (Double(value).IsSpecial()) {
    return HandleSpecialValues(value, result_builder);
  }

  if (requested_digits < -1) return false;
  if (requested_digits > kMaxExponentialDigits) return false;

  int decimal_point;
  bool sign;
  // Add space for digit before the decimal point and the '\0' character.
  constexpr size_t kDecimalRepCapacity = kMaxExponentialDigits + 2;
  static_assert(kDecimalRepCapacity > kBase10MaximalLength);
  std::array<char, kDecimalRepCapacity> decimal_rep;
  int decimal_rep_length;

  if (requested_digits == -1) {
    DoubleToAscii(value, SHORTEST, 0, std::span<char> { decimal_rep }, sign, decimal_rep_length, decimal_point);
  } else {
    DoubleToAscii(value, PRECISION, requested_digits + 1, std::span<char> { decimal_rep }, sign, decimal_rep_length, decimal_point);
    ASSERT_WITH_SECURITY_IMPLICATION(decimal_rep_length <= requested_digits + 1);

    if (decimal_rep_length < requested_digits + 1) {
      for (int i = decimal_rep_length; i < requested_digits + 1; ++i)
        decimal_rep[i] = '0';
      decimal_rep_length = requested_digits + 1;
      decimal_rep[decimal_rep_length] = '\0';
    }
  }

  bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
  if (sign && (value != 0.0 || !unique_zero)) {
    result_builder->AddCharacter('-');
  }

  int exponent = decimal_point - 1;
  CreateExponentialRepresentation(std::span<const char> { decimal_rep }.first(decimal_rep_length),
                                  exponent,
                                  result_builder);
  return true;
}


bool DoubleToStringConverter::ToPrecision(double value,
                                          int precision,
                                          StringBuilder* result_builder) const {
  if (Double(value).IsSpecial()) {
    return HandleSpecialValues(value, result_builder);
  }

  if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
    return false;
  }

  // Find a sufficiently precise decimal representation of n.
  int decimal_point;
  bool sign;
  // Add one for the terminating null character.
  constexpr size_t kDecimalRepCapacity = kMaxPrecisionDigits + 1;
  std::array<char, kDecimalRepCapacity> decimal_rep;
  int decimal_rep_length;

  DoubleToAscii(value, PRECISION, precision, std::span<char> { decimal_rep }, sign, decimal_rep_length, decimal_point);
  ASSERT_WITH_SECURITY_IMPLICATION(decimal_rep_length <= precision);

  bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
  if (sign && (value != 0.0 || !unique_zero)) {
    result_builder->AddCharacter('-');
  }

  // The exponent if we print the number as x.xxeyyy. That is with the
  // decimal point after the first digit.
  int exponent = decimal_point - 1;

  int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
  if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
      (decimal_point - precision + extra_zero >
       max_trailing_padding_zeroes_in_precision_mode_)) {
    // Fill buffer to contain 'precision' digits.
    // Usually the buffer is already at the correct length, but 'DoubleToAscii'
    // is allowed to return less characters.
    for (int i = decimal_rep_length; i < precision; ++i) {
      decimal_rep[i] = '0';
    }

    CreateExponentialRepresentation(std::span<const char> { decimal_rep }.first(precision), exponent, result_builder);
  } else {
    CreateDecimalRepresentation(std::span<const char> { decimal_rep }.first(decimal_rep_length), decimal_point,
        Max(0, precision - decimal_point), result_builder);
  }
  return true;
}


static BignumDtoaMode DtoaToBignumDtoaMode(
    DoubleToStringConverter::DtoaMode dtoa_mode) {
  switch (dtoa_mode) {
    case DoubleToStringConverter::SHORTEST:  return BIGNUM_DTOA_SHORTEST;
    case DoubleToStringConverter::SHORTEST_SINGLE:
        return BIGNUM_DTOA_SHORTEST_SINGLE;
    case DoubleToStringConverter::FIXED:     return BIGNUM_DTOA_FIXED;
    case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
    default:
      UNREACHABLE();
  }
}


void DoubleToStringConverter::DoubleToAscii(double v,
                                            DtoaMode mode,
                                            int requested_digits,
                                            std::span<char> buffer,
                                            bool& sign,
                                            int& length,
                                            int& point) {
  BufferReference<char> bufferReference(buffer);
  ASSERT(!Double(v).IsSpecial());
  ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);

  if (Double(v).Sign() < 0) {
    sign = true;
    v = -v;
  } else {
    sign = false;
  }

  if (mode == PRECISION && requested_digits == 0) {
    bufferReference[0] = '\0';
    length = 0;
    return;
  }

  if (v == 0) {
    bufferReference[0] = '0';
    bufferReference[1] = '\0';
    length = 1;
    point = 1;
    return;
  }

  bool fast_worked;
  switch (mode) {
    case SHORTEST:
      fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, bufferReference, length, point);
      break;
    case SHORTEST_SINGLE:
      fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0, bufferReference, length, point);
      break;
    case FIXED:
      fast_worked = FastFixedDtoa(v, requested_digits, bufferReference, length, point);
      break;
    case PRECISION:
      fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits, bufferReference, length, point);
      break;
    default:
      fast_worked = false;
      UNREACHABLE();
  }
  if (fast_worked) return;

  // If the fast dtoa didn't succeed use the slower bignum version.
  BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
  BignumDtoa(v, bignum_mode, requested_digits, bufferReference, length, point);
  bufferReference[length] = '\0';
}

// Maximum number of significant digits in decimal representation.
// The longest possible double in decimal representation is
// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
// (768 digits). If we parse a number whose first digits are equal to a
// mean of 2 adjacent doubles (that could have up to 769 digits) the result
// must be rounded to the bigger one unless the tail consists of zeros, so
// we don't need to preserve all the digits.
const int kMaxSignificantDigits = 772;


static double SignedZero(bool sign) {
  return sign ? -0.0 : 0.0;
}


// Returns true, when the iterator is equal to end.
template<class Iterator>
static inline bool Advance(Iterator* it, Iterator& end) {
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
  ++(*it);
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
  return *it == end;
}

template <typename FloatingPointType>
inline FloatingPointType StringToFloatingPointType(BufferReference<const char> buffer, int exponent);

template <>
inline double StringToFloatingPointType<double>(BufferReference<const char> buffer, int exponent) {
  return Strtod(buffer, exponent);
}

template <>
inline float StringToFloatingPointType<float>(BufferReference<const char> buffer, int exponent) {
  return Strtof(buffer, exponent);
}

WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
template <typename FloatingPointType, class Iterator>
static FloatingPointType StringToIeee(
    Iterator input,
    size_t length,
    size_t* processed_characters_count) {
  static_assert(std::is_floating_point<FloatingPointType>::value, "Only floating point types are allowed.");

  Iterator current = input;
  Iterator end = input + length;

  *processed_characters_count = 0;

  // To make sure that iterator dereferencing is valid the following
  // convention is used:
  // 1. Each '++current' statement is followed by check for equality to 'end'.
  // 3. If 'current' becomes equal to 'end' the function returns or goes to
  // 'parsing_done'.
  // 4. 'current' is not dereferenced after the 'parsing_done' label.
  // 5. Code before 'parsing_done' may rely on 'current != end'.

  if (current == end) return 0.0;

  // The longest form of simplified number is: "-<significant digits>.1eXXX\0".
  constexpr int kBufferSize = kMaxSignificantDigits + 10;
  std::array<char, kBufferSize> buffer;  // NOLINT: size is known at compile time.
  int buffer_pos = 0;

  // Exponent will be adjusted if insignificant digits of the integer part
  // or insignificant leading zeros of the fractional part are dropped.
  int exponent = 0;
  int significant_digits = 0;
  int insignificant_digits = 0;
  bool nonzero_digit_dropped = false;

  bool sign = false;

  if (*current == '+' || *current == '-') {
    sign = (*current == '-');
    ++current;
    if (current == end) return 0.0;
  }

  bool leading_zero = false;
  if (*current == '0') {
    if (Advance(&current, end)) {
      *processed_characters_count = static_cast<size_t>(current - input);
      return SignedZero(sign);
    }

    leading_zero = true;

    // Ignore leading zeros in the integer part.
    while (*current == '0') {
      if (Advance(&current, end)) {
        *processed_characters_count = static_cast<size_t>(current - input);
        return SignedZero(sign);
      }
    }
  }

  // Copy significant digits of the integer part (if any) to the buffer.
  while (isASCIIDigit(*current)) {
    if (significant_digits < kMaxSignificantDigits) {
      ASSERT_WITH_SECURITY_IMPLICATION(buffer_pos < kBufferSize);
      buffer[buffer_pos++] = static_cast<char>(*current);
      significant_digits++;
    } else {
      insignificant_digits++;  // Move the digit into the exponential part.
      nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
    }
    if (Advance(&current, end)) goto parsing_done;
  }

  if (*current == '.') {
    if (Advance(&current, end)) {
      if (significant_digits == 0 && !leading_zero) {
        return 0.0;
      } else {
        goto parsing_done;
      }
    }

    if (significant_digits == 0) {
      // Integer part consists of 0 or is absent. Significant digits start after
      // leading zeros (if any).
      while (*current == '0') {
        if (Advance(&current, end)) {
          *processed_characters_count = static_cast<size_t>(current - input);
          return SignedZero(sign);
        }
        exponent--;  // Move this 0 into the exponent.
      }
    }

    // There is a fractional part.
    // We don't emit a '.', but adjust the exponent instead.
    while (isASCIIDigit(*current)) {
      if (significant_digits < kMaxSignificantDigits) {
        ASSERT_WITH_SECURITY_IMPLICATION(buffer_pos < kBufferSize);
        buffer[buffer_pos++] = static_cast<char>(*current);
        significant_digits++;
        exponent--;
      } else {
        // Ignore insignificant digits in the fractional part.
        nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
      }
      if (Advance(&current, end)) goto parsing_done;
    }
  }

  if (!leading_zero && exponent == 0 && significant_digits == 0) {
    // If leading_zeros is true then the string contains zeros.
    // If exponent < 0 then string was [+-]\.0*...
    // If significant_digits != 0 the string is not equal to 0.
    // Otherwise there are no digits in the string.
    return 0.0;
  }

  // Parse exponential part.
  if (*current == 'e' || *current == 'E') {
    ++current;
    if (current == end) {
      --current;
      goto parsing_done;
    }
    char exponen_sign = 0;
    if (*current == '+' || *current == '-') {
      exponen_sign = static_cast<char>(*current);
      ++current;
      if (current == end) {
        current -= 2;
        goto parsing_done;
      }
    }

    if (*current < '0' || *current > '9') {
      if (exponen_sign)
        --current;
      --current;
      goto parsing_done;
    }

    const int max_exponent = INT_MAX / 2;
    ASSERT_WITH_SECURITY_IMPLICATION(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
    int num = 0;
    do {
      // Check overflow.
      int digit = *current - '0';
      if (num >= max_exponent / 10
          && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
        num = max_exponent;
      } else {
        num = num * 10 + digit;
      }
      ++current;
    } while (current != end && isASCIIDigit(*current));

    exponent += (exponen_sign == '-' ? -num : num);
  }

  parsing_done:
  exponent += insignificant_digits;

  if (nonzero_digit_dropped) {
    buffer[buffer_pos++] = '1';
    exponent--;
  }

  ASSERT_WITH_SECURITY_IMPLICATION(buffer_pos < kBufferSize);
  buffer[buffer_pos] = '\0';

  auto converted = StringToFloatingPointType<FloatingPointType>(BufferReference<const char>(std::span { buffer }.first(buffer_pos)), exponent);
  *processed_characters_count = static_cast<size_t>(current - input);
  return sign? -converted: converted;
}
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END

double StringToDoubleConverter::StringToDouble(
    const char* buffer,
    size_t length,
    size_t* processed_characters_count) {
  return StringToIeee<double>(buffer, length, processed_characters_count);
}


double StringToDoubleConverter::StringToDouble(
    const uc16* buffer,
    size_t length,
    size_t* processed_characters_count) {
  return StringToIeee<double>(buffer, length, processed_characters_count);
}


float StringToDoubleConverter::StringToFloat(
    const char* buffer,
    size_t length,
    size_t* processed_characters_count) {
  return StringToIeee<float>(buffer, length, processed_characters_count);
}


float StringToDoubleConverter::StringToFloat(
    const uc16* buffer,
    size_t length,
    size_t* processed_characters_count) {
  return StringToIeee<float>(buffer, length, processed_characters_count);
}

}  // namespace double_conversion
}  // namespace WTF