Make sure that rfl::Underlying enum behaves as expected; fixes #463 (#476)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-08-05 22:11:12 +02:00
committed by GitHub
parent 93e41778ca
commit a6b74370bc
3 changed files with 36 additions and 3 deletions
+6 -2
View File
@@ -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<T>) {
if constexpr (ProcessorsType::underlying_enums_ ||
schemaful::IsSchemafulReader<R>) {
return static_cast<T>(
*_r.template to_basic_type<std::underlying_type_t<T>>(_var));
static_assert(enchantum::ScopedEnum<T>,
"The enum must be a scoped enum in order to retrieve "
"the underlying value.");
return _r.template to_basic_type<std::underlying_type_t<T>>(_var)
.transform([](const auto _val) { return static_cast<T>(_val); });
} else {
return _r.template to_basic_type<std::string>(_var).and_then(
rfl::string_to_enum<T>);
@@ -13,7 +13,7 @@ struct Person {
std::vector<Person> 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"};
+29
View File
@@ -0,0 +1,29 @@
#include <gtest/gtest.h>
#include <rfl/json.hpp>
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<int>(
rfl::json::read<ChangeCameraSourcePayload, rfl::UnderlyingEnums>(
payloads[0])
.value()
.source);
const auto res2 =
rfl::json::read<CameraSource, rfl::UnderlyingEnums>(payloads[1]);
EXPECT_EQ(res1, 20);
EXPECT_TRUE(!res2); // should not succeed
}
} // namespace test_enum_underlying