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