Coverage Report

Created: 2025-07-11 06:37

/src/abseil-cpp/absl/strings/numbers.cc
Line
Count
Source (jump to first uncovered line)
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 <cmath>   // for HUGE_VAL
25
#include <cstdint>
26
#include <cstdio>
27
#include <cstdlib>
28
#include <cstring>
29
#include <iterator>
30
#include <limits>
31
#include <system_error>  // NOLINT(build/c++11)
32
#include <utility>
33
34
#include "absl/base/attributes.h"
35
#include "absl/base/config.h"
36
#include "absl/base/internal/endian.h"
37
#include "absl/base/internal/raw_logging.h"
38
#include "absl/base/nullability.h"
39
#include "absl/base/optimization.h"
40
#include "absl/numeric/bits.h"
41
#include "absl/numeric/int128.h"
42
#include "absl/strings/ascii.h"
43
#include "absl/strings/charconv.h"
44
#include "absl/strings/match.h"
45
#include "absl/strings/string_view.h"
46
47
namespace absl {
48
ABSL_NAMESPACE_BEGIN
49
50
0
bool SimpleAtof(absl::string_view str, float* absl_nonnull out) {
51
0
  *out = 0.0;
52
0
  str = StripAsciiWhitespace(str);
53
  // std::from_chars doesn't accept an initial +, but SimpleAtof does, so if one
54
  // is present, skip it, while avoiding accepting "+-0" as valid.
55
0
  if (!str.empty() && str[0] == '+') {
56
0
    str.remove_prefix(1);
57
0
    if (!str.empty() && str[0] == '-') {
58
0
      return false;
59
0
    }
60
0
  }
61
0
  auto result = absl::from_chars(str.data(), str.data() + str.size(), *out);
62
0
  if (result.ec == std::errc::invalid_argument) {
63
0
    return false;
64
0
  }
65
0
  if (result.ptr != str.data() + str.size()) {
66
    // not all non-whitespace characters consumed
67
0
    return false;
68
0
  }
69
  // from_chars() with DR 3081's current wording will return max() on
70
  // overflow.  SimpleAtof returns infinity instead.
71
0
  if (result.ec == std::errc::result_out_of_range) {
72
0
    if (*out > 1.0) {
73
0
      *out = std::numeric_limits<float>::infinity();
74
0
    } else if (*out < -1.0) {
75
0
      *out = -std::numeric_limits<float>::infinity();
76
0
    }
77
0
  }
78
0
  return true;
79
0
}
80
81
0
bool SimpleAtod(absl::string_view str, double* absl_nonnull out) {
82
0
  *out = 0.0;
83
0
  str = StripAsciiWhitespace(str);
84
  // std::from_chars doesn't accept an initial +, but SimpleAtod does, so if one
85
  // is present, skip it, while avoiding accepting "+-0" as valid.
86
0
  if (!str.empty() && str[0] == '+') {
87
0
    str.remove_prefix(1);
88
0
    if (!str.empty() && str[0] == '-') {
89
0
      return false;
90
0
    }
91
0
  }
92
0
  auto result = absl::from_chars(str.data(), str.data() + str.size(), *out);
93
0
  if (result.ec == std::errc::invalid_argument) {
94
0
    return false;
95
0
  }
96
0
  if (result.ptr != str.data() + str.size()) {
97
    // not all non-whitespace characters consumed
98
0
    return false;
99
0
  }
100
  // from_chars() with DR 3081's current wording will return max() on
101
  // overflow.  SimpleAtod returns infinity instead.
102
0
  if (result.ec == std::errc::result_out_of_range) {
103
0
    if (*out > 1.0) {
104
0
      *out = std::numeric_limits<double>::infinity();
105
0
    } else if (*out < -1.0) {
106
0
      *out = -std::numeric_limits<double>::infinity();
107
0
    }
108
0
  }
109
0
  return true;
110
0
}
111
112
0
bool SimpleAtob(absl::string_view str, bool* absl_nonnull out) {
113
0
  ABSL_RAW_CHECK(out != nullptr, "Output pointer must not be nullptr.");
114
0
  if (EqualsIgnoreCase(str, "true") || EqualsIgnoreCase(str, "t") ||
115
0
      EqualsIgnoreCase(str, "yes") || EqualsIgnoreCase(str, "y") ||
116
0
      EqualsIgnoreCase(str, "1")) {
117
0
    *out = true;
118
0
    return true;
119
0
  }
120
0
  if (EqualsIgnoreCase(str, "false") || EqualsIgnoreCase(str, "f") ||
121
0
      EqualsIgnoreCase(str, "no") || EqualsIgnoreCase(str, "n") ||
122
0
      EqualsIgnoreCase(str, "0")) {
123
0
    *out = false;
124
0
    return true;
125
0
  }
126
0
  return false;
127
0
}
128
129
// ----------------------------------------------------------------------
130
// FastIntToBuffer() overloads
131
//
132
// Like the Fast*ToBuffer() functions above, these are intended for speed.
133
// Unlike the Fast*ToBuffer() functions, however, these functions write
134
// their output to the beginning of the buffer.  The caller is responsible
135
// for ensuring that the buffer has enough space to hold the output.
136
//
137
// Returns a pointer to the end of the string (i.e. the null character
138
// terminating the string).
139
// ----------------------------------------------------------------------
140
141
namespace {
142
143
// Various routines to encode integers to strings.
144
145
// We split data encodings into a group of 2 digits, 4 digits, 8 digits as
146
// it's easier to combine powers of two into scalar arithmetic.
147
148
// Previous implementation used a lookup table of 200 bytes for every 2 bytes
149
// and it was memory bound, any L1 cache miss would result in a much slower
150
// result. When benchmarking with a cache eviction rate of several percent,
151
// this implementation proved to be better.
152
153
// These constants represent '00', '0000' and '00000000' as ascii strings in
154
// integers. We can add these numbers if we encode to bytes from 0 to 9. as
155
// 'i' = '0' + i for 0 <= i <= 9.
156
constexpr uint32_t kTwoZeroBytes = 0x0101 * '0';
157
constexpr uint64_t kFourZeroBytes = 0x01010101 * '0';
158
constexpr uint64_t kEightZeroBytes = 0x0101010101010101ull * '0';
159
160
// * 103 / 1024 is a division by 10 for values from 0 to 99. It's also a
161
// division of a structure [k takes 2 bytes][m takes 2 bytes], then * 103 / 1024
162
// will be [k / 10][m / 10]. It allows parallel division.
163
constexpr uint64_t kDivisionBy10Mul = 103u;
164
constexpr uint64_t kDivisionBy10Div = 1 << 10;
165
166
// * 10486 / 1048576 is a division by 100 for values from 0 to 9999.
167
constexpr uint64_t kDivisionBy100Mul = 10486u;
168
constexpr uint64_t kDivisionBy100Div = 1 << 20;
169
170
// Encode functions write the ASCII output of input `n` to `out_str`.
171
0
inline char* EncodeHundred(uint32_t n, char* absl_nonnull out_str) {
172
0
  int num_digits = static_cast<int>(n - 10) >> 8;
173
0
  uint32_t div10 = (n * kDivisionBy10Mul) / kDivisionBy10Div;
174
0
  uint32_t mod10 = n - 10u * div10;
175
0
  uint32_t base = kTwoZeroBytes + div10 + (mod10 << 8);
176
0
  base >>= num_digits & 8;
177
0
  little_endian::Store16(out_str, static_cast<uint16_t>(base));
178
0
  return out_str + 2 + num_digits;
179
0
}
180
181
0
inline char* EncodeTenThousand(uint32_t n, char* absl_nonnull out_str) {
182
  // We split lower 2 digits and upper 2 digits of n into 2 byte consecutive
183
  // blocks. 123 ->  [\0\1][\0\23]. We divide by 10 both blocks
184
  // (it's 1 division + zeroing upper bits), and compute modulo 10 as well "in
185
  // parallel". Then we combine both results to have both ASCII digits,
186
  // strip trailing zeros, add ASCII '0000' and return.
187
0
  uint32_t div100 = (n * kDivisionBy100Mul) / kDivisionBy100Div;
188
0
  uint32_t mod100 = n - 100ull * div100;
189
0
  uint32_t hundreds = (mod100 << 16) + div100;
190
0
  uint32_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div;
191
0
  tens &= (0xFull << 16) | 0xFull;
192
0
  tens += (hundreds - 10ull * tens) << 8;
193
0
  ABSL_ASSUME(tens != 0);
194
  // The result can contain trailing zero bits, we need to strip them to a first
195
  // significant byte in a final representation. For example, for n = 123, we
196
  // have tens to have representation \0\1\2\3. We do `& -8` to round
197
  // to a multiple to 8 to strip zero bytes, not all zero bits.
198
  // countr_zero to help.
199
  // 0 minus 8 to make MSVC happy.
200
0
  uint32_t zeroes = static_cast<uint32_t>(absl::countr_zero(tens)) & (0 - 8u);
201
0
  tens += kFourZeroBytes;
202
0
  tens >>= zeroes;
203
0
  little_endian::Store32(out_str, tens);
204
0
  return out_str + sizeof(tens) - zeroes / 8;
205
0
}
206
207
// Helper function to produce an ASCII representation of `i`.
208
//
209
// Function returns an 8-byte integer which when summed with `kEightZeroBytes`,
210
// can be treated as a printable buffer with ascii representation of `i`,
211
// possibly with leading zeros.
212
//
213
// Example:
214
//
215
//  uint64_t buffer = PrepareEightDigits(102030) + kEightZeroBytes;
216
//  char* ascii = reinterpret_cast<char*>(&buffer);
217
//  // Note two leading zeros:
218
//  EXPECT_EQ(absl::string_view(ascii, 8), "00102030");
219
//
220
// Pre-condition: `i` must be less than 100000000.
221
870
inline uint64_t PrepareEightDigits(uint32_t i) {
222
870
  ABSL_ASSUME(i < 10000'0000);
223
  // Prepare 2 blocks of 4 digits "in parallel".
224
870
  uint32_t hi = i / 10000;
225
870
  uint32_t lo = i % 10000;
226
870
  uint64_t merged = hi | (uint64_t{lo} << 32);
227
870
  uint64_t div100 = ((merged * kDivisionBy100Mul) / kDivisionBy100Div) &
228
870
                    ((0x7Full << 32) | 0x7Full);
229
870
  uint64_t mod100 = merged - 100ull * div100;
230
870
  uint64_t hundreds = (mod100 << 16) + div100;
231
870
  uint64_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div;
232
870
  tens &= (0xFull << 48) | (0xFull << 32) | (0xFull << 16) | 0xFull;
233
870
  tens += (hundreds - 10ull * tens) << 8;
234
870
  return tens;
235
870
}
236
237
inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* absl_nonnull EncodeFullU32(
238
16.1k
    uint32_t n, char* absl_nonnull out_str) {
239
16.1k
  if (n < 10) {
240
15.2k
    *out_str = static_cast<char>('0' + n);
241
15.2k
    return out_str + 1;
242
15.2k
  }
243
870
  if (n < 100'000'000) {
244
870
    uint64_t bottom = PrepareEightDigits(n);
245
870
    ABSL_ASSUME(bottom != 0);
246
    // 0 minus 8 to make MSVC happy.
247
870
    uint32_t zeroes =
248
870
        static_cast<uint32_t>(absl::countr_zero(bottom)) & (0 - 8u);
249
870
    little_endian::Store64(out_str, (bottom + kEightZeroBytes) >> zeroes);
250
870
    return out_str + sizeof(bottom) - zeroes / 8;
251
870
  }
252
0
  uint32_t div08 = n / 100'000'000;
253
0
  uint32_t mod08 = n % 100'000'000;
254
0
  uint64_t bottom = PrepareEightDigits(mod08) + kEightZeroBytes;
255
0
  out_str = EncodeHundred(div08, out_str);
256
0
  little_endian::Store64(out_str, bottom);
257
0
  return out_str + sizeof(bottom);
258
870
}
259
260
inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* EncodeFullU64(uint64_t i,
261
0
                                                        char* buffer) {
262
0
  if (i <= std::numeric_limits<uint32_t>::max()) {
263
0
    return EncodeFullU32(static_cast<uint32_t>(i), buffer);
264
0
  }
265
0
  uint32_t mod08;
266
0
  if (i < 1'0000'0000'0000'0000ull) {
267
0
    uint32_t div08 = static_cast<uint32_t>(i / 100'000'000ull);
268
0
    mod08 =  static_cast<uint32_t>(i % 100'000'000ull);
269
0
    buffer = EncodeFullU32(div08, buffer);
270
0
  } else {
271
0
    uint64_t div08 = i / 100'000'000ull;
272
0
    mod08 =  static_cast<uint32_t>(i % 100'000'000ull);
273
0
    uint32_t div016 = static_cast<uint32_t>(div08 / 100'000'000ull);
274
0
    uint32_t div08mod08 = static_cast<uint32_t>(div08 % 100'000'000ull);
275
0
    uint64_t mid_result = PrepareEightDigits(div08mod08) + kEightZeroBytes;
276
0
    buffer = EncodeTenThousand(div016, buffer);
277
0
    little_endian::Store64(buffer, mid_result);
278
0
    buffer += sizeof(mid_result);
279
0
  }
280
0
  uint64_t mod_result = PrepareEightDigits(mod08) + kEightZeroBytes;
281
0
  little_endian::Store64(buffer, mod_result);
282
0
  return buffer + sizeof(mod_result);
283
0
}
284
285
}  // namespace
286
287
0
void numbers_internal::PutTwoDigits(uint32_t i, char* absl_nonnull buf) {
288
0
  assert(i < 100);
289
0
  uint32_t base = kTwoZeroBytes;
290
0
  uint32_t div10 = (i * kDivisionBy10Mul) / kDivisionBy10Div;
291
0
  uint32_t mod10 = i - 10u * div10;
292
0
  base += div10 + (mod10 << 8);
293
0
  little_endian::Store16(buf, static_cast<uint16_t>(base));
294
0
}
295
296
char* absl_nonnull numbers_internal::FastIntToBuffer(
297
0
    uint32_t n, char* absl_nonnull out_str) {
298
0
  out_str = EncodeFullU32(n, out_str);
299
0
  *out_str = '\0';
300
0
  return out_str;
301
0
}
302
303
char* absl_nonnull numbers_internal::FastIntToBuffer(
304
16.1k
    int32_t i, char* absl_nonnull buffer) {
305
16.1k
  uint32_t u = static_cast<uint32_t>(i);
306
16.1k
  if (i < 0) {
307
0
    *buffer++ = '-';
308
    // We need to do the negation in modular (i.e., "unsigned")
309
    // arithmetic; MSVC++ apparently warns for plain "-u", so
310
    // we write the equivalent expression "0 - u" instead.
311
0
    u = 0 - u;
312
0
  }
313
16.1k
  buffer = EncodeFullU32(u, buffer);
314
16.1k
  *buffer = '\0';
315
16.1k
  return buffer;
316
16.1k
}
317
318
char* absl_nonnull numbers_internal::FastIntToBuffer(
319
0
    uint64_t i, char* absl_nonnull buffer) {
320
0
  buffer = EncodeFullU64(i, buffer);
321
0
  *buffer = '\0';
322
0
  return buffer;
323
0
}
324
325
char* absl_nonnull numbers_internal::FastIntToBuffer(
326
0
    int64_t i, char* absl_nonnull buffer) {
327
0
  uint64_t u = static_cast<uint64_t>(i);
328
0
  if (i < 0) {
329
0
    *buffer++ = '-';
330
    // We need to do the negation in modular (i.e., "unsigned")
331
    // arithmetic; MSVC++ apparently warns for plain "-u", so
332
    // we write the equivalent expression "0 - u" instead.
333
0
    u = 0 - u;
334
0
  }
335
0
  buffer = EncodeFullU64(u, buffer);
336
0
  *buffer = '\0';
337
0
  return buffer;
338
0
}
339
340
// Given a 128-bit number expressed as a pair of uint64_t, high half first,
341
// return that number multiplied by the given 32-bit value.  If the result is
342
// too large to fit in a 128-bit number, divide it by 2 until it fits.
343
static std::pair<uint64_t, uint64_t> Mul32(std::pair<uint64_t, uint64_t> num,
344
0
                                           uint32_t mul) {
345
0
  uint64_t bits0_31 = num.second & 0xFFFFFFFF;
346
0
  uint64_t bits32_63 = num.second >> 32;
347
0
  uint64_t bits64_95 = num.first & 0xFFFFFFFF;
348
0
  uint64_t bits96_127 = num.first >> 32;
349
350
  // The picture so far: each of these 64-bit values has only the lower 32 bits
351
  // filled in.
352
  // bits96_127:          [ 00000000 xxxxxxxx ]
353
  // bits64_95:                    [ 00000000 xxxxxxxx ]
354
  // bits32_63:                             [ 00000000 xxxxxxxx ]
355
  // bits0_31:                                       [ 00000000 xxxxxxxx ]
356
357
0
  bits0_31 *= mul;
358
0
  bits32_63 *= mul;
359
0
  bits64_95 *= mul;
360
0
  bits96_127 *= mul;
361
362
  // Now the top halves may also have value, though all 64 of their bits will
363
  // never be set at the same time, since they are a result of a 32x32 bit
364
  // multiply.  This makes the carry calculation slightly easier.
365
  // bits96_127:          [ mmmmmmmm | mmmmmmmm ]
366
  // bits64_95:                    [ | mmmmmmmm mmmmmmmm | ]
367
  // bits32_63:                      |        [ mmmmmmmm | mmmmmmmm ]
368
  // bits0_31:                       |                 [ | mmmmmmmm mmmmmmmm ]
369
  // eventually:        [ bits128_up | ...bits64_127.... | ..bits0_63... ]
370
371
0
  uint64_t bits0_63 = bits0_31 + (bits32_63 << 32);
372
0
  uint64_t bits64_127 = bits64_95 + (bits96_127 << 32) + (bits32_63 >> 32) +
373
0
                        (bits0_63 < bits0_31);
374
0
  uint64_t bits128_up = (bits96_127 >> 32) + (bits64_127 < bits64_95);
375
0
  if (bits128_up == 0) return {bits64_127, bits0_63};
376
377
0
  auto shift = static_cast<unsigned>(bit_width(bits128_up));
378
0
  uint64_t lo = (bits0_63 >> shift) + (bits64_127 << (64 - shift));
379
0
  uint64_t hi = (bits64_127 >> shift) + (bits128_up << (64 - shift));
380
0
  return {hi, lo};
381
0
}
382
383
// Compute num * 5 ^ expfive, and return the first 128 bits of the result,
384
// where the first bit is always a one.  So PowFive(1, 0) starts 0b100000,
385
// PowFive(1, 1) starts 0b101000, PowFive(1, 2) starts 0b110010, etc.
386
0
static std::pair<uint64_t, uint64_t> PowFive(uint64_t num, int expfive) {
387
0
  std::pair<uint64_t, uint64_t> result = {num, 0};
388
0
  while (expfive >= 13) {
389
    // 5^13 is the highest power of five that will fit in a 32-bit integer.
390
0
    result = Mul32(result, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5);
391
0
    expfive -= 13;
392
0
  }
393
0
  constexpr uint32_t powers_of_five[13] = {
394
0
      1,
395
0
      5,
396
0
      5 * 5,
397
0
      5 * 5 * 5,
398
0
      5 * 5 * 5 * 5,
399
0
      5 * 5 * 5 * 5 * 5,
400
0
      5 * 5 * 5 * 5 * 5 * 5,
401
0
      5 * 5 * 5 * 5 * 5 * 5 * 5,
402
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
403
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
404
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
405
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
406
0
      5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5};
407
0
  result = Mul32(result, powers_of_five[expfive & 15]);
408
0
  int shift = countl_zero(result.first);
409
0
  if (shift != 0) {
410
0
    result.first = (result.first << shift) + (result.second >> (64 - shift));
411
0
    result.second = (result.second << shift);
412
0
  }
413
0
  return result;
414
0
}
415
416
struct ExpDigits {
417
  int32_t exponent;
418
  char digits[6];
419
};
420
421
// SplitToSix converts value, a positive double-precision floating-point number,
422
// into a base-10 exponent and 6 ASCII digits, where the first digit is never
423
// zero.  For example, SplitToSix(1) returns an exponent of zero and a digits
424
// array of {'1', '0', '0', '0', '0', '0'}.  If value is exactly halfway between
425
// two possible representations, e.g. value = 100000.5, then "round to even" is
426
// performed.
427
0
static ExpDigits SplitToSix(const double value) {
428
0
  ExpDigits exp_dig;
429
0
  int exp = 5;
430
0
  double d = value;
431
  // First step: calculate a close approximation of the output, where the
432
  // value d will be between 100,000 and 999,999, representing the digits
433
  // in the output ASCII array, and exp is the base-10 exponent.  It would be
434
  // faster to use a table here, and to look up the base-2 exponent of value,
435
  // however value is an IEEE-754 64-bit number, so the table would have 2,000
436
  // entries, which is not cache-friendly.
437
0
  if (d >= 999999.5) {
438
0
    if (d >= 1e+261) exp += 256, d *= 1e-256;
439
0
    if (d >= 1e+133) exp += 128, d *= 1e-128;
440
0
    if (d >= 1e+69) exp += 64, d *= 1e-64;
441
0
    if (d >= 1e+37) exp += 32, d *= 1e-32;
442
0
    if (d >= 1e+21) exp += 16, d *= 1e-16;
443
0
    if (d >= 1e+13) exp += 8, d *= 1e-8;
444
0
    if (d >= 1e+9) exp += 4, d *= 1e-4;
445
0
    if (d >= 1e+7) exp += 2, d *= 1e-2;
446
0
    if (d >= 1e+6) exp += 1, d *= 1e-1;
447
0
  } else {
448
0
    if (d < 1e-250) exp -= 256, d *= 1e256;
449
0
    if (d < 1e-122) exp -= 128, d *= 1e128;
450
0
    if (d < 1e-58) exp -= 64, d *= 1e64;
451
0
    if (d < 1e-26) exp -= 32, d *= 1e32;
452
0
    if (d < 1e-10) exp -= 16, d *= 1e16;
453
0
    if (d < 1e-2) exp -= 8, d *= 1e8;
454
0
    if (d < 1e+2) exp -= 4, d *= 1e4;
455
0
    if (d < 1e+4) exp -= 2, d *= 1e2;
456
0
    if (d < 1e+5) exp -= 1, d *= 1e1;
457
0
  }
458
  // At this point, d is in the range [99999.5..999999.5) and exp is in the
459
  // range [-324..308]. Since we need to round d up, we want to add a half
460
  // and truncate.
461
  // However, the technique above may have lost some precision, due to its
462
  // repeated multiplication by constants that each may be off by half a bit
463
  // of precision.  This only matters if we're close to the edge though.
464
  // Since we'd like to know if the fractional part of d is close to a half,
465
  // we multiply it by 65536 and see if the fractional part is close to 32768.
466
  // (The number doesn't have to be a power of two,but powers of two are faster)
467
0
  uint64_t d64k = static_cast<uint64_t>(d * 65536);
468
0
  uint32_t dddddd;  // A 6-digit decimal integer.
469
0
  if ((d64k % 65536) == 32767 || (d64k % 65536) == 32768) {
470
    // OK, it's fairly likely that precision was lost above, which is
471
    // not a surprise given only 52 mantissa bits are available.  Therefore
472
    // redo the calculation using 128-bit numbers.  (64 bits are not enough).
473
474
    // Start out with digits rounded down; maybe add one below.
475
0
    dddddd = static_cast<uint32_t>(d64k / 65536);
476
477
    // mantissa is a 64-bit integer representing M.mmm... * 2^63.  The actual
478
    // value we're representing, of course, is M.mmm... * 2^exp2.
479
0
    int exp2;
480
0
    double m = std::frexp(value, &exp2);
481
0
    uint64_t mantissa =
482
0
        static_cast<uint64_t>(m * (32768.0 * 65536.0 * 65536.0 * 65536.0));
483
    // std::frexp returns an m value in the range [0.5, 1.0), however we
484
    // can't multiply it by 2^64 and convert to an integer because some FPUs
485
    // throw an exception when converting an number higher than 2^63 into an
486
    // integer - even an unsigned 64-bit integer!  Fortunately it doesn't matter
487
    // since m only has 52 significant bits anyway.
488
0
    mantissa <<= 1;
489
0
    exp2 -= 64;  // not needed, but nice for debugging
490
491
    // OK, we are here to compare:
492
    //     (dddddd + 0.5) * 10^(exp-5)  vs.  mantissa * 2^exp2
493
    // so we can round up dddddd if appropriate.  Those values span the full
494
    // range of 600 orders of magnitude of IEE 64-bit floating-point.
495
    // Fortunately, we already know they are very close, so we don't need to
496
    // track the base-2 exponent of both sides.  This greatly simplifies the
497
    // the math since the 2^exp2 calculation is unnecessary and the power-of-10
498
    // calculation can become a power-of-5 instead.
499
500
0
    std::pair<uint64_t, uint64_t> edge, val;
501
0
    if (exp >= 6) {
502
      // Compare (dddddd + 0.5) * 5 ^ (exp - 5) to mantissa
503
      // Since we're tossing powers of two, 2 * dddddd + 1 is the
504
      // same as dddddd + 0.5
505
0
      edge = PowFive(2 * dddddd + 1, exp - 5);
506
507
0
      val.first = mantissa;
508
0
      val.second = 0;
509
0
    } else {
510
      // We can't compare (dddddd + 0.5) * 5 ^ (exp - 5) to mantissa as we did
511
      // above because (exp - 5) is negative.  So we compare (dddddd + 0.5) to
512
      // mantissa * 5 ^ (5 - exp)
513
0
      edge = PowFive(2 * dddddd + 1, 0);
514
515
0
      val = PowFive(mantissa, 5 - exp);
516
0
    }
517
    // printf("exp=%d %016lx %016lx vs %016lx %016lx\n", exp, val.first,
518
    //        val.second, edge.first, edge.second);
519
0
    if (val > edge) {
520
0
      dddddd++;
521
0
    } else if (val == edge) {
522
0
      dddddd += (dddddd & 1);
523
0
    }
524
0
  } else {
525
    // Here, we are not close to the edge.
526
0
    dddddd = static_cast<uint32_t>((d64k + 32768) / 65536);
527
0
  }
528
0
  if (dddddd == 1000000) {
529
0
    dddddd = 100000;
530
0
    exp += 1;
531
0
  }
532
0
  exp_dig.exponent = exp;
533
534
0
  uint32_t two_digits = dddddd / 10000;
535
0
  dddddd -= two_digits * 10000;
536
0
  numbers_internal::PutTwoDigits(two_digits, &exp_dig.digits[0]);
537
538
0
  two_digits = dddddd / 100;
539
0
  dddddd -= two_digits * 100;
540
0
  numbers_internal::PutTwoDigits(two_digits, &exp_dig.digits[2]);
541
542
0
  numbers_internal::PutTwoDigits(dddddd, &exp_dig.digits[4]);
543
0
  return exp_dig;
544
0
}
545
546
// Helper function for fast formatting of floating-point.
547
// The result is the same as "%g", a.k.a. "%.6g".
548
size_t numbers_internal::SixDigitsToBuffer(double d,
549
0
                                           char* absl_nonnull const buffer) {
550
0
  static_assert(std::numeric_limits<float>::is_iec559,
551
0
                "IEEE-754/IEC-559 support only");
552
553
0
  char* out = buffer;  // we write data to out, incrementing as we go, but
554
                       // FloatToBuffer always returns the address of the buffer
555
                       // passed in.
556
557
0
  if (std::isnan(d)) {
558
0
    strcpy(out, "nan");  // NOLINT(runtime/printf)
559
0
    return 3;
560
0
  }
561
0
  if (d == 0) {  // +0 and -0 are handled here
562
0
    if (std::signbit(d)) *out++ = '-';
563
0
    *out++ = '0';
564
0
    *out = 0;
565
0
    return static_cast<size_t>(out - buffer);
566
0
  }
567
0
  if (d < 0) {
568
0
    *out++ = '-';
569
0
    d = -d;
570
0
  }
571
0
  if (d > std::numeric_limits<double>::max()) {
572
0
    strcpy(out, "inf");  // NOLINT(runtime/printf)
573
0
    return static_cast<size_t>(out + 3 - buffer);
574
0
  }
575
576
0
  auto exp_dig = SplitToSix(d);
577
0
  int exp = exp_dig.exponent;
578
0
  const char* digits = exp_dig.digits;
579
0
  out[0] = '0';
580
0
  out[1] = '.';
581
0
  switch (exp) {
582
0
    case 5:
583
0
      memcpy(out, &digits[0], 6), out += 6;
584
0
      *out = 0;
585
0
      return static_cast<size_t>(out - buffer);
586
0
    case 4:
587
0
      memcpy(out, &digits[0], 5), out += 5;
588
0
      if (digits[5] != '0') {
589
0
        *out++ = '.';
590
0
        *out++ = digits[5];
591
0
      }
592
0
      *out = 0;
593
0
      return static_cast<size_t>(out - buffer);
594
0
    case 3:
595
0
      memcpy(out, &digits[0], 4), out += 4;
596
0
      if ((digits[5] | digits[4]) != '0') {
597
0
        *out++ = '.';
598
0
        *out++ = digits[4];
599
0
        if (digits[5] != '0') *out++ = digits[5];
600
0
      }
601
0
      *out = 0;
602
0
      return static_cast<size_t>(out - buffer);
603
0
    case 2:
604
0
      memcpy(out, &digits[0], 3), out += 3;
605
0
      *out++ = '.';
606
0
      memcpy(out, &digits[3], 3);
607
0
      out += 3;
608
0
      while (out[-1] == '0') --out;
609
0
      if (out[-1] == '.') --out;
610
0
      *out = 0;
611
0
      return static_cast<size_t>(out - buffer);
612
0
    case 1:
613
0
      memcpy(out, &digits[0], 2), out += 2;
614
0
      *out++ = '.';
615
0
      memcpy(out, &digits[2], 4);
616
0
      out += 4;
617
0
      while (out[-1] == '0') --out;
618
0
      if (out[-1] == '.') --out;
619
0
      *out = 0;
620
0
      return static_cast<size_t>(out - buffer);
621
0
    case 0:
622
0
      memcpy(out, &digits[0], 1), out += 1;
623
0
      *out++ = '.';
624
0
      memcpy(out, &digits[1], 5);
625
0
      out += 5;
626
0
      while (out[-1] == '0') --out;
627
0
      if (out[-1] == '.') --out;
628
0
      *out = 0;
629
0
      return static_cast<size_t>(out - buffer);
630
0
    case -4:
631
0
      out[2] = '0';
632
0
      ++out;
633
0
      ABSL_FALLTHROUGH_INTENDED;
634
0
    case -3:
635
0
      out[2] = '0';
636
0
      ++out;
637
0
      ABSL_FALLTHROUGH_INTENDED;
638
0
    case -2:
639
0
      out[2] = '0';
640
0
      ++out;
641
0
      ABSL_FALLTHROUGH_INTENDED;
642
0
    case -1:
643
0
      out += 2;
644
0
      memcpy(out, &digits[0], 6);
645
0
      out += 6;
646
0
      while (out[-1] == '0') --out;
647
0
      *out = 0;
648
0
      return static_cast<size_t>(out - buffer);
649
0
  }
650
0
  assert(exp < -4 || exp >= 6);
651
0
  out[0] = digits[0];
652
0
  assert(out[1] == '.');
653
0
  out += 2;
654
0
  memcpy(out, &digits[1], 5), out += 5;
655
0
  while (out[-1] == '0') --out;
656
0
  if (out[-1] == '.') --out;
657
0
  *out++ = 'e';
658
0
  if (exp > 0) {
659
0
    *out++ = '+';
660
0
  } else {
661
0
    *out++ = '-';
662
0
    exp = -exp;
663
0
  }
664
0
  if (exp > 99) {
665
0
    int dig1 = exp / 100;
666
0
    exp -= dig1 * 100;
667
0
    *out++ = '0' + static_cast<char>(dig1);
668
0
  }
669
0
  PutTwoDigits(static_cast<uint32_t>(exp), out);
670
0
  out += 2;
671
0
  *out = 0;
672
0
  return static_cast<size_t>(out - buffer);
673
0
}
674
675
namespace {
676
// Represents integer values of digits.
677
// Uses 36 to indicate an invalid character since we support
678
// bases up to 36.
679
static constexpr std::array<int8_t, 256> kAsciiToInt = {
680
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,  // 16 36s.
681
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
682
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 0,  1,  2,  3,  4,  5,
683
    6,  7,  8,  9,  36, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17,
684
    18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
685
    36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
686
    24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 36,
687
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
688
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
689
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
690
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
691
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
692
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
693
    36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36};
694
695
// Parse the sign and optional hex or oct prefix in text.
696
inline bool safe_parse_sign_and_base(
697
    absl::string_view* absl_nonnull text /*inout*/,
698
    int* absl_nonnull base_ptr /*inout*/,
699
0
    bool* absl_nonnull negative_ptr /*output*/) {
700
0
  if (text->data() == nullptr) {
701
0
    return false;
702
0
  }
703
704
0
  const char* start = text->data();
705
0
  const char* end = start + text->size();
706
0
  int base = *base_ptr;
707
708
  // Consume whitespace.
709
0
  while (start < end &&
710
0
         absl::ascii_isspace(static_cast<unsigned char>(start[0]))) {
711
0
    ++start;
712
0
  }
713
0
  while (start < end &&
714
0
         absl::ascii_isspace(static_cast<unsigned char>(end[-1]))) {
715
0
    --end;
716
0
  }
717
0
  if (start >= end) {
718
0
    return false;
719
0
  }
720
721
  // Consume sign.
722
0
  *negative_ptr = (start[0] == '-');
723
0
  if (*negative_ptr || start[0] == '+') {
724
0
    ++start;
725
0
    if (start >= end) {
726
0
      return false;
727
0
    }
728
0
  }
729
730
  // Consume base-dependent prefix.
731
  //  base 0: "0x" -> base 16, "0" -> base 8, default -> base 10
732
  //  base 16: "0x" -> base 16
733
  // Also validate the base.
734
0
  if (base == 0) {
735
0
    if (end - start >= 2 && start[0] == '0' &&
736
0
        (start[1] == 'x' || start[1] == 'X')) {
737
0
      base = 16;
738
0
      start += 2;
739
0
      if (start >= end) {
740
        // "0x" with no digits after is invalid.
741
0
        return false;
742
0
      }
743
0
    } else if (end - start >= 1 && start[0] == '0') {
744
0
      base = 8;
745
0
      start += 1;
746
0
    } else {
747
0
      base = 10;
748
0
    }
749
0
  } else if (base == 16) {
750
0
    if (end - start >= 2 && start[0] == '0' &&
751
0
        (start[1] == 'x' || start[1] == 'X')) {
752
0
      start += 2;
753
0
      if (start >= end) {
754
        // "0x" with no digits after is invalid.
755
0
        return false;
756
0
      }
757
0
    }
758
0
  } else if (base >= 2 && base <= 36) {
759
    // okay
760
0
  } else {
761
0
    return false;
762
0
  }
763
0
  *text = absl::string_view(start, static_cast<size_t>(end - start));
764
0
  *base_ptr = base;
765
0
  return true;
766
0
}
767
768
// Consume digits.
769
//
770
// The classic loop:
771
//
772
//   for each digit
773
//     value = value * base + digit
774
//   value *= sign
775
//
776
// The classic loop needs overflow checking.  It also fails on the most
777
// negative integer, -2147483648 in 32-bit two's complement representation.
778
//
779
// My improved loop:
780
//
781
//  if (!negative)
782
//    for each digit
783
//      value = value * base
784
//      value = value + digit
785
//  else
786
//    for each digit
787
//      value = value * base
788
//      value = value - digit
789
//
790
// Overflow checking becomes simple.
791
792
// Lookup tables per IntType:
793
// vmax/base and vmin/base are precomputed because division costs at least 8ns.
794
// TODO(junyer): Doing this per base instead (i.e. an array of structs, not a
795
// struct of arrays) would probably be better in terms of d-cache for the most
796
// commonly used bases.
797
template <typename IntType>
798
struct LookupTables {
799
  ABSL_CONST_INIT static const IntType kVmaxOverBase[];
800
  ABSL_CONST_INIT static const IntType kVminOverBase[];
801
};
802
803
// An array initializer macro for X/base where base in [0, 36].
804
// However, note that lookups for base in [0, 1] should never happen because
805
// base has been validated to be in [2, 36] by safe_parse_sign_and_base().
806
#define X_OVER_BASE_INITIALIZER(X)                                        \
807
  {                                                                       \
808
    0, 0, X / 2, X / 3, X / 4, X / 5, X / 6, X / 7, X / 8, X / 9, X / 10, \
809
        X / 11, X / 12, X / 13, X / 14, X / 15, X / 16, X / 17, X / 18,   \
810
        X / 19, X / 20, X / 21, X / 22, X / 23, X / 24, X / 25, X / 26,   \
811
        X / 27, X / 28, X / 29, X / 30, X / 31, X / 32, X / 33, X / 34,   \
812
        X / 35, X / 36,                                                   \
813
  }
814
815
// This kVmaxOverBase is generated with
816
//  for (int base = 2; base < 37; ++base) {
817
//    absl::uint128 max = std::numeric_limits<absl::uint128>::max();
818
//    auto result = max / base;
819
//    std::cout << "    MakeUint128(" << absl::Uint128High64(result) << "u, "
820
//              << absl::Uint128Low64(result) << "u),\n";
821
//  }
822
// See https://godbolt.org/z/aneYsb
823
//
824
// uint128& operator/=(uint128) is not constexpr, so hardcode the resulting
825
// array to avoid a static initializer.
826
template <>
827
ABSL_CONST_INIT const uint128 LookupTables<uint128>::kVmaxOverBase[] = {
828
    0,
829
    0,
830
    MakeUint128(9223372036854775807u, 18446744073709551615u),
831
    MakeUint128(6148914691236517205u, 6148914691236517205u),
832
    MakeUint128(4611686018427387903u, 18446744073709551615u),
833
    MakeUint128(3689348814741910323u, 3689348814741910323u),
834
    MakeUint128(3074457345618258602u, 12297829382473034410u),
835
    MakeUint128(2635249153387078802u, 5270498306774157604u),
836
    MakeUint128(2305843009213693951u, 18446744073709551615u),
837
    MakeUint128(2049638230412172401u, 14347467612885206812u),
838
    MakeUint128(1844674407370955161u, 11068046444225730969u),
839
    MakeUint128(1676976733973595601u, 8384883669867978007u),
840
    MakeUint128(1537228672809129301u, 6148914691236517205u),
841
    MakeUint128(1418980313362273201u, 4256940940086819603u),
842
    MakeUint128(1317624576693539401u, 2635249153387078802u),
843
    MakeUint128(1229782938247303441u, 1229782938247303441u),
844
    MakeUint128(1152921504606846975u, 18446744073709551615u),
845
    MakeUint128(1085102592571150095u, 1085102592571150095u),
846
    MakeUint128(1024819115206086200u, 16397105843297379214u),
847
    MakeUint128(970881267037344821u, 16504981539634861972u),
848
    MakeUint128(922337203685477580u, 14757395258967641292u),
849
    MakeUint128(878416384462359600u, 14054662151397753612u),
850
    MakeUint128(838488366986797800u, 13415813871788764811u),
851
    MakeUint128(802032351030850070u, 4812194106185100421u),
852
    MakeUint128(768614336404564650u, 12297829382473034410u),
853
    MakeUint128(737869762948382064u, 11805916207174113034u),
854
    MakeUint128(709490156681136600u, 11351842506898185609u),
855
    MakeUint128(683212743470724133u, 17080318586768103348u),
856
    MakeUint128(658812288346769700u, 10540996613548315209u),
857
    MakeUint128(636094623231363848u, 15266270957552732371u),
858
    MakeUint128(614891469123651720u, 9838263505978427528u),
859
    MakeUint128(595056260442243600u, 9520900167075897608u),
860
    MakeUint128(576460752303423487u, 18446744073709551615u),
861
    MakeUint128(558992244657865200u, 8943875914525843207u),
862
    MakeUint128(542551296285575047u, 9765923333140350855u),
863
    MakeUint128(527049830677415760u, 8432797290838652167u),
864
    MakeUint128(512409557603043100u, 8198552921648689607u),
865
};
866
867
// This kVmaxOverBase generated with
868
//   for (int base = 2; base < 37; ++base) {
869
//    absl::int128 max = std::numeric_limits<absl::int128>::max();
870
//    auto result = max / base;
871
//    std::cout << "\tMakeInt128(" << absl::Int128High64(result) << ", "
872
//              << absl::Int128Low64(result) << "u),\n";
873
//  }
874
// See https://godbolt.org/z/7djYWz
875
//
876
// int128& operator/=(int128) is not constexpr, so hardcode the resulting array
877
// to avoid a static initializer.
878
template <>
879
ABSL_CONST_INIT const int128 LookupTables<int128>::kVmaxOverBase[] = {
880
    0,
881
    0,
882
    MakeInt128(4611686018427387903, 18446744073709551615u),
883
    MakeInt128(3074457345618258602, 12297829382473034410u),
884
    MakeInt128(2305843009213693951, 18446744073709551615u),
885
    MakeInt128(1844674407370955161, 11068046444225730969u),
886
    MakeInt128(1537228672809129301, 6148914691236517205u),
887
    MakeInt128(1317624576693539401, 2635249153387078802u),
888
    MakeInt128(1152921504606846975, 18446744073709551615u),
889
    MakeInt128(1024819115206086200, 16397105843297379214u),
890
    MakeInt128(922337203685477580, 14757395258967641292u),
891
    MakeInt128(838488366986797800, 13415813871788764811u),
892
    MakeInt128(768614336404564650, 12297829382473034410u),
893
    MakeInt128(709490156681136600, 11351842506898185609u),
894
    MakeInt128(658812288346769700, 10540996613548315209u),
895
    MakeInt128(614891469123651720, 9838263505978427528u),
896
    MakeInt128(576460752303423487, 18446744073709551615u),
897
    MakeInt128(542551296285575047, 9765923333140350855u),
898
    MakeInt128(512409557603043100, 8198552921648689607u),
899
    MakeInt128(485440633518672410, 17475862806672206794u),
900
    MakeInt128(461168601842738790, 7378697629483820646u),
901
    MakeInt128(439208192231179800, 7027331075698876806u),
902
    MakeInt128(419244183493398900, 6707906935894382405u),
903
    MakeInt128(401016175515425035, 2406097053092550210u),
904
    MakeInt128(384307168202282325, 6148914691236517205u),
905
    MakeInt128(368934881474191032, 5902958103587056517u),
906
    MakeInt128(354745078340568300, 5675921253449092804u),
907
    MakeInt128(341606371735362066, 17763531330238827482u),
908
    MakeInt128(329406144173384850, 5270498306774157604u),
909
    MakeInt128(318047311615681924, 7633135478776366185u),
910
    MakeInt128(307445734561825860, 4919131752989213764u),
911
    MakeInt128(297528130221121800, 4760450083537948804u),
912
    MakeInt128(288230376151711743, 18446744073709551615u),
913
    MakeInt128(279496122328932600, 4471937957262921603u),
914
    MakeInt128(271275648142787523, 14106333703424951235u),
915
    MakeInt128(263524915338707880, 4216398645419326083u),
916
    MakeInt128(256204778801521550, 4099276460824344803u),
917
};
918
919
// This kVminOverBase generated with
920
//  for (int base = 2; base < 37; ++base) {
921
//    absl::int128 min = std::numeric_limits<absl::int128>::min();
922
//    auto result = min / base;
923
//    std::cout << "\tMakeInt128(" << absl::Int128High64(result) << ", "
924
//              << absl::Int128Low64(result) << "u),\n";
925
//  }
926
//
927
// See https://godbolt.org/z/7djYWz
928
//
929
// int128& operator/=(int128) is not constexpr, so hardcode the resulting array
930
// to avoid a static initializer.
931
template <>
932
ABSL_CONST_INIT const int128 LookupTables<int128>::kVminOverBase[] = {
933
    0,
934
    0,
935
    MakeInt128(-4611686018427387904, 0u),
936
    MakeInt128(-3074457345618258603, 6148914691236517206u),
937
    MakeInt128(-2305843009213693952, 0u),
938
    MakeInt128(-1844674407370955162, 7378697629483820647u),
939
    MakeInt128(-1537228672809129302, 12297829382473034411u),
940
    MakeInt128(-1317624576693539402, 15811494920322472814u),
941
    MakeInt128(-1152921504606846976, 0u),
942
    MakeInt128(-1024819115206086201, 2049638230412172402u),
943
    MakeInt128(-922337203685477581, 3689348814741910324u),
944
    MakeInt128(-838488366986797801, 5030930201920786805u),
945
    MakeInt128(-768614336404564651, 6148914691236517206u),
946
    MakeInt128(-709490156681136601, 7094901566811366007u),
947
    MakeInt128(-658812288346769701, 7905747460161236407u),
948
    MakeInt128(-614891469123651721, 8608480567731124088u),
949
    MakeInt128(-576460752303423488, 0u),
950
    MakeInt128(-542551296285575048, 8680820740569200761u),
951
    MakeInt128(-512409557603043101, 10248191152060862009u),
952
    MakeInt128(-485440633518672411, 970881267037344822u),
953
    MakeInt128(-461168601842738791, 11068046444225730970u),
954
    MakeInt128(-439208192231179801, 11419412998010674810u),
955
    MakeInt128(-419244183493398901, 11738837137815169211u),
956
    MakeInt128(-401016175515425036, 16040647020617001406u),
957
    MakeInt128(-384307168202282326, 12297829382473034411u),
958
    MakeInt128(-368934881474191033, 12543785970122495099u),
959
    MakeInt128(-354745078340568301, 12770822820260458812u),
960
    MakeInt128(-341606371735362067, 683212743470724134u),
961
    MakeInt128(-329406144173384851, 13176245766935394012u),
962
    MakeInt128(-318047311615681925, 10813608594933185431u),
963
    MakeInt128(-307445734561825861, 13527612320720337852u),
964
    MakeInt128(-297528130221121801, 13686293990171602812u),
965
    MakeInt128(-288230376151711744, 0u),
966
    MakeInt128(-279496122328932601, 13974806116446630013u),
967
    MakeInt128(-271275648142787524, 4340410370284600381u),
968
    MakeInt128(-263524915338707881, 14230345428290225533u),
969
    MakeInt128(-256204778801521551, 14347467612885206813u),
970
};
971
972
template <typename IntType>
973
ABSL_CONST_INIT const IntType LookupTables<IntType>::kVmaxOverBase[] =
974
    X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::max());
975
976
template <typename IntType>
977
ABSL_CONST_INIT const IntType LookupTables<IntType>::kVminOverBase[] =
978
    X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::min());
979
980
#undef X_OVER_BASE_INITIALIZER
981
982
template <typename IntType>
983
inline bool safe_parse_positive_int(absl::string_view text, int base,
984
0
                                    IntType* absl_nonnull value_p) {
985
0
  IntType value = 0;
986
0
  const IntType vmax = std::numeric_limits<IntType>::max();
987
0
  assert(vmax > 0);
988
0
  assert(base >= 0);
989
0
  const IntType base_inttype = static_cast<IntType>(base);
990
0
  assert(vmax >= base_inttype);
991
0
  const IntType vmax_over_base = LookupTables<IntType>::kVmaxOverBase[base];
992
0
  assert(base < 2 ||
993
0
         std::numeric_limits<IntType>::max() / base_inttype == vmax_over_base);
994
0
  const char* start = text.data();
995
0
  const char* end = start + text.size();
996
  // loop over digits
997
0
  for (; start < end; ++start) {
998
0
    unsigned char c = static_cast<unsigned char>(start[0]);
999
0
    IntType digit = static_cast<IntType>(kAsciiToInt[c]);
1000
0
    if (digit >= base_inttype) {
1001
0
      *value_p = value;
1002
0
      return false;
1003
0
    }
1004
0
    if (value > vmax_over_base) {
1005
0
      *value_p = vmax;
1006
0
      return false;
1007
0
    }
1008
0
    value *= base_inttype;
1009
0
    if (value > vmax - digit) {
1010
0
      *value_p = vmax;
1011
0
      return false;
1012
0
    }
1013
0
    value += digit;
1014
0
  }
1015
0
  *value_p = value;
1016
0
  return true;
1017
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*)
1018
1019
template <typename IntType>
1020
inline bool safe_parse_negative_int(absl::string_view text, int base,
1021
0
                                    IntType* absl_nonnull value_p) {
1022
0
  IntType value = 0;
1023
0
  const IntType vmin = std::numeric_limits<IntType>::min();
1024
0
  assert(vmin < 0);
1025
0
  assert(vmin <= 0 - base);
1026
0
  IntType vmin_over_base = LookupTables<IntType>::kVminOverBase[base];
1027
0
  assert(base < 2 ||
1028
0
         std::numeric_limits<IntType>::min() / base == vmin_over_base);
1029
  // 2003 c++ standard [expr.mul]
1030
  // "... the sign of the remainder is implementation-defined."
1031
  // Although (vmin/base)*base + vmin%base is always vmin.
1032
  // 2011 c++ standard tightens the spec but we cannot rely on it.
1033
  // TODO(junyer): Handle this in the lookup table generation.
1034
0
  if (vmin % base > 0) {
1035
0
    vmin_over_base += 1;
1036
0
  }
1037
0
  const char* start = text.data();
1038
0
  const char* end = start + text.size();
1039
  // loop over digits
1040
0
  for (; start < end; ++start) {
1041
0
    unsigned char c = static_cast<unsigned char>(start[0]);
1042
0
    int digit = kAsciiToInt[c];
1043
0
    if (digit >= base) {
1044
0
      *value_p = value;
1045
0
      return false;
1046
0
    }
1047
0
    if (value < vmin_over_base) {
1048
0
      *value_p = vmin;
1049
0
      return false;
1050
0
    }
1051
0
    value *= base;
1052
0
    if (value < vmin + digit) {
1053
0
      *value_p = vmin;
1054
0
      return false;
1055
0
    }
1056
0
    value -= digit;
1057
0
  }
1058
0
  *value_p = value;
1059
0
  return true;
1060
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*)
1061
1062
// Input format based on POSIX.1-2008 strtol
1063
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
1064
template <typename IntType>
1065
inline bool safe_int_internal(absl::string_view text,
1066
0
                              IntType* absl_nonnull value_p, int base) {
1067
0
  *value_p = 0;
1068
0
  bool negative;
1069
0
  if (!safe_parse_sign_and_base(&text, &base, &negative)) {
1070
0
    return false;
1071
0
  }
1072
0
  if (!negative) {
1073
0
    return safe_parse_positive_int(text, base, value_p);
1074
0
  } else {
1075
0
    return safe_parse_negative_int(text, base, value_p);
1076
0
  }
1077
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)
1078
1079
template <typename IntType>
1080
inline bool safe_uint_internal(absl::string_view text,
1081
0
                               IntType* absl_nonnull value_p, int base) {
1082
0
  *value_p = 0;
1083
0
  bool negative;
1084
0
  if (!safe_parse_sign_and_base(&text, &base, &negative) || negative) {
1085
0
    return false;
1086
0
  }
1087
0
  return safe_parse_positive_int(text, base, value_p);
1088
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)
1089
}  // anonymous namespace
1090
1091
namespace numbers_internal {
1092
1093
// Digit conversion.
1094
ABSL_CONST_INIT ABSL_DLL const char kHexChar[] =
1095
    "0123456789abcdef";
1096
1097
ABSL_CONST_INIT ABSL_DLL const char kHexTable[513] =
1098
    "000102030405060708090a0b0c0d0e0f"
1099
    "101112131415161718191a1b1c1d1e1f"
1100
    "202122232425262728292a2b2c2d2e2f"
1101
    "303132333435363738393a3b3c3d3e3f"
1102
    "404142434445464748494a4b4c4d4e4f"
1103
    "505152535455565758595a5b5c5d5e5f"
1104
    "606162636465666768696a6b6c6d6e6f"
1105
    "707172737475767778797a7b7c7d7e7f"
1106
    "808182838485868788898a8b8c8d8e8f"
1107
    "909192939495969798999a9b9c9d9e9f"
1108
    "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
1109
    "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
1110
    "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
1111
    "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
1112
    "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
1113
    "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff";
1114
1115
bool safe_strto8_base(absl::string_view text, int8_t* absl_nonnull value,
1116
0
                      int base) {
1117
0
  return safe_int_internal<int8_t>(text, value, base);
1118
0
}
1119
1120
bool safe_strto16_base(absl::string_view text, int16_t* absl_nonnull value,
1121
0
                       int base) {
1122
0
  return safe_int_internal<int16_t>(text, value, base);
1123
0
}
1124
1125
bool safe_strto32_base(absl::string_view text, int32_t* absl_nonnull value,
1126
0
                       int base) {
1127
0
  return safe_int_internal<int32_t>(text, value, base);
1128
0
}
1129
1130
bool safe_strto64_base(absl::string_view text, int64_t* absl_nonnull value,
1131
0
                       int base) {
1132
0
  return safe_int_internal<int64_t>(text, value, base);
1133
0
}
1134
1135
bool safe_strto128_base(absl::string_view text, int128* absl_nonnull value,
1136
0
                        int base) {
1137
0
  return safe_int_internal<absl::int128>(text, value, base);
1138
0
}
1139
1140
bool safe_strtou8_base(absl::string_view text, uint8_t* absl_nonnull value,
1141
0
                       int base) {
1142
0
  return safe_uint_internal<uint8_t>(text, value, base);
1143
0
}
1144
1145
bool safe_strtou16_base(absl::string_view text, uint16_t* absl_nonnull value,
1146
0
                        int base) {
1147
0
  return safe_uint_internal<uint16_t>(text, value, base);
1148
0
}
1149
1150
bool safe_strtou32_base(absl::string_view text, uint32_t* absl_nonnull value,
1151
0
                        int base) {
1152
0
  return safe_uint_internal<uint32_t>(text, value, base);
1153
0
}
1154
1155
bool safe_strtou64_base(absl::string_view text, uint64_t* absl_nonnull value,
1156
0
                        int base) {
1157
0
  return safe_uint_internal<uint64_t>(text, value, base);
1158
0
}
1159
1160
bool safe_strtou128_base(absl::string_view text, uint128* absl_nonnull value,
1161
0
                         int base) {
1162
0
  return safe_uint_internal<absl::uint128>(text, value, base);
1163
0
}
1164
1165
}  // namespace numbers_internal
1166
ABSL_NAMESPACE_END
1167
}  // namespace absl