DelayedDestructionBaseTest.cpp 1.7 KB

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