4#ifndef CBM_ALGO_BASE_UTIL_SERIALIZABLEENUM_H
5#define CBM_ALGO_BASE_UTIL_SERIALIZABLEENUM_H
7#include <boost/algorithm/string/predicate.hpp>
16#include <fmt/format.h>
17#include <xpu/defines.h>
24 using EnumDict_t = std::vector<std::pair<std::string_view, T>>;
36 template<
typename T,
typename = std::enable_if_t<detail::EnumHasDict_v<T>>>
39 std::vector<std::string_view> entries;
41 entries.push_back(pair.first);
46 void RaiseUnknownEntry(std::string_view str,
const std::vector<std::string_view>& validEntries);
49 template<
typename T,
typename = std::enable_if_t<detail::EnumHasDict_v<T>>>
50 std::optional<T>
FromString(std::string_view str,
bool caseSensitive =
false)
53 auto it = std::find_if(dict.begin(), dict.end(), [&](
const auto& pair) {
55 return pair.first == str;
57 return boost::iequals(pair.first, str);
59 if (it == dict.end())
return std::nullopt;
63 template<
typename T,
typename = std::enable_if_t<detail::EnumHasDict_v<T>>>
67 auto it = std::find_if(dict.begin(), dict.end(), [t](
const auto& pair) { return pair.second == t; });
68 if (it == dict.end())
throw std::runtime_error(fmt::format(
"Entry {} for enum missing!",
static_cast<int>(t)));
98#define CBM_ENUM_DICT(type, ...) \
100 inline const cbm::algo::detail::EnumDict_t<type> cbm::algo::detail::EnumDict<type> = {__VA_ARGS__}; \
102 struct cbm::algo::detail::EnumHasDict<type> : std::true_type { \
106#define CBM_ENUM_DICT(type, ...)
113 template<
typename T,
typename = std::enable_if_t<cbm::algo::detail::EnumHasDict_v<T>>>
120 template<
typename T,
typename = std::enable_if_t<cbm::algo::detail::EnumHasDict_v<T>>>
std::vector< std::pair< std::string_view, T > > EnumDict_t
void RaiseUnknownEntry(std::string_view str, const std::vector< std::string_view > &validEntries)
constexpr bool EnumHasDict_v
std::vector< std::string_view > ValidEntries()
const EnumDict_t< T > EnumDict
std::string_view ToString(T t)
std::optional< T > FromString(std::string_view str, bool caseSensitive=false)
std::ostream & operator<<(std::ostream &os, const std::vector< T > &v)
std::istream & operator>>(std::istream &is, T &t)