From: Marc Horowitz Date: Mon, 21 Sep 2015 16:42:44 +0000 (-0700) Subject: make to skip range check X-Git-Tag: deprecate-dynamic-initializer~387 X-Git-Url: http://plrg.eecs.uci.edu/git/?a=commitdiff_plain;h=be90fbfb2424ba27822e9055283896cefc9eafd2;p=folly.git make to skip range check Summary: to(42) should return true, not throw an exception. Reviewed By: @yfeldblum Differential Revision: D2459766 --- diff --git a/folly/Conv.h b/folly/Conv.h index 113a1495..7ccedcff 100644 --- a/folly/Conv.h +++ b/folly/Conv.h @@ -86,6 +86,21 @@ to(Src && value) { * Integral to integral ******************************************************************************/ +/** + * Unchecked conversion from integral to boolean. This is different from the + * other integral conversions because we use the C convention of treating any + * non-zero value as true, instead of range checking. + */ +template +typename std::enable_if< + std::is_integral::value + && !std::is_same::value + && std::is_same::value, + Tgt>::type +to(const Src & value) { + return value != 0; +} + /** * Checked conversion from integral to integral. The checks are only * performed when meaningful, e.g. conversion from int to long goes @@ -94,8 +109,9 @@ to(Src && value) { template typename std::enable_if< std::is_integral::value - && std::is_integral::value - && !std::is_same::value, + && !std::is_same::value + && !std::is_same::value + && std::is_integral::value, Tgt>::type to(const Src & value) { /* static */ if (std::numeric_limits::max() diff --git a/folly/test/ConvTest.cpp b/folly/test/ConvTest.cpp index 189c96bd..625a651d 100644 --- a/folly/test/ConvTest.cpp +++ b/folly/test/ConvTest.cpp @@ -90,6 +90,9 @@ TEST(Conv, digits10) { // Test to(T) TEST(Conv, Type2Type) { + bool boolV = true; + EXPECT_EQ(to(boolV), true); + int intV = 42; EXPECT_EQ(to(intV), 42); @@ -109,6 +112,7 @@ TEST(Conv, Type2Type) { EXPECT_EQ(to(spV), "StringPiece"); // Rvalues + EXPECT_EQ(to(true), true); EXPECT_EQ(to(42), 42); EXPECT_EQ(to(4.2f), 4.2f); EXPECT_EQ(to(.42), .42); @@ -725,6 +729,17 @@ TEST(Conv, EnumClassToString) { EXPECT_EQ("foo.65", to("foo.", A::z)); } +TEST(Conv, IntegralToBool) { + EXPECT_FALSE(to(0)); + EXPECT_FALSE(to(0ul)); + + EXPECT_TRUE(to(1)); + EXPECT_TRUE(to(1ul)); + + EXPECT_TRUE(to(-42)); + EXPECT_TRUE(to(42ul)); +} + template void testStr2Bool() { EXPECT_FALSE(to(Src("0"))); diff --git a/folly/test/JsonTest.cpp b/folly/test/JsonTest.cpp index c54b0b54..8b5964f6 100644 --- a/folly/test/JsonTest.cpp +++ b/folly/test/JsonTest.cpp @@ -150,6 +150,10 @@ TEST(Json, ParseTrailingComma) { EXPECT_THROW(parseJson("{\"a\":1,}", off), std::runtime_error); } +TEST(Json, BoolConversion) { + EXPECT_TRUE(parseJson("42").asBool()); +} + TEST(Json, JavascriptSafe) { auto badDouble = (1ll << 63ll) + 1; dynamic badDyn = badDouble;