VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
EnumNames.hpp
Go to the documentation of this file.
1#pragma once
2
3// Pin the scanned range explicitly rather than inheriting magic_enum's default: the framework's
4// enums are small and contiguous, and a wide range costs compile time in every including TU.
5// These must be set before magic_enum.hpp is first included, which is why nothing else in the
6// framework includes it directly.
7#ifndef MAGIC_ENUM_RANGE_MIN
8#define MAGIC_ENUM_RANGE_MIN 0
9#endif
10#ifndef MAGIC_ENUM_RANGE_MAX
11#define MAGIC_ENUM_RANGE_MAX 255
12#endif
13
14#include <cstddef>
15#include <magic_enum/magic_enum.hpp>
16#include <optional>
17#include <string_view>
18
19namespace VoltMod
20{
21
22/**
23 * @file EnumNames.hpp
24 * @brief Enumerator names without a hand-written switch.
25 *
26 * Every framework enum spells its enumerators the way the log and the JSON status want to read
27 * them, so the name is the compiler's copy of the identifier. A switch that maps them to strings
28 * is one more thing to forget when an enumerator is added.
29 */
30
31/** Identifier of @p value, or an empty view when it is not a declared enumerator. */
32template <class E>
33constexpr std::string_view Name(E value) noexcept
34{
35 return magic_enum::enum_name(value);
36}
37
38/**
39 * The enumerator spelled @p name, or nullopt.
40 *
41 * Case-insensitive: enumerators are PascalCase, but the text being parsed is almost always a
42 * lowercase config value ("observe", "grants"), and a case-sensitive match would send every
43 * such call back to a hand-written chain. Pair it with `value_or` to supply the fallback.
44 */
45template <class E>
46constexpr std::optional<E> Parse(std::string_view name) noexcept
47{
48 return magic_enum::enum_cast<E>(name, magic_enum::case_insensitive);
49}
50
51/** How many enumerators @p E declares. */
52template <class E>
53inline constexpr std::size_t EnumCount = magic_enum::enum_count<E>();
54
55/** Position of @p value in @p E's declaration order, for indexing a per-enumerator array. */
56template <class E>
57constexpr std::size_t EnumIndex(E value) noexcept
58{
59 return magic_enum::enum_index(value).value_or(EnumCount<E>);
60}
61
62/** Every enumerator of @p E, in declaration order. */
63template <class E>
64constexpr auto EnumValues() noexcept
65{
66 return magic_enum::enum_values<E>();
67}
68
69} // namespace VoltMod
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
constexpr std::size_t EnumIndex(E value) noexcept
Definition EnumNames.hpp:57
constexpr std::size_t EnumCount
Definition EnumNames.hpp:53
constexpr auto EnumValues() noexcept
Definition EnumNames.hpp:64
constexpr std::optional< E > Parse(std::string_view name) noexcept
Definition EnumNames.hpp:46