2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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>
26 using namespace folly;
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()));
43 TEST(Conv, digits10) {
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));
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));
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));
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));
92 TEST(Conv, Type2Type) {
94 EXPECT_EQ(to<int>(intV), 42);
97 EXPECT_EQ(to<float>(floatV), 4.2f);
99 double doubleV = 0.42;
100 EXPECT_EQ(to<double>(doubleV), 0.42);
102 std::string stringV = "StdString";
103 EXPECT_EQ(to<std::string>(stringV), "StdString");
105 folly::fbstring fbStrV = "FBString";
106 EXPECT_EQ(to<folly::fbstring>(fbStrV), "FBString");
108 folly::StringPiece spV("StringPiece");
109 EXPECT_EQ(to<folly::StringPiece>(spV), "StringPiece");
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")),
121 TEST(Conv, Integral2Integral) {
122 // Same size, different signs
123 s64 = numeric_limits<uint8_t>::max();
124 EXPECT_EQ(to<uint8_t>(s64), s64);
126 s64 = numeric_limits<int8_t>::max();
127 EXPECT_EQ(to<int8_t>(s64), s64);
130 TEST(Conv, Floating2Floating) {
132 double d1 = to<double>(f1);
136 auto f2 = to<float>(d2);
137 EXPECT_EQ(double(f2), d2);
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));
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() ||
155 template <class String>
156 void testIntegral2String() {
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;
165 EXPECT_EQ(to<String>(value), "123");
167 EXPECT_EQ(to<String>(svalue), "123");
169 EXPECT_EQ(to<String>(svalue), "-123");
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);
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);
181 testIntegral2String<String, Ints...>();
184 #if FOLLY_HAVE_INT128_T
185 template <class String>
186 void test128Bit2String() {
187 typedef unsigned __int128 Uint;
188 typedef __int128 Sint;
190 EXPECT_EQ(detail::digitsEnough<unsigned __int128>(), 39);
193 EXPECT_EQ(to<String>(value), "123");
195 EXPECT_EQ(to<String>(svalue), "123");
197 EXPECT_EQ(to<String>(svalue), "-123");
199 value = __int128(1) << 64;
200 EXPECT_EQ(to<String>(value), "18446744073709551616");
202 svalue = -(__int128(1) << 64);
203 EXPECT_EQ(to<String>(svalue), "-18446744073709551616");
206 EXPECT_EQ(to<String>(value), "0");
209 EXPECT_EQ(to<String>(svalue), "0");
211 // TODO: the following do not compile to<__int128> ...
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);
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);
228 TEST(Conv, Integral2String) {
229 testIntegral2String<std::string, char, short, int, long>();
230 testIntegral2String<fbstring, char, short, int, long>();
232 #if FOLLY_HAVE_INT128_T
233 test128Bit2String<std::string>();
234 test128Bit2String<fbstring>();
238 template <class String>
239 void testString2Integral() {
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;
247 // Unsigned numbers small enough to fit in a signed type
248 static const String strings[] = {
255 "0000000000000000000000000042"
257 static const Uint values[] = {
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]);
271 // Unsigned numbers that won't fit in the signed variation
272 static const String uStrings[] = {
277 static const Uint uValues[] = {
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);
289 if (sizeof(Int) >= 4) {
290 static const String strings2[] = {
296 static const Uint values2[] = {
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]);
307 static const String uStrings2[] = {
313 static const Uint uValues2[] = {
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);
327 if (sizeof(Int) >= 8) {
328 static_assert(sizeof(Int) <= 8, "Now that would be interesting");
329 static const String strings3[] = {
333 "100000000000000000",
334 "9223372036854775807",
336 static const Uint values3[] = {
339 (Uint)25687346509278435ULL,
340 (Uint)100000000000000000ULL,
341 (Uint)9223372036854775807ULL,
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]);
348 static const String uStrings3[] = {
349 "9223372036854775808",
350 "9987435987394857987",
351 "17873648761234698740",
352 "18446744073709551615",
354 static const Uint uValues3[] = {
355 (Uint)9223372036854775808ULL,
356 (Uint)9987435987394857987ULL,
357 (Uint)17873648761234698740ULL,
358 (Uint)18446744073709551615ULL,
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);
368 // Minimum possible negative values, and negative sign overflow
369 static const String strings4[] = {
373 "-9223372036854775808",
375 static const String strings5[] = {
379 "-9223372036854775809",
381 static const Sint values4[] = {
385 (Sint)(-9223372036854775807LL - 1),
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);
395 EXPECT_THROW(to<Sint>(strings4[i]), std::range_error);
396 EXPECT_THROW(to<Sint>(strings5[i]), std::range_error);
400 // Bogus string values
401 static const String bogusStrings[] = {
408 "- 42", // whitespace is not allowed between the sign and the value
410 "12345678901234567890123456789",
412 for (const auto& str : bogusStrings) {
413 EXPECT_THROW(to<Sint>(str), std::range_error);
414 EXPECT_THROW(to<Uint>(str), std::range_error);
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);
422 testString2Integral<String, Ints...>();
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>();
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
440 char buf2[] = "1002";
441 StringPiece sp2(buf2);
442 EXPECT_THROW(to<uint8_t>(&sp2), std::range_error);
443 EXPECT_EQ(buf2, sp2.begin());
446 TEST(Conv, StringPiece2Integral) {
447 string s = " +123 hello world ";
449 EXPECT_EQ(to<int>(&sp), 123);
450 EXPECT_EQ(sp, " hello world ");
453 TEST(Conv, StringPieceAppend) {
456 StringPiece sp(s, 0, 3);
457 string result = to<string>(s, sp);
458 EXPECT_EQ(result, "foobarfoo");
461 StringPiece sp1(s, 0, 3);
462 StringPiece sp2(s, 3, 3);
463 string result = to<string>(sp1, sp2);
464 EXPECT_EQ(result, s);
468 TEST(Conv, BadStringToIntegral) {
469 // Note that leading spaces (e.g. " 1") are valid.
470 vector<string> v = { "a", "", " ", "\n", " a0", "abcdef", "1Z", "!#" };
472 EXPECT_THROW(to<int>(s), std::range_error) << "s=" << s;
476 template <class String>
477 void testIdenticalTo() {
478 String s("Yukkuri shiteitte ne!!!");
480 String result = to<String>(s);
481 EXPECT_EQ(result, s);
484 template <class String>
485 void testVariadicTo() {
488 toAppend("Lorem ipsum ", 1234, String(" dolor amet "), 567.89, '!', &s);
489 EXPECT_EQ(s, "Lorem ipsum 1234 dolor amet 567.89!");
492 EXPECT_TRUE(s.empty());
494 s = to<String>("Lorem ipsum ", nullptr, 1234, " dolor amet ", 567.89, '.');
495 EXPECT_EQ(s, "Lorem ipsum 1234 dolor amet 567.89.");
498 template <class String>
499 void testIdenticalToDelim() {
500 String s("Yukkuri shiteitte ne!!!");
502 String charDelim = toDelim<String>('$', s);
503 EXPECT_EQ(charDelim, s);
505 String strDelim = toDelim<String>(String(">_<"), s);
506 EXPECT_EQ(strDelim, s);
509 template <class String>
510 void testVariadicToDelim() {
512 toAppendDelim(":", &s);
514 ":", "Lorem ipsum ", 1234, String(" dolor amet "), 567.89, '!', &s);
515 EXPECT_EQ(s, "Lorem ipsum :1234: dolor amet :567.89:!");
517 s = toDelim<String>(':');
518 EXPECT_TRUE(s.empty());
521 ":", "Lorem ipsum ", nullptr, 1234, " dolor amet ", 567.89, '.');
522 EXPECT_EQ(s, "Lorem ipsum ::1234: dolor amet :567.89:.");
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());
532 TEST(Conv, VariadicTo) {
533 testIdenticalTo<string>();
534 testIdenticalTo<fbstring>();
535 testVariadicTo<string>();
536 testVariadicTo<fbstring>();
539 TEST(Conv, VariadicToDelim) {
540 testIdenticalToDelim<string>();
541 testIdenticalToDelim<fbstring>();
542 testVariadicToDelim<string>();
543 testVariadicToDelim<fbstring>();
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");
554 TEST(Conv, DoubleToString) {
555 testDoubleToString<string>();
556 testDoubleToString<fbstring>();
559 TEST(Conv, FBStringToString) {
561 string ret = to<string>(foo);
562 EXPECT_EQ(ret, "foo");
563 string ret2 = to<string>(foo, 2);
564 EXPECT_EQ(ret2, "foo2");
567 TEST(Conv, StringPieceToDouble) {
568 string s = "2134123.125 zorro";
570 EXPECT_EQ(to<double>(&pc), 2134123.125);
571 EXPECT_EQ(pc, " zorro");
573 EXPECT_THROW(to<double>(StringPiece(s)), std::range_error);
574 EXPECT_EQ(to<double>(StringPiece(s.data(), pc.data())), 2134123.125);
576 // Test NaN conversion
578 to<double>("not a number");
580 } catch (const std::range_error &) {
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);
592 TEST(Conv, EmptyStringToInt) {
599 } catch (const std::range_error &) {
603 TEST(Conv, CorruptedStringToInt) {
605 StringPiece pc(s.data(), s.data() + 1); // Only "-"
610 } catch (const std::range_error &) {
614 TEST(Conv, EmptyStringToDouble) {
621 } catch (const std::range_error &) {
625 TEST(Conv, IntToDouble) {
626 auto d = to<double>(42);
628 /* This seems not work in ubuntu11.10, gcc 4.6.1
630 auto f = to<float>(957837589847);
632 } catch (std::range_error& e) {
633 //LOG(INFO) << e.what();
638 TEST(Conv, DoubleToInt) {
639 auto i = to<int>(42.0);
642 auto i = to<int>(42.1);
644 } catch (std::range_error& e) {
645 //LOG(INFO) << e.what();
649 TEST(Conv, EnumToInt) {
650 enum A { x = 42, y = 420, z = 65 };
653 auto j = to<char>(x);
656 auto i = to<char>(y);
657 LOG(ERROR) << static_cast<unsigned int>(i);
659 } catch (std::range_error& e) {
660 //LOG(INFO) << e.what();
664 TEST(Conv, EnumToString) {
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));
672 TEST(Conv, IntToEnum) {
673 enum A { x = 42, y = 420 };
679 auto i = to<A>(5000000000L);
681 } catch (std::range_error& e) {
682 //LOG(INFO) << e.what();
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);
695 auto i = to<int32_t>(x);
696 LOG(ERROR) << to<uint32_t>(x);
698 } catch (std::range_error& e) {
702 TEST(Conv, UnsignedEnumClass) {
703 enum class E : uint32_t { x = 3000000000U };
704 auto u = to<uint32_t>(E::x);
706 EXPECT_EQ(u, 3000000000U);
707 auto s = to<string>(E::x);
708 EXPECT_EQ("3000000000", s);
709 auto e = to<E>(3000000000U);
712 auto i = to<int32_t>(E::x);
713 LOG(ERROR) << to<uint32_t>(E::x);
715 } catch (std::range_error& e) {
719 // Multi-argument to<string> uses toAppend, a different code path than
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));
728 template<typename Src>
729 void testStr2Bool() {
730 EXPECT_FALSE(to<bool>(Src("0")));
731 EXPECT_FALSE(to<bool>(Src(" 000 ")));
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")));
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")));
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")),
767 TEST(Conv, StringToBool) {
768 // testStr2Bool<const char *>();
769 testStr2Bool<std::string>();
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"
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());
792 TEST(Conv, NewUint64ToString) {
795 #define THE_GREAT_EXPECTATIONS(n, len) \
797 EXPECT_EQ((len), uint64ToBufferUnsafe((n), buf)); \
799 auto s = string(#n); \
800 s = s.substr(0, s.size() - 2); \
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);
827 #undef THE_GREAT_EXPECTATIONS
830 TEST(Conv, allocate_size) {
831 std::string str1 = "meh meh meh";
832 std::string str2 = "zdech zdech zdech";
834 auto res1 = folly::to<std::string>(str1, ".", str2);
835 EXPECT_EQ(res1, str1 + "." + str2);
837 std::string res2; //empty
838 toAppendFit(str1, str2, 1, &res2);
839 EXPECT_EQ(res2, str1 + str2 + "1");
842 toAppendDelimFit(",", str1, str2, &res3);
843 EXPECT_EQ(res3, str1 + "," + str2);
846 ////////////////////////////////////////////////////////////////////////////////
847 // Benchmarks for ASCII to int conversion
848 ////////////////////////////////////////////////////////////////////////////////
849 // @author: Rajat Goel (rajat)
851 static int64_t handwrittenAtoi(const char* start, const char* end) {
853 bool positive = true;
857 throw std::runtime_error("empty string");
860 while (start < end && isspace(*start)) {
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");
881 throw std::runtime_error("extra chars at the end");
884 return positive ? retVal : -retVal;
887 static StringPiece pc1 = "1234567890123456789";
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()));
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()));
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()));
912 void clibStrtoulMeasure(unsigned int n, unsigned int digits) {
913 auto p = pc1.subpiece(pc1.size() - digits, digits);
914 assert(*p.end() == 0);
916 FOR_EACH_RANGE (i, 0, n) {
917 doNotOptimizeAway(strtoul(p.begin(), &endptr, 10));
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()));
929 // Benchmarks for unsigned to string conversion, raw
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";
944 uint32_t const length = digits10(value);
945 uint32_t next = length - 1;
946 while (value >= 100) {
947 auto const i = (value % 100) * 2;
949 dst[next] = digits[i + 1];
950 dst[next - 1] = digits[i];
953 // Handle last 1-2 digits
955 dst[next] = '0' + uint32_t(value);
957 auto i = uint32_t(value) * 2;
958 dst[next] = digits[i + 1];
959 dst[next - 1] = digits[i];
964 void u64ToAsciiTableBM(unsigned int n, uint64_t value) {
965 // This is too fast, need to do 10 times per iteration
967 FOR_EACH_RANGE (i, 0, n) {
968 doNotOptimizeAway(u64ToAsciiTable(value + n, buf));
972 unsigned u64ToAsciiClassic(uint64_t value, char* dst) {
974 char* next = (char*)dst;
977 *next++ = '0' + (value % 10);
979 } while (value != 0);
980 unsigned length = next - start;
984 while (next > start) {
994 void u64ToAsciiClassicBM(unsigned int n, uint64_t value) {
995 // This is too fast, need to do 10 times per iteration
997 FOR_EACH_RANGE (i, 0, n) {
998 doNotOptimizeAway(u64ToAsciiClassic(value + n, buf));
1002 void u64ToAsciiFollyBM(unsigned int n, uint64_t value) {
1003 // This is too fast, need to do 10 times per iteration
1005 FOR_EACH_RANGE (i, 0, n) {
1006 doNotOptimizeAway(uint64ToBufferUnsafe(value + n, buf));
1010 // Benchmark uitoa with string append
1012 void u2aAppendClassicBM(unsigned int n, uint64_t value) {
1014 FOR_EACH_RANGE (i, 0, n) {
1015 // auto buf = &s.back() + 1;
1017 s.append(buffer, u64ToAsciiClassic(value, buffer));
1018 doNotOptimizeAway(s.size());
1022 void u2aAppendFollyBM(unsigned int n, uint64_t value) {
1024 FOR_EACH_RANGE (i, 0, n) {
1025 // auto buf = &s.back() + 1;
1027 s.append(buffer, uint64ToBufferUnsafe(value, buffer));
1028 doNotOptimizeAway(s.size());
1032 template <class String>
1033 struct StringIdenticalToBM {
1034 StringIdenticalToBM() {}
1035 void operator()(unsigned int n, size_t len) const {
1037 BENCHMARK_SUSPEND { s.append(len, '0'); }
1038 FOR_EACH_RANGE (i, 0, n) {
1039 String result = to<String>(s);
1040 doNotOptimizeAway(result.size());
1045 template <class String>
1046 struct StringVariadicToBM {
1047 StringVariadicToBM() {}
1048 void operator()(unsigned int n, size_t len) const {
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());
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;
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);
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);
1083 BENCHMARK_DRAW_LINE();
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;
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();
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);
1117 #undef DEFINE_BENCHMARK_GROUP
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();
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);
1146 #undef DEFINE_BENCHMARK_GROUP
1148 #define DEFINE_BENCHMARK_GROUP(T, n) \
1149 BENCHMARK_PARAM(T ## VariadicToBM, n); \
1150 BENCHMARK_RELATIVE_PARAM(T ## IdenticalToBM, n); \
1151 BENCHMARK_DRAW_LINE();
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);
1160 #undef DEFINE_BENCHMARK_GROUP
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();