Fix output of 128 bit integer to string conversion.
[folly.git] / folly / test / ConvTest.cpp
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "folly/Benchmark.h"
18 #include "folly/Conv.h"
19 #include "folly/Foreach.h"
20 #include <boost/lexical_cast.hpp>
21 #include <gtest/gtest.h>
22 #include <limits>
23 #include <stdexcept>
24
25 using namespace std;
26 using namespace folly;
27
28 static int8_t s8;
29 static uint8_t u8;
30 static int16_t s16;
31 static uint16_t u16;
32 static int32_t s32;
33 static uint32_t u32;
34 static int64_t s64;
35 static uint64_t u64;
36
37 TEST(Conv, Integral2Integral) {
38   // Same size, different signs
39   s64 = numeric_limits<uint8_t>::max();
40   EXPECT_EQ(to<uint8_t>(s64), s64);
41
42   s64 = numeric_limits<int8_t>::max();
43   EXPECT_EQ(to<int8_t>(s64), s64);
44 }
45
46 TEST(Conv, Floating2Floating) {
47   float f1 = 1e3;
48   double d1 = to<double>(f1);
49   EXPECT_EQ(f1, d1);
50
51   double d2 = 23.0;
52   auto f2 = to<float>(d2);
53   EXPECT_EQ(double(f2), d2);
54
55   double invalidFloat = std::numeric_limits<double>::max();
56   EXPECT_ANY_THROW(to<float>(invalidFloat));
57   invalidFloat = -std::numeric_limits<double>::max();
58   EXPECT_ANY_THROW(to<float>(invalidFloat));
59
60   try {
61     auto shouldWork = to<float>(std::numeric_limits<double>::min());
62     // The value of `shouldWork' is an implementation defined choice
63     // between the following two alternatives.
64     EXPECT_TRUE(shouldWork == std::numeric_limits<float>::min() ||
65                 shouldWork == 0.f);
66   } catch (...) {
67     EXPECT_TRUE(false);
68   }
69 }
70
71 template <class String>
72 void testIntegral2String() {
73 }
74
75 template <class String, class Int, class... Ints>
76 void testIntegral2String() {
77   typedef typename make_unsigned<Int>::type Uint;
78   typedef typename make_signed<Int>::type Sint;
79
80   Uint value = 123;
81   EXPECT_EQ(to<String>(value), "123");
82   Sint svalue = 123;
83   EXPECT_EQ(to<String>(svalue), "123");
84   svalue = -123;
85   EXPECT_EQ(to<String>(svalue), "-123");
86
87   value = numeric_limits<Uint>::min();
88   EXPECT_EQ(to<Uint>(to<String>(value)), value);
89   value = numeric_limits<Uint>::max();
90   EXPECT_EQ(to<Uint>(to<String>(value)), value);
91
92   svalue = numeric_limits<Sint>::min();
93   EXPECT_EQ(to<Sint>(to<String>(svalue)), svalue);
94   value = numeric_limits<Sint>::max();
95   EXPECT_EQ(to<Sint>(to<String>(svalue)), svalue);
96
97   testIntegral2String<String, Ints...>();
98 }
99
100 #if FOLLY_HAVE_INT128_T
101 template <class String>
102 void test128Bit2String() {
103   typedef unsigned __int128 Uint;
104   typedef __int128 Sint;
105
106   EXPECT_EQ(detail::digitsEnough<unsigned __int128>(), 39);
107
108   Uint value = 123;
109   EXPECT_EQ(to<String>(value), "123");
110   Sint svalue = 123;
111   EXPECT_EQ(to<String>(svalue), "123");
112   svalue = -123;
113   EXPECT_EQ(to<String>(svalue), "-123");
114
115   value = __int128(1) << 64;
116   EXPECT_EQ(to<String>(value), "18446744073709551616");
117
118   svalue =  -(__int128(1) << 64);
119   EXPECT_EQ(to<String>(svalue), "-18446744073709551616");
120
121   value = 0;
122   EXPECT_EQ(to<String>(value), "0");
123
124   svalue = 0;
125   EXPECT_EQ(to<String>(svalue), "0");
126
127   // TODO: the following do not compile to<__int128> ...
128
129 #if 0
130   value = numeric_limits<Uint>::min();
131   EXPECT_EQ(to<Uint>(to<String>(value)), value);
132   value = numeric_limits<Uint>::max();
133   EXPECT_EQ(to<Uint>(to<String>(value)), value);
134
135   svalue = numeric_limits<Sint>::min();
136   EXPECT_EQ(to<Sint>(to<String>(svalue)), svalue);
137   value = numeric_limits<Sint>::max();
138   EXPECT_EQ(to<Sint>(to<String>(svalue)), svalue);
139 #endif
140 }
141
142 #endif
143
144 TEST(Conv, Integral2String) {
145   testIntegral2String<std::string, char, short, int, long>();
146   testIntegral2String<fbstring, char, short, int, long>();
147
148 #if FOLLY_HAVE_INT128_T
149   test128Bit2String<std::string>();
150   test128Bit2String<fbstring>();
151 #endif
152 }
153
154 template <class String>
155 void testString2Integral() {
156 }
157
158 template <class String, class Int, class... Ints>
159 void testString2Integral() {
160   typedef typename make_unsigned<Int>::type Uint;
161   typedef typename make_signed<Int>::type Sint;
162
163   // Unsigned numbers small enough to fit in a signed type
164   static const String strings[] = {
165     "0",
166     "00",
167     "2 ",
168     " 84",
169     " \n 123    \t\n",
170     " 127",
171     "0000000000000000000000000042"
172   };
173   static const Uint values[] = {
174     0,
175     0,
176     2,
177     84,
178     123,
179     127,
180     42
181   };
182   FOR_EACH_RANGE (i, 0, sizeof(strings) / sizeof(*strings)) {
183     EXPECT_EQ(to<Uint>(strings[i]), values[i]);
184     EXPECT_EQ(to<Sint>(strings[i]), values[i]);
185   }
186
187   // Unsigned numbers that won't fit in the signed variation
188   static const String uStrings[] = {
189     " 128",
190     "213",
191     "255"
192   };
193   static const Uint uValues[] = {
194     128,
195     213,
196     255
197   };
198   FOR_EACH_RANGE (i, 0, sizeof(uStrings)/sizeof(*uStrings)) {
199     EXPECT_EQ(to<Uint>(uStrings[i]), uValues[i]);
200     if (sizeof(Int) == 1) {
201       EXPECT_THROW(to<Sint>(uStrings[i]), std::range_error);
202     }
203   }
204
205   if (sizeof(Int) >= 4) {
206     static const String strings2[] = {
207       "256",
208       "6324 ",
209       "63245675 ",
210       "2147483647"
211     };
212     static const Uint values2[] = {
213       (Uint)256,
214       (Uint)6324,
215       (Uint)63245675,
216       (Uint)2147483647
217     };
218     FOR_EACH_RANGE (i, 0, sizeof(strings2)/sizeof(*strings2)) {
219       EXPECT_EQ(to<Uint>(strings2[i]), values2[i]);
220       EXPECT_EQ(to<Sint>(strings2[i]), values2[i]);
221     }
222
223     static const String uStrings2[] = {
224       "2147483648",
225       "3147483648",
226       "4147483648",
227       "4000000000",
228     };
229     static const Uint uValues2[] = {
230       (Uint)2147483648U,
231       (Uint)3147483648U,
232       (Uint)4147483648U,
233       (Uint)4000000000U,
234     };
235     FOR_EACH_RANGE (i, 0, sizeof(uStrings2)/sizeof(uStrings2)) {
236       EXPECT_EQ(to<Uint>(uStrings2[i]), uValues2[i]);
237       if (sizeof(Int) == 4) {
238         EXPECT_THROW(to<Sint>(uStrings2[i]), std::range_error);
239       }
240     }
241   }
242
243   if (sizeof(Int) >= 8) {
244     static_assert(sizeof(Int) <= 8, "Now that would be interesting");
245     static const String strings3[] = {
246       "2147483648",
247       "5000000001",
248       "25687346509278435",
249       "100000000000000000",
250       "9223372036854775807",
251     };
252     static const Uint values3[] = {
253       (Uint)2147483648ULL,
254       (Uint)5000000001ULL,
255       (Uint)25687346509278435ULL,
256       (Uint)100000000000000000ULL,
257       (Uint)9223372036854775807ULL,
258     };
259     FOR_EACH_RANGE (i, 0, sizeof(strings3)/sizeof(*strings3)) {
260       EXPECT_EQ(to<Uint>(strings3[i]), values3[i]);
261       EXPECT_EQ(to<Sint>(strings3[i]), values3[i]);
262     }
263
264     static const String uStrings3[] = {
265       "9223372036854775808",
266       "9987435987394857987",
267       "17873648761234698740",
268       "18446744073709551615",
269     };
270     static const Uint uValues3[] = {
271       (Uint)9223372036854775808ULL,
272       (Uint)9987435987394857987ULL,
273       (Uint)17873648761234698740ULL,
274       (Uint)18446744073709551615ULL,
275     };
276     FOR_EACH_RANGE (i, 0, sizeof(uStrings3)/sizeof(*uStrings3)) {
277       EXPECT_EQ(to<Uint>(uStrings3[i]), uValues3[i]);
278       if (sizeof(Int) == 8) {
279         EXPECT_THROW(to<Sint>(uStrings3[i]), std::range_error);
280       }
281     }
282   }
283
284   // Minimum possible negative values, and negative sign overflow
285   static const String strings4[] = {
286     "-128",
287     "-32768",
288     "-2147483648",
289     "-9223372036854775808",
290   };
291   static const String strings5[] = {
292     "-129",
293     "-32769",
294     "-2147483649",
295     "-9223372036854775809",
296   };
297   static const Sint values4[] = {
298     (Sint)-128LL,
299     (Sint)-32768LL,
300     (Sint)-2147483648LL,
301     (Sint)(-9223372036854775807LL - 1),
302   };
303   FOR_EACH_RANGE (i, 0, sizeof(strings4)/sizeof(*strings4)) {
304     if (sizeof(Int) > std::pow(2, i)) {
305       EXPECT_EQ(values4[i], to<Sint>(strings4[i]));
306       EXPECT_EQ(values4[i] - 1, to<Sint>(strings5[i]));
307     } else if (sizeof(Int) == std::pow(2, i)) {
308       EXPECT_EQ(values4[i], to<Sint>(strings4[i]));
309       EXPECT_THROW(to<Sint>(strings5[i]), std::range_error);
310     } else {
311       EXPECT_THROW(to<Sint>(strings4[i]), std::range_error);
312       EXPECT_THROW(to<Sint>(strings5[i]), std::range_error);
313     }
314   }
315
316   // Bogus string values
317   static const String bogusStrings[] = {
318     "",
319     "0x1234",
320     "123L",
321     "123a",
322     "x 123 ",
323     "234 y",
324     "- 42",  // whitespace is not allowed between the sign and the value
325     " +   13 ",
326     "12345678901234567890123456789",
327   };
328   for (const auto& str : bogusStrings) {
329     EXPECT_THROW(to<Sint>(str), std::range_error);
330     EXPECT_THROW(to<Uint>(str), std::range_error);
331   }
332
333   // A leading '+' character is only allowed when converting to signed types.
334   String posSign("+42");
335   EXPECT_EQ(42, to<Sint>(posSign));
336   EXPECT_THROW(to<Uint>(posSign), std::range_error);
337
338   testString2Integral<String, Ints...>();
339 }
340
341 TEST(Conv, String2Integral) {
342   testString2Integral<const char*, signed char, short, int, long, long long>();
343   testString2Integral<std::string, signed char, short, int, long, long long>();
344   testString2Integral<fbstring, signed char, short, int, long, long long>();
345
346   // Testing the behavior of the StringPiece* API
347   // StringPiece* normally parses as much valid data as it can,
348   // and advances the StringPiece to the end of the valid data.
349   char buf1[] = "100foo";
350   StringPiece sp1(buf1);
351   EXPECT_EQ(100, to<uint8_t>(&sp1));
352   EXPECT_EQ(buf1 + 3, sp1.begin());
353   // However, if the next character would cause an overflow it throws a
354   // range_error rather than consuming only as much as it can without
355   // overflowing.
356   char buf2[] = "1002";
357   StringPiece sp2(buf2);
358   EXPECT_THROW(to<uint8_t>(&sp2), std::range_error);
359   EXPECT_EQ(buf2, sp2.begin());
360 }
361
362 TEST(Conv, StringPiece2Integral) {
363   string s = "  +123  hello world  ";
364   StringPiece sp = s;
365   EXPECT_EQ(to<int>(&sp), 123);
366   EXPECT_EQ(sp, "  hello world  ");
367 }
368
369 TEST(Conv, StringPieceAppend) {
370   string s = "foobar";
371   {
372     StringPiece sp(s, 0, 3);
373     string result = to<string>(s, sp);
374     EXPECT_EQ(result, "foobarfoo");
375   }
376   {
377     StringPiece sp1(s, 0, 3);
378     StringPiece sp2(s, 3, 3);
379     string result = to<string>(sp1, sp2);
380     EXPECT_EQ(result, s);
381   }
382 }
383
384 TEST(Conv, BadStringToIntegral) {
385   // Note that leading spaces (e.g.  " 1") are valid.
386   vector<string> v = { "a", "", " ", "\n", " a0", "abcdef", "1Z", "!#" };
387   for (auto& s: v) {
388     EXPECT_THROW(to<int>(s), std::range_error) << "s=" << s;
389   }
390 }
391
392 template <class String>
393 void testVariadicTo() {
394   String s;
395   toAppend(&s);
396   toAppend("Lorem ipsum ", 1234, String(" dolor amet "), 567.89, '!', &s);
397   EXPECT_EQ(s, "Lorem ipsum 1234 dolor amet 567.89!");
398
399   s = to<String>();
400   EXPECT_TRUE(s.empty());
401
402   s = to<String>("Lorem ipsum ", nullptr, 1234, " dolor amet ", 567.89, '.');
403   EXPECT_EQ(s, "Lorem ipsum 1234 dolor amet 567.89.");
404 }
405
406 TEST(Conv, NullString) {
407   string s1 = to<string>((char *) NULL);
408   EXPECT_TRUE(s1.empty());
409   fbstring s2 = to<fbstring>((char *) NULL);
410   EXPECT_TRUE(s2.empty());
411 }
412
413 TEST(Conv, VariadicTo) {
414   testVariadicTo<string>();
415   testVariadicTo<fbstring>();
416 }
417
418 template <class String>
419 void testDoubleToString() {
420   EXPECT_EQ(to<string>(0.0), "0");
421   EXPECT_EQ(to<string>(0.5), "0.5");
422   EXPECT_EQ(to<string>(10.25), "10.25");
423   EXPECT_EQ(to<string>(1.123e10), "11230000000");
424 }
425
426 TEST(Conv, DoubleToString) {
427   testDoubleToString<string>();
428   testDoubleToString<fbstring>();
429 }
430
431 TEST(Conv, FBStringToString) {
432   fbstring foo("foo");
433   string ret = to<string>(foo);
434   EXPECT_EQ(ret, "foo");
435   string ret2 = to<string>(foo, 2);
436   EXPECT_EQ(ret2, "foo2");
437 }
438
439 TEST(Conv, StringPieceToDouble) {
440   string s = "2134123.125 zorro";
441   StringPiece pc(s);
442   EXPECT_EQ(to<double>(&pc), 2134123.125);
443   EXPECT_EQ(pc, " zorro");
444
445   EXPECT_THROW(to<double>(StringPiece(s)), std::range_error);
446   EXPECT_EQ(to<double>(StringPiece(s.data(), pc.data())), 2134123.125);
447
448 // Test NaN conversion
449   try {
450     to<double>("not a number");
451     EXPECT_TRUE(false);
452   } catch (const std::range_error &) {
453   }
454
455   EXPECT_TRUE(std::isnan(to<double>("NaN")));
456   EXPECT_EQ(to<double>("inf"), numeric_limits<double>::infinity());
457   EXPECT_EQ(to<double>("infinity"), numeric_limits<double>::infinity());
458   EXPECT_THROW(to<double>("infinitX"), std::range_error);
459   EXPECT_EQ(to<double>("-inf"), -numeric_limits<double>::infinity());
460   EXPECT_EQ(to<double>("-infinity"), -numeric_limits<double>::infinity());
461   EXPECT_THROW(to<double>("-infinitX"), std::range_error);
462 }
463
464 TEST(Conv, EmptyStringToInt) {
465   string s = "";
466   StringPiece pc(s);
467
468   try {
469     to<int>(pc);
470     EXPECT_TRUE(false);
471   } catch (const std::range_error &) {
472   }
473 }
474
475 TEST(Conv, CorruptedStringToInt) {
476   string s = "-1";
477   StringPiece pc(s.data(), s.data() + 1); // Only  "-"
478
479   try {
480     to<int64_t>(&pc);
481     EXPECT_TRUE(false);
482   } catch (const std::range_error &) {
483   }
484 }
485
486 TEST(Conv, EmptyStringToDouble) {
487   string s = "";
488   StringPiece pc(s);
489
490   try {
491     to<double>(pc);
492     EXPECT_TRUE(false);
493   } catch (const std::range_error &) {
494   }
495 }
496
497 TEST(Conv, IntToDouble) {
498   auto d = to<double>(42);
499   EXPECT_EQ(d, 42);
500   /* This seems not work in ubuntu11.10, gcc 4.6.1
501   try {
502     auto f = to<float>(957837589847);
503     EXPECT_TRUE(false);
504   } catch (std::range_error& e) {
505     //LOG(INFO) << e.what();
506   }
507   */
508 }
509
510 TEST(Conv, DoubleToInt) {
511   auto i = to<int>(42.0);
512   EXPECT_EQ(i, 42);
513   try {
514     auto i = to<int>(42.1);
515     EXPECT_TRUE(false);
516   } catch (std::range_error& e) {
517     //LOG(INFO) << e.what();
518   }
519 }
520
521 TEST(Conv, EnumToInt) {
522   enum A { x = 42, y = 420, z = 65 };
523   auto i = to<int>(x);
524   EXPECT_EQ(i, 42);
525   auto j = to<char>(x);
526   EXPECT_EQ(j, 42);
527   try {
528     auto i = to<char>(y);
529     LOG(ERROR) << static_cast<unsigned int>(i);
530     EXPECT_TRUE(false);
531   } catch (std::range_error& e) {
532     //LOG(INFO) << e.what();
533   }
534 }
535
536 TEST(Conv, EnumToString) {
537   // task 813959
538   enum A { x = 4, y = 420, z = 65 };
539   EXPECT_EQ("foo.4", to<string>("foo.", x));
540   EXPECT_EQ("foo.420", to<string>("foo.", y));
541   EXPECT_EQ("foo.65", to<string>("foo.", z));
542 }
543
544 TEST(Conv, IntToEnum) {
545   enum A { x = 42, y = 420 };
546   auto i = to<A>(42);
547   EXPECT_EQ(i, x);
548   auto j = to<A>(100);
549   EXPECT_EQ(j, 100);
550   try {
551     auto i = to<A>(5000000000L);
552     EXPECT_TRUE(false);
553   } catch (std::range_error& e) {
554     //LOG(INFO) << e.what();
555   }
556 }
557
558 TEST(Conv, UnsignedEnum) {
559   enum E : uint32_t { x = 3000000000U };
560   auto u = to<uint32_t>(x);
561   EXPECT_EQ(u, 3000000000U);
562   auto s = to<string>(x);
563   EXPECT_EQ("3000000000", s);
564   auto e = to<E>(3000000000U);
565   EXPECT_EQ(e, x);
566   try {
567     auto i = to<int32_t>(x);
568     LOG(ERROR) << to<uint32_t>(x);
569     EXPECT_TRUE(false);
570   } catch (std::range_error& e) {
571   }
572 }
573
574 #if defined(__GNUC__) && __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
575 // to<enum class> and to(enum class) only supported in gcc 4.7 onwards
576
577 TEST(Conv, UnsignedEnumClass) {
578   enum class E : uint32_t { x = 3000000000U };
579   auto u = to<uint32_t>(E::x);
580   EXPECT_GT(u, 0);
581   EXPECT_EQ(u, 3000000000U);
582   auto s = to<string>(E::x);
583   EXPECT_EQ("3000000000", s);
584   auto e = to<E>(3000000000U);
585   EXPECT_EQ(e, E::x);
586   try {
587     auto i = to<int32_t>(E::x);
588     LOG(ERROR) << to<uint32_t>(E::x);
589     EXPECT_TRUE(false);
590   } catch (std::range_error& e) {
591   }
592 }
593
594 // Multi-argument to<string> uses toAppend, a different code path than
595 // to<string>(enum).
596 TEST(Conv, EnumClassToString) {
597   enum class A { x = 4, y = 420, z = 65 };
598   EXPECT_EQ("foo.4", to<string>("foo.", A::x));
599   EXPECT_EQ("foo.420", to<string>("foo.", A::y));
600   EXPECT_EQ("foo.65", to<string>("foo.", A::z));
601 }
602
603 #endif // gcc 4.7 onwards
604
605 template<typename Src>
606 void testStr2Bool() {
607   EXPECT_FALSE(to<bool>(Src("0")));
608   EXPECT_FALSE(to<bool>(Src("  000  ")));
609
610   EXPECT_FALSE(to<bool>(Src("n")));
611   EXPECT_FALSE(to<bool>(Src("no")));
612   EXPECT_FALSE(to<bool>(Src("false")));
613   EXPECT_FALSE(to<bool>(Src("False")));
614   EXPECT_FALSE(to<bool>(Src("  fAlSe"  )));
615   EXPECT_FALSE(to<bool>(Src("F")));
616   EXPECT_FALSE(to<bool>(Src("off")));
617
618   EXPECT_TRUE(to<bool>(Src("1")));
619   EXPECT_TRUE(to<bool>(Src("  001 ")));
620   EXPECT_TRUE(to<bool>(Src("y")));
621   EXPECT_TRUE(to<bool>(Src("yes")));
622   EXPECT_TRUE(to<bool>(Src("\nyEs\t")));
623   EXPECT_TRUE(to<bool>(Src("true")));
624   EXPECT_TRUE(to<bool>(Src("True")));
625   EXPECT_TRUE(to<bool>(Src("T")));
626   EXPECT_TRUE(to<bool>(Src("on")));
627
628   EXPECT_THROW(to<bool>(Src("")), std::range_error);
629   EXPECT_THROW(to<bool>(Src("2")), std::range_error);
630   EXPECT_THROW(to<bool>(Src("11")), std::range_error);
631   EXPECT_THROW(to<bool>(Src("19")), std::range_error);
632   EXPECT_THROW(to<bool>(Src("o")), std::range_error);
633   EXPECT_THROW(to<bool>(Src("fal")), std::range_error);
634   EXPECT_THROW(to<bool>(Src("tru")), std::range_error);
635   EXPECT_THROW(to<bool>(Src("ye")), std::range_error);
636   EXPECT_THROW(to<bool>(Src("yes foo")), std::range_error);
637   EXPECT_THROW(to<bool>(Src("bar no")), std::range_error);
638   EXPECT_THROW(to<bool>(Src("one")), std::range_error);
639   EXPECT_THROW(to<bool>(Src("true_")), std::range_error);
640   EXPECT_THROW(to<bool>(Src("bogus_token_that_is_too_long")),
641                std::range_error);
642 }
643
644 TEST(Conv, StringToBool) {
645   // testStr2Bool<const char *>();
646   testStr2Bool<std::string>();
647
648   // Test with strings that are not NUL terminated.
649   const char buf[] = "01234";
650   EXPECT_FALSE(to<bool>(StringPiece(buf, buf + 1)));  // "0"
651   EXPECT_TRUE(to<bool>(StringPiece(buf + 1, buf + 2)));  // "1"
652   const char buf2[] = "one two three";
653   EXPECT_TRUE(to<bool>(StringPiece(buf2, buf2 + 2)));  // "on"
654   const char buf3[] = "false";
655   EXPECT_THROW(to<bool>(StringPiece(buf3, buf3 + 3)),  // "fal"
656                std::range_error);
657
658   // Test the StringPiece* API
659   const char buf4[] = "001foo";
660   StringPiece sp4(buf4);
661   EXPECT_TRUE(to<bool>(&sp4));
662   EXPECT_EQ(buf4 + 3, sp4.begin());
663   const char buf5[] = "0012";
664   StringPiece sp5(buf5);
665   EXPECT_THROW(to<bool>(&sp5), std::range_error);
666   EXPECT_EQ(buf5, sp5.begin());
667 }
668
669 TEST(Conv, NewUint64ToString) {
670   char buf[21];
671
672 #define THE_GREAT_EXPECTATIONS(n, len)                  \
673   do {                                                  \
674     EXPECT_EQ((len), uint64ToBufferUnsafe((n), buf));   \
675     buf[(len)] = 0;                                     \
676     auto s = string(#n);                                \
677     s = s.substr(0, s.size() - 2);                      \
678     EXPECT_EQ(s, buf);                                  \
679   } while (0)
680
681   THE_GREAT_EXPECTATIONS(0UL, 1);
682   THE_GREAT_EXPECTATIONS(1UL, 1);
683   THE_GREAT_EXPECTATIONS(12UL, 2);
684   THE_GREAT_EXPECTATIONS(123UL, 3);
685   THE_GREAT_EXPECTATIONS(1234UL, 4);
686   THE_GREAT_EXPECTATIONS(12345UL, 5);
687   THE_GREAT_EXPECTATIONS(123456UL, 6);
688   THE_GREAT_EXPECTATIONS(1234567UL, 7);
689   THE_GREAT_EXPECTATIONS(12345678UL, 8);
690   THE_GREAT_EXPECTATIONS(123456789UL, 9);
691   THE_GREAT_EXPECTATIONS(1234567890UL, 10);
692   THE_GREAT_EXPECTATIONS(12345678901UL, 11);
693   THE_GREAT_EXPECTATIONS(123456789012UL, 12);
694   THE_GREAT_EXPECTATIONS(1234567890123UL, 13);
695   THE_GREAT_EXPECTATIONS(12345678901234UL, 14);
696   THE_GREAT_EXPECTATIONS(123456789012345UL, 15);
697   THE_GREAT_EXPECTATIONS(1234567890123456UL, 16);
698   THE_GREAT_EXPECTATIONS(12345678901234567UL, 17);
699   THE_GREAT_EXPECTATIONS(123456789012345678UL, 18);
700   THE_GREAT_EXPECTATIONS(1234567890123456789UL, 19);
701   THE_GREAT_EXPECTATIONS(18446744073709551614UL, 20);
702   THE_GREAT_EXPECTATIONS(18446744073709551615UL, 20);
703
704 #undef THE_GREAT_EXPECTATIONS
705 }
706
707 ////////////////////////////////////////////////////////////////////////////////
708 // Benchmarks for ASCII to int conversion
709 ////////////////////////////////////////////////////////////////////////////////
710 // @author: Rajat Goel (rajat)
711
712 static int64_t handwrittenAtoi(const char* start, const char* end) {
713
714   bool positive = true;
715   int64_t retVal = 0;
716
717   if (start == end) {
718     throw std::runtime_error("empty string");
719   }
720
721   while (start < end && isspace(*start)) {
722     ++start;
723   }
724
725   switch (*start) {
726     case '-':
727       positive = false;
728     case '+':
729       ++start;
730     default:;
731   }
732
733   while (start < end && *start >= '0' && *start <= '9') {
734     auto const newRetVal = retVal * 10 + (*start++ - '0');
735     if (newRetVal < retVal) {
736       throw std::runtime_error("overflow");
737     }
738     retVal = newRetVal;
739   }
740
741   if (start != end) {
742     throw std::runtime_error("extra chars at the end");
743   }
744
745   return positive ? retVal : -retVal;
746 }
747
748 static StringPiece pc1 = "1234567890123456789";
749
750 void handwrittenAtoiMeasure(uint n, uint digits) {
751   auto p = pc1.subpiece(pc1.size() - digits, digits);
752   FOR_EACH_RANGE (i, 0, n) {
753     doNotOptimizeAway(handwrittenAtoi(p.begin(), p.end()));
754   }
755 }
756
757 void follyAtoiMeasure(uint n, uint digits) {
758   auto p = pc1.subpiece(pc1.size() - digits, digits);
759   FOR_EACH_RANGE (i, 0, n) {
760     doNotOptimizeAway(folly::to<int64_t>(p.begin(), p.end()));
761   }
762 }
763
764 void clibAtoiMeasure(uint n, uint digits) {
765   auto p = pc1.subpiece(pc1.size() - digits, digits);
766   assert(*p.end() == 0);
767   static_assert(sizeof(long) == 8, "64-bit long assumed");
768   FOR_EACH_RANGE (i, 0, n) {
769     doNotOptimizeAway(atol(p.begin()));
770   }
771 }
772
773 void clibStrtoulMeasure(uint n, uint digits) {
774   auto p = pc1.subpiece(pc1.size() - digits, digits);
775   assert(*p.end() == 0);
776   char * endptr;
777   FOR_EACH_RANGE (i, 0, n) {
778     doNotOptimizeAway(strtoul(p.begin(), &endptr, 10));
779   }
780 }
781
782 void lexicalCastMeasure(uint n, uint digits) {
783   auto p = pc1.subpiece(pc1.size() - digits, digits);
784   assert(*p.end() == 0);
785   FOR_EACH_RANGE (i, 0, n) {
786     doNotOptimizeAway(boost::lexical_cast<uint64_t>(p.begin()));
787   }
788 }
789
790 // Benchmarks for unsigned to string conversion, raw
791
792 unsigned u64ToAsciiTable(uint64_t value, char* dst) {
793   static const char digits[201] =
794     "00010203040506070809"
795     "10111213141516171819"
796     "20212223242526272829"
797     "30313233343536373839"
798     "40414243444546474849"
799     "50515253545556575859"
800     "60616263646566676869"
801     "70717273747576777879"
802     "80818283848586878889"
803     "90919293949596979899";
804
805   uint32_t const length = digits10(value);
806   uint32_t next = length - 1;
807   while (value >= 100) {
808     auto const i = (value % 100) * 2;
809     value /= 100;
810     dst[next] = digits[i + 1];
811     dst[next - 1] = digits[i];
812     next -= 2;
813   }
814   // Handle last 1-2 digits
815   if (value < 10) {
816     dst[next] = '0' + uint32_t(value);
817   } else {
818     auto i = uint32_t(value) * 2;
819     dst[next] = digits[i + 1];
820     dst[next - 1] = digits[i];
821   }
822   return length;
823 }
824
825 void u64ToAsciiTableBM(uint n, uint64_t value) {
826   // This is too fast, need to do 10 times per iteration
827   char buf[20];
828   FOR_EACH_RANGE (i, 0, n) {
829     doNotOptimizeAway(u64ToAsciiTable(value + n, buf));
830   }
831 }
832
833 unsigned u64ToAsciiClassic(uint64_t value, char* dst) {
834   // Write backwards.
835   char* next = (char*)dst;
836   char* start = next;
837   do {
838     *next++ = '0' + (value % 10);
839     value /= 10;
840   } while (value != 0);
841   unsigned length = next - start;
842
843   // Reverse in-place.
844   next--;
845   while (next > start) {
846     char swap = *next;
847     *next = *start;
848     *start = swap;
849     next--;
850     start++;
851   }
852   return length;
853 }
854
855 void u64ToAsciiClassicBM(uint n, uint64_t value) {
856   // This is too fast, need to do 10 times per iteration
857   char buf[20];
858   FOR_EACH_RANGE (i, 0, n) {
859     doNotOptimizeAway(u64ToAsciiClassic(value + n, buf));
860   }
861 }
862
863 void u64ToAsciiFollyBM(uint n, uint64_t value) {
864   // This is too fast, need to do 10 times per iteration
865   char buf[20];
866   FOR_EACH_RANGE (i, 0, n) {
867     doNotOptimizeAway(uint64ToBufferUnsafe(value + n, buf));
868   }
869 }
870
871 // Benchmark uitoa with string append
872
873 void u2aAppendClassicBM(uint n, uint64_t value) {
874   string s;
875   FOR_EACH_RANGE (i, 0, n) {
876     // auto buf = &s.back() + 1;
877     char buffer[20];
878     s.append(buffer, u64ToAsciiClassic(value, buffer));
879     doNotOptimizeAway(s.size());
880   }
881 }
882
883 void u2aAppendFollyBM(uint n, uint64_t value) {
884   string s;
885   FOR_EACH_RANGE (i, 0, n) {
886     // auto buf = &s.back() + 1;
887     char buffer[20];
888     s.append(buffer, uint64ToBufferUnsafe(value, buffer));
889     doNotOptimizeAway(s.size());
890   }
891 }
892
893 #define DEFINE_BENCHMARK_GROUP(n)                       \
894   BENCHMARK_PARAM(u64ToAsciiClassicBM, n);              \
895   BENCHMARK_RELATIVE_PARAM(u64ToAsciiTableBM, n);       \
896   BENCHMARK_RELATIVE_PARAM(u64ToAsciiFollyBM, n);       \
897   BENCHMARK_DRAW_LINE();
898
899 DEFINE_BENCHMARK_GROUP(1);
900 DEFINE_BENCHMARK_GROUP(12);
901 DEFINE_BENCHMARK_GROUP(123);
902 DEFINE_BENCHMARK_GROUP(1234);
903 DEFINE_BENCHMARK_GROUP(12345);
904 DEFINE_BENCHMARK_GROUP(123456);
905 DEFINE_BENCHMARK_GROUP(1234567);
906 DEFINE_BENCHMARK_GROUP(12345678);
907 DEFINE_BENCHMARK_GROUP(123456789);
908 DEFINE_BENCHMARK_GROUP(1234567890);
909 DEFINE_BENCHMARK_GROUP(12345678901);
910 DEFINE_BENCHMARK_GROUP(123456789012);
911 DEFINE_BENCHMARK_GROUP(1234567890123);
912 DEFINE_BENCHMARK_GROUP(12345678901234);
913 DEFINE_BENCHMARK_GROUP(123456789012345);
914 DEFINE_BENCHMARK_GROUP(1234567890123456);
915 DEFINE_BENCHMARK_GROUP(12345678901234567);
916 DEFINE_BENCHMARK_GROUP(123456789012345678);
917 DEFINE_BENCHMARK_GROUP(1234567890123456789);
918 DEFINE_BENCHMARK_GROUP(12345678901234567890U);
919
920 #undef DEFINE_BENCHMARK_GROUP
921
922 #define DEFINE_BENCHMARK_GROUP(n)                       \
923   BENCHMARK_PARAM(clibAtoiMeasure, n);                  \
924   BENCHMARK_RELATIVE_PARAM(lexicalCastMeasure, n);      \
925   BENCHMARK_RELATIVE_PARAM(handwrittenAtoiMeasure, n);  \
926   BENCHMARK_RELATIVE_PARAM(follyAtoiMeasure, n);        \
927   BENCHMARK_DRAW_LINE();
928
929 DEFINE_BENCHMARK_GROUP(1);
930 DEFINE_BENCHMARK_GROUP(2);
931 DEFINE_BENCHMARK_GROUP(3);
932 DEFINE_BENCHMARK_GROUP(4);
933 DEFINE_BENCHMARK_GROUP(5);
934 DEFINE_BENCHMARK_GROUP(6);
935 DEFINE_BENCHMARK_GROUP(7);
936 DEFINE_BENCHMARK_GROUP(8);
937 DEFINE_BENCHMARK_GROUP(9);
938 DEFINE_BENCHMARK_GROUP(10);
939 DEFINE_BENCHMARK_GROUP(11);
940 DEFINE_BENCHMARK_GROUP(12);
941 DEFINE_BENCHMARK_GROUP(13);
942 DEFINE_BENCHMARK_GROUP(14);
943 DEFINE_BENCHMARK_GROUP(15);
944 DEFINE_BENCHMARK_GROUP(16);
945 DEFINE_BENCHMARK_GROUP(17);
946 DEFINE_BENCHMARK_GROUP(18);
947 DEFINE_BENCHMARK_GROUP(19);
948
949 #undef DEFINE_BENCHMARK_GROUP
950
951 int main(int argc, char** argv) {
952   testing::InitGoogleTest(&argc, argv);
953   google::ParseCommandLineFlags(&argc, &argv, true);
954   auto ret = RUN_ALL_TESTS();
955   if (!ret && FLAGS_benchmark) {
956     folly::runBenchmarks();
957   }
958   return ret;
959 }