Debian Codegraph @

Source/Core/Common/EnumFormatter.h

raw symbols SCIP
1 // Copyright 2021 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include "Common/EnumMap.h"
7
8 #include <fmt/format.h>
9 #include <type_traits>
10
11 /*
12 * Helper for using enums with fmt.
13 *
14 * Usage example:
15 *
16 * enum class Foo
17 * {
18 * A = 0,
19 * B = 1,
20 * C = 2,
21 * };
22 *
23 * template <>
24 * struct fmt::formatter<Foo> : EnumFormatter<Foo::C>
25 * {
26 * constexpr formatter() : EnumFormatter({"A", "B", "C"}) {}
27 * };
28 *
29 * enum class Bar
30 * {
31 * D = 0,
32 * E = 1,
33 * F = 3,
34 * };
35 *
36 * template <>
37 * struct fmt::formatter<Bar> : EnumFormatter<Bar::F>
38 * {
39 * // using std::array here fails due to nullptr not being const char*, at least in MSVC
40 * // (but only when a field is used; directly in the constructor is OK)
41 * static constexpr array_type names = {"D", "E", nullptr, "F"};
42 * constexpr formatter() : EnumFormatter(names) {}
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 // 'u' for user display, 's' for shader generation, 'n' for name only
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); // Possibly signed
64 const auto value_u = static_cast<std::make_unsigned_t<T>>(value_s); // Always unsigned
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 // This is needed because std::array deduces incorrectly if nullptr is included in the list
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 };