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