8#include <boost/asio/co_spawn.hpp>
9#include <boost/asio/io_context.hpp>
10#include <boost/asio/post.hpp>
11#include <boost/asio/awaitable.hpp>
12#include <boost/asio/use_awaitable.hpp>
13#include <boost/asio/associated_cancellation_slot.hpp>
19namespace asio = boost::asio;
21template<
typename T, std::invocable<Callback<T>> F,
typename CompletionToken>
22auto callbackToAwaitable(F && initiate, CompletionToken && token)
24 return asio::async_initiate<CompletionToken, void(std::future<T>)>(
25 [initiate = std::forward<F>(initiate)](
auto handler)
mutable {
26 auto executor = asio::get_associated_executor(handler);
27 auto done = std::make_shared<std::atomic<bool>>(
false);
28 auto h = std::make_shared<decltype(handler)>(std::move(handler));
30 if (
auto slot = asio::get_associated_cancellation_slot(*h); slot.is_connected()) {
32 std::weak_ptr wdone = done;
33 slot.assign([executor, wh, wdone](asio::cancellation_type ) {
35 auto done = wdone.lock();
36 if (!h || !done || done->exchange(
true))
40 p.set_exception(std::make_exception_ptr(Interrupted(
"interrupted by user")));
41 asio::post(executor, [h, fut = p.get_future()]()
mutable { std::move (*h)(std::move(fut)); });
51 guard = asio::make_work_guard(
52 static_cast<asio::io_context &
>(asio::query(executor, asio::execution::context)))](
53 std::future<T> fut)
mutable {
54 auto releaseOwnership = [&]() {
63 if (done->exchange(
true)) {
71 asio::post(executor, [h, fut = std::move(fut)]()
mutable { std::move (*h)(std::move(fut)); });
75 std::forward<CompletionToken>(token));
83template<
typename T, std::invocable<Callback<T>> F>
84asio::awaitable<T> callbackToAwaitable(F && initiate)
86 auto fut =
co_await callbackToAwaitable<T>(std::forward<F>(initiate), asio::use_awaitable);
90template<
typename Range,
typename F>
91asio::awaitable<void> forEachAsync(Range && range,
const F & f)
95 auto pending = std::ranges::size(range);
98 else if (pending == 1)
99 co_return co_await f(*range.begin());
101 auto executor =
co_await asio::this_coro::executor;
102 std::exception_ptr err;
106 co_await asio::async_initiate<decltype(asio::use_awaitable), void(std::exception_ptr)>(
108 auto h = std::make_shared<decltype(handler)>(std::move(handler));
109 for (
auto && elt : std::forward<Range>(range)) {
110 asio::co_spawn(executor, f(elt), [executor, h, &err, &pending](std::exception_ptr ex) {
115 asio::post(executor, [h = std::move(h), &err]()
mutable { std::move (*h)(err); });
119 asio::use_awaitable);
Definition callback.hh:19