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