f48c69c39e34838a89f9c63355f54c69bb854884
[folly.git] / folly / test / ConvTest.cpp
1 /*
2  * Copyright 2013 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 template <class String>
407 void testVariadicToDelim() {
408   String s;
409   toAppendDelim(":", &s);
410   toAppendDelim(
411       ":", "Lorem ipsum ", 1234, String(" dolor amet "), 567.89, '!', &s);
412   EXPECT_EQ(s, "Lorem ipsum :1234: dolor amet :567.89:!");
413
414   s = toDelim<String>(':');
415   EXPECT_TRUE(s.empty());
416
417   s = toDelim<String>(
418       ":", "Lorem ipsum ", nullptr, 1234, " dolor amet ", 567.89, '.');
419   EXPECT_EQ(s, "Lorem ipsum ::1234: dolor amet :567.89:.");
420 }
421
422 TEST(Conv, NullString) {
423   string s1 = to<string>((char *) NULL);
424   EXPECT_TRUE(s1.empty());
425   fbstring s2 = to<fbstring>((char *) NULL);
426   EXPECT_TRUE(s2.empty());
427 }
428
429 TEST(Conv, VariadicTo) {
430   testVariadicTo<string>();
431   testVariadicTo<fbstring>();
432 }
433
434 TEST(Conv, VariadicToDelim) {
435   testVariadicToDelim<string>();
436   testVariadicToDelim<fbstring>();
437 }
438
439 template <class String>
440 void testDoubleToString() {
441   EXPECT_EQ(to<string>(0.0), "0");
442   EXPECT_EQ(to<string>(0.5), "0.5");
443   EXPECT_EQ(to<string>(10.25), "10.25");
444   EXPECT_EQ(to<string>(1.123e10), "11230000000");
445 }
446
447 TEST(Conv, DoubleToString) {
448   testDoubleToString<string>();
449   testDoubleToString<fbstring>();
450 }
451
452 TEST(Conv, FBStringToString) {
453   fbstring foo("foo");
454   string ret = to<string>(foo);
455   EXPECT_EQ(ret, "foo");
456   string ret2 = to<string>(foo, 2);
457   EXPECT_EQ(ret2, "foo2");
458 }
459
460 TEST(Conv, StringPieceToDouble) {
461   string s = "2134123.125 zorro";
462   StringPiece pc(s);
463   EXPECT_EQ(to<double>(&pc), 2134123.125);
464   EXPECT_EQ(pc, " zorro");
465
466   EXPECT_THROW(to<double>(StringPiece(s)), std::range_error);
467   EXPECT_EQ(to<double>(StringPiece(s.data(), pc.data())), 2134123.125);
468
469 // Test NaN conversion
470   try {
471     to<double>("not a number");
472     EXPECT_TRUE(false);
473   } catch (const std::range_error &) {
474   }
475
476   EXPECT_TRUE(std::isnan(to<double>("NaN")));
477   EXPECT_EQ(to<double>("inf"), numeric_limits<double>::infinity());
478   EXPECT_EQ(to<double>("infinity"), numeric_limits<double>::infinity());
479   EXPECT_THROW(to<double>("infinitX"), std::range_error);
480   EXPECT_EQ(to<double>("-inf"), -numeric_limits<double>::infinity());
481   EXPECT_EQ(to<double>("-infinity"), -numeric_limits<double>::infinity());
482   EXPECT_THROW(to<double>("-infinitX"), std::range_error);
483 }
484
485 TEST(Conv, EmptyStringToInt) {
486   string s = "";
487   StringPiece pc(s);
488
489   try {
490     to<int>(pc);
491     EXPECT_TRUE(false);
492   } catch (const std::range_error &) {
493   }
494 }
495
496 TEST(Conv, CorruptedStringToInt) {
497   string s = "-1";
498   StringPiece pc(s.data(), s.data() + 1); // Only  "-"
499
500   try {
501     to<int64_t>(&pc);
502     EXPECT_TRUE(false);
503   } catch (const std::range_error &) {
504   }
505 }
506
507 TEST(Conv, EmptyStringToDouble) {
508   string s = "";
509   StringPiece pc(s);
510
511   try {
512     to<double>(pc);
513     EXPECT_TRUE(false);
514   } catch (const std::range_error &) {
515   }
516 }
517
518 TEST(Conv, IntToDouble) {
519   auto d = to<double>(42);
520   EXPECT_EQ(d, 42);
521   /* This seems not work in ubuntu11.10, gcc 4.6.1
522   try {
523     auto f = to<float>(957837589847);
524     EXPECT_TRUE(false);
525   } catch (std::range_error& e) {
526     //LOG(INFO) << e.what();
527   }
528   */
529 }
530
531 TEST(Conv, DoubleToInt) {
532   auto i = to<int>(42.0);
533   EXPECT_EQ(i, 42);
534   try {
535     auto i = to<int>(42.1);
536     EXPECT_TRUE(false);
537   } catch (std::range_error& e) {
538     //LOG(INFO) << e.what();
539   }
540 }
541
542 TEST(Conv, EnumToInt) {
543   enum A { x = 42, y = 420, z = 65 };
544   auto i = to<int>(x);
545   EXPECT_EQ(i, 42);
546   auto j = to<char>(x);
547   EXPECT_EQ(j, 42);
548   try {
549     auto i = to<char>(y);
550     LOG(ERROR) << static_cast<unsigned int>(i);
551     EXPECT_TRUE(false);
552   } catch (std::range_error& e) {
553     //LOG(INFO) << e.what();
554   }
555 }
556
557 TEST(Conv, EnumToString) {
558   // task 813959
559   enum A { x = 4, y = 420, z = 65 };
560   EXPECT_EQ("foo.4", to<string>("foo.", x));
561   EXPECT_EQ("foo.420", to<string>("foo.", y));
562   EXPECT_EQ("foo.65", to<string>("foo.", z));
563 }
564
565 TEST(Conv, IntToEnum) {
566   enum A { x = 42, y = 420 };
567   auto i = to<A>(42);
568   EXPECT_EQ(i, x);
569   auto j = to<A>(100);
570   EXPECT_EQ(j, 100);
571   try {
572     auto i = to<A>(5000000000L);
573     EXPECT_TRUE(false);
574   } catch (std::range_error& e) {
575     //LOG(INFO) << e.what();
576   }
577 }
578
579 TEST(Conv, UnsignedEnum) {
580   enum E : uint32_t { x = 3000000000U };
581   auto u = to<uint32_t>(x);
582   EXPECT_EQ(u, 3000000000U);
583   auto s = to<string>(x);
584   EXPECT_EQ("3000000000", s);
585   auto e = to<E>(3000000000U);
586   EXPECT_EQ(e, x);
587   try {
588     auto i = to<int32_t>(x);
589     LOG(ERROR) << to<uint32_t>(x);
590     EXPECT_TRUE(false);
591   } catch (std::range_error& e) {
592   }
593 }
594
595 #if defined(__GNUC__) && __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
596 // to<enum class> and to(enum class) only supported in gcc 4.7 onwards
597
598 TEST(Conv, UnsignedEnumClass) {
599   enum class E : uint32_t { x = 3000000000U };
600   auto u = to<uint32_t>(E::x);
601   EXPECT_GT(u, 0);
602   EXPECT_EQ(u, 3000000000U);
603   auto s = to<string>(E::x);
604   EXPECT_EQ("3000000000", s);
605   auto e = to<E>(3000000000U);
606   EXPECT_EQ(e, E::x);
607   try {
608     auto i = to<int32_t>(E::x);
609     LOG(ERROR) << to<uint32_t>(E::x);
610     EXPECT_TRUE(false);
611   } catch (std::range_error& e) {
612   }
613 }
614
615 // Multi-argument to<string> uses toAppend, a different code path than
616 // to<string>(enum).
617 TEST(Conv, EnumClassToString) {
618   enum class A { x = 4, y = 420, z = 65 };
619   EXPECT_EQ("foo.4", to<string>("foo.", A::x));
620   EXPECT_EQ("foo.420", to<string>("foo.", A::y));
621   EXPECT_EQ("foo.65", to<string>("foo.", A::z));
622 }
623
624 #endif // gcc 4.7 onwards
625
626 template<typename Src>
627 void testStr2Bool() {
628   EXPECT_FALSE(to<bool>(Src("0")));
629   EXPECT_FALSE(to<bool>(Src("  000  ")));
630
631   EXPECT_FALSE(to<bool>(Src("n")));
632   EXPECT_FALSE(to<bool>(Src("no")));
633   EXPECT_FALSE(to<bool>(Src("false")));
634   EXPECT_FALSE(to<bool>(Src("False")));
635   EXPECT_FALSE(to<bool>(Src("  fAlSe"  )));
636   EXPECT_FALSE(to<bool>(Src("F")));
637   EXPECT_FALSE(to<bool>(Src("off")));
638
639   EXPECT_TRUE(to<bool>(Src("1")));
640   EXPECT_TRUE(to<bool>(Src("  001 ")));
641   EXPECT_TRUE(to<bool>(Src("y")));
642   EXPECT_TRUE(to<bool>(Src("yes")));
643   EXPECT_TRUE(to<bool>(Src("\nyEs\t")));
644   EXPECT_TRUE(to<bool>(Src("true")));
645   EXPECT_TRUE(to<bool>(Src("True")));
646   EXPECT_TRUE(to<bool>(Src("T")));
647   EXPECT_TRUE(to<bool>(Src("on")));
648
649   EXPECT_THROW(to<bool>(Src("")), std::range_error);
650   EXPECT_THROW(to<bool>(Src("2")), std::range_error);
651   EXPECT_THROW(to<bool>(Src("11")), std::range_error);
652   EXPECT_THROW(to<bool>(Src("19")), std::range_error);
653   EXPECT_THROW(to<bool>(Src("o")), std::range_error);
654   EXPECT_THROW(to<bool>(Src("fal")), std::range_error);
655   EXPECT_THROW(to<bool>(Src("tru")), std::range_error);
656   EXPECT_THROW(to<bool>(Src("ye")), std::range_error);
657   EXPECT_THROW(to<bool>(Src("yes foo")), std::range_error);
658   EXPECT_THROW(to<bool>(Src("bar no")), std::range_error);
659   EXPECT_THROW(to<bool>(Src("one")), std::range_error);
660   EXPECT_THROW(to<bool>(Src("true_")), std::range_error);
661   EXPECT_THROW(to<bool>(Src("bogus_token_that_is_too_long")),
662                std::range_error);
663 }
664
665 TEST(Conv, StringToBool) {
666   // testStr2Bool<const char *>();
667   testStr2Bool<std::string>();
668
669   // Test with strings that are not NUL terminated.
670   const char buf[] = "01234";
671   EXPECT_FALSE(to<bool>(StringPiece(buf, buf + 1)));  // "0"
672   EXPECT_TRUE(to<bool>(StringPiece(buf + 1, buf + 2)));  // "1"
673   const char buf2[] = "one two three";
674   EXPECT_TRUE(to<bool>(StringPiece(buf2, buf2 + 2)));  // "on"
675   const char buf3[] = "false";
676   EXPECT_THROW(to<bool>(StringPiece(buf3, buf3 + 3)),  // "fal"
677                std::range_error);
678
679   // Test the StringPiece* API
680   const char buf4[] = "001foo";
681   StringPiece sp4(buf4);
682   EXPECT_TRUE(to<bool>(&sp4));
683   EXPECT_EQ(buf4 + 3, sp4.begin());
684   const char buf5[] = "0012";
685   StringPiece sp5(buf5);
686   EXPECT_THROW(to<bool>(&sp5), std::range_error);
687   EXPECT_EQ(buf5, sp5.begin());
688 }
689
690 TEST(Conv, NewUint64ToString) {
691   char buf[21];
692
693 #define THE_GREAT_EXPECTATIONS(n, len)                  \
694   do {                                                  \
695     EXPECT_EQ((len), uint64ToBufferUnsafe((n), buf));   \
696     buf[(len)] = 0;                                     \
697     auto s = string(#n);                                \
698     s = s.substr(0, s.size() - 2);                      \
699     EXPECT_EQ(s, buf);                                  \
700   } while (0)
701
702   THE_GREAT_EXPECTATIONS(0UL, 1);
703   THE_GREAT_EXPECTATIONS(1UL, 1);
704   THE_GREAT_EXPECTATIONS(12UL, 2);
705   THE_GREAT_EXPECTATIONS(123UL, 3);
706   THE_GREAT_EXPECTATIONS(1234UL, 4);
707   THE_GREAT_EXPECTATIONS(12345UL, 5);
708   THE_GREAT_EXPECTATIONS(123456UL, 6);
709   THE_GREAT_EXPECTATIONS(1234567UL, 7);
710   THE_GREAT_EXPECTATIONS(12345678UL, 8);
711   THE_GREAT_EXPECTATIONS(123456789UL, 9);
712   THE_GREAT_EXPECTATIONS(1234567890UL, 10);
713   THE_GREAT_EXPECTATIONS(12345678901UL, 11);
714   THE_GREAT_EXPECTATIONS(123456789012UL, 12);
715   THE_GREAT_EXPECTATIONS(1234567890123UL, 13);
716   THE_GREAT_EXPECTATIONS(12345678901234UL, 14);
717   THE_GREAT_EXPECTATIONS(123456789012345UL, 15);
718   THE_GREAT_EXPECTATIONS(1234567890123456UL, 16);
719   THE_GREAT_EXPECTATIONS(12345678901234567UL, 17);
720   THE_GREAT_EXPECTATIONS(123456789012345678UL, 18);
721   THE_GREAT_EXPECTATIONS(1234567890123456789UL, 19);
722   THE_GREAT_EXPECTATIONS(18446744073709551614UL, 20);
723   THE_GREAT_EXPECTATIONS(18446744073709551615UL, 20);
724
725 #undef THE_GREAT_EXPECTATIONS
726 }
727
728 ////////////////////////////////////////////////////////////////////////////////
729 // Benchmarks for ASCII to int conversion
730 ////////////////////////////////////////////////////////////////////////////////
731 // @author: Rajat Goel (rajat)
732
733 static int64_t handwrittenAtoi(const char* start, const char* end) {
734
735   bool positive = true;
736   int64_t retVal = 0;
737
738   if (start == end) {
739     throw std::runtime_error("empty string");
740   }
741
742   while (start < end && isspace(*start)) {
743     ++start;
744   }
745
746   switch (*start) {
747     case '-':
748       positive = false;
749     case '+':
750       ++start;
751     default:;
752   }
753
754   while (start < end && *start >= '0' && *start <= '9') {
755     auto const newRetVal = retVal * 10 + (*start++ - '0');
756     if (newRetVal < retVal) {
757       throw std::runtime_error("overflow");
758     }
759     retVal = newRetVal;
760   }
761
762   if (start != end) {
763     throw std::runtime_error("extra chars at the end");
764   }
765
766   return positive ? retVal : -retVal;
767 }
768
769 static StringPiece pc1 = "1234567890123456789";
770
771 void handwrittenAtoiMeasure(uint n, uint digits) {
772   auto p = pc1.subpiece(pc1.size() - digits, digits);
773   FOR_EACH_RANGE (i, 0, n) {
774     doNotOptimizeAway(handwrittenAtoi(p.begin(), p.end()));
775   }
776 }
777
778 void follyAtoiMeasure(uint n, uint digits) {
779   auto p = pc1.subpiece(pc1.size() - digits, digits);
780   FOR_EACH_RANGE (i, 0, n) {
781     doNotOptimizeAway(folly::to<int64_t>(p.begin(), p.end()));
782   }
783 }
784
785 void clibAtoiMeasure(uint n, uint digits) {
786   auto p = pc1.subpiece(pc1.size() - digits, digits);
787   assert(*p.end() == 0);
788   static_assert(sizeof(long) == 8, "64-bit long assumed");
789   FOR_EACH_RANGE (i, 0, n) {
790     doNotOptimizeAway(atol(p.begin()));
791   }
792 }
793
794 void clibStrtoulMeasure(uint n, uint digits) {
795   auto p = pc1.subpiece(pc1.size() - digits, digits);
796   assert(*p.end() == 0);
797   char * endptr;
798   FOR_EACH_RANGE (i, 0, n) {
799     doNotOptimizeAway(strtoul(p.begin(), &endptr, 10));
800   }
801 }
802
803 void lexicalCastMeasure(uint n, uint digits) {
804   auto p = pc1.subpiece(pc1.size() - digits, digits);
805   assert(*p.end() == 0);
806   FOR_EACH_RANGE (i, 0, n) {
807     doNotOptimizeAway(boost::lexical_cast<uint64_t>(p.begin()));
808   }
809 }
810
811 // Benchmarks for unsigned to string conversion, raw
812
813 unsigned u64ToAsciiTable(uint64_t value, char* dst) {
814   static const char digits[201] =
815     "00010203040506070809"
816     "10111213141516171819"
817     "20212223242526272829"
818     "30313233343536373839"
819     "40414243444546474849"
820     "50515253545556575859"
821     "60616263646566676869"
822     "70717273747576777879"
823     "80818283848586878889"
824     "90919293949596979899";
825
826   uint32_t const length = digits10(value);
827   uint32_t next = length - 1;
828   while (value >= 100) {
829     auto const i = (value % 100) * 2;
830     value /= 100;
831     dst[next] = digits[i + 1];
832     dst[next - 1] = digits[i];
833     next -= 2;
834   }
835   // Handle last 1-2 digits
836   if (value < 10) {
837     dst[next] = '0' + uint32_t(value);
838   } else {
839     auto i = uint32_t(value) * 2;
840     dst[next] = digits[i + 1];
841     dst[next - 1] = digits[i];
842   }
843   return length;
844 }
845
846 void u64ToAsciiTableBM(uint n, uint64_t value) {
847   // This is too fast, need to do 10 times per iteration
848   char buf[20];
849   FOR_EACH_RANGE (i, 0, n) {
850     doNotOptimizeAway(u64ToAsciiTable(value + n, buf));
851   }
852 }
853
854 unsigned u64ToAsciiClassic(uint64_t value, char* dst) {
855   // Write backwards.
856   char* next = (char*)dst;
857   char* start = next;
858   do {
859     *next++ = '0' + (value % 10);
860     value /= 10;
861   } while (value != 0);
862   unsigned length = next - start;
863
864   // Reverse in-place.
865   next--;
866   while (next > start) {
867     char swap = *next;
868     *next = *start;
869     *start = swap;
870     next--;
871     start++;
872   }
873   return length;
874 }
875
876 void u64ToAsciiClassicBM(uint n, uint64_t value) {
877   // This is too fast, need to do 10 times per iteration
878   char buf[20];
879   FOR_EACH_RANGE (i, 0, n) {
880     doNotOptimizeAway(u64ToAsciiClassic(value + n, buf));
881   }
882 }
883
884 void u64ToAsciiFollyBM(uint n, uint64_t value) {
885   // This is too fast, need to do 10 times per iteration
886   char buf[20];
887   FOR_EACH_RANGE (i, 0, n) {
888     doNotOptimizeAway(uint64ToBufferUnsafe(value + n, buf));
889   }
890 }
891
892 // Benchmark uitoa with string append
893
894 void u2aAppendClassicBM(uint n, uint64_t value) {
895   string s;
896   FOR_EACH_RANGE (i, 0, n) {
897     // auto buf = &s.back() + 1;
898     char buffer[20];
899     s.append(buffer, u64ToAsciiClassic(value, buffer));
900     doNotOptimizeAway(s.size());
901   }
902 }
903
904 void u2aAppendFollyBM(uint n, uint64_t value) {
905   string s;
906   FOR_EACH_RANGE (i, 0, n) {
907     // auto buf = &s.back() + 1;
908     char buffer[20];
909     s.append(buffer, uint64ToBufferUnsafe(value, buffer));
910     doNotOptimizeAway(s.size());
911   }
912 }
913
914 #define DEFINE_BENCHMARK_GROUP(n)                       \
915   BENCHMARK_PARAM(u64ToAsciiClassicBM, n);              \
916   BENCHMARK_RELATIVE_PARAM(u64ToAsciiTableBM, n);       \
917   BENCHMARK_RELATIVE_PARAM(u64ToAsciiFollyBM, n);       \
918   BENCHMARK_DRAW_LINE();
919
920 DEFINE_BENCHMARK_GROUP(1);
921 DEFINE_BENCHMARK_GROUP(12);
922 DEFINE_BENCHMARK_GROUP(123);
923 DEFINE_BENCHMARK_GROUP(1234);
924 DEFINE_BENCHMARK_GROUP(12345);
925 DEFINE_BENCHMARK_GROUP(123456);
926 DEFINE_BENCHMARK_GROUP(1234567);
927 DEFINE_BENCHMARK_GROUP(12345678);
928 DEFINE_BENCHMARK_GROUP(123456789);
929 DEFINE_BENCHMARK_GROUP(1234567890);
930 DEFINE_BENCHMARK_GROUP(12345678901);
931 DEFINE_BENCHMARK_GROUP(123456789012);
932 DEFINE_BENCHMARK_GROUP(1234567890123);
933 DEFINE_BENCHMARK_GROUP(12345678901234);
934 DEFINE_BENCHMARK_GROUP(123456789012345);
935 DEFINE_BENCHMARK_GROUP(1234567890123456);
936 DEFINE_BENCHMARK_GROUP(12345678901234567);
937 DEFINE_BENCHMARK_GROUP(123456789012345678);
938 DEFINE_BENCHMARK_GROUP(1234567890123456789);
939 DEFINE_BENCHMARK_GROUP(12345678901234567890U);
940
941 #undef DEFINE_BENCHMARK_GROUP
942
943 #define DEFINE_BENCHMARK_GROUP(n)                       \
944   BENCHMARK_PARAM(clibAtoiMeasure, n);                  \
945   BENCHMARK_RELATIVE_PARAM(lexicalCastMeasure, n);      \
946   BENCHMARK_RELATIVE_PARAM(handwrittenAtoiMeasure, n);  \
947   BENCHMARK_RELATIVE_PARAM(follyAtoiMeasure, n);        \
948   BENCHMARK_DRAW_LINE();
949
950 DEFINE_BENCHMARK_GROUP(1);
951 DEFINE_BENCHMARK_GROUP(2);
952 DEFINE_BENCHMARK_GROUP(3);
953 DEFINE_BENCHMARK_GROUP(4);
954 DEFINE_BENCHMARK_GROUP(5);
955 DEFINE_BENCHMARK_GROUP(6);
956 DEFINE_BENCHMARK_GROUP(7);
957 DEFINE_BENCHMARK_GROUP(8);
958 DEFINE_BENCHMARK_GROUP(9);
959 DEFINE_BENCHMARK_GROUP(10);
960 DEFINE_BENCHMARK_GROUP(11);
961 DEFINE_BENCHMARK_GROUP(12);
962 DEFINE_BENCHMARK_GROUP(13);
963 DEFINE_BENCHMARK_GROUP(14);
964 DEFINE_BENCHMARK_GROUP(15);
965 DEFINE_BENCHMARK_GROUP(16);
966 DEFINE_BENCHMARK_GROUP(17);
967 DEFINE_BENCHMARK_GROUP(18);
968 DEFINE_BENCHMARK_GROUP(19);
969
970 #undef DEFINE_BENCHMARK_GROUP
971
972 int main(int argc, char** argv) {
973   testing::InitGoogleTest(&argc, argv);
974   google::ParseCommandLineFlags(&argc, &argv, true);
975   auto ret = RUN_ALL_TESTS();
976   if (!ret && FLAGS_benchmark) {
977     folly::runBenchmarks();
978   }
979   return ret;
980 }