• 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__anone49e85af0111::MyInteger132   explicit constexpr MyInteger(integer i) : i(i) {}
operator integer__anone49e85af0111::MyInteger133   constexpr operator integer() const { return i; }
134 
operator +__anone49e85af0111::MyInteger135   constexpr MyInteger operator+(MyInteger other) const { return i + other.i; }
operator -__anone49e85af0111::MyInteger136   constexpr MyInteger operator-(MyInteger other) const { return i - other.i; }
operator *__anone49e85af0111::MyInteger137   constexpr MyInteger operator*(MyInteger other) const { return i * other.i; }
operator /__anone49e85af0111::MyInteger138   constexpr MyInteger operator/(MyInteger other) const { return i / other.i; }
139 
operator <__anone49e85af0111::MyInteger140   constexpr bool operator<(MyInteger other) const { return i < other.i; }
operator <=__anone49e85af0111::MyInteger141   constexpr bool operator<=(MyInteger other) const { return i <= other.i; }
operator ==__anone49e85af0111::MyInteger142   constexpr bool operator==(MyInteger other) const { return i == other.i; }
operator >=__anone49e85af0111::MyInteger143   constexpr bool operator>=(MyInteger other) const { return i >= other.i; }
operator >__anone49e85af0111::MyInteger144   constexpr bool operator>(MyInteger other) const { return i > other.i; }
operator !=__anone49e85af0111::MyInteger145   constexpr bool operator!=(MyInteger other) const { return i != other.i; }
146 
as_integer__anone49e85af0111::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   // uint128 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 = absl::StrCat(in_value);
268   int_type x;
269   EXPECT_FALSE(SimpleAtoi(s, &x));
270   EXPECT_FALSE(SimpleAtoi(s.c_str(), &x));
271 }
272 
TEST(NumbersTest,Atoi)273 TEST(NumbersTest, Atoi) {
274   // SimpleAtoi(absl::string_view, int32_t)
275   VerifySimpleAtoiGood<int32_t>(0, 0);
276   VerifySimpleAtoiGood<int32_t>(42, 42);
277   VerifySimpleAtoiGood<int32_t>(-42, -42);
278 
279   VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(),
280                                 std::numeric_limits<int32_t>::min());
281   VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(),
282                                 std::numeric_limits<int32_t>::max());
283 
284   // SimpleAtoi(absl::string_view, uint32_t)
285   VerifySimpleAtoiGood<uint32_t>(0, 0);
286   VerifySimpleAtoiGood<uint32_t>(42, 42);
287   VerifySimpleAtoiBad<uint32_t>(-42);
288 
289   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min());
290   VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(),
291                                  std::numeric_limits<int32_t>::max());
292   VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(),
293                                  std::numeric_limits<uint32_t>::max());
294   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min());
295   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max());
296   VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max());
297 
298   // SimpleAtoi(absl::string_view, int64_t)
299   VerifySimpleAtoiGood<int64_t>(0, 0);
300   VerifySimpleAtoiGood<int64_t>(42, 42);
301   VerifySimpleAtoiGood<int64_t>(-42, -42);
302 
303   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(),
304                                 std::numeric_limits<int32_t>::min());
305   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(),
306                                 std::numeric_limits<int32_t>::max());
307   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(),
308                                 std::numeric_limits<uint32_t>::max());
309   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(),
310                                 std::numeric_limits<int64_t>::min());
311   VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(),
312                                 std::numeric_limits<int64_t>::max());
313   VerifySimpleAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max());
314 
315   // SimpleAtoi(absl::string_view, uint64_t)
316   VerifySimpleAtoiGood<uint64_t>(0, 0);
317   VerifySimpleAtoiGood<uint64_t>(42, 42);
318   VerifySimpleAtoiBad<uint64_t>(-42);
319 
320   VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min());
321   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(),
322                                  std::numeric_limits<int32_t>::max());
323   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(),
324                                  std::numeric_limits<uint32_t>::max());
325   VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min());
326   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(),
327                                  std::numeric_limits<int64_t>::max());
328   VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(),
329                                  std::numeric_limits<uint64_t>::max());
330 
331   // SimpleAtoi(absl::string_view, absl::uint128)
332   VerifySimpleAtoiGood<absl::uint128>(0, 0);
333   VerifySimpleAtoiGood<absl::uint128>(42, 42);
334   VerifySimpleAtoiBad<absl::uint128>(-42);
335 
336   VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min());
337   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(),
338                                       std::numeric_limits<int32_t>::max());
339   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(),
340                                       std::numeric_limits<uint32_t>::max());
341   VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min());
342   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(),
343                                       std::numeric_limits<int64_t>::max());
344   VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(),
345                                       std::numeric_limits<uint64_t>::max());
346   VerifySimpleAtoiGood<absl::uint128>(
347       std::numeric_limits<absl::uint128>::max(),
348       std::numeric_limits<absl::uint128>::max());
349 
350   // Some other types
351   VerifySimpleAtoiGood<int>(-42, -42);
352   VerifySimpleAtoiGood<int32_t>(-42, -42);
353   VerifySimpleAtoiGood<uint32_t>(42, 42);
354   VerifySimpleAtoiGood<unsigned int>(42, 42);
355   VerifySimpleAtoiGood<int64_t>(-42, -42);
356   VerifySimpleAtoiGood<long>(-42, -42);  // NOLINT(runtime/int)
357   VerifySimpleAtoiGood<uint64_t>(42, 42);
358   VerifySimpleAtoiGood<size_t>(42, 42);
359   VerifySimpleAtoiGood<std::string::size_type>(42, 42);
360 }
361 
TEST(NumbersTest,Atod)362 TEST(NumbersTest, Atod) {
363   double d;
364   EXPECT_TRUE(absl::SimpleAtod("nan", &d));
365   EXPECT_TRUE(std::isnan(d));
366 }
367 
TEST(NumbersTest,Atoenum)368 TEST(NumbersTest, Atoenum) {
369   enum E01 {
370     E01_zero = 0,
371     E01_one = 1,
372   };
373 
374   VerifySimpleAtoiGood<E01>(E01_zero, E01_zero);
375   VerifySimpleAtoiGood<E01>(E01_one, E01_one);
376 
377   enum E_101 {
378     E_101_minusone = -1,
379     E_101_zero = 0,
380     E_101_one = 1,
381   };
382 
383   VerifySimpleAtoiGood<E_101>(E_101_minusone, E_101_minusone);
384   VerifySimpleAtoiGood<E_101>(E_101_zero, E_101_zero);
385   VerifySimpleAtoiGood<E_101>(E_101_one, E_101_one);
386 
387   enum E_bigint {
388     E_bigint_zero = 0,
389     E_bigint_one = 1,
390     E_bigint_max31 = static_cast<int32_t>(0x7FFFFFFF),
391   };
392 
393   VerifySimpleAtoiGood<E_bigint>(E_bigint_zero, E_bigint_zero);
394   VerifySimpleAtoiGood<E_bigint>(E_bigint_one, E_bigint_one);
395   VerifySimpleAtoiGood<E_bigint>(E_bigint_max31, E_bigint_max31);
396 
397   enum E_fullint {
398     E_fullint_zero = 0,
399     E_fullint_one = 1,
400     E_fullint_max31 = static_cast<int32_t>(0x7FFFFFFF),
401     E_fullint_min32 = INT32_MIN,
402   };
403 
404   VerifySimpleAtoiGood<E_fullint>(E_fullint_zero, E_fullint_zero);
405   VerifySimpleAtoiGood<E_fullint>(E_fullint_one, E_fullint_one);
406   VerifySimpleAtoiGood<E_fullint>(E_fullint_max31, E_fullint_max31);
407   VerifySimpleAtoiGood<E_fullint>(E_fullint_min32, E_fullint_min32);
408 
409   enum E_biguint {
410     E_biguint_zero = 0,
411     E_biguint_one = 1,
412     E_biguint_max31 = static_cast<uint32_t>(0x7FFFFFFF),
413     E_biguint_max32 = static_cast<uint32_t>(0xFFFFFFFF),
414   };
415 
416   VerifySimpleAtoiGood<E_biguint>(E_biguint_zero, E_biguint_zero);
417   VerifySimpleAtoiGood<E_biguint>(E_biguint_one, E_biguint_one);
418   VerifySimpleAtoiGood<E_biguint>(E_biguint_max31, E_biguint_max31);
419   VerifySimpleAtoiGood<E_biguint>(E_biguint_max32, E_biguint_max32);
420 }
421 
TEST(stringtest,safe_strto32_base)422 TEST(stringtest, safe_strto32_base) {
423   int32_t value;
424   EXPECT_TRUE(safe_strto32_base("0x34234324", &value, 16));
425   EXPECT_EQ(0x34234324, value);
426 
427   EXPECT_TRUE(safe_strto32_base("0X34234324", &value, 16));
428   EXPECT_EQ(0x34234324, value);
429 
430   EXPECT_TRUE(safe_strto32_base("34234324", &value, 16));
431   EXPECT_EQ(0x34234324, value);
432 
433   EXPECT_TRUE(safe_strto32_base("0", &value, 16));
434   EXPECT_EQ(0, value);
435 
436   EXPECT_TRUE(safe_strto32_base(" \t\n -0x34234324", &value, 16));
437   EXPECT_EQ(-0x34234324, value);
438 
439   EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 16));
440   EXPECT_EQ(-0x34234324, value);
441 
442   EXPECT_TRUE(safe_strto32_base("7654321", &value, 8));
443   EXPECT_EQ(07654321, value);
444 
445   EXPECT_TRUE(safe_strto32_base("-01234", &value, 8));
446   EXPECT_EQ(-01234, value);
447 
448   EXPECT_FALSE(safe_strto32_base("1834", &value, 8));
449 
450   // Autodetect base.
451   EXPECT_TRUE(safe_strto32_base("0", &value, 0));
452   EXPECT_EQ(0, value);
453 
454   EXPECT_TRUE(safe_strto32_base("077", &value, 0));
455   EXPECT_EQ(077, value);  // Octal interpretation
456 
457   // Leading zero indicates octal, but then followed by invalid digit.
458   EXPECT_FALSE(safe_strto32_base("088", &value, 0));
459 
460   // Leading 0x indicated hex, but then followed by invalid digit.
461   EXPECT_FALSE(safe_strto32_base("0xG", &value, 0));
462 
463   // Base-10 version.
464   EXPECT_TRUE(safe_strto32_base("34234324", &value, 10));
465   EXPECT_EQ(34234324, value);
466 
467   EXPECT_TRUE(safe_strto32_base("0", &value, 10));
468   EXPECT_EQ(0, value);
469 
470   EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 10));
471   EXPECT_EQ(-34234324, value);
472 
473   EXPECT_TRUE(safe_strto32_base("34234324 \n\t ", &value, 10));
474   EXPECT_EQ(34234324, value);
475 
476   // Invalid ints.
477   EXPECT_FALSE(safe_strto32_base("", &value, 10));
478   EXPECT_FALSE(safe_strto32_base("  ", &value, 10));
479   EXPECT_FALSE(safe_strto32_base("abc", &value, 10));
480   EXPECT_FALSE(safe_strto32_base("34234324a", &value, 10));
481   EXPECT_FALSE(safe_strto32_base("34234.3", &value, 10));
482 
483   // Out of bounds.
484   EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10));
485   EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10));
486 
487   // String version.
488   EXPECT_TRUE(safe_strto32_base(std::string("0x1234"), &value, 16));
489   EXPECT_EQ(0x1234, value);
490 
491   // Base-10 string version.
492   EXPECT_TRUE(safe_strto32_base("1234", &value, 10));
493   EXPECT_EQ(1234, value);
494 }
495 
TEST(stringtest,safe_strto32_range)496 TEST(stringtest, safe_strto32_range) {
497   // These tests verify underflow/overflow behaviour.
498   int32_t value;
499   EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10));
500   EXPECT_EQ(std::numeric_limits<int32_t>::max(), value);
501 
502   EXPECT_TRUE(safe_strto32_base("-2147483648", &value, 10));
503   EXPECT_EQ(std::numeric_limits<int32_t>::min(), value);
504 
505   EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10));
506   EXPECT_EQ(std::numeric_limits<int32_t>::min(), value);
507 }
508 
TEST(stringtest,safe_strto64_range)509 TEST(stringtest, safe_strto64_range) {
510   // These tests verify underflow/overflow behaviour.
511   int64_t value;
512   EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10));
513   EXPECT_EQ(std::numeric_limits<int64_t>::max(), value);
514 
515   EXPECT_TRUE(safe_strto64_base("-9223372036854775808", &value, 10));
516   EXPECT_EQ(std::numeric_limits<int64_t>::min(), value);
517 
518   EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10));
519   EXPECT_EQ(std::numeric_limits<int64_t>::min(), value);
520 }
521 
TEST(stringtest,safe_strto32_leading_substring)522 TEST(stringtest, safe_strto32_leading_substring) {
523   // These tests verify this comment in numbers.h:
524   // On error, returns false, and sets *value to: [...]
525   //   conversion of leading substring if available ("123@@@" -> 123)
526   //   0 if no leading substring available
527   int32_t value;
528   EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 10));
529   EXPECT_EQ(4069, value);
530 
531   EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 8));
532   EXPECT_EQ(0406, value);
533 
534   EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 10));
535   EXPECT_EQ(4069, value);
536 
537   EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 16));
538   EXPECT_EQ(0x4069ba, value);
539 
540   EXPECT_FALSE(safe_strto32_base("@@@", &value, 10));
541   EXPECT_EQ(0, value);  // there was no leading substring
542 }
543 
TEST(stringtest,safe_strto64_leading_substring)544 TEST(stringtest, safe_strto64_leading_substring) {
545   // These tests verify this comment in numbers.h:
546   // On error, returns false, and sets *value to: [...]
547   //   conversion of leading substring if available ("123@@@" -> 123)
548   //   0 if no leading substring available
549   int64_t value;
550   EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 10));
551   EXPECT_EQ(4069, value);
552 
553   EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 8));
554   EXPECT_EQ(0406, value);
555 
556   EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 10));
557   EXPECT_EQ(4069, value);
558 
559   EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 16));
560   EXPECT_EQ(0x4069ba, value);
561 
562   EXPECT_FALSE(safe_strto64_base("@@@", &value, 10));
563   EXPECT_EQ(0, value);  // there was no leading substring
564 }
565 
TEST(stringtest,safe_strto64_base)566 TEST(stringtest, safe_strto64_base) {
567   int64_t value;
568   EXPECT_TRUE(safe_strto64_base("0x3423432448783446", &value, 16));
569   EXPECT_EQ(int64_t{0x3423432448783446}, value);
570 
571   EXPECT_TRUE(safe_strto64_base("3423432448783446", &value, 16));
572   EXPECT_EQ(int64_t{0x3423432448783446}, value);
573 
574   EXPECT_TRUE(safe_strto64_base("0", &value, 16));
575   EXPECT_EQ(0, value);
576 
577   EXPECT_TRUE(safe_strto64_base(" \t\n -0x3423432448783446", &value, 16));
578   EXPECT_EQ(int64_t{-0x3423432448783446}, value);
579 
580   EXPECT_TRUE(safe_strto64_base(" \t\n -3423432448783446", &value, 16));
581   EXPECT_EQ(int64_t{-0x3423432448783446}, value);
582 
583   EXPECT_TRUE(safe_strto64_base("123456701234567012", &value, 8));
584   EXPECT_EQ(int64_t{0123456701234567012}, value);
585 
586   EXPECT_TRUE(safe_strto64_base("-017777777777777", &value, 8));
587   EXPECT_EQ(int64_t{-017777777777777}, value);
588 
589   EXPECT_FALSE(safe_strto64_base("19777777777777", &value, 8));
590 
591   // Autodetect base.
592   EXPECT_TRUE(safe_strto64_base("0", &value, 0));
593   EXPECT_EQ(0, value);
594 
595   EXPECT_TRUE(safe_strto64_base("077", &value, 0));
596   EXPECT_EQ(077, value);  // Octal interpretation
597 
598   // Leading zero indicates octal, but then followed by invalid digit.
599   EXPECT_FALSE(safe_strto64_base("088", &value, 0));
600 
601   // Leading 0x indicated hex, but then followed by invalid digit.
602   EXPECT_FALSE(safe_strto64_base("0xG", &value, 0));
603 
604   // Base-10 version.
605   EXPECT_TRUE(safe_strto64_base("34234324487834466", &value, 10));
606   EXPECT_EQ(int64_t{34234324487834466}, value);
607 
608   EXPECT_TRUE(safe_strto64_base("0", &value, 10));
609   EXPECT_EQ(0, value);
610 
611   EXPECT_TRUE(safe_strto64_base(" \t\n -34234324487834466", &value, 10));
612   EXPECT_EQ(int64_t{-34234324487834466}, value);
613 
614   EXPECT_TRUE(safe_strto64_base("34234324487834466 \n\t ", &value, 10));
615   EXPECT_EQ(int64_t{34234324487834466}, value);
616 
617   // Invalid ints.
618   EXPECT_FALSE(safe_strto64_base("", &value, 10));
619   EXPECT_FALSE(safe_strto64_base("  ", &value, 10));
620   EXPECT_FALSE(safe_strto64_base("abc", &value, 10));
621   EXPECT_FALSE(safe_strto64_base("34234324487834466a", &value, 10));
622   EXPECT_FALSE(safe_strto64_base("34234487834466.3", &value, 10));
623 
624   // Out of bounds.
625   EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10));
626   EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10));
627 
628   // String version.
629   EXPECT_TRUE(safe_strto64_base(std::string("0x1234"), &value, 16));
630   EXPECT_EQ(0x1234, value);
631 
632   // Base-10 string version.
633   EXPECT_TRUE(safe_strto64_base("1234", &value, 10));
634   EXPECT_EQ(1234, value);
635 }
636 
637 const size_t kNumRandomTests = 10000;
638 
639 template <typename IntType>
test_random_integer_parse_base(bool (* parse_func)(absl::string_view,IntType * value,int base))640 void test_random_integer_parse_base(bool (*parse_func)(absl::string_view,
641                                                        IntType* value,
642                                                        int base)) {
643   using RandomEngine = std::minstd_rand0;
644   std::random_device rd;
645   RandomEngine rng(rd());
646   std::uniform_int_distribution<IntType> random_int(
647       std::numeric_limits<IntType>::min());
648   std::uniform_int_distribution<int> random_base(2, 35);
649   for (size_t i = 0; i < kNumRandomTests; i++) {
650     IntType value = random_int(rng);
651     int base = random_base(rng);
652     std::string str_value;
653     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
654     IntType parsed_value;
655 
656     // Test successful parse
657     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
658     EXPECT_EQ(parsed_value, value);
659 
660     // Test overflow
661     EXPECT_FALSE(
662         parse_func(absl::StrCat(std::numeric_limits<IntType>::max(), value),
663                    &parsed_value, base));
664 
665     // Test underflow
666     if (std::numeric_limits<IntType>::min() < 0) {
667       EXPECT_FALSE(
668           parse_func(absl::StrCat(std::numeric_limits<IntType>::min(), value),
669                      &parsed_value, base));
670     } else {
671       EXPECT_FALSE(parse_func(absl::StrCat("-", value), &parsed_value, base));
672     }
673   }
674 }
675 
TEST(stringtest,safe_strto32_random)676 TEST(stringtest, safe_strto32_random) {
677   test_random_integer_parse_base<int32_t>(&safe_strto32_base);
678 }
TEST(stringtest,safe_strto64_random)679 TEST(stringtest, safe_strto64_random) {
680   test_random_integer_parse_base<int64_t>(&safe_strto64_base);
681 }
TEST(stringtest,safe_strtou32_random)682 TEST(stringtest, safe_strtou32_random) {
683   test_random_integer_parse_base<uint32_t>(&safe_strtou32_base);
684 }
TEST(stringtest,safe_strtou64_random)685 TEST(stringtest, safe_strtou64_random) {
686   test_random_integer_parse_base<uint64_t>(&safe_strtou64_base);
687 }
TEST(stringtest,safe_strtou128_random)688 TEST(stringtest, safe_strtou128_random) {
689   // random number generators don't work for uint128, and
690   // uint128 can be streamed but not StrCat'd, so this code must be custom
691   // implemented for uint128, but is generally the same as what's above.
692   // test_random_integer_parse_base<absl::uint128>(
693   //     &absl::numbers_internal::safe_strtou128_base);
694   using RandomEngine = std::minstd_rand0;
695   using IntType = absl::uint128;
696   constexpr auto parse_func = &absl::numbers_internal::safe_strtou128_base;
697 
698   std::random_device rd;
699   RandomEngine rng(rd());
700   std::uniform_int_distribution<uint64_t> random_uint64(
701       std::numeric_limits<uint64_t>::min());
702   std::uniform_int_distribution<int> random_base(2, 35);
703 
704   for (size_t i = 0; i < kNumRandomTests; i++) {
705     IntType value = random_uint64(rng);
706     value = (value << 64) + random_uint64(rng);
707     int base = random_base(rng);
708     std::string str_value;
709     EXPECT_TRUE(Itoa<IntType>(value, base, &str_value));
710     IntType parsed_value;
711 
712     // Test successful parse
713     EXPECT_TRUE(parse_func(str_value, &parsed_value, base));
714     EXPECT_EQ(parsed_value, value);
715 
716     // Test overflow
717     std::string s;
718     absl::strings_internal::OStringStream(&s)
719         << std::numeric_limits<IntType>::max() << value;
720     EXPECT_FALSE(parse_func(s, &parsed_value, base));
721 
722     // Test underflow
723     s.clear();
724     absl::strings_internal::OStringStream(&s) << "-" << value;
725     EXPECT_FALSE(parse_func(s, &parsed_value, base));
726   }
727 }
728 
TEST(stringtest,safe_strtou32_base)729 TEST(stringtest, safe_strtou32_base) {
730   for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) {
731     const auto& e = strtouint32_test_cases()[i];
732     uint32_t value;
733     EXPECT_EQ(e.expect_ok, safe_strtou32_base(e.str, &value, e.base))
734         << "str=\"" << e.str << "\" base=" << e.base;
735     if (e.expect_ok) {
736       EXPECT_EQ(e.expected, value) << "i=" << i << " str=\"" << e.str
737                                    << "\" base=" << e.base;
738     }
739   }
740 }
741 
TEST(stringtest,safe_strtou32_base_length_delimited)742 TEST(stringtest, safe_strtou32_base_length_delimited) {
743   for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) {
744     const auto& e = strtouint32_test_cases()[i];
745     std::string tmp(e.str);
746     tmp.append("12");  // Adds garbage at the end.
747 
748     uint32_t value;
749     EXPECT_EQ(e.expect_ok,
750               safe_strtou32_base(absl::string_view(tmp.data(), strlen(e.str)),
751                                  &value, e.base))
752         << "str=\"" << e.str << "\" base=" << e.base;
753     if (e.expect_ok) {
754       EXPECT_EQ(e.expected, value) << "i=" << i << " str=" << e.str
755                                    << " base=" << e.base;
756     }
757   }
758 }
759 
TEST(stringtest,safe_strtou64_base)760 TEST(stringtest, safe_strtou64_base) {
761   for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) {
762     const auto& e = strtouint64_test_cases()[i];
763     uint64_t value;
764     EXPECT_EQ(e.expect_ok, safe_strtou64_base(e.str, &value, e.base))
765         << "str=\"" << e.str << "\" base=" << e.base;
766     if (e.expect_ok) {
767       EXPECT_EQ(e.expected, value) << "str=" << e.str << " base=" << e.base;
768     }
769   }
770 }
771 
TEST(stringtest,safe_strtou64_base_length_delimited)772 TEST(stringtest, safe_strtou64_base_length_delimited) {
773   for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) {
774     const auto& e = strtouint64_test_cases()[i];
775     std::string tmp(e.str);
776     tmp.append("12");  // Adds garbage at the end.
777 
778     uint64_t value;
779     EXPECT_EQ(e.expect_ok,
780               safe_strtou64_base(absl::string_view(tmp.data(), strlen(e.str)),
781                                  &value, e.base))
782         << "str=\"" << e.str << "\" base=" << e.base;
783     if (e.expect_ok) {
784       EXPECT_EQ(e.expected, value) << "str=\"" << e.str << "\" base=" << e.base;
785     }
786   }
787 }
788 
789 // feenableexcept() and fedisableexcept() are extensions supported by some libc
790 // implementations.
791 #if defined(__GLIBC__) || defined(__BIONIC__)
792 #define ABSL_HAVE_FEENABLEEXCEPT 1
793 #define ABSL_HAVE_FEDISABLEEXCEPT 1
794 #endif
795 
796 class SimpleDtoaTest : public testing::Test {
797  protected:
SetUp()798   void SetUp() override {
799     // Store the current floating point env & clear away any pending exceptions.
800     feholdexcept(&fp_env_);
801 #ifdef ABSL_HAVE_FEENABLEEXCEPT
802     // Turn on floating point exceptions.
803     feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
804 #endif
805   }
806 
TearDown()807   void TearDown() override {
808     // Restore the floating point environment to the original state.
809     // In theory fedisableexcept is unnecessary; fesetenv will also do it.
810     // In practice, our toolchains have subtle bugs.
811 #ifdef ABSL_HAVE_FEDISABLEEXCEPT
812     fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
813 #endif
814     fesetenv(&fp_env_);
815   }
816 
ToNineDigits(double value)817   std::string ToNineDigits(double value) {
818     char buffer[16];  // more than enough for %.9g
819     snprintf(buffer, sizeof(buffer), "%.9g", value);
820     return buffer;
821   }
822 
823   fenv_t fp_env_;
824 };
825 
826 // Run the given runnable functor for "cases" test cases, chosen over the
827 // available range of float.  pi and e and 1/e are seeded, and then all
828 // available integer powers of 2 and 10 are multiplied against them.  In
829 // addition to trying all those values, we try the next higher and next lower
830 // float, and then we add additional test cases evenly distributed between them.
831 // Each test case is passed to runnable as both a positive and negative value.
832 template <typename R>
ExhaustiveFloat(uint32_t cases,R && runnable)833 void ExhaustiveFloat(uint32_t cases, R&& runnable) {
834   runnable(0.0f);
835   runnable(-0.0f);
836   if (cases >= 2e9) {  // more than 2 billion?  Might as well run them all.
837     for (float f = 0; f < std::numeric_limits<float>::max(); ) {
838       f = nextafterf(f, std::numeric_limits<float>::max());
839       runnable(-f);
840       runnable(f);
841     }
842     return;
843   }
844   std::set<float> floats = {3.4028234e38f};
845   for (float f : {1.0, 3.14159265, 2.718281828, 1 / 2.718281828}) {
846     for (float testf = f; testf != 0; testf *= 0.1f) floats.insert(testf);
847     for (float testf = f; testf != 0; testf *= 0.5f) floats.insert(testf);
848     for (float testf = f; testf < 3e38f / 2; testf *= 2.0f)
849       floats.insert(testf);
850     for (float testf = f; testf < 3e38f / 10; testf *= 10) floats.insert(testf);
851   }
852 
853   float last = *floats.begin();
854 
855   runnable(last);
856   runnable(-last);
857   int iters_per_float = cases / floats.size();
858   if (iters_per_float == 0) iters_per_float = 1;
859   for (float f : floats) {
860     if (f == last) continue;
861     float testf = std::nextafter(last, std::numeric_limits<float>::max());
862     runnable(testf);
863     runnable(-testf);
864     last = testf;
865     if (f == last) continue;
866     double step = (double{f} - last) / iters_per_float;
867     for (double d = last + step; d < f; d += step) {
868       testf = d;
869       if (testf != last) {
870         runnable(testf);
871         runnable(-testf);
872         last = testf;
873       }
874     }
875     testf = std::nextafter(f, 0.0f);
876     if (testf > last) {
877       runnable(testf);
878       runnable(-testf);
879       last = testf;
880     }
881     if (f != last) {
882       runnable(f);
883       runnable(-f);
884       last = f;
885     }
886   }
887 }
888 
TEST_F(SimpleDtoaTest,ExhaustiveDoubleToSixDigits)889 TEST_F(SimpleDtoaTest, ExhaustiveDoubleToSixDigits) {
890   uint64_t test_count = 0;
891   std::vector<double> mismatches;
892   auto checker = [&](double d) {
893     if (d != d) return;  // rule out NaNs
894     ++test_count;
895     char sixdigitsbuf[kSixDigitsToBufferSize] = {0};
896     SixDigitsToBuffer(d, sixdigitsbuf);
897     char snprintfbuf[kSixDigitsToBufferSize] = {0};
898     snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d);
899     if (strcmp(sixdigitsbuf, snprintfbuf) != 0) {
900       mismatches.push_back(d);
901       if (mismatches.size() < 10) {
902         ABSL_RAW_LOG(ERROR, "%s",
903                      absl::StrCat("Six-digit failure with double.  ", "d=", d,
904                                   "=", d, " sixdigits=", sixdigitsbuf,
905                                   " printf(%g)=", snprintfbuf)
906                          .c_str());
907       }
908     }
909   };
910   // Some quick sanity checks...
911   checker(5e-324);
912   checker(1e-308);
913   checker(1.0);
914   checker(1.000005);
915   checker(1.7976931348623157e308);
916   checker(0.00390625);
917 #ifndef _MSC_VER
918   // on MSVC, snprintf() rounds it to 0.00195313. SixDigitsToBuffer() rounds it
919   // to 0.00195312 (round half to even).
920   checker(0.001953125);
921 #endif
922   checker(0.005859375);
923   // Some cases where the rounding is very very close
924   checker(1.089095e-15);
925   checker(3.274195e-55);
926   checker(6.534355e-146);
927   checker(2.920845e+234);
928 
929   if (mismatches.empty()) {
930     test_count = 0;
931     ExhaustiveFloat(kFloatNumCases, checker);
932 
933     test_count = 0;
934     std::vector<int> digit_testcases{
935         100000, 100001, 100002, 100005, 100010, 100020, 100050, 100100,  // misc
936         195312, 195313,  // 1.953125 is a case where we round down, just barely.
937         200000, 500000, 800000,  // misc mid-range cases
938         585937, 585938,  // 5.859375 is a case where we round up, just barely.
939         900000, 990000, 999000, 999900, 999990, 999996, 999997, 999998, 999999};
940     if (kFloatNumCases >= 1e9) {
941       // If at least 1 billion test cases were requested, user wants an
942       // exhaustive test. So let's test all mantissas, too.
943       constexpr int min_mantissa = 100000, max_mantissa = 999999;
944       digit_testcases.resize(max_mantissa - min_mantissa + 1);
945       std::iota(digit_testcases.begin(), digit_testcases.end(), min_mantissa);
946     }
947 
948     for (int exponent = -324; exponent <= 308; ++exponent) {
949       double powten = absl::strings_internal::Pow10(exponent);
950       if (powten == 0) powten = 5e-324;
951       if (kFloatNumCases >= 1e9) {
952         // The exhaustive test takes a very long time, so log progress.
953         char buf[kSixDigitsToBufferSize];
954         ABSL_RAW_LOG(
955             INFO, "%s",
956             absl::StrCat("Exp ", exponent, " powten=", powten, "(", powten,
957                          ") (",
958                          std::string(buf, SixDigitsToBuffer(powten, buf)), ")")
959                 .c_str());
960       }
961       for (int digits : digit_testcases) {
962         if (exponent == 308 && digits >= 179769) break;  // don't overflow!
963         double digiform = (digits + 0.5) * 0.00001;
964         double testval = digiform * powten;
965         double pretestval = nextafter(testval, 0);
966         double posttestval = nextafter(testval, 1.7976931348623157e308);
967         checker(testval);
968         checker(pretestval);
969         checker(posttestval);
970       }
971     }
972   } else {
973     EXPECT_EQ(mismatches.size(), 0);
974     for (size_t i = 0; i < mismatches.size(); ++i) {
975       if (i > 100) i = mismatches.size() - 1;
976       double d = mismatches[i];
977       char sixdigitsbuf[kSixDigitsToBufferSize] = {0};
978       SixDigitsToBuffer(d, sixdigitsbuf);
979       char snprintfbuf[kSixDigitsToBufferSize] = {0};
980       snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d);
981       double before = nextafter(d, 0.0);
982       double after = nextafter(d, 1.7976931348623157e308);
983       char b1[32], b2[kSixDigitsToBufferSize];
984       ABSL_RAW_LOG(
985           ERROR, "%s",
986           absl::StrCat(
987               "Mismatch #", i, "  d=", d, " (", ToNineDigits(d), ")",
988               " sixdigits='", sixdigitsbuf, "'", " snprintf='", snprintfbuf,
989               "'", " Before.=", PerfectDtoa(before), " ",
990               (SixDigitsToBuffer(before, b2), b2),
991               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", before), b1),
992               " Perfect=", PerfectDtoa(d), " ", (SixDigitsToBuffer(d, b2), b2),
993               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", d), b1),
994               " After.=.", PerfectDtoa(after), " ",
995               (SixDigitsToBuffer(after, b2), b2),
996               " vs snprintf=", (snprintf(b1, sizeof(b1), "%g", after), b1))
997               .c_str());
998     }
999   }
1000 }
1001 
TEST(StrToInt32,Partial)1002 TEST(StrToInt32, Partial) {
1003   struct Int32TestLine {
1004     std::string input;
1005     bool status;
1006     int32_t value;
1007   };
1008   const int32_t int32_min = std::numeric_limits<int32_t>::min();
1009   const int32_t int32_max = std::numeric_limits<int32_t>::max();
1010   Int32TestLine int32_test_line[] = {
1011       {"", false, 0},
1012       {" ", false, 0},
1013       {"-", false, 0},
1014       {"123@@@", false, 123},
1015       {absl::StrCat(int32_min, int32_max), false, int32_min},
1016       {absl::StrCat(int32_max, int32_max), false, int32_max},
1017   };
1018 
1019   for (const Int32TestLine& test_line : int32_test_line) {
1020     int32_t value = -2;
1021     bool status = safe_strto32_base(test_line.input, &value, 10);
1022     EXPECT_EQ(test_line.status, status) << test_line.input;
1023     EXPECT_EQ(test_line.value, value) << test_line.input;
1024     value = -2;
1025     status = safe_strto32_base(test_line.input, &value, 10);
1026     EXPECT_EQ(test_line.status, status) << test_line.input;
1027     EXPECT_EQ(test_line.value, value) << test_line.input;
1028     value = -2;
1029     status = safe_strto32_base(absl::string_view(test_line.input), &value, 10);
1030     EXPECT_EQ(test_line.status, status) << test_line.input;
1031     EXPECT_EQ(test_line.value, value) << test_line.input;
1032   }
1033 }
1034 
TEST(StrToUint32,Partial)1035 TEST(StrToUint32, Partial) {
1036   struct Uint32TestLine {
1037     std::string input;
1038     bool status;
1039     uint32_t value;
1040   };
1041   const uint32_t uint32_max = std::numeric_limits<uint32_t>::max();
1042   Uint32TestLine uint32_test_line[] = {
1043       {"", false, 0},
1044       {" ", false, 0},
1045       {"-", false, 0},
1046       {"123@@@", false, 123},
1047       {absl::StrCat(uint32_max, uint32_max), false, uint32_max},
1048   };
1049 
1050   for (const Uint32TestLine& test_line : uint32_test_line) {
1051     uint32_t value = 2;
1052     bool status = safe_strtou32_base(test_line.input, &value, 10);
1053     EXPECT_EQ(test_line.status, status) << test_line.input;
1054     EXPECT_EQ(test_line.value, value) << test_line.input;
1055     value = 2;
1056     status = safe_strtou32_base(test_line.input, &value, 10);
1057     EXPECT_EQ(test_line.status, status) << test_line.input;
1058     EXPECT_EQ(test_line.value, value) << test_line.input;
1059     value = 2;
1060     status = safe_strtou32_base(absl::string_view(test_line.input), &value, 10);
1061     EXPECT_EQ(test_line.status, status) << test_line.input;
1062     EXPECT_EQ(test_line.value, value) << test_line.input;
1063   }
1064 }
1065 
TEST(StrToInt64,Partial)1066 TEST(StrToInt64, Partial) {
1067   struct Int64TestLine {
1068     std::string input;
1069     bool status;
1070     int64_t value;
1071   };
1072   const int64_t int64_min = std::numeric_limits<int64_t>::min();
1073   const int64_t int64_max = std::numeric_limits<int64_t>::max();
1074   Int64TestLine int64_test_line[] = {
1075       {"", false, 0},
1076       {" ", false, 0},
1077       {"-", false, 0},
1078       {"123@@@", false, 123},
1079       {absl::StrCat(int64_min, int64_max), false, int64_min},
1080       {absl::StrCat(int64_max, int64_max), false, int64_max},
1081   };
1082 
1083   for (const Int64TestLine& test_line : int64_test_line) {
1084     int64_t value = -2;
1085     bool status = safe_strto64_base(test_line.input, &value, 10);
1086     EXPECT_EQ(test_line.status, status) << test_line.input;
1087     EXPECT_EQ(test_line.value, value) << test_line.input;
1088     value = -2;
1089     status = safe_strto64_base(test_line.input, &value, 10);
1090     EXPECT_EQ(test_line.status, status) << test_line.input;
1091     EXPECT_EQ(test_line.value, value) << test_line.input;
1092     value = -2;
1093     status = safe_strto64_base(absl::string_view(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   }
1097 }
1098 
TEST(StrToUint64,Partial)1099 TEST(StrToUint64, Partial) {
1100   struct Uint64TestLine {
1101     std::string input;
1102     bool status;
1103     uint64_t value;
1104   };
1105   const uint64_t uint64_max = std::numeric_limits<uint64_t>::max();
1106   Uint64TestLine uint64_test_line[] = {
1107       {"", false, 0},
1108       {" ", false, 0},
1109       {"-", false, 0},
1110       {"123@@@", false, 123},
1111       {absl::StrCat(uint64_max, uint64_max), false, uint64_max},
1112   };
1113 
1114   for (const Uint64TestLine& test_line : uint64_test_line) {
1115     uint64_t value = 2;
1116     bool status = safe_strtou64_base(test_line.input, &value, 10);
1117     EXPECT_EQ(test_line.status, status) << test_line.input;
1118     EXPECT_EQ(test_line.value, value) << test_line.input;
1119     value = 2;
1120     status = safe_strtou64_base(test_line.input, &value, 10);
1121     EXPECT_EQ(test_line.status, status) << test_line.input;
1122     EXPECT_EQ(test_line.value, value) << test_line.input;
1123     value = 2;
1124     status = safe_strtou64_base(absl::string_view(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   }
1128 }
1129 
TEST(StrToInt32Base,PrefixOnly)1130 TEST(StrToInt32Base, PrefixOnly) {
1131   struct Int32TestLine {
1132     std::string input;
1133     bool status;
1134     int32_t value;
1135   };
1136   Int32TestLine int32_test_line[] = {
1137     { "", false, 0 },
1138     { "-", false, 0 },
1139     { "-0", true, 0 },
1140     { "0", true, 0 },
1141     { "0x", false, 0 },
1142     { "-0x", false, 0 },
1143   };
1144   const int base_array[] = { 0, 2, 8, 10, 16 };
1145 
1146   for (const Int32TestLine& line : int32_test_line) {
1147     for (const int base : base_array) {
1148       int32_t value = 2;
1149       bool status = safe_strto32_base(line.input.c_str(), &value, base);
1150       EXPECT_EQ(line.status, status) << line.input << " " << base;
1151       EXPECT_EQ(line.value, value) << line.input << " " << base;
1152       value = 2;
1153       status = safe_strto32_base(line.input, &value, base);
1154       EXPECT_EQ(line.status, status) << line.input << " " << base;
1155       EXPECT_EQ(line.value, value) << line.input << " " << base;
1156       value = 2;
1157       status = safe_strto32_base(absl::string_view(line.input), &value, base);
1158       EXPECT_EQ(line.status, status) << line.input << " " << base;
1159       EXPECT_EQ(line.value, value) << line.input << " " << base;
1160     }
1161   }
1162 }
1163 
TEST(StrToUint32Base,PrefixOnly)1164 TEST(StrToUint32Base, PrefixOnly) {
1165   struct Uint32TestLine {
1166     std::string input;
1167     bool status;
1168     uint32_t value;
1169   };
1170   Uint32TestLine uint32_test_line[] = {
1171     { "", false, 0 },
1172     { "0", true, 0 },
1173     { "0x", false, 0 },
1174   };
1175   const int base_array[] = { 0, 2, 8, 10, 16 };
1176 
1177   for (const Uint32TestLine& line : uint32_test_line) {
1178     for (const int base : base_array) {
1179       uint32_t value = 2;
1180       bool status = safe_strtou32_base(line.input.c_str(), &value, base);
1181       EXPECT_EQ(line.status, status) << line.input << " " << base;
1182       EXPECT_EQ(line.value, value) << line.input << " " << base;
1183       value = 2;
1184       status = safe_strtou32_base(line.input, &value, base);
1185       EXPECT_EQ(line.status, status) << line.input << " " << base;
1186       EXPECT_EQ(line.value, value) << line.input << " " << base;
1187       value = 2;
1188       status = safe_strtou32_base(absl::string_view(line.input), &value, base);
1189       EXPECT_EQ(line.status, status) << line.input << " " << base;
1190       EXPECT_EQ(line.value, value) << line.input << " " << base;
1191     }
1192   }
1193 }
1194 
TEST(StrToInt64Base,PrefixOnly)1195 TEST(StrToInt64Base, PrefixOnly) {
1196   struct Int64TestLine {
1197     std::string input;
1198     bool status;
1199     int64_t value;
1200   };
1201   Int64TestLine int64_test_line[] = {
1202     { "", false, 0 },
1203     { "-", false, 0 },
1204     { "-0", true, 0 },
1205     { "0", true, 0 },
1206     { "0x", false, 0 },
1207     { "-0x", false, 0 },
1208   };
1209   const int base_array[] = { 0, 2, 8, 10, 16 };
1210 
1211   for (const Int64TestLine& line : int64_test_line) {
1212     for (const int base : base_array) {
1213       int64_t value = 2;
1214       bool status = safe_strto64_base(line.input.c_str(), &value, base);
1215       EXPECT_EQ(line.status, status) << line.input << " " << base;
1216       EXPECT_EQ(line.value, value) << line.input << " " << base;
1217       value = 2;
1218       status = safe_strto64_base(line.input, &value, base);
1219       EXPECT_EQ(line.status, status) << line.input << " " << base;
1220       EXPECT_EQ(line.value, value) << line.input << " " << base;
1221       value = 2;
1222       status = safe_strto64_base(absl::string_view(line.input), &value, base);
1223       EXPECT_EQ(line.status, status) << line.input << " " << base;
1224       EXPECT_EQ(line.value, value) << line.input << " " << base;
1225     }
1226   }
1227 }
1228 
TEST(StrToUint64Base,PrefixOnly)1229 TEST(StrToUint64Base, PrefixOnly) {
1230   struct Uint64TestLine {
1231     std::string input;
1232     bool status;
1233     uint64_t value;
1234   };
1235   Uint64TestLine uint64_test_line[] = {
1236     { "", false, 0 },
1237     { "0", true, 0 },
1238     { "0x", false, 0 },
1239   };
1240   const int base_array[] = { 0, 2, 8, 10, 16 };
1241 
1242   for (const Uint64TestLine& line : uint64_test_line) {
1243     for (const int base : base_array) {
1244       uint64_t value = 2;
1245       bool status = safe_strtou64_base(line.input.c_str(), &value, base);
1246       EXPECT_EQ(line.status, status) << line.input << " " << base;
1247       EXPECT_EQ(line.value, value) << line.input << " " << base;
1248       value = 2;
1249       status = safe_strtou64_base(line.input, &value, base);
1250       EXPECT_EQ(line.status, status) << line.input << " " << base;
1251       EXPECT_EQ(line.value, value) << line.input << " " << base;
1252       value = 2;
1253       status = safe_strtou64_base(absl::string_view(line.input), &value, base);
1254       EXPECT_EQ(line.status, status) << line.input << " " << base;
1255       EXPECT_EQ(line.value, value) << line.input << " " << base;
1256     }
1257   }
1258 }
1259 
TestFastHexToBufferZeroPad16(uint64_t v)1260 void TestFastHexToBufferZeroPad16(uint64_t v) {
1261   char buf[16];
1262   auto digits = absl::numbers_internal::FastHexToBufferZeroPad16(v, buf);
1263   absl::string_view res(buf, 16);
1264   char buf2[17];
1265   snprintf(buf2, sizeof(buf2), "%016" PRIx64, v);
1266   EXPECT_EQ(res, buf2) << v;
1267   size_t expected_digits = snprintf(buf2, sizeof(buf2), "%" PRIx64, v);
1268   EXPECT_EQ(digits, expected_digits) << v;
1269 }
1270 
TEST(FastHexToBufferZeroPad16,Smoke)1271 TEST(FastHexToBufferZeroPad16, Smoke) {
1272   TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::min());
1273   TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::max());
1274   TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::min());
1275   TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::max());
1276   absl::BitGen rng;
1277   for (int i = 0; i < 100000; ++i) {
1278     TestFastHexToBufferZeroPad16(
1279         absl::LogUniform(rng, std::numeric_limits<uint64_t>::min(),
1280                          std::numeric_limits<uint64_t>::max()));
1281   }
1282 }
1283 
1284 }  // namespace
1285