xref: /freebsd/contrib/llvm-project/libcxx/include/__algorithm/ranges_reverse.h (revision da5432eda807c4b7232d030d5157d5b417ea4f52)
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_REVERSE_H
10 #define _LIBCPP___ALGORITHM_RANGES_REVERSE_H
11 
12 #include <__config>
13 #include <__iterator/concepts.h>
14 #include <__iterator/iter_swap.h>
15 #include <__iterator/next.h>
16 #include <__iterator/permutable.h>
17 #include <__ranges/access.h>
18 #include <__ranges/concepts.h>
19 #include <__ranges/dangling.h>
20 
21 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
22 #  pragma GCC system_header
23 #endif
24 
25 #if _LIBCPP_STD_VER > 17
26 
27 _LIBCPP_BEGIN_NAMESPACE_STD
28 
29 namespace ranges {
30 namespace __reverse {
31 struct __fn {
32 
33   template <bidirectional_iterator _Iter, sentinel_for<_Iter> _Sent>
34     requires permutable<_Iter>
35   _LIBCPP_HIDE_FROM_ABI constexpr
36   _Iter operator()(_Iter __first, _Sent __last) const {
37     if constexpr (random_access_iterator<_Iter>) {
38       if (__first == __last)
39         return __first;
40 
41       auto __end = ranges::next(__first, __last);
42       auto __ret = __end;
43 
44       while (__first < --__end) {
45         ranges::iter_swap(__first, __end);
46         ++__first;
47       }
48       return __ret;
49     } else {
50       auto __end = ranges::next(__first, __last);
51       auto __ret = __end;
52 
53       while (__first != __end) {
54         if (__first == --__end)
55           break;
56 
57         ranges::iter_swap(__first, __end);
58         ++__first;
59       }
60       return __ret;
61     }
62   }
63 
64   template <bidirectional_range _Range>
65     requires permutable<iterator_t<_Range>>
66   _LIBCPP_HIDE_FROM_ABI constexpr
67   borrowed_iterator_t<_Range> operator()(_Range&& __range) const {
68     return (*this)(ranges::begin(__range), ranges::end(__range));
69   }
70 
71 };
72 } // namespace __reverse
73 
74 inline namespace __cpo {
75   inline constexpr auto reverse = __reverse::__fn{};
76 } // namespace __cpo
77 } // namespace ranges
78 
79 _LIBCPP_END_NAMESPACE_STD
80 
81 #endif // _LIBCPP_STD_VER > 17
82 
83 #endif // _LIBCPP___ALGORITHM_RANGES_REVERSE_H
84