• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 tests string processing functions related to numeric values.
16 
17 #include "absl/strings/numbers.h"
18 
19 #include <sys/types.h>
20 
21 #include <cfenv>  // NOLINT(build/c++11)
22 #include <cfloat>
23 #include <cinttypes>
24 #include <climits>
25 #include <cmath>
26 #include <cstddef>
27 #include <cstdint>
28 #include <cstdio>
29 #include <cstdlib>
30 #include <cstring>
31 #include <limits>
32 #include <numeric>
33 #include <random>
34 #include <set>
35 #include <string>
36 #include <vector>
37 
38 #include "gmock/gmock.h"
39 #include "gtest/gtest.h"
40 #include "absl/base/internal/raw_logging.h"
41 #include "absl/random/distributions.h"
42 #include "absl/random/random.h"
43 #include "absl/strings/internal/numbers_test_common.h"
44 #include "absl/strings/internal/ostringstream.h"
45 #include "absl/strings/internal/pow10_helper.h"
46 #include "absl/strings/str_cat.h"
47 
48 namespace {
49 
50 using absl::SimpleAtoi;
51 using absl::SimpleHexAtoi;
52 using absl::numbers_internal::kSixDigitsToBufferSize;
53 using absl::numbers_internal::safe_strto32_base;
54 using absl::numbers_internal::safe_strto64_base;
55 using absl::numbers_internal::safe_strtou32_base;
56 using absl::numbers_internal::safe_strtou64_base;
57 using absl::numbers_internal::SixDigitsToBuffer;
58 using absl::strings_internal::Itoa;
59 using absl::strings_internal::strtouint32_test_cases;
60 using absl::strings_internal::strtouint64_test_cases;
61 using testing::Eq;
62 using testing::MatchesRegex;
63 
64 // Number of floats to test with.
65 // 5,000,000 is a reasonable default for a test that only takes a few seconds.
66 // 1,000,000,000+ triggers checking for all possible mantissa values for
67 // double-precision tests. 2,000,000,000+ triggers checking for every possible
68 // single-precision float.
69 const int kFloatNumCases = 5000000;
70 
71 // This is a slow, brute-force routine to compute the exact base-10
72 // representation of a double-precision floating-point number.  It
73 // is useful for debugging only.
PerfectDtoa(double d)74 std::string PerfectDtoa(double d) {
75   if (d == 0) return "0";
76   if (d < 0) return "-" + PerfectDtoa(-d);
77 
78   // Basic theory: decompose d into mantissa and exp, where
79   // d = mantissa * 2^exp, and exp is as close to zero as possible.
80   int64_t mantissa, exp = 0;
81   while (d >= 1ULL << 63) ++exp, d *= 0.5;
82   while ((mantissa = d) != d) --exp, d *= 2.0;
83 
84   // Then convert mantissa to ASCII, and either double it (if
85   // exp > 0) or halve it (if exp < 0) repeatedly.  "halve it"
86   // in this case means multiplying it by five and dividing by 10.
87   constexpr int maxlen = 1100;  // worst case is actually 1030 or so.
88   char buf[maxlen + 5];
89   for (int64_t num = mantissa, pos = maxlen; --pos >= 0;) {
90     buf[pos] = '0' + (num % 10);
91     num /= 10;
92   }
93   char* begin = &buf[0];
94   char* end = buf + maxlen;
95   for (int i = 0; i != exp; i += (exp > 0) ? 1 : -1) {
96     int carry = 0;
97     for (char* p = end; --p != begin;) {
98       int dig = *p - '0';
99       dig = dig * (exp > 0 ? 2 : 5) + carry;
100       carry = dig / 10;
101       dig %= 10;
102       *p = '0' + dig;
103     }
104   }
105   if (exp < 0) {
106     // "dividing by 10" above means we have to add the decimal point.
107     memmove(end + 1 + exp, end + exp, 1 - exp);
108     end[exp] = '.';
109     ++end;
110   }
111   while (*begin == '0' && begin[1] != '.') ++begin;
112   return {begin, end};
113 }
114 
TEST(ToString,PerfectDtoa)115 TEST(ToString, PerfectDtoa) {
116   EXPECT_THAT(PerfectDtoa(1), Eq("1"));
117   EXPECT_THAT(PerfectDtoa(0.1),
118               Eq("0.1000000000000000055511151231257827021181583404541015625"));
119   EXPECT_THAT(PerfectDtoa(1e24), Eq("999999999999999983222784"));
120   EXPECT_THAT(PerfectDtoa(5e-324), MatchesRegex("0.0000.*625"));
121   for (int i = 0; i < 100; ++i) {
122     for (double multiplier :
123          {1e-300, 1e-200, 1e-100, 0.1, 1.0, 10.0, 1e100, 1e300}) {
124       double d = multiplier * i;
125       std::string s = PerfectDtoa(d);
126       EXPECT_DOUBLE_EQ(d, strtod(s.c_str(), nullptr));
127     }
128   }
129 }
130 
131 template <typename integer>
132 struct MyInteger {
133   integer i;
MyInteger__anoncbf2604d0111::MyInteger134   explicit constexpr MyInteger(integer i) : i(i) {}
operator integer__anoncbf2604d0111::MyInteger135   constexpr operator integer() const { return i; }
136 
operator +__anoncbf2604d0111::MyInteger137   constexpr MyInteger operator+(MyInteger other) const { return i + other.i; }
operator -__anoncbf2604d0111::MyInteger138   constexpr MyInteger operator-(MyInteger other) const { return i - other.i; }
operator *__anoncbf2604d0111::MyInteger139   constexpr MyInteger operator*(MyInteger other) const { return i * other.i; }
operator /__anoncbf2604d0111::MyInteger140   constexpr MyInteger operator/(MyInteger other) const { return i / other.i; }
141 
operator <__anoncbf2604d0111::MyInteger142   constexpr bool operator<(MyInteger other) const { return i < other.i; }
operator <=__anoncbf2604d0111::MyInteger143   constexpr bool operator<=(MyInteger other) const { return i <= other.i; }
operator ==__anoncbf2604d0111::MyInteger144   constexpr bool operator==(MyInteger other) const { return i == other.i; }
operator >=__anoncbf2604d0111::MyInteger145   constexpr bool operator>=(MyInteger other) const { return i >= other.i; }
operator >__anoncbf2604d0111::MyInteger146   constexpr bool operator>(MyInteger other) const { return i > other.i; }
operator !=__anoncbf2604d0111::MyInteger147   constexpr bool operator!=(MyInteger other) const { return i != other.i; }
148 
as_integer__anoncbf2604d0111::MyInteger149   integer as_integer() const { return i; }
150 };
151 
152 typedef MyInteger<int64_t> MyInt64;
153 typedef MyInteger<uint64_t> MyUInt64;
154 
CheckInt32(int32_t x)155 void CheckInt32(int32_t x) {
156   char buffer[absl::numbers_internal::kFastToBufferSize];
157   char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
158   std::string expected = std::to_string(x);
159   EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x;
160 
161   char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
162   EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x;
163 }
164 
CheckInt64(int64_t x)165 void CheckInt64(int64_t x) {
166   char buffer[absl::numbers_internal::kFastToBufferSize + 3];
167   buffer[0] = '*';
168   buffer[23] = '*';
169   buffer[24] = '*';
170   char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
171   std::string expected = std::to_string(x);
172   EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x;
173   EXPECT_EQ(buffer[0], '*');
174   EXPECT_EQ(buffer[23], '*');
175   EXPECT_EQ(buffer[24], '*');
176 
177   char* my_actual =
178       absl::numbers_internal::FastIntToBuffer(MyInt64(x), &buffer[1]);
179   EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x;
180 }
181 
CheckUInt32(uint32_t x)182 void CheckUInt32(uint32_t x) {
183   char buffer[absl::numbers_internal::kFastToBufferSize];
184   char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
185   std::string expected = std::to_string(x);
186   EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x;
187 
188   char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
189   EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x;
190 }
191 
CheckUInt64(uint64_t x)192 void CheckUInt64(uint64_t x) {
193   char buffer[absl::numbers_internal::kFastToBufferSize + 1];
194   char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
195   std::string expected = std::to_string(x);
196   EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x;
197 
198   char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
199   EXPECT_EQ(expected, std::string(&buffer[1], generic_actual))
200       << " Input " << x;
201 
202   char* my_actual =
203       absl::numbers_internal::FastIntToBuffer(MyUInt64(x), &buffer[1]);
204   EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x;
205 }
206 
CheckHex64(uint64_t v)207 void CheckHex64(uint64_t v) {
208   char expected[16 + 1];
209   std::string actual = absl::StrCat(absl::Hex(v, absl::kZeroPad16));
210   snprintf(expected, sizeof(expected), "%016" PRIx64, static_cast<uint64_t>(v));
211   EXPECT_EQ(expected, actual) << " Input " << v;
212   actual = absl::StrCat(absl::Hex(v, absl::kSpacePad16));
213   snprintf(expected, sizeof(expected), "%16" PRIx64, static_cast<uint64_t>(v));
214   EXPECT_EQ(expected, actual) << " Input " << v;
215 }
216 
TEST(Numbers,TestFastPrints)217 TEST(Numbers, TestFastPrints) {
218   for (int i = -100; i <= 100; i++) {
219     CheckInt32(i);
220     CheckInt64(i);
221   }
222   for (int i = 0; i <= 100; i++) {
223     CheckUInt32(i);
224     CheckUInt64(i);
225   }
226   // Test min int to make sure that works
227   CheckInt32(INT_MIN);
228   CheckInt32(INT_MAX);
229   CheckInt64(LONG_MIN);
230   CheckInt64(uint64_t{1000000000});
231   CheckInt64(uint64_t{9999999999});
232   CheckInt64(uint64_t{100000000000000});
233   CheckInt64(uint64_t{999999999999999});
234   CheckInt64(uint64_t{1000000000000000000});
235   CheckInt64(uint64_t{1199999999999999999});
236   CheckInt64(int64_t{-700000000000000000});
237   CheckInt64(LONG_MAX);
238   CheckUInt32(std::numeric_limits<uint32_t>::max());
239   CheckUInt64(uint64_t{1000000000});
240   CheckUInt64(uint64_t{9999999999});
241   CheckUInt64(uint64_t{100000000000000});
242   CheckUInt64(uint64_t{999999999999999});
243   CheckUInt64(uint64_t{1000000000000000000});
244   CheckUInt64(uint64_t{1199999999999999999});
245   CheckUInt64(std::numeric_limits<uint64_t>::max());
246 
247   for (int i = 0; i < 10000; i++) {
248     CheckHex64(i);
249   }
250   CheckHex64(uint64_t{0x123456789abcdef0});
251 }
252 
253 template <typename int_type, typename in_val_type>
VerifySimpleAtoiGood(in_val_type in_value,int_type exp_value)254 void VerifySimpleAtoiGood(in_val_type in_value, int_type exp_value) {
255   std::string s;
256   // (u)int128 can be streamed but not StrCat'd.
257   absl::strings_internal::OStringStream(&s) << in_value;
258   int_type x = static_cast<int_type>(~exp_value);
259   EXPECT_TRUE(SimpleAtoi(s, &x))
260       << "in_value=" << in_value << " s=" << s << " x=" << x;
261   EXPECT_EQ(exp_value, x);
262   x = static_cast<int_type>(~exp_value);
263   EXPECT_TRUE(SimpleAtoi(s.c_str(), &x));
264   EXPECT_EQ(exp_value, x);
265 }
266 
267 template <typename int_type, typename in_val_type>
VerifySimpleAtoiBad(in_val_type in_value)268 void VerifySimpleAtoiBad(in_val_type in_value) {
269   std::string s;
270   // (u)int128 can be streamed but not StrCat'd.
271   absl::strings_internal::OStringStream(&s) << in_value;
272   int_type x;
273   EXPECT_FALSE(SimpleAtoi(s, &x));
274   EXPECT_FALSE(SimpleAtoi(s.c_str(), &x));
275 }
276 
TEST(NumbersTest,Atoi)277 TEST(NumbersTest, Atoi) {
278   // SimpleAtoi(absl::string_view, int32_t)
279   VerifySimpleAtoiGood<int32_t>(0, 0);
280   VerifySimpleAtoiGood<int32_t>(42, 42);
281   VerifySimpleAtoiGood<int32_t>(-42, -42);
282 
283   VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(),
284                                 std::numeric_limits<int32_t>::min());
285   VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(),
286                                 std::numeric_limits<int32_t>::max());
287 
288   // SimpleAtoi(absl::string_view, uint32_t)
289   VerifySimpleAtoiGood<uint32_t>(0, 0);
290   VerifySimpleAtoiGood<uint32_t>(42, 42);
291   VerifySimpleAtoiBad<uint32_t>(-42);
292 
293   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min());
294   VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(),
295                                  std::numeric_limits<int32_t>::max());
296   VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(),
297                                  std::numeric_limits<uint32_t>::max());
298   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min());
299   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max());
300   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max());
301 
302   // SimpleAtoi(absl::string_view, int64_t)
303   VerifySimpleAtoiGood<int64_t>(0, 0);
304   VerifySimpleAtoiGood<int64_t>(42, 42);
305   VerifySimpleAtoiGood<int64_t>(-42, -42);
306 
307   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(),
308                                 std::numeric_limits<int32_t>::min());
309   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(),
310                                 std::numeric_limits<int32_t>::max());
311   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(),
312                                 std::numeric_limits<uint32_t>::max());
313   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(),
314                                 std::numeric_limits<int64_t>::min());
315   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(),
316                                 std::numeric_limits<int64_t>::max());
317   VerifySimpleAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max());
318 
319   // SimpleAtoi(absl::string_view, uint64_t)
320   VerifySimpleAtoiGood<uint64_t>(0, 0);
321   VerifySimpleAtoiGood<uint64_t>(42, 42);
322   VerifySimpleAtoiBad<uint64_t>(-42);
323 
324   VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min());
325   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(),
326                                  std::numeric_limits<int32_t>::max());
327   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(),
328                                  std::numeric_limits<uint32_t>::max());
329   VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min());
330   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(),
331                                  std::numeric_limits<int64_t>::max());
332   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(),
333                                  std::numeric_limits<uint64_t>::max());
334 
335   // SimpleAtoi(absl::string_view, absl::uint128)
336   VerifySimpleAtoiGood<absl::uint128>(0, 0);
337   VerifySimpleAtoiGood<absl::uint128>(42, 42);
338   VerifySimpleAtoiBad<absl::uint128>(-42);
339 
340   VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min());
341   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(),
342                                       std::numeric_limits<int32_t>::max());
343   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(),
344                                       std::numeric_limits<uint32_t>::max());
345   VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min());
346   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(),
347                                       std::numeric_limits<int64_t>::max());
348   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(),
349                                       std::numeric_limits<uint64_t>::max());
350   VerifySimpleAtoiGood<absl::uint128>(
351       std::numeric_limits<absl::uint128>::max(),
352       std::numeric_limits<absl::uint128>::max());
353 
354   // SimpleAtoi(absl::string_view, absl::int128)
355   VerifySimpleAtoiGood<absl::int128>(0, 0);
356   VerifySimpleAtoiGood<absl::int128>(42, 42);
357   VerifySimpleAtoiGood<absl::int128>(-42, -42);
358 
359   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::min(),
360                                       std::numeric_limits<int32_t>::min());
361   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::max(),
362                                       std::numeric_limits<int32_t>::max());
363   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint32_t>::max(),
364                                       std::numeric_limits<uint32_t>::max());
365   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::min(),
366                                       std::numeric_limits<int64_t>::min());
367   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::max(),
368                                       std::numeric_limits<int64_t>::max());
369   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint64_t>::max(),
370                                       std::numeric_limits<uint64_t>::max());
371   VerifySimpleAtoiGood<absl::int128>(
372       std::numeric_limits<absl::int128>::min(),
373       std::numeric_limits<absl::int128>::min());
374   VerifySimpleAtoiGood<absl::int128>(
375       std::numeric_limits<absl::int128>::max(),
376       std::numeric_limits<absl::int128>::max());
377   VerifySimpleAtoiBad<absl::int128>(std::numeric_limits<absl::uint128>::max());
378 
379   // Some other types
380   VerifySimpleAtoiGood<int>(-42, -42);
381   VerifySimpleAtoiGood<int32_t>(-42, -42);
382   VerifySimpleAtoiGood<uint32_t>(42, 42);
383   VerifySimpleAtoiGood<unsigned int>(42, 42);
384   VerifySimpleAtoiGood<int64_t>(-42, -42);
385   VerifySimpleAtoiGood<long>(-42, -42);  // NOLINT: runtime-int
386   VerifySimpleAtoiGood<uint64_t>(42, 42);
387   VerifySimpleAtoiGood<size_t>(42, 42);
388   VerifySimpleAtoiGood<std::string::size_type>(42, 42);
389 }
390 
TEST(NumbersTest,Atod)391 TEST(NumbersTest, Atod) {
392   // DBL_TRUE_MIN and FLT_TRUE_MIN were not mandated in <cfloat> before C++17.
393 #if !defined(DBL_TRUE_MIN)
394   static constexpr double DBL_TRUE_MIN =
395       4.940656458412465441765687928682213723650598026143247644255856825e-324;
396 #endif
397 #if !defined(FLT_TRUE_MIN)
398   static constexpr float FLT_TRUE_MIN =
399       1.401298464324817070923729583289916131280261941876515771757068284e-45f;
400 #endif
401 
402   double d;
403   float f;
404 
405   // NaN can be spelled in multiple ways.
406   EXPECT_TRUE(absl::SimpleAtod("NaN", &d));
407   EXPECT_TRUE(std::isnan(d));
408   EXPECT_TRUE(absl::SimpleAtod("nAN", &d));
409   EXPECT_TRUE(std::isnan(d));
410   EXPECT_TRUE(absl::SimpleAtod("-nan", &d));
411   EXPECT_TRUE(std::isnan(d));
412 
413   // Likewise for Infinity.
414   EXPECT_TRUE(absl::SimpleAtod("inf", &d));
415   EXPECT_TRUE(std::isinf(d) && (d > 0));
416   EXPECT_TRUE(absl::SimpleAtod("+Infinity", &d));
417   EXPECT_TRUE(std::isinf(d) && (d > 0));
418   EXPECT_TRUE(absl::SimpleAtod("-INF", &d));
419   EXPECT_TRUE(std::isinf(d) && (d < 0));
420 
421   // Parse DBL_MAX. Parsing something more than twice as big should also
422   // produce infinity.
423   EXPECT_TRUE(absl::SimpleAtod("1.7976931348623157e+308", &d));
424   EXPECT_EQ(d, 1.7976931348623157e+308);
425   EXPECT_TRUE(absl::SimpleAtod("5e308", &d));
426   EXPECT_TRUE(std::isinf(d) && (d > 0));
427   // Ditto, but for FLT_MAX.
428   EXPECT_TRUE(absl::SimpleAtof("3.4028234663852886e+38", &f));
429   EXPECT_EQ(f, 3.4028234663852886e+38f);
430   EXPECT_TRUE(absl::SimpleAtof("7e38", &f));
431   EXPECT_TRUE(std::isinf(f) && (f > 0));
432 
433   // Parse the largest N such that parsing 1eN produces a finite value and the
434   // smallest M = N + 1 such that parsing 1eM produces infinity.
435   //
436   // The 309 exponent (and 39) confirms the "definition of
437   // kEiselLemireMaxExclExp10" comment in charconv.cc.
438   EXPECT_TRUE(absl::SimpleAtod("1e308", &d));
439   EXPECT_EQ(d, 1e308);
440   EXPECT_FALSE(std::isinf(d));
441   EXPECT_TRUE(absl::SimpleAtod("1e309", &d));
442   EXPECT_TRUE(std::isinf(d));
443   // Ditto, but for Atof instead of Atod.
444   EXPECT_TRUE(absl::SimpleAtof("1e38", &f));
445   EXPECT_EQ(f, 1e38f);
446   EXPECT_FALSE(std::isinf(f));
447   EXPECT_TRUE(absl::SimpleAtof("1e39", &f));
448   EXPECT_TRUE(std::isinf(f));
449 
450   // Parse the largest N such that parsing 9.999999999999999999eN, with 19
451   // nines, produces a finite value.
452   //
453   // 9999999999999999999, with 19 nines but no decimal point, is the largest
454   // "repeated nines" integer that fits in a uint64_t.
455   EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e307", &d));
456   EXPECT_EQ(d, 9.999999999999999999e307);
457   EXPECT_FALSE(std::isinf(d));
458   EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e308", &d));
459   EXPECT_TRUE(std::isinf(d));
460   // Ditto, but for Atof instead of Atod.
461   EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e37", &f));
462   EXPECT_EQ(f, 9.999999999999999999e37f);
463   EXPECT_FALSE(std::isinf(f));
464   EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e38", &f));
465   EXPECT_TRUE(std::isinf(f));
466 
467   // Parse DBL_MIN (normal), DBL_TRUE_MIN (subnormal) and (DBL_TRUE_MIN / 10)
468   // (effectively zero).
469   EXPECT_TRUE(absl::SimpleAtod("2.2250738585072014e-308", &d));
470   EXPECT_EQ(d, 2.2250738585072014e-308);
471   EXPECT_TRUE(absl::SimpleAtod("4.9406564584124654e-324", &d));
472   EXPECT_EQ(d, 4.9406564584124654e-324);
473   EXPECT_TRUE(absl::SimpleAtod("4.9406564584124654e-325", &d));
474   EXPECT_EQ(d, 0);
475   // Ditto, but for FLT_MIN, FLT_TRUE_MIN and (FLT_TRUE_MIN / 10).
476   EXPECT_TRUE(absl::SimpleAtof("1.1754943508222875e-38", &f));
477   EXPECT_EQ(f, 1.1754943508222875e-38f);
478   EXPECT_TRUE(absl::SimpleAtof("1.4012984643248171e-45", &f));
479   EXPECT_EQ(f, 1.4012984643248171e-45f);
480   EXPECT_TRUE(absl::SimpleAtof("1.4012984643248171e-46", &f));
481   EXPECT_EQ(f, 0);
482 
483   // Parse the largest N (the most negative -N) such that parsing 1e-N produces
484   // a normal or subnormal (but still positive) or zero value.
485   EXPECT_TRUE(absl::SimpleAtod("1e-307", &d));
486   EXPECT_EQ(d, 1e-307);
487   EXPECT_GE(d, DBL_MIN);
488   EXPECT_LT(d, DBL_MIN * 10);
489   EXPECT_TRUE(absl::SimpleAtod("1e-323", &d));
490   EXPECT_EQ(d, 1e-323);
491   EXPECT_GE(d, DBL_TRUE_MIN);
492   EXPECT_LT(d, DBL_TRUE_MIN * 10);
493   EXPECT_TRUE(absl::SimpleAtod("1e-324", &d));
494   EXPECT_EQ(d, 0);
495   // Ditto, but for Atof instead of Atod.
496   EXPECT_TRUE(absl::SimpleAtof("1e-37", &f));
497   EXPECT_EQ(f, 1e-37f);
498   EXPECT_GE(f, FLT_MIN);
499   EXPECT_LT(f, FLT_MIN * 10);
500   EXPECT_TRUE(absl::SimpleAtof("1e-45", &f));
501   EXPECT_EQ(f, 1e-45f);
502   EXPECT_GE(f, FLT_TRUE_MIN);
503   EXPECT_LT(f, FLT_TRUE_MIN * 10);
504   EXPECT_TRUE(absl::SimpleAtof("1e-46", &f));
505   EXPECT_EQ(f, 0);
506 
507   // Parse the largest N (the most negative -N) such that parsing
508   // 9.999999999999999999e-N, with 19 nines, produces a normal or subnormal
509   // (but still positive) or zero value.
510   //
511   // 9999999999999999999, with 19 nines but no decimal point, is the largest
512   // "repeated nines" integer that fits in a uint64_t.
513   //
514   // The -324/-325 exponents (and -46/-47) confirms the "definition of
515   // kEiselLemireMinInclExp10" comment in charconv.cc.
516   EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-308", &d));
517   EXPECT_EQ(d, 9.999999999999999999e-308);
518   EXPECT_GE(d, DBL_MIN);
519   EXPECT_LT(d, DBL_MIN * 10);
520   EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-324", &d));
521   EXPECT_EQ(d, 9.999999999999999999e-324);
522   EXPECT_GE(d, DBL_TRUE_MIN);
523   EXPECT_LT(d, DBL_TRUE_MIN * 10);
524   EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-325", &d));
525   EXPECT_EQ(d, 0);
526   // Ditto, but for Atof instead of Atod.
527   EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-38", &f));
528   EXPECT_EQ(f, 9.999999999999999999e-38f);
529   EXPECT_GE(f, FLT_MIN);
530   EXPECT_LT(f, FLT_MIN * 10);
531   EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-46", &f));
532   EXPECT_EQ(f, 9.999999999999999999e-46f);
533   EXPECT_GE(f, FLT_TRUE_MIN);
534   EXPECT_LT(f, FLT_TRUE_MIN * 10);
535   EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-47", &f));
536   EXPECT_EQ(f, 0);
537 
538   // Leading and/or trailing whitespace is OK.
539   EXPECT_TRUE(absl::SimpleAtod("  \t\r\n  2.718", &d));
540   EXPECT_EQ(d, 2.718);
541   EXPECT_TRUE(absl::SimpleAtod("  3.141  ", &d));
542   EXPECT_EQ(d, 3.141);
543 
544   // Leading or trailing not-whitespace is not OK.
545   EXPECT_FALSE(absl::SimpleAtod("n 0", &d));
546   EXPECT_FALSE(absl::SimpleAtod("0n ", &d));
547 
548   // Multiple leading 0s are OK.
549   EXPECT_TRUE(absl::SimpleAtod("000123", &d));
550   EXPECT_EQ(d, 123);
551   EXPECT_TRUE(absl::SimpleAtod("000.456", &d));
552   EXPECT_EQ(d, 0.456);
553 
554   // An absent leading 0 (for a fraction < 1) is OK.
555   EXPECT_TRUE(absl::SimpleAtod(".5", &d));
556   EXPECT_EQ(d, 0.5);
557   EXPECT_TRUE(absl::SimpleAtod("-.707", &d));
558   EXPECT_EQ(d, -0.707);
559 
560   // Unary + is OK.
561   EXPECT_TRUE(absl::SimpleAtod("+6.0221408e+23", &d));
562   EXPECT_EQ(d, 6.0221408e+23);
563 
564   // Underscores are not OK.
565   EXPECT_FALSE(absl::SimpleAtod("123_456", &d));
566 
567   // The decimal separator must be '.' and is never ','.
568   EXPECT_TRUE(absl::SimpleAtod("8.9", &d));
569   EXPECT_FALSE(absl::SimpleAtod("8,9", &d));
570 
571   // These examples are called out in the EiselLemire function's comments.
572   EXPECT_TRUE(absl::SimpleAtod("4503599627370497.5", &d));
573   EXPECT_EQ(d, 4503599627370497.5);
574   EXPECT_TRUE(absl::SimpleAtod("1e+23", &d));
575   EXPECT_EQ(d, 1e+23);
576   EXPECT_TRUE(absl::SimpleAtod("9223372036854775807", &d));
577   EXPECT_EQ(d, 9223372036854775807);
578   // Ditto, but for Atof instead of Atod.
579   EXPECT_TRUE(absl::SimpleAtof("0.0625", &f));
580   EXPECT_EQ(f, 0.0625f);
581   EXPECT_TRUE(absl::SimpleAtof("20040229.0", &f));
582   EXPECT_EQ(f, 20040229.0f);
583   EXPECT_TRUE(absl::SimpleAtof("2147483647.0", &f));
584   EXPECT_EQ(f, 2147483647.0f);
585 
586   // Some parsing algorithms don't always round correctly (but absl::SimpleAtod
587   // should). This test case comes from
588   // https://github.com/serde-rs/json/issues/707
589   //
590   // See also atod_manual_test.cc for running many more test cases.
591   EXPECT_TRUE(absl::SimpleAtod("122.416294033786585", &d));
592   EXPECT_EQ(d, 122.416294033786585);
593   EXPECT_TRUE(absl::SimpleAtof("122.416294033786585", &f));
594   EXPECT_EQ(f, 122.416294033786585f);
595 }
596 
TEST(NumbersTest,Prefixes)597 TEST(NumbersTest, Prefixes) {
598   double d;
599   EXPECT_FALSE(absl::SimpleAtod("++1", &d));
600   EXPECT_FALSE(absl::SimpleAtod("+-1", &d));
601   EXPECT_FALSE(absl::SimpleAtod("-+1", &d));
602   EXPECT_FALSE(absl::SimpleAtod("--1", &d));
603   EXPECT_TRUE(absl::SimpleAtod("-1", &d));
604   EXPECT_EQ(d, -1.);
605   EXPECT_TRUE(absl::SimpleAtod("+1", &d));
606   EXPECT_EQ(d, +1.);
607 
608   float f;
609   EXPECT_FALSE(absl::SimpleAtof("++1", &f));
610   EXPECT_FALSE(absl::SimpleAtof("+-1", &f));
611   EXPECT_FALSE(absl::SimpleAtof("-+1", &f));
612   EXPECT_FALSE(absl::SimpleAtof("--1", &f));
613   EXPECT_TRUE(absl::SimpleAtof("-1", &f));
614   EXPECT_EQ(f, -1.f);
615   EXPECT_TRUE(absl::SimpleAtof("+1", &f));
616   EXPECT_EQ(f, +1.f);
617 }
618 
TEST(NumbersTest,Atoenum)619 TEST(NumbersTest, Atoenum) {
620   enum E01 {
621     E01_zero = 0,
622     E01_one = 1,
623   };
624 
625   VerifySimpleAtoiGood<E01>(E01_zero, E01_zero);
626   VerifySimpleAtoiGood<E01>(E01_one, E01_one);
627 
628   enum E_101 {
629     E_101_minusone = -1,
630     E_101_zero = 0,
631     E_101_one = 1,
632   };
633 
634   VerifySimpleAtoiGood<E_101>(E_101_minusone, E_101_minusone);
635   VerifySimpleAtoiGood<E_101>(E_101_zero, E_101_zero);
636   VerifySimpleAtoiGood<E_101>(E_101_one, E_101_one);
637 
638   enum E_bigint {
639     E_bigint_zero = 0,
640     E_bigint_one = 1,
641     E_bigint_max31 = static_cast<int32_t>(0x7FFFFFFF),
642   };
643 
644   VerifySimpleAtoiGood<E_bigint>(E_bigint_zero, E_bigint_zero);
645   VerifySimpleAtoiGood<E_bigint>(E_bigint_one, E_bigint_one);
646   VerifySimpleAtoiGood<E_bigint>(E_bigint_max31, E_bigint_max31);
647 
648   enum E_fullint {
649     E_fullint_zero = 0,
650     E_fullint_one = 1,
651     E_fullint_max31 = static_cast<int32_t>(0x7FFFFFFF),
652     E_fullint_min32 = INT32_MIN,
653   };
654 
655   VerifySimpleAtoiGood<E_fullint>(E_fullint_zero, E_fullint_zero);
656   VerifySimpleAtoiGood<E_fullint>(E_fullint_one, E_fullint_one);
657   VerifySimpleAtoiGood<E_fullint>(E_fullint_max31, E_fullint_max31);
658   VerifySimpleAtoiGood<E_fullint>(E_fullint_min32, E_fullint_min32);
659 
660   enum E_biguint {
661     E_biguint_zero = 0,
662     E_biguint_one = 1,
663     E_biguint_max31 = static_cast<uint32_t>(0x7FFFFFFF),
664     E_biguint_max32 = static_cast<uint32_t>(0xFFFFFFFF),
665   };
666 
667   VerifySimpleAtoiGood<E_biguint>(E_biguint_zero, E_biguint_zero);
668   VerifySimpleAtoiGood<E_biguint>(E_biguint_one, E_biguint_one);
669   VerifySimpleAtoiGood<E_biguint>(E_biguint_max31, E_biguint_max31);
670   VerifySimpleAtoiGood<E_biguint>(E_biguint_max32, E_biguint_max32);
671 }
672 
673 template <typename int_type, typename in_val_type>
VerifySimpleHexAtoiGood(in_val_type in_value,int_type exp_value)674 void VerifySimpleHexAtoiGood(in_val_type in_value, int_type exp_value) {
675   std::string s;
676   // uint128 can be streamed but not StrCat'd
677   absl::strings_internal::OStringStream strm(&s);
678   if (in_value >= 0) {
679     strm << std::hex << in_value;
680   } else {
681     // Inefficient for small integers, but works with all integral types.
682     strm << "-" << std::hex << -absl::uint128(in_value);
683   }
684   int_type x = static_cast<int_type>(~exp_value);
685   EXPECT_TRUE(SimpleHexAtoi(s, &x))
686       << "in_value=" << std::hex << in_value << " s=" << s << " x=" << x;
687   EXPECT_EQ(exp_value, x);
688   x = static_cast<int_type>(~exp_value);
689   EXPECT_TRUE(SimpleHexAtoi(
690       s.c_str(), &x));  // NOLINT: readability-redundant-string-conversions
691   EXPECT_EQ(exp_value, x);
692 }
693 
694 template <typename int_type, typename in_val_type>
VerifySimpleHexAtoiBad(in_val_type in_value)695 void VerifySimpleHexAtoiBad(in_val_type in_value) {
696   std::string s;
697   // uint128 can be streamed but not StrCat'd
698   absl::strings_internal::OStringStream strm(&s);
699   if (in_value >= 0) {
700     strm << std::hex << in_value;
701   } else {
702     // Inefficient for small integers, but works with all integral types.
703     strm << "-" << std::hex << -absl::uint128(in_value);
704   }
705   int_type x;
706   EXPECT_FALSE(SimpleHexAtoi(s, &x));
707   EXPECT_FALSE(SimpleHexAtoi(
708       s.c_str(), &x));  // NOLINT: readability-redundant-string-conversions
709 }
710 
TEST(NumbersTest,HexAtoi)711 TEST(NumbersTest, HexAtoi) {
712   // SimpleHexAtoi(absl::string_view, int32_t)
713   VerifySimpleHexAtoiGood<int32_t>(0, 0);
714   VerifySimpleHexAtoiGood<int32_t>(0x42, 0x42);
715   VerifySimpleHexAtoiGood<int32_t>(-0x42, -0x42);
716 
717   VerifySimpleHexAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(),
718                                    std::numeric_limits<int32_t>::min());
719   VerifySimpleHexAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(),
720                                    std::numeric_limits<int32_t>::max());
721 
722   // SimpleHexAtoi(absl::string_view, uint32_t)
723   VerifySimpleHexAtoiGood<uint32_t>(0, 0);
724   VerifySimpleHexAtoiGood<uint32_t>(0x42, 0x42);
725   VerifySimpleHexAtoiBad<uint32_t>(-0x42);
726 
727   VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min());
728   VerifySimpleHexAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(),
729                                     std::numeric_limits<int32_t>::max());
730   VerifySimpleHexAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(),
731                                     std::numeric_limits<uint32_t>::max());
732   VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min());
733   VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max());
734   VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max());
735 
736   // SimpleHexAtoi(absl::string_view, int64_t)
737   VerifySimpleHexAtoiGood<int64_t>(0, 0);
738   VerifySimpleHexAtoiGood<int64_t>(0x42, 0x42);
739   VerifySimpleHexAtoiGood<int64_t>(-0x42, -0x42);
740 
741   VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(),
742                                    std::numeric_limits<int32_t>::min());
743   VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(),
744                                    std::numeric_limits<int32_t>::max());
745   VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(),
746                                    std::numeric_limits<uint32_t>::max());
747   VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(),
748                                    std::numeric_limits<int64_t>::min());
749   VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(),
750                                    std::numeric_limits<int64_t>::max());
751   VerifySimpleHexAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max());
752 
753   // SimpleHexAtoi(absl::string_view, uint64_t)
754   VerifySimpleHexAtoiGood<uint64_t>(0, 0);
755   VerifySimpleHexAtoiGood<uint64_t>(0x42, 0x42);
756   VerifySimpleHexAtoiBad<uint64_t>(-0x42);
757 
758   VerifySimpleHexAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min());
759   VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(),
760                                     std::numeric_limits<int32_t>::max());
761   VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(),
762                                     std::numeric_limits<uint32_t>::max());
763   VerifySimpleHexAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min());
764   VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(),
765                                     std::numeric_limits<int64_t>::max());
766   VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(),
767                                     std::numeric_limits<uint64_t>::max());
768 
769   // SimpleHexAtoi(absl::string_view, absl::uint128)
770   VerifySimpleHexAtoiGood<absl::uint128>(0, 0);
771   VerifySimpleHexAtoiGood<absl::uint128>(0x42, 0x42);
772   VerifySimpleHexAtoiBad<absl::uint128>(-0x42);
773 
774   VerifySimpleHexAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min());
775   VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(),
776                                          std::numeric_limits<int32_t>::max());
777   VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(),
778                                          std::numeric_limits<uint32_t>::max());
779   VerifySimpleHexAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min());
780   VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(),
781                                          std::numeric_limits<int64_t>::max());
782   VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(),
783                                          std::numeric_limits<uint64_t>::max());
784   VerifySimpleHexAtoiGood<absl::uint128>(
785       std::numeric_limits<absl::uint128>::max(),
786       std::numeric_limits<absl::uint128>::max());
787 
788   // Some other types
789   VerifySimpleHexAtoiGood<int>(-0x42, -0x42);
790   VerifySimpleHexAtoiGood<int32_t>(-0x42, -0x42);
791   VerifySimpleHexAtoiGood<uint32_t>(0x42, 0x42);
792   VerifySimpleHexAtoiGood<unsigned int>(0x42, 0x42);
793   VerifySimpleHexAtoiGood<int64_t>(-0x42, -0x42);
794   VerifySimpleHexAtoiGood<long>(-0x42, -0x42);  // NOLINT: runtime-int
795   VerifySimpleHexAtoiGood<uint64_t>(0x42, 0x42);
796   VerifySimpleHexAtoiGood<size_t>(0x42, 0x42);
797   VerifySimpleHexAtoiGood<std::string::size_type>(0x42, 0x42);
798 
799   // Number prefix
800   int32_t value;
801   EXPECT_TRUE(safe_strto32_base("0x34234324", &value, 16));
802   EXPECT_EQ(0x34234324, value);
803 
804   EXPECT_TRUE(safe_strto32_base("0X34234324", &value, 16));
805   EXPECT_EQ(0x34234324, value);
806 
807   // ASCII whitespace
808   EXPECT_TRUE(safe_strto32_base(" \t\n 34234324", &value, 16));
809   EXPECT_EQ(0x34234324, value);
810 
811   EXPECT_TRUE(safe_strto32_base("34234324 \t\n ", &value, 16));
812   EXPECT_EQ(0x34234324, value);
813 }
814 
TEST(stringtest,safe_strto32_base)815 TEST(stringtest, safe_strto32_base) {
816   int32_t value;
817   EXPECT_TRUE(safe_strto32_base("0x34234324", &value, 16));
818   EXPECT_EQ(0x34234324, value);
819 
820   EXPECT_TRUE(safe_strto32_base("0X34234324", &value, 16));
821   EXPECT_EQ(0x34234324, value);
822 
823   EXPECT_TRUE(safe_strto32_base("34234324", &value, 16));
824   EXPECT_EQ(0x34234324, value);
825 
826   EXPECT_TRUE(safe_strto32_base("0", &value, 16));
827   EXPECT_EQ(0, value);
828 
829   EXPECT_TRUE(safe_strto32_base(" \t\n -0x34234324", &value, 16));
830   EXPECT_EQ(-0x34234324, value);
831 
832   EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 16));
833   EXPECT_EQ(-0x34234324, value);
834 
835   EXPECT_TRUE(safe_strto32_base("7654321", &value, 8));
836   EXPECT_EQ(07654321, value);
837 
838   EXPECT_TRUE(safe_strto32_base("-01234", &value, 8));
839   EXPECT_EQ(-01234, value);
840 
841   EXPECT_FALSE(safe_strto32_base("1834", &value, 8));
842 
843   // Autodetect base.
844   EXPECT_TRUE(safe_strto32_base("0", &value, 0));
845   EXPECT_EQ(0, value);
846 
847   EXPECT_TRUE(safe_strto32_base("077", &value, 0));
848   EXPECT_EQ(077, value);  // Octal interpretation
849 
850   // Leading zero indicates octal, but then followed by invalid digit.
851   EXPECT_FALSE(safe_strto32_base("088", &value, 0));
852 
853   // Leading 0x indicated hex, but then followed by invalid digit.
854   EXPECT_FALSE(safe_strto32_base("0xG", &value, 0));
855 
856   // Base-10 version.
857   EXPECT_TRUE(safe_strto32_base("34234324", &value, 10));
858   EXPECT_EQ(34234324, value);
859 
860   EXPECT_TRUE(safe_strto32_base("0", &value, 10));
861   EXPECT_EQ(0, value);
862 
863   EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 10));
864   EXPECT_EQ(-34234324, value);
865 
866   EXPECT_TRUE(safe_strto32_base("34234324 \n\t ", &value, 10));
867   EXPECT_EQ(34234324, value);
868 
869   // Invalid ints.
870   EXPECT_FALSE(safe_strto32_base("", &value, 10));
871   EXPECT_FALSE(safe_strto32_base("  ", &value, 10));
872   EXPECT_FALSE(safe_strto32_base("abc", &value, 10));
873   EXPECT_FALSE(safe_strto32_base("34234324a", &value, 10));
874   EXPECT_FALSE(safe_strto32_base("34234.3", &value, 10));
875 
876   // Out of bounds.
877   EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10));
878   EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10));
879 
880   // String version.
881   EXPECT_TRUE(safe_strto32_base(std::string("0x1234"), &value, 16));
882   EXPECT_EQ(0x1234, value);
883 
884   // Base-10 string version.
885   EXPECT_TRUE(safe_strto32_base("1234", &value, 10));
886   EXPECT_EQ(1234, value);
887 }
888 
TEST(stringtest,safe_strto32_range)889 TEST(stringtest, safe_strto32_range) {
890   // These tests verify underflow/overflow behaviour.
891   int32_t value;
892   EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10));
893   EXPECT_EQ(std::numeric_limits<int32_t>::max(), value);
894 
895   EXPECT_TRUE(safe_strto32_base("-2147483648", &value, 10));
896   EXPECT_EQ(std::numeric_limits<int32_t>::min(), value);
897 
898   EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10));
899   EXPECT_EQ(std::numeric_limits<int32_t>::min(), value);
900 }
901 
TEST(stringtest,safe_strto64_range)902 TEST(stringtest, safe_strto64_range) {
903   // These tests verify underflow/overflow behaviour.
904   int64_t value;
905   EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10));
906   EXPECT_EQ(std::numeric_limits<int64_t>::max(), value);
907 
908   EXPECT_TRUE(safe_strto64_base("-9223372036854775808", &value, 10));
909   EXPECT_EQ(std::numeric_limits<int64_t>::min(), value);
910 
911   EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10));
912   EXPECT_EQ(std::numeric_limits<int64_t>::min(), value);
913 }
914 
TEST(stringtest,safe_strto32_leading_substring)915 TEST(stringtest, safe_strto32_leading_substring) {
916   // These tests verify this comment in numbers.h:
917   // On error, returns false, and sets *value to: [...]
918   //   conversion of leading substring if available ("123@@@" -> 123)
919   //   0 if no leading substring available
920   int32_t value;
921   EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 10));
922   EXPECT_EQ(4069, value);
923 
924   EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 8));
925   EXPECT_EQ(0406, value);
926 
927   EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 10));
928   EXPECT_EQ(4069, value);
929 
930   EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 16));
931   EXPECT_EQ(0x4069ba, value);
932 
933   EXPECT_FALSE(safe_strto32_base("@@@", &value, 10));
934   EXPECT_EQ(0, value);  // there was no leading substring
935 }
936 
TEST(stringtest,safe_strto64_leading_substring)937 TEST(stringtest, safe_strto64_leading_substring) {
938   // These tests verify this comment in numbers.h:
939   // On error, returns false, and sets *value to: [...]
940   //   conversion of leading substring if available ("123@@@" -> 123)
941   //   0 if no leading substring available
942   int64_t value;
943   EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 10));
944   EXPECT_EQ(4069, value);
945 
946   EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 8));
947   EXPECT_EQ(0406, value);
948 
949   EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 10));
950   EXPECT_EQ(4069, value);
951 
952   EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 16));
953   EXPECT_EQ(0x4069ba, value);
954 
955   EXPECT_FALSE(safe_strto64_base("@@@", &value, 10));
956   EXPECT_EQ(0, value);  // there was no leading substring
957 }
958 
TEST(stringtest,safe_strto64_base)959 TEST(stringtest, safe_strto64_base) {
960   int64_t value;
961   EXPECT_TRUE(safe_strto64_base("0x3423432448783446", &value, 16));
962   EXPECT_EQ(int64_t{0x3423432448783446}, value);
963 
964   EXPECT_TRUE(safe_strto64_base("3423432448783446", &value, 16));
965   EXPECT_EQ(int64_t{0x3423432448783446}, value);
966 
967   EXPECT_TRUE(safe_strto64_base("0", &value, 16));
968   EXPECT_EQ(0, value);
969 
970   EXPECT_TRUE(safe_strto64_base(" \t\n -0x3423432448783446", &value, 16));
971   EXPECT_EQ(int64_t{-0x3423432448783446}, value);
972 
973   EXPECT_TRUE(safe_strto64_base(" \t\n -3423432448783446", &value, 16));
974   EXPECT_EQ(int64_t{-0x3423432448783446}, value);
975 
976   EXPECT_TRUE(safe_strto64_base("123456701234567012", &value, 8));
977   EXPECT_EQ(int64_t{0123456701234567012}, value);
978 
979   EXPECT_TRUE(safe_strto64_base("-017777777777777", &value, 8));
980   EXPECT_EQ(int64_t{-017777777777777}, value);
981 
982   EXPECT_FALSE(safe_strto64_base("19777777777777", &value, 8));
983 
984   // Autodetect base.
985   EXPECT_TRUE(safe_strto64_base("0", &value, 0));
986   EXPECT_EQ(0, value);
987 
988   EXPECT_TRUE(safe_strto64_base("077", &value, 0));
989   EXPECT_EQ(077, value);  // Octal interpretation
990 
991   // Leading zero indicates octal, but then followed by invalid digit.
992   EXPECT_FALSE(safe_strto64_base("088", &value, 0));
993 
994   // Leading 0x indicated hex, but then followed by invalid digit.
995   EXPECT_FALSE(safe_strto64_base("0xG", &value, 0));
996 
997   // Base-10 version.
998   EXPECT_TRUE(safe_strto64_base("34234324487834466", &value, 10));
999   EXPECT_EQ(int64_t{34234324487834466}, value);
1000 
1001   EXPECT_TRUE(safe_strto64_base("0", &value, 10));
1002   EXPECT_EQ(0, value);
1003 
1004   EXPECT_TRUE(safe_strto64_base(" \t\n -34234324487834466", &value, 10));
1005   EXPECT_EQ(int64_t{-34234324487834466}, value);
1006 
1007   EXPECT_TRUE(safe_strto64_base("34234324487834466 \n\t ", &value, 10));
1008   EXPECT_EQ(int64_t{34234324487834466}, value);
1009 
1010   // Invalid ints.
1011   EXPECT_FALSE(safe_strto64_base("", &value, 10));
1012   EXPECT_FALSE(safe_strto64_base("  ", &value, 10));
1013   EXPECT_FALSE(safe_strto64_base("abc", &value, 10));
1014   EXPECT_FALSE(safe_strto64_base("34234324487834466a", &value, 10));
1015   EXPECT_FALSE(safe_strto64_base("34234487834466.3", &value, 10));
1016 
1017   // Out of bounds.
1018   EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10));
1019   EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10));
1020 
1021   // String version.
1022   EXPECT_TRUE(safe_strto64_base(std::string("0x1234"), &value, 16));
1023   EXPECT_EQ(0x1234, value);
1024 
1025   // Base-10 string version.
1026   EXPECT_TRUE(safe_strto64_base("1234", &value, 10));
1027   EXPECT_EQ(1234, value);
1028 }
1029 
1030 const size_t kNumRandomTests = 10000;
1031 
1032 template <typename IntType>
test_random_integer_parse_base(bool (* parse_func)(absl::string_view,IntType * value,int base))1033 void test_random_integer_parse_base(bool (*parse_func)(absl::string_view,
1034                                                        IntType* value,
1035                                                        int base)) {
1036   using RandomEngine = std::minstd_rand0;
1037   std::random_device rd;
1038   RandomEngine rng(rd());
1039   std::uniform_int_distribution<IntType> random_int(
1040       std::numeric_limits<IntType>::min());
1041   std::uniform_int_distribution<int> random_base(2, 35);
1042   for (size_t i = 0; i < kNumRandomTests; i++) {
1043     IntType value = random_int(rng);
1044     int base = random_base(rng);
1045     std::string str_value;
1046     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
1047     IntType parsed_value;
1048 
1049     // Test successful parse
1050     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
1051     EXPECT_EQ(parsed_value, value);
1052 
1053     // Test overflow
1054     EXPECT_FALSE(
1055         parse_func(absl::StrCat(std::numeric_limits<IntType>::max(), value),
1056                    &parsed_value, base));
1057 
1058     // Test underflow
1059     if (std::numeric_limits<IntType>::min() < 0) {
1060       EXPECT_FALSE(
1061           parse_func(absl::StrCat(std::numeric_limits<IntType>::min(), value),
1062                      &parsed_value, base));
1063     } else {
1064       EXPECT_FALSE(parse_func(absl::StrCat("-", value), &parsed_value, base));
1065     }
1066   }
1067 }
1068 
TEST(stringtest,safe_strto32_random)1069 TEST(stringtest, safe_strto32_random) {
1070   test_random_integer_parse_base<int32_t>(&safe_strto32_base);
1071 }
TEST(stringtest,safe_strto64_random)1072 TEST(stringtest, safe_strto64_random) {
1073   test_random_integer_parse_base<int64_t>(&safe_strto64_base);
1074 }
TEST(stringtest,safe_strtou32_random)1075 TEST(stringtest, safe_strtou32_random) {
1076   test_random_integer_parse_base<uint32_t>(&safe_strtou32_base);
1077 }
TEST(stringtest,safe_strtou64_random)1078 TEST(stringtest, safe_strtou64_random) {
1079   test_random_integer_parse_base<uint64_t>(&safe_strtou64_base);
1080 }
TEST(stringtest,safe_strtou128_random)1081 TEST(stringtest, safe_strtou128_random) {
1082   // random number generators don't work for uint128, and
1083   // uint128 can be streamed but not StrCat'd, so this code must be custom
1084   // implemented for uint128, but is generally the same as what's above.
1085   // test_random_integer_parse_base<absl::uint128>(
1086   //     &absl::numbers_internal::safe_strtou128_base);
1087   using RandomEngine = std::minstd_rand0;
1088   using IntType = absl::uint128;
1089   constexpr auto parse_func = &absl::numbers_internal::safe_strtou128_base;
1090 
1091   std::random_device rd;
1092   RandomEngine rng(rd());
1093   std::uniform_int_distribution<uint64_t> random_uint64(
1094       std::numeric_limits<uint64_t>::min());
1095   std::uniform_int_distribution<int> random_base(2, 35);
1096 
1097   for (size_t i = 0; i < kNumRandomTests; i++) {
1098     IntType value = random_uint64(rng);
1099     value = (value << 64) + random_uint64(rng);
1100     int base = random_base(rng);
1101     std::string str_value;
1102     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
1103     IntType parsed_value;
1104 
1105     // Test successful parse
1106     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
1107     EXPECT_EQ(parsed_value, value);
1108 
1109     // Test overflow
1110     std::string s;
1111     absl::strings_internal::OStringStream(&s)
1112         << std::numeric_limits<IntType>::max() << value;
1113     EXPECT_FALSE(parse_func(s, &parsed_value, base));
1114 
1115     // Test underflow
1116     s.clear();
1117     absl::strings_internal::OStringStream(&s) << "-" << value;
1118     EXPECT_FALSE(parse_func(s, &parsed_value, base));
1119   }
1120 }
TEST(stringtest,safe_strto128_random)1121 TEST(stringtest, safe_strto128_random) {
1122   // random number generators don't work for int128, and
1123   // int128 can be streamed but not StrCat'd, so this code must be custom
1124   // implemented for int128, but is generally the same as what's above.
1125   // test_random_integer_parse_base<absl::int128>(
1126   //     &absl::numbers_internal::safe_strto128_base);
1127   using RandomEngine = std::minstd_rand0;
1128   using IntType = absl::int128;
1129   constexpr auto parse_func = &absl::numbers_internal::safe_strto128_base;
1130 
1131   std::random_device rd;
1132   RandomEngine rng(rd());
1133   std::uniform_int_distribution<int64_t> random_int64(
1134       std::numeric_limits<int64_t>::min());
1135   std::uniform_int_distribution<uint64_t> random_uint64(
1136       std::numeric_limits<uint64_t>::min());
1137   std::uniform_int_distribution<int> random_base(2, 35);
1138 
1139   for (size_t i = 0; i < kNumRandomTests; ++i) {
1140     int64_t high = random_int64(rng);
1141     uint64_t low = random_uint64(rng);
1142     IntType value = absl::MakeInt128(high, low);
1143 
1144     int base = random_base(rng);
1145     std::string str_value;
1146     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
1147     IntType parsed_value;
1148 
1149     // Test successful parse
1150     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
1151     EXPECT_EQ(parsed_value, value);
1152 
1153     // Test overflow
1154     std::string s;
1155     absl::strings_internal::OStringStream(&s)
1156         << std::numeric_limits<IntType>::max() << value;
1157     EXPECT_FALSE(parse_func(s, &parsed_value, base));
1158 
1159     // Test underflow
1160     s.clear();
1161     absl::strings_internal::OStringStream(&s)
1162         << std::numeric_limits<IntType>::min() << value;
1163     EXPECT_FALSE(parse_func(s, &parsed_value, base));
1164   }
1165 }
1166 
TEST(stringtest,safe_strtou32_base)1167 TEST(stringtest, safe_strtou32_base) {
1168   for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) {
1169     const auto& e = strtouint32_test_cases()[i];
1170     uint32_t value;
1171     EXPECT_EQ(e.expect_ok, safe_strtou32_base(e.str, &value, e.base))
1172         << "str=\"" << e.str << "\" base=" << e.base;
1173     if (e.expect_ok) {
1174       EXPECT_EQ(e.expected, value) << "i=" << i << " str=\"" << e.str
1175                                    << "\" base=" << e.base;
1176     }
1177   }
1178 }
1179 
TEST(stringtest,safe_strtou32_base_length_delimited)1180 TEST(stringtest, safe_strtou32_base_length_delimited) {
1181   for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) {
1182     const auto& e = strtouint32_test_cases()[i];
1183     std::string tmp(e.str);
1184     tmp.append("12");  // Adds garbage at the end.
1185 
1186     uint32_t value;
1187     EXPECT_EQ(e.expect_ok,
1188               safe_strtou32_base(absl::string_view(tmp.data(), strlen(e.str)),
1189                                  &value, e.base))
1190         << "str=\"" << e.str << "\" base=" << e.base;
1191     if (e.expect_ok) {
1192       EXPECT_EQ(e.expected, value) << "i=" << i << " str=" << e.str
1193                                    << " base=" << e.base;
1194     }
1195   }
1196 }
1197 
TEST(stringtest,safe_strtou64_base)1198 TEST(stringtest, safe_strtou64_base) {
1199   for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) {
1200     const auto& e = strtouint64_test_cases()[i];
1201     uint64_t value;
1202     EXPECT_EQ(e.expect_ok, safe_strtou64_base(e.str, &value, e.base))
1203         << "str=\"" << e.str << "\" base=" << e.base;
1204     if (e.expect_ok) {
1205       EXPECT_EQ(e.expected, value) << "str=" << e.str << " base=" << e.base;
1206     }
1207   }
1208 }
1209 
TEST(stringtest,safe_strtou64_base_length_delimited)1210 TEST(stringtest, safe_strtou64_base_length_delimited) {
1211   for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) {
1212     const auto& e = strtouint64_test_cases()[i];
1213     std::string tmp(e.str);
1214     tmp.append("12");  // Adds garbage at the end.
1215 
1216     uint64_t value;
1217     EXPECT_EQ(e.expect_ok,
1218               safe_strtou64_base(absl::string_view(tmp.data(), strlen(e.str)),
1219                                  &value, e.base))
1220         << "str=\"" << e.str << "\" base=" << e.base;
1221     if (e.expect_ok) {
1222       EXPECT_EQ(e.expected, value) << "str=\"" << e.str << "\" base=" << e.base;
1223     }
1224   }
1225 }
1226 
1227 // feenableexcept() and fedisableexcept() are extensions supported by some libc
1228 // implementations.
1229 #if defined(__GLIBC__) || defined(__BIONIC__)
1230 #define ABSL_HAVE_FEENABLEEXCEPT 1
1231 #define ABSL_HAVE_FEDISABLEEXCEPT 1
1232 #endif
1233 
1234 class SimpleDtoaTest : public testing::Test {
1235  protected:
SetUp()1236   void SetUp() override {
1237     // Store the current floating point env & clear away any pending exceptions.
1238     feholdexcept(&fp_env_);
1239 #ifdef ABSL_HAVE_FEENABLEEXCEPT
1240     // Turn on floating point exceptions.
1241     feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
1242 #endif
1243   }
1244 
TearDown()1245   void TearDown() override {
1246     // Restore the floating point environment to the original state.
1247     // In theory fedisableexcept is unnecessary; fesetenv will also do it.
1248     // In practice, our toolchains have subtle bugs.
1249 #ifdef ABSL_HAVE_FEDISABLEEXCEPT
1250     fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
1251 #endif
1252     fesetenv(&fp_env_);
1253   }
1254 
ToNineDigits(double value)1255   std::string ToNineDigits(double value) {
1256     char buffer[16];  // more than enough for %.9g
1257     snprintf(buffer, sizeof(buffer), "%.9g", value);
1258     return buffer;
1259   }
1260 
1261   fenv_t fp_env_;
1262 };
1263 
1264 // Run the given runnable functor for "cases" test cases, chosen over the
1265 // available range of float.  pi and e and 1/e are seeded, and then all
1266 // available integer powers of 2 and 10 are multiplied against them.  In
1267 // addition to trying all those values, we try the next higher and next lower
1268 // float, and then we add additional test cases evenly distributed between them.
1269 // Each test case is passed to runnable as both a positive and negative value.
1270 template <typename R>
ExhaustiveFloat(uint32_t cases,R && runnable)1271 void ExhaustiveFloat(uint32_t cases, R&& runnable) {
1272   runnable(0.0f);
1273   runnable(-0.0f);
1274   if (cases >= 2e9) {  // more than 2 billion?  Might as well run them all.
1275     for (float f = 0; f < std::numeric_limits<float>::max(); ) {
1276       f = nextafterf(f, std::numeric_limits<float>::max());
1277       runnable(-f);
1278       runnable(f);
1279     }
1280     return;
1281   }
1282   std::set<float> floats = {3.4028234e38f};
1283   for (float f : {1.0, 3.14159265, 2.718281828, 1 / 2.718281828}) {
1284     for (float testf = f; testf != 0; testf *= 0.1f) floats.insert(testf);
1285     for (float testf = f; testf != 0; testf *= 0.5f) floats.insert(testf);
1286     for (float testf = f; testf < 3e38f / 2; testf *= 2.0f)
1287       floats.insert(testf);
1288     for (float testf = f; testf < 3e38f / 10; testf *= 10) floats.insert(testf);
1289   }
1290 
1291   float last = *floats.begin();
1292 
1293   runnable(last);
1294   runnable(-last);
1295   int iters_per_float = cases / floats.size();
1296   if (iters_per_float == 0) iters_per_float = 1;
1297   for (float f : floats) {
1298     if (f == last) continue;
1299     float testf = std::nextafter(last, std::numeric_limits<float>::max());
1300     runnable(testf);
1301     runnable(-testf);
1302     last = testf;
1303     if (f == last) continue;
1304     double step = (double{f} - last) / iters_per_float;
1305     for (double d = last + step; d < f; d += step) {
1306       testf = d;
1307       if (testf != last) {
1308         runnable(testf);
1309         runnable(-testf);
1310         last = testf;
1311       }
1312     }
1313     testf = std::nextafter(f, 0.0f);
1314     if (testf > last) {
1315       runnable(testf);
1316       runnable(-testf);
1317       last = testf;
1318     }
1319     if (f != last) {
1320       runnable(f);
1321       runnable(-f);
1322       last = f;
1323     }
1324   }
1325 }
1326 
TEST_F(SimpleDtoaTest,ExhaustiveDoubleToSixDigits)1327 TEST_F(SimpleDtoaTest, ExhaustiveDoubleToSixDigits) {
1328   uint64_t test_count = 0;
1329   std::vector<double> mismatches;
1330   auto checker = [&](double d) {
1331     if (d != d) return;  // rule out NaNs
1332     ++test_count;
1333     char sixdigitsbuf[kSixDigitsToBufferSize] = {0};
1334     SixDigitsToBuffer(d, sixdigitsbuf);
1335     char snprintfbuf[kSixDigitsToBufferSize] = {0};
1336     snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d);
1337     if (strcmp(sixdigitsbuf, snprintfbuf) != 0) {
1338       mismatches.push_back(d);
1339       if (mismatches.size() < 10) {
1340         ABSL_RAW_LOG(ERROR, "%s",
1341                      absl::StrCat("Six-digit failure with double.  ", "d=", d,
1342                                   "=", d, " sixdigits=", sixdigitsbuf,
1343                                   " printf(%g)=", snprintfbuf)
1344                          .c_str());
1345       }
1346     }
1347   };
1348   // Some quick sanity checks...
1349   checker(5e-324);
1350   checker(1e-308);
1351   checker(1.0);
1352   checker(1.000005);
1353   checker(1.7976931348623157e308);
1354   checker(0.00390625);
1355 #ifndef _MSC_VER
1356   // on MSVC, snprintf() rounds it to 0.00195313. SixDigitsToBuffer() rounds it
1357   // to 0.00195312 (round half to even).
1358   checker(0.001953125);
1359 #endif
1360   checker(0.005859375);
1361   // Some cases where the rounding is very very close
1362   checker(1.089095e-15);
1363   checker(3.274195e-55);
1364   checker(6.534355e-146);
1365   checker(2.920845e+234);
1366 
1367   if (mismatches.empty()) {
1368     test_count = 0;
1369     ExhaustiveFloat(kFloatNumCases, checker);
1370 
1371     test_count = 0;
1372     std::vector<int> digit_testcases{
1373         100000, 100001, 100002, 100005, 100010, 100020, 100050, 100100,  // misc
1374         195312, 195313,  // 1.953125 is a case where we round down, just barely.
1375         200000, 500000, 800000,  // misc mid-range cases
1376         585937, 585938,  // 5.859375 is a case where we round up, just barely.
1377         900000, 990000, 999000, 999900, 999990, 999996, 999997, 999998, 999999};
1378     if (kFloatNumCases >= 1e9) {
1379       // If at least 1 billion test cases were requested, user wants an
1380       // exhaustive test. So let's test all mantissas, too.
1381       constexpr int min_mantissa = 100000, max_mantissa = 999999;
1382       digit_testcases.resize(max_mantissa - min_mantissa + 1);
1383       std::iota(digit_testcases.begin(), digit_testcases.end(), min_mantissa);
1384     }
1385 
1386     for (int exponent = -324; exponent <= 308; ++exponent) {
1387       double powten = absl::strings_internal::Pow10(exponent);
1388       if (powten == 0) powten = 5e-324;
1389       if (kFloatNumCases >= 1e9) {
1390         // The exhaustive test takes a very long time, so log progress.
1391         char buf[kSixDigitsToBufferSize];
1392         ABSL_RAW_LOG(
1393             INFO, "%s",
1394             absl::StrCat("Exp ", exponent, " powten=", powten, "(", powten,
1395                          ") (",
1396                          std::string(buf, SixDigitsToBuffer(powten, buf)), ")")
1397                 .c_str());
1398       }
1399       for (int digits : digit_testcases) {
1400         if (exponent == 308 && digits >= 179769) break;  // don't overflow!
1401         double digiform = (digits + 0.5) * 0.00001;
1402         double testval = digiform * powten;
1403         double pretestval = nextafter(testval, 0);
1404         double posttestval = nextafter(testval, 1.7976931348623157e308);
1405         checker(testval);
1406         checker(pretestval);
1407         checker(posttestval);
1408       }
1409     }
1410   } else {
1411     EXPECT_EQ(mismatches.size(), 0);
1412     for (size_t i = 0; i < mismatches.size(); ++i) {
1413       if (i > 100) i = mismatches.size() - 1;
1414       double d = mismatches[i];
1415       char sixdigitsbuf[kSixDigitsToBufferSize] = {0};
1416       SixDigitsToBuffer(d, sixdigitsbuf);
1417       char snprintfbuf[kSixDigitsToBufferSize] = {0};
1418       snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d);
1419       double before = nextafter(d, 0.0);
1420       double after = nextafter(d, 1.7976931348623157e308);
1421       char b1[32], b2[kSixDigitsToBufferSize];
1422       ABSL_RAW_LOG(
1423           ERROR, "%s",
1424           absl::StrCat(
1425               "Mismatch #", i, "  d=", d, " (", ToNineDigits(d), ")",
1426               " sixdigits='", sixdigitsbuf, "'", " snprintf='", snprintfbuf,
1427               "'", " Before.=", PerfectDtoa(before), " ",
1428               (SixDigitsToBuffer(before, b2), b2),
1429               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", before), b1),
1430               " Perfect=", PerfectDtoa(d), " ", (SixDigitsToBuffer(d, b2), b2),
1431               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", d), b1),
1432               " After.=.", PerfectDtoa(after), " ",
1433               (SixDigitsToBuffer(after, b2), b2),
1434               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", after), b1))
1435               .c_str());
1436     }
1437   }
1438 }
1439 
TEST(StrToInt32,Partial)1440 TEST(StrToInt32, Partial) {
1441   struct Int32TestLine {
1442     std::string input;
1443     bool status;
1444     int32_t value;
1445   };
1446   const int32_t int32_min = std::numeric_limits<int32_t>::min();
1447   const int32_t int32_max = std::numeric_limits<int32_t>::max();
1448   Int32TestLine int32_test_line[] = {
1449       {"", false, 0},
1450       {" ", false, 0},
1451       {"-", false, 0},
1452       {"123@@@", false, 123},
1453       {absl::StrCat(int32_min, int32_max), false, int32_min},
1454       {absl::StrCat(int32_max, int32_max), false, int32_max},
1455   };
1456 
1457   for (const Int32TestLine& test_line : int32_test_line) {
1458     int32_t value = -2;
1459     bool status = safe_strto32_base(test_line.input, &value, 10);
1460     EXPECT_EQ(test_line.status, status) << test_line.input;
1461     EXPECT_EQ(test_line.value, value) << test_line.input;
1462     value = -2;
1463     status = safe_strto32_base(test_line.input, &value, 10);
1464     EXPECT_EQ(test_line.status, status) << test_line.input;
1465     EXPECT_EQ(test_line.value, value) << test_line.input;
1466     value = -2;
1467     status = safe_strto32_base(absl::string_view(test_line.input), &value, 10);
1468     EXPECT_EQ(test_line.status, status) << test_line.input;
1469     EXPECT_EQ(test_line.value, value) << test_line.input;
1470   }
1471 }
1472 
TEST(StrToUint32,Partial)1473 TEST(StrToUint32, Partial) {
1474   struct Uint32TestLine {
1475     std::string input;
1476     bool status;
1477     uint32_t value;
1478   };
1479   const uint32_t uint32_max = std::numeric_limits<uint32_t>::max();
1480   Uint32TestLine uint32_test_line[] = {
1481       {"", false, 0},
1482       {" ", false, 0},
1483       {"-", false, 0},
1484       {"123@@@", false, 123},
1485       {absl::StrCat(uint32_max, uint32_max), false, uint32_max},
1486   };
1487 
1488   for (const Uint32TestLine& test_line : uint32_test_line) {
1489     uint32_t value = 2;
1490     bool status = safe_strtou32_base(test_line.input, &value, 10);
1491     EXPECT_EQ(test_line.status, status) << test_line.input;
1492     EXPECT_EQ(test_line.value, value) << test_line.input;
1493     value = 2;
1494     status = safe_strtou32_base(test_line.input, &value, 10);
1495     EXPECT_EQ(test_line.status, status) << test_line.input;
1496     EXPECT_EQ(test_line.value, value) << test_line.input;
1497     value = 2;
1498     status = safe_strtou32_base(absl::string_view(test_line.input), &value, 10);
1499     EXPECT_EQ(test_line.status, status) << test_line.input;
1500     EXPECT_EQ(test_line.value, value) << test_line.input;
1501   }
1502 }
1503 
TEST(StrToInt64,Partial)1504 TEST(StrToInt64, Partial) {
1505   struct Int64TestLine {
1506     std::string input;
1507     bool status;
1508     int64_t value;
1509   };
1510   const int64_t int64_min = std::numeric_limits<int64_t>::min();
1511   const int64_t int64_max = std::numeric_limits<int64_t>::max();
1512   Int64TestLine int64_test_line[] = {
1513       {"", false, 0},
1514       {" ", false, 0},
1515       {"-", false, 0},
1516       {"123@@@", false, 123},
1517       {absl::StrCat(int64_min, int64_max), false, int64_min},
1518       {absl::StrCat(int64_max, int64_max), false, int64_max},
1519   };
1520 
1521   for (const Int64TestLine& test_line : int64_test_line) {
1522     int64_t value = -2;
1523     bool status = safe_strto64_base(test_line.input, &value, 10);
1524     EXPECT_EQ(test_line.status, status) << test_line.input;
1525     EXPECT_EQ(test_line.value, value) << test_line.input;
1526     value = -2;
1527     status = safe_strto64_base(test_line.input, &value, 10);
1528     EXPECT_EQ(test_line.status, status) << test_line.input;
1529     EXPECT_EQ(test_line.value, value) << test_line.input;
1530     value = -2;
1531     status = safe_strto64_base(absl::string_view(test_line.input), &value, 10);
1532     EXPECT_EQ(test_line.status, status) << test_line.input;
1533     EXPECT_EQ(test_line.value, value) << test_line.input;
1534   }
1535 }
1536 
TEST(StrToUint64,Partial)1537 TEST(StrToUint64, Partial) {
1538   struct Uint64TestLine {
1539     std::string input;
1540     bool status;
1541     uint64_t value;
1542   };
1543   const uint64_t uint64_max = std::numeric_limits<uint64_t>::max();
1544   Uint64TestLine uint64_test_line[] = {
1545       {"", false, 0},
1546       {" ", false, 0},
1547       {"-", false, 0},
1548       {"123@@@", false, 123},
1549       {absl::StrCat(uint64_max, uint64_max), false, uint64_max},
1550   };
1551 
1552   for (const Uint64TestLine& test_line : uint64_test_line) {
1553     uint64_t value = 2;
1554     bool status = safe_strtou64_base(test_line.input, &value, 10);
1555     EXPECT_EQ(test_line.status, status) << test_line.input;
1556     EXPECT_EQ(test_line.value, value) << test_line.input;
1557     value = 2;
1558     status = safe_strtou64_base(test_line.input, &value, 10);
1559     EXPECT_EQ(test_line.status, status) << test_line.input;
1560     EXPECT_EQ(test_line.value, value) << test_line.input;
1561     value = 2;
1562     status = safe_strtou64_base(absl::string_view(test_line.input), &value, 10);
1563     EXPECT_EQ(test_line.status, status) << test_line.input;
1564     EXPECT_EQ(test_line.value, value) << test_line.input;
1565   }
1566 }
1567 
TEST(StrToInt32Base,PrefixOnly)1568 TEST(StrToInt32Base, PrefixOnly) {
1569   struct Int32TestLine {
1570     std::string input;
1571     bool status;
1572     int32_t value;
1573   };
1574   Int32TestLine int32_test_line[] = {
1575     { "", false, 0 },
1576     { "-", false, 0 },
1577     { "-0", true, 0 },
1578     { "0", true, 0 },
1579     { "0x", false, 0 },
1580     { "-0x", false, 0 },
1581   };
1582   const int base_array[] = { 0, 2, 8, 10, 16 };
1583 
1584   for (const Int32TestLine& line : int32_test_line) {
1585     for (const int base : base_array) {
1586       int32_t value = 2;
1587       bool status = safe_strto32_base(line.input.c_str(), &value, base);
1588       EXPECT_EQ(line.status, status) << line.input << " " << base;
1589       EXPECT_EQ(line.value, value) << line.input << " " << base;
1590       value = 2;
1591       status = safe_strto32_base(line.input, &value, base);
1592       EXPECT_EQ(line.status, status) << line.input << " " << base;
1593       EXPECT_EQ(line.value, value) << line.input << " " << base;
1594       value = 2;
1595       status = safe_strto32_base(absl::string_view(line.input), &value, base);
1596       EXPECT_EQ(line.status, status) << line.input << " " << base;
1597       EXPECT_EQ(line.value, value) << line.input << " " << base;
1598     }
1599   }
1600 }
1601 
TEST(StrToUint32Base,PrefixOnly)1602 TEST(StrToUint32Base, PrefixOnly) {
1603   struct Uint32TestLine {
1604     std::string input;
1605     bool status;
1606     uint32_t value;
1607   };
1608   Uint32TestLine uint32_test_line[] = {
1609     { "", false, 0 },
1610     { "0", true, 0 },
1611     { "0x", false, 0 },
1612   };
1613   const int base_array[] = { 0, 2, 8, 10, 16 };
1614 
1615   for (const Uint32TestLine& line : uint32_test_line) {
1616     for (const int base : base_array) {
1617       uint32_t value = 2;
1618       bool status = safe_strtou32_base(line.input.c_str(), &value, base);
1619       EXPECT_EQ(line.status, status) << line.input << " " << base;
1620       EXPECT_EQ(line.value, value) << line.input << " " << base;
1621       value = 2;
1622       status = safe_strtou32_base(line.input, &value, base);
1623       EXPECT_EQ(line.status, status) << line.input << " " << base;
1624       EXPECT_EQ(line.value, value) << line.input << " " << base;
1625       value = 2;
1626       status = safe_strtou32_base(absl::string_view(line.input), &value, base);
1627       EXPECT_EQ(line.status, status) << line.input << " " << base;
1628       EXPECT_EQ(line.value, value) << line.input << " " << base;
1629     }
1630   }
1631 }
1632 
TEST(StrToInt64Base,PrefixOnly)1633 TEST(StrToInt64Base, PrefixOnly) {
1634   struct Int64TestLine {
1635     std::string input;
1636     bool status;
1637     int64_t value;
1638   };
1639   Int64TestLine int64_test_line[] = {
1640     { "", false, 0 },
1641     { "-", false, 0 },
1642     { "-0", true, 0 },
1643     { "0", true, 0 },
1644     { "0x", false, 0 },
1645     { "-0x", false, 0 },
1646   };
1647   const int base_array[] = { 0, 2, 8, 10, 16 };
1648 
1649   for (const Int64TestLine& line : int64_test_line) {
1650     for (const int base : base_array) {
1651       int64_t value = 2;
1652       bool status = safe_strto64_base(line.input.c_str(), &value, base);
1653       EXPECT_EQ(line.status, status) << line.input << " " << base;
1654       EXPECT_EQ(line.value, value) << line.input << " " << base;
1655       value = 2;
1656       status = safe_strto64_base(line.input, &value, base);
1657       EXPECT_EQ(line.status, status) << line.input << " " << base;
1658       EXPECT_EQ(line.value, value) << line.input << " " << base;
1659       value = 2;
1660       status = safe_strto64_base(absl::string_view(line.input), &value, base);
1661       EXPECT_EQ(line.status, status) << line.input << " " << base;
1662       EXPECT_EQ(line.value, value) << line.input << " " << base;
1663     }
1664   }
1665 }
1666 
TEST(StrToUint64Base,PrefixOnly)1667 TEST(StrToUint64Base, PrefixOnly) {
1668   struct Uint64TestLine {
1669     std::string input;
1670     bool status;
1671     uint64_t value;
1672   };
1673   Uint64TestLine uint64_test_line[] = {
1674     { "", false, 0 },
1675     { "0", true, 0 },
1676     { "0x", false, 0 },
1677   };
1678   const int base_array[] = { 0, 2, 8, 10, 16 };
1679 
1680   for (const Uint64TestLine& line : uint64_test_line) {
1681     for (const int base : base_array) {
1682       uint64_t value = 2;
1683       bool status = safe_strtou64_base(line.input.c_str(), &value, base);
1684       EXPECT_EQ(line.status, status) << line.input << " " << base;
1685       EXPECT_EQ(line.value, value) << line.input << " " << base;
1686       value = 2;
1687       status = safe_strtou64_base(line.input, &value, base);
1688       EXPECT_EQ(line.status, status) << line.input << " " << base;
1689       EXPECT_EQ(line.value, value) << line.input << " " << base;
1690       value = 2;
1691       status = safe_strtou64_base(absl::string_view(line.input), &value, base);
1692       EXPECT_EQ(line.status, status) << line.input << " " << base;
1693       EXPECT_EQ(line.value, value) << line.input << " " << base;
1694     }
1695   }
1696 }
1697 
TestFastHexToBufferZeroPad16(uint64_t v)1698 void TestFastHexToBufferZeroPad16(uint64_t v) {
1699   char buf[16];
1700   auto digits = absl::numbers_internal::FastHexToBufferZeroPad16(v, buf);
1701   absl::string_view res(buf, 16);
1702   char buf2[17];
1703   snprintf(buf2, sizeof(buf2), "%016" PRIx64, v);
1704   EXPECT_EQ(res, buf2) << v;
1705   size_t expected_digits = snprintf(buf2, sizeof(buf2), "%" PRIx64, v);
1706   EXPECT_EQ(digits, expected_digits) << v;
1707 }
1708 
TEST(FastHexToBufferZeroPad16,Smoke)1709 TEST(FastHexToBufferZeroPad16, Smoke) {
1710   TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::min());
1711   TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::max());
1712   TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::min());
1713   TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::max());
1714   absl::BitGen rng;
1715   for (int i = 0; i < 100000; ++i) {
1716     TestFastHexToBufferZeroPad16(
1717         absl::LogUniform(rng, std::numeric_limits<uint64_t>::min(),
1718                          std::numeric_limits<uint64_t>::max()));
1719   }
1720 }
1721 
1722 }  // namespace
1723