Adds writer test case for RCU
[folly.git] / folly / io / async / test / DelayedDestructionBaseTest.cpp
1 /*
2  * Copyright 2015-present 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/io/async/DelayedDestructionBase.h>
18
19 #include <functional>
20
21 #include <folly/portability/GTest.h>
22
23 using namespace folly;
24
25 class DestructionOnCallback : public DelayedDestructionBase {
26  public:
27   DestructionOnCallback() : state_(0), deleted_(false) {
28   }
29
30   void onComplete(int n, int& state) {
31     DestructorGuard dg(this);
32     for (auto i = n; i >= 0; --i) {
33       onStackedComplete(i);
34     }
35     state = state_;
36   }
37
38   int state() const { return state_; }
39   bool deleted() const { return deleted_; }
40
41  protected:
42   void onStackedComplete(int recur) {
43     DestructorGuard dg(this);
44     ++state_;
45     if (recur <= 0) {
46       return;
47     }
48     onStackedComplete(--recur);
49   }
50  private:
51   int state_;
52   bool deleted_;
53
54   void onDelayedDestroy(bool delayed) override {
55     deleted_ = true;
56     delete this;
57     (void)delayed; // prevent unused variable warnings
58   }
59 };
60
61 struct DelayedDestructionBaseTest : public ::testing::Test {
62 };
63
64 TEST_F(DelayedDestructionBaseTest, basic) {
65   DestructionOnCallback* d = new DestructionOnCallback();
66   EXPECT_NE(d, nullptr);
67   int32_t state;
68   d->onComplete(3, state);
69   EXPECT_EQ(state, 10); // 10 = 6 + 3 + 1
70 }