From a42ad861f2696d8860cb44034941be2bf1e088e0 Mon Sep 17 00:00:00 2001 From: Xuehai Pan Date: Mon, 25 Mar 2024 16:35:58 +0000 Subject: [PATCH] style: move guard condition --- include/utils.h | 70 +++++++++++++++++++++++++------------------------ 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/include/utils.h b/include/utils.h index b980f496..6ed969a4 100644 --- a/include/utils.h +++ b/include/utils.h @@ -455,24 +455,25 @@ inline bool IsNamedTupleClassImpl(const py::handle& type) { return false; } inline bool IsNamedTupleClass(const py::handle& type) { - if (PyType_Check(type.ptr())) [[likely]] { - static auto cache = std::unordered_map{}; - auto it = cache.find(type); - if (it != cache.end()) [[likely]] { - return it->second; - } - bool result = IsNamedTupleClassImpl(type); - if (cache.size() < MAX_TYPE_CACHE_SIZE) [[likely]] { - cache.emplace(type, result); - (void)py::weakref(type, py::cpp_function([type](py::handle weakref) -> void { - cache.erase(type); - weakref.dec_ref(); - })) - .release(); - } - return result; + if (!PyType_Check(type.ptr())) [[unlikely]] { + return false; } - return false; + + static auto cache = std::unordered_map{}; + auto it = cache.find(type); + if (it != cache.end()) [[likely]] { + return it->second; + } + bool result = IsNamedTupleClassImpl(type); + if (cache.size() < MAX_TYPE_CACHE_SIZE) [[likely]] { + cache.emplace(type, result); + (void)py::weakref(type, py::cpp_function([type](py::handle weakref) -> void { + cache.erase(type); + weakref.dec_ref(); + })) + .release(); + } + return result; } inline bool IsNamedTupleInstance(const py::handle& object) { return IsNamedTupleClass(py::type::handle_of(object)); @@ -535,24 +536,25 @@ inline bool IsStructSequenceClassImpl(const py::handle& type) { return false; } inline bool IsStructSequenceClass(const py::handle& type) { - if (PyType_Check(type.ptr())) [[likely]] { - static auto cache = std::unordered_map{}; - auto it = cache.find(type); - if (it != cache.end()) [[likely]] { - return it->second; - } - bool result = IsStructSequenceClassImpl(type); - if (cache.size() < MAX_TYPE_CACHE_SIZE) [[likely]] { - cache.emplace(type, result); - (void)py::weakref(type, py::cpp_function([type](py::handle weakref) -> void { - cache.erase(type); - weakref.dec_ref(); - })) - .release(); - } - return result; + if (!PyType_Check(type.ptr())) [[unlikely]] { + return false; } - return false; + + static auto cache = std::unordered_map{}; + auto it = cache.find(type); + if (it != cache.end()) [[likely]] { + return it->second; + } + bool result = IsStructSequenceClassImpl(type); + if (cache.size() < MAX_TYPE_CACHE_SIZE) [[likely]] { + cache.emplace(type, result); + (void)py::weakref(type, py::cpp_function([type](py::handle weakref) -> void { + cache.erase(type); + weakref.dec_ref(); + })) + .release(); + } + return result; } inline bool IsStructSequenceInstance(const py::handle& object) { return IsStructSequenceClass(py::type::handle_of(object));