Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Timer.hpp 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 <chrono>
  21. #include <functional>
  22. namespace ableton
  23. {
  24. namespace util
  25. {
  26. namespace test
  27. {
  28. struct Timer
  29. {
  30. using ErrorCode = int;
  31. using TimePoint = std::chrono::system_clock::time_point;
  32. // Initialize timer with an arbitrary large value to simulate the
  33. // time_since_epoch of a real clock.
  34. Timer()
  35. : mNow{std::chrono::milliseconds{123456789}}
  36. {
  37. }
  38. void expires_at(std::chrono::system_clock::time_point t)
  39. {
  40. cancel();
  41. mFireAt = std::move(t);
  42. }
  43. template <typename T, typename Rep>
  44. void expires_from_now(std::chrono::duration<T, Rep> duration)
  45. {
  46. cancel();
  47. mFireAt = now() + duration;
  48. }
  49. ErrorCode cancel()
  50. {
  51. if (mHandler)
  52. {
  53. mHandler(1); // call existing handler with truthy error code
  54. }
  55. mHandler = nullptr;
  56. return 0;
  57. }
  58. template <typename Handler>
  59. void async_wait(Handler handler)
  60. {
  61. mHandler = [handler](ErrorCode ec) { handler(ec); };
  62. }
  63. std::chrono::system_clock::time_point now() const
  64. {
  65. return mNow;
  66. }
  67. template <typename T, typename Rep>
  68. void advance(std::chrono::duration<T, Rep> duration)
  69. {
  70. mNow += duration;
  71. if (mHandler && mFireAt < mNow)
  72. {
  73. mHandler(0);
  74. mHandler = nullptr;
  75. }
  76. }
  77. std::function<void(ErrorCode)> mHandler;
  78. std::chrono::system_clock::time_point mFireAt;
  79. std::chrono::system_clock::time_point mNow;
  80. };
  81. } // namespace test
  82. } // namespace util
  83. } // namespace ableton