utils.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #include <string>
  22. namespace smartdns
  23. {
  24. class DeferGuard
  25. {
  26. public:
  27. template <class Callable>
  28. DeferGuard(Callable &&fn) noexcept : fn_(std::forward<Callable>(fn))
  29. {
  30. }
  31. DeferGuard(DeferGuard &&other) noexcept
  32. {
  33. fn_ = std::move(other.fn_);
  34. other.fn_ = nullptr;
  35. }
  36. virtual ~DeferGuard()
  37. {
  38. if (fn_) {
  39. fn_();
  40. }
  41. };
  42. DeferGuard(const DeferGuard &) = delete;
  43. void operator=(const DeferGuard &) = delete;
  44. private:
  45. std::function<void()> fn_;
  46. };
  47. #define SMARTDNS_CONCAT_(a, b) a##b
  48. #define SMARTDNS_CONCAT(a, b) SMARTDNS_CONCAT_(a, b)
  49. #define Defer ::smartdns::DeferGuard SMARTDNS_CONCAT(__defer__, __LINE__) = [&]()
  50. bool IsCommandExists(const std::string &cmd);
  51. std::string GenerateRandomString(int len);
  52. } // namespace smartdns
  53. #endif // _SMARTDNS_TEST_UTILS_