Skip to content

Commit 397dcb0

Browse files
committed
refactor GetNamespace to enhance readability and handle missing keys gracefully
1 parent 9abeb45 commit 397dcb0

1 file changed

Lines changed: 17 additions & 14 deletions

File tree

modules/core/util/include/util.hpp

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -50,24 +50,27 @@ int GetNumThreads();
5050

5151
template <typename T>
5252
constexpr std::string_view GetNamespace() {
53-
#if defined(_MSC_VER)
54-
constexpr std::string_view func{__FUNCSIG__};
55-
auto start = func.find("GetNamespace<") + 13;
56-
for (auto p : {"class ", "struct ", "enum ", "union "})
57-
if (func.substr(start).starts_with(p)) {
58-
start += std::string_view{p}.size();
59-
break;
60-
}
53+
#ifdef _MSC_VER
54+
constexpr std::string_view kFunc{__FUNCSIG__};
55+
constexpr std::string_view key = "GetNamespace<";
6156
#else
62-
constexpr std::string_view func{__PRETTY_FUNCTION__};
63-
auto start = func.find("T = ") + 4;
57+
constexpr std::string_view kFunc{__PRETTY_FUNCTION__};
58+
constexpr std::string_view key = "T = ";
6459
#endif
65-
auto end = func.find_first_of(";]> ,>", start);
66-
auto ns = func.substr(start, end - start);
67-
auto pos = ns.rfind("::");
68-
return (pos != std::string_view::npos) ? ns.substr(0, pos) : std::string_view{};
60+
61+
auto start = kFunc.find(key);
62+
if (start == std::string_view::npos) return {};
63+
start += key.size();
64+
65+
for (auto p : {"class ", "struct ", "enum ", "union "})
66+
if (kFunc.substr(start).starts_with(p)) start += std::string_view{p}.size();
67+
68+
auto ns_type = kFunc.substr(start, kFunc.find(']', start) - start);
69+
auto pos = ns_type.rfind("::");
70+
return (pos != std::string_view::npos) ? ns_type.substr(0, pos) : std::string_view{};
6971
}
7072

73+
7174
inline std::shared_ptr<nlohmann::json> InitJSONPtr() { return std::make_shared<nlohmann::json>(); }
7275

7376
bool IsUnderMpirun();

0 commit comments

Comments
 (0)