xref: /freebsd/contrib/llvm-project/libcxx/include/__algorithm/lower_bound.h (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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 <__algorithm/iterator_operations.h>
15 #include <__config>
16 #include <__functional/identity.h>
17 #include <__functional/invoke.h>
18 #include <__iterator/advance.h>
19 #include <__iterator/distance.h>
20 #include <__iterator/iterator_traits.h>
21 #include <__type_traits/is_callable.h>
22 #include <__type_traits/remove_reference.h>
23 #include <type_traits>
24 
25 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
26 #  pragma GCC system_header
27 #endif
28 
29 _LIBCPP_BEGIN_NAMESPACE_STD
30 
31 template <class _AlgPolicy, class _Iter, class _Sent, class _Type, class _Proj, class _Comp>
32 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
33 _Iter __lower_bound_impl(_Iter __first, _Sent __last, const _Type& __value, _Comp& __comp, _Proj& __proj) {
34   auto __len = _IterOps<_AlgPolicy>::distance(__first, __last);
35 
36   while (__len != 0) {
37     auto __l2 = std::__half_positive(__len);
38     _Iter __m = __first;
39     _IterOps<_AlgPolicy>::advance(__m, __l2);
40     if (std::__invoke(__comp, std::__invoke(__proj, *__m), __value)) {
41       __first = ++__m;
42       __len -= __l2 + 1;
43     } else {
44       __len = __l2;
45     }
46   }
47   return __first;
48 }
49 
50 template <class _ForwardIterator, class _Tp, class _Compare>
51 _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
52 _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) {
53   static_assert(__is_callable<_Compare, decltype(*__first), const _Tp&>::value,
54                 "The comparator has to be callable");
55   auto __proj = std::__identity();
56   return std::__lower_bound_impl<_ClassicAlgPolicy>(__first, __last, __value, __comp, __proj);
57 }
58 
59 template <class _ForwardIterator, class _Tp>
60 _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
61 _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) {
62   return std::lower_bound(__first, __last, __value,
63                           __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
64 }
65 
66 _LIBCPP_END_NAMESPACE_STD
67 
68 #endif // _LIBCPP___ALGORITHM_LOWER_BOUND_H
69