coro.hpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. //
  2. // experimental/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_CORO_HPP
  12. #define BOOST_ASIO_EXPERIMENTAL_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/dispatch.hpp>
  18. #include <boost/asio/error.hpp>
  19. #include <boost/system/error_code.hpp>
  20. #include <boost/asio/experimental/coro_traits.hpp>
  21. #include <boost/asio/experimental/detail/coro_promise_allocator.hpp>
  22. #include <boost/asio/experimental/detail/partial_promise.hpp>
  23. #include <boost/asio/post.hpp>
  24. #include <boost/asio/detail/push_options.hpp>
  25. namespace boost {
  26. namespace asio {
  27. namespace experimental {
  28. namespace detail {
  29. template <typename Signature, typename Return,
  30. typename Executor, typename Allocator>
  31. struct coro_promise;
  32. template <typename T, typename Coroutine>
  33. struct coro_with_arg;
  34. } // namespace detail
  35. /// The main type of a resumable coroutine.
  36. /**
  37. * Template parameter @c Yield specifies type or signature used by co_yield,
  38. * @c Return specifies the type used for co_return, and @c Executor specifies
  39. * the underlying executor type.
  40. */
  41. template <typename Yield = void, typename Return = void,
  42. typename Executor = any_io_executor,
  43. typename Allocator = std::allocator<void>>
  44. struct coro
  45. {
  46. /// The traits of the coroutine. See boost::asio::experimental::coro_traits
  47. /// for details.
  48. using traits = coro_traits<Yield, Return, Executor>;
  49. /// The value that can be passed into a symmetrical cororoutine. @c void if
  50. /// asymmetrical.
  51. using input_type = typename traits::input_type;
  52. /// The type that can be passed out through a co_yield.
  53. using yield_type = typename traits::yield_type;
  54. /// The type that can be passed out through a co_return.
  55. using return_type = typename traits::return_type;
  56. /// The type received by a co_await or async_resume. Its a combination of
  57. /// yield and return.
  58. using result_type = typename traits::result_type;
  59. /// The signature used by the async_resume.
  60. using signature_type = typename traits::signature_type;
  61. /// Whether or not the coroutine is noexcept.
  62. constexpr static bool is_noexcept = traits::is_noexcept;
  63. /// The error type of the coroutine. Void for noexcept
  64. using error_type = typename traits::error_type;
  65. /// Completion handler type used by async_resume.
  66. using completion_handler = typename traits::completion_handler;
  67. /// The internal promise-type of the coroutine.
  68. using promise_type = detail::coro_promise<Yield, Return, Executor, Allocator>;
  69. #if !defined(GENERATING_DOCUMENTATION)
  70. template <typename T, typename Coroutine>
  71. friend struct detail::coro_with_arg;
  72. #endif // !defined(GENERATING_DOCUMENTATION)
  73. /// The executor type.
  74. using executor_type = Executor;
  75. /// The allocator type.
  76. using allocator_type = Allocator;
  77. #if !defined(GENERATING_DOCUMENTATION)
  78. friend struct detail::coro_promise<Yield, Return, Executor, Allocator>;
  79. #endif // !defined(GENERATING_DOCUMENTATION)
  80. /// The default constructor, gives an invalid coroutine.
  81. coro() = default;
  82. /// Move constructor.
  83. coro(coro&& lhs) noexcept
  84. : coro_(std::exchange(lhs.coro_, nullptr))
  85. {
  86. }
  87. coro(const coro&) = delete;
  88. /// Move assignment.
  89. coro& operator=(coro&& lhs) noexcept
  90. {
  91. std::swap(coro_, lhs.coro_);
  92. return *this;
  93. }
  94. coro& operator=(const coro&) = delete;
  95. /// Destructor. Destroys the coroutine, if it holds a valid one.
  96. /**
  97. * @note This does not cancel an active coroutine. Destructing a resumable
  98. * coroutine, i.e. one with a call to async_resume that has not completed, is
  99. * undefined behaviour.
  100. */
  101. ~coro()
  102. {
  103. if (coro_ != nullptr)
  104. {
  105. struct destroyer
  106. {
  107. detail::coroutine_handle<promise_type> handle;
  108. destroyer(const detail::coroutine_handle<promise_type>& handle)
  109. : handle(handle)
  110. { }
  111. destroyer(destroyer&& lhs)
  112. : handle(std::exchange(lhs.handle, nullptr))
  113. {
  114. }
  115. destroyer(const destroyer&) = delete;
  116. void operator()() {}
  117. ~destroyer()
  118. {
  119. if (handle)
  120. handle.destroy();
  121. }
  122. };
  123. auto handle =
  124. detail::coroutine_handle<promise_type>::from_promise(*coro_);
  125. if (handle)
  126. boost::asio::dispatch(coro_->get_executor(), destroyer{handle});
  127. }
  128. }
  129. /// Get the used executor.
  130. executor_type get_executor() const
  131. {
  132. if (coro_)
  133. return coro_->get_executor();
  134. if constexpr (std::is_default_constructible_v<Executor>)
  135. return Executor{};
  136. else
  137. throw std::logic_error("Coroutine has no executor");
  138. }
  139. /// Get the used allocator.
  140. allocator_type get_allocator() const
  141. {
  142. if (coro_)
  143. return coro_->get_allocator();
  144. if constexpr (std::is_default_constructible_v<Allocator>)
  145. return Allocator{};
  146. else
  147. throw std::logic_error(
  148. "Coroutine has no available allocator without a constructed promise");
  149. }
  150. /// Resume the coroutine.
  151. /**
  152. * @param token The completion token of the async resume.
  153. *
  154. * @attention Calling an invalid coroutine with a noexcept signature is
  155. * undefined behaviour.
  156. *
  157. * @note This overload is only available for coroutines without an input
  158. * value.
  159. */
  160. template <typename CompletionToken>
  161. requires std::is_void_v<input_type>
  162. auto async_resume(CompletionToken&& token) &
  163. {
  164. return async_initiate<CompletionToken,
  165. typename traits::completion_handler>(
  166. initiate_async_resume(this), token);
  167. }
  168. /// Resume the coroutine.
  169. /**
  170. * @param token The completion token of the async resume.
  171. *
  172. * @attention Calling an invalid coroutine with a noexcept signature is
  173. * undefined behaviour.
  174. *
  175. * @note This overload is only available for coroutines with an input value.
  176. */
  177. template <typename CompletionToken, detail::convertible_to<input_type> T>
  178. auto async_resume(T&& ip, CompletionToken&& token) &
  179. {
  180. return async_initiate<CompletionToken,
  181. typename traits::completion_handler>(
  182. initiate_async_resume(this), token, std::forward<T>(ip));
  183. }
  184. /// Operator used for coroutines without input value.
  185. auto operator co_await() requires (std::is_void_v<input_type>)
  186. {
  187. return awaitable_t{*this};
  188. }
  189. /// Operator used for coroutines with input value.
  190. /**
  191. * @param ip The input value
  192. *
  193. * @returns An awaitable handle.
  194. *
  195. * @code
  196. * coro<void> push_values(coro<double(int)> c)
  197. * {
  198. * std::optional<double> res = co_await c(42);
  199. * }
  200. * @endcode
  201. */
  202. template <detail::convertible_to<input_type> T>
  203. auto operator()(T&& ip)
  204. {
  205. return detail::coro_with_arg<std::decay_t<T>, coro>{
  206. std::forward<T>(ip), *this};
  207. }
  208. /// Check whether the coroutine is open, i.e. can be resumed.
  209. bool is_open() const
  210. {
  211. if (coro_)
  212. {
  213. auto handle =
  214. detail::coroutine_handle<promise_type>::from_promise(*coro_);
  215. return handle && !handle.done();
  216. }
  217. else
  218. return false;
  219. }
  220. /// Check whether the coroutine is open, i.e. can be resumed.
  221. explicit operator bool() const { return is_open(); }
  222. private:
  223. struct awaitable_t;
  224. struct initiate_async_resume;
  225. explicit coro(promise_type* const cr) : coro_(cr) {}
  226. promise_type* coro_{nullptr};
  227. };
  228. /// A generator is a coro that returns void and yields value.
  229. template<typename T, typename Executor = boost::asio::any_io_executor,
  230. typename Allocator = std::allocator<void>>
  231. using generator = coro<T, void, Executor, Allocator>;
  232. /// A task is a coro that does not yield values
  233. template<typename T, typename Executor = boost::asio::any_io_executor,
  234. typename Allocator = std::allocator<void>>
  235. using task = coro<void(), T, Executor, Allocator>;
  236. } // namespace experimental
  237. } // namespace asio
  238. } // namespace boost
  239. #include <boost/asio/detail/pop_options.hpp>
  240. #include <boost/asio/experimental/impl/coro.hpp>
  241. #endif // BOOST_ASIO_EXPERIMENTAL_CORO_HPP