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