Added a 'type()' accessor to fs::meta_value (#9553)

* Added a 'type()' accessor to fs::meta_value

Let's try to hide the nastiness of std::visit() as much as humanly possible

* Changing visitor approach for std::visit() call in fs::meta_value::type()
This commit is contained in:
npwoods 2022-04-14 03:38:39 -04:00 committed by GitHub
parent e0e3cb7431
commit 539c135078
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 16 deletions

View File

@ -7,6 +7,8 @@
#include "strformat.h"
#include <optional>
namespace fs {
const char *meta_data::entry_name(meta_name name)
@ -32,33 +34,48 @@ const char *meta_data::entry_name(meta_name name)
return "";
}
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...)->overloaded<Ts...>;
meta_type meta_value::type() const
{
std::optional<meta_type> result;
std::visit(overloaded
{
[&result](const std::string &) { result = meta_type::string; },
[&result](std::uint64_t) { result = meta_type::number; },
[&result](bool) { result = meta_type::flag; },
[&result](const util::arbitrary_datetime &) { result = meta_type::date; }
}, value);
return *result;
}
std::string meta_value::to_string() const
{
std::string result;
std::visit([this, &result](auto &&arg)
{
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, std::string>)
switch (type())
{
case meta_type::string:
result = as_string();
}
else if constexpr (std::is_same_v<T, uint64_t>)
{
break;
case meta_type::number:
result = util::string_format("0x%x", as_number());
}
else if constexpr (std::is_same_v<T, bool>)
{
break;
case meta_type::flag:
result = as_flag() ? "t" : "f";
}
else if constexpr (std::is_same_v<T, util::arbitrary_datetime>)
break;
case meta_type::date:
{
auto dt = as_date();
result = util::string_format("%04d-%02d-%02d %02d:%02d:%02d",
dt.year, dt.month, dt.day_of_month,
dt.hour, dt.minute, dt.second);
}
}, value);
break;
default:
throw false;
}
return result;
}

View File

@ -47,6 +47,7 @@ enum class meta_type {
class meta_value {
public:
meta_type type() const;
std::string to_string() const;
static meta_value from_string(meta_type type, std::string value);