xref: /llvm-project/libcxx/include/__algorithm/ranges_minmax.h (revision d4ffccfce103b01401b8a9222e373f2d404f8439)
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_RANGES_MINMAX_H
10 #define _LIBCPP___ALGORITHM_RANGES_MINMAX_H
11 
12 #include <__algorithm/min_max_result.h>
13 #include <__algorithm/minmax_element.h>
14 #include <__assert>
15 #include <__concepts/copyable.h>
16 #include <__concepts/same_as.h>
17 #include <__config>
18 #include <__functional/identity.h>
19 #include <__functional/invoke.h>
20 #include <__functional/ranges_operations.h>
21 #include <__iterator/concepts.h>
22 #include <__iterator/next.h>
23 #include <__iterator/projected.h>
24 #include <__ranges/access.h>
25 #include <__ranges/concepts.h>
26 #include <__type_traits/desugars_to.h>
27 #include <__type_traits/is_reference.h>
28 #include <__type_traits/is_trivially_copyable.h>
29 #include <__type_traits/remove_cvref.h>
30 #include <__utility/forward.h>
31 #include <__utility/move.h>
32 #include <__utility/pair.h>
33 #include <initializer_list>
34 
35 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
36 #  pragma GCC system_header
37 #endif
38 
39 #if _LIBCPP_STD_VER >= 20
40 
41 _LIBCPP_PUSH_MACROS
42 #  include <__undef_macros>
43 
44 _LIBCPP_BEGIN_NAMESPACE_STD
45 
46 namespace ranges {
47 template <class _T1>
48 using minmax_result = min_max_result<_T1>;
49 
50 struct __minmax {
51   template <class _Type,
52             class _Proj                                                      = identity,
53             indirect_strict_weak_order<projected<const _Type*, _Proj>> _Comp = ranges::less>
54   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr ranges::minmax_result<const _Type&>
55   operator()(_LIBCPP_LIFETIMEBOUND const _Type& __a,
56              _LIBCPP_LIFETIMEBOUND const _Type& __b,
57              _Comp __comp = {},
58              _Proj __proj = {}) const {
59     if (std::invoke(__comp, std::invoke(__proj, __b), std::invoke(__proj, __a)))
60       return {__b, __a};
61     return {__a, __b};
62   }
63 
64   template <copyable _Type,
65             class _Proj                                                      = identity,
66             indirect_strict_weak_order<projected<const _Type*, _Proj>> _Comp = ranges::less>
67   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr ranges::minmax_result<_Type>
68   operator()(initializer_list<_Type> __il, _Comp __comp = {}, _Proj __proj = {}) const {
69     _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
70         __il.begin() != __il.end(), "initializer_list has to contain at least one element");
71     auto __iters = std::__minmax_element_impl(__il.begin(), __il.end(), __comp, __proj);
72     return ranges::minmax_result<_Type>{*__iters.first, *__iters.second};
73   }
74 
75   template <input_range _Range,
76             class _Proj                                                            = identity,
77             indirect_strict_weak_order<projected<iterator_t<_Range>, _Proj>> _Comp = ranges::less>
78     requires indirectly_copyable_storable<iterator_t<_Range>, range_value_t<_Range>*>
79   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr ranges::minmax_result<range_value_t<_Range>>
80   operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const {
81     auto __first  = ranges::begin(__r);
82     auto __last   = ranges::end(__r);
83     using _ValueT = range_value_t<_Range>;
84 
85     _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__first != __last, "range has to contain at least one element");
86 
87     // This optimiation is not in minmax_element because clang doesn't see through the pointers and as a result doesn't
88     // vectorize the code.
89     if constexpr (contiguous_range<_Range> && is_integral_v<_ValueT> &&
90                   __is_cheap_to_copy<_ValueT> & __is_identity<_Proj>::value &&
91                   __desugars_to_v<__less_tag, _Comp, _ValueT, _ValueT>) {
92       minmax_result<_ValueT> __result = {__r[0], __r[0]};
93       for (auto __e : __r) {
94         if (__e < __result.min)
95           __result.min = __e;
96         if (__result.max < __e)
97           __result.max = __e;
98       }
99       return __result;
100     } else if constexpr (forward_range<_Range>) {
101       // Special-case the one element case. Avoid repeatedly initializing objects from the result of an iterator
102       // dereference when doing so might not be idempotent. The `if constexpr` avoids the extra branch in cases where
103       // it's not needed.
104       if constexpr (!same_as<remove_cvref_t<range_reference_t<_Range>>, _ValueT> ||
105                     is_rvalue_reference_v<range_reference_t<_Range>>) {
106         if (ranges::next(__first) == __last) {
107           // During initialization, members are allowed to refer to already initialized members
108           // (see http://eel.is/c++draft/dcl.init.aggr#6)
109           minmax_result<_ValueT> __result = {*__first, __result.min};
110           return __result;
111         }
112       }
113       auto __result = std::__minmax_element_impl(__first, __last, __comp, __proj);
114       return {*__result.first, *__result.second};
115     } else {
116       // input_iterators can't be copied, so the implementation for input_iterators has to store
117       // the values instead of a pointer to the correct values
118       auto __less = [&](auto&& __a, auto&& __b) -> bool {
119         return std::invoke(__comp,
120                            std::invoke(__proj, std::forward<decltype(__a)>(__a)),
121                            std::invoke(__proj, std::forward<decltype(__b)>(__b)));
122       };
123 
124       // During initialization, members are allowed to refer to already initialized members
125       // (see http://eel.is/c++draft/dcl.init.aggr#6)
126       ranges::minmax_result<_ValueT> __result = {*__first, __result.min};
127       if (__first == __last || ++__first == __last)
128         return __result;
129 
130       if (__less(*__first, __result.min))
131         __result.min = *__first;
132       else
133         __result.max = *__first;
134 
135       while (++__first != __last) {
136         _ValueT __i = *__first;
137         if (++__first == __last) {
138           if (__less(__i, __result.min))
139             __result.min = __i;
140           else if (!__less(__i, __result.max))
141             __result.max = __i;
142           return __result;
143         }
144 
145         if (__less(*__first, __i)) {
146           if (__less(*__first, __result.min))
147             __result.min = *__first;
148           if (!__less(__i, __result.max))
149             __result.max = std::move(__i);
150         } else {
151           if (__less(__i, __result.min))
152             __result.min = std::move(__i);
153           if (!__less(*__first, __result.max))
154             __result.max = *__first;
155         }
156       }
157       return __result;
158     }
159   }
160 };
161 
162 inline namespace __cpo {
163 inline constexpr auto minmax = __minmax{};
164 } // namespace __cpo
165 } // namespace ranges
166 
167 _LIBCPP_END_NAMESPACE_STD
168 
169 _LIBCPP_POP_MACROS
170 
171 #endif // _LIBCPP_STD_VER >= 20
172 
173 #endif // _LIBCPP___ALGORITHM_RANGES_MINMAX_H
174