ravel
Deterministic simulation testing for C++. Seed a bug, replay it exact.
Loading...
Searching...
No Matches
task.hpp
1#pragma once
2
3#include <coroutine>
4#include <exception>
5#include <utility>
6
7namespace ravel {
8
19class Task {
20 public:
21 struct promise_type {
22 Task get_return_object() noexcept {
23 return Task(std::coroutine_handle<promise_type>::from_promise(*this));
24 }
25 std::suspend_always initial_suspend() const noexcept { return {}; }
26 std::suspend_always final_suspend() const noexcept { return {}; }
27 void return_void() const noexcept {}
28 void unhandled_exception() noexcept { exception = std::current_exception(); }
29
30 std::exception_ptr exception;
31 };
32
33 Task() noexcept = default;
35 Task(Task&& other) noexcept : handle_(std::exchange(other.handle_, {})) {}
37 Task& operator=(Task&& other) noexcept {
38 if (this != &other) {
39 destroy();
40 handle_ = std::exchange(other.handle_, {});
41 }
42 return *this;
43 }
44 Task(const Task&) = delete;
45 Task& operator=(const Task&) = delete;
46 ~Task() { destroy(); }
47
50 bool done() const noexcept { return !handle_ || handle_.done(); }
51
53 void resume() { handle_.resume(); }
54
56 std::exception_ptr exception() const noexcept {
57 return handle_ ? handle_.promise().exception : nullptr;
58 }
59
60 private:
61 explicit Task(std::coroutine_handle<promise_type> handle) noexcept : handle_(handle) {}
62
63 void destroy() noexcept {
64 if (handle_) handle_.destroy();
65 handle_ = {};
66 }
67
68 std::coroutine_handle<promise_type> handle_;
69};
70
71} // namespace ravel
The coroutine type for simulated tasks.
Definition task.hpp:19
bool done() const noexcept
True once the coroutine ran to completion or threw.
Definition task.hpp:50
std::exception_ptr exception() const noexcept
The exception that escaped the coroutine body, if any.
Definition task.hpp:56
Task & operator=(Task &&other) noexcept
Tasks are move-only: a Task owns its coroutine.
Definition task.hpp:37
Task(Task &&other) noexcept
Tasks are move-only: a Task owns its coroutine.
Definition task.hpp:35
void resume()
Runs the coroutine to its next suspension point.
Definition task.hpp:53