Make Enum Helper parse functions constexpr, added Enum Helper Try Parse functions.
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2020-02-13 13:19:59 +01:00
parent 0ef909cf55
commit 02aa6f252e
2 changed files with 57 additions and 8 deletions

View File

@@ -1,5 +1,5 @@
#include <algorithm>
#include <string>
#include <sstream>
#include <vector>
#include "Exceptions/NotReachableException.hpp"
#include "MacroUtils.hpp"
@@ -12,10 +12,20 @@
case ConstHash(#x): \
return name::x;
#
#define ENUM_TRY_PARSE_CASE(x, name) \
case ConstHash(#x): \
out = name::x; \
return true;
#
#define ENUM_PARSE_CASE_INSENSITIVE(x, name) \
case ConstHashCI(#x): \
return name::x;
#
#define ENUM_TRY_PARSE_CASE_INSENSITIVE(x, name) \
case ConstHashCI(#x): \
out = name::x; \
return true;
#
#define ARRAY_NAME(x, name) name::x,
#define ENUM(name, type, values...) \
@@ -33,21 +43,31 @@
} \
\
public: \
static std::string ToString(name value) { \
constexpr static const char* ToString(name value) { \
switch (value) { FOR_EACH(ENUM_CASE, name, values) } \
throw NotReachableException(); \
} \
static name Parse(const std::string& input, bool caseInsensitive = false) { \
constexpr static name Parse(const char* input, bool caseInsensitive = false) { \
if (caseInsensitive) \
return ParseCaseInsensitive(input); \
switch (ConstHash(input.c_str())) { FOR_EACH(ENUM_PARSE_CASE, name, values) } \
throw CreatureException("String '" + input + "' could not be parsed as " #name); \
switch (ConstHash(input)) { FOR_EACH(ENUM_PARSE_CASE, name, values) } \
throw CreatureException("Invalid AttackCategory string."); \
} \
constexpr static bool TryParse(const char* input, name& out, bool caseInsensitive = false) { \
if (caseInsensitive) \
return TryParseCaseInsensitive(input, out); \
switch (ConstHash(input)) { FOR_EACH(ENUM_TRY_PARSE_CASE, name, values) } \
return false; \
} \
static std::vector<name> GetValues() { return {FOR_EACH(ARRAY_NAME, name, values)}; } \
\
private: \
static name ParseCaseInsensitive(const std::string& input) { \
switch (ConstHashCI(input.c_str())) { FOR_EACH(ENUM_PARSE_CASE_INSENSITIVE, name, values) } \
throw CreatureException("String '" + input + "' could not be parsed as " #name); \
static name ParseCaseInsensitive(const char* input) { \
switch (ConstHashCI(input)) { FOR_EACH(ENUM_PARSE_CASE_INSENSITIVE, name, values) } \
throw CreatureException("Invalid AttackCategory string."); \
} \
static bool TryParseCaseInsensitive(const char* input, name& out) { \
switch (ConstHashCI(input)) { FOR_EACH(ENUM_TRY_PARSE_CASE_INSENSITIVE, name, values) } \
return false; \
} \
};