-
Notifications
You must be signed in to change notification settings - Fork 1
/
task.hpp
52 lines (41 loc) · 1.32 KB
/
task.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//
// Created by kobi on 12/29/22.
//
#ifndef JAN_2023_COROUTINES_TASK_HPP
#define JAN_2023_COROUTINES_TASK_HPP
#include <coroutine>
#include <utility> // exchange
#include <cassert>
#include "result.hpp"
namespace example {
class Task {
public:
struct promise_type {
example::result result;
Task get_return_object() { return Task(this); }
void unhandled_exception() noexcept {}
void return_value(example::result res) noexcept { result = res; }
std::suspend_never initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
};
explicit Task(promise_type *promise)
: handle_{HandleT::from_promise(*promise)} {}
Task(Task &&other) noexcept : handle_{std::exchange(other.handle_, nullptr)} {}
~Task() {
if (handle_) {
handle_.destroy();
}
}
[[nodiscard]]
example::result get_result() const & {
assert(handle_.done());
return handle_.promise().result;
}
[[nodiscard]]
bool done() const { return handle_.done(); }
private:
using HandleT = std::coroutine_handle<promise_type>;
HandleT handle_;
};
}
#endif //JAN_2023_COROUTINES_TASK_HPP