[libcxx-commits] [libcxx] 25607d1 - [libc++] Implement `std::ranges::merge`

Hui Xie via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jul 4 05:44:44 PDT 2022


Author: Hui Xie
Date: 2022-07-04T13:44:31+01:00
New Revision: 25607d143d1d98ac1b16ebeb6af4f3cceea0d738

URL: https://github.com/llvm/llvm-project/commit/25607d143d1d98ac1b16ebeb6af4f3cceea0d738
DIFF: https://github.com/llvm/llvm-project/commit/25607d143d1d98ac1b16ebeb6af4f3cceea0d738.diff

LOG: [libc++] Implement `std::ranges::merge`

Implement `std::ranges::merge`. added unit tests

Differential Revision: https://reviews.llvm.org/D128611

Added: 
    libcxx/include/__algorithm/ranges_merge.h
    libcxx/test/std/algorithms/alg.sorting/alg.merge/ranges_merge.pass.cpp

Modified: 
    libcxx/docs/Status/RangesAlgorithms.csv
    libcxx/include/CMakeLists.txt
    libcxx/include/algorithm
    libcxx/include/module.modulemap.in
    libcxx/test/libcxx/algorithms/ranges_robust_against_copying_comparators.pass.cpp
    libcxx/test/libcxx/algorithms/ranges_robust_against_copying_projections.pass.cpp
    libcxx/test/libcxx/private_headers.verify.cpp
    libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp

Removed: 
    


################################################################################
diff  --git a/libcxx/docs/Status/RangesAlgorithms.csv b/libcxx/docs/Status/RangesAlgorithms.csv
index d78fe54df1470..91468f1841705 100644
--- a/libcxx/docs/Status/RangesAlgorithms.csv
+++ b/libcxx/docs/Status/RangesAlgorithms.csv
@@ -60,11 +60,11 @@ Write,sample,Not assigned,n/a,Not started
 Write,unique_copy,Not assigned,n/a,Not started
 Write,partition_copy,Not assigned,n/a,Not started
 Write,partial_sort_copy,Not assigned,n/a,Not started
-Merge,merge,Not assigned,n/a,Not started
-Merge,set_
diff erence,Not assigned,n/a,Not started
-Merge,set_intersection,Not assigned,n/a,Not started
-Merge,set_symmetric_
diff erence,Not assigned,n/a,Not started
-Merge,set_union,Not assigned,n/a,Not started
+Merge,merge,Hui Xie,`D128611 <https://llvm.org/D128611>`_,✅
+Merge,set_
diff erence,Hui Xie,n/a,Not started
+Merge,set_intersection,Hui Xie,n/a,Not started
+Merge,set_symmetric_
diff erence,Hui Xie,n/a,Not started
+Merge,set_union,Not assigned,Hui Xie,Not started
 Permutation,remove,Not assigned,n/a,Not started
 Permutation,remove_if,Not assigned,n/a,Not started
 Permutation,reverse,Nikolas Klauser,`D125752 <https://llvm.org/D125752>`_,✅

