xref: /llvm-project/pstl/test/std/algorithms/alg.modifying.operations/generate.pass.cpp (revision 4d88b17b3f282b1023400837c3249c9f27774eca)
1 // -*- C++ -*-
2 //===-- generate.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 <atomic>
13 #include <execution>
14 #include <algorithm>
15 
16 #include "support/utils.h"
17 
18 using namespace TestUtils;
19 
20 template <typename T>
21 struct Generator_count
22 {
23     const T def_val = T(-1);
24     T
25     operator()()
26     {
27         return def_val;
28     }
29     T
30     default_value() const
31     {
32         return def_val;
33     }
34 };
35 
36 struct test_generate
37 {
38     template <typename Policy, typename Iterator, typename Size>
39     void
40     operator()(Policy&& exec, Iterator first, Iterator last, Size n)
41     {
42         using namespace std;
43         typedef typename std::iterator_traits<Iterator>::value_type T;
44 
45         // Try random-access iterator
46         {
47             Generator_count<T> g;
48             generate(exec, first, last, g);
49             EXPECT_TRUE(std::count(first, last, g.default_value()) == n, "generate wrong result for generate");
50             std::fill(first, last, T(0));
51         }
52 
53         {
54             Generator_count<T> g;
55             const auto m = n / 2;
56             auto last = generate_n(exec, first, m, g);
57             EXPECT_TRUE(std::count(first, last, g.default_value()) == m && last == std::next(first, m),
58                         "generate_n wrong result for generate_n");
59             std::fill(first, last, T(0));
60         }
61     }
62 };
63 
64 template <typename T>
65 void
66 test_generate_by_type()
67 {
68     for (size_t n = 0; n <= 100000; n = n < 16 ? n + 1 : size_t(3.1415 * n))
69     {
70         Sequence<T> in(n, [](size_t v) -> T { return T(0); }); //fill by zero
71 
72         invoke_on_all_policies(test_generate(), in.begin(), in.end(), in.size());
73     }
74 }
75 
76 template <typename T>
77 struct test_non_const
78 {
79     template <typename Policy, typename Iterator>
80     void
81     operator()(Policy&& exec, Iterator iter)
82     {
83         auto gen = []() { return T(0); };
84 
85         generate(exec, iter, iter, non_const(gen));
86         generate_n(exec, iter, 0, non_const(gen));
87     }
88 };
89 
90 int32_t
91 main()
92 {
93 
94     test_generate_by_type<int32_t>();
95     test_generate_by_type<float64_t>();
96 
97     test_algo_basic_single<int32_t>(run_for_rnd_fw<test_non_const<int32_t>>());
98 
99     std::cout << done() << std::endl;
100     return 0;
101 }
102