1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef _LIBCPP___ALGORITHM_LOWER_BOUND_H 10 #define _LIBCPP___ALGORITHM_LOWER_BOUND_H 11 12 #include <__algorithm/comp.h> 13 #include <__algorithm/half_positive.h> 14 #include <__config> 15 #include <__functional/identity.h> 16 #include <__type_traits/is_callable.h> 17 #include <iterator> 18 19 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) 20 # pragma GCC system_header 21 #endif 22 23 _LIBCPP_BEGIN_NAMESPACE_STD 24 25 template <class _Iter, class _Sent, class _Type, class _Proj, class _Comp> 26 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 27 _Iter __lower_bound_impl(_Iter __first, _Sent __last, const _Type& __value, _Comp& __comp, _Proj& __proj) { 28 auto __len = std::__ranges_distance(__first, __last); 29 30 while (__len != 0) { 31 auto __l2 = std::__half_positive(__len); 32 _Iter __m = __first; 33 std::__ranges_advance(__m, __l2); 34 if (std::__invoke(__comp, std::__invoke(__proj, *__m), __value)) { 35 __first = ++__m; 36 __len -= __l2 + 1; 37 } else { 38 __len = __l2; 39 } 40 } 41 return __first; 42 } 43 44 template <class _ForwardIterator, class _Tp, class _Compare> 45 _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 46 _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) { 47 static_assert(__is_callable<_Compare, decltype(*__first), const _Tp&>::value, 48 "The comparator has to be callable"); 49 auto __proj = std::__identity(); 50 return std::__lower_bound_impl(__first, __last, __value_, __comp, __proj); 51 } 52 53 template <class _ForwardIterator, class _Tp> 54 _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 55 _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) { 56 return std::lower_bound(__first, __last, __value_, 57 __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>()); 58 } 59 60 _LIBCPP_END_NAMESPACE_STD 61 62 #endif // _LIBCPP___ALGORITHM_LOWER_BOUND_H 63