Skip to content

Commit

Permalink
adding ability to predeclare enum serialization with nlohmann json
Browse files Browse the repository at this point in the history
  • Loading branch information
mtao committed Nov 23, 2024
1 parent 1c4baaf commit 266927b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
6 changes: 6 additions & 0 deletions components/utils/wmtk/components/utils/json_macros.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)\
Expand All @@ -22,3 +27,4 @@
{ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }



25 changes: 25 additions & 0 deletions components/utils/wmtk/components/utils/json_serialize_enum.hpp
Original file line number Diff line number Diff line change
@@ -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<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
static const std::pair<ENUM_TYPE, nlohmann::json> m[] = __VA_ARGS__; \
auto it = std::find_if(std::begin(m), std::end(m), \
[e](const std::pair<ENUM_TYPE, nlohmann::json>& 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<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
static const std::pair<ENUM_TYPE, nlohmann::json> m[] = __VA_ARGS__; \
auto it = std::find_if(std::begin(m), std::end(m), \
[&j](const std::pair<ENUM_TYPE, nlohmann::json>& ej_pair) -> bool \
{ \
return ej_pair.second == j; \
}); \
e = ((it != std::end(m)) ? it : std::begin(m))->first; \
}

0 comments on commit 266927b

Please sign in to comment.