1 /*
2 * Copyright 2018 Google LLC
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 "fcp/base/move_to_lambda.h"
18
19 #include "gmock/gmock.h"
20 #include "gtest/gtest.h"
21 #include "fcp/base/unique_value.h"
22
23 namespace fcp {
24
25 using ::testing::Eq;
26
TEST(MoveToLambda,Basic)27 TEST(MoveToLambda, Basic) {
28 auto capture = MoveToLambda(UniqueValue<int>{123});
29 auto lambda = [capture]() {
30 EXPECT_TRUE(capture->has_value()) << "Should have moved the original";
31 return **capture;
32 };
33
34 int returned = lambda();
35 EXPECT_FALSE(capture->has_value()) << "Should have moved the original";
36 EXPECT_THAT(returned, Eq(123));
37
38 int returned_again = lambda();
39 EXPECT_THAT(returned_again, Eq(123)) << "Usage shouldn't be destructive";
40 }
41
TEST(MoveToLambda,Mutable)42 TEST(MoveToLambda, Mutable) {
43 auto capture = MoveToLambda(UniqueValue<int>{0});
44 auto counter = [capture]() mutable {
45 EXPECT_TRUE(capture->has_value()) << "Should have moved the original";
46 return (**capture)++;
47 };
48
49 EXPECT_FALSE(capture->has_value()) << "Should have moved the original";
50
51 EXPECT_THAT(counter(), Eq(0));
52 EXPECT_THAT(counter(), Eq(1));
53 EXPECT_THAT(counter(), Eq(2));
54 }
55
56 } // namespace fcp
57