flat_stream.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_CORE_FLAT_STREAM_HPP
  10. #define BOOST_BEAST_CORE_FLAT_STREAM_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/core/error.hpp>
  13. #include <boost/beast/core/flat_buffer.hpp>
  14. #include <boost/beast/core/stream_traits.hpp>
  15. #include <boost/beast/core/detail/flat_stream.hpp>
  16. #include <boost/asio/async_result.hpp>
  17. #include <cstdlib>
  18. #include <utility>
  19. namespace boost {
  20. namespace beast {
  21. /** Stream wrapper to improve write performance.
  22. This wrapper flattens writes for buffer sequences having length
  23. greater than 1 and total size below a predefined amount, using
  24. a dynamic memory allocation. It is primarily designed to overcome
  25. a performance limitation of the current version of `net::ssl::stream`,
  26. which does not use OpenSSL's scatter/gather interface for its
  27. low-level read some and write some operations.
  28. It is normally not necessary to use this class directly if you
  29. are already using @ref ssl_stream. The following examples shows
  30. how to use this class with the ssl stream that comes with
  31. networking:
  32. @par Example
  33. To use the @ref flat_stream template with SSL streams, declare
  34. a variable of the correct type. Parameters passed to the constructor
  35. will be forwarded to the next layer's constructor:
  36. @code
  37. flat_stream<net::ssl::stream<ip::tcp::socket>> fs{ioc, ctx};
  38. @endcode
  39. Alternatively you can write
  40. @code
  41. ssl::stream<ip::tcp::socket> ss{ioc, ctx};
  42. flat_stream<net::ssl::stream<ip::tcp::socket>&> fs{ss};
  43. @endcode
  44. The resulting stream may be passed to any stream algorithms which
  45. operate on synchronous or asynchronous read or write streams,
  46. examples include:
  47. @li `net::read`, `net::async_read`
  48. @li `net::write`, `net::async_write`
  49. @li `net::read_until`, `net::async_read_until`
  50. The stream may also be used as a template parameter in other
  51. stream wrappers, such as for websocket:
  52. @code
  53. websocket::stream<flat_stream<net::ssl::stream<ip::tcp::socket>>> ws{ioc, ctx};
  54. @endcode
  55. @tparam NextLayer The type representing the next layer, to which
  56. data will be read and written during operations. For synchronous
  57. operations, the type must support the @b SyncStream concept. For
  58. asynchronous operations, the type must support the @b AsyncStream
  59. concept. This type will usually be some variation of
  60. `net::ssl::stream`.
  61. @par Concepts
  62. @li SyncStream
  63. @li AsyncStream
  64. @see
  65. @li https://github.com/boostorg/asio/issues/100
  66. @li https://github.com/boostorg/beast/issues/1108
  67. @li https://stackoverflow.com/questions/38198638/openssl-ssl-write-from-multiple-buffers-ssl-writev
  68. @li https://stackoverflow.com/questions/50026167/performance-drop-on-port-from-beast-1-0-0-b66-to-boost-1-67-0-beast
  69. */
  70. template<class NextLayer>
  71. class flat_stream
  72. #if ! BOOST_BEAST_DOXYGEN
  73. : private detail::flat_stream_base
  74. #endif
  75. {
  76. NextLayer stream_;
  77. flat_buffer buffer_;
  78. BOOST_STATIC_ASSERT(has_get_executor<NextLayer>::value);
  79. struct ops;
  80. template<class ConstBufferSequence>
  81. std::size_t
  82. stack_write_some(
  83. std::size_t size,
  84. ConstBufferSequence const& buffers,
  85. error_code& ec);
  86. public:
  87. /// The type of the next layer.
  88. using next_layer_type =
  89. typename std::remove_reference<NextLayer>::type;
  90. /// The type of the executor associated with the object.
  91. using executor_type = beast::executor_type<next_layer_type>;
  92. flat_stream(flat_stream&&) = default;
  93. flat_stream(flat_stream const&) = default;
  94. flat_stream& operator=(flat_stream&&) = default;
  95. flat_stream& operator=(flat_stream const&) = default;
  96. /** Destructor
  97. The treatment of pending operations will be the same as that
  98. of the next layer.
  99. */
  100. ~flat_stream() = default;
  101. /** Constructor
  102. Arguments, if any, are forwarded to the next layer's constructor.
  103. */
  104. template<class... Args>
  105. explicit
  106. flat_stream(Args&&... args);
  107. //--------------------------------------------------------------------------
  108. /** Get the executor associated with the object.
  109. This function may be used to obtain the executor object that the
  110. stream uses to dispatch handlers for asynchronous operations.
  111. @return A copy of the executor that stream will use to dispatch handlers.
  112. */
  113. executor_type
  114. get_executor() noexcept
  115. {
  116. return stream_.get_executor();
  117. }
  118. /** Get a reference to the next layer
  119. This function returns a reference to the next layer
  120. in a stack of stream layers.
  121. @return A reference to the next layer in the stack of
  122. stream layers.
  123. */
  124. next_layer_type&
  125. next_layer() noexcept
  126. {
  127. return stream_;
  128. }
  129. /** Get a reference to the next layer
  130. This function returns a reference to the next layer in a
  131. stack of stream layers.
  132. @return A reference to the next layer in the stack of
  133. stream layers.
  134. */
  135. next_layer_type const&
  136. next_layer() const noexcept
  137. {
  138. return stream_;
  139. }
  140. //--------------------------------------------------------------------------
  141. /** Read some data from the stream.
  142. This function is used to read data from the stream. The function call will
  143. block until one or more bytes of data has been read successfully, or until
  144. an error occurs.
  145. @param buffers The buffers into which the data will be read.
  146. @returns The number of bytes read.
  147. @throws boost::system::system_error Thrown on failure.
  148. @note The `read_some` operation may not read all of the requested number of
  149. bytes. Consider using the function `net::read` if you need to ensure
  150. that the requested amount of data is read before the blocking operation
  151. completes.
  152. */
  153. template<class MutableBufferSequence>
  154. std::size_t
  155. read_some(MutableBufferSequence const& buffers);
  156. /** Read some data from the stream.
  157. This function is used to read data from the stream. The function call will
  158. block until one or more bytes of data has been read successfully, or until
  159. an error occurs.
  160. @param buffers The buffers into which the data will be read.
  161. @param ec Set to indicate what error occurred, if any.
  162. @returns The number of bytes read.
  163. @note The `read_some` operation may not read all of the requested number of
  164. bytes. Consider using the function `net::read` if you need to ensure
  165. that the requested amount of data is read before the blocking operation
  166. completes.
  167. */
  168. template<class MutableBufferSequence>
  169. std::size_t
  170. read_some(
  171. MutableBufferSequence const& buffers,
  172. error_code& ec);
  173. /** Start an asynchronous read.
  174. This function is used to asynchronously read one or more bytes of data from
  175. the stream. The function call always returns immediately.
  176. @param buffers The buffers into which the data will be read. Although the
  177. buffers object may be copied as necessary, ownership of the underlying
  178. buffers is retained by the caller, which must guarantee that they remain
  179. valid until the handler is called.
  180. @param handler The completion handler to invoke when the operation
  181. completes. The implementation takes ownership of the handler by
  182. performing a decay-copy. The equivalent function signature of
  183. the handler must be:
  184. @code
  185. void handler(
  186. error_code const& error, // Result of operation.
  187. std::size_t bytes_transferred // Number of bytes read.
  188. );
  189. @endcode
  190. Regardless of whether the asynchronous operation completes
  191. immediately or not, the handler will not be invoked from within
  192. this function. Invocation of the handler will be performed in a
  193. manner equivalent to using `net::post`.
  194. @note The `read_some` operation may not read all of the requested number of
  195. bytes. Consider using the function `net::async_read` if you need
  196. to ensure that the requested amount of data is read before the asynchronous
  197. operation completes.
  198. */
  199. template<
  200. class MutableBufferSequence,
  201. BOOST_BEAST_ASYNC_TPARAM2 ReadHandler =
  202. net::default_completion_token_t<executor_type>>
  203. BOOST_BEAST_ASYNC_RESULT2(ReadHandler)
  204. async_read_some(
  205. MutableBufferSequence const& buffers,
  206. ReadHandler&& handler =
  207. net::default_completion_token_t<executor_type>{});
  208. /** Write some data to the stream.
  209. This function is used to write data on the stream. The function call will
  210. block until one or more bytes of data has been written successfully, or
  211. until an error occurs.
  212. @param buffers The data to be written.
  213. @returns The number of bytes written.
  214. @throws boost::system::system_error Thrown on failure.
  215. @note The `write_some` operation may not transmit all of the data to the
  216. peer. Consider using the function `net::write` if you need to
  217. ensure that all data is written before the blocking operation completes.
  218. */
  219. template<class ConstBufferSequence>
  220. std::size_t
  221. write_some(ConstBufferSequence const& buffers);
  222. /** Write some data to the stream.
  223. This function is used to write data on the stream. The function call will
  224. block until one or more bytes of data has been written successfully, or
  225. until an error occurs.
  226. @param buffers The data to be written.
  227. @param ec Set to indicate what error occurred, if any.
  228. @returns The number of bytes written.
  229. @note The `write_some` operation may not transmit all of the data to the
  230. peer. Consider using the function `net::write` if you need to
  231. ensure that all data is written before the blocking operation completes.
  232. */
  233. template<class ConstBufferSequence>
  234. std::size_t
  235. write_some(
  236. ConstBufferSequence const& buffers,
  237. error_code& ec);
  238. /** Start an asynchronous write.
  239. This function is used to asynchronously write one or more bytes of data to
  240. the stream. The function call always returns immediately.
  241. @param buffers The data to be written to the stream. Although the buffers
  242. object may be copied as necessary, ownership of the underlying buffers is
  243. retained by the caller, which must guarantee that they remain valid until
  244. the handler is called.
  245. @param handler The completion handler to invoke when the operation
  246. completes. The implementation takes ownership of the handler by
  247. performing a decay-copy. The equivalent function signature of
  248. the handler must be:
  249. @code
  250. void handler(
  251. error_code const& ec, // Result of operation.
  252. std::size_t bytes_transferred // Number of bytes written.
  253. );
  254. @endcode
  255. Regardless of whether the asynchronous operation completes
  256. immediately or not, the handler will not be invoked from within
  257. this function. Invocation of the handler will be performed in a
  258. manner equivalent to using `net::post`.
  259. @note The `async_write_some` operation may not transmit all of the data to
  260. the peer. Consider using the function `net::async_write` if you need
  261. to ensure that all data is written before the asynchronous operation completes.
  262. */
  263. template<
  264. class ConstBufferSequence,
  265. BOOST_BEAST_ASYNC_TPARAM2 WriteHandler =
  266. net::default_completion_token_t<executor_type>>
  267. BOOST_BEAST_ASYNC_RESULT2(WriteHandler)
  268. async_write_some(
  269. ConstBufferSequence const& buffers,
  270. WriteHandler&& handler =
  271. net::default_completion_token_t<executor_type>{});
  272. };
  273. } // beast
  274. } // boost
  275. #include <boost/beast/core/impl/flat_stream.hpp>
  276. #endif