basic_stream_descriptor.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. //
  2. // posix/basic_stream_descriptor.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
  11. #define ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #include "asio/posix/basic_descriptor.hpp"
  17. #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \
  18. || defined(GENERATING_DOCUMENTATION)
  19. #include "asio/detail/push_options.hpp"
  20. namespace asio {
  21. namespace posix {
  22. /// Provides stream-oriented descriptor functionality.
  23. /**
  24. * The posix::basic_stream_descriptor class template provides asynchronous and
  25. * blocking stream-oriented descriptor functionality.
  26. *
  27. * @par Thread Safety
  28. * @e Distinct @e objects: Safe.@n
  29. * @e Shared @e objects: Unsafe.
  30. *
  31. * Synchronous @c read_some and @c write_some operations are thread safe with
  32. * respect to each other, if the underlying operating system calls are also
  33. * thread safe. This means that it is permitted to perform concurrent calls to
  34. * these synchronous operations on a single descriptor object. Other synchronous
  35. * operations, such as @c close, are not thread safe.
  36. *
  37. * @par Concepts:
  38. * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
  39. */
  40. template <typename Executor = any_io_executor>
  41. class basic_stream_descriptor
  42. : public basic_descriptor<Executor>
  43. {
  44. private:
  45. class initiate_async_write_some;
  46. class initiate_async_read_some;
  47. public:
  48. /// The type of the executor associated with the object.
  49. typedef Executor executor_type;
  50. /// Rebinds the descriptor type to another executor.
  51. template <typename Executor1>
  52. struct rebind_executor
  53. {
  54. /// The descriptor type when rebound to the specified executor.
  55. typedef basic_stream_descriptor<Executor1> other;
  56. };
  57. /// The native representation of a descriptor.
  58. typedef typename basic_descriptor<Executor>::native_handle_type
  59. native_handle_type;
  60. /// Construct a stream descriptor without opening it.
  61. /**
  62. * This constructor creates a stream descriptor without opening it. The
  63. * descriptor needs to be opened and then connected or accepted before data
  64. * can be sent or received on it.
  65. *
  66. * @param ex The I/O executor that the descriptor will use, by default, to
  67. * dispatch handlers for any asynchronous operations performed on the
  68. * descriptor.
  69. */
  70. explicit basic_stream_descriptor(const executor_type& ex)
  71. : basic_descriptor<Executor>(ex)
  72. {
  73. }
  74. /// Construct a stream descriptor without opening it.
  75. /**
  76. * This constructor creates a stream descriptor without opening it. The
  77. * descriptor needs to be opened and then connected or accepted before data
  78. * can be sent or received on it.
  79. *
  80. * @param context An execution context which provides the I/O executor that
  81. * the descriptor will use, by default, to dispatch handlers for any
  82. * asynchronous operations performed on the descriptor.
  83. */
  84. template <typename ExecutionContext>
  85. explicit basic_stream_descriptor(ExecutionContext& context,
  86. constraint_t<
  87. is_convertible<ExecutionContext&, execution_context&>::value,
  88. defaulted_constraint
  89. > = defaulted_constraint())
  90. : basic_descriptor<Executor>(context)
  91. {
  92. }
  93. /// Construct a stream descriptor on an existing native descriptor.
  94. /**
  95. * This constructor creates a stream descriptor object to hold an existing
  96. * native descriptor.
  97. *
  98. * @param ex The I/O executor that the descriptor will use, by default, to
  99. * dispatch handlers for any asynchronous operations performed on the
  100. * descriptor.
  101. *
  102. * @param native_descriptor The new underlying descriptor implementation.
  103. *
  104. * @throws asio::system_error Thrown on failure.
  105. */
  106. basic_stream_descriptor(const executor_type& ex,
  107. const native_handle_type& native_descriptor)
  108. : basic_descriptor<Executor>(ex, native_descriptor)
  109. {
  110. }
  111. /// Construct a stream descriptor on an existing native descriptor.
  112. /**
  113. * This constructor creates a stream descriptor object to hold an existing
  114. * native descriptor.
  115. *
  116. * @param context An execution context which provides the I/O executor that
  117. * the descriptor will use, by default, to dispatch handlers for any
  118. * asynchronous operations performed on the descriptor.
  119. *
  120. * @param native_descriptor The new underlying descriptor implementation.
  121. *
  122. * @throws asio::system_error Thrown on failure.
  123. */
  124. template <typename ExecutionContext>
  125. basic_stream_descriptor(ExecutionContext& context,
  126. const native_handle_type& native_descriptor,
  127. constraint_t<
  128. is_convertible<ExecutionContext&, execution_context&>::value
  129. > = 0)
  130. : basic_descriptor<Executor>(context, native_descriptor)
  131. {
  132. }
  133. /// Move-construct a stream descriptor from another.
  134. /**
  135. * This constructor moves a stream descriptor from one object to another.
  136. *
  137. * @param other The other stream descriptor object from which the move
  138. * will occur.
  139. *
  140. * @note Following the move, the moved-from object is in the same state as if
  141. * constructed using the @c basic_stream_descriptor(const executor_type&)
  142. * constructor.
  143. */
  144. basic_stream_descriptor(basic_stream_descriptor&& other) noexcept
  145. : basic_descriptor<Executor>(std::move(other))
  146. {
  147. }
  148. /// Move-assign a stream descriptor from another.
  149. /**
  150. * This assignment operator moves a stream descriptor from one object to
  151. * another.
  152. *
  153. * @param other The other stream descriptor object from which the move
  154. * will occur.
  155. *
  156. * @note Following the move, the moved-from object is in the same state as if
  157. * constructed using the @c basic_stream_descriptor(const executor_type&)
  158. * constructor.
  159. */
  160. basic_stream_descriptor& operator=(basic_stream_descriptor&& other)
  161. {
  162. basic_descriptor<Executor>::operator=(std::move(other));
  163. return *this;
  164. }
  165. /// Move-construct a basic_stream_descriptor from a descriptor of another
  166. /// executor type.
  167. /**
  168. * This constructor moves a descriptor from one object to another.
  169. *
  170. * @param other The other basic_stream_descriptor object from which the move
  171. * will occur.
  172. *
  173. * @note Following the move, the moved-from object is in the same state as if
  174. * constructed using the @c basic_stream_descriptor(const executor_type&)
  175. * constructor.
  176. */
  177. template <typename Executor1>
  178. basic_stream_descriptor(basic_stream_descriptor<Executor1>&& other,
  179. constraint_t<
  180. is_convertible<Executor1, Executor>::value,
  181. defaulted_constraint
  182. > = defaulted_constraint())
  183. : basic_descriptor<Executor>(std::move(other))
  184. {
  185. }
  186. /// Move-assign a basic_stream_descriptor from a descriptor of another
  187. /// executor type.
  188. /**
  189. * This assignment operator moves a descriptor from one object to another.
  190. *
  191. * @param other The other basic_stream_descriptor object from which the move
  192. * will occur.
  193. *
  194. * @note Following the move, the moved-from object is in the same state as if
  195. * constructed using the @c basic_stream_descriptor(const executor_type&)
  196. * constructor.
  197. */
  198. template <typename Executor1>
  199. constraint_t<
  200. is_convertible<Executor1, Executor>::value,
  201. basic_stream_descriptor&
  202. > operator=(basic_stream_descriptor<Executor1> && other)
  203. {
  204. basic_descriptor<Executor>::operator=(std::move(other));
  205. return *this;
  206. }
  207. /// Write some data to the descriptor.
  208. /**
  209. * This function is used to write data to the stream descriptor. The function
  210. * call will block until one or more bytes of the data has been written
  211. * successfully, or until an error occurs.
  212. *
  213. * @param buffers One or more data buffers to be written to the descriptor.
  214. *
  215. * @returns The number of bytes written.
  216. *
  217. * @throws asio::system_error Thrown on failure. An error code of
  218. * asio::error::eof indicates that the connection was closed by the
  219. * peer.
  220. *
  221. * @note The write_some operation may not transmit all of the data to the
  222. * peer. Consider using the @ref write function if you need to ensure that
  223. * all data is written before the blocking operation completes.
  224. *
  225. * @par Example
  226. * To write a single data buffer use the @ref buffer function as follows:
  227. * @code
  228. * descriptor.write_some(asio::buffer(data, size));
  229. * @endcode
  230. * See the @ref buffer documentation for information on writing multiple
  231. * buffers in one go, and how to use it with arrays, boost::array or
  232. * std::vector.
  233. */
  234. template <typename ConstBufferSequence>
  235. std::size_t write_some(const ConstBufferSequence& buffers)
  236. {
  237. asio::error_code ec;
  238. std::size_t s = this->impl_.get_service().write_some(
  239. this->impl_.get_implementation(), buffers, ec);
  240. asio::detail::throw_error(ec, "write_some");
  241. return s;
  242. }
  243. /// Write some data to the descriptor.
  244. /**
  245. * This function is used to write data to the stream descriptor. The function
  246. * call will block until one or more bytes of the data has been written
  247. * successfully, or until an error occurs.
  248. *
  249. * @param buffers One or more data buffers to be written to the descriptor.
  250. *
  251. * @param ec Set to indicate what error occurred, if any.
  252. *
  253. * @returns The number of bytes written. Returns 0 if an error occurred.
  254. *
  255. * @note The write_some operation may not transmit all of the data to the
  256. * peer. Consider using the @ref write function if you need to ensure that
  257. * all data is written before the blocking operation completes.
  258. */
  259. template <typename ConstBufferSequence>
  260. std::size_t write_some(const ConstBufferSequence& buffers,
  261. asio::error_code& ec)
  262. {
  263. return this->impl_.get_service().write_some(
  264. this->impl_.get_implementation(), buffers, ec);
  265. }
  266. /// Start an asynchronous write.
  267. /**
  268. * This function is used to asynchronously write data to the stream
  269. * descriptor. It is an initiating function for an @ref
  270. * asynchronous_operation, and always returns immediately.
  271. *
  272. * @param buffers One or more data buffers to be written to the descriptor.
  273. * Although the buffers object may be copied as necessary, ownership of the
  274. * underlying memory blocks is retained by the caller, which must guarantee
  275. * that they remain valid until the completion handler is called.
  276. *
  277. * @param token The @ref completion_token that will be used to produce a
  278. * completion handler, which will be called when the write completes.
  279. * Potential completion tokens include @ref use_future, @ref use_awaitable,
  280. * @ref yield_context, or a function object with the correct completion
  281. * signature. The function signature of the completion handler must be:
  282. * @code void handler(
  283. * const asio::error_code& error, // Result of operation.
  284. * std::size_t bytes_transferred // Number of bytes written.
  285. * ); @endcode
  286. * Regardless of whether the asynchronous operation completes immediately or
  287. * not, the completion handler will not be invoked from within this function.
  288. * On immediate completion, invocation of the handler will be performed in a
  289. * manner equivalent to using asio::post().
  290. *
  291. * @par Completion Signature
  292. * @code void(asio::error_code, std::size_t) @endcode
  293. *
  294. * @note The write operation may not transmit all of the data to the peer.
  295. * Consider using the @ref async_write function if you need to ensure that all
  296. * data is written before the asynchronous operation completes.
  297. *
  298. * @par Example
  299. * To write a single data buffer use the @ref buffer function as follows:
  300. * @code
  301. * descriptor.async_write_some(asio::buffer(data, size), handler);
  302. * @endcode
  303. * See the @ref buffer documentation for information on writing multiple
  304. * buffers in one go, and how to use it with arrays, boost::array or
  305. * std::vector.
  306. *
  307. * @par Per-Operation Cancellation
  308. * This asynchronous operation supports cancellation for the following
  309. * asio::cancellation_type values:
  310. *
  311. * @li @c cancellation_type::terminal
  312. *
  313. * @li @c cancellation_type::partial
  314. *
  315. * @li @c cancellation_type::total
  316. */
  317. template <typename ConstBufferSequence,
  318. ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
  319. std::size_t)) WriteToken = default_completion_token_t<executor_type>>
  320. auto async_write_some(const ConstBufferSequence& buffers,
  321. WriteToken&& token = default_completion_token_t<executor_type>())
  322. -> decltype(
  323. async_initiate<WriteToken,
  324. void (asio::error_code, std::size_t)>(
  325. initiate_async_write_some(this), token, buffers))
  326. {
  327. return async_initiate<WriteToken,
  328. void (asio::error_code, std::size_t)>(
  329. initiate_async_write_some(this), token, buffers);
  330. }
  331. /// Read some data from the descriptor.
  332. /**
  333. * This function is used to read data from the stream descriptor. The function
  334. * call will block until one or more bytes of data has been read successfully,
  335. * or until an error occurs.
  336. *
  337. * @param buffers One or more buffers into which the data will be read.
  338. *
  339. * @returns The number of bytes read.
  340. *
  341. * @throws asio::system_error Thrown on failure. An error code of
  342. * asio::error::eof indicates that the connection was closed by the
  343. * peer.
  344. *
  345. * @note The read_some operation may not read all of the requested number of
  346. * bytes. Consider using the @ref read function if you need to ensure that
  347. * the requested amount of data is read before the blocking operation
  348. * completes.
  349. *
  350. * @par Example
  351. * To read into a single data buffer use the @ref buffer function as follows:
  352. * @code
  353. * descriptor.read_some(asio::buffer(data, size));
  354. * @endcode
  355. * See the @ref buffer documentation for information on reading into multiple
  356. * buffers in one go, and how to use it with arrays, boost::array or
  357. * std::vector.
  358. */
  359. template <typename MutableBufferSequence>
  360. std::size_t read_some(const MutableBufferSequence& buffers)
  361. {
  362. asio::error_code ec;
  363. std::size_t s = this->impl_.get_service().read_some(
  364. this->impl_.get_implementation(), buffers, ec);
  365. asio::detail::throw_error(ec, "read_some");
  366. return s;
  367. }
  368. /// Read some data from the descriptor.
  369. /**
  370. * This function is used to read data from the stream descriptor. The function
  371. * call will block until one or more bytes of data has been read successfully,
  372. * or until an error occurs.
  373. *
  374. * @param buffers One or more buffers into which the data will be read.
  375. *
  376. * @param ec Set to indicate what error occurred, if any.
  377. *
  378. * @returns The number of bytes read. Returns 0 if an error occurred.
  379. *
  380. * @note The read_some operation may not read all of the requested number of
  381. * bytes. Consider using the @ref read function if you need to ensure that
  382. * the requested amount of data is read before the blocking operation
  383. * completes.
  384. */
  385. template <typename MutableBufferSequence>
  386. std::size_t read_some(const MutableBufferSequence& buffers,
  387. asio::error_code& ec)
  388. {
  389. return this->impl_.get_service().read_some(
  390. this->impl_.get_implementation(), buffers, ec);
  391. }
  392. /// Start an asynchronous read.
  393. /**
  394. * This function is used to asynchronously read data from the stream
  395. * descriptor. It is an initiating function for an @ref
  396. * asynchronous_operation, and always returns immediately.
  397. *
  398. * @param buffers One or more buffers into which the data will be read.
  399. * Although the buffers object may be copied as necessary, ownership of the
  400. * underlying memory blocks is retained by the caller, which must guarantee
  401. * that they remain valid until the completion handler is called.
  402. *
  403. * @param token The @ref completion_token that will be used to produce a
  404. * completion handler, which will be called when the read completes.
  405. * Potential completion tokens include @ref use_future, @ref use_awaitable,
  406. * @ref yield_context, or a function object with the correct completion
  407. * signature. The function signature of the completion handler must be:
  408. * @code void handler(
  409. * const asio::error_code& error, // Result of operation.
  410. * std::size_t bytes_transferred // Number of bytes read.
  411. * ); @endcode
  412. * Regardless of whether the asynchronous operation completes immediately or
  413. * not, the completion handler will not be invoked from within this function.
  414. * On immediate completion, invocation of the handler will be performed in a
  415. * manner equivalent to using asio::post().
  416. *
  417. * @par Completion Signature
  418. * @code void(asio::error_code, std::size_t) @endcode
  419. *
  420. * @note The read operation may not read all of the requested number of bytes.
  421. * Consider using the @ref async_read function if you need to ensure that the
  422. * requested amount of data is read before the asynchronous operation
  423. * completes.
  424. *
  425. * @par Example
  426. * To read into a single data buffer use the @ref buffer function as follows:
  427. * @code
  428. * descriptor.async_read_some(asio::buffer(data, size), handler);
  429. * @endcode
  430. * See the @ref buffer documentation for information on reading into multiple
  431. * buffers in one go, and how to use it with arrays, boost::array or
  432. * std::vector.
  433. *
  434. * @par Per-Operation Cancellation
  435. * This asynchronous operation supports cancellation for the following
  436. * asio::cancellation_type values:
  437. *
  438. * @li @c cancellation_type::terminal
  439. *
  440. * @li @c cancellation_type::partial
  441. *
  442. * @li @c cancellation_type::total
  443. */
  444. template <typename MutableBufferSequence,
  445. ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
  446. std::size_t)) ReadToken = default_completion_token_t<executor_type>>
  447. auto async_read_some(const MutableBufferSequence& buffers,
  448. ReadToken&& token = default_completion_token_t<executor_type>())
  449. -> decltype(
  450. async_initiate<ReadToken,
  451. void (asio::error_code, std::size_t)>(
  452. declval<initiate_async_read_some>(), token, buffers))
  453. {
  454. return async_initiate<ReadToken,
  455. void (asio::error_code, std::size_t)>(
  456. initiate_async_read_some(this), token, buffers);
  457. }
  458. private:
  459. class initiate_async_write_some
  460. {
  461. public:
  462. typedef Executor executor_type;
  463. explicit initiate_async_write_some(basic_stream_descriptor* self)
  464. : self_(self)
  465. {
  466. }
  467. const executor_type& get_executor() const noexcept
  468. {
  469. return self_->get_executor();
  470. }
  471. template <typename WriteHandler, typename ConstBufferSequence>
  472. void operator()(WriteHandler&& handler,
  473. const ConstBufferSequence& buffers) const
  474. {
  475. // If you get an error on the following line it means that your handler
  476. // does not meet the documented type requirements for a WriteHandler.
  477. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
  478. detail::non_const_lvalue<WriteHandler> handler2(handler);
  479. self_->impl_.get_service().async_write_some(
  480. self_->impl_.get_implementation(), buffers,
  481. handler2.value, self_->impl_.get_executor());
  482. }
  483. private:
  484. basic_stream_descriptor* self_;
  485. };
  486. class initiate_async_read_some
  487. {
  488. public:
  489. typedef Executor executor_type;
  490. explicit initiate_async_read_some(basic_stream_descriptor* self)
  491. : self_(self)
  492. {
  493. }
  494. const executor_type& get_executor() const noexcept
  495. {
  496. return self_->get_executor();
  497. }
  498. template <typename ReadHandler, typename MutableBufferSequence>
  499. void operator()(ReadHandler&& handler,
  500. const MutableBufferSequence& buffers) const
  501. {
  502. // If you get an error on the following line it means that your handler
  503. // does not meet the documented type requirements for a ReadHandler.
  504. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
  505. detail::non_const_lvalue<ReadHandler> handler2(handler);
  506. self_->impl_.get_service().async_read_some(
  507. self_->impl_.get_implementation(), buffers,
  508. handler2.value, self_->impl_.get_executor());
  509. }
  510. private:
  511. basic_stream_descriptor* self_;
  512. };
  513. };
  514. } // namespace posix
  515. } // namespace asio
  516. #include "asio/detail/pop_options.hpp"
  517. #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
  518. // || defined(GENERATING_DOCUMENTATION)
  519. #endif // ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP