From 539c1350789f3462e917a691e316efba7600d0b2 Mon Sep 17 00:00:00 2001 From: npwoods Date: Thu, 14 Apr 2022 03:38:39 -0400 Subject: 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() --- src/lib/formats/fsmeta.cpp | 49 +++++++++++++++++++++++++++++++--------------- src/lib/formats/fsmeta.h | 1 + 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/lib/formats/fsmeta.cpp b/src/lib/formats/fsmeta.cpp index 9c7143301ce..681d644f18e 100644 --- a/src/lib/formats/fsmeta.cpp +++ b/src/lib/formats/fsmeta.cpp @@ -7,6 +7,8 @@ #include "strformat.h" +#include + 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 struct overloaded : Ts... { using Ts::operator()...; }; +template overloaded(Ts...)->overloaded; + +meta_type meta_value::type() const +{ + std::optional 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) + switch (type()) { - using T = std::decay_t; - if constexpr (std::is_same_v) - { - result = as_string(); - } - else if constexpr (std::is_same_v) - { - result = util::string_format("0x%x", as_number()); - } - else if constexpr (std::is_same_v) - { - result = as_flag() ? "t" : "f"; - } - else if constexpr (std::is_same_v) + case meta_type::string: + result = as_string(); + break; + case meta_type::number: + result = util::string_format("0x%x", as_number()); + break; + case meta_type::flag: + result = as_flag() ? "t" : "f"; + 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; } diff --git a/src/lib/formats/fsmeta.h b/src/lib/formats/fsmeta.h index 01cc30eb7d7..84498ea8e1e 100644 --- a/src/lib/formats/fsmeta.h +++ b/src/lib/formats/fsmeta.h @@ -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); -- cgit v1.2.3