fix flaky ConnectTFOTimeout and ConnectTFOFallbackTimeout tests
[folly.git] / folly / test / ConvTest.cpp
1 /*
2  * Copyright 2016 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/Conv.h>
18 #include <folly/Foreach.h>
19 #include <boost/lexical_cast.hpp>
20 #include <gtest/gtest.h>
21 #include <limits>
22 #include <stdexcept>
23
24 using namespace std;
25 using namespace folly;
26
27
28 TEST(Conv, digits10) {
29   char buffer[100];
30   uint64_t power;
31
32   // first, some basic sniff tests
33   EXPECT_EQ( 1, digits10(0));
34   EXPECT_EQ( 1, digits10(1));
35   EXPECT_EQ( 1, digits10(9));
36   EXPECT_EQ( 2, digits10(10));
37   EXPECT_EQ( 2, digits10(99));
38   EXPECT_EQ( 3, digits10(100));
39   EXPECT_EQ( 3, digits10(999));
40   EXPECT_EQ( 4, digits10(1000));
41   EXPECT_EQ( 4, digits10(9999));
42   EXPECT_EQ(20, digits10(18446744073709551615ULL));
43
44   // try the first X nonnegatives.
45   // Covers some more cases of 2^p, 10^p
46   for (uint64_t i = 0; i < 100000; i++) {
47     snprintf(buffer, sizeof(buffer), "%" PRIu64, i);
48     EXPECT_EQ(strlen(buffer), digits10(i));
49   }
50
51   // try powers of 2
52   power = 1;
53   for (int p = 0; p < 64; p++) {
54     snprintf(buffer, sizeof(buffer), "%" PRIu64, power);
55     EXPECT_EQ(strlen(buffer), digits10(power));
56     snprintf(buffer, sizeof(buffer), "%" PRIu64, power - 1);
57     EXPECT_EQ(strlen(buffer), digits10(power - 1));
58     snprintf(buffer, sizeof(buffer), "%" PRIu64, power + 1);
59     EXPECT_EQ(strlen(buffer), digits10(power + 1));
60     power *= 2;
61   }
62
63   // try powers of 10
64   power = 1;
65   for (int p = 0; p < 20; p++) {
66     snprintf(buffer, sizeof(buffer), "%" PRIu64, power);
67     EXPECT_EQ(strlen(buffer), digits10(power));
68     snprintf(buffer, sizeof(buffer), "%" PRIu64, power - 1);
69     EXPECT_EQ(strlen(buffer), digits10(power - 1));
70     snprintf(buffer, sizeof(buffer), "%" PRIu64, power + 1);
71     EXPECT_EQ(strlen(buffer), digits10(power + 1));
72     power *= 10;
73   }
74 }
75
76 // Test to<T>(T)
77 TEST(Conv, Type2Type) {
78   bool boolV = true;
79   EXPECT_EQ(to<bool>(boolV), true);
80
81   int intV = 42;
82   EXPECT_EQ(to<int>(intV), 42);
83
84   float floatV = 4.2f;
85   EXPECT_EQ(to<float>(floatV), 4.2f);
86
87   double doubleV = 0.42;
88   EXPECT_EQ(to<double>(doubleV), 0.42);
89
90   std::string stringV = "StdString";
91   EXPECT_EQ(to<std::string>(stringV), "StdString");
92
93   folly::fbstring fbStrV = "FBString";
94   EXPECT_EQ(to<folly::fbstring>(fbStrV), "FBString");
95
96   folly::StringPiece spV("StringPiece");
97   EXPECT_EQ(to<folly::StringPiece>(spV), "StringPiece");
98
99   // Rvalues
100   EXPECT_EQ(to<bool>(true), true);
101   EXPECT_EQ(to<int>(42), 42);
102   EXPECT_EQ(to<float>(4.2f), 4.2f);
103   EXPECT_EQ(to<double>(.42), .42);
104   EXPECT_EQ(to<std::string>(std::string("Hello")), "Hello");
105   EXPECT_EQ(to<folly::fbstring>(folly::fbstring("hello")), "hello");
106   EXPECT_EQ(to<folly::StringPiece>(folly::StringPiece("Forty Two")),
107             "Forty Two");
108 }
109
110 TEST(Conv, Integral2Integral) {
111   // Same size, different signs
112   int64_t s64 = numeric_limits<uint8_t>::max();
113   EXPECT_EQ(to<uint8_t>(s64), s64);
114
115   s64 = numeric_limits<int8_t>::max();
116   EXPECT_EQ(to<int8_t>(s64), s64);
117 }
118
119 TEST(Conv, Floating2Floating) {
120   float f1 = 1e3f;
121   double d1 = to<double>(f1);
122   EXPECT_EQ(f1, d1);
123
124   double d2 = 23.0;
125   auto f2 = to<float>(d2);
126   EXPECT_EQ(double(f2), d2);
127
128   double invalidFloat = std::numeric_limits<double>::max();
129   EXPECT_ANY_THROW(to<float>(invalidFloat));
130   invalidFloat = -std::numeric_limits<double>::max();
131   EXPECT_ANY_THROW(to<float>(invalidFloat));
132
133   try {
134     auto shouldWork = to<float>(std::numeric_limits<double>::min());
135     // The value of `shouldWork' is an implementation defined choice
136     // between the following two alternatives.
137     EXPECT_TRUE(shouldWork == std::numeric_limits<float>::min() ||
138                 shouldWork == 0.f);
139   } catch (...) {
140     EXPECT_TRUE(false);
141   }
142 }
143
144 template <class String>
145 void testIntegral2String() {
146 }
147
148 template <class String, class Int, class... Ints>
149 void testIntegral2String() {
150   typedef typename make_unsigned<Int>::type Uint;
151   typedef typename make_signed<Int>::type Sint;
152
153   Uint value = 123;
154   EXPECT_EQ(to<String>(value), "123");
155   Sint svalue = 123;
156   EXPECT_EQ(to<String>(svalue), "123");
157   svalue = -123;
158   EXPECT_EQ(to<String>(svalue), "-123");
159
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
170   testIntegral2String<String, Ints...>();
171 }
172
173 #if FOLLY_HAVE_INT128_T
174 template <class String>
175 void test128Bit2String() {
176   typedef unsigned __int128 Uint;
177   typedef __int128 Sint;
178
179   EXPECT_EQ(detail::digitsEnough<unsigned __int128>(), 39);
180
181   Uint value = 123;
182   EXPECT_EQ(to<String>(value), "123");
183   Sint svalue = 123;
184   EXPECT_EQ(to<String>(svalue), "123");
185   svalue = -123;
186   EXPECT_EQ(to<String>(svalue), "-123");
187
188   value = __int128(1) << 64;
189   EXPECT_EQ(to<String>(value), "18446744073709551616");
190
191   svalue =  -(__int128(1) << 64);
192   EXPECT_EQ(to<String>(svalue), "-18446744073709551616");
193
194   value = 0;
195   EXPECT_EQ(to<String>(value), "0");
196
197   svalue = 0;
198   EXPECT_EQ(to<String>(svalue), "0");
199
200   value = ~__int128(0);
201   EXPECT_EQ(to<String>(value), "340282366920938463463374607431768211455");
202
203   svalue = -(Uint(1) << 127);
204   EXPECT_EQ(to<String>(svalue), "-170141183460469231731687303715884105728");
205
206   svalue = (Uint(1) << 127) - 1;
207   EXPECT_EQ(to<String>(svalue), "170141183460469231731687303715884105727");
208
209   // TODO: the following do not compile to<__int128> ...
210
211 #if 0
212   value = numeric_limits<Uint>::min();
213   EXPECT_EQ(to<Uint>(to<String>(value)), value);
214   value = numeric_limits<Uint>::max();
215   EXPECT_EQ(to<Uint>(to<String>(value)), value);
216
217   svalue = numeric_limits<Sint>::min();
218   EXPECT_EQ(to<Sint>(to<String>(svalue)), svalue);
219   value = numeric_limits<Sint>::max();
220   EXPECT_EQ(to<Sint>(to<String>(svalue)), svalue);
221 #endif
222 }
223
224 #endif
225
226 TEST(Conv, Integral2String) {
227   testIntegral2String<std::string, char, short, int, long>();
228   testIntegral2String<fbstring, char, short, int, long>();
229
230 #if FOLLY_HAVE_INT128_T
231   test128Bit2String<std::string>();
232   test128Bit2String<fbstring>();
233 #endif
234 }
235
236 template <class String>
237 void testString2Integral() {
238 }
239
240 template <class String, class Int, class... Ints>
241 void testString2Integral() {
242   typedef typename make_unsigned<Int>::type Uint;
243   typedef typename make_signed<Int>::type Sint;
244
245   // Unsigned numbers small enough to fit in a signed type
246   static const String strings[] = {
247     "0",
248     "00",
249     "2 ",
250     " 84",
251     " \n 123    \t\n",
252     " 127",
253     "0000000000000000000000000042"
254   };
255   static const Uint values[] = {
256     0,
257     0,
258     2,
259     84,
260     123,
261     127,
262     42
263   };
264   FOR_EACH_RANGE (i, 0, sizeof(strings) / sizeof(*strings)) {
265     EXPECT_EQ(to<Uint>(strings[i]), values[i]);
266     EXPECT_EQ(to<Sint>(strings[i]), values[i]);
267   }
268
269   // Unsigned numbers that won't fit in the signed variation
270   static const String uStrings[] = {
271     " 128",
272     "213",
273     "255"
274   };
275   static const Uint uValues[] = {
276     128,
277     213,
278     255
279   };
280   FOR_EACH_RANGE (i, 0, sizeof(uStrings)/sizeof(*uStrings)) {
281     EXPECT_EQ(to<Uint>(uStrings[i]), uValues[i]);
282     if (sizeof(Int) == 1) {
283       EXPECT_THROW(to<Sint>(uStrings[i]), std::range_error);
284     }
285   }
286
287   if (sizeof(Int) >= 4) {
288     static const String strings2[] = {
289       "256",
290       "6324 ",
291       "63245675 ",
292       "2147483647"
293     };
294     static const Uint values2[] = {
295       (Uint)256,
296       (Uint)6324,
297       (Uint)63245675,
298       (Uint)2147483647
299     };
300     FOR_EACH_RANGE (i, 0, sizeof(strings2)/sizeof(*strings2)) {
301       EXPECT_EQ(to<Uint>(strings2[i]), values2[i]);
302       EXPECT_EQ(to<Sint>(strings2[i]), values2[i]);
303     }
304
305     static const String uStrings2[] = {
306       "2147483648",
307       "3147483648",
308       "4147483648",
309       "4000000000",
310     };
311     static const Uint uValues2[] = {
312       (Uint)2147483648U,
313       (Uint)3147483648U,
314       (Uint)4147483648U,
315       (Uint)4000000000U,
316     };
317     FOR_EACH_RANGE (i, 0, sizeof(uStrings2)/sizeof(uStrings2)) {
318       EXPECT_EQ(to<Uint>(uStrings2[i]), uValues2[i]);
319       if (sizeof(Int) == 4) {
320         EXPECT_THROW(to<Sint>(uStrings2[i]), std::range_error);
321       }
322     }
323   }
324
325   if (sizeof(Int) >= 8) {
326     static_assert(sizeof(Int) <= 8, "Now that would be interesting");
327     static const String strings3[] = {
328       "2147483648",
329       "5000000001",
330       "25687346509278435",
331       "100000000000000000",
332       "9223372036854775807",
333     };
334     static const Uint values3[] = {
335       (Uint)2147483648ULL,
336       (Uint)5000000001ULL,
337       (Uint)25687346509278435ULL,
338       (Uint)100000000000000000ULL,
339       (Uint)9223372036854775807ULL,
340     };
341     FOR_EACH_RANGE (i, 0, sizeof(strings3)/sizeof(*strings3)) {
342       EXPECT_EQ(to<Uint>(strings3[i]), values3[i]);
343       EXPECT_EQ(to<Sint>(strings3[i]), values3[i]);
344     }
345
346     static const String uStrings3[] = {
347       "9223372036854775808",
348       "9987435987394857987",
349       "17873648761234698740",
350       "18446744073709551615",
351     };
352     static const Uint uValues3[] = {
353       (Uint)9223372036854775808ULL,
354       (Uint)9987435987394857987ULL,
355       (Uint)17873648761234698740ULL,
356       (Uint)18446744073709551615ULL,
357     };
358     FOR_EACH_RANGE (i, 0, sizeof(uStrings3)/sizeof(*uStrings3)) {
359       EXPECT_EQ(to<Uint>(uStrings3[i]), uValues3[i]);
360       if (sizeof(Int) == 8) {
361         EXPECT_THROW(to<Sint>(uStrings3[i]), std::range_error);
362       }
363     }
364   }
365
366   // Minimum possible negative values, and negative sign overflow
367   static const String strings4[] = {
368     "-128",
369     "-32768",
370     "-2147483648",
371     "-9223372036854775808",
372   };
373   static const String strings5[] = {
374     "-129",
375     "-32769",
376     "-2147483649",
377     "-9223372036854775809",
378   };
379   static const Sint values4[] = {
380     (Sint)-128LL,
381     (Sint)-32768LL,
382     (Sint)-2147483648LL,
383     (Sint)(-9223372036854775807LL - 1),
384   };
385   FOR_EACH_RANGE (i, 0, sizeof(strings4)/sizeof(*strings4)) {
386     if (sizeof(Int) > std::pow(2, i)) {
387       EXPECT_EQ(values4[i], to<Sint>(strings4[i]));
388       EXPECT_EQ(values4[i] - 1, to<Sint>(strings5[i]));
389     } else if (sizeof(Int) == std::pow(2, i)) {
390       EXPECT_EQ(values4[i], to<Sint>(strings4[i]));
391       EXPECT_THROW(to<Sint>(strings5[i]), std::range_error);
392     } else {
393       EXPECT_THROW(to<Sint>(strings4[i]), std::range_error);
394       EXPECT_THROW(to<Sint>(strings5[i]), std::range_error);
395     }
396   }
397
398   // Bogus string values
399   static const String bogusStrings[] = {
400     "",
401     "0x1234",
402     "123L",
403     "123a",
404     "x 123 ",
405     "234 y",
406     "- 42",  // whitespace is not allowed between the sign and the value
407     " +   13 ",
408     "12345678901234567890123456789",
409   };
410   for (const auto& str : bogusStrings) {
411     EXPECT_THROW(to<Sint>(str), std::range_error);
412     EXPECT_THROW(to<Uint>(str), std::range_error);
413   }
414
415   // A leading '+' character is only allowed when converting to signed types.
416   String posSign("+42");
417   EXPECT_EQ(42, to<Sint>(posSign));
418   EXPECT_THROW(to<Uint>(posSign), std::range_error);
419
420   testString2Integral<String, Ints...>();
421 }
422
423 TEST(Conv, String2Integral) {
424   testString2Integral<const char*, signed char, short, int, long, long long>();
425   testString2Integral<std::string, signed char, short, int, long, long long>();
426   testString2Integral<fbstring, signed char, short, int, long, long long>();
427
428   // Testing the behavior of the StringPiece* API
429   // StringPiece* normally parses as much valid data as it can,
430   // and advances the StringPiece to the end of the valid data.
431   char buf1[] = "100foo";
432   StringPiece sp1(buf1);
433   EXPECT_EQ(100, to<uint8_t>(&sp1));
434   EXPECT_EQ(buf1 + 3, sp1.begin());
435   // However, if the next character would cause an overflow it throws a
436   // range_error rather than consuming only as much as it can without
437   // overflowing.
438   char buf2[] = "1002";
439   StringPiece sp2(buf2);
440   EXPECT_THROW(to<uint8_t>(&sp2), std::range_error);
441   EXPECT_EQ(buf2, sp2.begin());
442 }
443
444 TEST(Conv, StringPiece2Integral) {
445   string s = "  +123  hello world  ";
446   StringPiece sp = s;
447   EXPECT_EQ(to<int>(&sp), 123);
448   EXPECT_EQ(sp, "  hello world  ");
449 }
450
451 TEST(Conv, StringPieceAppend) {
452   string s = "foobar";
453   {
454     StringPiece sp(s, 0, 3);
455     string result = to<string>(s, sp);
456     EXPECT_EQ(result, "foobarfoo");
457   }
458   {
459     StringPiece sp1(s, 0, 3);
460     StringPiece sp2(s, 3, 3);
461     string result = to<string>(sp1, sp2);
462     EXPECT_EQ(result, s);
463   }
464 }
465
466 TEST(Conv, BadStringToIntegral) {
467   // Note that leading spaces (e.g.  " 1") are valid.
468   vector<string> v = { "a", "", " ", "\n", " a0", "abcdef", "1Z", "!#" };
469   for (auto& s: v) {
470     EXPECT_THROW(to<int>(s), std::range_error) << "s=" << s;
471   }
472 }
473
474 template <class String>
475 void testIdenticalTo() {
476   String s("Yukkuri shiteitte ne!!!");
477
478   String result = to<String>(s);
479   EXPECT_EQ(result, s);
480 }
481
482 template <class String>
483 void testVariadicTo() {
484   String s;
485   toAppend(&s);
486   toAppend("Lorem ipsum ", 1234, String(" dolor amet "), 567.89, '!', &s);
487   EXPECT_EQ(s, "Lorem ipsum 1234 dolor amet 567.89!");
488
489   s = to<String>();
490   EXPECT_TRUE(s.empty());
491
492   s = to<String>("Lorem ipsum ", nullptr, 1234, " dolor amet ", 567.89, '.');
493   EXPECT_EQ(s, "Lorem ipsum 1234 dolor amet 567.89.");
494 }
495
496 template <class String>
497 void testIdenticalToDelim() {
498   String s("Yukkuri shiteitte ne!!!");
499
500   String charDelim = toDelim<String>('$', s);
501   EXPECT_EQ(charDelim, s);
502
503   String strDelim = toDelim<String>(String(">_<"), s);
504   EXPECT_EQ(strDelim, s);
505 }
506
507 template <class String>
508 void testVariadicToDelim() {
509   String s;
510   toAppendDelim(":", &s);
511   toAppendDelim(
512       ":", "Lorem ipsum ", 1234, String(" dolor amet "), 567.89, '!', &s);
513   EXPECT_EQ(s, "Lorem ipsum :1234: dolor amet :567.89:!");
514
515   s = toDelim<String>(':');
516   EXPECT_TRUE(s.empty());
517
518   s = toDelim<String>(
519       ":", "Lorem ipsum ", nullptr, 1234, " dolor amet ", 567.89, '.');
520   EXPECT_EQ(s, "Lorem ipsum ::1234: dolor amet :567.89:.");
521 }
522
523 TEST(Conv, NullString) {
524   string s1 = to<string>((char *) nullptr);
525   EXPECT_TRUE(s1.empty());
526   fbstring s2 = to<fbstring>((char *) nullptr);
527   EXPECT_TRUE(s2.empty());
528 }
529
530 TEST(Conv, VariadicTo) {
531   testIdenticalTo<string>();
532   testIdenticalTo<fbstring>();
533   testVariadicTo<string>();
534   testVariadicTo<fbstring>();
535 }
536
537 TEST(Conv, VariadicToDelim) {
538   testIdenticalToDelim<string>();
539   testIdenticalToDelim<fbstring>();
540   testVariadicToDelim<string>();
541   testVariadicToDelim<fbstring>();
542 }
543
544 template <class String>
545 void testDoubleToString() {
546   EXPECT_EQ(to<string>(0.0), "0");
547   EXPECT_EQ(to<string>(0.5), "0.5");
548   EXPECT_EQ(to<string>(10.25), "10.25");
549   EXPECT_EQ(to<string>(1.123e10), "11230000000");
550 }
551
552 TEST(Conv, DoubleToString) {
553   testDoubleToString<string>();
554   testDoubleToString<fbstring>();
555 }
556
557 TEST(Conv, FBStringToString) {
558   fbstring foo("foo");
559   string ret = to<string>(foo);
560   EXPECT_EQ(ret, "foo");
561   string ret2 = to<string>(foo, 2);
562   EXPECT_EQ(ret2, "foo2");
563 }
564
565 TEST(Conv, StringPieceToDouble) {
566   string s = "2134123.125 zorro";
567   StringPiece pc(s);
568   EXPECT_EQ(to<double>(&pc), 2134123.125);
569   EXPECT_EQ(pc, " zorro");
570
571   EXPECT_THROW(to<double>(StringPiece(s)), std::range_error);
572   EXPECT_EQ(to<double>(StringPiece(s.data(), pc.data())), 2134123.125);
573
574 // Test NaN conversion
575   try {
576     to<double>("not a number");
577     EXPECT_TRUE(false);
578   } catch (const std::range_error &) {
579   }
580
581   EXPECT_TRUE(std::isnan(to<double>("NaN")));
582   EXPECT_EQ(to<double>("inf"), numeric_limits<double>::infinity());
583   EXPECT_EQ(to<double>("infinity"), numeric_limits<double>::infinity());
584   EXPECT_THROW(to<double>("infinitX"), std::range_error);
585   EXPECT_EQ(to<double>("-inf"), -numeric_limits<double>::infinity());
586   EXPECT_EQ(to<double>("-infinity"), -numeric_limits<double>::infinity());
587   EXPECT_THROW(to<double>("-infinitX"), std::range_error);
588 }
589
590 TEST(Conv, EmptyStringToInt) {
591   string s = "";
592   StringPiece pc(s);
593
594   try {
595     to<int>(pc);
596     EXPECT_TRUE(false);
597   } catch (const std::range_error &) {
598   }
599 }
600
601 TEST(Conv, CorruptedStringToInt) {
602   string s = "-1";
603   StringPiece pc(s.data(), s.data() + 1); // Only  "-"
604
605   try {
606     to<int64_t>(&pc);
607     EXPECT_TRUE(false);
608   } catch (const std::range_error &) {
609   }
610 }
611
612 TEST(Conv, EmptyStringToDouble) {
613   string s = "";
614   StringPiece pc(s);
615
616   try {
617     to<double>(pc);
618     EXPECT_TRUE(false);
619   } catch (const std::range_error &) {
620   }
621 }
622
623 TEST(Conv, IntToDouble) {
624   auto d = to<double>(42);
625   EXPECT_EQ(d, 42);
626   /* This seems not work in ubuntu11.10, gcc 4.6.1
627   try {
628     auto f = to<float>(957837589847);
629     EXPECT_TRUE(false);
630   } catch (std::range_error& e) {
631     //LOG(INFO) << e.what();
632   }
633   */
634 }
635
636 TEST(Conv, DoubleToInt) {
637   auto i = to<int>(42.0);
638   EXPECT_EQ(i, 42);
639   try {
640     auto i = to<int>(42.1);
641     LOG(ERROR) << "to<int> returned " << i << " instead of throwing";
642     EXPECT_TRUE(false);
643   } catch (std::range_error& e) {
644     //LOG(INFO) << e.what();
645   }
646 }
647
648 TEST(Conv, EnumToInt) {
649   enum A { x = 42, y = 420, z = 65 };
650   auto i = to<int>(x);
651   EXPECT_EQ(i, 42);
652   auto j = to<char>(x);
653   EXPECT_EQ(j, 42);
654   try {
655     auto i = to<char>(y);
656     LOG(ERROR) << "to<char> returned "
657                << static_cast<unsigned int>(i)
658                << " instead of throwing";
659     EXPECT_TRUE(false);
660   } catch (std::range_error& e) {
661     //LOG(INFO) << e.what();
662   }
663 }
664
665 TEST(Conv, EnumToString) {
666   // task 813959
667   enum A { x = 4, y = 420, z = 65 };
668   EXPECT_EQ("foo.4", to<string>("foo.", x));
669   EXPECT_EQ("foo.420", to<string>("foo.", y));
670   EXPECT_EQ("foo.65", to<string>("foo.", z));
671 }
672
673 TEST(Conv, IntToEnum) {
674   enum A { x = 42, y = 420 };
675   auto i = to<A>(42);
676   EXPECT_EQ(i, x);
677   auto j = to<A>(100);
678   EXPECT_EQ(j, 100);
679   try {
680     auto i = to<A>(5000000000L);
681     LOG(ERROR) << "to<A> returned "
682                << static_cast<unsigned int>(i)
683                << " instead of throwing";
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<int32_t> returned " << i << " instead of throwing";
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   EXPECT_EQ("3000000000", to<string>(E::x));
712   EXPECT_EQ(E::x, to<E>(3000000000U));
713   EXPECT_EQ(E::x, to<E>("3000000000"));
714   E e;
715   parseTo("3000000000", e);
716   EXPECT_EQ(E::x, e);
717   EXPECT_THROW(to<int32_t>(E::x), std::range_error);
718 }
719
720 // Multi-argument to<string> uses toAppend, a different code path than
721 // to<string>(enum).
722 TEST(Conv, EnumClassToString) {
723   enum class A { x = 4, y = 420, z = 65 };
724   EXPECT_EQ("foo.4", to<string>("foo.", A::x));
725   EXPECT_EQ("foo.420", to<string>("foo.", A::y));
726   EXPECT_EQ("foo.65", to<string>("foo.", A::z));
727 }
728
729 TEST(Conv, IntegralToBool) {
730   EXPECT_FALSE(to<bool>(0));
731   EXPECT_FALSE(to<bool>(0ul));
732
733   EXPECT_TRUE(to<bool>(1));
734   EXPECT_TRUE(to<bool>(1ul));
735
736   EXPECT_TRUE(to<bool>(-42));
737   EXPECT_TRUE(to<bool>(42ul));
738 }
739
740 template<typename Src>
741 void testStr2Bool() {
742   EXPECT_FALSE(to<bool>(Src("0")));
743   EXPECT_FALSE(to<bool>(Src("  000  ")));
744
745   EXPECT_FALSE(to<bool>(Src("n")));
746   EXPECT_FALSE(to<bool>(Src("no")));
747   EXPECT_FALSE(to<bool>(Src("false")));
748   EXPECT_FALSE(to<bool>(Src("False")));
749   EXPECT_FALSE(to<bool>(Src("  fAlSe"  )));
750   EXPECT_FALSE(to<bool>(Src("F")));
751   EXPECT_FALSE(to<bool>(Src("off")));
752
753   EXPECT_TRUE(to<bool>(Src("1")));
754   EXPECT_TRUE(to<bool>(Src("  001 ")));
755   EXPECT_TRUE(to<bool>(Src("y")));
756   EXPECT_TRUE(to<bool>(Src("yes")));
757   EXPECT_TRUE(to<bool>(Src("\nyEs\t")));
758   EXPECT_TRUE(to<bool>(Src("true")));
759   EXPECT_TRUE(to<bool>(Src("True")));
760   EXPECT_TRUE(to<bool>(Src("T")));
761   EXPECT_TRUE(to<bool>(Src("on")));
762
763   EXPECT_THROW(to<bool>(Src("")), std::range_error);
764   EXPECT_THROW(to<bool>(Src("2")), std::range_error);
765   EXPECT_THROW(to<bool>(Src("11")), std::range_error);
766   EXPECT_THROW(to<bool>(Src("19")), std::range_error);
767   EXPECT_THROW(to<bool>(Src("o")), std::range_error);
768   EXPECT_THROW(to<bool>(Src("fal")), std::range_error);
769   EXPECT_THROW(to<bool>(Src("tru")), std::range_error);
770   EXPECT_THROW(to<bool>(Src("ye")), std::range_error);
771   EXPECT_THROW(to<bool>(Src("yes foo")), std::range_error);
772   EXPECT_THROW(to<bool>(Src("bar no")), std::range_error);
773   EXPECT_THROW(to<bool>(Src("one")), std::range_error);
774   EXPECT_THROW(to<bool>(Src("true_")), std::range_error);
775   EXPECT_THROW(to<bool>(Src("bogus_token_that_is_too_long")),
776                std::range_error);
777 }
778
779 TEST(Conv, StringToBool) {
780   // testStr2Bool<const char *>();
781   testStr2Bool<std::string>();
782
783   // Test with strings that are not NUL terminated.
784   const char buf[] = "01234";
785   EXPECT_FALSE(to<bool>(StringPiece(buf, buf + 1)));  // "0"
786   EXPECT_TRUE(to<bool>(StringPiece(buf + 1, buf + 2)));  // "1"
787   const char buf2[] = "one two three";
788   EXPECT_TRUE(to<bool>(StringPiece(buf2, buf2 + 2)));  // "on"
789   const char buf3[] = "false";
790   EXPECT_THROW(to<bool>(StringPiece(buf3, buf3 + 3)),  // "fal"
791                std::range_error);
792
793   // Test the StringPiece* API
794   const char buf4[] = "001foo";
795   StringPiece sp4(buf4);
796   EXPECT_TRUE(to<bool>(&sp4));
797   EXPECT_EQ(buf4 + 3, sp4.begin());
798   const char buf5[] = "0012";
799   StringPiece sp5(buf5);
800   EXPECT_THROW(to<bool>(&sp5), std::range_error);
801   EXPECT_EQ(buf5, sp5.begin());
802 }
803
804 TEST(Conv, FloatToInt) {
805   EXPECT_EQ(to<int>(42.0f), 42);
806   EXPECT_EQ(to<int8_t>(-128.0f), int8_t(-128));
807   EXPECT_THROW(to<int8_t>(-129.0), std::range_error);
808   EXPECT_THROW(to<int8_t>(127.001), std::range_error);
809   EXPECT_THROW(to<uint8_t>(-0.0001), std::range_error);
810   EXPECT_THROW(
811       to<uint64_t>(static_cast<float>(std::numeric_limits<uint64_t>::max())),
812       std::range_error);
813 }
814
815 TEST(Conv, IntToFloat) {
816   EXPECT_EQ(to<float>(42ULL), 42.0);
817   EXPECT_EQ(to<float>(int8_t(-128)), -128.0);
818   EXPECT_THROW(
819       to<float>(std::numeric_limits<uint64_t>::max()), std::range_error);
820   EXPECT_THROW(
821       to<float>(std::numeric_limits<int64_t>::max()), std::range_error);
822   EXPECT_THROW(
823       to<float>(std::numeric_limits<int64_t>::min() + 1), std::range_error);
824 #if FOLLY_HAVE_INT128_T
825   EXPECT_THROW(
826       to<double>(std::numeric_limits<unsigned __int128>::max()),
827       std::range_error);
828   EXPECT_THROW(
829       to<double>(std::numeric_limits<__int128>::max()), std::range_error);
830   EXPECT_THROW(
831       to<double>(std::numeric_limits<__int128>::min() + 1), std::range_error);
832 #endif
833 }
834
835 TEST(Conv, BoolToFloat) {
836   EXPECT_EQ(to<double>(true), 1.0);
837   EXPECT_EQ(to<double>(false), 0.0);
838 }
839
840 TEST(Conv, FloatToBool) {
841   EXPECT_EQ(to<bool>(1.0), true);
842   EXPECT_EQ(to<bool>(0.0), false);
843   EXPECT_EQ(to<bool>(2.7), true);
844   EXPECT_EQ(to<bool>(std::numeric_limits<double>::max()), true);
845   EXPECT_EQ(to<bool>(std::numeric_limits<double>::min()), true);
846   EXPECT_EQ(to<bool>(std::numeric_limits<double>::lowest()), true);
847   EXPECT_EQ(to<bool>(std::numeric_limits<double>::quiet_NaN()), true);
848   EXPECT_EQ(to<bool>(std::numeric_limits<double>::infinity()), true);
849   EXPECT_EQ(to<bool>(-std::numeric_limits<double>::infinity()), true);
850 }
851
852 TEST(Conv, NewUint64ToString) {
853   char buf[21];
854
855 #define THE_GREAT_EXPECTATIONS(n, len)                  \
856   do {                                                  \
857     EXPECT_EQ((len), uint64ToBufferUnsafe((n), buf));   \
858     buf[(len)] = 0;                                     \
859     auto s = string(#n);                                \
860     s = s.substr(0, s.size() - 2);                      \
861     EXPECT_EQ(s, buf);                                  \
862   } while (0)
863
864   THE_GREAT_EXPECTATIONS(0UL, 1);
865   THE_GREAT_EXPECTATIONS(1UL, 1);
866   THE_GREAT_EXPECTATIONS(12UL, 2);
867   THE_GREAT_EXPECTATIONS(123UL, 3);
868   THE_GREAT_EXPECTATIONS(1234UL, 4);
869   THE_GREAT_EXPECTATIONS(12345UL, 5);
870   THE_GREAT_EXPECTATIONS(123456UL, 6);
871   THE_GREAT_EXPECTATIONS(1234567UL, 7);
872   THE_GREAT_EXPECTATIONS(12345678UL, 8);
873   THE_GREAT_EXPECTATIONS(123456789UL, 9);
874   THE_GREAT_EXPECTATIONS(1234567890UL, 10);
875   THE_GREAT_EXPECTATIONS(12345678901UL, 11);
876   THE_GREAT_EXPECTATIONS(123456789012UL, 12);
877   THE_GREAT_EXPECTATIONS(1234567890123UL, 13);
878   THE_GREAT_EXPECTATIONS(12345678901234UL, 14);
879   THE_GREAT_EXPECTATIONS(123456789012345UL, 15);
880   THE_GREAT_EXPECTATIONS(1234567890123456UL, 16);
881   THE_GREAT_EXPECTATIONS(12345678901234567UL, 17);
882   THE_GREAT_EXPECTATIONS(123456789012345678UL, 18);
883   THE_GREAT_EXPECTATIONS(1234567890123456789UL, 19);
884   THE_GREAT_EXPECTATIONS(18446744073709551614UL, 20);
885   THE_GREAT_EXPECTATIONS(18446744073709551615UL, 20);
886
887 #undef THE_GREAT_EXPECTATIONS
888 }
889
890 TEST(Conv, allocate_size) {
891   std::string str1 = "meh meh meh";
892   std::string str2 = "zdech zdech zdech";
893
894   auto res1 = folly::to<std::string>(str1, ".", str2);
895   EXPECT_EQ(res1, str1 + "." + str2);
896
897   std::string res2; //empty
898   toAppendFit(str1, str2, 1, &res2);
899   EXPECT_EQ(res2, str1 + str2 + "1");
900
901   std::string res3;
902   toAppendDelimFit(",", str1, str2, &res3);
903   EXPECT_EQ(res3, str1 + "," + str2);
904 }
905
906 namespace my {
907 struct Dimensions {
908   int w, h;
909   std::tuple<const int&, const int&> tuple_view() const {
910     return tie(w, h);
911   }
912   bool operator==(const Dimensions& other) const {
913     return this->tuple_view() == other.tuple_view();
914   }
915 };
916
917 void parseTo(folly::StringPiece in, Dimensions& out) {
918   out.w = folly::to<int>(&in);
919   in.removePrefix("x");
920   out.h = folly::to<int>(&in);
921 }
922
923 template <class String>
924 void toAppend(const Dimensions& in, String* result) {
925   folly::toAppend(in.w, 'x', in.h, result);
926 }
927
928 size_t estimateSpaceNeeded(const Dimensions&in) {
929   return 2000 + folly::estimateSpaceNeeded(in.w) +
930       folly::estimateSpaceNeeded(in.h);
931 }
932 }
933
934 TEST(Conv, custom_kkproviders) {
935   my::Dimensions expected{7, 8};
936   EXPECT_EQ(expected, folly::to<my::Dimensions>("7x8"));
937   auto str = folly::to<std::string>(expected);
938   EXPECT_EQ("7x8", str);
939   // make sure above implementation of estimateSpaceNeeded() is used.
940   EXPECT_GT(str.capacity(), 2000);
941   EXPECT_LT(str.capacity(), 2500);
942 }