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 #ifdef PSTL_STANDALONE_TESTS 13 #include "pstl/execution" 14 #include "pstl/algorithm" 15 #else 16 #include <execution> 17 #include <algorithm> 18 #endif // PSTL_STANDALONE_TESTS 19 20 #include "support/utils.h" 21 22 using namespace TestUtils; 23 24 template <typename Type> 25 struct Gen 26 { 27 Type 28 operator()(std::size_t k) 29 { 30 return Type(k % 5 != 1 ? 3 * k - 7 : 0); 31 }; 32 }; 33 34 template <typename T> 35 struct Flip 36 { 37 int32_t val; 38 Flip(int32_t y) : val(y) {} 39 T 40 operator()(T& x) const 41 { 42 return x = val - x; 43 } 44 }; 45 46 struct test_one_policy 47 { 48 template <typename Policy, typename Iterator, typename Size> 49 void 50 operator()(Policy&& exec, Iterator first, Iterator last, Iterator expected_first, Iterator expected_last, Size n) 51 { 52 typedef typename std::iterator_traits<Iterator>::value_type T; 53 54 // Try for_each 55 std::for_each(expected_first, expected_last, Flip<T>(1)); 56 for_each(exec, first, last, Flip<T>(1)); 57 EXPECT_EQ_N(expected_first, first, n, "wrong effect from for_each"); 58 59 // Try for_each_n 60 std::for_each_n(pstl::execution::seq, expected_first, n, Flip<T>(1)); 61 for_each_n(exec, first, n, Flip<T>(1)); 62 EXPECT_EQ_N(expected_first, first, n, "wrong effect from for_each_n"); 63 } 64 }; 65 66 template <typename T> 67 void 68 test() 69 { 70 for (size_t n = 0; n <= 100000; n = n <= 16 ? n + 1 : size_t(3.1415 * n)) 71 { 72 Sequence<T> inout(n, Gen<T>()); 73 Sequence<T> expected(n, Gen<T>()); 74 invoke_on_all_policies(test_one_policy(), inout.begin(), inout.end(), expected.begin(), expected.end(), 75 inout.size()); 76 } 77 } 78 79 struct test_non_const 80 { 81 template <typename Policy, typename Iterator> 82 void 83 operator()(Policy&& exec, Iterator iter) 84 { 85 invoke_if(exec, [&]() { 86 auto f = [](typename std::iterator_traits<Iterator>::reference x) { x = x + 1; }; 87 88 for_each(exec, iter, iter, non_const(f)); 89 for_each_n(exec, iter, 0, non_const(f)); 90 }); 91 } 92 }; 93 94 int32_t 95 main() 96 { 97 test<int32_t>(); 98 test<uint16_t>(); 99 test<float64_t>(); 100 101 test_algo_basic_single<int32_t>(run_for_rnd_fw<test_non_const>()); 102 103 std::cout << done() << std::endl; 104 return 0; 105 } 106