@@ -2617,6 +2617,45 @@ JSON_HEDLEY_DIAGNOSTIC_POP
26172617 e = ((it != std::end(m)) ? it : std::begin(m))->first; \
26182618 }
26192619
2620+ /*!
2621+ @brief macro to briefly define a mapping between an enum and JSON with exception
2622+ on invalid input
2623+ @def NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
2624+ @since version 3.12.0
2625+ */
2626+ #define NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(ENUM_TYPE, ...) \
2627+ template<typename BasicJsonType> \
2628+ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
2629+ { \
2630+ /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \
2631+ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
2632+ /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on <array> */ \
2633+ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
2634+ auto it = std::find_if(std::begin(m), std::end(m), \
2635+ [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
2636+ { \
2637+ return ej_pair.first == e; \
2638+ }); \
2639+ if (it != std::end(m)) j = it->second; \
2640+ else throw nlohmann::detail::out_of_range::create(403, "enum value out of range", nullptr);\
2641+ } \
2642+ template<typename BasicJsonType> \
2643+ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
2644+ { \
2645+ /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \
2646+ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
2647+ /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on <array> */ \
2648+ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
2649+ auto it = std::find_if(std::begin(m), std::end(m), \
2650+ [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
2651+ { \
2652+ return ej_pair.second == j; \
2653+ }); \
2654+ if (it != std::end(m)) e = it->first; \
2655+ else throw nlohmann::detail::out_of_range::create(403, "enum value out of range", nullptr);\
2656+ }
2657+
2658+
26202659// Ugly macros to avoid uglier copy-paste when specializing basic_json. They
26212660// may be removed in the future once the class is split.
26222661
0 commit comments