LeviLamina
Loading...
Searching...
No Matches
InterruptableSleep.h
1#pragma once
2
3#include <coroutine>
4
5#include "ll/api/coro/Executor.h"
6
7namespace ll::coro {
9 std::shared_ptr<data::CancellableCallback> sleeped;
10 ExecutorRef exec;
11
12 class DurAwaiter {
14 Duration dur;
15
16 public:
17 template <class R, class P>
18 constexpr DurAwaiter(std::chrono::duration<R, P> dur, InterruptableSleep& s)
19 : self(s),
20 dur(std::chrono::duration_cast<Duration>(dur)) {}
21 template <class C, class D>
22 constexpr DurAwaiter(std::chrono::time_point<C, D> time, InterruptableSleep& s)
23 : SleepAwaiter(time - C::now(), s) {}
24 constexpr void setExecutor(ExecutorRef ex) { self.exec = ex; }
25 constexpr bool await_ready() const noexcept { return dur <= Duration{0}; }
26 void await_suspend(std::coroutine_handle<> handle) { self.sleeped = self.exec->executeAfter(handle, dur); }
27 constexpr void await_resume() const noexcept {}
28 };
29
30 class EtnAwaiter {
32
33 public:
34 constexpr EtnAwaiter(InterruptableSleep& s) : self(s) {}
35 constexpr void setExecutor(ExecutorRef ex) { self.exec = ex; }
36 constexpr bool await_ready() const noexcept { return false; }
37 void await_suspend(std::coroutine_handle<> handle) {
38 self.sleeped = std::make_shared<data::CancellableCallback>(handle);
39 }
40 constexpr void await_resume() const noexcept {}
41 };
42
43public:
45 InterruptableSleep& operator=(InterruptableSleep const&) = delete;
46
47 InterruptableSleep() = default;
48 ~InterruptableSleep() = default;
49
50 template <class R, class P>
51 DurAwaiter sleepFor(std::chrono::duration<R, P> duration) {
52 return {duration, *this};
53 }
54
55 template <class C, class D>
56 DurAwaiter sleepUntil(std::chrono::time_point<C, D> time) {
57 return {time, *this};
58 }
59
60 EtnAwaiter sleep() { return {*this}; }
61
62 bool interrupt(bool inplace = false) {
63 if (auto ptr = std::move(sleeped)) {
64 if (inplace) {
65 return ptr->call();
66 } else {
67 return ptr->moveTo([&](auto&& f) {
68 exec->execute(std::move(f));
69 return true;
70 });
71 }
72 }
73 return false;
74 }
75};
76} // namespace ll::coro
Definition InterruptableSleep.h:8
Definition SleepAwaiter.h:8
Definition optional_ref.h:10