IoService.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /* Copyright 2016, Ableton AG, Berlin. All rights reserved.
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. * If you would like to incorporate Link into a proprietary software application,
  17. * please contact <link-devs@ableton.com>.
  18. */
  19. #pragma once
  20. #include <ableton/util/test/Timer.hpp>
  21. namespace ableton
  22. {
  23. namespace util
  24. {
  25. namespace test
  26. {
  27. struct IoService
  28. {
  29. // Wrapper around the internal util::test::Timer in the list
  30. struct Timer
  31. {
  32. using ErrorCode = test::Timer::ErrorCode;
  33. using TimePoint = test::Timer::TimePoint;
  34. Timer(util::test::Timer* pTimer)
  35. : mpTimer(pTimer)
  36. {
  37. }
  38. void expires_at(std::chrono::system_clock::time_point t) { mpTimer->expires_at(t); }
  39. template <typename T, typename Rep>
  40. void expires_from_now(std::chrono::duration<T, Rep> duration)
  41. {
  42. mpTimer->expires_from_now(duration);
  43. }
  44. ErrorCode cancel() { return mpTimer->cancel(); }
  45. template <typename Handler>
  46. void async_wait(Handler handler)
  47. {
  48. mpTimer->async_wait(std::move(handler));
  49. }
  50. TimePoint now() const { return mpTimer->now(); }
  51. util::test::Timer* mpTimer;
  52. };
  53. IoService() = default;
  54. Timer makeTimer()
  55. {
  56. mTimers.emplace_back();
  57. return Timer{&mTimers.back()};
  58. }
  59. template <typename Handler>
  60. void post(Handler handler)
  61. {
  62. mHandlers.emplace_back(std::move(handler));
  63. }
  64. template <typename T, typename Rep>
  65. void advance(std::chrono::duration<T, Rep> duration)
  66. {
  67. runHandlers();
  68. for (auto& timer : mTimers)
  69. {
  70. timer.advance(duration);
  71. }
  72. }
  73. void runHandlers()
  74. {
  75. for (auto& handler : mHandlers)
  76. {
  77. handler();
  78. }
  79. mHandlers.clear();
  80. }
  81. std::vector<std::function<void()>> mHandlers;
  82. std::vector<util::test::Timer> mTimers;
  83. };
  84. } // namespace test
  85. } // namespace util
  86. } // namespace ableton