Coverage Report

Created: 2025-11-15 06:18

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