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_SWAP_RANGES_H
10#define _LIBCPP___PSTL_CPU_ALGOS_SWAP_RANGES_H
11
12#include <__algorithm/swap_ranges.h>
13#include <__config>
14#include <__iterator/concepts.h>
15#include <__iterator/iterator_traits.h>
16#include <__optional/nullopt_t.h>
17#include <__optional/optional.h>
18#include <__pstl/backend_fwd.h>
19#include <__pstl/cpu_algos/cpu_traits.h>
20#include <__pstl/cpu_algos/for_each.h>
21#include <__type_traits/is_execution_policy.h>
22#include <__utility/move.h>
23
24#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
25# pragma GCC system_header
26#endif
27
28_LIBCPP_PUSH_MACROS
29#include <__undef_macros>
30
31#if _LIBCPP_STD_VER >= 17
32
33_LIBCPP_BEGIN_NAMESPACE_STD
34
35namespace __pstl {
36
37template <class _Backend, class _RawExecutionPolicy>
38struct __cpu_parallel_swap_ranges {
39 template <class _Policy, class _ForwardIterator1, class _ForwardIterator2>
40 _LIBCPP_HIDE_FROM_ABI optional<_ForwardIterator2> operator()(
41 _Policy&&, _ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2) const noexcept {
42 if constexpr (__is_parallel_execution_policy_v<_RawExecutionPolicy> &&
43 __has_random_access_iterator_category_or_concept<_ForwardIterator1>::value &&
44 __has_random_access_iterator_category_or_concept<_ForwardIterator2>::value) {
45 auto __res = __pstl::__parallel_for_each_iter_pair<_Backend>(
46 __first1,
47 __last1,
48 __first2,
49 [](_ForwardIterator1 __brick_first1, _ForwardIterator1 __brick_last1, _ForwardIterator2 __brick_first2) {
50 std::swap_ranges(std::move(__brick_first1), std::move(__brick_last1), std::move(__brick_first2));
51 });
52 if (!__res) {
53 return std::nullopt; // Failed to run the algorithm, propagate the error.
54 }
55 return __first2 + (__last1 - __first1);
56 } else {
57 // Non-random access iterators cannot be processed in parallel, fall back to the sequential implementation.
58 return std::swap_ranges(std::move(__first1), std::move(__last1), std::move(__first2));
59 }
60 }
61};
62
63} // namespace __pstl
64
65_LIBCPP_END_NAMESPACE_STD
66
67#endif // _LIBCPP_STD_VER >= 17
68
69_LIBCPP_POP_MACROS
70
71#endif // _LIBCPP___PSTL_CPU_ALGOS_SWAP_RANGES_H
72