folly/futures: use folly::Function to store callback
[folly.git] / folly / futures / test / NonCopyableLambdaTest.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
17 #include <gtest/gtest.h>
18
19 #include <folly/futures/Future.h>
20
21 using namespace folly;
22
23 TEST(NonCopyableLambda, basic) {
24   Promise<int> promise;
25   Future<int> future = promise.getFuture();
26
27   Future<Unit>().then(std::bind(
28       [](Promise<int>& promise) mutable { promise.setValue(123); },
29       std::move(promise)));
30
31   // The previous statement can be simplified in C++14:
32   //  Future<Unit>().then([promise = std::move(promise)]() mutable {
33   //    promise.setValue(123);
34   //  });
35
36   EXPECT_TRUE(future.isReady());
37   EXPECT_EQ(future.get(), 123);
38 }
39
40 TEST(NonCopyableLambda, unique_ptr) {
41   Promise<Unit> promise;
42   auto int_ptr = folly::make_unique<int>(1);
43
44   EXPECT_EQ(*int_ptr, 1);
45
46   auto future = promise.getFuture().then(std::bind(
47       [](std::unique_ptr<int>& int_ptr) mutable {
48         ++*int_ptr;
49         return std::move(int_ptr);
50       },
51       std::move(int_ptr)));
52
53   // The previous statement can be simplified in C++14:
54   //  auto future =
55   //      promise.getFuture().then([int_ptr = std::move(int_ptr)]() mutable {
56   //        ++*int_ptr;
57   //        return std::move(int_ptr);
58   //      });
59
60   EXPECT_FALSE(future.isReady());
61   promise.setValue();
62   EXPECT_TRUE(future.isReady());
63   EXPECT_EQ(*future.get(), 2);
64 }
65
66 TEST(NonCopyableLambda, Function) {
67   Promise<int> promise;
68
69   Function<int(int)> callback = [](int x) { return x + 1; };
70
71   auto future = promise.getFuture().then(std::move(callback));
72   EXPECT_THROW(callback(0), std::bad_function_call);
73
74   EXPECT_FALSE(future.isReady());
75   promise.setValue(100);
76   EXPECT_TRUE(future.isReady());
77   EXPECT_EQ(future.get(), 101);
78 }
79
80 TEST(NonCopyableLambda, FunctionConst) {
81   Promise<int> promise;
82
83   Function<int(int) const> callback = [](int x) { return x + 1; };
84
85   auto future = promise.getFuture().then(std::move(callback));
86   EXPECT_THROW(callback(0), std::bad_function_call);
87
88   EXPECT_FALSE(future.isReady());
89   promise.setValue(100);
90   EXPECT_TRUE(future.isReady());
91   EXPECT_EQ(future.get(), 101);
92 }