xref: /llvm-project/libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/copy.pass.cpp (revision c4e98722ca79c827dd57b809e0ef16b3b8da8c72)
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 // <algorithm>
10 
11 // template<InputIterator InIter, OutputIterator<auto, InIter::reference> OutIter>
12 //   constexpr OutIter   // constexpr after C++17
13 //   copy(InIter first, InIter last, OutIter result);
14 
15 #include <algorithm>
16 #include <cassert>
17 
18 #include "test_macros.h"
19 #include "test_iterators.h"
20 
21 class PaddedBase {
22 public:
PaddedBase(std::int16_t a,std::int8_t b)23   TEST_CONSTEXPR PaddedBase(std::int16_t a, std::int8_t b) : a_(a), b_(b) {}
24 
25   std::int16_t a_;
26   std::int8_t b_;
27 };
28 
29 class Derived : public PaddedBase {
30 public:
Derived(std::int16_t a,std::int8_t b,std::int8_t c)31   TEST_CONSTEXPR Derived(std::int16_t a, std::int8_t b, std::int8_t c) : PaddedBase(a, b), c_(c) {}
32 
33   std::int8_t c_;
34 };
35 
36 template <class InIter>
37 struct Test {
38   template <class OutIter>
operator ()Test39   TEST_CONSTEXPR_CXX20 void operator()() {
40     const unsigned N = 1000;
41     int ia[N]        = {};
42     for (unsigned i = 0; i < N; ++i)
43       ia[i] = i;
44     int ib[N] = {0};
45 
46     OutIter r = std::copy(InIter(ia), InIter(ia + N), OutIter(ib));
47     assert(base(r) == ib + N);
48     for (unsigned i = 0; i < N; ++i)
49       assert(ia[i] == ib[i]);
50   }
51 };
52 
53 struct TestInIters {
54   template <class InIter>
operator ()TestInIters55   TEST_CONSTEXPR_CXX20 void operator()() {
56     types::for_each(
57         types::concatenate_t<types::cpp17_input_iterator_list<int*>, types::type_list<cpp17_output_iterator<int*> > >(),
58         Test<InIter>());
59   }
60 };
61 
test()62 TEST_CONSTEXPR_CXX20 bool test() {
63   types::for_each(types::cpp17_input_iterator_list<int*>(), TestInIters());
64 
65   { // Make sure that padding bits aren't copied
66     Derived src(1, 2, 3);
67     Derived dst(4, 5, 6);
68     std::copy(static_cast<PaddedBase*>(&src), static_cast<PaddedBase*>(&src) + 1, static_cast<PaddedBase*>(&dst));
69     assert(dst.a_ == 1);
70     assert(dst.b_ == 2);
71     assert(dst.c_ == 6);
72   }
73 
74   { // Make sure that overlapping ranges can be copied
75     int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
76     std::copy(a + 3, a + 10, a);
77     int expected[] = {4, 5, 6, 7, 8, 9, 10, 8, 9, 10};
78     assert(std::equal(a, a + 10, expected));
79   }
80 
81   return true;
82 }
83 
main(int,char **)84 int main(int, char**) {
85   test();
86 
87 #if TEST_STD_VER > 17
88   static_assert(test());
89 #endif
90 
91   return 0;
92 }
93