utils.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*************************************************************************
  2. *
  3. * Copyright (C) 2018-2023 Ruilin Peng (Nick) <[email protected]>.
  4. *
  5. * smartdns is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * smartdns is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef _SMARTDNS_TEST_UTILS_
  19. #define _SMARTDNS_TEST_UTILS_
  20. #include <functional>
  21. namespace smartdns
  22. {
  23. class DeferGuard
  24. {
  25. public:
  26. template <class Callable>
  27. DeferGuard(Callable &&fn) noexcept : fn_(std::forward<Callable>(fn))
  28. {
  29. }
  30. DeferGuard(DeferGuard &&other) noexcept
  31. {
  32. fn_ = std::move(other.fn_);
  33. other.fn_ = nullptr;
  34. }
  35. virtual ~DeferGuard()
  36. {
  37. if (fn_) {
  38. fn_();
  39. }
  40. };
  41. DeferGuard(const DeferGuard &) = delete;
  42. void operator=(const DeferGuard &) = delete;
  43. private:
  44. std::function<void()> fn_;
  45. };
  46. #define SMARTDNS_CONCAT_(a, b) a##b
  47. #define SMARTDNS_CONCAT(a, b) SMARTDNS_CONCAT_(a, b)
  48. #define Defer ::smartdns::DeferGuard SMARTDNS_CONCAT(__defer__, __LINE__) = [&]()
  49. } // namespace smartdns
  50. #endif // _SMARTDNS_TEST_UTILS_