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_MERGE_H
10#define _LIBCPP___PSTL_CPU_ALGOS_MERGE_H
11
12#include <__algorithm/merge.h>
13#include <__assert>
14#include <__config>
15#include <__iterator/concepts.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 <__type_traits/is_execution_policy.h>
21#include <__utility/move.h>
22
23#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
24# pragma GCC system_header
25#endif
26
27_LIBCPP_PUSH_MACROS
28#include <__undef_macros>
29
30#if _LIBCPP_STD_VER >= 17
31
32_LIBCPP_BEGIN_NAMESPACE_STD
33namespace __pstl {
34
35template <class _Backend, class _RawExecutionPolicy>
36struct __cpu_parallel_merge {
37 template <class _Policy, class _ForwardIterator1, class _ForwardIterator2, class _ForwardOutIterator, class _Comp>
38 _LIBCPP_HIDE_FROM_ABI optional<_ForwardOutIterator> operator()(
39 _Policy&& __policy,
40 _ForwardIterator1 __first1,
41 _ForwardIterator1 __last1,
42 _ForwardIterator2 __first2,
43 _ForwardIterator2 __last2,
44 _ForwardOutIterator __result,
45 _Comp __comp) const noexcept {
46 if constexpr (__is_parallel_execution_policy_v<_RawExecutionPolicy> &&
47 __has_random_access_iterator_category_or_concept<_ForwardIterator1>::value &&
48 __has_random_access_iterator_category_or_concept<_ForwardIterator2>::value &&
49 __has_random_access_iterator_category_or_concept<_ForwardOutIterator>::value) {
50 auto __res = __cpu_traits<_Backend>::__merge(
51 __first1,
52 __last1,
53 __first2,
54 __last2,
55 __result,
56 __comp,
57 [&__policy](_ForwardIterator1 __g_first1,
58 _ForwardIterator1 __g_last1,
59 _ForwardIterator2 __g_first2,
60 _ForwardIterator2 __g_last2,
61 _ForwardOutIterator __g_result,
62 _Comp __g_comp) {
63 using _MergeUnseq = __pstl::__merge<_Backend, __remove_parallel_policy_t<_RawExecutionPolicy>>;
64 [[maybe_unused]] auto __g_res = _MergeUnseq()(
65 std::__remove_parallel_policy(__policy),
66 std::move(__g_first1),
67 std::move(__g_last1),
68 std::move(__g_first2),
69 std::move(__g_last2),
70 std::move(__g_result),
71 std::move(__g_comp));
72 _LIBCPP_ASSERT_INTERNAL(__g_res, "unsed/sed should never try to allocate!");
73 });
74 if (!__res)
75 return nullopt;
76 return __result + (__last1 - __first1) + (__last2 - __first2);
77 } else {
78 return std::merge(__first1, __last1, __first2, __last2, __result, __comp);
79 }
80 }
81};
82
83} // namespace __pstl
84_LIBCPP_END_NAMESPACE_STD
85
86#endif // _LIBCPP_STD_VER >= 17
87
88_LIBCPP_POP_MACROS
89
90#endif // _LIBCPP___PSTL_CPU_ALGOS_MERGE_H
91