coro.hpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. //
  2. // experimental/impl/coro.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2021-2023 Klemens D. Morgenstern
  6. // (klemens dot morgenstern at gmx dot net)
  7. //
  8. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. #ifndef BOOST_ASIO_EXPERIMENTAL_IMPL_CORO_HPP
  12. #define BOOST_ASIO_EXPERIMENTAL_IMPL_CORO_HPP
  13. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  14. # pragma once
  15. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  16. #include <boost/asio/detail/config.hpp>
  17. #include <boost/asio/append.hpp>
  18. #include <boost/asio/associated_cancellation_slot.hpp>
  19. #include <boost/asio/bind_allocator.hpp>
  20. #include <boost/asio/deferred.hpp>
  21. #include <boost/asio/experimental/detail/coro_completion_handler.hpp>
  22. #include <boost/asio/detail/push_options.hpp>
  23. namespace boost {
  24. namespace asio {
  25. namespace experimental {
  26. template <typename Yield, typename Return,
  27. typename Executor, typename Allocator>
  28. struct coro;
  29. namespace detail {
  30. struct coro_cancellation_source
  31. {
  32. cancellation_slot slot;
  33. cancellation_state state;
  34. bool throw_if_cancelled_ = true;
  35. void reset_cancellation_state()
  36. {
  37. state = cancellation_state(slot);
  38. }
  39. template <typename Filter>
  40. void reset_cancellation_state(Filter&& filter)
  41. {
  42. state = cancellation_state(slot, static_cast<Filter&&>(filter));
  43. }
  44. template <typename InFilter, typename OutFilter>
  45. void reset_cancellation_state(InFilter&& in_filter,
  46. OutFilter&& out_filter)
  47. {
  48. state = cancellation_state(slot,
  49. static_cast<InFilter&&>(in_filter),
  50. static_cast<OutFilter&&>(out_filter));
  51. }
  52. bool throw_if_cancelled() const
  53. {
  54. return throw_if_cancelled_;
  55. }
  56. void throw_if_cancelled(bool value)
  57. {
  58. throw_if_cancelled_ = value;
  59. }
  60. };
  61. template <typename Signature, typename Return,
  62. typename Executor, typename Allocator>
  63. struct coro_promise;
  64. template <typename T>
  65. struct is_noexcept : std::false_type
  66. {
  67. };
  68. template <typename Return, typename... Args>
  69. struct is_noexcept<Return(Args...)> : std::false_type
  70. {
  71. };
  72. template <typename Return, typename... Args>
  73. struct is_noexcept<Return(Args...) noexcept> : std::true_type
  74. {
  75. };
  76. template <typename T>
  77. constexpr bool is_noexcept_v = is_noexcept<T>::value;
  78. template <typename T>
  79. struct coro_error;
  80. template <>
  81. struct coro_error<boost::system::error_code>
  82. {
  83. static boost::system::error_code invalid()
  84. {
  85. return boost::asio::error::fault;
  86. }
  87. static boost::system::error_code cancelled()
  88. {
  89. return boost::asio::error::operation_aborted;
  90. }
  91. static boost::system::error_code interrupted()
  92. {
  93. return boost::asio::error::interrupted;
  94. }
  95. static boost::system::error_code done()
  96. {
  97. return boost::asio::error::broken_pipe;
  98. }
  99. };
  100. template <>
  101. struct coro_error<std::exception_ptr>
  102. {
  103. static std::exception_ptr invalid()
  104. {
  105. return std::make_exception_ptr(
  106. boost::system::system_error(
  107. coro_error<boost::system::error_code>::invalid()));
  108. }
  109. static std::exception_ptr cancelled()
  110. {
  111. return std::make_exception_ptr(
  112. boost::system::system_error(
  113. coro_error<boost::system::error_code>::cancelled()));
  114. }
  115. static std::exception_ptr interrupted()
  116. {
  117. return std::make_exception_ptr(
  118. boost::system::system_error(
  119. coro_error<boost::system::error_code>::interrupted()));
  120. }
  121. static std::exception_ptr done()
  122. {
  123. return std::make_exception_ptr(
  124. boost::system::system_error(
  125. coro_error<boost::system::error_code>::done()));
  126. }
  127. };
  128. template <typename T, typename Coroutine >
  129. struct coro_with_arg
  130. {
  131. using coro_t = Coroutine;
  132. T value;
  133. coro_t& coro;
  134. struct awaitable_t
  135. {
  136. T value;
  137. coro_t& coro;
  138. constexpr static bool await_ready() { return false; }
  139. template <typename Y, typename R, typename E, typename A>
  140. auto await_suspend(coroutine_handle<coro_promise<Y, R, E, A>> h)
  141. -> coroutine_handle<>
  142. {
  143. auto& hp = h.promise();
  144. if constexpr (!coro_promise<Y, R, E, A>::is_noexcept)
  145. {
  146. if ((hp.cancel->state.cancelled() != cancellation_type::none)
  147. && hp.cancel->throw_if_cancelled_)
  148. {
  149. boost::asio::detail::throw_error(
  150. boost::asio::error::operation_aborted, "coro-cancelled");
  151. }
  152. }
  153. if (hp.get_executor() == coro.get_executor())
  154. {
  155. coro.coro_->awaited_from = h;
  156. coro.coro_->reset_error();
  157. coro.coro_->input_ = std::move(value);
  158. coro.coro_->cancel = hp.cancel;
  159. return coro.coro_->get_handle();
  160. }
  161. else
  162. {
  163. coro.coro_->awaited_from =
  164. dispatch_coroutine(
  165. boost::asio::prefer(hp.get_executor(),
  166. execution::outstanding_work.tracked),
  167. [h]() mutable { h.resume(); }).handle;
  168. coro.coro_->reset_error();
  169. coro.coro_->input_ = std::move(value);
  170. struct cancel_handler
  171. {
  172. using src = std::pair<cancellation_signal,
  173. detail::coro_cancellation_source>;
  174. std::shared_ptr<src> st = std::make_shared<src>();
  175. cancel_handler(E e, coro_t& coro) : e(e), coro_(coro.coro_)
  176. {
  177. st->second.state =
  178. cancellation_state(st->second.slot = st->first.slot());
  179. }
  180. E e;
  181. typename coro_t::promise_type* coro_;
  182. void operator()(cancellation_type ct)
  183. {
  184. boost::asio::dispatch(e, [ct, st = st]() mutable
  185. {
  186. auto & [sig, state] = *st;
  187. sig.emit(ct);
  188. });
  189. }
  190. };
  191. if (hp.cancel->state.slot().is_connected())
  192. {
  193. hp.cancel->state.slot().template emplace<cancel_handler>(
  194. coro.get_executor(), coro);
  195. }
  196. auto hh = detail::coroutine_handle<
  197. typename coro_t::promise_type>::from_promise(*coro.coro_);
  198. return dispatch_coroutine(
  199. coro.coro_->get_executor(), [hh]() mutable { hh.resume(); }).handle;
  200. }
  201. }
  202. auto await_resume() -> typename coro_t::result_type
  203. {
  204. coro.coro_->cancel = nullptr;
  205. coro.coro_->rethrow_if();
  206. return std::move(coro.coro_->result_);
  207. }
  208. };
  209. template <typename CompletionToken>
  210. auto async_resume(CompletionToken&& token) &&
  211. {
  212. return coro.async_resume(std::move(value),
  213. std::forward<CompletionToken>(token));
  214. }
  215. auto operator co_await() &&
  216. {
  217. return awaitable_t{std::move(value), coro};
  218. }
  219. };
  220. template <bool IsNoexcept>
  221. struct coro_promise_error;
  222. template <>
  223. struct coro_promise_error<false>
  224. {
  225. std::exception_ptr error_;
  226. void reset_error()
  227. {
  228. error_ = std::exception_ptr{};
  229. }
  230. void unhandled_exception()
  231. {
  232. error_ = std::current_exception();
  233. }
  234. void rethrow_if()
  235. {
  236. if (error_)
  237. std::rethrow_exception(error_);
  238. }
  239. };
  240. #if defined(__GNUC__)
  241. # pragma GCC diagnostic push
  242. # if defined(__clang__)
  243. # pragma GCC diagnostic ignored "-Wexceptions"
  244. # else
  245. # pragma GCC diagnostic ignored "-Wterminate"
  246. # endif
  247. #elif defined(_MSC_VER)
  248. # pragma warning(push)
  249. # pragma warning (disable:4297)
  250. #endif
  251. template <>
  252. struct coro_promise_error<true>
  253. {
  254. void reset_error()
  255. {
  256. }
  257. void unhandled_exception() noexcept
  258. {
  259. throw;
  260. }
  261. void rethrow_if()
  262. {
  263. }
  264. };
  265. #if defined(__GNUC__)
  266. # pragma GCC diagnostic pop
  267. #elif defined(_MSC_VER)
  268. # pragma warning(pop)
  269. #endif
  270. template <typename T = void>
  271. struct yield_input
  272. {
  273. T& value;
  274. coroutine_handle<> awaited_from{noop_coroutine()};
  275. bool await_ready() const noexcept
  276. {
  277. return false;
  278. }
  279. template <typename U>
  280. coroutine_handle<> await_suspend(coroutine_handle<U>) noexcept
  281. {
  282. return std::exchange(awaited_from, noop_coroutine());
  283. }
  284. T await_resume() const noexcept
  285. {
  286. return std::move(value);
  287. }
  288. };
  289. template <>
  290. struct yield_input<void>
  291. {
  292. coroutine_handle<> awaited_from{noop_coroutine()};
  293. bool await_ready() const noexcept
  294. {
  295. return false;
  296. }
  297. auto await_suspend(coroutine_handle<>) noexcept
  298. {
  299. return std::exchange(awaited_from, noop_coroutine());
  300. }
  301. constexpr void await_resume() const noexcept
  302. {
  303. }
  304. };
  305. struct coro_awaited_from
  306. {
  307. coroutine_handle<> awaited_from{noop_coroutine()};
  308. auto final_suspend() noexcept
  309. {
  310. struct suspendor
  311. {
  312. coroutine_handle<> awaited_from;
  313. constexpr static bool await_ready() noexcept
  314. {
  315. return false;
  316. }
  317. auto await_suspend(coroutine_handle<>) noexcept
  318. {
  319. return std::exchange(awaited_from, noop_coroutine());
  320. }
  321. constexpr static void await_resume() noexcept
  322. {
  323. }
  324. };
  325. return suspendor{std::exchange(awaited_from, noop_coroutine())};
  326. }
  327. ~coro_awaited_from()
  328. {
  329. awaited_from.resume();
  330. }//must be on the right executor
  331. };
  332. template <typename Yield, typename Input, typename Return>
  333. struct coro_promise_exchange : coro_awaited_from
  334. {
  335. using result_type = coro_result_t<Yield, Return>;
  336. result_type result_;
  337. Input input_;
  338. auto yield_value(Yield&& y)
  339. {
  340. result_ = std::move(y);
  341. return yield_input<Input>{std::move(input_),
  342. std::exchange(awaited_from, noop_coroutine())};
  343. }
  344. auto yield_value(const Yield& y)
  345. {
  346. result_ = y;
  347. return yield_input<Input>{std::move(input_),
  348. std::exchange(awaited_from, noop_coroutine())};
  349. }
  350. void return_value(const Return& r)
  351. {
  352. result_ = r;
  353. }
  354. void return_value(Return&& r)
  355. {
  356. result_ = std::move(r);
  357. }
  358. };
  359. template <typename YieldReturn>
  360. struct coro_promise_exchange<YieldReturn, void, YieldReturn> : coro_awaited_from
  361. {
  362. using result_type = coro_result_t<YieldReturn, YieldReturn>;
  363. result_type result_;
  364. auto yield_value(const YieldReturn& y)
  365. {
  366. result_ = y;
  367. return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
  368. }
  369. auto yield_value(YieldReturn&& y)
  370. {
  371. result_ = std::move(y);
  372. return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
  373. }
  374. void return_value(const YieldReturn& r)
  375. {
  376. result_ = r;
  377. }
  378. void return_value(YieldReturn&& r)
  379. {
  380. result_ = std::move(r);
  381. }
  382. };
  383. template <typename Yield, typename Return>
  384. struct coro_promise_exchange<Yield, void, Return> : coro_awaited_from
  385. {
  386. using result_type = coro_result_t<Yield, Return>;
  387. result_type result_;
  388. auto yield_value(const Yield& y)
  389. {
  390. result_.template emplace<0>(y);
  391. return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
  392. }
  393. auto yield_value(Yield&& y)
  394. {
  395. result_.template emplace<0>(std::move(y));
  396. return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
  397. }
  398. void return_value(const Return& r)
  399. {
  400. result_.template emplace<1>(r);
  401. }
  402. void return_value(Return&& r)
  403. {
  404. result_.template emplace<1>(std::move(r));
  405. }
  406. };
  407. template <typename Yield, typename Input>
  408. struct coro_promise_exchange<Yield, Input, void> : coro_awaited_from
  409. {
  410. using result_type = coro_result_t<Yield, void>;
  411. result_type result_;
  412. Input input_;
  413. auto yield_value(Yield&& y)
  414. {
  415. result_ = std::move(y);
  416. return yield_input<Input>{input_,
  417. std::exchange(awaited_from, noop_coroutine())};
  418. }
  419. auto yield_value(const Yield& y)
  420. {
  421. result_ = y;
  422. return yield_input<Input>{input_,
  423. std::exchange(awaited_from, noop_coroutine())};
  424. }
  425. void return_void()
  426. {
  427. result_.reset();
  428. }
  429. };
  430. template <typename Return>
  431. struct coro_promise_exchange<void, void, Return> : coro_awaited_from
  432. {
  433. using result_type = coro_result_t<void, Return>;
  434. result_type result_;
  435. void yield_value();
  436. void return_value(const Return& r)
  437. {
  438. result_ = r;
  439. }
  440. void return_value(Return&& r)
  441. {
  442. result_ = std::move(r);
  443. }
  444. };
  445. template <>
  446. struct coro_promise_exchange<void, void, void> : coro_awaited_from
  447. {
  448. void return_void() {}
  449. void yield_value();
  450. };
  451. template <typename Yield>
  452. struct coro_promise_exchange<Yield, void, void> : coro_awaited_from
  453. {
  454. using result_type = coro_result_t<Yield, void>;
  455. result_type result_;
  456. auto yield_value(const Yield& y)
  457. {
  458. result_ = y;
  459. return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
  460. }
  461. auto yield_value(Yield&& y)
  462. {
  463. result_ = std::move(y);
  464. return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
  465. }
  466. void return_void()
  467. {
  468. result_.reset();
  469. }
  470. };
  471. template <typename Yield, typename Return,
  472. typename Executor, typename Allocator>
  473. struct coro_promise final :
  474. coro_promise_allocator<Allocator>,
  475. coro_promise_error<coro_traits<Yield, Return, Executor>::is_noexcept>,
  476. coro_promise_exchange<
  477. typename coro_traits<Yield, Return, Executor>::yield_type,
  478. typename coro_traits<Yield, Return, Executor>::input_type,
  479. typename coro_traits<Yield, Return, Executor>::return_type>
  480. {
  481. using coro_type = coro<Yield, Return, Executor, Allocator>;
  482. auto handle()
  483. {
  484. return coroutine_handle<coro_promise>::from_promise(this);
  485. }
  486. using executor_type = Executor;
  487. executor_type executor_;
  488. std::optional<coro_cancellation_source> cancel_source;
  489. coro_cancellation_source * cancel;
  490. using cancellation_slot_type = boost::asio::cancellation_slot;
  491. cancellation_slot_type get_cancellation_slot() const noexcept
  492. {
  493. return cancel ? cancel->state.slot() : cancellation_slot_type{};
  494. }
  495. using allocator_type =
  496. typename std::allocator_traits<associated_allocator_t<Executor>>::
  497. template rebind_alloc<std::byte>;
  498. using traits = coro_traits<Yield, Return, Executor>;
  499. using input_type = typename traits::input_type;
  500. using yield_type = typename traits::yield_type;
  501. using return_type = typename traits::return_type;
  502. using error_type = typename traits::error_type;
  503. using result_type = typename traits::result_type;
  504. constexpr static bool is_noexcept = traits::is_noexcept;
  505. auto get_executor() const -> Executor
  506. {
  507. return executor_;
  508. }
  509. auto get_handle()
  510. {
  511. return coroutine_handle<coro_promise>::from_promise(*this);
  512. }
  513. template <typename... Args>
  514. coro_promise(Executor executor, Args&&... args) noexcept
  515. : coro_promise_allocator<Allocator>(
  516. executor, std::forward<Args>(args)...),
  517. executor_(std::move(executor))
  518. {
  519. }
  520. template <typename First, typename... Args>
  521. coro_promise(First&& f, Executor executor, Args&&... args) noexcept
  522. : coro_promise_allocator<Allocator>(
  523. f, executor, std::forward<Args>(args)...),
  524. executor_(std::move(executor))
  525. {
  526. }
  527. template <typename First, detail::execution_context Context, typename... Args>
  528. coro_promise(First&& f, Context&& ctx, Args&&... args) noexcept
  529. : coro_promise_allocator<Allocator>(
  530. f, ctx, std::forward<Args>(args)...),
  531. executor_(ctx.get_executor())
  532. {
  533. }
  534. template <detail::execution_context Context, typename... Args>
  535. coro_promise(Context&& ctx, Args&&... args) noexcept
  536. : coro_promise_allocator<Allocator>(
  537. ctx, std::forward<Args>(args)...),
  538. executor_(ctx.get_executor())
  539. {
  540. }
  541. auto get_return_object()
  542. {
  543. return coro<Yield, Return, Executor, Allocator>{this};
  544. }
  545. auto initial_suspend() noexcept
  546. {
  547. return suspend_always{};
  548. }
  549. using coro_promise_exchange<
  550. typename coro_traits<Yield, Return, Executor>::yield_type,
  551. typename coro_traits<Yield, Return, Executor>::input_type,
  552. typename coro_traits<Yield, Return, Executor>::return_type>::yield_value;
  553. auto await_transform(this_coro::executor_t) const
  554. {
  555. struct exec_helper
  556. {
  557. const executor_type& value;
  558. constexpr static bool await_ready() noexcept
  559. {
  560. return true;
  561. }
  562. constexpr static void await_suspend(coroutine_handle<>) noexcept
  563. {
  564. }
  565. executor_type await_resume() const noexcept
  566. {
  567. return value;
  568. }
  569. };
  570. return exec_helper{executor_};
  571. }
  572. auto await_transform(this_coro::cancellation_state_t) const
  573. {
  574. struct exec_helper
  575. {
  576. const boost::asio::cancellation_state& value;
  577. constexpr static bool await_ready() noexcept
  578. {
  579. return true;
  580. }
  581. constexpr static void await_suspend(coroutine_handle<>) noexcept
  582. {
  583. }
  584. boost::asio::cancellation_state await_resume() const noexcept
  585. {
  586. return value;
  587. }
  588. };
  589. assert(cancel);
  590. return exec_helper{cancel->state};
  591. }
  592. // This await transformation resets the associated cancellation state.
  593. auto await_transform(this_coro::reset_cancellation_state_0_t) noexcept
  594. {
  595. struct result
  596. {
  597. detail::coro_cancellation_source * src_;
  598. bool await_ready() const noexcept
  599. {
  600. return true;
  601. }
  602. void await_suspend(coroutine_handle<void>) noexcept
  603. {
  604. }
  605. auto await_resume() const
  606. {
  607. return src_->reset_cancellation_state();
  608. }
  609. };
  610. return result{cancel};
  611. }
  612. // This await transformation resets the associated cancellation state.
  613. template <typename Filter>
  614. auto await_transform(
  615. this_coro::reset_cancellation_state_1_t<Filter> reset) noexcept
  616. {
  617. struct result
  618. {
  619. detail::coro_cancellation_source* src_;
  620. Filter filter_;
  621. bool await_ready() const noexcept
  622. {
  623. return true;
  624. }
  625. void await_suspend(coroutine_handle<void>) noexcept
  626. {
  627. }
  628. auto await_resume()
  629. {
  630. return src_->reset_cancellation_state(
  631. static_cast<Filter&&>(filter_));
  632. }
  633. };
  634. return result{cancel, static_cast<Filter&&>(reset.filter)};
  635. }
  636. // This await transformation resets the associated cancellation state.
  637. template <typename InFilter, typename OutFilter>
  638. auto await_transform(
  639. this_coro::reset_cancellation_state_2_t<InFilter, OutFilter> reset)
  640. noexcept
  641. {
  642. struct result
  643. {
  644. detail::coro_cancellation_source* src_;
  645. InFilter in_filter_;
  646. OutFilter out_filter_;
  647. bool await_ready() const noexcept
  648. {
  649. return true;
  650. }
  651. void await_suspend(coroutine_handle<void>) noexcept
  652. {
  653. }
  654. auto await_resume()
  655. {
  656. return src_->reset_cancellation_state(
  657. static_cast<InFilter&&>(in_filter_),
  658. static_cast<OutFilter&&>(out_filter_));
  659. }
  660. };
  661. return result{cancel,
  662. static_cast<InFilter&&>(reset.in_filter),
  663. static_cast<OutFilter&&>(reset.out_filter)};
  664. }
  665. // This await transformation determines whether cancellation is propagated as
  666. // an exception.
  667. auto await_transform(this_coro::throw_if_cancelled_0_t) noexcept
  668. requires (!is_noexcept)
  669. {
  670. struct result
  671. {
  672. detail::coro_cancellation_source* src_;
  673. bool await_ready() const noexcept
  674. {
  675. return true;
  676. }
  677. void await_suspend(coroutine_handle<void>) noexcept
  678. {
  679. }
  680. auto await_resume()
  681. {
  682. return src_->throw_if_cancelled();
  683. }
  684. };
  685. return result{cancel};
  686. }
  687. // This await transformation sets whether cancellation is propagated as an
  688. // exception.
  689. auto await_transform(
  690. this_coro::throw_if_cancelled_1_t throw_if_cancelled) noexcept
  691. requires (!is_noexcept)
  692. {
  693. struct result
  694. {
  695. detail::coro_cancellation_source* src_;
  696. bool value_;
  697. bool await_ready() const noexcept
  698. {
  699. return true;
  700. }
  701. void await_suspend(coroutine_handle<void>) noexcept
  702. {
  703. }
  704. auto await_resume()
  705. {
  706. src_->throw_if_cancelled(value_);
  707. }
  708. };
  709. return result{cancel, throw_if_cancelled.value};
  710. }
  711. template <typename Yield_, typename Return_,
  712. typename Executor_, typename Allocator_>
  713. auto await_transform(coro<Yield_, Return_, Executor_, Allocator_>& kr)
  714. -> decltype(auto)
  715. {
  716. return kr;
  717. }
  718. template <typename Yield_, typename Return_,
  719. typename Executor_, typename Allocator_>
  720. auto await_transform(coro<Yield_, Return_, Executor_, Allocator_>&& kr)
  721. {
  722. return std::move(kr);
  723. }
  724. template <typename T_, typename Coroutine >
  725. auto await_transform(coro_with_arg<T_, Coroutine>&& kr) -> decltype(auto)
  726. {
  727. return std::move(kr);
  728. }
  729. template <typename T_>
  730. requires requires(T_ t) {{ t.async_wait(deferred) }; }
  731. auto await_transform(T_& t) -> decltype(auto)
  732. {
  733. return await_transform(t.async_wait(deferred));
  734. }
  735. template <typename Op>
  736. auto await_transform(Op&& op,
  737. constraint_t<is_async_operation<Op>::value> = 0)
  738. {
  739. if ((cancel->state.cancelled() != cancellation_type::none)
  740. && cancel->throw_if_cancelled_)
  741. {
  742. boost::asio::detail::throw_error(
  743. boost::asio::error::operation_aborted, "coro-cancelled");
  744. }
  745. using signature = completion_signature_of_t<Op>;
  746. using result_type = detail::coro_completion_handler_type_t<signature>;
  747. using handler_type =
  748. typename detail::coro_completion_handler_type<signature>::template
  749. completion_handler<coro_promise>;
  750. struct aw_t
  751. {
  752. Op op;
  753. std::optional<result_type> result;
  754. constexpr static bool await_ready()
  755. {
  756. return false;
  757. }
  758. void await_suspend(coroutine_handle<coro_promise> h)
  759. {
  760. std::move(op)(handler_type{h, result});
  761. }
  762. auto await_resume()
  763. {
  764. if constexpr (is_noexcept)
  765. {
  766. if constexpr (std::tuple_size_v<result_type> == 0u)
  767. return;
  768. else if constexpr (std::tuple_size_v<result_type> == 1u)
  769. return std::get<0>(std::move(result).value());
  770. else
  771. return std::move(result).value();
  772. }
  773. else
  774. return detail::coro_interpret_result(std::move(result).value());
  775. }
  776. };
  777. return aw_t{std::move(op), {}};
  778. }
  779. };
  780. } // namespace detail
  781. template <typename Yield, typename Return,
  782. typename Executor, typename Allocator>
  783. struct coro<Yield, Return, Executor, Allocator>::awaitable_t
  784. {
  785. coro& coro_;
  786. constexpr static bool await_ready() { return false; }
  787. template <typename Y, typename R, typename E, typename A>
  788. auto await_suspend(
  789. detail::coroutine_handle<detail::coro_promise<Y, R, E, A>> h)
  790. -> detail::coroutine_handle<>
  791. {
  792. auto& hp = h.promise();
  793. if constexpr (!detail::coro_promise<Y, R, E, A>::is_noexcept)
  794. {
  795. if ((hp.cancel->state.cancelled() != cancellation_type::none)
  796. && hp.cancel->throw_if_cancelled_)
  797. {
  798. boost::asio::detail::throw_error(
  799. boost::asio::error::operation_aborted, "coro-cancelled");
  800. }
  801. }
  802. if (hp.get_executor() == coro_.get_executor())
  803. {
  804. coro_.coro_->awaited_from = h;
  805. coro_.coro_->cancel = hp.cancel;
  806. coro_.coro_->reset_error();
  807. return coro_.coro_->get_handle();
  808. }
  809. else
  810. {
  811. coro_.coro_->awaited_from = detail::dispatch_coroutine(
  812. boost::asio::prefer(hp.get_executor(),
  813. execution::outstanding_work.tracked),
  814. [h]() mutable
  815. {
  816. h.resume();
  817. }).handle;
  818. coro_.coro_->reset_error();
  819. struct cancel_handler
  820. {
  821. std::shared_ptr<std::pair<cancellation_signal,
  822. detail::coro_cancellation_source>> st = std::make_shared<
  823. std::pair<cancellation_signal, detail::coro_cancellation_source>>();
  824. cancel_handler(E e, coro& coro) : e(e), coro_(coro.coro_)
  825. {
  826. st->second.state = cancellation_state(
  827. st->second.slot = st->first.slot());
  828. }
  829. E e;
  830. typename coro::promise_type* coro_;
  831. void operator()(cancellation_type ct)
  832. {
  833. boost::asio::dispatch(e,
  834. [ct, st = st]() mutable
  835. {
  836. auto & [sig, state] = *st;
  837. sig.emit(ct);
  838. });
  839. }
  840. };
  841. if (hp.cancel->state.slot().is_connected())
  842. {
  843. hp.cancel->state.slot().template emplace<cancel_handler>(
  844. coro_.get_executor(), coro_);
  845. }
  846. auto hh = detail::coroutine_handle<
  847. detail::coro_promise<Yield, Return, Executor, Allocator>>::from_promise(
  848. *coro_.coro_);
  849. return detail::dispatch_coroutine(
  850. coro_.coro_->get_executor(),
  851. [hh]() mutable { hh.resume(); }).handle;
  852. }
  853. }
  854. auto await_resume() -> result_type
  855. {
  856. coro_.coro_->cancel = nullptr;
  857. coro_.coro_->rethrow_if();
  858. if constexpr (!std::is_void_v<result_type>)
  859. return std::move(coro_.coro_->result_);
  860. }
  861. };
  862. template <typename Yield, typename Return,
  863. typename Executor, typename Allocator>
  864. struct coro<Yield, Return, Executor, Allocator>::initiate_async_resume
  865. {
  866. typedef Executor executor_type;
  867. typedef Allocator allocator_type;
  868. typedef boost::asio::cancellation_slot cancellation_slot_type;
  869. explicit initiate_async_resume(coro* self)
  870. : coro_(self->coro_)
  871. {
  872. }
  873. executor_type get_executor() const noexcept
  874. {
  875. return coro_->get_executor();
  876. }
  877. allocator_type get_allocator() const noexcept
  878. {
  879. return coro_->get_allocator();
  880. }
  881. template <typename E, typename WaitHandler>
  882. auto handle(E exec, WaitHandler&& handler,
  883. std::true_type /* error is noexcept */,
  884. std::true_type /* result is void */) //noexcept
  885. {
  886. return [this, the_coro = coro_,
  887. h = std::forward<WaitHandler>(handler),
  888. exec = std::move(exec)]() mutable
  889. {
  890. assert(the_coro);
  891. auto ch = detail::coroutine_handle<promise_type>::from_promise(*the_coro);
  892. assert(ch && !ch.done());
  893. the_coro->awaited_from = post_coroutine(std::move(exec), std::move(h));
  894. the_coro->reset_error();
  895. ch.resume();
  896. };
  897. }
  898. template <typename E, typename WaitHandler>
  899. requires (!std::is_void_v<result_type>)
  900. auto handle(E exec, WaitHandler&& handler,
  901. std::true_type /* error is noexcept */,
  902. std::false_type /* result is void */) //noexcept
  903. {
  904. return [the_coro = coro_,
  905. h = std::forward<WaitHandler>(handler),
  906. exec = std::move(exec)]() mutable
  907. {
  908. assert(the_coro);
  909. auto ch = detail::coroutine_handle<promise_type>::from_promise(*the_coro);
  910. assert(ch && !ch.done());
  911. the_coro->awaited_from = detail::post_coroutine(
  912. exec, std::move(h), the_coro->result_).handle;
  913. the_coro->reset_error();
  914. ch.resume();
  915. };
  916. }
  917. template <typename E, typename WaitHandler>
  918. auto handle(E exec, WaitHandler&& handler,
  919. std::false_type /* error is noexcept */,
  920. std::true_type /* result is void */)
  921. {
  922. return [the_coro = coro_,
  923. h = std::forward<WaitHandler>(handler),
  924. exec = std::move(exec)]() mutable
  925. {
  926. if (!the_coro)
  927. return boost::asio::post(exec,
  928. boost::asio::append(std::move(h),
  929. detail::coro_error<error_type>::invalid()));
  930. auto ch = detail::coroutine_handle<promise_type>::from_promise(*the_coro);
  931. if (!ch)
  932. return boost::asio::post(exec,
  933. boost::asio::append(std::move(h),
  934. detail::coro_error<error_type>::invalid()));
  935. else if (ch.done())
  936. return boost::asio::post(exec,
  937. boost::asio::append(std::move(h),
  938. detail::coro_error<error_type>::done()));
  939. else
  940. {
  941. the_coro->awaited_from = detail::post_coroutine(
  942. exec, std::move(h), the_coro->error_).handle;
  943. the_coro->reset_error();
  944. ch.resume();
  945. }
  946. };
  947. }
  948. template <typename E, typename WaitHandler>
  949. auto handle(E exec, WaitHandler&& handler,
  950. std::false_type /* error is noexcept */,
  951. std::false_type /* result is void */)
  952. {
  953. return [the_coro = coro_,
  954. h = std::forward<WaitHandler>(handler),
  955. exec = std::move(exec)]() mutable
  956. {
  957. if (!the_coro)
  958. return boost::asio::post(exec,
  959. boost::asio::append(std::move(h),
  960. detail::coro_error<error_type>::invalid(), result_type{}));
  961. auto ch =
  962. detail::coroutine_handle<promise_type>::from_promise(*the_coro);
  963. if (!ch)
  964. return boost::asio::post(exec,
  965. boost::asio::append(std::move(h),
  966. detail::coro_error<error_type>::invalid(), result_type{}));
  967. else if (ch.done())
  968. return boost::asio::post(exec,
  969. boost::asio::append(std::move(h),
  970. detail::coro_error<error_type>::done(), result_type{}));
  971. else
  972. {
  973. the_coro->awaited_from = detail::post_coroutine(
  974. exec, std::move(h), the_coro->error_, the_coro->result_).handle;
  975. the_coro->reset_error();
  976. ch.resume();
  977. }
  978. };
  979. }
  980. template <typename WaitHandler>
  981. void operator()(WaitHandler&& handler)
  982. {
  983. const auto exec = boost::asio::prefer(
  984. get_associated_executor(handler, get_executor()),
  985. execution::outstanding_work.tracked);
  986. coro_->cancel = &coro_->cancel_source.emplace();
  987. coro_->cancel->state = cancellation_state(
  988. coro_->cancel->slot = get_associated_cancellation_slot(handler));
  989. boost::asio::dispatch(get_executor(),
  990. handle(exec, std::forward<WaitHandler>(handler),
  991. std::integral_constant<bool, is_noexcept>{},
  992. std::is_void<result_type>{}));
  993. }
  994. template <typename WaitHandler, typename Input>
  995. void operator()(WaitHandler&& handler, Input&& input)
  996. {
  997. const auto exec = boost::asio::prefer(
  998. get_associated_executor(handler, get_executor()),
  999. execution::outstanding_work.tracked);
  1000. coro_->cancel = &coro_->cancel_source.emplace();
  1001. coro_->cancel->state = cancellation_state(
  1002. coro_->cancel->slot = get_associated_cancellation_slot(handler));
  1003. boost::asio::dispatch(get_executor(),
  1004. [h = handle(exec, std::forward<WaitHandler>(handler),
  1005. std::integral_constant<bool, is_noexcept>{},
  1006. std::is_void<result_type>{}),
  1007. in = std::forward<Input>(input), the_coro = coro_]() mutable
  1008. {
  1009. the_coro->input_ = std::move(in);
  1010. std::move(h)();
  1011. });
  1012. }
  1013. private:
  1014. typename coro::promise_type* coro_;
  1015. };
  1016. } // namespace experimental
  1017. } // namespace asio
  1018. } // namespace boost
  1019. #include <boost/asio/detail/pop_options.hpp>
  1020. #endif // BOOST_ASIO_EXPERIMENTAL_IMPL_CORO_HPP