Coverage Report

Created: 2026-07-16 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/strings/internal/charconv_parse.cc
Line
Count
Source
1
// Copyright 2018 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include "absl/strings/internal/charconv_parse.h"
16
17
#include <cassert>
18
#include <cstddef>
19
#include <cstdint>
20
#include <limits>
21
22
#include "absl/strings/charconv.h"
23
#include "absl/strings/internal/memutil.h"
24
25
namespace absl {
26
ABSL_NAMESPACE_BEGIN
27
namespace {
28
29
// ParseFloat<10> will read the first 19 significant digits of the mantissa.
30
// This number was chosen for multiple reasons.
31
//
32
// (a) First, for whatever integer type we choose to represent the mantissa, we
33
// want to choose the largest possible number of decimal digits for that integer
34
// type.  We are using uint64_t, which can express any 19-digit unsigned
35
// integer.
36
//
37
// (b) Second, we need to parse enough digits that the binary value of any
38
// mantissa we capture has more bits of resolution than the mantissa
39
// representation in the target float.  Our algorithm requires at least 3 bits
40
// of headway, but 19 decimal digits give a little more than that.
41
//
42
// The following static assertions verify the above comments:
43
constexpr int kDecimalMantissaDigitsMax = 19;
44
45
static_assert(std::numeric_limits<uint64_t>::digits10 ==
46
                  kDecimalMantissaDigitsMax,
47
              "(a) above");
48
49
// IEEE doubles, which we assume in Abseil, have 53 binary bits of mantissa.
50
static_assert(std::numeric_limits<double>::is_iec559, "IEEE double assumed");
51
static_assert(std::numeric_limits<double>::radix == 2, "IEEE double fact");
52
static_assert(std::numeric_limits<double>::digits == 53, "IEEE double fact");
53
54
// The lowest valued 19-digit decimal mantissa we can read still contains
55
// sufficient information to reconstruct a binary mantissa.
56
static_assert(1000000000000000000u > (uint64_t{1} << (53 + 3)), "(b) above");
57
58
// ParseFloat<16> will read the first 15 significant digits of the mantissa.
59
//
60
// Because a base-16-to-base-2 conversion can be done exactly, we do not need
61
// to maximize the number of scanned hex digits to improve our conversion.  What
62
// is required is to scan two more bits than the mantissa can represent, so that
63
// we always round correctly.
64
//
65
// (One extra bit does not suffice to perform correct rounding, since a number
66
// exactly halfway between two representable floats has unique rounding rules,
67
// so we need to differentiate between a "halfway between" number and a "closer
68
// to the larger value" number.)
69
constexpr int kHexadecimalMantissaDigitsMax = 15;
70
71
// The minimum number of significant bits that will be read from
72
// kHexadecimalMantissaDigitsMax hex digits.  We must subtract by three, since
73
// the most significant digit can be a "1", which only contributes a single
74
// significant bit.
75
constexpr int kGuaranteedHexadecimalMantissaBitPrecision =
76
    4 * kHexadecimalMantissaDigitsMax - 3;
77
78
static_assert(kGuaranteedHexadecimalMantissaBitPrecision >
79
                  std::numeric_limits<double>::digits + 2,
80
              "kHexadecimalMantissaDigitsMax too small");
81
82
// We also impose a limit on the number of significant digits we will read from
83
// an exponent, to avoid having to deal with integer overflow.  We use 9 for
84
// this purpose.
85
//
86
// If we read a 9 digit exponent, the end result of the conversion will
87
// necessarily be infinity or zero, depending on the sign of the exponent.
88
// Therefore we can just drop extra digits on the floor without any extra
89
// logic.
90
constexpr int kDecimalExponentDigitsMax = 9;
91
static_assert(std::numeric_limits<int>::digits10 >= kDecimalExponentDigitsMax,
92
              "int type too small");
93
94
// To avoid incredibly large inputs causing integer overflow for our exponent,
95
// we impose an arbitrary but very large limit on the number of significant
96
// digits we will accept.  The implementation refuses to match a string with
97
// more consecutive significant mantissa digits than this.
98
constexpr int kDecimalDigitLimit = 50000000;
99
100
// Corresponding limit for hexadecimal digit inputs.  This is one fourth the
101
// amount of kDecimalDigitLimit, since each dropped hexadecimal digit requires
102
// a binary exponent adjustment of 4.
103
constexpr int kHexadecimalDigitLimit = kDecimalDigitLimit / 4;
104
105
// The largest exponent we can read is 999999999 (per
106
// kDecimalExponentDigitsMax), and the largest exponent adjustment we can get
107
// from dropped mantissa digits is 2 * kDecimalDigitLimit, and the sum of these
108
// comfortably fits in an integer.
109
//
110
// We count kDecimalDigitLimit twice because there are independent limits for
111
// numbers before and after the decimal point.  (In the case where there are no
112
// significant digits before the decimal point, there are independent limits for
113
// post-decimal-point leading zeroes and for significant digits.)
114
static_assert(999999999 + 2 * kDecimalDigitLimit <
115
                  std::numeric_limits<int>::max(),
116
              "int type too small");
117
static_assert(999999999 + 2 * (4 * kHexadecimalDigitLimit) <
118
                  std::numeric_limits<int>::max(),
119
              "int type too small");
120
121
// Returns true if the provided bitfield allows parsing an exponent value
122
// (e.g., "1.5e100").
123
0
bool AllowExponent(chars_format flags) {
124
0
  bool fixed = (flags & chars_format::fixed) == chars_format::fixed;
125
0
  bool scientific =
126
0
      (flags & chars_format::scientific) == chars_format::scientific;
127
0
  return scientific || !fixed;
128
0
}
129
130
// Returns true if the provided bitfield requires an exponent value be present.
131
0
bool RequireExponent(chars_format flags) {
132
0
  bool fixed = (flags & chars_format::fixed) == chars_format::fixed;
133
0
  bool scientific =
134
0
      (flags & chars_format::scientific) == chars_format::scientific;
135
0
  return scientific && !fixed;
136
0
}
137
138
const int8_t kAsciiToInt[256] = {
139
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
140
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
141
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0,  1,  2,  3,  4,  5,  6,  7,  8,
142
    9,  -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1,
143
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
144
    -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
145
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
146
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
147
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
148
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
149
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
150
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
151
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
152
    -1, -1, -1, -1, -1, -1, -1, -1, -1};
153
154
// Returns true if `ch` is a digit in the given base
155
template <int base>
156
bool IsDigit(char ch);
157
158
// Converts a valid `ch` to its digit value in the given base.
159
template <int base>
160
unsigned ToDigit(char ch);
161
162
// Returns true if `ch` is the exponent delimiter for the given base.
163
template <int base>
164
bool IsExponentCharacter(char ch);
165
166
// Returns the maximum number of significant digits we will read for a float
167
// in the given base.
168
template <int base>
169
constexpr int MantissaDigitsMax();
170
171
// Returns the largest consecutive run of digits we will accept when parsing a
172
// number in the given base.
173
template <int base>
174
constexpr int DigitLimit();
175
176
// Returns the amount the exponent must be adjusted by for each dropped digit.
177
// (For decimal this is 1, since the digits are in base 10 and the exponent base
178
// is also 10, but for hexadecimal this is 4, since the digits are base 16 but
179
// the exponent base is 2.)
180
template <int base>
181
constexpr int DigitMagnitude();
182
183
template <>
184
0
bool IsDigit<10>(char ch) {
185
0
  return ch >= '0' && ch <= '9';
186
0
}
187
template <>
188
0
bool IsDigit<16>(char ch) {
189
0
  return kAsciiToInt[static_cast<unsigned char>(ch)] >= 0;
190
0
}
191
192
template <>
193
0
unsigned ToDigit<10>(char ch) {
194
0
  return static_cast<unsigned>(ch - '0');
195
0
}
196
template <>
197
0
unsigned ToDigit<16>(char ch) {
198
0
  return static_cast<unsigned>(kAsciiToInt[static_cast<unsigned char>(ch)]);
199
0
}
200
201
template <>
202
0
bool IsExponentCharacter<10>(char ch) {
203
0
  return ch == 'e' || ch == 'E';
204
0
}
205
206
template <>
207
0
bool IsExponentCharacter<16>(char ch) {
208
0
  return ch == 'p' || ch == 'P';
209
0
}
210
211
template <>
212
0
constexpr int MantissaDigitsMax<10>() {
213
0
  return kDecimalMantissaDigitsMax;
214
0
}
215
template <>
216
0
constexpr int MantissaDigitsMax<16>() {
217
0
  return kHexadecimalMantissaDigitsMax;
218
0
}
219
220
template <>
221
0
constexpr int DigitLimit<10>() {
222
0
  return kDecimalDigitLimit;
223
0
}
224
template <>
225
0
constexpr int DigitLimit<16>() {
226
0
  return kHexadecimalDigitLimit;
227
0
}
228
229
template <>
230
0
constexpr int DigitMagnitude<10>() {
231
0
  return 1;
232
0
}
233
template <>
234
0
constexpr int DigitMagnitude<16>() {
235
0
  return 4;
236
0
}
237
238
// Reads decimal digits from [begin, end) into *out.  Returns the number of
239
// digits consumed.
240
//
241
// After max_digits has been read, keeps consuming characters, but no longer
242
// adjusts *out.  If a nonzero digit is dropped this way, *dropped_nonzero_digit
243
// is set; otherwise, it is left unmodified.
244
//
245
// If no digits are matched, returns 0 and leaves *out unchanged.
246
//
247
// ConsumeDigits does not protect against overflow on *out; max_digits must
248
// be chosen with respect to type T to avoid the possibility of overflow.
249
template <int base, typename T>
250
ptrdiff_t ConsumeDigits(const char* begin, const char* end,
251
                        ptrdiff_t max_digits, T* out,
252
0
                        bool* dropped_nonzero_digit) {
253
0
  if (base == 10) {
254
0
    assert(max_digits <= std::numeric_limits<T>::digits10);
255
0
  } else if (base == 16) {
256
0
    assert(max_digits * 4 <= std::numeric_limits<T>::digits);
257
0
  }
258
0
  const char* const original_begin = begin;
259
260
  // Skip leading zeros, but only if *out is zero.
261
  // They don't cause an overflow so we don't have to count them for
262
  // `max_digits`.
263
0
  while (!*out && end != begin && *begin == '0') ++begin;
264
265
0
  T accumulator = *out;
266
0
  const char* significant_digits_end =
267
0
      (end - begin > max_digits) ? begin + max_digits : end;
268
0
  while (begin < significant_digits_end && IsDigit<base>(*begin)) {
269
    // Do not guard against *out overflow; max_digits was chosen to avoid this.
270
    // Do assert against it, to detect problems in debug builds.
271
0
    auto digit = static_cast<T>(ToDigit<base>(*begin));
272
0
    assert(accumulator * base >= accumulator);
273
0
    accumulator *= base;
274
0
    assert(accumulator + digit >= accumulator);
275
0
    accumulator += digit;
276
0
    ++begin;
277
0
  }
278
0
  bool dropped_nonzero = false;
279
0
  while (begin < end && IsDigit<base>(*begin)) {
280
0
    dropped_nonzero = dropped_nonzero || (*begin != '0');
281
0
    ++begin;
282
0
  }
283
0
  if (dropped_nonzero && dropped_nonzero_digit != nullptr) {
284
0
    *dropped_nonzero_digit = true;
285
0
  }
286
0
  *out = accumulator;
287
0
  return begin - original_begin;
288
0
}
Unexecuted instantiation: charconv_parse.cc:long absl::(anonymous namespace)::ConsumeDigits<10, unsigned long>(char const*, char const*, long, unsigned long*, bool*)
Unexecuted instantiation: charconv_parse.cc:long absl::(anonymous namespace)::ConsumeDigits<10, int>(char const*, char const*, long, int*, bool*)
Unexecuted instantiation: charconv_parse.cc:long absl::(anonymous namespace)::ConsumeDigits<16, unsigned long>(char const*, char const*, long, unsigned long*, bool*)
289
290
// Returns true if `v` is one of the chars allowed inside parentheses following
291
// a NaN.
292
0
bool IsNanChar(char v) {
293
0
  return (v == '_') || (v >= '0' && v <= '9') || (v >= 'a' && v <= 'z') ||
294
0
         (v >= 'A' && v <= 'Z');
295
0
}
296
297
// Checks the range [begin, end) for a strtod()-formatted infinity or NaN.  If
298
// one is found, sets `out` appropriately and returns true.
299
bool ParseInfinityOrNan(const char* begin, const char* end,
300
0
                        strings_internal::ParsedFloat* out) {
301
0
  if (end - begin < 3) {
302
0
    return false;
303
0
  }
304
0
  switch (*begin) {
305
0
    case 'i':
306
0
    case 'I': {
307
      // An infinity string consists of the characters "inf" or "infinity",
308
      // case insensitive.
309
0
      if (strings_internal::memcasecmp(begin + 1, "nf", 2) != 0) {
310
0
        return false;
311
0
      }
312
0
      out->type = strings_internal::FloatType::kInfinity;
313
0
      if (end - begin >= 8 &&
314
0
          strings_internal::memcasecmp(begin + 3, "inity", 5) == 0) {
315
0
        out->end = begin + 8;
316
0
      } else {
317
0
        out->end = begin + 3;
318
0
      }
319
0
      return true;
320
0
    }
321
0
    case 'n':
322
0
    case 'N': {
323
      // A NaN consists of the characters "nan", case insensitive, optionally
324
      // followed by a parenthesized sequence of zero or more alphanumeric
325
      // characters and/or underscores.
326
0
      if (strings_internal::memcasecmp(begin + 1, "an", 2) != 0) {
327
0
        return false;
328
0
      }
329
0
      out->type = strings_internal::FloatType::kNan;
330
0
      out->end = begin + 3;
331
      // NaN is allowed to be followed by a parenthesized string, consisting of
332
      // only the characters [a-zA-Z0-9_].  Match that if it's present.
333
0
      begin += 3;
334
0
      if (begin < end && *begin == '(') {
335
0
        const char* nan_begin = begin + 1;
336
0
        while (nan_begin < end && IsNanChar(*nan_begin)) {
337
0
          ++nan_begin;
338
0
        }
339
0
        if (nan_begin < end && *nan_begin == ')') {
340
          // We found an extra NaN specifier range
341
0
          out->subrange_begin = begin + 1;
342
0
          out->subrange_end = nan_begin;
343
0
          out->end = nan_begin + 1;
344
0
        }
345
0
      }
346
0
      return true;
347
0
    }
348
0
    default:
349
0
      return false;
350
0
  }
351
0
}
352
}  // namespace
353
354
namespace strings_internal {
355
356
template <int base>
357
strings_internal::ParsedFloat ParseFloat(const char* begin, const char* end,
358
0
                                         chars_format format_flags) {
359
0
  strings_internal::ParsedFloat result;
360
361
  // Exit early if we're given an empty range.
362
0
  if (begin == end) return result;
363
364
  // Handle the infinity and NaN cases.
365
0
  if (ParseInfinityOrNan(begin, end, &result)) {
366
0
    return result;
367
0
  }
368
369
0
  const char* const mantissa_begin = begin;
370
0
  while (begin < end && *begin == '0') {
371
0
    ++begin;  // skip leading zeros
372
0
  }
373
0
  uint64_t mantissa = 0;
374
375
0
  ptrdiff_t exponent_adjustment = 0;
376
0
  bool mantissa_is_inexact = false;
377
0
  ptrdiff_t pre_decimal_digits = ConsumeDigits<base>(
378
0
      begin, end, MantissaDigitsMax<base>(), &mantissa, &mantissa_is_inexact);
379
0
  begin += pre_decimal_digits;
380
0
  ptrdiff_t digits_left;
381
0
  if (pre_decimal_digits >= DigitLimit<base>()) {
382
    // refuse to parse pathological inputs
383
0
    return result;
384
0
  } else if (pre_decimal_digits > MantissaDigitsMax<base>()) {
385
    // We dropped some non-fraction digits on the floor.  Adjust our exponent
386
    // to compensate.
387
0
    exponent_adjustment = pre_decimal_digits - MantissaDigitsMax<base>();
388
0
    digits_left = 0;
389
0
  } else {
390
0
    digits_left = MantissaDigitsMax<base>() - pre_decimal_digits;
391
0
  }
392
0
  if (begin < end && *begin == '.') {
393
0
    ++begin;
394
0
    if (mantissa == 0) {
395
      // If we haven't seen any nonzero digits yet, keep skipping zeros.  We
396
      // have to adjust the exponent to reflect the changed place value.
397
0
      const char* begin_zeros = begin;
398
0
      while (begin < end && *begin == '0') {
399
0
        ++begin;
400
0
      }
401
0
      ptrdiff_t zeros_skipped = begin - begin_zeros;
402
0
      if (zeros_skipped >= DigitLimit<base>()) {
403
        // refuse to parse pathological inputs
404
0
        return result;
405
0
      }
406
0
      exponent_adjustment -= zeros_skipped;
407
0
    }
408
0
    ptrdiff_t post_decimal_digits = ConsumeDigits<base>(
409
0
        begin, end, digits_left, &mantissa, &mantissa_is_inexact);
410
0
    begin += post_decimal_digits;
411
412
    // Since `mantissa` is an integer, each significant digit we read after
413
    // the decimal point requires an adjustment to the exponent. "1.23e0" will
414
    // be stored as `mantissa` == 123 and `exponent` == -2 (that is,
415
    // "123e-2").
416
0
    if (post_decimal_digits >= DigitLimit<base>()) {
417
      // refuse to parse pathological inputs
418
0
      return result;
419
0
    } else if (post_decimal_digits > digits_left) {
420
0
      exponent_adjustment -= digits_left;
421
0
    } else {
422
0
      exponent_adjustment -= post_decimal_digits;
423
0
    }
424
0
  }
425
  // If we've found no mantissa whatsoever, this isn't a number.
426
0
  if (mantissa_begin == begin) {
427
0
    return result;
428
0
  }
429
  // A bare "." doesn't count as a mantissa either.
430
0
  if (begin - mantissa_begin == 1 && *mantissa_begin == '.') {
431
0
    return result;
432
0
  }
433
434
0
  if (mantissa_is_inexact) {
435
    // We dropped significant digits on the floor.  Handle this appropriately.
436
0
    if (base == 10) {
437
      // If we truncated significant decimal digits, store the full range of the
438
      // mantissa for future big integer math for exact rounding.
439
0
      result.subrange_begin = mantissa_begin;
440
0
      result.subrange_end = begin;
441
0
    } else if (base == 16) {
442
      // If we truncated hex digits, reflect this fact by setting the low
443
      // ("sticky") bit.  This allows for correct rounding in all cases.
444
0
      mantissa |= 1;
445
0
    }
446
0
  }
447
0
  result.mantissa = mantissa;
448
449
0
  const char* const exponent_begin = begin;
450
0
  result.literal_exponent = 0;
451
0
  bool found_exponent = false;
452
0
  if (AllowExponent(format_flags) && begin < end &&
453
0
      IsExponentCharacter<base>(*begin)) {
454
0
    bool negative_exponent = false;
455
0
    ++begin;
456
0
    if (begin < end && *begin == '-') {
457
0
      negative_exponent = true;
458
0
      ++begin;
459
0
    } else if (begin < end && *begin == '+') {
460
0
      ++begin;
461
0
    }
462
0
    const char* const exponent_digits_begin = begin;
463
    // Exponent is always expressed in decimal, even for hexadecimal floats.
464
0
    begin += ConsumeDigits<10>(begin, end, kDecimalExponentDigitsMax,
465
0
                               &result.literal_exponent, nullptr);
466
0
    if (begin == exponent_digits_begin) {
467
      // there were no digits where we expected an exponent.  We failed to read
468
      // an exponent and should not consume the 'e' after all.  Rewind 'begin'.
469
0
      found_exponent = false;
470
0
      begin = exponent_begin;
471
0
    } else {
472
0
      found_exponent = true;
473
0
      if (negative_exponent) {
474
0
        result.literal_exponent = -result.literal_exponent;
475
0
      }
476
0
    }
477
0
  }
478
479
0
  if (!found_exponent && RequireExponent(format_flags)) {
480
    // Provided flags required an exponent, but none was found.  This results
481
    // in a failure to scan.
482
0
    return result;
483
0
  }
484
485
0
  if (result.mantissa > 0) {
486
0
    const ptrdiff_t exponent = result.literal_exponent +
487
0
                               (DigitMagnitude<base>() * exponent_adjustment);
488
489
0
    if (exponent < (std::numeric_limits<int>::min)() ||
490
0
        exponent > (std::numeric_limits<int>::max)()) {
491
      // We cannot store the exponent in int. Fail by returning a result with
492
      // end default-initialized to nullptr.
493
0
      return result;
494
0
    }
495
496
0
    result.exponent = static_cast<int>(exponent);
497
0
  } else {
498
0
    result.exponent = 0;
499
0
  }
500
0
  result.end = begin;
501
502
  // Success!
503
0
  result.type = strings_internal::FloatType::kNumber;
504
505
0
  return result;
506
0
}
Unexecuted instantiation: absl::strings_internal::ParsedFloat absl::strings_internal::ParseFloat<10>(char const*, char const*, absl::chars_format)
Unexecuted instantiation: absl::strings_internal::ParsedFloat absl::strings_internal::ParseFloat<16>(char const*, char const*, absl::chars_format)
507
508
template ParsedFloat ParseFloat<10>(const char* begin, const char* end,
509
                                    chars_format format_flags);
510
template ParsedFloat ParseFloat<16>(const char* begin, const char* end,
511
                                    chars_format format_flags);
512
513
}  // namespace strings_internal
514
ABSL_NAMESPACE_END
515
}  // namespace absl