packages.biu: yaml support enum

This commit is contained in:
2024-12-04 14:10:19 +08:00
parent 78b5bc8504
commit 454792d0c0
3 changed files with 22 additions and 0 deletions

View File

@@ -34,6 +34,11 @@ namespace YAML
static Node encode(const Set&);
static bool decode(const Node& node, Set&);
};
template <biu::Enumerable Enum> struct convert<Enum>
{
static Node encode(const Enum&);
static bool decode(const Node& node, Enum&);
};
template <typename T> struct convert
{
static Node encode(const T&);

View File

@@ -5,6 +5,8 @@
# include <biu/eigen.hpp>
# include <boost/pfr.hpp>
# include <boost/pfr/core_name.hpp>
# include <nameof.hpp>
# include <magic_enum.hpp>
namespace YAML
{
@@ -76,6 +78,16 @@ namespace YAML
set = vec | ranges::to<Set>;
return true;
}
template <biu::Enumerable Enum> Node convert<Enum>::encode(const Enum& e)
{ return convert<std::string_view>::encode(nameof::nameof_enum(e)); }
template <biu::Enumerable Enum> bool convert<Enum>::decode(const Node& node, Enum& e)
{
std::string name;
if (!convert<std::string>::decode(node, name)) return false;
auto optional_value = magic_enum::enum_cast<Enum>(name);
if (!optional_value) return false;
else { e = *optional_value; return true; }
}
template <typename T> Node convert<T>::encode(const T& t)
{
YAML::Node node;

View File

@@ -41,4 +41,9 @@ d: null
auto e = node["c"].as<std::set<int>>();
assert((e == std::set<int>{1, 2}));
node["c"] = e;
std::string data2 = R"(
a: AAA
)";
enum class E { AAA, BBB, CCC };
auto f = YAML::Load(data2)["a"].as<E>();
}