blob: ff95f461bfd9502001b880471820b8a33bcc659b [file] [log] [blame]
William A. Kennington IIIece19432023-07-15 03:17:24 -07001#include <function2/function2.hpp>
2#include <stdplus/function_view.hpp>
3
4#include <functional>
5
6#include <gtest/gtest.h>
7
8namespace stdplus
9{
10
11int add(int a, int b)
12{
13 return a + b;
14}
15
16int mul(int a, int b) noexcept
17{
18 return a * b;
19}
20
21struct Funcy
22{
23 int a = 0;
24
25 int operator()(float y) noexcept
26 {
27 return a += (int)y;
28 }
29
30 int operator()(int b) noexcept
31 {
32 return a += b;
33 }
34};
35
36struct FuncyPriv : private Funcy
37{
38 using Funcy::operator();
39};
40
41int callFv(stdplus::function_view<int(int, int)> fv)
42{
43 return fv(3, 5);
44}
45
46TEST(FunctionView, Ptr)
47{
48 function_view<int(int, int)> fv = add;
49 EXPECT_EQ(3, fv(1, 2));
50 EXPECT_EQ(14, fv(5, 9));
51 fv = mul;
52 EXPECT_EQ(14, fv(7, 2));
53 EXPECT_EQ(0, fv(0, 10));
54 function_view fv2 = add;
55 EXPECT_EQ(1, fv2(1, 0));
56
57 EXPECT_EQ(8, callFv(add));
58}
59
60TEST(FunctionView, Obj)
61{
62 Funcy f;
63 function_view<int(int)> fv = f;
64 EXPECT_EQ(2, fv(2));
65 EXPECT_EQ(5, fv(3));
66
67 FuncyPriv fp;
68 fv = fp;
69 EXPECT_EQ(2, fv(2));
70 EXPECT_EQ(5, fv(3));
71}
72
73TEST(FunctionView, Lambda)
74{
75 auto addl = [](int a, int b) { return a + b; };
76 function_view<int(int, int)> fv = addl;
77 EXPECT_EQ(3, fv(1, 2));
78 EXPECT_EQ(14, fv(5, 9));
79 function_view fv2 = addl;
80 EXPECT_EQ(1, fv2(1, 0));
81 fv = fv2;
82 EXPECT_EQ(1, fv(1, 0));
83 function_view<int(int, int) const> fv3 = addl;
84 EXPECT_EQ(1, fv3(1, 0));
85
86 auto mull = [old = 1](int a) mutable { return old *= a; };
87 function_view fvm = mull;
88 EXPECT_EQ(2, fvm(2));
89 EXPECT_EQ(4, fvm(2));
90
91 auto mula = [](auto a, auto b) { return a + b; };
92 fv = mula;
93 EXPECT_EQ(5, fv(3, 2));
94
95 EXPECT_EQ(8, callFv([](auto a, auto b) { return a + b; }));
96}
97
98TEST(FunctionView, StdFunction)
99{
100 std::function<int(int, int)> addf = add;
101 function_view<int(int, int)> fv = addf;
102 EXPECT_EQ(3, fv(1, 2));
103 EXPECT_EQ(14, fv(5, 9));
104 {
105 function_view fv2 = addf;
106 EXPECT_EQ(1, fv2(1, 0));
107 fv = fv2;
108 }
109 EXPECT_EQ(6, fv(3, 3));
110
111 fu2::unique_function<int(int, int) const noexcept> mulf = mul;
112 function_view<int(int, int) const> fv2 = mulf;
113 EXPECT_EQ(2, fv2(1, 2));
114
115 fu2::unique_function<int(int)> mulfa = [old = 1](auto a) mutable {
116 return old *= a;
117 };
118 function_view<int(int)> fva = mulfa;
119 EXPECT_EQ(3, fva(3));
120 EXPECT_EQ(9, fva(3));
121}
122
123} // namespace stdplus