diff  --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 2b45a43f05561..621dc3171e26a 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -94,6 +94,7 @@ set(files
   __algorithm/ranges_lower_bound.h
   __algorithm/ranges_max.h
   __algorithm/ranges_max_element.h
+  __algorithm/ranges_merge.h
   __algorithm/ranges_min.h
   __algorithm/ranges_min_element.h
   __algorithm/ranges_minmax.h

diff  --git a/libcxx/include/__algorithm/ranges_merge.h b/libcxx/include/__algorithm/ranges_merge.h
new file mode 100644
index 0000000000000..c73e09e94ccc5
--- /dev/null
+++ b/libcxx/include/__algorithm/ranges_merge.h
@@ -0,0 +1,142 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_RANGES_MERGE_H
+#define _LIBCPP___ALGORITHM_RANGES_MERGE_H
+
+#include <__algorithm/in_in_out_result.h>
+#include <__algorithm/ranges_copy.h>
+#include <__config>
+#include <__functional/identity.h>
+#include <__functional/invoke.h>
+#include <__functional/ranges_operations.h>
+#include <__iterator/concepts.h>
+#include <__iterator/mergeable.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__ranges/dangling.h>
+#include <__utility/move.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+namespace ranges {
+
+template <class _InIter1, class _InIter2, class _OutIter>
+using merge_result = in_in_out_result<_InIter1, _InIter2, _OutIter>;
+
+namespace __merge {
+
+template <
+    class _InIter1,
+    class _Sent1,
+    class _InIter2,
+    class _Sent2,
+    class _OutIter,
+    class _Comp,
+    class _Proj1,
+    class _Proj2>
+_LIBCPP_HIDE_FROM_ABI constexpr merge_result<__uncvref_t<_InIter1>, __uncvref_t<_InIter2>, __uncvref_t<_OutIter>>
+__merge_impl(
+    _InIter1&& __first1,
+    _Sent1&& __last1,
+    _InIter2&& __first2,
+    _Sent2&& __last2,
+    _OutIter&& __result,
+    _Comp&& __comp,
+    _Proj1&& __proj1,
+    _Proj2&& __proj2) {
+  for (; __first1 != __last1 && __first2 != __last2; ++__result) {
+    if (std::invoke(__comp, std::invoke(__proj2, *__first2), std::invoke(__proj1, *__first1))) {
+      *__result = *__first2;
+      ++__first2;
+    } else {
+      *__result = *__first1;
+      ++__first1;
+    }
+  }
+  auto __ret1 = ranges::copy(std::move(__first1), std::move(__last1), std::move(__result));
+  auto __ret2 = ranges::copy(std::move(__first2), std::move(__last2), std::move(__ret1.out));
+  return {std::move(__ret1.in), std::move(__ret2.in), std::move(__ret2.out)};
+}
+
+struct __fn {
+  template <
+      input_iterator _InIter1,
+      sentinel_for<_InIter1> _Sent1,
+      input_iterator _InIter2,
+      sentinel_for<_InIter2> _Sent2,
+      weakly_incrementable _OutIter,
+      class _Comp  = less,
+      class _Proj1 = identity,
+      class _Proj2 = identity>
+    requires mergeable<_InIter1, _InIter2, _OutIter, _Comp, _Proj1, _Proj2>
+  _LIBCPP_HIDE_FROM_ABI constexpr merge_result<_InIter1, _InIter2, _OutIter> operator()(
+      _InIter1 __first1,
+      _Sent1 __last1,
+      _InIter2 __first2,
+      _Sent2 __last2,
+      _OutIter __result,
+      _Comp __comp   = {},
+      _Proj1 __proj1 = {},
+      _Proj2 __proj2 = {}) const {
+    return __merge::__merge_impl(__first1, __last1, __first2, __last2, __result, __comp, __proj1, __proj2);
+  }
+
+  template <
+      input_range _Range1,
+      input_range _Range2,
+      weakly_incrementable _OutIter,
+      class _Comp  = less,
+      class _Proj1 = identity,
+      class _Proj2 = identity>
+    requires mergeable<
+        iterator_t<_Range1>,
+        iterator_t<_Range2>,
+        _OutIter,
+        _Comp,
+        _Proj1,
+        _Proj2> 
+  _LIBCPP_HIDE_FROM_ABI constexpr merge_result<borrowed_iterator_t<_Range1>, borrowed_iterator_t<_Range2>, _OutIter>
+        operator()(
+            _Range1&& __range1,
+            _Range2&& __range2,
+            _OutIter __result,
+            _Comp __comp   = {},
+            _Proj1 __proj1 = {},
+            _Proj2 __proj2 = {}) const {
+    return __merge::__merge_impl(
+        ranges::begin(__range1),
+        ranges::end(__range1),
+        ranges::begin(__range2),
+        ranges::end(__range2),
+        __result,
+        __comp,
+        __proj1,
+        __proj2);
+  }
+};
+
+} // namespace __merge
+
+inline namespace __cpo {
+  inline constexpr auto merge = __merge::__fn{};
+} // namespace __cpo
+} // namespace ranges
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
+
+#endif // _LIBCPP___ALGORITHM_RANGES_MERGE_H

diff  --git a/libcxx/include/algorithm b/libcxx/include/algorithm
index 0154dbc39c08a..76bdf3b85a656 100644
--- a/libcxx/include/algorithm
+++ b/libcxx/include/algorithm
@@ -493,6 +493,23 @@ namespace ranges {
     constexpr ranges::move_result<borrowed_iterator_t<R>, O>
       ranges::move(R&& r, O result);                                                                // since C++20
 
+  template<class I1, class I2, class O>
+    using merge_result = in_in_out_result<I1, I2, O>;                                               // since C++20
+
+  template<input_iterator I1, sentinel_for<I1> S1, input_iterator I2, sentinel_for<I2> S2,
+           weakly_incrementable O, class Comp = ranges::less, class Proj1 = identity,
+           class Proj2 = identity>
+    requires mergeable<I1, I2, O, Comp, Proj1, Proj2>
+    constexpr merge_result<I1, I2, O>
+      merge(I1 first1, S1 last1, I2 first2, S2 last2, O result,
+            Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {});                                    // since C++20
+
+  template<input_range R1, input_range R2, weakly_incrementable O, class Comp = ranges::less,
+           class Proj1 = identity, class Proj2 = identity>
+    requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2>
+    constexpr merge_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O>
+      merge(R1&& r1, R2&& r2, O result,
+            Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {});                                    // since C++20
 
 }
 
