• 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 <cinttypes>
23 #include <climits>
24 #include <cmath>
25 #include <cstddef>
26 #include <cstdint>
27 #include <cstdio>
28 #include <cstdlib>
29 #include <cstring>
30 #include <limits>
31 #include <numeric>
32 #include <random>
33 #include <set>
34 #include <string>
35 #include <vector>
36 
37 #include "gmock/gmock.h"
38 #include "gtest/gtest.h"
39 #include "absl/base/internal/raw_logging.h"
40 #include "absl/random/distributions.h"
41 #include "absl/random/random.h"
42 #include "absl/strings/internal/numbers_test_common.h"
43 #include "absl/strings/internal/ostringstream.h"
44 #include "absl/strings/internal/pow10_helper.h"
45 #include "absl/strings/str_cat.h"
46 
47 namespace {
48 
49 using absl::numbers_internal::kSixDigitsToBufferSize;
50 using absl::numbers_internal::safe_strto32_base;
51 using absl::numbers_internal::safe_strto64_base;
52 using absl::numbers_internal::safe_strtou32_base;
53 using absl::numbers_internal::safe_strtou64_base;
54 using absl::numbers_internal::SixDigitsToBuffer;
55 using absl::strings_internal::Itoa;
56 using absl::strings_internal::strtouint32_test_cases;
57 using absl::strings_internal::strtouint64_test_cases;
58 using absl::SimpleAtoi;
59 using testing::Eq;
60 using testing::MatchesRegex;
61 
62 // Number of floats to test with.
63 // 5,000,000 is a reasonable default for a test that only takes a few seconds.
64 // 1,000,000,000+ triggers checking for all possible mantissa values for
65 // double-precision tests. 2,000,000,000+ triggers checking for every possible
66 // single-precision float.
67 const int kFloatNumCases = 5000000;
68 
69 // This is a slow, brute-force routine to compute the exact base-10
70 // representation of a double-precision floating-point number.  It
71 // is useful for debugging only.
PerfectDtoa(double d)72 std::string PerfectDtoa(double d) {
73   if (d == 0) return "0";
74   if (d < 0) return "-" + PerfectDtoa(-d);
75 
76   // Basic theory: decompose d into mantissa and exp, where
77   // d = mantissa * 2^exp, and exp is as close to zero as possible.
78   int64_t mantissa, exp = 0;
79   while (d >= 1ULL << 63) ++exp, d *= 0.5;
80   while ((mantissa = d) != d) --exp, d *= 2.0;
81 
82   // Then convert mantissa to ASCII, and either double it (if
83   // exp > 0) or halve it (if exp < 0) repeatedly.  "halve it"
84   // in this case means multiplying it by five and dividing by 10.
85   constexpr int maxlen = 1100;  // worst case is actually 1030 or so.
86   char buf[maxlen + 5];
87   for (int64_t num = mantissa, pos = maxlen; --pos >= 0;) {
88     buf[pos] = '0' + (num % 10);
89     num /= 10;
90   }
91   char* begin = &buf[0];
92   char* end = buf + maxlen;
93   for (int i = 0; i != exp; i += (exp > 0) ? 1 : -1) {
94     int carry = 0;
95     for (char* p = end; --p != begin;) {
96       int dig = *p - '0';
97       dig = dig * (exp > 0 ? 2 : 5) + carry;
98       carry = dig / 10;
99       dig %= 10;
100       *p = '0' + dig;
101     }
102   }
103   if (exp < 0) {
104     // "dividing by 10" above means we have to add the decimal point.
105     memmove(end + 1 + exp, end + exp, 1 - exp);
106     end[exp] = '.';
107     ++end;
108   }
109   while (*begin == '0' && begin[1] != '.') ++begin;
110   return {begin, end};
111 }
112 
TEST(ToString,PerfectDtoa)113 TEST(ToString, PerfectDtoa) {
114   EXPECT_THAT(PerfectDtoa(1), Eq("1"));
115   EXPECT_THAT(PerfectDtoa(0.1),
116               Eq("0.1000000000000000055511151231257827021181583404541015625"));
117   EXPECT_THAT(PerfectDtoa(1e24), Eq("999999999999999983222784"));
118   EXPECT_THAT(PerfectDtoa(5e-324), MatchesRegex("0.0000.*625"));
119   for (int i = 0; i < 100; ++i) {
120     for (double multiplier :
121          {1e-300, 1e-200, 1e-100, 0.1, 1.0, 10.0, 1e100, 1e300}) {
122       double d = multiplier * i;
123       std::string s = PerfectDtoa(d);
124       EXPECT_DOUBLE_EQ(d, strtod(s.c_str(), nullptr));
125     }
126   }
127 }
128 
129 template <typename integer>
130 struct MyInteger {
131   integer i;
MyInteger__anon2d9ee7ff0111::MyInteger132   explicit constexpr MyInteger(integer i) : i(i) {}
operator integer__anon2d9ee7ff0111::MyInteger133   constexpr operator integer() const { return i; }
134 
operator +__anon2d9ee7ff0111::MyInteger135   constexpr MyInteger operator+(MyInteger other) const { return i + other.i; }
operator -__anon2d9ee7ff0111::MyInteger136   constexpr MyInteger operator-(MyInteger other) const { return i - other.i; }
operator *__anon2d9ee7ff0111::MyInteger137   constexpr MyInteger operator*(MyInteger other) const { return i * other.i; }
operator /__anon2d9ee7ff0111::MyInteger138   constexpr MyInteger operator/(MyInteger other) const { return i / other.i; }
139 
operator <__anon2d9ee7ff0111::MyInteger140   constexpr bool operator<(MyInteger other) const { return i < other.i; }
operator <=__anon2d9ee7ff0111::MyInteger141   constexpr bool operator<=(MyInteger other) const { return i <= other.i; }
operator ==__anon2d9ee7ff0111::MyInteger142   constexpr bool operator==(MyInteger other) const { return i == other.i; }
operator >=__anon2d9ee7ff0111::MyInteger143   constexpr bool operator>=(MyInteger other) const { return i >= other.i; }
operator >__anon2d9ee7ff0111::MyInteger144   constexpr bool operator>(MyInteger other) const { return i > other.i; }
operator !=__anon2d9ee7ff0111::MyInteger145   constexpr bool operator!=(MyInteger other) const { return i != other.i; }
146 
as_integer__anon2d9ee7ff0111::MyInteger147   integer as_integer() const { return i; }
148 };
149 
150 typedef MyInteger<int64_t> MyInt64;
151 typedef MyInteger<uint64_t> MyUInt64;
152 
CheckInt32(int32_t x)153 void CheckInt32(int32_t x) {
154   char buffer[absl::numbers_internal::kFastToBufferSize];
155   char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
156   std::string expected = std::to_string(x);
157   EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x;
158 
159   char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
160   EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x;
161 }
162 
CheckInt64(int64_t x)163 void CheckInt64(int64_t x) {
164   char buffer[absl::numbers_internal::kFastToBufferSize + 3];
165   buffer[0] = '*';
166   buffer[23] = '*';
167   buffer[24] = '*';
168   char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
169   std::string expected = std::to_string(x);
170   EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x;
171   EXPECT_EQ(buffer[0], '*');
172   EXPECT_EQ(buffer[23], '*');
173   EXPECT_EQ(buffer[24], '*');
174 
175   char* my_actual =
176       absl::numbers_internal::FastIntToBuffer(MyInt64(x), &buffer[1]);
177   EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x;
178 }
179 
CheckUInt32(uint32_t x)180 void CheckUInt32(uint32_t x) {
181   char buffer[absl::numbers_internal::kFastToBufferSize];
182   char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
183   std::string expected = std::to_string(x);
184   EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x;
185 
186   char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
187   EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x;
188 }
189 
CheckUInt64(uint64_t x)190 void CheckUInt64(uint64_t x) {
191   char buffer[absl::numbers_internal::kFastToBufferSize + 1];
192   char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
193   std::string expected = std::to_string(x);
194   EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x;
195 
196   char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
197   EXPECT_EQ(expected, std::string(&buffer[1], generic_actual))
198       << " Input " << x;
199 
200   char* my_actual =
201       absl::numbers_internal::FastIntToBuffer(MyUInt64(x), &buffer[1]);
202   EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x;
203 }
204 
CheckHex64(uint64_t v)205 void CheckHex64(uint64_t v) {
206   char expected[16 + 1];
207   std::string actual = absl::StrCat(absl::Hex(v, absl::kZeroPad16));
208   snprintf(expected, sizeof(expected), "%016" PRIx64, static_cast<uint64_t>(v));
209   EXPECT_EQ(expected, actual) << " Input " << v;
210   actual = absl::StrCat(absl::Hex(v, absl::kSpacePad16));
211   snprintf(expected, sizeof(expected), "%16" PRIx64, static_cast<uint64_t>(v));
212   EXPECT_EQ(expected, actual) << " Input " << v;
213 }
214 
TEST(Numbers,TestFastPrints)215 TEST(Numbers, TestFastPrints) {
216   for (int i = -100; i <= 100; i++) {
217     CheckInt32(i);
218     CheckInt64(i);
219   }
220   for (int i = 0; i <= 100; i++) {
221     CheckUInt32(i);
222     CheckUInt64(i);
223   }
224   // Test min int to make sure that works
225   CheckInt32(INT_MIN);
226   CheckInt32(INT_MAX);
227   CheckInt64(LONG_MIN);
228   CheckInt64(uint64_t{1000000000});
229   CheckInt64(uint64_t{9999999999});
230   CheckInt64(uint64_t{100000000000000});
231   CheckInt64(uint64_t{999999999999999});
232   CheckInt64(uint64_t{1000000000000000000});
233   CheckInt64(uint64_t{1199999999999999999});
234   CheckInt64(int64_t{-700000000000000000});
235   CheckInt64(LONG_MAX);
236   CheckUInt32(std::numeric_limits<uint32_t>::max());
237   CheckUInt64(uint64_t{1000000000});
238   CheckUInt64(uint64_t{9999999999});
239   CheckUInt64(uint64_t{100000000000000});
240   CheckUInt64(uint64_t{999999999999999});
241   CheckUInt64(uint64_t{1000000000000000000});
242   CheckUInt64(uint64_t{1199999999999999999});
243   CheckUInt64(std::numeric_limits<uint64_t>::max());
244 
245   for (int i = 0; i < 10000; i++) {
246     CheckHex64(i);
247   }
248   CheckHex64(uint64_t{0x123456789abcdef0});
249 }
250 
251 template <typename int_type, typename in_val_type>
VerifySimpleAtoiGood(in_val_type in_value,int_type exp_value)252 void VerifySimpleAtoiGood(in_val_type in_value, int_type exp_value) {
253   std::string s;
254   // (u)int128 can be streamed but not StrCat'd.
255   absl::strings_internal::OStringStream(&s) << in_value;
256   int_type x = static_cast<int_type>(~exp_value);
257   EXPECT_TRUE(SimpleAtoi(s, &x))
258       << "in_value=" << in_value << " s=" << s << " x=" << x;
259   EXPECT_EQ(exp_value, x);
260   x = static_cast<int_type>(~exp_value);
261   EXPECT_TRUE(SimpleAtoi(s.c_str(), &x));
262   EXPECT_EQ(exp_value, x);
263 }
264 
265 template <typename int_type, typename in_val_type>
VerifySimpleAtoiBad(in_val_type in_value)266 void VerifySimpleAtoiBad(in_val_type in_value) {
267   std::string s;
268   // (u)int128 can be streamed but not StrCat'd.
269   absl::strings_internal::OStringStream(&s) << in_value;
270   int_type x;
271   EXPECT_FALSE(SimpleAtoi(s, &x));
272   EXPECT_FALSE(SimpleAtoi(s.c_str(), &x));
273 }
274 
TEST(NumbersTest,Atoi)275 TEST(NumbersTest, Atoi) {
276   // SimpleAtoi(absl::string_view, int32_t)
277   VerifySimpleAtoiGood<int32_t>(0, 0);
278   VerifySimpleAtoiGood<int32_t>(42, 42);
279   VerifySimpleAtoiGood<int32_t>(-42, -42);
280 
281   VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(),
282                                 std::numeric_limits<int32_t>::min());
283   VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(),
284                                 std::numeric_limits<int32_t>::max());
285 
286   // SimpleAtoi(absl::string_view, uint32_t)
287   VerifySimpleAtoiGood<uint32_t>(0, 0);
288   VerifySimpleAtoiGood<uint32_t>(42, 42);
289   VerifySimpleAtoiBad<uint32_t>(-42);
290 
291   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min());
292   VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(),
293                                  std::numeric_limits<int32_t>::max());
294   VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(),
295                                  std::numeric_limits<uint32_t>::max());
296   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min());
297   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max());
298   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max());
299 
300   // SimpleAtoi(absl::string_view, int64_t)
301   VerifySimpleAtoiGood<int64_t>(0, 0);
302   VerifySimpleAtoiGood<int64_t>(42, 42);
303   VerifySimpleAtoiGood<int64_t>(-42, -42);
304 
305   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(),
306                                 std::numeric_limits<int32_t>::min());
307   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(),
308                                 std::numeric_limits<int32_t>::max());
309   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(),
310                                 std::numeric_limits<uint32_t>::max());
311   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(),
312                                 std::numeric_limits<int64_t>::min());
313   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(),
314                                 std::numeric_limits<int64_t>::max());
315   VerifySimpleAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max());
316 
317   // SimpleAtoi(absl::string_view, uint64_t)
318   VerifySimpleAtoiGood<uint64_t>(0, 0);
319   VerifySimpleAtoiGood<uint64_t>(42, 42);
320   VerifySimpleAtoiBad<uint64_t>(-42);
321 
322   VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min());
323   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(),
324                                  std::numeric_limits<int32_t>::max());
325   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(),
326                                  std::numeric_limits<uint32_t>::max());
327   VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min());
328   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(),
329                                  std::numeric_limits<int64_t>::max());
330   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(),
331                                  std::numeric_limits<uint64_t>::max());
332 
333   // SimpleAtoi(absl::string_view, absl::uint128)
334   VerifySimpleAtoiGood<absl::uint128>(0, 0);
335   VerifySimpleAtoiGood<absl::uint128>(42, 42);
336   VerifySimpleAtoiBad<absl::uint128>(-42);
337 
338   VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min());
339   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(),
340                                       std::numeric_limits<int32_t>::max());
341   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(),
342                                       std::numeric_limits<uint32_t>::max());
343   VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min());
344   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(),
345                                       std::numeric_limits<int64_t>::max());
346   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(),
347                                       std::numeric_limits<uint64_t>::max());
348   VerifySimpleAtoiGood<absl::uint128>(
349       std::numeric_limits<absl::uint128>::max(),
350       std::numeric_limits<absl::uint128>::max());
351 
352   // SimpleAtoi(absl::string_view, absl::int128)
353   VerifySimpleAtoiGood<absl::int128>(0, 0);
354   VerifySimpleAtoiGood<absl::int128>(42, 42);
355   VerifySimpleAtoiGood<absl::int128>(-42, -42);
356 
357   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::min(),
358                                       std::numeric_limits<int32_t>::min());
359   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::max(),
360                                       std::numeric_limits<int32_t>::max());
361   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint32_t>::max(),
362                                       std::numeric_limits<uint32_t>::max());
363   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::min(),
364                                       std::numeric_limits<int64_t>::min());
365   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::max(),
366                                       std::numeric_limits<int64_t>::max());
367   VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint64_t>::max(),
368                                       std::numeric_limits<uint64_t>::max());
369   VerifySimpleAtoiGood<absl::int128>(
370       std::numeric_limits<absl::int128>::min(),
371       std::numeric_limits<absl::int128>::min());
372   VerifySimpleAtoiGood<absl::int128>(
373       std::numeric_limits<absl::int128>::max(),
374       std::numeric_limits<absl::int128>::max());
375   VerifySimpleAtoiBad<absl::int128>(std::numeric_limits<absl::uint128>::max());
376 
377   // Some other types
378   VerifySimpleAtoiGood<int>(-42, -42);
379   VerifySimpleAtoiGood<int32_t>(-42, -42);
380   VerifySimpleAtoiGood<uint32_t>(42, 42);
381   VerifySimpleAtoiGood<unsigned int>(42, 42);
382   VerifySimpleAtoiGood<int64_t>(-42, -42);
383   VerifySimpleAtoiGood<long>(-42, -42);  // NOLINT(runtime/int)
384   VerifySimpleAtoiGood<uint64_t>(42, 42);
385   VerifySimpleAtoiGood<size_t>(42, 42);
386   VerifySimpleAtoiGood<std::string::size_type>(42, 42);
387 }
388 
TEST(NumbersTest,Atod)389 TEST(NumbersTest, Atod) {
390   double d;
391   EXPECT_TRUE(absl::SimpleAtod("nan", &d));
392   EXPECT_TRUE(std::isnan(d));
393 }
394 
TEST(NumbersTest,Atoenum)395 TEST(NumbersTest, Atoenum) {
396   enum E01 {
397     E01_zero = 0,
398     E01_one = 1,
399   };
400 
401   VerifySimpleAtoiGood<E01>(E01_zero, E01_zero);
402   VerifySimpleAtoiGood<E01>(E01_one, E01_one);
403 
404   enum E_101 {
405     E_101_minusone = -1,
406     E_101_zero = 0,
407     E_101_one = 1,
408   };
409 
410   VerifySimpleAtoiGood<E_101>(E_101_minusone, E_101_minusone);
411   VerifySimpleAtoiGood<E_101>(E_101_zero, E_101_zero);
412   VerifySimpleAtoiGood<E_101>(E_101_one, E_101_one);
413 
414   enum E_bigint {
415     E_bigint_zero = 0,
416     E_bigint_one = 1,
417     E_bigint_max31 = static_cast<int32_t>(0x7FFFFFFF),
418   };
419 
420   VerifySimpleAtoiGood<E_bigint>(E_bigint_zero, E_bigint_zero);
421   VerifySimpleAtoiGood<E_bigint>(E_bigint_one, E_bigint_one);
422   VerifySimpleAtoiGood<E_bigint>(E_bigint_max31, E_bigint_max31);
423 
424   enum E_fullint {
425     E_fullint_zero = 0,
426     E_fullint_one = 1,
427     E_fullint_max31 = static_cast<int32_t>(0x7FFFFFFF),
428     E_fullint_min32 = INT32_MIN,
429   };
430 
431   VerifySimpleAtoiGood<E_fullint>(E_fullint_zero, E_fullint_zero);
432   VerifySimpleAtoiGood<E_fullint>(E_fullint_one, E_fullint_one);
433   VerifySimpleAtoiGood<E_fullint>(E_fullint_max31, E_fullint_max31);
434   VerifySimpleAtoiGood<E_fullint>(E_fullint_min32, E_fullint_min32);
435 
436   enum E_biguint {
437     E_biguint_zero = 0,
438     E_biguint_one = 1,
439     E_biguint_max31 = static_cast<uint32_t>(0x7FFFFFFF),
440     E_biguint_max32 = static_cast<uint32_t>(0xFFFFFFFF),
441   };
442 
443   VerifySimpleAtoiGood<E_biguint>(E_biguint_zero, E_biguint_zero);
444   VerifySimpleAtoiGood<E_biguint>(E_biguint_one, E_biguint_one);
445   VerifySimpleAtoiGood<E_biguint>(E_biguint_max31, E_biguint_max31);
446   VerifySimpleAtoiGood<E_biguint>(E_biguint_max32, E_biguint_max32);
447 }
448 
TEST(stringtest,safe_strto32_base)449 TEST(stringtest, safe_strto32_base) {
450   int32_t value;
451   EXPECT_TRUE(safe_strto32_base("0x34234324", &value, 16));
452   EXPECT_EQ(0x34234324, value);
453 
454   EXPECT_TRUE(safe_strto32_base("0X34234324", &value, 16));
455   EXPECT_EQ(0x34234324, value);
456 
457   EXPECT_TRUE(safe_strto32_base("34234324", &value, 16));
458   EXPECT_EQ(0x34234324, value);
459 
460   EXPECT_TRUE(safe_strto32_base("0", &value, 16));
461   EXPECT_EQ(0, value);
462 
463   EXPECT_TRUE(safe_strto32_base(" \t\n -0x34234324", &value, 16));
464   EXPECT_EQ(-0x34234324, value);
465 
466   EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 16));
467   EXPECT_EQ(-0x34234324, value);
468 
469   EXPECT_TRUE(safe_strto32_base("7654321", &value, 8));
470   EXPECT_EQ(07654321, value);
471 
472   EXPECT_TRUE(safe_strto32_base("-01234", &value, 8));
473   EXPECT_EQ(-01234, value);
474 
475   EXPECT_FALSE(safe_strto32_base("1834", &value, 8));
476 
477   // Autodetect base.
478   EXPECT_TRUE(safe_strto32_base("0", &value, 0));
479   EXPECT_EQ(0, value);
480 
481   EXPECT_TRUE(safe_strto32_base("077", &value, 0));
482   EXPECT_EQ(077, value);  // Octal interpretation
483 
484   // Leading zero indicates octal, but then followed by invalid digit.
485   EXPECT_FALSE(safe_strto32_base("088", &value, 0));
486 
487   // Leading 0x indicated hex, but then followed by invalid digit.
488   EXPECT_FALSE(safe_strto32_base("0xG", &value, 0));
489 
490   // Base-10 version.
491   EXPECT_TRUE(safe_strto32_base("34234324", &value, 10));
492   EXPECT_EQ(34234324, value);
493 
494   EXPECT_TRUE(safe_strto32_base("0", &value, 10));
495   EXPECT_EQ(0, value);
496 
497   EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 10));
498   EXPECT_EQ(-34234324, value);
499 
500   EXPECT_TRUE(safe_strto32_base("34234324 \n\t ", &value, 10));
501   EXPECT_EQ(34234324, value);
502 
503   // Invalid ints.
504   EXPECT_FALSE(safe_strto32_base("", &value, 10));
505   EXPECT_FALSE(safe_strto32_base("  ", &value, 10));
506   EXPECT_FALSE(safe_strto32_base("abc", &value, 10));
507   EXPECT_FALSE(safe_strto32_base("34234324a", &value, 10));
508   EXPECT_FALSE(safe_strto32_base("34234.3", &value, 10));
509 
510   // Out of bounds.
511   EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10));
512   EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10));
513 
514   // String version.
515   EXPECT_TRUE(safe_strto32_base(std::string("0x1234"), &value, 16));
516   EXPECT_EQ(0x1234, value);
517 
518   // Base-10 string version.
519   EXPECT_TRUE(safe_strto32_base("1234", &value, 10));
520   EXPECT_EQ(1234, value);
521 }
522 
TEST(stringtest,safe_strto32_range)523 TEST(stringtest, safe_strto32_range) {
524   // These tests verify underflow/overflow behaviour.
525   int32_t value;
526   EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10));
527   EXPECT_EQ(std::numeric_limits<int32_t>::max(), value);
528 
529   EXPECT_TRUE(safe_strto32_base("-2147483648", &value, 10));
530   EXPECT_EQ(std::numeric_limits<int32_t>::min(), value);
531 
532   EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10));
533   EXPECT_EQ(std::numeric_limits<int32_t>::min(), value);
534 }
535 
TEST(stringtest,safe_strto64_range)536 TEST(stringtest, safe_strto64_range) {
537   // These tests verify underflow/overflow behaviour.
538   int64_t value;
539   EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10));
540   EXPECT_EQ(std::numeric_limits<int64_t>::max(), value);
541 
542   EXPECT_TRUE(safe_strto64_base("-9223372036854775808", &value, 10));
543   EXPECT_EQ(std::numeric_limits<int64_t>::min(), value);
544 
545   EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10));
546   EXPECT_EQ(std::numeric_limits<int64_t>::min(), value);
547 }
548 
TEST(stringtest,safe_strto32_leading_substring)549 TEST(stringtest, safe_strto32_leading_substring) {
550   // These tests verify this comment in numbers.h:
551   // On error, returns false, and sets *value to: [...]
552   //   conversion of leading substring if available ("123@@@" -> 123)
553   //   0 if no leading substring available
554   int32_t value;
555   EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 10));
556   EXPECT_EQ(4069, value);
557 
558   EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 8));
559   EXPECT_EQ(0406, value);
560 
561   EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 10));
562   EXPECT_EQ(4069, value);
563 
564   EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 16));
565   EXPECT_EQ(0x4069ba, value);
566 
567   EXPECT_FALSE(safe_strto32_base("@@@", &value, 10));
568   EXPECT_EQ(0, value);  // there was no leading substring
569 }
570 
TEST(stringtest,safe_strto64_leading_substring)571 TEST(stringtest, safe_strto64_leading_substring) {
572   // These tests verify this comment in numbers.h:
573   // On error, returns false, and sets *value to: [...]
574   //   conversion of leading substring if available ("123@@@" -> 123)
575   //   0 if no leading substring available
576   int64_t value;
577   EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 10));
578   EXPECT_EQ(4069, value);
579 
580   EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 8));
581   EXPECT_EQ(0406, value);
582 
583   EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 10));
584   EXPECT_EQ(4069, value);
585 
586   EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 16));
587   EXPECT_EQ(0x4069ba, value);
588 
589   EXPECT_FALSE(safe_strto64_base("@@@", &value, 10));
590   EXPECT_EQ(0, value);  // there was no leading substring
591 }
592 
TEST(stringtest,safe_strto64_base)593 TEST(stringtest, safe_strto64_base) {
594   int64_t value;
595   EXPECT_TRUE(safe_strto64_base("0x3423432448783446", &value, 16));
596   EXPECT_EQ(int64_t{0x3423432448783446}, value);
597 
598   EXPECT_TRUE(safe_strto64_base("3423432448783446", &value, 16));
599   EXPECT_EQ(int64_t{0x3423432448783446}, value);
600 
601   EXPECT_TRUE(safe_strto64_base("0", &value, 16));
602   EXPECT_EQ(0, value);
603 
604   EXPECT_TRUE(safe_strto64_base(" \t\n -0x3423432448783446", &value, 16));
605   EXPECT_EQ(int64_t{-0x3423432448783446}, value);
606 
607   EXPECT_TRUE(safe_strto64_base(" \t\n -3423432448783446", &value, 16));
608   EXPECT_EQ(int64_t{-0x3423432448783446}, value);
609 
610   EXPECT_TRUE(safe_strto64_base("123456701234567012", &value, 8));
611   EXPECT_EQ(int64_t{0123456701234567012}, value);
612 
613   EXPECT_TRUE(safe_strto64_base("-017777777777777", &value, 8));
614   EXPECT_EQ(int64_t{-017777777777777}, value);
615 
616   EXPECT_FALSE(safe_strto64_base("19777777777777", &value, 8));
617 
618   // Autodetect base.
619   EXPECT_TRUE(safe_strto64_base("0", &value, 0));
620   EXPECT_EQ(0, value);
621 
622   EXPECT_TRUE(safe_strto64_base("077", &value, 0));
623   EXPECT_EQ(077, value);  // Octal interpretation
624 
625   // Leading zero indicates octal, but then followed by invalid digit.
626   EXPECT_FALSE(safe_strto64_base("088", &value, 0));
627 
628   // Leading 0x indicated hex, but then followed by invalid digit.
629   EXPECT_FALSE(safe_strto64_base("0xG", &value, 0));
630 
631   // Base-10 version.
632   EXPECT_TRUE(safe_strto64_base("34234324487834466", &value, 10));
633   EXPECT_EQ(int64_t{34234324487834466}, value);
634 
635   EXPECT_TRUE(safe_strto64_base("0", &value, 10));
636   EXPECT_EQ(0, value);
637 
638   EXPECT_TRUE(safe_strto64_base(" \t\n -34234324487834466", &value, 10));
639   EXPECT_EQ(int64_t{-34234324487834466}, value);
640 
641   EXPECT_TRUE(safe_strto64_base("34234324487834466 \n\t ", &value, 10));
642   EXPECT_EQ(int64_t{34234324487834466}, value);
643 
644   // Invalid ints.
645   EXPECT_FALSE(safe_strto64_base("", &value, 10));
646   EXPECT_FALSE(safe_strto64_base("  ", &value, 10));
647   EXPECT_FALSE(safe_strto64_base("abc", &value, 10));
648   EXPECT_FALSE(safe_strto64_base("34234324487834466a", &value, 10));
649   EXPECT_FALSE(safe_strto64_base("34234487834466.3", &value, 10));
650 
651   // Out of bounds.
652   EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10));
653   EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10));
654 
655   // String version.
656   EXPECT_TRUE(safe_strto64_base(std::string("0x1234"), &value, 16));
657   EXPECT_EQ(0x1234, value);
658 
659   // Base-10 string version.
660   EXPECT_TRUE(safe_strto64_base("1234", &value, 10));
661   EXPECT_EQ(1234, value);
662 }
663 
664 const size_t kNumRandomTests = 10000;
665 
666 template <typename IntType>
test_random_integer_parse_base(bool (* parse_func)(absl::string_view,IntType * value,int base))667 void test_random_integer_parse_base(bool (*parse_func)(absl::string_view,
668                                                        IntType* value,
669                                                        int base)) {
670   using RandomEngine = std::minstd_rand0;
671   std::random_device rd;
672   RandomEngine rng(rd());
673   std::uniform_int_distribution<IntType> random_int(
674       std::numeric_limits<IntType>::min());
675   std::uniform_int_distribution<int> random_base(2, 35);
676   for (size_t i = 0; i < kNumRandomTests; i++) {
677     IntType value = random_int(rng);
678     int base = random_base(rng);
679     std::string str_value;
680     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
681     IntType parsed_value;
682 
683     // Test successful parse
684     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
685     EXPECT_EQ(parsed_value, value);
686 
687     // Test overflow
688     EXPECT_FALSE(
689         parse_func(absl::StrCat(std::numeric_limits<IntType>::max(), value),
690                    &parsed_value, base));
691 
692     // Test underflow
693     if (std::numeric_limits<IntType>::min() < 0) {
694       EXPECT_FALSE(
695           parse_func(absl::StrCat(std::numeric_limits<IntType>::min(), value),
696                      &parsed_value, base));
697     } else {
698       EXPECT_FALSE(parse_func(absl::StrCat("-", value), &parsed_value, base));
699     }
700   }
701 }
702 
TEST(stringtest,safe_strto32_random)703 TEST(stringtest, safe_strto32_random) {
704   test_random_integer_parse_base<int32_t>(&safe_strto32_base);
705 }
TEST(stringtest,safe_strto64_random)706 TEST(stringtest, safe_strto64_random) {
707   test_random_integer_parse_base<int64_t>(&safe_strto64_base);
708 }
TEST(stringtest,safe_strtou32_random)709 TEST(stringtest, safe_strtou32_random) {
710   test_random_integer_parse_base<uint32_t>(&safe_strtou32_base);
711 }
TEST(stringtest,safe_strtou64_random)712 TEST(stringtest, safe_strtou64_random) {
713   test_random_integer_parse_base<uint64_t>(&safe_strtou64_base);
714 }
TEST(stringtest,safe_strtou128_random)715 TEST(stringtest, safe_strtou128_random) {
716   // random number generators don't work for uint128, and
717   // uint128 can be streamed but not StrCat'd, so this code must be custom
718   // implemented for uint128, but is generally the same as what's above.
719   // test_random_integer_parse_base<absl::uint128>(
720   //     &absl::numbers_internal::safe_strtou128_base);
721   using RandomEngine = std::minstd_rand0;
722   using IntType = absl::uint128;
723   constexpr auto parse_func = &absl::numbers_internal::safe_strtou128_base;
724 
725   std::random_device rd;
726   RandomEngine rng(rd());
727   std::uniform_int_distribution<uint64_t> random_uint64(
728       std::numeric_limits<uint64_t>::min());
729   std::uniform_int_distribution<int> random_base(2, 35);
730 
731   for (size_t i = 0; i < kNumRandomTests; i++) {
732     IntType value = random_uint64(rng);
733     value = (value << 64) + random_uint64(rng);
734     int base = random_base(rng);
735     std::string str_value;
736     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
737     IntType parsed_value;
738 
739     // Test successful parse
740     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
741     EXPECT_EQ(parsed_value, value);
742 
743     // Test overflow
744     std::string s;
745     absl::strings_internal::OStringStream(&s)
746         << std::numeric_limits<IntType>::max() << value;
747     EXPECT_FALSE(parse_func(s, &parsed_value, base));
748 
749     // Test underflow
750     s.clear();
751     absl::strings_internal::OStringStream(&s) << "-" << value;
752     EXPECT_FALSE(parse_func(s, &parsed_value, base));
753   }
754 }
TEST(stringtest,safe_strto128_random)755 TEST(stringtest, safe_strto128_random) {
756   // random number generators don't work for int128, and
757   // int128 can be streamed but not StrCat'd, so this code must be custom
758   // implemented for int128, but is generally the same as what's above.
759   // test_random_integer_parse_base<absl::int128>(
760   //     &absl::numbers_internal::safe_strto128_base);
761   using RandomEngine = std::minstd_rand0;
762   using IntType = absl::int128;
763   constexpr auto parse_func = &absl::numbers_internal::safe_strto128_base;
764 
765   std::random_device rd;
766   RandomEngine rng(rd());
767   std::uniform_int_distribution<int64_t> random_int64(
768       std::numeric_limits<int64_t>::min());
769   std::uniform_int_distribution<uint64_t> random_uint64(
770       std::numeric_limits<uint64_t>::min());
771   std::uniform_int_distribution<int> random_base(2, 35);
772 
773   for (size_t i = 0; i < kNumRandomTests; ++i) {
774     int64_t high = random_int64(rng);
775     uint64_t low = random_uint64(rng);
776     IntType value = absl::MakeInt128(high, low);
777 
778     int base = random_base(rng);
779     std::string str_value;
780     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
781     IntType parsed_value;
782 
783     // Test successful parse
784     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
785     EXPECT_EQ(parsed_value, value);
786 
787     // Test overflow
788     std::string s;
789     absl::strings_internal::OStringStream(&s)
790         << std::numeric_limits<IntType>::max() << value;
791     EXPECT_FALSE(parse_func(s, &parsed_value, base));
792 
793     // Test underflow
794     s.clear();
795     absl::strings_internal::OStringStream(&s)
796         << std::numeric_limits<IntType>::min() << value;
797     EXPECT_FALSE(parse_func(s, &parsed_value, base));
798   }
799 }
800 
TEST(stringtest,safe_strtou32_base)801 TEST(stringtest, safe_strtou32_base) {
802   for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) {
803     const auto& e = strtouint32_test_cases()[i];
804     uint32_t value;
805     EXPECT_EQ(e.expect_ok, safe_strtou32_base(e.str, &value, e.base))
806         << "str=\"" << e.str << "\" base=" << e.base;
807     if (e.expect_ok) {
808       EXPECT_EQ(e.expected, value) << "i=" << i << " str=\"" << e.str
809                                    << "\" base=" << e.base;
810     }
811   }
812 }
813 
TEST(stringtest,safe_strtou32_base_length_delimited)814 TEST(stringtest, safe_strtou32_base_length_delimited) {
815   for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) {
816     const auto& e = strtouint32_test_cases()[i];
817     std::string tmp(e.str);
818     tmp.append("12");  // Adds garbage at the end.
819 
820     uint32_t value;
821     EXPECT_EQ(e.expect_ok,
822               safe_strtou32_base(absl::string_view(tmp.data(), strlen(e.str)),
823                                  &value, e.base))
824         << "str=\"" << e.str << "\" base=" << e.base;
825     if (e.expect_ok) {
826       EXPECT_EQ(e.expected, value) << "i=" << i << " str=" << e.str
827                                    << " base=" << e.base;
828     }
829   }
830 }
831 
TEST(stringtest,safe_strtou64_base)832 TEST(stringtest, safe_strtou64_base) {
833   for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) {
834     const auto& e = strtouint64_test_cases()[i];
835     uint64_t value;
836     EXPECT_EQ(e.expect_ok, safe_strtou64_base(e.str, &value, e.base))
837         << "str=\"" << e.str << "\" base=" << e.base;
838     if (e.expect_ok) {
839       EXPECT_EQ(e.expected, value) << "str=" << e.str << " base=" << e.base;
840     }
841   }
842 }
843 
TEST(stringtest,safe_strtou64_base_length_delimited)844 TEST(stringtest, safe_strtou64_base_length_delimited) {
845   for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) {
846     const auto& e = strtouint64_test_cases()[i];
847     std::string tmp(e.str);
848     tmp.append("12");  // Adds garbage at the end.
849 
850     uint64_t value;
851     EXPECT_EQ(e.expect_ok,
852               safe_strtou64_base(absl::string_view(tmp.data(), strlen(e.str)),
853                                  &value, e.base))
854         << "str=\"" << e.str << "\" base=" << e.base;
855     if (e.expect_ok) {
856       EXPECT_EQ(e.expected, value) << "str=\"" << e.str << "\" base=" << e.base;
857     }
858   }
859 }
860 
861 // feenableexcept() and fedisableexcept() are extensions supported by some libc
862 // implementations.
863 #if defined(__GLIBC__) || defined(__BIONIC__)
864 #define ABSL_HAVE_FEENABLEEXCEPT 1
865 #define ABSL_HAVE_FEDISABLEEXCEPT 1
866 #endif
867 
868 class SimpleDtoaTest : public testing::Test {
869  protected:
SetUp()870   void SetUp() override {
871     // Store the current floating point env & clear away any pending exceptions.
872     feholdexcept(&fp_env_);
873 #ifdef ABSL_HAVE_FEENABLEEXCEPT
874     // Turn on floating point exceptions.
875     feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
876 #endif
877   }
878 
TearDown()879   void TearDown() override {
880     // Restore the floating point environment to the original state.
881     // In theory fedisableexcept is unnecessary; fesetenv will also do it.
882     // In practice, our toolchains have subtle bugs.
883 #ifdef ABSL_HAVE_FEDISABLEEXCEPT
884     fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
885 #endif
886     fesetenv(&fp_env_);
887   }
888 
ToNineDigits(double value)889   std::string ToNineDigits(double value) {
890     char buffer[16];  // more than enough for %.9g
891     snprintf(buffer, sizeof(buffer), "%.9g", value);
892     return buffer;
893   }
894 
895   fenv_t fp_env_;
896 };
897 
898 // Run the given runnable functor for "cases" test cases, chosen over the
899 // available range of float.  pi and e and 1/e are seeded, and then all
900 // available integer powers of 2 and 10 are multiplied against them.  In
901 // addition to trying all those values, we try the next higher and next lower
902 // float, and then we add additional test cases evenly distributed between them.
903 // Each test case is passed to runnable as both a positive and negative value.
904 template <typename R>
ExhaustiveFloat(uint32_t cases,R && runnable)905 void ExhaustiveFloat(uint32_t cases, R&& runnable) {
906   runnable(0.0f);
907   runnable(-0.0f);
908   if (cases >= 2e9) {  // more than 2 billion?  Might as well run them all.
909     for (float f = 0; f < std::numeric_limits<float>::max(); ) {
910       f = nextafterf(f, std::numeric_limits<float>::max());
911       runnable(-f);
912       runnable(f);
913     }
914     return;
915   }
916   std::set<float> floats = {3.4028234e38f};
917   for (float f : {1.0, 3.14159265, 2.718281828, 1 / 2.718281828}) {
918     for (float testf = f; testf != 0; testf *= 0.1f) floats.insert(testf);
919     for (float testf = f; testf != 0; testf *= 0.5f) floats.insert(testf);
920     for (float testf = f; testf < 3e38f / 2; testf *= 2.0f)
921       floats.insert(testf);
922     for (float testf = f; testf < 3e38f / 10; testf *= 10) floats.insert(testf);
923   }
924 
925   float last = *floats.begin();
926 
927   runnable(last);
928   runnable(-last);
929   int iters_per_float = cases / floats.size();
930   if (iters_per_float == 0) iters_per_float = 1;
931   for (float f : floats) {
932     if (f == last) continue;
933     float testf = std::nextafter(last, std::numeric_limits<float>::max());
934     runnable(testf);
935     runnable(-testf);
936     last = testf;
937     if (f == last) continue;
938     double step = (double{f} - last) / iters_per_float;
939     for (double d = last + step; d < f; d += step) {
940       testf = d;
941       if (testf != last) {
942         runnable(testf);
943         runnable(-testf);
944         last = testf;
945       }
946     }
947     testf = std::nextafter(f, 0.0f);
948     if (testf > last) {
949       runnable(testf);
950       runnable(-testf);
951       last = testf;
952     }
953     if (f != last) {
954       runnable(f);
955       runnable(-f);
956       last = f;
957     }
958   }
959 }
960 
TEST_F(SimpleDtoaTest,ExhaustiveDoubleToSixDigits)961 TEST_F(SimpleDtoaTest, ExhaustiveDoubleToSixDigits) {
962   uint64_t test_count = 0;
963   std::vector<double> mismatches;
964   auto checker = [&](double d) {
965     if (d != d) return;  // rule out NaNs
966     ++test_count;
967     char sixdigitsbuf[kSixDigitsToBufferSize] = {0};
968     SixDigitsToBuffer(d, sixdigitsbuf);
969     char snprintfbuf[kSixDigitsToBufferSize] = {0};
970     snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d);
971     if (strcmp(sixdigitsbuf, snprintfbuf) != 0) {
972       mismatches.push_back(d);
973       if (mismatches.size() < 10) {
974         ABSL_RAW_LOG(ERROR, "%s",
975                      absl::StrCat("Six-digit failure with double.  ", "d=", d,
976                                   "=", d, " sixdigits=", sixdigitsbuf,
977                                   " printf(%g)=", snprintfbuf)
978                          .c_str());
979       }
980     }
981   };
982   // Some quick sanity checks...
983   checker(5e-324);
984   checker(1e-308);
985   checker(1.0);
986   checker(1.000005);
987   checker(1.7976931348623157e308);
988   checker(0.00390625);
989 #ifndef _MSC_VER
990   // on MSVC, snprintf() rounds it to 0.00195313. SixDigitsToBuffer() rounds it
991   // to 0.00195312 (round half to even).
992   checker(0.001953125);
993 #endif
994   checker(0.005859375);
995   // Some cases where the rounding is very very close
996   checker(1.089095e-15);
997   checker(3.274195e-55);
998   checker(6.534355e-146);
999   checker(2.920845e+234);
1000 
1001   if (mismatches.empty()) {
1002     test_count = 0;
1003     ExhaustiveFloat(kFloatNumCases, checker);
1004 
1005     test_count = 0;
1006     std::vector<int> digit_testcases{
1007         100000, 100001, 100002, 100005, 100010, 100020, 100050, 100100,  // misc
1008         195312, 195313,  // 1.953125 is a case where we round down, just barely.
1009         200000, 500000, 800000,  // misc mid-range cases
1010         585937, 585938,  // 5.859375 is a case where we round up, just barely.
1011         900000, 990000, 999000, 999900, 999990, 999996, 999997, 999998, 999999};
1012     if (kFloatNumCases >= 1e9) {
1013       // If at least 1 billion test cases were requested, user wants an
1014       // exhaustive test. So let's test all mantissas, too.
1015       constexpr int min_mantissa = 100000, max_mantissa = 999999;
1016       digit_testcases.resize(max_mantissa - min_mantissa + 1);
1017       std::iota(digit_testcases.begin(), digit_testcases.end(), min_mantissa);
1018     }
1019 
1020     for (int exponent = -324; exponent <= 308; ++exponent) {
1021       double powten = absl::strings_internal::Pow10(exponent);
1022       if (powten == 0) powten = 5e-324;
1023       if (kFloatNumCases >= 1e9) {
1024         // The exhaustive test takes a very long time, so log progress.
1025         char buf[kSixDigitsToBufferSize];
1026         ABSL_RAW_LOG(
1027             INFO, "%s",
1028             absl::StrCat("Exp ", exponent, " powten=", powten, "(", powten,
1029                          ") (",
1030                          std::string(buf, SixDigitsToBuffer(powten, buf)), ")")
1031                 .c_str());
1032       }
1033       for (int digits : digit_testcases) {
1034         if (exponent == 308 && digits >= 179769) break;  // don't overflow!
1035         double digiform = (digits + 0.5) * 0.00001;
1036         double testval = digiform * powten;
1037         double pretestval = nextafter(testval, 0);
1038         double posttestval = nextafter(testval, 1.7976931348623157e308);
1039         checker(testval);
1040         checker(pretestval);
1041         checker(posttestval);
1042       }
1043     }
1044   } else {
1045     EXPECT_EQ(mismatches.size(), 0);
1046     for (size_t i = 0; i < mismatches.size(); ++i) {
1047       if (i > 100) i = mismatches.size() - 1;
1048       double d = mismatches[i];
1049       char sixdigitsbuf[kSixDigitsToBufferSize] = {0};
1050       SixDigitsToBuffer(d, sixdigitsbuf);
1051       char snprintfbuf[kSixDigitsToBufferSize] = {0};
1052       snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d);
1053       double before = nextafter(d, 0.0);
1054       double after = nextafter(d, 1.7976931348623157e308);
1055       char b1[32], b2[kSixDigitsToBufferSize];
1056       ABSL_RAW_LOG(
1057           ERROR, "%s",
1058           absl::StrCat(
1059               "Mismatch #", i, "  d=", d, " (", ToNineDigits(d), ")",
1060               " sixdigits='", sixdigitsbuf, "'", " snprintf='", snprintfbuf,
1061               "'", " Before.=", PerfectDtoa(before), " ",
1062               (SixDigitsToBuffer(before, b2), b2),
1063               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", before), b1),
1064               " Perfect=", PerfectDtoa(d), " ", (SixDigitsToBuffer(d, b2), b2),
1065               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", d), b1),
1066               " After.=.", PerfectDtoa(after), " ",
1067               (SixDigitsToBuffer(after, b2), b2),
1068               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", after), b1))
1069               .c_str());
1070     }
1071   }
1072 }
1073 
TEST(StrToInt32,Partial)1074 TEST(StrToInt32, Partial) {
1075   struct Int32TestLine {
1076     std::string input;
1077     bool status;
1078     int32_t value;
1079   };
1080   const int32_t int32_min = std::numeric_limits<int32_t>::min();
1081   const int32_t int32_max = std::numeric_limits<int32_t>::max();
1082   Int32TestLine int32_test_line[] = {
1083       {"", false, 0},
1084       {" ", false, 0},
1085       {"-", false, 0},
1086       {"123@@@", false, 123},
1087       {absl::StrCat(int32_min, int32_max), false, int32_min},
1088       {absl::StrCat(int32_max, int32_max), false, int32_max},
1089   };
1090 
1091   for (const Int32TestLine& test_line : int32_test_line) {
1092     int32_t value = -2;
1093     bool status = safe_strto32_base(test_line.input, &value, 10);
1094     EXPECT_EQ(test_line.status, status) << test_line.input;
1095     EXPECT_EQ(test_line.value, value) << test_line.input;
1096     value = -2;
1097     status = safe_strto32_base(test_line.input, &value, 10);
1098     EXPECT_EQ(test_line.status, status) << test_line.input;
1099     EXPECT_EQ(test_line.value, value) << test_line.input;
1100     value = -2;
1101     status = safe_strto32_base(absl::string_view(test_line.input), &value, 10);
1102     EXPECT_EQ(test_line.status, status) << test_line.input;
1103     EXPECT_EQ(test_line.value, value) << test_line.input;
1104   }
1105 }
1106 
TEST(StrToUint32,Partial)1107 TEST(StrToUint32, Partial) {
1108   struct Uint32TestLine {
1109     std::string input;
1110     bool status;
1111     uint32_t value;
1112   };
1113   const uint32_t uint32_max = std::numeric_limits<uint32_t>::max();
1114   Uint32TestLine uint32_test_line[] = {
1115       {"", false, 0},
1116       {" ", false, 0},
1117       {"-", false, 0},
1118       {"123@@@", false, 123},
1119       {absl::StrCat(uint32_max, uint32_max), false, uint32_max},
1120   };
1121 
1122   for (const Uint32TestLine& test_line : uint32_test_line) {
1123     uint32_t value = 2;
1124     bool status = safe_strtou32_base(test_line.input, &value, 10);
1125     EXPECT_EQ(test_line.status, status) << test_line.input;
1126     EXPECT_EQ(test_line.value, value) << test_line.input;
1127     value = 2;
1128     status = safe_strtou32_base(test_line.input, &value, 10);
1129     EXPECT_EQ(test_line.status, status) << test_line.input;
1130     EXPECT_EQ(test_line.value, value) << test_line.input;
1131     value = 2;
1132     status = safe_strtou32_base(absl::string_view(test_line.input), &value, 10);
1133     EXPECT_EQ(test_line.status, status) << test_line.input;
1134     EXPECT_EQ(test_line.value, value) << test_line.input;
1135   }
1136 }
1137 
TEST(StrToInt64,Partial)1138 TEST(StrToInt64, Partial) {
1139   struct Int64TestLine {
1140     std::string input;
1141     bool status;
1142     int64_t value;
1143   };
1144   const int64_t int64_min = std::numeric_limits<int64_t>::min();
1145   const int64_t int64_max = std::numeric_limits<int64_t>::max();
1146   Int64TestLine int64_test_line[] = {
1147       {"", false, 0},
1148       {" ", false, 0},
1149       {"-", false, 0},
1150       {"123@@@", false, 123},
1151       {absl::StrCat(int64_min, int64_max), false, int64_min},
1152       {absl::StrCat(int64_max, int64_max), false, int64_max},
1153   };
1154 
1155   for (const Int64TestLine& test_line : int64_test_line) {
1156     int64_t value = -2;
1157     bool status = safe_strto64_base(test_line.input, &value, 10);
1158     EXPECT_EQ(test_line.status, status) << test_line.input;
1159     EXPECT_EQ(test_line.value, value) << test_line.input;
1160     value = -2;
1161     status = safe_strto64_base(test_line.input, &value, 10);
1162     EXPECT_EQ(test_line.status, status) << test_line.input;
1163     EXPECT_EQ(test_line.value, value) << test_line.input;
1164     value = -2;
1165     status = safe_strto64_base(absl::string_view(test_line.input), &value, 10);
1166     EXPECT_EQ(test_line.status, status) << test_line.input;
1167     EXPECT_EQ(test_line.value, value) << test_line.input;
1168   }
1169 }
1170 
TEST(StrToUint64,Partial)1171 TEST(StrToUint64, Partial) {
1172   struct Uint64TestLine {
1173     std::string input;
1174     bool status;
1175     uint64_t value;
1176   };
1177   const uint64_t uint64_max = std::numeric_limits<uint64_t>::max();
1178   Uint64TestLine uint64_test_line[] = {
1179       {"", false, 0},
1180       {" ", false, 0},
1181       {"-", false, 0},
1182       {"123@@@", false, 123},
1183       {absl::StrCat(uint64_max, uint64_max), false, uint64_max},
1184   };
1185 
1186   for (const Uint64TestLine& test_line : uint64_test_line) {
1187     uint64_t value = 2;
1188     bool status = safe_strtou64_base(test_line.input, &value, 10);
1189     EXPECT_EQ(test_line.status, status) << test_line.input;
1190     EXPECT_EQ(test_line.value, value) << test_line.input;
1191     value = 2;
1192     status = safe_strtou64_base(test_line.input, &value, 10);
1193     EXPECT_EQ(test_line.status, status) << test_line.input;
1194     EXPECT_EQ(test_line.value, value) << test_line.input;
1195     value = 2;
1196     status = safe_strtou64_base(absl::string_view(test_line.input), &value, 10);
1197     EXPECT_EQ(test_line.status, status) << test_line.input;
1198     EXPECT_EQ(test_line.value, value) << test_line.input;
1199   }
1200 }
1201 
TEST(StrToInt32Base,PrefixOnly)1202 TEST(StrToInt32Base, PrefixOnly) {
1203   struct Int32TestLine {
1204     std::string input;
1205     bool status;
1206     int32_t value;
1207   };
1208   Int32TestLine int32_test_line[] = {
1209     { "", false, 0 },
1210     { "-", false, 0 },
1211     { "-0", true, 0 },
1212     { "0", true, 0 },
1213     { "0x", false, 0 },
1214     { "-0x", false, 0 },
1215   };
1216   const int base_array[] = { 0, 2, 8, 10, 16 };
1217 
1218   for (const Int32TestLine& line : int32_test_line) {
1219     for (const int base : base_array) {
1220       int32_t value = 2;
1221       bool status = safe_strto32_base(line.input.c_str(), &value, base);
1222       EXPECT_EQ(line.status, status) << line.input << " " << base;
1223       EXPECT_EQ(line.value, value) << line.input << " " << base;
1224       value = 2;
1225       status = safe_strto32_base(line.input, &value, base);
1226       EXPECT_EQ(line.status, status) << line.input << " " << base;
1227       EXPECT_EQ(line.value, value) << line.input << " " << base;
1228       value = 2;
1229       status = safe_strto32_base(absl::string_view(line.input), &value, base);
1230       EXPECT_EQ(line.status, status) << line.input << " " << base;
1231       EXPECT_EQ(line.value, value) << line.input << " " << base;
1232     }
1233   }
1234 }
1235 
TEST(StrToUint32Base,PrefixOnly)1236 TEST(StrToUint32Base, PrefixOnly) {
1237   struct Uint32TestLine {
1238     std::string input;
1239     bool status;
1240     uint32_t value;
1241   };
1242   Uint32TestLine uint32_test_line[] = {
1243     { "", false, 0 },
1244     { "0", true, 0 },
1245     { "0x", false, 0 },
1246   };
1247   const int base_array[] = { 0, 2, 8, 10, 16 };
1248 
1249   for (const Uint32TestLine& line : uint32_test_line) {
1250     for (const int base : base_array) {
1251       uint32_t value = 2;
1252       bool status = safe_strtou32_base(line.input.c_str(), &value, base);
1253       EXPECT_EQ(line.status, status) << line.input << " " << base;
1254       EXPECT_EQ(line.value, value) << line.input << " " << base;
1255       value = 2;
1256       status = safe_strtou32_base(line.input, &value, base);
1257       EXPECT_EQ(line.status, status) << line.input << " " << base;
1258       EXPECT_EQ(line.value, value) << line.input << " " << base;
1259       value = 2;
1260       status = safe_strtou32_base(absl::string_view(line.input), &value, base);
1261       EXPECT_EQ(line.status, status) << line.input << " " << base;
1262       EXPECT_EQ(line.value, value) << line.input << " " << base;
1263     }
1264   }
1265 }
1266 
TEST(StrToInt64Base,PrefixOnly)1267 TEST(StrToInt64Base, PrefixOnly) {
1268   struct Int64TestLine {
1269     std::string input;
1270     bool status;
1271     int64_t value;
1272   };
1273   Int64TestLine int64_test_line[] = {
1274     { "", false, 0 },
1275     { "-", false, 0 },
1276     { "-0", true, 0 },
1277     { "0", true, 0 },
1278     { "0x", false, 0 },
1279     { "-0x", false, 0 },
1280   };
1281   const int base_array[] = { 0, 2, 8, 10, 16 };
1282 
1283   for (const Int64TestLine& line : int64_test_line) {
1284     for (const int base : base_array) {
1285       int64_t value = 2;
1286       bool status = safe_strto64_base(line.input.c_str(), &value, base);
1287       EXPECT_EQ(line.status, status) << line.input << " " << base;
1288       EXPECT_EQ(line.value, value) << line.input << " " << base;
1289       value = 2;
1290       status = safe_strto64_base(line.input, &value, base);
1291       EXPECT_EQ(line.status, status) << line.input << " " << base;
1292       EXPECT_EQ(line.value, value) << line.input << " " << base;
1293       value = 2;
1294       status = safe_strto64_base(absl::string_view(line.input), &value, base);
1295       EXPECT_EQ(line.status, status) << line.input << " " << base;
1296       EXPECT_EQ(line.value, value) << line.input << " " << base;
1297     }
1298   }
1299 }
1300 
TEST(StrToUint64Base,PrefixOnly)1301 TEST(StrToUint64Base, PrefixOnly) {
1302   struct Uint64TestLine {
1303     std::string input;
1304     bool status;
1305     uint64_t value;
1306   };
1307   Uint64TestLine uint64_test_line[] = {
1308     { "", false, 0 },
1309     { "0", true, 0 },
1310     { "0x", false, 0 },
1311   };
1312   const int base_array[] = { 0, 2, 8, 10, 16 };
1313 
1314   for (const Uint64TestLine& line : uint64_test_line) {
1315     for (const int base : base_array) {
1316       uint64_t value = 2;
1317       bool status = safe_strtou64_base(line.input.c_str(), &value, base);
1318       EXPECT_EQ(line.status, status) << line.input << " " << base;
1319       EXPECT_EQ(line.value, value) << line.input << " " << base;
1320       value = 2;
1321       status = safe_strtou64_base(line.input, &value, base);
1322       EXPECT_EQ(line.status, status) << line.input << " " << base;
1323       EXPECT_EQ(line.value, value) << line.input << " " << base;
1324       value = 2;
1325       status = safe_strtou64_base(absl::string_view(line.input), &value, base);
1326       EXPECT_EQ(line.status, status) << line.input << " " << base;
1327       EXPECT_EQ(line.value, value) << line.input << " " << base;
1328     }
1329   }
1330 }
1331 
TestFastHexToBufferZeroPad16(uint64_t v)1332 void TestFastHexToBufferZeroPad16(uint64_t v) {
1333   char buf[16];
1334   auto digits = absl::numbers_internal::FastHexToBufferZeroPad16(v, buf);
1335   absl::string_view res(buf, 16);
1336   char buf2[17];
1337   snprintf(buf2, sizeof(buf2), "%016" PRIx64, v);
1338   EXPECT_EQ(res, buf2) << v;
1339   size_t expected_digits = snprintf(buf2, sizeof(buf2), "%" PRIx64, v);
1340   EXPECT_EQ(digits, expected_digits) << v;
1341 }
1342 
TEST(FastHexToBufferZeroPad16,Smoke)1343 TEST(FastHexToBufferZeroPad16, Smoke) {
1344   TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::min());
1345   TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::max());
1346   TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::min());
1347   TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::max());
1348   absl::BitGen rng;
1349   for (int i = 0; i < 100000; ++i) {
1350     TestFastHexToBufferZeroPad16(
1351         absl::LogUniform(rng, std::numeric_limits<uint64_t>::min(),
1352                          std::numeric_limits<uint64_t>::max()));
1353   }
1354 }
1355 
1356 }  // namespace
1357