Coverage Report

Created: 2025-10-27 06:07

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