Skip to content

Instantly share code, notes, and snippets.

@jamboree
Created August 29, 2017 05:10
Show Gist options
  • Save jamboree/fa0837bc328da27e90b1121cbfbe502c to your computer and use it in GitHub Desktop.
Save jamboree/fa0837bc328da27e90b1121cbfbe502c to your computer and use it in GitHub Desktop.
suspend awaiter for Coroutine-TS
namespace stdex = std::experimental;
class unique_coroutine
{
stdex::coroutine_handle<> _h;
public:
explicit unique_coroutine(stdex::coroutine_handle<> h) noexcept : _h(h) {}
unique_coroutine(unique_coroutine&& other) noexcept : _h(other._h) { other._h = nullptr; }
~unique_coroutine()
{
if (_h)
_h.destroy();
}
unique_coroutine& operator=(unique_coroutine&& other) noexcept
{
reset(other._h);
other._h = nullptr;
return *this;
}
void reset(stdex::coroutine_handle<> handle) noexcept
{
if (_h)
_h.destroy();
_h = handle;
}
void operator()() noexcept
{
_h();
_h = nullptr;
}
};
template<class F>
auto suspend(F f)
{
struct awaiter
{
F f;
bool await_ready() const
{
return false;
}
void await_suspend(stdex::coroutine_handle<> h)
{
unique_coroutine coro(h);
f(coro);
}
void await_resume() const {}
};
return awaiter{std::move(f)};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment