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___PSTL_BACKENDS_STATPART_REVERSE_H
10#define _LIBCPP___PSTL_BACKENDS_STATPART_REVERSE_H
11
12#include <__algorithm/reverse.h>
13#include <__algorithm/swap_ranges.h>
14#include <__config>
15#include <__execution/is_execution_policy.h>
16#include <__functional/operations.h>
17#include <__iterator/concepts.h>
18#include <__iterator/iterator_traits.h>
19#include <__iterator/reverse_iterator.h>
20#include <__optional/nullopt_t.h>
21#include <__optional/optional.h>
22#include <__pstl/backend_fwd.h>
23#include <__pstl/backends/statpart/basis.h>
24#include <__utility/empty.h>
25#include <__utility/move.h>
26
27#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
28# pragma GCC system_header
29#endif
30
31_LIBCPP_PUSH_MACROS
32#include <__undef_macros>
33
34#if _LIBCPP_STD_VER >= 17
35_LIBCPP_BEGIN_NAMESPACE_STD
36_LIBCPP_BEGIN_EXPLICIT_ABI_ANNOTATIONS
37namespace __pstl {
38
39template <class _ExecutionPolicy>
40struct __reverse<__statpart_backend_tag, _ExecutionPolicy> {
41 template <class _Policy, class _BidirectionalIterator>
42 _LIBCPP_HIDE_FROM_ABI optional<__empty>
43 operator()(_Policy&&, _BidirectionalIterator __first, _BidirectionalIterator __last) const noexcept {
44 if constexpr (__is_parallel_execution_policy_v<_ExecutionPolicy> &&
45 __has_random_access_iterator_category_or_concept<_BidirectionalIterator>::value) {
46 // Perform a chunked for_each on the first half of the range.
47 // Odd-sized ranges will leave the middle element untouched, which is correct for this algorithm:
48 // its reversed position is the same.
49 auto __n = (__last - __first) / 2;
50 return __statpart::__for_each(
51 __first, __first + __n, [__first, __last](_BidirectionalIterator __i, _BidirectionalIterator __j) {
52 // Derive the last position of the mirrored range by counting from the end.
53 _BidirectionalIterator __mirror_last = __last - (__i - __first);
54 // Swap the elements in the range of the first half with their mirrored counterparts in the second half.
55 std::swap_ranges(std::move(__i),
56 std::move(__j),
57 std::reverse_iterator<_BidirectionalIterator>(std::move(__mirror_last)));
58 });
59 } else {
60 // Non-random access iterators currently cannot be processed in parallel, use the sequential implementation.
61 std::reverse(std::move(__first), std::move(__last));
62 return __empty{};
63 }
64 }
65};
66
67} // namespace __pstl
68_LIBCPP_END_EXPLICIT_ABI_ANNOTATIONS
69_LIBCPP_END_NAMESPACE_STD
70
71#endif // _LIBCPP_STD_VER >= 17
72
73_LIBCPP_POP_MACROS
74
75#endif // _LIBCPP___PSTL_BACKENDS_STATPART_REVERSE_H
76