@@ -1249,6 +1266,7 @@ template <class BidirectionalIterator, class Compare>
 #include <__algorithm/ranges_lower_bound.h>
 #include <__algorithm/ranges_max.h>
 #include <__algorithm/ranges_max_element.h>
+#include <__algorithm/ranges_merge.h>
 #include <__algorithm/ranges_min.h>
 #include <__algorithm/ranges_min_element.h>
 #include <__algorithm/ranges_minmax.h>

diff  --git a/libcxx/include/module.modulemap.in b/libcxx/include/module.modulemap.in
index a52357954af98..becfec44ea7b1 100644
--- a/libcxx/include/module.modulemap.in
+++ b/libcxx/include/module.modulemap.in
@@ -333,6 +333,7 @@ module std [system] {
       module ranges_lower_bound              { private header "__algorithm/ranges_lower_bound.h" }
       module ranges_max                      { private header "__algorithm/ranges_max.h" }
       module ranges_max_element              { private header "__algorithm/ranges_max_element.h" }
+      module ranges_merge                    { private header "__algorithm/ranges_merge.h" }
       module ranges_min                      { private header "__algorithm/ranges_min.h" }
       module ranges_min_element              { private header "__algorithm/ranges_min_element.h" }
       module ranges_minmax                   { private header "__algorithm/ranges_minmax.h" }

diff  --git a/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_comparators.pass.cpp b/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_comparators.pass.cpp
index 7d7fbfde983e6..9d6c80f28f68a 100644
--- a/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_comparators.pass.cpp
+++ b/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_comparators.pass.cpp
@@ -79,7 +79,7 @@ constexpr bool all_the_algorithms()
 {
     void *a[10] = {};
     void *b[10] = {};
-    //void *half[5] = {};
+    void *half[5] = {};
     void **first = a;
     void **mid = a+5;
     void **last = a+10;
@@ -151,8 +151,8 @@ constexpr bool all_the_algorithms()
     (void)std::ranges::max(a, Less(&copies)); assert(copies == 0);
     (void)std::ranges::max_element(first, last, Less(&copies)); assert(copies == 0);
     (void)std::ranges::max_element(a, Less(&copies)); assert(copies == 0);
-    //(void)std::ranges::merge(first, mid, mid, last, first2, Less(&copies)); assert(copies == 0);
-    //(void)std::ranges::merge(half, half, b, Less(&copies)); assert(copies == 0);
+    (void)std::ranges::merge(first, mid, mid, last, first2, Less(&copies)); assert(copies == 0);
+    (void)std::ranges::merge(half, half, b, Less(&copies)); assert(copies == 0);
     (void)std::ranges::min(value, value, Less(&copies)); assert(copies == 0);
     (void)std::ranges::min({ value, value }, Less(&copies)); assert(copies == 0);
     (void)std::ranges::min(a, Less(&copies)); assert(copies == 0);

diff  --git a/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_projections.pass.cpp b/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_projections.pass.cpp
index 86effc85b1d5c..75a932a398fe4 100644
--- a/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_projections.pass.cpp
+++ b/libcxx/test/libcxx/algorithms/ranges_robust_against_copying_projections.pass.cpp
@@ -61,7 +61,7 @@ constexpr bool all_the_algorithms()
 {
     T a[10] = {};
     T b[10] = {};
-    //T half[5] = {};
+    T half[5] = {};
     T *first = a;
     T *mid = a+5;
     T *last = a+10;
@@ -134,8 +134,8 @@ constexpr bool all_the_algorithms()
     (void)std::ranges::max(a, Less(), Proj(&copies)); assert(copies == 0);
     (void)std::ranges::max_element(first, last, Less(), Proj(&copies)); assert(copies == 0);
     (void)std::ranges::max_element(a, Less(), Proj(&copies)); assert(copies == 0);
-    //(void)std::ranges::merge(first, mid, mid, last, first2, Less(), Proj(&copies), Proj(&copies)); assert(copies == 0);
-    //(void)std::ranges::merge(half, half, b, Less(), Proj(&copies), Proj(&copies)); assert(copies == 0);
+    (void)std::ranges::merge(first, mid, mid, last, first2, Less(), Proj(&copies), Proj(&copies)); assert(copies == 0);
+    (void)std::ranges::merge(half, half, b, Less(), Proj(&copies), Proj(&copies)); assert(copies == 0);
     (void)std::ranges::min(T(), T(), Less(), Proj(&copies)); assert(copies == 0);
     (void)std::ranges::min({ T(), T() }, Less(), Proj(&copies)); assert(copies == 0);
     (void)std::ranges::min(a, Less(), Proj(&copies)); assert(copies == 0);

diff  --git a/libcxx/test/libcxx/private_headers.verify.cpp b/libcxx/test/libcxx/private_headers.verify.cpp
index dbe5ba0ca0c92..cf75caf4409ea 100644
--- a/libcxx/test/libcxx/private_headers.verify.cpp
+++ b/libcxx/test/libcxx/private_headers.verify.cpp
@@ -131,6 +131,7 @@ END-SCRIPT
 #include <__algorithm/ranges_lower_bound.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_lower_bound.h'}}
 #include <__algorithm/ranges_max.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_max.h'}}
 #include <__algorithm/ranges_max_element.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_max_element.h'}}
+#include <__algorithm/ranges_merge.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_merge.h'}}
 #include <__algorithm/ranges_min.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_min.h'}}
 #include <__algorithm/ranges_min_element.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_min_element.h'}}
 #include <__algorithm/ranges_minmax.h> // expected-error@*:* {{use of private header from outside its module: '__algorithm/ranges_minmax.h'}}

diff  --git a/libcxx/test/std/algorithms/alg.sorting/alg.merge/ranges_merge.pass.cpp b/libcxx/test/std/algorithms/alg.sorting/alg.merge/ranges_merge.pass.cpp
new file mode 100644
index 0000000000000..869535a999028
--- /dev/null
+++ b/libcxx/test/std/algorithms/alg.sorting/alg.merge/ranges_merge.pass.cpp
@@ -0,0 +1,613 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <algorithm>
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17
+// UNSUPPORTED: libcpp-has-no-incomplete-ranges
+
+// template<input_­iterator I1, sentinel_­for<I1> S1, input_­iterator I2, sentinel_­for<I2> S2,
+//          weakly_­incrementable O, class Comp = ranges::less, class Proj1 = identity,
+//          class Proj2 = identity>
+//   requires mergeable<I1, I2, O, Comp, Proj1, Proj2>
+//   constexpr merge_result<I1, I2, O>
+//     merge(I1 first1, S1 last1, I2 first2, S2 last2, O result,
+//           Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {});                                    // since C++20
+//
+// template<input_­range R1, input_­range R2, weakly_­incrementable O, class Comp = ranges::less,
+//          class Proj1 = identity, class Proj2 = identity>
+//   requires mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2>
+//   constexpr merge_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>, O>
+//     merge(R1&& r1, R2&& r2, O result,
+//           Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {});                                    // since C++20
+
+#include <algorithm>
+#include <array>
+#include <concepts>
+
+#include "almost_satisfies_types.h"
+#include "MoveOnly.h"
+#include "test_iterators.h"
+
+// Test iterator overload's constraints:
+// =====================================
+template <
+    class InIter1,
+    class InIter2,
+    class OutIter,
+    class Sent1 = sentinel_wrapper<InIter1>,
+    class Sent2 = sentinel_wrapper<InIter2>>
+concept HasMergeIter =
+    requires(InIter1&& inIter1, InIter2&& inIter2, OutIter&& outIter, Sent1&& sent1, Sent2&& sent2) {
+      std::ranges::merge(
+          std::forward<InIter1>(inIter1),
+          std::forward<Sent1>(sent1),
+          std::forward<InIter2>(inIter2),
+          std::forward<Sent2>(sent2),
+          std::forward<OutIter>(outIter));
+    };
+
+static_assert(HasMergeIter<int*, int*, int*, int*, int*>);
+
+// !std::input_iterator<I1>
+static_assert(!HasMergeIter<InputIteratorNotDerivedFrom, int*, int*>);
+
+// !std::sentinel_for<S1, I1>
+static_assert(!HasMergeIter<int*, int*, int*, SentinelForNotSemiregular>);
+
+// !std::input_iterator<I2>
+static_assert(!HasMergeIter<int*, InputIteratorNotDerivedFrom, int*>);
+
+// !std::sentinel_for<S2, I2>
+static_assert(!HasMergeIter<int*, int*, int*, int*, SentinelForNotSemiregular>);
+
+// !std::weakly_incrementable<O>
+static_assert(!HasMergeIter<int*, int*, WeaklyIncrementableNotMovable>);
+
+// !std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
+static_assert(!HasMergeIter<MoveOnly*, MoveOnly*, MoveOnly*, MoveOnly*, MoveOnly*>);
+
+// Test range overload's constraints:
+// =====================================
+
+template <class Range1, class Range2, class OutIter>
+concept HasMergeRange =
+    requires(Range1&& range1, Range2&& range2, OutIter&& outIter) {
+      std::ranges::merge(std::forward<Range1>(range1), std::forward<Range2>(range2), std::forward<OutIter>(outIter));
+    };
+
+static_assert(HasMergeRange<UncheckedRange<int*>, UncheckedRange<int*>, int* >);
+
+// !std::input_range<R2>
+static_assert(!HasMergeRange<UncheckedRange<InputIteratorNotDerivedFrom>, UncheckedRange<int*>, int*>);
+
+// !std::input_range<R2>
+static_assert(!HasMergeRange<UncheckedRange<int*>, UncheckedRange<InputIteratorNotDerivedFrom>, int*>);
+
+// !std::weakly_incrementable<O>
+static_assert(!HasMergeRange<UncheckedRange<int*>, UncheckedRange<int*>, WeaklyIncrementableNotMovable >);
+
+// !mergeable<iterator_t<R1>, iterator_t<R2>, O, Comp, Proj1, Proj2>
+static_assert(!HasMergeRange< UncheckedRange<MoveOnly*>, UncheckedRange<MoveOnly*>, MoveOnly*>);
+
+using std::ranges::merge_result;
+
+template <class In1, class In2, class Out, std::size_t N1, std::size_t N2>
+constexpr void testMergeImpl(std::array<int, N1> in1, std::array<int, N2> in2, const auto& expected) {
+  // TODO: std::ranges::merge calls std::ranges::copy
+  // std::ranges::copy(contiguous_iterator<int*>, sentinel_wrapper<contiguous_iterator<int*>>, contiguous_iterator<int*>) doesn't seem to work.
+  // It seems that std::ranges::copy calls std::copy, which unwraps contiguous_iterator<int*> into int*,
+  // and then it failed because there is no == between int* and sentinel_wrapper<contiguous_iterator<int*>>
+  using Sent1 = std::conditional_t<std::contiguous_iterator<In1>, In1, sentinel_wrapper<In1>>;
+  using Sent2 = std::conditional_t<std::contiguous_iterator<In2>, In2, sentinel_wrapper<In2>>;
+
+  // iterator overload
+  {
+    std::array<int, N1 + N2> out;
+    std::same_as<merge_result<In1, In2, Out>> decltype(auto) result = std::ranges::merge(
+        In1{in1.data()},
+        Sent1{In1{in1.data() + in1.size()}},
+        In2{in2.data()},
+        Sent2{In2{in2.data() + in2.size()}},
+        Out{out.data()});
+    assert(std::ranges::equal(out, expected));
+
+    assert(base(result.in1) == in1.data() + in1.size());
+    assert(base(result.in2) == in2.data() + in2.size());
+    assert(base(result.out) == out.data() + out.size());
+  }
+
+  // range overload
+  {
+    std::array<int, N1 + N2> out;
+    std::ranges::subrange r1{In1{in1.data()}, Sent1{In1{in1.data() + in1.size()}}};
+    std::ranges::subrange r2{In2{in2.data()}, Sent2{In2{in2.data() + in2.size()}}};
+    std::same_as<merge_result<In1, In2, Out>> decltype(auto) result = std::ranges::merge(r1, r2, Out{out.data()});
+    assert(std::ranges::equal(out, expected));
+
+    assert(base(result.in1) == in1.data() + in1.size());
+    assert(base(result.in2) == in2.data() + in2.size());
+    assert(base(result.out) == out.data() + out.size());
+  }
+}
+
+template <class In1, class In2, class Out>
+constexpr void testImpl() {
+  // range 1 shorter than range2
+  {
+    std::array in1{0, 1, 5, 6, 9, 10};
+    std::array in2{3, 6, 7, 9, 13, 15, 100};
+    std::array expected{0, 1, 3, 5, 6, 6, 7, 9, 9, 10, 13, 15, 100};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // range 2 shorter than range 1
+  {
+    std::array in1{2, 6, 8, 12};
+    std::array in2{0, 1, 2};
+    std::array expected{0, 1, 2, 2, 6, 8, 12};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // range 1 == range 2
+  {
+    std::array in1{0, 1, 2};
+    std::array in2{0, 1, 2};
+    std::array expected{0, 0, 1, 1, 2, 2};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // All elements in range 1 are greater than every element in range 2
+  {
+    std::array in1{8, 8, 10, 12};
+    std::array in2{0, 0, 1};
+    std::array expected{0, 0, 1, 8, 8, 10, 12};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // All elements in range 2 are greater than every element in range 1
+  {
+    std::array in1{0, 1, 1};
+    std::array in2{7, 7};
+    std::array expected{0, 1, 1, 7, 7};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // range 1 is empty
+  {
+    std::array<int, 0> in1{};
+    std::array in2{3, 4, 5};
+    std::array expected{3, 4, 5};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // range 2 is empty
+  {
+    std::array in1{3, 4, 5};
+    std::array<int, 0> in2{};
+    std::array expected{3, 4, 5};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // both ranges are empty
+  {
+    std::array<int, 0> in1{};
+    std::array<int, 0> in2{};
+    std::array<int, 0> expected{};
+    testMergeImpl<In1, In2, Out>(in1, in2, expected);
+  }
+
+  // check that ranges::dangling is returned for non-borrowed_range and iterator_t is returned for borrowed_range
+  {
+    struct NonBorrowedRange {
+      int* data_;
+      size_t size_;
+
+      // TODO: std::ranges::merge calls std::ranges::copy
+      // std::ranges::copy(contiguous_iterator<int*>, sentinel_wrapper<contiguous_iterator<int*>>, contiguous_iterator<int*>) doesn't seem to work.
+      // It seems that std::ranges::copy calls std::copy, which unwraps contiguous_iterator<int*> into int*,
+      // and then it failed because there is no == between int* and sentinel_wrapper<contiguous_iterator<int*>>
+      using Sent = std::conditional_t<std::contiguous_iterator<In2>, In2, sentinel_wrapper<In2>>;
+
+      constexpr NonBorrowedRange(int* d, size_t s) : data_{d}, size_{s} {}
+
+      constexpr In2 begin() const { return In2{data_}; };
+      constexpr Sent end() const { return Sent{In2{data_ + size_}}; };
+    };
+
+    std::array r1{3, 6, 7, 9};
+    std::array r2{2, 3, 4};
+    std::array<int, 7> out;
+    std::same_as<merge_result<std::array<int, 4>::iterator, std::ranges::dangling, int*>> decltype(auto) result =
+        std::ranges::merge(r1, NonBorrowedRange{r2.data(), r2.size()}, out.data());
+    assert(base(result.in1) == r1.end());
+    assert(base(result.out) == out.data() + out.size());
+    assert(std::ranges::equal(out, std::array{2, 3, 3, 4, 6, 7, 9}));
+  }
+}
+
+template <class InIter2, class OutIter>
+constexpr void withAllPermutationsOfInIter1() {
+  testImpl<cpp20_input_iterator<int*>, InIter2, OutIter>();
+  testImpl<forward_iterator<int*>, InIter2, OutIter>();
+  testImpl<bidirectional_iterator<int*>, InIter2, OutIter>();
+  testImpl<random_access_iterator<int*>, InIter2, OutIter>();
+  testImpl<contiguous_iterator<int*>, InIter2, OutIter>();
+}
+
+template <class OutIter>
+constexpr bool withAllPermutationsOfInIter1AndInIter2() {
+  withAllPermutationsOfInIter1<cpp20_input_iterator<int*>, OutIter>();
+  withAllPermutationsOfInIter1<forward_iterator<int*>, OutIter>();
+  withAllPermutationsOfInIter1<bidirectional_iterator<int*>, OutIter>();
+  withAllPermutationsOfInIter1<random_access_iterator<int*>, OutIter>();
+  withAllPermutationsOfInIter1<contiguous_iterator<int*>, OutIter>();
+  return true;
+}
+
+constexpr void runAllIteratorPermutationsTests() {
+  withAllPermutationsOfInIter1AndInIter2<cpp17_output_iterator<int*>>();
+  withAllPermutationsOfInIter1AndInIter2<cpp20_output_iterator<int*>>();
+  withAllPermutationsOfInIter1AndInIter2<forward_iterator<int*>>();
+  withAllPermutationsOfInIter1AndInIter2<bidirectional_iterator<int*>>();
+  withAllPermutationsOfInIter1AndInIter2<random_access_iterator<int*>>();
+  withAllPermutationsOfInIter1AndInIter2<contiguous_iterator<int*>>();
+
+  static_assert(withAllPermutationsOfInIter1AndInIter2<cpp17_output_iterator<int*>>());
+  static_assert(withAllPermutationsOfInIter1AndInIter2<cpp20_output_iterator<int*>>());
+  static_assert(withAllPermutationsOfInIter1AndInIter2<forward_iterator<int*>>());
+  static_assert(withAllPermutationsOfInIter1AndInIter2<bidirectional_iterator<int*>>());
+  static_assert(withAllPermutationsOfInIter1AndInIter2<random_access_iterator<int*>>());
+  static_assert(withAllPermutationsOfInIter1AndInIter2<contiguous_iterator<int*>>());
+}
+
+constexpr bool test() {
+  // check that every element is copied exactly once
+  struct TracedCopy {
+    int copy_assign = 0;
+    int data        = 0;
+
+    constexpr TracedCopy() = default;
+    constexpr TracedCopy(int i) : data(i) {}
+    constexpr TracedCopy(const TracedCopy& other) : copy_assign(other.copy_assign), data(other.data) {}
+
+    constexpr TracedCopy(TracedCopy&& other)            = delete;
+    constexpr TracedCopy& operator=(TracedCopy&& other) = delete;
+
+    constexpr TracedCopy& operator=(const TracedCopy& other) {
+      copy_assign = other.copy_assign + 1;
+      data        = other.data;
+      return *this;
+    }
+
+    constexpr bool operator==(const TracedCopy& o) const { return data == o.data; }
+    constexpr auto operator<=>(const TracedCopy& o) const { return data <=> o.data; }
+  };
+  {
+    std::array<TracedCopy, 3> r1{3, 5, 8};
+    std::array<TracedCopy, 3> r2{1, 3, 8};
+
+    // iterator overload
+    {
+      std::array<TracedCopy, 6> out;
+      auto result = std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data());
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+      assert(std::ranges::equal(out, std::array<TracedCopy, 6>{1, 3, 3, 5, 8, 8}));
+
+      assert(std::ranges::all_of(out, [](const TracedCopy& e) { return e.copy_assign == 1; }));
+    }
+
+    // range overload
+    {
+      std::array<TracedCopy, 6> out;
+      auto result = std::ranges::merge(r1, r2, out.data());
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+      assert(std::ranges::equal(out, std::array<TracedCopy, 6>{1, 3, 3, 5, 8, 8}));
+
+      assert(std::ranges::all_of(out, [](const TracedCopy& e) { return e.copy_assign == 1; }));
+    }
+  }
+
+  struct IntAndID {
+    int data;
+    int id;
+
+    constexpr auto operator==(const IntAndID& o) const { return data == o.data; }
+    constexpr auto operator<=>(const IntAndID& o) const { return data <=> o.data; }
+  };
+
+  // Algorithm is stable: equal elements should be merged in the original order
+  {
+    std::array<IntAndID, 3> r1{{{0, 0}, {0, 1}, {0, 2}}};
+    std::array<IntAndID, 3> r2{{{1, 0}, {1, 1}, {1, 2}}};
+
+    // iterator overload
+    {
+      std::array<IntAndID, 6> out;
+      std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data());
+
+      assert(std::ranges::equal(out, std::array{0, 0, 0, 1, 1, 1}, {}, &IntAndID::data));
+      // ID should be in their original order
+      assert(std::ranges::equal(out, std::array{0, 1, 2, 0, 1, 2}, {}, &IntAndID::id));
+    }
+
+    // range overload
+    {
+      std::array<IntAndID, 6> out;
+      std::ranges::merge(r1, r2, out.data());
+
+      assert(std::ranges::equal(out, std::array{0, 0, 0, 1, 1, 1}, {}, &IntAndID::data));
+      // ID should be in their original order
+      assert(std::ranges::equal(out, std::array{0, 1, 2, 0, 1, 2}, {}, &IntAndID::id));
+    }
+  }
+
+  // Equal elements in R1 should be merged before equal elements in R2
+  {
+    std::array<IntAndID, 3> r1{{{0, 1}, {1, 1}, {2, 1}}};
+    std::array<IntAndID, 3> r2{{{0, 2}, {1, 2}, {2, 2}}};
+
+    // iterator overload
+    {
+      std::array<IntAndID, 6> out;
+      std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data());
+
+      assert(std::ranges::equal(out, std::array{0, 0, 1, 1, 2, 2}, {}, &IntAndID::data));
+      // ID 1 (from R1) should be in front of ID 2 (from R2)
+      assert(std::ranges::equal(out, std::array{1, 2, 1, 2, 1, 2}, {}, &IntAndID::id));
+    }
+
+    // range overload
+    {
+      std::array<IntAndID, 6> out;
+      std::ranges::merge(r1, r2, out.data());
+
+      assert(std::ranges::equal(out, std::array{0, 0, 1, 1, 2, 2}, {}, &IntAndID::data));
+      // ID 1 (from R1) should be in front of ID 2 (from R2)
+      assert(std::ranges::equal(out, std::array{1, 2, 1, 2, 1, 2}, {}, &IntAndID::id));
+    }
+  }
+
+  struct Data {
+    int data;
+
+    constexpr bool smallerThan(const Data& o) const { return data < o.data; }
+  };
+
+  // Test custom comparator
+  {
+    std::array r1{Data{4}, Data{8}, Data{12}};
+    std::array r2{Data{5}, Data{9}};
+    using Iter1 = std::array<Data, 3>::iterator;
+    using Iter2 = std::array<Data, 2>::iterator;
+
+    // iterator overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data(), [](const Data& x, const Data& y) {
+            return x.data < y.data;
+          });
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+
+    // range overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1, r2, out.data(), [](const Data& x, const Data& y) { return x.data < y.data; });
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+
+    // member pointer Comparator iterator overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data(), &Data::smallerThan);
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+
+    // member pointer Comparator range overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1, r2, out.data(), &Data::smallerThan);
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+  }
+
+  // Test Projection
+  {
+    std::array r1{Data{4}, Data{8}, Data{12}};
+    std::array r2{Data{5}, Data{9}};
+    using Iter1 = std::array<Data, 3>::iterator;
+    using Iter2 = std::array<Data, 2>::iterator;
+
+    const auto proj = [](const Data& d) { return d.data; };
+
+    // iterator overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data(), std::ranges::less{}, proj, proj);
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+
+    // range overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1, r2, out.data(), std::ranges::less{}, proj, proj);
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+
+    // member pointer Projection iterator overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1.begin(), r1.end(), r2.begin(), r2.end(), out.data(), {}, &Data::data, &Data::data);
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+
+    // member pointer Projection range overload
+    {
+      std::array<Data, 5> out;
+      std::same_as<merge_result<Iter1, Iter2, Data*>> decltype(auto) result =
+          std::ranges::merge(r1, r2, out.data(), std::ranges::less{}, &Data::data, &Data::data);
+
+      assert(std::ranges::equal(out, std::array{4, 5, 8, 9, 12}, {}, &Data::data));
+
+      assert(result.in1 == r1.end());
+      assert(result.in2 == r2.end());
+      assert(result.out == out.end());
+    }
+  }
+
+  // Complexity: at most N - 1 comparisons and applications of each projection.
+  {
+    Data r1[] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}};
+    Data r2[] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}};
+    std::array expected{0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9};
+
+    // iterator overload
+    {
+      std::array<Data, 20> out;
+      std::size_t numberOfComp  = 0;
+      std::size_t numberOfProj1 = 0;
+      std::size_t numberOfProj2 = 0;
+
+      const auto comp = [&numberOfComp](int x, int y) {
+        ++numberOfComp;
+        return x < y;
+      };
+
+      const auto proj1 = [&numberOfProj1](const Data& d) {
+        ++numberOfProj1;
+        return d.data;
+      };
+
+      const auto proj2 = [&numberOfProj2](const Data& d) {
+        ++numberOfProj2;
+        return d.data;
+      };
+
+      std::ranges::merge(r1, r1 + 10, r2, r2 + 10, out.data(), comp, proj1, proj2);
+      assert(std::ranges::equal(out, expected, {}, &Data::data));
+      assert(numberOfComp < out.size());
+      assert(numberOfProj1 < out.size());
+      assert(numberOfProj2 < out.size());
+    }
+
+    // range overload
+    {
+      std::array<Data, 20> out;
+      std::size_t numberOfComp  = 0;
+      std::size_t numberOfProj1 = 0;
+      std::size_t numberOfProj2 = 0;
+
+      const auto comp = [&numberOfComp](int x, int y) {
+        ++numberOfComp;
+        return x < y;
+      };
+
+      const auto proj1 = [&numberOfProj1](const Data& d) {
+        ++numberOfProj1;
+        return d.data;
+      };
+
+      const auto proj2 = [&numberOfProj2](const Data& d) {
+        ++numberOfProj2;
+        return d.data;
+      };
+
+      std::ranges::merge(r1, r2, out.data(), comp, proj1, proj2);
+      assert(std::ranges::equal(out, expected, {}, &Data::data));
+      assert(numberOfComp < out.size());
+      assert(numberOfProj1 < out.size());
+      assert(numberOfProj2 < out.size());
+    }
+  }
+
+  // Comparator convertible to bool
+  {
+    struct ConvertibleToBool {
+      bool b;
+      constexpr operator bool() const { return b; }
+    };
+    Data r1[] = {{2}, {4}};
+    Data r2[] = {{3}, {4}, {5}};
+
+    const auto comp = [](const Data& x, const Data& y) { return ConvertibleToBool{x.data < y.data}; };
+
+    // iterator overload
+    {
+      std::array<Data, 5> out;
+      std::ranges::merge(r1, r1 + 2, r2, r2 + 3, out.data(), comp);
+      assert(std::ranges::equal(out, std::array{2, 3, 4, 4, 5}, {}, &Data::data));
+    }
+
+    // range overload
+    {
+      std::array<Data, 5> out;
+      std::ranges::merge(r1, r2, out.data(), comp);
+      assert(std::ranges::equal(out, std::array{2, 3, 4, 4, 5}, {}, &Data::data));
+    }
+  }
+
+  return true;
+}
+
+int main(int, char**) {
+  test();
+  static_assert(test());
+
+  runAllIteratorPermutationsTests();
+
+  return 0;
+}

diff  --git a/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp b/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp
index 6cc6081e2c291..b66c78951b55c 100644
--- a/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp
+++ b/libcxx/test/std/library/description/conventions/customization.point.object/niebloid.compile.pass.cpp
@@ -98,7 +98,7 @@ static_assert(test(std::ranges::lower_bound, a, 42));
 //static_assert(test(std::ranges::make_heap, a));
 static_assert(test(std::ranges::max, a));
 static_assert(test(std::ranges::max_element, a));
-//static_assert(test(std::ranges::merge, a, a, a));
+static_assert(test(std::ranges::merge, a, a, a));
 static_assert(test(std::ranges::min, a));
 static_assert(test(std::ranges::min_element, a));
 static_assert(test(std::ranges::minmax, a));


        


More information about the libcxx-commits mailing list