Commit 863a22ad authored by Marcelo Juchem's avatar Marcelo Juchem Committed by Facebook Github Bot 6

Adding DynamicConverter support for enums

Summary:DynamicConverter doesn't currently support reading enums.
This diff addresses that by adding an enum specialization that uses integers as its underlying implementation.
A follow-up is to handle both integers and strings, but that would require a way to parse strings into enums like Thrift static reflection provides (see https://github.com/facebook/fbthrift/blob/d17b072daddbd318f9afaa5562100eaba0f890e3/thrift/lib/cpp2/fatal/folly_dynamic-inl.h#L88,L92.

Reviewed By: yfeldblum

Differential Revision: D3002569

fb-gh-sync-id: 27bf4a9d5a7844762f5311e2c777606a0e7753f0
shipit-source-id: 27bf4a9d5a7844762f5311e2c777606a0e7753f0
parent 6a7158dc
...@@ -211,6 +211,16 @@ struct DynamicConverter<T, ...@@ -211,6 +211,16 @@ struct DynamicConverter<T,
} }
}; };
// enums
template <typename T>
struct DynamicConverter<T,
typename std::enable_if<std::is_enum<T>::value>::type> {
static T convert(const dynamic& d) {
using type = typename std::underlying_type<T>::type;
return static_cast<T>(DynamicConverter<type>::convert(d));
}
};
// floating point // floating point
template <typename T> template <typename T>
struct DynamicConverter<T, struct DynamicConverter<T,
......
...@@ -99,6 +99,28 @@ TEST(DynamicConverter, arithmetic_types) { ...@@ -99,6 +99,28 @@ TEST(DynamicConverter, arithmetic_types) {
EXPECT_EQ(i8, false); EXPECT_EQ(i8, false);
} }
TEST(DynamicConverter, enums) {
enum enum1 { foo = 1, bar = 2 };
dynamic d1 = 1;
auto i1 = convertTo<enum1>(d1);
EXPECT_EQ(i1, foo);
dynamic d2 = 2;
auto i2 = convertTo<enum1>(d2);
EXPECT_EQ(i2, bar);
enum class enum2 { FOO = 1, BAR = 2 };
dynamic d3 = 1;
auto i3 = convertTo<enum2>(d3);
EXPECT_EQ(i3, enum2::FOO);
dynamic d4 = 2;
auto i4 = convertTo<enum2>(d4);
EXPECT_EQ(i4, enum2::BAR);
}
TEST(DynamicConverter, simple_builtins) { TEST(DynamicConverter, simple_builtins) {
dynamic d1 = "Haskell"; dynamic d1 = "Haskell";
auto i1 = convertTo<folly::fbstring>(d1); auto i1 = convertTo<folly::fbstring>(d1);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment