6ee8005d21033c10f3e1b1cf1ebda8bcdc6b6e31
[folly.git] / folly / test / IndestructibleTest.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 <folly/Indestructible.h>
18
19 #include <functional>
20 #include <map>
21 #include <memory>
22 #include <string>
23 #include <gtest/gtest.h>
24 #include <folly/Memory.h>
25
26 using namespace std;
27 using namespace folly;
28
29 namespace {
30
31 struct Magic {
32   function<void()> dtor_;
33   function<void()> move_;
34   Magic(function<void()> ctor, function<void()> dtor, function<void()> move)
35       : dtor_(std::move(dtor)), move_(std::move(move)) {
36     ctor();
37   }
38   Magic(Magic&& other) /* may throw */ { *this = std::move(other); }
39   Magic& operator=(Magic&& other) {
40     dtor_ = std::move(other.dtor_);
41     move_ = std::move(other.move_);
42     move_();
43     return *this;
44   }
45   ~Magic() { dtor_(); }
46 };
47
48 class IndestructibleTest : public testing::Test {};
49 }
50
51 TEST_F(IndestructibleTest, access) {
52   static const Indestructible<map<string, int>> data{
53       map<string, int>{{"key1", 17}, {"key2", 19}, {"key3", 23}}};
54
55   auto& m = *data;
56   EXPECT_EQ(19, m.at("key2"));
57 }
58
59 TEST_F(IndestructibleTest, no_destruction) {
60   int state = 0;
61   int value = 0;
62
63   static Indestructible<Magic> sing(
64       [&] {
65         ++state;
66         value = 7;
67       },
68       [&] { state = -1; },
69       [] {});
70   EXPECT_EQ(1, state);
71   EXPECT_EQ(7, value);
72
73   sing.~Indestructible();
74   EXPECT_EQ(1, state);
75 }
76
77 TEST_F(IndestructibleTest, move) {
78   int state = 0;
79   int value = 0;
80   int moves = 0;
81
82   static Indestructible<Magic> sing( // move assignment
83       [&] {
84         ++state;
85         value = 7;
86       },
87       [&] { state = -1; },
88       [&] { ++moves; });
89
90   EXPECT_EQ(1, state);
91   EXPECT_EQ(7, value);
92   EXPECT_EQ(0, moves);
93
94   // move constructor
95   static Indestructible<Magic> move_ctor(std::move(sing));
96   EXPECT_EQ(1, state);
97   EXPECT_EQ(1, moves);
98
99   // move assignment
100   static Indestructible<Magic> move_assign = std::move(move_ctor);
101   EXPECT_EQ(1, state);
102   EXPECT_EQ(2, moves);
103 }