Fix SimpleBarrier
[folly.git] / folly / test / LazyTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/Lazy.h>
17
18 #include <map>
19 #include <functional>
20 #include <iostream>
21
22 #include <folly/portability/GTest.h>
23
24 namespace folly {
25
26 TEST(Lazy, Simple) {
27   int computeCount = 0;
28
29   auto const val = folly::lazy([&]() -> int {
30     ++computeCount;
31     EXPECT_EQ(computeCount, 1);
32     return 12;
33   });
34   EXPECT_EQ(computeCount, 0);
35
36   for (int i = 0; i < 100; ++i) {
37     if (i > 50) {
38       EXPECT_EQ(val(), 12);
39       EXPECT_EQ(computeCount, 1);
40     } else {
41       EXPECT_EQ(computeCount, 0);
42     }
43   }
44   EXPECT_EQ(val(), 12);
45   EXPECT_EQ(computeCount, 1);
46 }
47
48 auto globalCount = folly::lazy([]{ return 0; });
49 auto const foo = folly::lazy([]() -> std::string {
50   ++globalCount();
51   EXPECT_EQ(globalCount(), 1);
52   return std::string("YEP");
53 });
54
55 TEST(Lazy, Global) {
56   EXPECT_EQ(globalCount(), 0);
57   EXPECT_EQ(foo(), "YEP");
58   EXPECT_EQ(globalCount(), 1);
59 }
60
61 TEST(Lazy, Map) {
62   auto lazyMap = folly::lazy([]() -> std::map<std::string,std::string> {
63     return {
64       { "foo", "bar" },
65       { "baz", "quux" }
66     };
67   });
68
69   EXPECT_EQ(lazyMap().size(), 2);
70   lazyMap()["blah"] = "asd";
71   EXPECT_EQ(lazyMap().size(), 3);
72 }
73
74 struct CopyCount {
75   CopyCount() {}
76   CopyCount(const CopyCount&) { ++count; }
77   CopyCount(CopyCount&&) noexcept {}
78
79   static int count;
80
81   bool operator()() const { return true ; }
82 };
83
84 int CopyCount::count = 0;
85
86 TEST(Lazy, NonLambda) {
87   auto const rval = folly::lazy(CopyCount());
88   EXPECT_EQ(CopyCount::count, 0);
89   EXPECT_EQ(rval(), true);
90   EXPECT_EQ(CopyCount::count, 0);
91
92   CopyCount cpy;
93   auto const lval = folly::lazy(cpy);
94   EXPECT_EQ(CopyCount::count, 1);
95   EXPECT_EQ(lval(), true);
96   EXPECT_EQ(CopyCount::count, 1);
97
98   std::function<bool()> f = [&]{ return 12; };
99   auto const lazyF = folly::lazy(f);
100   EXPECT_EQ(lazyF(), true);
101 }
102
103 TEST(Lazy, Consty) {
104   std::function<int ()> const f = [&] { return 12; };
105   auto lz = folly::lazy(f);
106   EXPECT_EQ(lz(), 12);
107 }
108
109 }