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