From 266927b1153e958eb1ae8909e136417dfe17c715 Mon Sep 17 00:00:00 2001 From: Michael Tao Date: Sat, 23 Nov 2024 17:01:07 -0500 Subject: [PATCH] adding ability to predeclare enum serialization with nlohmann json --- .../wmtk/components/utils/json_macros.hpp | 6 +++++ .../components/utils/json_serialize_enum.hpp | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 components/utils/wmtk/components/utils/json_serialize_enum.hpp diff --git a/components/utils/wmtk/components/utils/json_macros.hpp b/components/utils/wmtk/components/utils/json_macros.hpp index 45725f786a..546c7db2bc 100644 --- a/components/utils/wmtk/components/utils/json_macros.hpp +++ b/components/utils/wmtk/components/utils/json_macros.hpp @@ -7,6 +7,11 @@ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t);\ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t); +// place these in the class for which serialization is desired +#define WMTK_NLOHMANN_JSON_DECLARATION(Type)\ + void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t);\ + void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t); + // place this to define the prototype of the to_json function #define WMTK_NLOHMANN_JSON_FRIEND_TO_JSON_PROTOTYPE(Type)\ @@ -22,3 +27,4 @@ { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + diff --git a/components/utils/wmtk/components/utils/json_serialize_enum.hpp b/components/utils/wmtk/components/utils/json_serialize_enum.hpp new file mode 100644 index 0000000000..ac4bf6c76f --- /dev/null +++ b/components/utils/wmtk/components/utils/json_serialize_enum.hpp @@ -0,0 +1,25 @@ +#pragma once +// copy of nlohmann's json serialize enum (include/nlohmann/detail/macro_scope.hpp), but without inlining +#define WMTK_NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + void to_json(nlohmann::json& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + void from_json(const nlohmann::json& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + }