From a6b74370bc21cf4eaace4b96382d61cae77c4b74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dr=2E=20Patrick=20Urbanke=20=28=E5=8A=89=E8=87=AA=E6=88=90?= =?UTF-8?q?=29?= Date: Tue, 5 Aug 2025 22:11:12 +0200 Subject: [PATCH] Make sure that rfl::Underlying enum behaves as expected; fixes #463 (#476) --- include/rfl/parsing/Parser_default.hpp | 8 +++-- .../test_snake_case_to_pascal_case.cpp | 2 +- tests/json/test_enum_underlying.cpp | 29 +++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 tests/json/test_enum_underlying.cpp diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index bc98ac3a..700cdf0a 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -20,6 +20,7 @@ #include "../internal/processed_t.hpp" #include "../internal/ptr_cast.hpp" #include "../internal/to_ptr_named_tuple.hpp" +#include "../thirdparty/enchantum/enchantum.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" #include "Parent.hpp" @@ -86,8 +87,11 @@ struct Parser { } else if constexpr (std::is_enum_v) { if constexpr (ProcessorsType::underlying_enums_ || schemaful::IsSchemafulReader) { - return static_cast( - *_r.template to_basic_type>(_var)); + static_assert(enchantum::ScopedEnum, + "The enum must be a scoped enum in order to retrieve " + "the underlying value."); + return _r.template to_basic_type>(_var) + .transform([](const auto _val) { return static_cast(_val); }); } else { return _r.template to_basic_type(_var).and_then( rfl::string_to_enum); diff --git a/tests/generic/test_snake_case_to_pascal_case.cpp b/tests/generic/test_snake_case_to_pascal_case.cpp index c709445c..dfa17ea3 100644 --- a/tests/generic/test_snake_case_to_pascal_case.cpp +++ b/tests/generic/test_snake_case_to_pascal_case.cpp @@ -13,7 +13,7 @@ struct Person { std::vector children; }; -TEST(bson, test_snake_case_to_pascal_case) { +TEST(generic, test_snake_case_to_pascal_case) { const auto bart = Person{ .first_name = "Bart", .last_name = "Simpson", .birthday = "1987-04-19"}; diff --git a/tests/json/test_enum_underlying.cpp b/tests/json/test_enum_underlying.cpp new file mode 100644 index 00000000..82605636 --- /dev/null +++ b/tests/json/test_enum_underlying.cpp @@ -0,0 +1,29 @@ +#include + +#include + +namespace test_enum_underlying { + +enum class CameraSource : uint32_t { kWide, kInfrared, kZoom }; + +struct ChangeCameraSourcePayload { + CameraSource source; +}; + +constexpr const char* payloads[2] = {R"({"source":20})", + R"({"source":"hello"})"}; + +TEST(json, test_enum_underlying) { + const auto res1 = static_cast( + rfl::json::read( + payloads[0]) + .value() + .source); + const auto res2 = + rfl::json::read(payloads[1]); + + EXPECT_EQ(res1, 20); + EXPECT_TRUE(!res2); // should not succeed +} + +} // namespace test_enum_underlying