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