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