[libcxx-commits] [libcxx] [libc++] Optimize most of the __tree search algorithms (PR #155245)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Aug 28 08:52:28 PDT 2025


================
@@ -0,0 +1,93 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_THREE_WAY_COMPARATOR_H
+#define _LIBCPP___UTILITY_THREE_WAY_COMPARATOR_H
+
+#include <__config>
+#include <__type_traits/desugars_to.h>
+#include <__type_traits/enable_if.h>
+#include <__type_traits/is_arithmetic.h>
+#include <__type_traits/remove_const_ref.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _LHS, class _RHS, class = void>
+struct __default_three_way_comparator;
+
+template <class _Tp>
+struct __default_three_way_comparator<_Tp, _Tp, __enable_if_t<is_arithmetic<_Tp>::value> > {
+  _LIBCPP_HIDE_FROM_ABI static int operator()(_Tp __lhs, _Tp __rhs) {
+    if (__lhs < __rhs)
+      return -1;
+    if (__lhs > __rhs)
+      return 1;
+    return 0;
+  }
+};
+
+template <class _LHS, class _RHS, bool = true>
+inline const bool __has_default_three_way_comparator_v = false;
+
+template <class _LHS, class _RHS>
+inline const bool
+    __has_default_three_way_comparator_v< _LHS, _RHS, sizeof(__default_three_way_comparator<_LHS, _RHS>) >= 0> = true;
+
+template <class _Comparator, class _LHS, class _RHS>
+struct __lazy_compare_result {
+  const _Comparator& __comp_;
+  const _LHS& __lhs_;
+  const _RHS& __rhs_;
+
+  __lazy_compare_result(const _Comparator& __comp, const _LHS& __lhs, const _RHS& __rhs)
+      : __comp_(__comp), __lhs_(__lhs), __rhs_(__rhs) {}
+
+  bool __less() const { return __comp_(__lhs_, __rhs_); }
+  bool __greater() const { return __comp_(__rhs_, __lhs_); }
+};
+
+template <class _Comparator, class _LHS, class _RHS, class = void>
+struct __three_way_comparator {
+  const _Comparator& __comp_;
+
+  __three_way_comparator(const _Comparator& __comp) : __comp_(__comp) {}
+
+  __lazy_compare_result<_Comparator, _LHS, _RHS> operator()(const _LHS& __lhs, const _RHS& __rhs) const {
----------------
ldionne wrote:

Is there a way to add lifetimebound annotations here or to the constructor since we're storing a reference internally? I'm really not a huge fan of reference types like this, although I understand the need for them in this case.

https://github.com/llvm/llvm-project/pull/155245


More information about the libcxx-commits mailing list