From 440000edbb37468a1fa70f8120a32df2c7ef5b24 Mon Sep 17 00:00:00 2001 From: Yagiz Nizipli Date: Thu, 28 Nov 2024 13:45:26 -0500 Subject: [PATCH] src: modernize cleanup queue to use c++20 --- src/cleanup_queue-inl.h | 12 ++++++++++++ src/cleanup_queue.cc | 15 +++++---------- src/cleanup_queue.h | 2 ++ 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/cleanup_queue-inl.h b/src/cleanup_queue-inl.h index ac86d06ada7c8be..77ee3b8e6f20ccc 100644 --- a/src/cleanup_queue-inl.h +++ b/src/cleanup_queue-inl.h @@ -29,6 +29,18 @@ void CleanupQueue::Remove(Callback cb, void* arg) { cleanup_hooks_.erase(search); } +constexpr auto CleanupQueue::CleanupHookCallback::operator<=>( + const CleanupHookCallback& other) const noexcept { + if (insertion_order_counter_ > other.insertion_order_counter_) { + return std::strong_ordering::greater; + } + + if (insertion_order_counter_ < other.insertion_order_counter_) { + return std::strong_ordering::less; + } + return std::strong_ordering::equivalent; +} + } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/cleanup_queue.cc b/src/cleanup_queue.cc index 5923db6b89d4b48..0c4490340153a72 100644 --- a/src/cleanup_queue.cc +++ b/src/cleanup_queue.cc @@ -8,18 +8,13 @@ namespace node { std::vector CleanupQueue::GetOrdered() const { // Copy into a vector, since we can't sort an unordered_set in-place. - std::vector callbacks(cleanup_hooks_.begin(), - cleanup_hooks_.end()); + std::vector callbacks(cleanup_hooks_.begin(), cleanup_hooks_.end()); // We can't erase the copied elements from `cleanup_hooks_` yet, because we // need to be able to check whether they were un-scheduled by another hook. - std::sort(callbacks.begin(), - callbacks.end(), - [](const CleanupHookCallback& a, const CleanupHookCallback& b) { - // Sort in descending order so that the most recently inserted - // callbacks are run first. - return a.insertion_order_counter_ > b.insertion_order_counter_; - }); + // Sort in descending order so that the most recently inserted callbacks are + // run first. + std::ranges::sort(callbacks, std::greater()); return callbacks; } @@ -28,7 +23,7 @@ void CleanupQueue::Drain() { std::vector callbacks = GetOrdered(); for (const CleanupHookCallback& cb : callbacks) { - if (cleanup_hooks_.count(cb) == 0) { + if (!cleanup_hooks_.contains(cb)) { // This hook was removed from the `cleanup_hooks_` set during another // hook that was run earlier. Nothing to do here. continue; diff --git a/src/cleanup_queue.h b/src/cleanup_queue.h index 7edc828eb654a81..1340ec6b47fa958 100644 --- a/src/cleanup_queue.h +++ b/src/cleanup_queue.h @@ -41,6 +41,8 @@ class CleanupQueue : public MemoryRetainer { arg_(arg), insertion_order_counter_(insertion_order_counter) {} + constexpr auto operator<=>(const CleanupHookCallback& other) const noexcept; + // Only hashes `arg_`, since that is usually enough to identify the hook. struct Hash { size_t operator()(const CleanupHookCallback& cb) const;