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