| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#include "Common/EnumMap.h" |
| 7 |
|
| 8 |
#include <fmt/format.h> |
| 9 |
#include <type_traits> |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
template <Common::Enum auto last_member> |
| 46 |
class EnumFormatter |
| 47 |
{ |
| 48 |
using T = decltype(last_member); |
| 49 |
|
| 50 |
public: |
| 51 |
constexpr auto parse(fmt::format_parse_context& ctx) |
| 52 |
{ |
| 53 |
auto it = ctx.begin(), end = ctx.end(); |
| 54 |
|
| 55 |
if (it != end && (*it == 'u' || *it == 's' || *it == 'n')) |
| 56 |
format_type = *it++; |
| 57 |
return it; |
| 58 |
} |
| 59 |
|
| 60 |
template <typename FormatContext> |
| 61 |
auto format(const T& e, FormatContext& ctx) const |
| 62 |
{ |
| 63 |
const auto value_s = static_cast<std::underlying_type_t<T>>(e); |
| 64 |
const auto value_u = static_cast<std::make_unsigned_t<T>>(value_s); |
| 65 |
const bool has_name = m_names.InBounds(e) && m_names[e] != nullptr; |
| 66 |
|
| 67 |
switch (format_type) |
| 68 |
{ |
| 69 |
default: |
| 70 |
case 'u': |
| 71 |
if (has_name) |
| 72 |
return fmt::format_to(ctx.out(), "{} ({})", m_names[e], value_s); |
| 73 |
else |
| 74 |
return fmt::format_to(ctx.out(), "Invalid ({})", value_s); |
| 75 |
case 's': |
| 76 |
if (has_name) |
| 77 |
return fmt::format_to(ctx.out(), "{:#x}u /* {} */", value_u, m_names[e]); |
| 78 |
else |
| 79 |
return fmt::format_to(ctx.out(), "{:#x}u /* Invalid */", value_u); |
| 80 |
case 'n': |
| 81 |
if (has_name) |
| 82 |
return fmt::format_to(ctx.out(), "{}", m_names[e]); |
| 83 |
else |
| 84 |
return fmt::format_to(ctx.out(), "Invalid ({})", value_s); |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
protected: |
| 89 |
|
| 90 |
using array_type = Common::EnumMap<const char*, last_member>; |
| 91 |
|
| 92 |
constexpr explicit EnumFormatter(const array_type names) : m_names(std::move(names)) {} |
| 93 |
|
| 94 |
const array_type m_names; |
| 95 |
char format_type = 'u'; |
| 96 |
}; |