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/numbers.cc
Line
Count
Source
1
// Copyright 2017 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
// This file contains string processing functions related to
16
// numeric values.
17
18
#include "absl/strings/numbers.h"
19
20
#include <algorithm>
21
#include <array>
22
#include <cassert>
23
#include <cfloat>  // for DBL_DIG and FLT_DIG
24
#include <clocale>  // for localeconv
25
#include <cmath>   // for HUGE_VAL
26
#include <cstdint>
27
#include <cstdio>
28
#include <cstdlib>
29
#include <cstring>
30
#include <iterator>
31
#include <limits>
32
#include <system_error>  // NOLINT(build/c++11)
33
#include <utility>
34
35
#include "absl/base/attributes.h"
36
#include "absl/base/config.h"
37
#include "absl/base/internal/endian.h"
38
#include "absl/base/internal/raw_logging.h"
39
#include "absl/base/macros.h"
40
#include "absl/base/nullability.h"
41
#include "absl/base/optimization.h"
42
#include "absl/numeric/bits.h"
43
#include "absl/numeric/int128.h"
44
#include "absl/strings/ascii.h"
45
#include "absl/strings/charconv.h"
46
#include "absl/strings/match.h"
47
#include "absl/strings/string_view.h"
48
49
namespace absl {
50
ABSL_NAMESPACE_BEGIN
51
52
0
bool SimpleAtof(absl::string_view str, float* absl_nonnull out) {
53
0
  *out = 0.0;
54
0
  str = StripAsciiWhitespace(str);
55
0
  if (str.empty()) {
56
    // absl::from_chars doesn't accept empty strings.
57
0
    return false;
58
0
  }
59
  // std::from_chars doesn't accept an initial +, but SimpleAtof does, so if one
60
  // is present, skip it, while avoiding accepting "+-0" as valid.
61
0
  if (str[0] == '+') {
62
0
    str.remove_prefix(1);
63
0
    if (str.empty() || str[0] == '-') {
64
0
      return false;
65
0
    }
66
0
  }
67
0
  auto result = absl::from_chars(str.data(), str.data() + str.size(), *out);
68
0
  if (result.ec == std::errc::invalid_argument) {
69
0
    return false;
70
0
  }
71
0
  if (result.ptr != str.data() + str.size()) {
72
    // not all non-whitespace characters consumed
73
0
    return false;
74
0
  }
75
  // from_chars() with DR 3081's current wording will return max() on
76
  // overflow.  SimpleAtof returns infinity instead.
77
0
  if (result.ec == std::errc::result_out_of_range) {
78
0
    if (*out > 1.0) {
79
0
      *out = std::numeric_limits<float>::infinity();
80
0
    } else if (*out < -1.0) {
81
0
      *out = -std::numeric_limits<float>::infinity();
82
0
    }
83
0
  }
84
0
  return true;
85
0
}
86
87
0
bool SimpleAtod(absl::string_view str, double* absl_nonnull out) {
88
0
  *out = 0.0;
89
0
  str = StripAsciiWhitespace(str);
90
0
  if (str.empty()) {
91
    // absl::from_chars doesn't accept empty strings.
92
0
    return false;
93
0
  }
94
  // std::from_chars doesn't accept an initial +, but SimpleAtod does, so if one
95
  // is present, skip it, while avoiding accepting "+-0" as valid.
96
0
  if (str[0] == '+') {
97
0
    str.remove_prefix(1);
98
0
    if (str.empty() || str[0] == '-') {
99
0
      return false;
100
0
    }
101
0
  }
102
0
  auto result = absl::from_chars(str.data(), str.data() + str.size(), *out);
103
0
  if (result.ec == std::errc::invalid_argument) {
104
0
    return false;
105
0
  }
106
0
  if (result.ptr != str.data() + str.size()) {
107
    // not all non-whitespace characters consumed
108
0
    return false;
109
0
  }
110
  // from_chars() with DR 3081's current wording will return max() on
111
  // overflow.  SimpleAtod returns infinity instead.
112
0
  if (result.ec == std::errc::result_out_of_range) {
113
0
    if (*out > 1.0) {
114
0
      *out = std::numeric_limits<double>::infinity();
115
0
    } else if (*out < -1.0) {
116
0
      *out = -std::numeric_limits<double>::infinity();
117
0
    }
118
0
  }
119
0
  return true;
120
0
}
121
122
0
bool SimpleAtob(absl::string_view str, bool* absl_nonnull out) {
123
0
  ABSL_RAW_CHECK(out != nullptr, "Output pointer must not be nullptr.");
124
0
  if (EqualsIgnoreCase(str, "true") || EqualsIgnoreCase(str, "t") ||
125
0
      EqualsIgnoreCase(str, "yes") || EqualsIgnoreCase(str, "y") ||
126
0
      EqualsIgnoreCase(str, "1")) {
127
0
    *out = true;
128
0
    return true;
129
0
  }
130
0
  if (EqualsIgnoreCase(str, "false") || EqualsIgnoreCase(str, "f") ||
131
0
      EqualsIgnoreCase(str, "no") || EqualsIgnoreCase(str, "n") ||
132
0
      EqualsIgnoreCase(str, "0")) {
133
0
    *out = false;
134
0
    return true;
135
0
  }
136
0
  return false;
137
0
}
138
139
// ----------------------------------------------------------------------
140
// FastIntToBuffer() overloads
141
//
142
// Like the Fast*ToBuffer() functions above, these are intended for speed.
143
// Unlike the Fast*ToBuffer() functions, however, these functions write
144
// their output to the beginning of the buffer.  The caller is responsible
145
// for ensuring that the buffer has enough space to hold the output.
146
//
147
// Returns a pointer to the end of the string (i.e. the null character
148
// terminating the string).
149
// ----------------------------------------------------------------------
150
151
namespace {
152
153
// Various routines to encode integers to strings.
154
155
// We split data encodings into a group of 2 digits, 4 digits, 8 digits as
156
// it's easier to combine powers of two into scalar arithmetic.
157
158
// Previous implementation used a lookup table of 200 bytes for every 2 bytes
159
// and it was memory bound, any L1 cache miss would result in a much slower
160
// result. When benchmarking with a cache eviction rate of several percent,
161
// this implementation proved to be better.
162
163
// These constants represent '00', '0000' and '00000000' as ascii strings in
164
// integers. We can add these numbers if we encode to bytes from 0 to 9. as
165
// 'i' = '0' + i for 0 <= i <= 9.
166
constexpr uint32_t kTwoZeroBytes = 0x0101 * '0';
167
constexpr uint64_t kFourZeroBytes = 0x01010101 * '0';
168
constexpr uint64_t kEightZeroBytes = 0x0101010101010101ull * '0';
169
170
// * 103 / 1024 is a division by 10 for values from 0 to 99. It's also a
171
// division of a structure [k takes 2 bytes][m takes 2 bytes], then * 103 / 1024
172
// will be [k / 10][m / 10]. It allows parallel division.
173
constexpr uint64_t kDivisionBy10Mul = 103u;
174
constexpr uint64_t kDivisionBy10Div = 1 << 10;
175
176
// * 10486 / 1048576 is a division by 100 for values from 0 to 9999.
177
constexpr uint64_t kDivisionBy100Mul = 10486u;
178
constexpr uint64_t kDivisionBy100Div = 1 << 20;
179
180
// Encode functions write the ASCII output of input `n` to `out_str`.
181
0
inline char* EncodeHundred(uint32_t n, char* absl_nonnull out_str) {
182
0
  int num_digits = static_cast<int>(n - 10) >> 8;
183
0
  uint32_t div10 = (n * kDivisionBy10Mul) / kDivisionBy10Div;
184
0
  uint32_t mod10 = n - 10u * div10;
185
0
  uint32_t base = kTwoZeroBytes + div10 + (mod10 << 8);
186
0
  base >>= num_digits & 8;
187
0
  little_endian::Store16(out_str, static_cast<uint16_t>(base));
188
0
  return out_str + 2 + num_digits;
189
0
}
190
191
0
inline char* EncodeTenThousand(uint32_t n, char* absl_nonnull out_str) {
192
  // We split lower 2 digits and upper 2 digits of n into 2 byte consecutive
193
  // blocks. 123 ->  [\0\1][\0\23]. We divide by 10 both blocks
194
  // (it's 1 division + zeroing upper bits), and compute modulo 10 as well "in
195
  // parallel". Then we combine both results to have both ASCII digits,
196
  // strip trailing zeros, add ASCII '0000' and return.
197
0
  uint32_t div100 = (n * kDivisionBy100Mul) / kDivisionBy100Div;
198
0
  uint32_t mod100 = n - 100ull * div100;
199
0
  uint32_t hundreds = (mod100 << 16) + div100;
200
0
  uint32_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div;
201
0
  tens &= (0xFull << 16) | 0xFull;
202
0
  tens += (hundreds - 10ull * tens) << 8;
203
0
  ABSL_ASSUME(tens != 0);
204
  // The result can contain trailing zero bits, we need to strip them to a first
205
  // significant byte in a final representation. For example, for n = 123, we
206
  // have tens to have representation \0\1\2\3. We do `& -8` to round
207
  // to a multiple to 8 to strip zero bytes, not all zero bits.
208
  // countr_zero to help.
209
  // 0 minus 8 to make MSVC happy.
210
0
  uint32_t zeroes = static_cast<uint32_t>(absl::countr_zero(tens)) & (0 - 8u);
211
0
  tens += kFourZeroBytes;
212
0
  tens >>= zeroes;
213
0
  little_endian::Store32(out_str, tens);
214
0
  return out_str + sizeof(tens) - zeroes / 8;
215
0
}
216
217
// Helper function to produce an ASCII representation of `i`.
218
//
219
// Function returns an 8-byte integer which when summed with `kEightZeroBytes`,
220
// can be treated as a printable buffer with ascii representation of `i`,
221
// possibly with leading zeros.
222
//
223
// Example:
224
//
225
//  uint64_t buffer = PrepareEightDigits(102030) + kEightZeroBytes;
226
//  char* ascii = reinterpret_cast<char*>(&buffer);
227
//  // Note two leading zeros:
228
//  EXPECT_EQ(absl::string_view(ascii, 8), "00102030");
229
//
230
// Pre-condition: `i` must be less than 100000000.
231
882
inline uint64_t PrepareEightDigits(uint32_t i) {
232
882
  ABSL_ASSUME(i < 10000'0000);
233
  // Prepare 2 blocks of 4 digits "in parallel".
234
882
  uint32_t hi = i / 10000;
235
882
  uint32_t lo = i % 10000;
236
882
  uint64_t merged = hi | (uint64_t{lo} << 32);
237
882
  uint64_t div100 = ((merged * kDivisionBy100Mul) / kDivisionBy100Div) &
238
882
                    ((0x7Full << 32) | 0x7Full);
239
882
  uint64_t mod100 = merged - 100ull * div100;
240
882
  uint64_t hundreds = (mod100 << 16) + div100;
241
882
  uint64_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div;
242
882
  tens &= (0xFull << 48) | (0xFull << 32) | (0xFull << 16) | 0xFull;
243
882
  tens += (hundreds - 10ull * tens) << 8;
244
882
  return tens;
245
882
}
246
247
248
// Encodes v to buffer as 16 digits padded with leading zeros.
249
// Pre-condition: v must be < 10^16.
250
0
inline char* EncodePadded16(uint64_t v, char* absl_nonnull buffer) {
251
0
  constexpr uint64_t k1e8 = 100000000;
252
0
  uint32_t hi = static_cast<uint32_t>(v / k1e8);
253
0
  uint32_t lo = static_cast<uint32_t>(v % k1e8);
254
0
  little_endian::Store64(buffer, PrepareEightDigits(hi) + kEightZeroBytes);
255
0
  little_endian::Store64(buffer + 8, PrepareEightDigits(lo) + kEightZeroBytes);
256
0
  return buffer + 16;
257
0
}
258
259
inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* absl_nonnull EncodeFullU32(
260
16.7k
    uint32_t n, char* absl_nonnull out_str) {
261
16.7k
  if (n < 10) {
262
15.9k
    *out_str = static_cast<char>('0' + n);
263
15.9k
    return out_str + 1;
264
15.9k
  }
265
882
  if (n < 100'000'000) {
266
882
    uint64_t bottom = PrepareEightDigits(n);
267
882
    ABSL_ASSUME(bottom != 0);
268
    // 0 minus 8 to make MSVC happy.
269
882
    uint32_t zeroes =
270
882
        static_cast<uint32_t>(absl::countr_zero(bottom)) & (0 - 8u);
271
882
    little_endian::Store64(out_str, (bottom + kEightZeroBytes) >> zeroes);
272
882
    return out_str + sizeof(bottom) - zeroes / 8;
273
882
  }
274
0
  uint32_t div08 = n / 100'000'000;
275
0
  uint32_t mod08 = n % 100'000'000;
276
0
  uint64_t bottom = PrepareEightDigits(mod08) + kEightZeroBytes;
277
0
  out_str = EncodeHundred(div08, out_str);
278
0
  little_endian::Store64(out_str, bottom);
279
0
  return out_str + sizeof(bottom);
280
882
}
281
282
inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* absl_nonnull EncodeFullU64(
283
0
    uint64_t i, char* absl_nonnull buffer) {
284
0
  if (i <= std::numeric_limits<uint32_t>::max()) {
285
0
    return EncodeFullU32(static_cast<uint32_t>(i), buffer);
286
0
  }
287
0
  uint32_t mod08;
288
0
  if (i < 1'0000'0000'0000'0000ull) {
289
0
    uint32_t div08 = static_cast<uint32_t>(i / 100'000'000ull);
290
0
    mod08 = static_cast<uint32_t>(i % 100'000'000ull);
291
0
    buffer = EncodeFullU32(div08, buffer);
292
0
  } else {
293
0
    uint64_t div08 = i / 100'000'000ull;
294
0
    mod08 = static_cast<uint32_t>(i % 100'000'000ull);
295
0
    uint32_t div016 = static_cast<uint32_t>(div08 / 100'000'000ull);
296
0
    uint32_t div08mod08 = static_cast<uint32_t>(div08 % 100'000'000ull);
297
0
    uint64_t mid_result = PrepareEightDigits(div08mod08) + kEightZeroBytes;
298
0
    buffer = EncodeTenThousand(div016, buffer);
299
0
    little_endian::Store64(buffer, mid_result);
300
0
    buffer += sizeof(mid_result);
301
0
  }
302
0
  uint64_t mod_result = PrepareEightDigits(mod08) + kEightZeroBytes;
303
0
  little_endian::Store64(buffer, mod_result);
304
0
  return buffer + sizeof(mod_result);
305
0
}
306
307
inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* absl_nonnull EncodeFullU128(
308
0
    uint128 i, char* absl_nonnull buffer) {
309
0
  if (absl::Uint128High64(i) == 0) {
310
0
    return EncodeFullU64(absl::Uint128Low64(i), buffer);
311
0
  }
312
  // We divide the number into 16-digit chunks because `EncodePadded16` is
313
  // optimized to handle 16 digits at a time (as two 8-digit chunks).
314
0
  constexpr uint64_t k1e16 = uint64_t{10'000'000'000'000'000};
315
0
  uint128 high = i / k1e16;
316
0
  uint64_t low = absl::Uint128Low64(i % k1e16);
317
0
  uint64_t mid = absl::Uint128Low64(high % k1e16);
318
0
  high /= k1e16;
319
320
0
  if (high == 0) {
321
0
    buffer = EncodeFullU64(mid, buffer);
322
0
    buffer = EncodePadded16(low, buffer);
323
0
  } else {
324
0
    buffer = EncodeFullU64(absl::Uint128Low64(high), buffer);
325
0
    buffer = EncodePadded16(mid, buffer);
326
0
    buffer = EncodePadded16(low, buffer);
327
0
  }
328
0
  return buffer;
329
0
}
330
331
}  // namespace
332
333
0
void numbers_internal::PutTwoDigits(uint32_t i, char* absl_nonnull buf) {
334
0
  assert(i < 100);
335
0
  uint32_t base = kTwoZeroBytes;
336
0
  uint32_t div10 = (i * kDivisionBy10Mul) / kDivisionBy10Div;
337
0
  uint32_t mod10 = i - 10u * div10;
338
0
  base += div10 + (mod10 << 8);
339
0
  little_endian::Store16(buf, static_cast<uint16_t>(base));
340
0
}
341
342
char* absl_nonnull numbers_internal::FastIntToBuffer(
343
0
    uint32_t n, char* absl_nonnull out_str) {
344
0
  out_str = EncodeFullU32(n, out_str);
345
0
  *out_str = '\0';
346
0
  return out_str;
347
0
}
348
349
char* absl_nonnull numbers_internal::FastIntToBuffer(
350
16.7k
    int32_t i, char* absl_nonnull buffer) {
351
16.7k
  uint32_t u = static_cast<uint32_t>(i);
352
16.7k
  if (i < 0) {
353
0
    *buffer++ = '-';
354
    // We need to do the negation in modular (i.e., "unsigned")
355
    // arithmetic; MSVC++ apparently warns for plain "-u", so
356
    // we write the equivalent expression "0 - u" instead.
357
0
    u = 0 - u;
358
0
  }
359
16.7k
  buffer = EncodeFullU32(u, buffer);
360
16.7k
  *buffer = '\0';
361
16.7k
  return buffer;
362
16.7k
}
363
364
char* absl_nonnull numbers_internal::FastIntToBuffer(
365
0
    uint64_t i, char* absl_nonnull buffer) {
366
0
  buffer = EncodeFullU64(i, buffer);
367
0
  *buffer = '\0';
368
0
  return buffer;
369
0
}
370
371
char* absl_nonnull numbers_internal::FastIntToBuffer(
372
0
    int64_t i, char* absl_nonnull buffer) {
373
0
  uint64_t u = static_cast<uint64_t>(i);
374
0
  if (i < 0) {
375
0
    *buffer++ = '-';
376
    // We need to do the negation in modular (i.e., "unsigned")
377
    // arithmetic; MSVC++ apparently warns for plain "-u", so
378
    // we write the equivalent expression "0 - u" instead.
379
0
    u = 0 - u;
380
0
  }
381
0
  buffer = EncodeFullU64(u, buffer);
382
0
  *buffer = '\0';
383
0
  return buffer;
384
0
}
385
386
char* absl_nonnull numbers_internal::FastIntToBuffer(
387
0
    uint128 i, char* absl_nonnull buffer) {
388
0
  buffer = EncodeFullU128(i, buffer);
389
0
  *buffer = '\0';
390
0
  return buffer;
391
0
}
392
393
char* absl_nonnull numbers_internal::FastIntToBuffer(
394
0
    int128 i, char* absl_nonnull buffer) {
395
0
  uint128 u = static_cast<uint128>(i);
396
0
  if (i < 0) {
397
0
    *buffer++ = '-';
398
0
    u = -u;
399
0
  }
400
0
  buffer = EncodeFullU128(u, buffer);
401
0
  *buffer = '\0';
402
0
  return buffer;
403
0
}
404
405
// Although DBL_DIG is typically 15, DBL_MAX is normally represented with 17
406
// digits of precision. When converted to a string value with fewer digits
407
// of precision using strtod(), the result can be bigger than DBL_MAX due to
408
// a rounding error. Converting this value back to a double will produce an
409
// Inf which will trigger a SIGFPE if FP exceptions are enabled. We skip
410
// the precision check for sufficiently large values to avoid the SIGFPE.
411
static constexpr double kDoublePrecisionCheckMax =
412
    std::numeric_limits<double>::max() / 1.000000000000001;
413
414
char* absl_nonnull numbers_internal::RoundTripDoubleToBuffer(
415
0
    double d, char* absl_nonnull buffer) {
416
  // DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all
417
  // platforms these days.  Just in case some system exists where DBL_DIG
418
  // is significantly larger -- and risks overflowing our buffer -- we have
419
  // this assert.
420
0
  static_assert(std::numeric_limits<double>::digits10 < 20,
421
0
                "std::numeric_limits<double>::digits10 is too big");
422
423
  // We avoid snprintf for NaNs because it inconsistently outputs "-nan"
424
  // or "nan" when given a nan with the sign bit set.
425
0
  if (std::isnan(d)) {
426
0
    strcpy(buffer, "nan");  // NOLINT(runtime/printf)
427
0
    return buffer;
428
0
  }
429
0
  bool full_precision_needed = true;
430
0
  if (std::abs(d) <= kDoublePrecisionCheckMax) {
431
0
    int snprintf_result =
432
0
        snprintf(buffer, numbers_internal::kFastToBufferSize, "%.*g",
433
0
                 std::numeric_limits<double>::digits10, d);
434
435
    // The snprintf should never overflow because the buffer is significantly
436
    // larger than the precision we asked for.
437
0
    ABSL_ASSERT(snprintf_result > 0 &&
438
0
                snprintf_result < numbers_internal::kFastToBufferSize);
439
440
0
    full_precision_needed = strtod(buffer, nullptr) != d;
441
0
  }
442
443
0
  if (full_precision_needed) {
444
0
    int snprintf_result =
445
0
        snprintf(buffer, numbers_internal::kFastToBufferSize, "%.*g",
446
0
                 std::numeric_limits<double>::digits10 + 2, d);
447
448
    // Should never overflow; see above.
449
0
    ABSL_ASSERT(snprintf_result > 0 &&
450
0
                snprintf_result < numbers_internal::kFastToBufferSize);
451
0
  }
452
453
  // snprintf() writes the radix character chosen by the global C locale's
454
  // LC_NUMERIC category, so a process that has called setlocale() can end up
455
  // with a separator other than '.' here. The rest of Abseil's float formatting
456
  // (RoundTripFloatToBuffer, SixDigitsToBuffer) is locale- independent and
457
  // SimpleAtod() only accepts '.', so rewrite the radix back to '.' to keep
458
  // absl::HighPrecision(double) locale-independent and round-trippable through
459
  // SimpleAtod().
460
  // TODO: b/526633099 - Once all supported compilers ship std::to_chars with
461
  // floating-point support, use it here for inherent locale independence.
462
0
  const char* radix = localeconv()->decimal_point;
463
  // Skip an empty decimal_point (some minimal environments leave it ""), which
464
  // would otherwise match the beginning of the buffer and corrupt it.
465
0
  if (radix[0] != '\0' && std::strcmp(radix, ".") != 0) {
466
0
    if (char* p = std::strstr(buffer, radix)) {
467
0
      const size_t radix_len = std::strlen(radix);
468
0
      *p = '.';
469
      // A multibyte radix (rare, but possible in some locales) leaves trailing
470
      // bytes behind; collapse them so the output is a single '.'.
471
0
      if (radix_len > 1) {
472
0
        std::memmove(p + 1, p + radix_len, std::strlen(p + radix_len) + 1);
473
0
      }
474
0
    }
475
0
  }
476
0
  return buffer;
477
0
}
478
479
namespace {
480
481
// This table is used to quickly calculate the base-ten exponent of a given
482
// float, and then to provide a multiplier to bring that number into the
483
// range 1-999,999,999, that is, into uint32_t range.  Finally, the exp
484
// string is made available so there is one less int-to-string conversion
485
// to be done.
486
struct Spec {
487
  double min_range;
488
  double multiplier;
489
  const char expstr[5];
490
};
491
492
// clang-format off
493
constexpr Spec kNegExpTable[] = {
494
    Spec{1.4e-45f, 1e+55, "e-45"},
495
    Spec{1e-44f, 1e+54, "e-44"},
496
    Spec{1e-43f, 1e+53, "e-43"},
497
    Spec{1e-42f, 1e+52, "e-42"},
498
    Spec{1e-41f, 1e+51, "e-41"},
499
    Spec{1e-40f, 1e+50, "e-40"},
500
    Spec{1e-39f, 1e+49, "e-39"},
501
    Spec{1e-38f, 1e+48, "e-38"},
502
    Spec{1e-37f, 1e+47, "e-37"},
503
    Spec{1e-36f, 1e+46, "e-36"},
504
    Spec{1e-35f, 1e+45, "e-35"},
505
    Spec{1e-34f, 1e+44, "e-34"},
506
    Spec{1e-33f, 1e+43, "e-33"},
507
    Spec{1e-32f, 1e+42, "e-32"},
508
    Spec{1e-31f, 1e+41, "e-31"},
509
    Spec{1e-30f, 1e+40, "e-30"},
510
    Spec{1e-29f, 1e+39, "e-29"},
511
    Spec{1e-28f, 1e+38, "e-28"},
512
    Spec{1e-27f, 1e+37, "e-27"},
513
    Spec{1e-26f, 1e+36, "e-26"},
514
    Spec{1e-25f, 1e+35, "e-25"},
515
    Spec{1e-24f, 1e+34, "e-24"},
516
    Spec{1e-23f, 1e+33, "e-23"},
517
    Spec{1e-22f, 1e+32, "e-22"},
518
    Spec{1e-21f, 1e+31, "e-21"},
519
    Spec{1e-20f, 1e+30, "e-20"},
520
    Spec{1e-19f, 1e+29, "e-19"},
521
    Spec{1e-18f, 1e+28, "e-18"},
522
    Spec{1e-17f, 1e+27, "e-17"},
523
    Spec{1e-16f, 1e+26, "e-16"},
524
    Spec{1e-15f, 1e+25, "e-15"},
525
    Spec{1e-14f, 1e+24, "e-14"},
526
    Spec{1e-13f, 1e+23, "e-13"},
527
    Spec{1e-12f, 1e+22, "e-12"},
528
    Spec{1e-11f, 1e+21, "e-11"},
529
    Spec{1e-10f, 1e+20, "e-10"},
530
    Spec{1e-09f, 1e+19, "e-09"},
531
    Spec{1e-08f, 1e+18, "e-08"},
532
    Spec{1e-07f, 1e+17, "e-07"},
533
    Spec{1e-06f, 1e+16, "e-06"},
534
    Spec{1e-05f, 1e+15, "e-05"},
535
    Spec{1e-04f, 1e+14, "e-04"},
536
};
537
// clang-format on
538
539
// clang-format off
540
constexpr Spec kPosExpTable[] = {
541
    Spec{1e+08f, 1e+02, "e+08"},
542
    Spec{1e+09f, 1e+01, "e+09"},
543
    Spec{1e+10f, 1e+00, "e+10"},
544
    Spec{1e+11f, 1e-01, "e+11"},
545
    Spec{1e+12f, 1e-02, "e+12"},
546
    Spec{1e+13f, 1e-03, "e+13"},
547
    Spec{1e+14f, 1e-04, "e+14"},
548
    Spec{1e+15f, 1e-05, "e+15"},
549
    Spec{1e+16f, 1e-06, "e+16"},
550
    Spec{1e+17f, 1e-07, "e+17"},
551
    Spec{1e+18f, 1e-08, "e+18"},
552
    Spec{1e+19f, 1e-09, "e+19"},
553
    Spec{1e+20f, 1e-10, "e+20"},
554
    Spec{1e+21f, 1e-11, "e+21"},
555
    Spec{1e+22f, 1e-12, "e+22"},
556
    Spec{1e+23f, 1e-13, "e+23"},
557
    Spec{1e+24f, 1e-14, "e+24"},
558
    Spec{1e+25f, 1e-15, "e+25"},
559
    Spec{1e+26f, 1e-16, "e+26"},
560
    Spec{1e+27f, 1e-17, "e+27"},
561
    Spec{1e+28f, 1e-18, "e+28"},
562
    Spec{1e+29f, 1e-19, "e+29"},
563
    Spec{1e+30f, 1e-20, "e+30"},
564
    Spec{1e+31f, 1e-21, "e+31"},
565
    Spec{1e+32f, 1e-22, "e+32"},
566
    Spec{1e+33f, 1e-23, "e+33"},
567
    Spec{1e+34f, 1e-24, "e+34"},
568
    Spec{1e+35f, 1e-25, "e+35"},
569
    Spec{1e+36f, 1e-26, "e+36"},
570
    Spec{1e+37f, 1e-27, "e+37"},
571
    Spec{1e+38f, 1e-28, "e+38"},
572
    Spec{1e+39,  1e-29, "e+39"},
573
};
574
// clang-format on
575
576
struct ExpCompare {
577
0
  bool operator()(const Spec& spec, double d) const {
578
0
    return spec.min_range < d;
579
0
  }
580
};
581
582
}  // namespace
583
584
// Utility routine(s) for RoundTripFloatToBuffer:
585
// OutputNecessaryDigits takes two 11-digit numbers, whose integer portion
586
// represents the fractional part of a floating-point number, and outputs a
587
// number that is in-between them, with the fewest digits possible. For
588
// instance, given 12345678900 and 12345876900, it would output "0123457".
589
// When there are multiple final digits that would satisfy this requirement,
590
// this routine attempts to use a digit that would represent the average of
591
// lower_double and upper_double.
592
//
593
// Although the routine works using integers, all callers use doubles, so
594
// for their convenience this routine accepts doubles.
595
static char* absl_nonnull OutputNecessaryDigits(double lower_double,
596
                                                double upper_double,
597
0
                                                char* absl_nonnull out) {
598
0
  assert(lower_double > 0);
599
0
  assert(lower_double < upper_double - 10);
600
0
  assert(upper_double < 100000000000.0);
601
602
  // Narrow the range a bit; without this bias, an input of lower=87654320010.0
603
  // and upper=87654320100.0 would produce an output of 876543201
604
  //
605
  // We do this in three steps: first, we lower the upper bound and truncate it
606
  // to an integer.  Then, we increase the lower bound by exactly the amount we
607
  // just decreased the upper bound by - at that point, the midpoint is exactly
608
  // where it used to be.  Then we truncate the lower bound.
609
610
0
  uint64_t upper64 = static_cast<uint64_t>(upper_double - (1.0 / 1024));
611
0
  double shrink = upper_double - upper64;
612
0
  uint64_t lower64 = static_cast<uint64_t>(lower_double + shrink);
613
614
  // Theory of operation: we convert the lower number to ascii representation,
615
  // two digits at a time.  As we go, we remove the same digits from the upper
616
  // number.  When we see the upper number does not share those same digits, we
617
  // know we can stop converting. When we stop, the last digit we output is
618
  // taken from the average of upper and lower values, rounded up.
619
0
  char buf[2];
620
0
  uint32_t lodigits =
621
0
      static_cast<uint32_t>(lower64 / 1000000000);  // 1,000,000,000
622
0
  uint64_t mul64 = lodigits * uint64_t{1000000000};
623
624
0
  numbers_internal::PutTwoDigits(lodigits, out);
625
0
  out += 2;
626
0
  if (upper64 - mul64 >= 1000000000) {  // digit mismatch!
627
0
    numbers_internal::PutTwoDigits(static_cast<uint32_t>(upper64 / 1000000000),
628
0
                                   buf);
629
0
    if (out[-2] != buf[0]) {
630
0
      out[-2] = static_cast<char>('0' + (upper64 + lower64 + 10000000000) /
631
0
                                            20000000000);
632
0
      --out;
633
0
    } else {
634
0
      numbers_internal::PutTwoDigits(
635
0
          static_cast<uint32_t>((upper64 + lower64 + 1000000000) / 2000000000),
636
0
          out - 2);
637
0
    }
638
0
    *out = '\0';
639
0
    return out;
640
0
  }
641
0
  uint32_t lower = static_cast<uint32_t>(lower64 - mul64);
642
0
  uint32_t upper = static_cast<uint32_t>(upper64 - mul64);
643
644
0
  lodigits = lower / 10000000;  // 10,000,000
645
0
  uint32_t mul = lodigits * 10000000;
646
0
  numbers_internal::PutTwoDigits(lodigits, out);
647
0
  out += 2;
648
0
  if (upper - mul >= 10000000) {  // digit mismatch!
649
0
    numbers_internal::PutTwoDigits(upper / 10000000, buf);
650
0
    if (out[-2] != buf[0]) {
651
0
      out[-2] = '0' + (upper + lower + 100000000) / 200000000;
652
0
      --out;
653
0
    } else {
654
0
      numbers_internal::PutTwoDigits((upper + lower + 10000000) / 20000000,
655
0
                                      out - 2);
656
0
    }
657
0
    *out = '\0';
658
0
    return out;
659
0
  }
660
0
  lower -= mul;
661
0
  upper -= mul;
662
663
0
  lodigits = lower / 100000;  // 100,000
664
0
  mul = lodigits * 100000;
665
0
  numbers_internal::PutTwoDigits(lodigits, out);
666
0
  out += 2;
667
0
  if (upper - mul >= 100000) {  // digit mismatch!
668
0
    numbers_internal::PutTwoDigits(upper / 100000, buf);
669
0
    if (out[-2] != buf[0]) {
670
0
      out[-2] = static_cast<char>('0' + (upper + lower + 1000000) / 2000000);
671
0
      --out;
672
0
    } else {
673
0
      numbers_internal::PutTwoDigits((upper + lower + 100000) / 200000,
674
0
                                      out - 2);
675
0
    }
676
0
    *out = '\0';
677
0
    return out;
678
0
  }
679
0
  lower -= mul;
680
0
  upper -= mul;
681
682
0
  lodigits = lower / 1000;
683
0
  mul = lodigits * 1000;
684
0
  numbers_internal::PutTwoDigits(lodigits, out);
685
0
  out += 2;
686
0
  if (upper - mul >= 1000) {  // digit mismatch!
687
0
    numbers_internal::PutTwoDigits(upper / 1000, buf);
688
0
    if (out[-2] != buf[0]) {
689
0
      out[-2] = static_cast<char>('0' + (upper + lower + 10000) / 20000);
690
0
      --out;
691
0
    } else {
692
0
      numbers_internal::PutTwoDigits((upper + lower + 1000) / 2000, out - 2);
693
0
    }
694
0
    *out = '\0';
695
0
    return out;
696
0
  }
697
0
  lower -= mul;
698
0
  upper -= mul;
699
700
0
  numbers_internal::PutTwoDigits(lower / 10, out);
701
0
  out += 2;
702
0
  numbers_internal::PutTwoDigits(upper / 10, buf);
703
0
  if (out[-2] != buf[0]) {
704
0
    out[-2] = static_cast<char>('0' + (upper + lower + 100) / 200);
705
0
    --out;
706
0
  } else {
707
0
    numbers_internal::PutTwoDigits((upper + lower + 10) / 20, out - 2);
708
0
  }
709
0
  *out = '\0';
710
0
  return out;
711
0
}
712
713
// RoundTripFloatToBuffer converts the given float into a string which, if
714
// passed to strtof, will produce the exact same original float.  It does this
715
// by computing the range of possible doubles which map to the given float, and
716
// then examining the digits of the doubles in that range.  If all the doubles
717
// in the range start with "2.37", then clearly our float does, too.  As soon as
718
// they diverge, only one more digit is needed.
719
char* absl_nonnull numbers_internal::RoundTripFloatToBuffer(
720
0
    float f, char* absl_nonnull buffer) {
721
0
  static_assert(std::numeric_limits<float>::is_iec559,
722
0
                "IEEE-754/IEC-559 support only");
723
724
  // We write data to out, incrementing as we go, but FloatToBuffer always
725
  // returns the address of the buffer passed in.
726
0
  char* out = buffer;
727
728
0
  if (std::isnan(f)) {
729
0
    strcpy(out, "nan");  // NOLINT(runtime/printf)
730
0
    return buffer;
731
0
  }
732
0
  if (f == 0) {  // +0 and -0 are handled here
733
0
    if (std::signbit(f)) {
734
0
      strcpy(out, "-0");  // NOLINT(runtime/printf)
735
0
    } else {
736
0
      strcpy(out, "0");  // NOLINT(runtime/printf)
737
0
    }
738
0
    return buffer;
739
0
  }
740
0
  if (f < 0) {
741
0
    *out++ = '-';
742
0
    f = -f;
743
0
  }
744
0
  if (f > std::numeric_limits<float>::max()) {
745
0
    strcpy(out, "inf");  // NOLINT(runtime/printf)
746
0
    return buffer;
747
0
  }
748
749
0
  double next_lower = nextafterf(f, 0.0f);
750
  // For all doubles in the range lower_bound < f < upper_bound, the
751
  // nearest float is f.
752
0
  double lower_bound = (f + next_lower) * 0.5;
753
0
  double upper_bound = f + (f - lower_bound);
754
  // Note: because std::nextafter is slow, we calculate upper_bound
755
  // assuming that it is the same distance from f as lower_bound is.
756
  // For exact powers of two, upper_bound is actually twice as far
757
  // from f as lower_bound is, but this turns out not to matter.
758
759
  // Most callers pass floats that are either 0 or within the
760
  // range 0.0001 through 100,000,000, so handle those first,
761
  // since they don't need exponential notation.
762
0
  const Spec* spec = nullptr;
763
0
  if (f < 1.0) {
764
0
    if (f >= 0.0001f) {
765
      // For fractional values, we set up the multiplier at the same
766
      // time as we output the leading "0." / "0.0" / "0.00" / "0.000"
767
0
      double multiplier = 1e+11;
768
0
      *out++ = '0';
769
0
      *out++ = '.';
770
0
      if (f < 0.1f) {
771
0
        multiplier = 1e+12;
772
0
        *out++ = '0';
773
0
        if (f < 0.01f) {
774
0
          multiplier = 1e+13;
775
0
          *out++ = '0';
776
0
          if (f < 0.001f) {
777
0
            multiplier = 1e+14;
778
0
            *out++ = '0';
779
0
          }
780
0
        }
781
0
      }
782
0
      OutputNecessaryDigits(lower_bound * multiplier, upper_bound * multiplier,
783
0
                            out);
784
0
      return buffer;
785
0
    }
786
0
    spec = std::lower_bound(std::begin(kNegExpTable), std::end(kNegExpTable),
787
0
                            double{f}, ExpCompare());
788
0
    if (spec == std::end(kNegExpTable)) --spec;
789
0
  } else if (f < 1e8) {
790
    // Handling non-exponential format greater than 1.0 is similar to the above,
791
    // but instead of 0.0 / 0.00 / 0.000, the prefix is simply the truncated
792
    // integer part of f.
793
0
    int32_t as_int = static_cast<int32_t>(f);
794
0
    out = numbers_internal::FastIntToBuffer(as_int, out);
795
    // Easy: if the integer part is within (lower_bound, upper_bound), then we
796
    // are already done.
797
0
    if (as_int > lower_bound && as_int < upper_bound) {
798
0
      return buffer;
799
0
    }
800
0
    *out++ = '.';
801
0
    OutputNecessaryDigits((lower_bound - as_int) * 1e11,
802
0
                          (upper_bound - as_int) * 1e11, out);
803
0
    return buffer;
804
0
  } else {
805
0
    spec = std::lower_bound(std::begin(kPosExpTable), std::end(kPosExpTable),
806
0
                            double{f}, ExpCompare());
807
0
    if (spec == std::end(kPosExpTable)) --spec;
808
0
  }
809
  // Exponential notation from here on.  "spec" was computed using lower_bound,
810
  // which means it's the first spec from the table where min_range is greater
811
  // or equal to f.
812
  // Unfortunately that's not quite what we want; we want a min_range that is
813
  // less or equal.  So first thing, if it was greater, back up one entry.
814
0
  if (spec->min_range > f) --spec;
815
816
  // The digits might be "237000123", but we want "2.37000123",
817
  // so we output the digits one character later, and then move the first
818
  // digit back so we can stick the "." in.
819
0
  char* start = out;
820
0
  out = OutputNecessaryDigits(lower_bound * spec->multiplier,
821
0
                              upper_bound * spec->multiplier, start + 1);
822
0
  start[0] = start[1];
823
0
  start[1] = '.';
824
825
  // If it turns out there was only one digit output, then back up over the '.'
826
0
  if (out == &start[2]) --out;
827
828
  // Now add the "e+NN" part.
829
0
  memcpy(out, spec->expstr, 4);
830
0
  out[4] = '\0';
831
0
  return buffer;
832
0
}
833
834
// Given a 128-bit number expressed as a pair of uint64_t, high half first,
835
// return that number multiplied by the given 32-bit value.  If the result is
836
// too large to fit in a 128-bit number, divide it by 2 until it fits.
837
static std::pair<uint64_t, uint64_t> Mul32(std::pair<uint64_t, uint64_t> num,
838
0
                                           uint32_t mul) {
839
0
  uint64_t bits0_31 = num.second & 0xFFFFFFFF;
840
0
  uint64_t bits32_63 = num.second >> 32;
841
0
  uint64_t bits64_95 = num.first & 0xFFFFFFFF;
842
0
  uint64_t bits96_127 = num.first >> 32;
843
844
  // The picture so far: each of these 64-bit values has only the lower 32 bits
845
  // filled in.
846
  // bits96_127:          [ 00000000 xxxxxxxx ]
847
  // bits64_95:                    [ 00000000 xxxxxxxx ]
848
  // bits32_63:                             [ 00000000 xxxxxxxx ]
849
  // bits0_31:                                       [ 00000000 xxxxxxxx ]
850
851
0
  bits0_31 *= mul;
852
0
  bits32_63 *= mul;
853
0
  bits64_95 *= mul;
854
0
  bits96_127 *= mul;
855
856
  // Now the top halves may also have value, though all 64 of their bits will
857
  // never be set at the same time, since they are a result of a 32x32 bit
858
  // multiply.  This makes the carry calculation slightly easier.
859
  // bits96_127:          [ mmmmmmmm | mmmmmmmm ]
860
  // bits64_95:                    [ | mmmmmmmm mmmmmmmm | ]
861
  // bits32_63:                      |        [ mmmmmmmm | mmmmmmmm ]
862
  // bits0_31:                       |                 [ | mmmmmmmm mmmmmmmm ]
863
  // eventually:        [ bits128_up | ...bits64_127.... | ..bits0_63... ]
864
865
0
  uint64_t bits0_63 = bits0_31 + (bits32_63 << 32);
866
0
  uint64_t bits64_127 = bits64_95 + (bits96_127 << 32) + (bits32_63 >> 32) +
867
0
                        (bits0_63 < bits0_31);
868
0
  uint64_t bits128_up = (bits96_127 >> 32) + (bits64_127 < bits64_95);
869
0
  if (bits128_up == 0) return {bits64_127, bits0_63};
870
871
0
  auto shift = static_cast<unsigned>(bit_width(bits128_up));
872
0
  uint64_t lo = (bits0_63 >> shift) + (bits64_127 << (64 - shift));
873
0
  uint64_t hi = (bits64_127 >> shift) + (bits128_up << (64 - shift));
874
0
  return {hi, lo};
875
0
}
876
877
// Compute num * 5 ^ expfive, and return the first 128 bits of the result,
878
// where the first bit is always a one.  So PowFive(1, 0) starts 0b100000,
879
// PowFive(1, 1) starts 0b101000, PowFive(1, 2) starts 0b110010, etc.
880
0
static std::pair<uint64_t, uint64_t> PowFive(uint64_t num, int expfive) {
881
0
  std::pair<uint64_t, uint64_t> result = {num, 0};
882
0
  while (expfive >= 13) {
883
    // 5^13 is the highest power of five that will fit in a 32-bit integer.
884
0
    result = Mul32(result, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5);
885
0
    expfive -= 13;
886
0
  }
887
0
  constexpr uint32_t powers_of_five[13] = {
888
0
      1,
889
0
      5,
890
0
      5 * 5,
891
0
      5 * 5 * 5,
892
0
      5 * 5 * 5 * 5,
893
0
      5 * 5 * 5 * 5 * 5,
894
0
      5 * 5 * 5 * 5 * 5 * 5,
895
0
      5 * 5 * 5 * 5 * 5 * 5 * 5,
896
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
897
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
898
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
899
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
900
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5};
901
0
  result = Mul32(result, powers_of_five[expfive & 15]);
902
0
  int shift = countl_zero(result.first);
903
0
  if (shift != 0) {
904
0
    result.first = (result.first << shift) + (result.second >> (64 - shift));
905
0
    result.second = (result.second << shift);
906
0
  }
907
0
  return result;
908
0
}
909
910
struct ExpDigits {
911
  int32_t exponent;
912
  char digits[6];
913
};
914
915
// SplitToSix converts value, a positive double-precision floating-point number,
916
// into a base-10 exponent and 6 ASCII digits, where the first digit is never
917
// zero.  For example, SplitToSix(1) returns an exponent of zero and a digits
918
// array of {'1', '0', '0', '0', '0', '0'}.  If value is exactly halfway between
919
// two possible representations, e.g. value = 100000.5, then "round to even" is
920
// performed.
921
0
static ExpDigits SplitToSix(const double value) {
922
0
  ExpDigits exp_dig;
923
0
  int exp = 5;
924
0
  double d = value;
925
  // First step: calculate a close approximation of the output, where the
926
  // value d will be between 100,000 and 999,999, representing the digits
927
  // in the output ASCII array, and exp is the base-10 exponent.  It would be
928
  // faster to use a table here, and to look up the base-2 exponent of value,
929
  // however value is an IEEE-754 64-bit number, so the table would have 2,000
930
  // entries, which is not cache-friendly.
931
0
  if (d >= 999999.5) {
932
0
    if (d >= 1e+261) exp += 256, d *= 1e-256;
933
0
    if (d >= 1e+133) exp += 128, d *= 1e-128;
934
0
    if (d >= 1e+69) exp += 64, d *= 1e-64;
935
0
    if (d >= 1e+37) exp += 32, d *= 1e-32;
936
0
    if (d >= 1e+21) exp += 16, d *= 1e-16;
937
0
    if (d >= 1e+13) exp += 8, d *= 1e-8;
938
0
    if (d >= 1e+9) exp += 4, d *= 1e-4;
939
0
    if (d >= 1e+7) exp += 2, d *= 1e-2;
940
0
    if (d >= 1e+6) exp += 1, d *= 1e-1;
941
0
  } else {
942
0
    if (d < 1e-250) exp -= 256, d *= 1e256;
943
0
    if (d < 1e-122) exp -= 128, d *= 1e128;
944
0
    if (d < 1e-58) exp -= 64, d *= 1e64;
945
0
    if (d < 1e-26) exp -= 32, d *= 1e32;
946
0
    if (d < 1e-10) exp -= 16, d *= 1e16;
947
0
    if (d < 1e-2) exp -= 8, d *= 1e8;
948
0
    if (d < 1e+2) exp -= 4, d *= 1e4;
949
0
    if (d < 1e+4) exp -= 2, d *= 1e2;
950
0
    if (d < 1e+5) exp -= 1, d *= 1e1;
951
0
  }
952
  // At this point, d is in the range [99999.5..999999.5) and exp is in the
953
  // range [-324..308]. Since we need to round d up, we want to add a half
954
  // and truncate.
955
  // However, the technique above may have lost some precision, due to its
956
  // repeated multiplication by constants that each may be off by half a bit
957
  // of precision.  This only matters if we're close to the edge though.
958
  // Since we'd like to know if the fractional part of d is close to a half,
959
  // we multiply it by 65536 and see if the fractional part is close to 32768.
960
  // (The number doesn't have to be a power of two,but powers of two are faster)
961
0
  uint64_t d64k = static_cast<uint64_t>(d * 65536);
962
0
  uint32_t dddddd;  // A 6-digit decimal integer.
963
0
  if ((d64k % 65536) == 32767 || (d64k % 65536) == 32768) {
964
    // OK, it's fairly likely that precision was lost above, which is
965
    // not a surprise given only 52 mantissa bits are available.  Therefore
966
    // redo the calculation using 128-bit numbers.  (64 bits are not enough).
967
968
    // Start out with digits rounded down; maybe add one below.
969
0
    dddddd = static_cast<uint32_t>(d64k / 65536);
970
971
    // mantissa is a 64-bit integer representing M.mmm... * 2^63.  The actual
972
    // value we're representing, of course, is M.mmm... * 2^exp2.
973
0
    int exp2;
974
0
    double m = std::frexp(value, &exp2);
975
0
    uint64_t mantissa =
976
0
        static_cast<uint64_t>(m * (32768.0 * 65536.0 * 65536.0 * 65536.0));
977
    // std::frexp returns an m value in the range [0.5, 1.0), however we
978
    // can't multiply it by 2^64 and convert to an integer because some FPUs
979
    // throw an exception when converting an number higher than 2^63 into an
980
    // integer - even an unsigned 64-bit integer!  Fortunately it doesn't matter
981
    // since m only has 52 significant bits anyway.
982
0
    mantissa <<= 1;
983
0
    exp2 -= 64;  // not needed, but nice for debugging
984
985
    // OK, we are here to compare:
986
    //     (dddddd + 0.5) * 10^(exp-5)  vs.  mantissa * 2^exp2
987
    // so we can round up dddddd if appropriate.  Those values span the full
988
    // range of 600 orders of magnitude of IEE 64-bit floating-point.
989
    // Fortunately, we already know they are very close, so we don't need to
990
    // track the base-2 exponent of both sides.  This greatly simplifies the
991
    // the math since the 2^exp2 calculation is unnecessary and the power-of-10
992
    // calculation can become a power-of-5 instead.
993
994
0
    std::pair<uint64_t, uint64_t> edge, val;
995
0
    if (exp >= 6) {
996
      // Compare (dddddd + 0.5) * 5 ^ (exp - 5) to mantissa
997
      // Since we're tossing powers of two, 2 * dddddd + 1 is the
998
      // same as dddddd + 0.5
999
0
      edge = PowFive(2 * dddddd + 1, exp - 5);
1000
1001
0
      val.first = mantissa;
1002
0
      val.second = 0;
1003
0
    } else {
1004
      // We can't compare (dddddd + 0.5) * 5 ^ (exp - 5) to mantissa as we did
1005
      // above because (exp - 5) is negative.  So we compare (dddddd + 0.5) to
1006
      // mantissa * 5 ^ (5 - exp)
1007
0
      edge = PowFive(2 * dddddd + 1, 0);
1008
1009
0
      val = PowFive(mantissa, 5 - exp);
1010
0
    }
1011
    // printf("exp=%d %016lx %016lx vs %016lx %016lx\n", exp, val.first,
1012
    //        val.second, edge.first, edge.second);
1013
0
    if (val > edge) {
1014
0
      dddddd++;
1015
0
    } else if (val == edge) {
1016
0
      dddddd += (dddddd & 1);
1017
0
    }
1018
0
  } else {
1019
    // Here, we are not close to the edge.
1020
0
    dddddd = static_cast<uint32_t>((d64k + 32768) / 65536);
1021
0
  }
1022
0
  if (dddddd == 1000000) {
1023
0
    dddddd = 100000;
1024
0
    exp += 1;
1025
0
  }
1026
0
  exp_dig.exponent = exp;
1027
1028
0
  uint32_t two_digits = dddddd / 10000;
1029
0
  dddddd -= two_digits * 10000;
1030
0
  numbers_internal::PutTwoDigits(two_digits, &exp_dig.digits[0]);
1031
1032
0
  two_digits = dddddd / 100;
1033
0
  dddddd -= two_digits * 100;
1034
0
  numbers_internal::PutTwoDigits(two_digits, &exp_dig.digits[2]);
1035
1036
0
  numbers_internal::PutTwoDigits(dddddd, &exp_dig.digits[4]);
1037
0
  return exp_dig;
1038
0
}
1039
1040
// Helper function for fast formatting of floating-point.
1041
// The result is the same as "%g", a.k.a. "%.6g".
1042
size_t numbers_internal::SixDigitsToBuffer(double d,
1043
0
                                           char* absl_nonnull const buffer) {
1044
0
  static_assert(std::numeric_limits<float>::is_iec559,
1045
0
                "IEEE-754/IEC-559 support only");
1046
1047
0
  char* out = buffer;  // we write data to out, incrementing as we go, but
1048
                       // FloatToBuffer always returns the address of the buffer
1049
                       // passed in.
1050
1051
0
  if (std::isnan(d)) {
1052
0
    strcpy(out, "nan");  // NOLINT(runtime/printf)
1053
0
    return 3;
1054
0
  }
1055
0
  if (d == 0) {  // +0 and -0 are handled here
1056
0
    if (std::signbit(d)) *out++ = '-';
1057
0
    *out++ = '0';
1058
0
    *out = 0;
1059
0
    return static_cast<size_t>(out - buffer);
1060
0
  }
1061
0
  if (d < 0) {
1062
0
    *out++ = '-';
1063
0
    d = -d;
1064
0
  }
1065
0
  if (d > std::numeric_limits<double>::max()) {
1066
0
    strcpy(out, "inf");  // NOLINT(runtime/printf)
1067
0
    return static_cast<size_t>(out + 3 - buffer);
1068
0
  }
1069
1070
0
  auto exp_dig = SplitToSix(d);
1071
0
  int exp = exp_dig.exponent;
1072
0
  const char* digits = exp_dig.digits;
1073
0
  out[0] = '0';
1074
0
  out[1] = '.';
1075
0
  switch (exp) {
1076
0
    case 5:
1077
0
      memcpy(out, &digits[0], 6), out += 6;
1078
0
      *out = 0;
1079
0
      return static_cast<size_t>(out - buffer);
1080
0
    case 4:
1081
0
      memcpy(out, &digits[0], 5), out += 5;
1082
0
      if (digits[5] != '0') {
1083
0
        *out++ = '.';
1084
0
        *out++ = digits[5];
1085
0
      }
1086
0
      *out = 0;
1087
0
      return static_cast<size_t>(out - buffer);
1088
0
    case 3:
1089
0
      memcpy(out, &digits[0], 4), out += 4;
1090
0
      if ((digits[5] | digits[4]) != '0') {
1091
0
        *out++ = '.';
1092
0
        *out++ = digits[4];
1093
0
        if (digits[5] != '0') *out++ = digits[5];
1094
0
      }
1095
0
      *out = 0;
1096
0
      return static_cast<size_t>(out - buffer);
1097
0
    case 2:
1098
0
      memcpy(out, &digits[0], 3), out += 3;
1099
0
      *out++ = '.';
1100
0
      memcpy(out, &digits[3], 3);
1101
0
      out += 3;
1102
0
      while (out[-1] == '0') --out;
1103
0
      if (out[-1] == '.') --out;
1104
0
      *out = 0;
1105
0
      return static_cast<size_t>(out - buffer);
1106
0
    case 1:
1107
0
      memcpy(out, &digits[0], 2), out += 2;
1108
0
      *out++ = '.';
1109
0
      memcpy(out, &digits[2], 4);
1110
0
      out += 4;
1111
0
      while (out[-1] == '0') --out;
1112
0
      if (out[-1] == '.') --out;
1113
0
      *out = 0;
1114
0
      return static_cast<size_t>(out - buffer);
1115
0
    case 0:
1116
0
      memcpy(out, &digits[0], 1), out += 1;
1117
0
      *out++ = '.';
1118
0
      memcpy(out, &digits[1], 5);
1119
0
      out += 5;
1120
0
      while (out[-1] == '0') --out;
1121
0
      if (out[-1] == '.') --out;
1122
0
      *out = 0;
1123
0
      return static_cast<size_t>(out - buffer);
1124
0
    case -4:
1125
0
      out[2] = '0';
1126
0
      ++out;
1127
0
      ABSL_FALLTHROUGH_INTENDED;
1128
0
    case -3:
1129
0
      out[2] = '0';
1130
0
      ++out;
1131
0
      ABSL_FALLTHROUGH_INTENDED;
1132
0
    case -2:
1133
0
      out[2] = '0';
1134
0
      ++out;
1135
0
      ABSL_FALLTHROUGH_INTENDED;
1136
0
    case -1:
1137
0
      out += 2;
1138
0
      memcpy(out, &digits[0], 6);
1139
0
      out += 6;
1140
0
      while (out[-1] == '0') --out;
1141
0
      *out = 0;
1142
0
      return static_cast<size_t>(out - buffer);
1143
0
  }
1144
0
  assert(exp < -4 || exp >= 6);
1145
0
  out[0] = digits[0];
1146
0
  assert(out[1] == '.');
1147
0
  out += 2;
1148
0
  memcpy(out, &digits[1], 5), out += 5;
1149
0
  while (out[-1] == '0') --out;
1150
0
  if (out[-1] == '.') --out;
1151
0
  *out++ = 'e';
1152
0
  if (exp > 0) {
1153
0
    *out++ = '+';
1154
0
  } else {
1155
0
    *out++ = '-';
1156
0
    exp = -exp;
1157
0
  }
1158
0
  if (exp > 99) {
1159
0
    int dig1 = exp / 100;
1160
0
    exp -= dig1 * 100;
1161
0
    *out++ = '0' + static_cast<char>(dig1);
1162
0
  }
1163
0
  PutTwoDigits(static_cast<uint32_t>(exp), out);
1164
0
  out += 2;
1165
0
  *out = 0;
1166
0
  return static_cast<size_t>(out - buffer);
1167
0
}
1168
1169
namespace {
1170
// Represents integer values of digits.
1171
// Uses 36 to indicate an invalid character since we support
1172
// bases up to 36.
1173
static constexpr std::array<int8_t, 256> kAsciiToInt = {
1174
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,  // 16 36s.
1175
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1176
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 0,  1,  2,  3,  4,  5,
1177
    6,  7,  8,  9,  36, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17,
1178
    18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
1179
    36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
1180
    24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 36,
1181
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1182
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1183
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1184
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1185
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1186
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
1187
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36};
1188
1189
// Parse the sign and optional hex or oct prefix in text.
1190
inline bool safe_parse_sign_and_base(
1191
    absl::string_view* absl_nonnull text /*inout*/,
1192
    int* absl_nonnull base_ptr /*inout*/,
1193
0
    bool* absl_nonnull negative_ptr /*output*/) {
1194
0
  if (text->data() == nullptr) {
1195
0
    return false;
1196
0
  }
1197
1198
0
  const char* start = text->data();
1199
0
  const char* end = start + text->size();
1200
0
  int base = *base_ptr;
1201
1202
  // Consume whitespace.
1203
0
  while (start < end &&
1204
0
         absl::ascii_isspace(static_cast<unsigned char>(start[0]))) {
1205
0
    ++start;
1206
0
  }
1207
0
  while (start < end &&
1208
0
         absl::ascii_isspace(static_cast<unsigned char>(end[-1]))) {
1209
0
    --end;
1210
0
  }
1211
0
  if (start >= end) {
1212
0
    return false;
1213
0
  }
1214
1215
  // Consume sign.
1216
0
  *negative_ptr = (start[0] == '-');
1217
0
  if (*negative_ptr || start[0] == '+') {
1218
0
    ++start;
1219
0
    if (start >= end) {
1220
0
      return false;
1221
0
    }
1222
0
  }
1223
1224
  // Consume base-dependent prefix.
1225
  //  base 0: "0x" -> base 16, "0" -> base 8, default -> base 10
1226
  //  base 16: "0x" -> base 16
1227
  // Also validate the base.
1228
0
  if (base == 0) {
1229
0
    if (end - start >= 2 && start[0] == '0' &&
1230
0
        (start[1] == 'x' || start[1] == 'X')) {
1231
0
      base = 16;
1232
0
      start += 2;
1233
0
      if (start >= end) {
1234
        // "0x" with no digits after is invalid.
1235
0
        return false;
1236
0
      }
1237
0
    } else if (end - start >= 1 && start[0] == '0') {
1238
0
      base = 8;
1239
0
      start += 1;
1240
0
    } else {
1241
0
      base = 10;
1242
0
    }
1243
0
  } else if (base == 16) {
1244
0
    if (end - start >= 2 && start[0] == '0' &&
1245
0
        (start[1] == 'x' || start[1] == 'X')) {
1246
0
      start += 2;
1247
0
      if (start >= end) {
1248
        // "0x" with no digits after is invalid.
1249
0
        return false;
1250
0
      }
1251
0
    }
1252
0
  } else if (base >= 2 && base <= 36) {
1253
    // okay
1254
0
  } else {
1255
0
    return false;
1256
0
  }
1257
0
  *text = absl::string_view(start, static_cast<size_t>(end - start));
1258
0
  *base_ptr = base;
1259
0
  return true;
1260
0
}
1261
1262
// Consume digits.
1263
//
1264
// The classic loop:
1265
//
1266
//   for each digit
1267
//     value = value * base + digit
1268
//   value *= sign
1269
//
1270
// The classic loop needs overflow checking.  It also fails on the most
1271
// negative integer, -2147483648 in 32-bit two's complement representation.
1272
//
1273
// My improved loop:
1274
//
1275
//  if (!negative)
1276
//    for each digit
1277
//      value = value * base
1278
//      value = value + digit
1279
//  else
1280
//    for each digit
1281
//      value = value * base
1282
//      value = value - digit
1283
//
1284
// Overflow checking becomes simple.
1285
1286
// Lookup tables per IntType:
1287
// vmax/base and vmin/base are precomputed because division costs at least 8ns.
1288
// TODO(junyer): Doing this per base instead (i.e. an array of structs, not a
1289
// struct of arrays) would probably be better in terms of d-cache for the most
1290
// commonly used bases.
1291
template <typename IntType>
1292
struct LookupTables {
1293
  ABSL_CONST_INIT static const IntType kVmaxOverBase[];
1294
  ABSL_CONST_INIT static const IntType kVminOverBase[];
1295
};
1296
1297
// An array initializer macro for X/base where base in [0, 36].
1298
// However, note that lookups for base in [0, 1] should never happen because
1299
// base has been validated to be in [2, 36] by safe_parse_sign_and_base().
1300
#define X_OVER_BASE_INITIALIZER(X)                                        \
1301
  {                                                                       \
1302
    0, 0, X / 2, X / 3, X / 4, X / 5, X / 6, X / 7, X / 8, X / 9, X / 10, \
1303
        X / 11, X / 12, X / 13, X / 14, X / 15, X / 16, X / 17, X / 18,   \
1304
        X / 19, X / 20, X / 21, X / 22, X / 23, X / 24, X / 25, X / 26,   \
1305
        X / 27, X / 28, X / 29, X / 30, X / 31, X / 32, X / 33, X / 34,   \
1306
        X / 35, X / 36,                                                   \
1307
  }
1308
1309
// This kVmaxOverBase is generated with
1310
//  for (int base = 2; base < 37; ++base) {
1311
//    absl::uint128 max = std::numeric_limits<absl::uint128>::max();
1312
//    auto result = max / base;
1313
//    std::cout << "    MakeUint128(" << absl::Uint128High64(result) << "u, "
1314
//              << absl::Uint128Low64(result) << "u),\n";
1315
//  }
1316
// See https://godbolt.org/z/aneYsb
1317
//
1318
// uint128& operator/=(uint128) is not constexpr, so hardcode the resulting
1319
// array to avoid a static initializer.
1320
template <>
1321
ABSL_CONST_INIT const uint128 LookupTables<uint128>::kVmaxOverBase[] = {
1322
    0,
1323
    0,
1324
    MakeUint128(9223372036854775807u, 18446744073709551615u),
1325
    MakeUint128(6148914691236517205u, 6148914691236517205u),
1326
    MakeUint128(4611686018427387903u, 18446744073709551615u),
1327
    MakeUint128(3689348814741910323u, 3689348814741910323u),
1328
    MakeUint128(3074457345618258602u, 12297829382473034410u),
1329
    MakeUint128(2635249153387078802u, 5270498306774157604u),
1330
    MakeUint128(2305843009213693951u, 18446744073709551615u),
1331
    MakeUint128(2049638230412172401u, 14347467612885206812u),
1332
    MakeUint128(1844674407370955161u, 11068046444225730969u),
1333
    MakeUint128(1676976733973595601u, 8384883669867978007u),
1334
    MakeUint128(1537228672809129301u, 6148914691236517205u),
1335
    MakeUint128(1418980313362273201u, 4256940940086819603u),
1336
    MakeUint128(1317624576693539401u, 2635249153387078802u),
1337
    MakeUint128(1229782938247303441u, 1229782938247303441u),
1338
    MakeUint128(1152921504606846975u, 18446744073709551615u),
1339
    MakeUint128(1085102592571150095u, 1085102592571150095u),
1340
    MakeUint128(1024819115206086200u, 16397105843297379214u),
1341
    MakeUint128(970881267037344821u, 16504981539634861972u),
1342
    MakeUint128(922337203685477580u, 14757395258967641292u),
1343
    MakeUint128(878416384462359600u, 14054662151397753612u),
1344
    MakeUint128(838488366986797800u, 13415813871788764811u),
1345
    MakeUint128(802032351030850070u, 4812194106185100421u),
1346
    MakeUint128(768614336404564650u, 12297829382473034410u),
1347
    MakeUint128(737869762948382064u, 11805916207174113034u),
1348
    MakeUint128(709490156681136600u, 11351842506898185609u),
1349
    MakeUint128(683212743470724133u, 17080318586768103348u),
1350
    MakeUint128(658812288346769700u, 10540996613548315209u),
1351
    MakeUint128(636094623231363848u, 15266270957552732371u),
1352
    MakeUint128(614891469123651720u, 9838263505978427528u),
1353
    MakeUint128(595056260442243600u, 9520900167075897608u),
1354
    MakeUint128(576460752303423487u, 18446744073709551615u),
1355
    MakeUint128(558992244657865200u, 8943875914525843207u),
1356
    MakeUint128(542551296285575047u, 9765923333140350855u),
1357
    MakeUint128(527049830677415760u, 8432797290838652167u),
1358
    MakeUint128(512409557603043100u, 8198552921648689607u),
1359
};
1360
1361
// This kVmaxOverBase generated with
1362
//   for (int base = 2; base < 37; ++base) {
1363
//    absl::int128 max = std::numeric_limits<absl::int128>::max();
1364
//    auto result = max / base;
1365
//    std::cout << "\tMakeInt128(" << absl::Int128High64(result) << ", "
1366
//              << absl::Int128Low64(result) << "u),\n";
1367
//  }
1368
// See https://godbolt.org/z/7djYWz
1369
//
1370
// int128& operator/=(int128) is not constexpr, so hardcode the resulting array
1371
// to avoid a static initializer.
1372
template <>
1373
ABSL_CONST_INIT const int128 LookupTables<int128>::kVmaxOverBase[] = {
1374
    0,
1375
    0,
1376
    MakeInt128(4611686018427387903, 18446744073709551615u),
1377
    MakeInt128(3074457345618258602, 12297829382473034410u),
1378
    MakeInt128(2305843009213693951, 18446744073709551615u),
1379
    MakeInt128(1844674407370955161, 11068046444225730969u),
1380
    MakeInt128(1537228672809129301, 6148914691236517205u),
1381
    MakeInt128(1317624576693539401, 2635249153387078802u),
1382
    MakeInt128(1152921504606846975, 18446744073709551615u),
1383
    MakeInt128(1024819115206086200, 16397105843297379214u),
1384
    MakeInt128(922337203685477580, 14757395258967641292u),
1385
    MakeInt128(838488366986797800, 13415813871788764811u),
1386
    MakeInt128(768614336404564650, 12297829382473034410u),
1387
    MakeInt128(709490156681136600, 11351842506898185609u),
1388
    MakeInt128(658812288346769700, 10540996613548315209u),
1389
    MakeInt128(614891469123651720, 9838263505978427528u),
1390
    MakeInt128(576460752303423487, 18446744073709551615u),
1391
    MakeInt128(542551296285575047, 9765923333140350855u),
1392
    MakeInt128(512409557603043100, 8198552921648689607u),
1393
    MakeInt128(485440633518672410, 17475862806672206794u),
1394
    MakeInt128(461168601842738790, 7378697629483820646u),
1395
    MakeInt128(439208192231179800, 7027331075698876806u),
1396
    MakeInt128(419244183493398900, 6707906935894382405u),
1397
    MakeInt128(401016175515425035, 2406097053092550210u),
1398
    MakeInt128(384307168202282325, 6148914691236517205u),
1399
    MakeInt128(368934881474191032, 5902958103587056517u),
1400
    MakeInt128(354745078340568300, 5675921253449092804u),
1401
    MakeInt128(341606371735362066, 17763531330238827482u),
1402
    MakeInt128(329406144173384850, 5270498306774157604u),
1403
    MakeInt128(318047311615681924, 7633135478776366185u),
1404
    MakeInt128(307445734561825860, 4919131752989213764u),
1405
    MakeInt128(297528130221121800, 4760450083537948804u),
1406
    MakeInt128(288230376151711743, 18446744073709551615u),
1407
    MakeInt128(279496122328932600, 4471937957262921603u),
1408
    MakeInt128(271275648142787523, 14106333703424951235u),
1409
    MakeInt128(263524915338707880, 4216398645419326083u),
1410
    MakeInt128(256204778801521550, 4099276460824344803u),
1411
};
1412
1413
// This kVminOverBase generated with
1414
//  for (int base = 2; base < 37; ++base) {
1415
//    absl::int128 min = std::numeric_limits<absl::int128>::min();
1416
//    auto result = min / base;
1417
//    std::cout << "\tMakeInt128(" << absl::Int128High64(result) << ", "
1418
//              << absl::Int128Low64(result) << "u),\n";
1419
//  }
1420
//
1421
// See https://godbolt.org/z/7djYWz
1422
//
1423
// int128& operator/=(int128) is not constexpr, so hardcode the resulting array
1424
// to avoid a static initializer.
1425
template <>
1426
ABSL_CONST_INIT const int128 LookupTables<int128>::kVminOverBase[] = {
1427
    0,
1428
    0,
1429
    MakeInt128(-4611686018427387904, 0u),
1430
    MakeInt128(-3074457345618258603, 6148914691236517206u),
1431
    MakeInt128(-2305843009213693952, 0u),
1432
    MakeInt128(-1844674407370955162, 7378697629483820647u),
1433
    MakeInt128(-1537228672809129302, 12297829382473034411u),
1434
    MakeInt128(-1317624576693539402, 15811494920322472814u),
1435
    MakeInt128(-1152921504606846976, 0u),
1436
    MakeInt128(-1024819115206086201, 2049638230412172402u),
1437
    MakeInt128(-922337203685477581, 3689348814741910324u),
1438
    MakeInt128(-838488366986797801, 5030930201920786805u),
1439
    MakeInt128(-768614336404564651, 6148914691236517206u),
1440
    MakeInt128(-709490156681136601, 7094901566811366007u),
1441
    MakeInt128(-658812288346769701, 7905747460161236407u),
1442
    MakeInt128(-614891469123651721, 8608480567731124088u),
1443
    MakeInt128(-576460752303423488, 0u),
1444
    MakeInt128(-542551296285575048, 8680820740569200761u),
1445
    MakeInt128(-512409557603043101, 10248191152060862009u),
1446
    MakeInt128(-485440633518672411, 970881267037344822u),
1447
    MakeInt128(-461168601842738791, 11068046444225730970u),
1448
    MakeInt128(-439208192231179801, 11419412998010674810u),
1449
    MakeInt128(-419244183493398901, 11738837137815169211u),
1450
    MakeInt128(-401016175515425036, 16040647020617001406u),
1451
    MakeInt128(-384307168202282326, 12297829382473034411u),
1452
    MakeInt128(-368934881474191033, 12543785970122495099u),
1453
    MakeInt128(-354745078340568301, 12770822820260458812u),
1454
    MakeInt128(-341606371735362067, 683212743470724134u),
1455
    MakeInt128(-329406144173384851, 13176245766935394012u),
1456
    MakeInt128(-318047311615681925, 10813608594933185431u),
1457
    MakeInt128(-307445734561825861, 13527612320720337852u),
1458
    MakeInt128(-297528130221121801, 13686293990171602812u),
1459
    MakeInt128(-288230376151711744, 0u),
1460
    MakeInt128(-279496122328932601, 13974806116446630013u),
1461
    MakeInt128(-271275648142787524, 4340410370284600381u),
1462
    MakeInt128(-263524915338707881, 14230345428290225533u),
1463
    MakeInt128(-256204778801521551, 14347467612885206813u),
1464
};
1465
1466
template <typename IntType>
1467
ABSL_CONST_INIT const IntType LookupTables<IntType>::kVmaxOverBase[] =
1468
    X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::max());
1469
1470
template <typename IntType>
1471
ABSL_CONST_INIT const IntType LookupTables<IntType>::kVminOverBase[] =
1472
    X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::min());
1473
1474
#undef X_OVER_BASE_INITIALIZER
1475
1476
template <typename IntType>
1477
inline bool safe_parse_positive_int(absl::string_view text, int base,
1478
0
                                    IntType* absl_nonnull value_p) {
1479
0
  IntType value = 0;
1480
0
  const IntType vmax = std::numeric_limits<IntType>::max();
1481
0
  assert(vmax > 0);
1482
0
  assert(base >= 0);
1483
0
  const IntType base_inttype = static_cast<IntType>(base);
1484
0
  assert(vmax >= base_inttype);
1485
0
  const IntType vmax_over_base = LookupTables<IntType>::kVmaxOverBase[base];
1486
0
  assert(base < 2 ||
1487
0
         std::numeric_limits<IntType>::max() / base_inttype == vmax_over_base);
1488
0
  const char* start = text.data();
1489
0
  const char* end = start + text.size();
1490
  // loop over digits
1491
0
  for (; start < end; ++start) {
1492
0
    unsigned char c = static_cast<unsigned char>(start[0]);
1493
0
    IntType digit = static_cast<IntType>(kAsciiToInt[c]);
1494
0
    if (digit >= base_inttype) {
1495
0
      *value_p = value;
1496
0
      return false;
1497
0
    }
1498
0
    if (value > vmax_over_base) {
1499
0
      *value_p = vmax;
1500
0
      return false;
1501
0
    }
1502
0
    value *= base_inttype;
1503
0
    if (value > vmax - digit) {
1504
0
      *value_p = vmax;
1505
0
      return false;
1506
0
    }
1507
0
    value += digit;
1508
0
  }
1509
0
  *value_p = value;
1510
0
  return true;
1511
0
}
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<signed char>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, signed char*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<short>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, short*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<int>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, int*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<long>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, long*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<absl::int128>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, absl::int128*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<unsigned char>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, unsigned char*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<unsigned short>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, unsigned short*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<unsigned int>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, unsigned int*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<unsigned long>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, unsigned long*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_positive_int<absl::uint128>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, absl::uint128*)
1512
1513
template <typename IntType>
1514
inline bool safe_parse_negative_int(absl::string_view text, int base,
1515
0
                                    IntType* absl_nonnull value_p) {
1516
0
  IntType value = 0;
1517
0
  const IntType vmin = std::numeric_limits<IntType>::min();
1518
0
  assert(vmin < 0);
1519
0
  assert(vmin <= 0 - base);
1520
0
  IntType vmin_over_base = LookupTables<IntType>::kVminOverBase[base];
1521
0
  assert(base < 2 ||
1522
0
         std::numeric_limits<IntType>::min() / base == vmin_over_base);
1523
  // 2003 c++ standard [expr.mul]
1524
  // "... the sign of the remainder is implementation-defined."
1525
  // Although (vmin/base)*base + vmin%base is always vmin.
1526
  // 2011 c++ standard tightens the spec but we cannot rely on it.
1527
  // TODO(junyer): Handle this in the lookup table generation.
1528
0
  if (vmin % base > 0) {
1529
0
    vmin_over_base += 1;
1530
0
  }
1531
0
  const char* start = text.data();
1532
0
  const char* end = start + text.size();
1533
  // loop over digits
1534
0
  for (; start < end; ++start) {
1535
0
    unsigned char c = static_cast<unsigned char>(start[0]);
1536
0
    int digit = kAsciiToInt[c];
1537
0
    if (digit >= base) {
1538
0
      *value_p = value;
1539
0
      return false;
1540
0
    }
1541
0
    if (value < vmin_over_base) {
1542
0
      *value_p = vmin;
1543
0
      return false;
1544
0
    }
1545
0
    value *= base;
1546
0
    if (value < vmin + digit) {
1547
0
      *value_p = vmin;
1548
0
      return false;
1549
0
    }
1550
0
    value -= digit;
1551
0
  }
1552
0
  *value_p = value;
1553
0
  return true;
1554
0
}
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_negative_int<signed char>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, signed char*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_negative_int<short>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, short*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_negative_int<int>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, int*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_negative_int<long>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, long*)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_parse_negative_int<absl::int128>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int, absl::int128*)
1555
1556
// Input format based on POSIX.1-2008 strtol
1557
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
1558
template <typename IntType>
1559
inline bool safe_int_internal(absl::string_view text,
1560
0
                              IntType* absl_nonnull value_p, int base) {
1561
0
  *value_p = 0;
1562
0
  bool negative;
1563
0
  if (!safe_parse_sign_and_base(&text, &base, &negative)) {
1564
0
    return false;
1565
0
  }
1566
0
  if (!negative) {
1567
0
    return safe_parse_positive_int(text, base, value_p);
1568
0
  } else {
1569
0
    return safe_parse_negative_int(text, base, value_p);
1570
0
  }
1571
0
}
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_int_internal<signed char>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, signed char*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_int_internal<short>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, short*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_int_internal<int>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, int*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_int_internal<long>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, long*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_int_internal<absl::int128>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, absl::int128*, int)
1572
1573
template <typename IntType>
1574
inline bool safe_uint_internal(absl::string_view text,
1575
0
                               IntType* absl_nonnull value_p, int base) {
1576
0
  *value_p = 0;
1577
0
  bool negative;
1578
0
  if (!safe_parse_sign_and_base(&text, &base, &negative) || negative) {
1579
0
    return false;
1580
0
  }
1581
0
  return safe_parse_positive_int(text, base, value_p);
1582
0
}
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_uint_internal<unsigned char>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, unsigned char*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_uint_internal<unsigned short>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, unsigned short*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_uint_internal<unsigned int>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, unsigned int*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_uint_internal<unsigned long>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, unsigned long*, int)
Unexecuted instantiation: numbers.cc:bool absl::(anonymous namespace)::safe_uint_internal<absl::uint128>(std::__1::basic_string_view<char, std::__1::char_traits<char> >, absl::uint128*, int)
1583
}  // anonymous namespace
1584
1585
namespace numbers_internal {
1586
1587
// Digit conversion.
1588
ABSL_CONST_INIT ABSL_DLL const char kHexChar[] =
1589
    "0123456789abcdef";
1590
1591
ABSL_CONST_INIT ABSL_DLL const char kHexTable[513] =
1592
    "000102030405060708090a0b0c0d0e0f"
1593
    "101112131415161718191a1b1c1d1e1f"
1594
    "202122232425262728292a2b2c2d2e2f"
1595
    "303132333435363738393a3b3c3d3e3f"
1596
    "404142434445464748494a4b4c4d4e4f"
1597
    "505152535455565758595a5b5c5d5e5f"
1598
    "606162636465666768696a6b6c6d6e6f"
1599
    "707172737475767778797a7b7c7d7e7f"
1600
    "808182838485868788898a8b8c8d8e8f"
1601
    "909192939495969798999a9b9c9d9e9f"
1602
    "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
1603
    "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
1604
    "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
1605
    "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
1606
    "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
1607
    "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff";
1608
1609
bool safe_strto8_base(absl::string_view text, int8_t* absl_nonnull value,
1610
0
                      int base) {
1611
0
  return safe_int_internal<int8_t>(text, value, base);
1612
0
}
1613
1614
bool safe_strto16_base(absl::string_view text, int16_t* absl_nonnull value,
1615
0
                       int base) {
1616
0
  return safe_int_internal<int16_t>(text, value, base);
1617
0
}
1618
1619
bool safe_strto32_base(absl::string_view text, int32_t* absl_nonnull value,
1620
0
                       int base) {
1621
0
  return safe_int_internal<int32_t>(text, value, base);
1622
0
}
1623
1624
bool safe_strto64_base(absl::string_view text, int64_t* absl_nonnull value,
1625
0
                       int base) {
1626
0
  return safe_int_internal<int64_t>(text, value, base);
1627
0
}
1628
1629
bool safe_strto128_base(absl::string_view text, int128* absl_nonnull value,
1630
0
                        int base) {
1631
0
  return safe_int_internal<absl::int128>(text, value, base);
1632
0
}
1633
1634
bool safe_strtou8_base(absl::string_view text, uint8_t* absl_nonnull value,
1635
0
                       int base) {
1636
0
  return safe_uint_internal<uint8_t>(text, value, base);
1637
0
}
1638
1639
bool safe_strtou16_base(absl::string_view text, uint16_t* absl_nonnull value,
1640
0
                        int base) {
1641
0
  return safe_uint_internal<uint16_t>(text, value, base);
1642
0
}
1643
1644
bool safe_strtou32_base(absl::string_view text, uint32_t* absl_nonnull value,
1645
0
                        int base) {
1646
0
  return safe_uint_internal<uint32_t>(text, value, base);
1647
0
}
1648
1649
bool safe_strtou64_base(absl::string_view text, uint64_t* absl_nonnull value,
1650
0
                        int base) {
1651
0
  return safe_uint_internal<uint64_t>(text, value, base);
1652
0
}
1653
1654
bool safe_strtou128_base(absl::string_view text, uint128* absl_nonnull value,
1655
0
                         int base) {
1656
0
  return safe_uint_internal<absl::uint128>(text, value, base);
1657
0
}
1658
1659
}  // namespace numbers_internal
1660
ABSL_NAMESPACE_END
1661
}  // namespace absl