1 // -*- C++ -*-
2 //===-- for_each.pass.cpp -------------------------------------------------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "support/pstl_test_config.h"
11 
12 #include <execution>
13 #include <algorithm>
14 
15 #include "support/utils.h"
16 
17 using namespace TestUtils;
18 
19 template <typename Type>
20 struct Gen
21 {
22     Type
23     operator()(std::size_t k)
24     {
25         return Type(k % 5 != 1 ? 3 * k - 7 : 0);
26     };
27 };
28 
29 template <typename T>
30 struct Flip
31 {
32     int32_t val;
33     Flip(int32_t y) : val(y) {}
34     T
35     operator()(T& x) const
36     {
37         return x = val - x;
38     }
39 };
40 
41 struct test_one_policy
42 {
43     template <typename Policy, typename Iterator, typename Size>
44     void
45     operator()(Policy&& exec, Iterator first, Iterator last, Iterator expected_first, Iterator expected_last, Size n)
46     {
47         typedef typename std::iterator_traits<Iterator>::value_type T;
48 
49         // Try for_each
50         std::for_each(expected_first, expected_last, Flip<T>(1));
51         for_each(exec, first, last, Flip<T>(1));
52         EXPECT_EQ_N(expected_first, first, n, "wrong effect from for_each");
53 
54         // Try for_each_n
55         std::for_each_n(pstl::execution::seq, expected_first, n, Flip<T>(1));
56         for_each_n(exec, first, n, Flip<T>(1));
57         EXPECT_EQ_N(expected_first, first, n, "wrong effect from for_each_n");
58     }
59 };
60 
61 template <typename T>
62 void
63 test()
64 {
65     for (size_t n = 0; n <= 100000; n = n <= 16 ? n + 1 : size_t(3.1415 * n))
66     {
67         Sequence<T> inout(n, Gen<T>());
68         Sequence<T> expected(n, Gen<T>());
69         invoke_on_all_policies(test_one_policy(), inout.begin(), inout.end(), expected.begin(), expected.end(),
70                                inout.size());
71     }
72 }
73 
74 struct test_non_const
75 {
76     template <typename Policy, typename Iterator>
77     void
78     operator()(Policy&& exec, Iterator iter)
79     {
80         invoke_if(exec, [&]() {
81             auto f = [](typename std::iterator_traits<Iterator>::reference x) { x = x + 1; };
82 
83             for_each(exec, iter, iter, non_const(f));
84             for_each_n(exec, iter, 0, non_const(f));
85         });
86     }
87 };
88 
89 int32_t
90 main()
91 {
92     test<int32_t>();
93     test<uint16_t>();
94     test<float64_t>();
95 
96     test_algo_basic_single<int32_t>(run_for_rnd_fw<test_non_const>());
97 
98     std::cout << done() << std::endl;
99     return 0;
100 }
101