From f29ad727ba54d554b89f74703c95fca8aec8adf3 Mon Sep 17 00:00:00 2001 From: neargye Date: Mon, 7 Nov 2022 23:14:24 +0400 Subject: [PATCH] enum_cast optimization --- include/magic_enum.hpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/include/magic_enum.hpp b/include/magic_enum.hpp index b638156..52e4d23 100644 --- a/include/magic_enum.hpp +++ b/include/magic_enum.hpp @@ -261,7 +261,6 @@ constexpr string_view pretty_name(string_view name) noexcept { (name[0] == '_'))) { return name; } - return {}; // Invalid name. } @@ -1173,7 +1172,6 @@ template if (check_value != 0 && check_value == static_cast(value)) { return name; } - return {}; // Invalid value or out of range. } @@ -1250,12 +1248,19 @@ template static_cast(value), detail::default_result_type_lambda>); #else - for (std::size_t i = 0; i < detail::count_v; ++i) { - if (value == static_cast(enum_value(i))) { + if constexpr (detail::is_sparse_v || detail::is_flags_v) { + for (std::size_t i = 0; i < detail::count_v; ++i) { + if (value == static_cast(enum_value(i))) { + return static_cast(value); + } + } + return {}; // Invalid value or out of range. + } else { + if (value >= detail::min_v && value <= detail::max_v) { return static_cast(value); } + return {}; // Invalid value or out of range. } - return {}; // Invalid value or out of range. #endif } }