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