buffered_write_stream.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. //
  2. // buffered_write_stream.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2011 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_BUFFERED_WRITE_STREAM_HPP
  11. #define ASIO_BUFFERED_WRITE_STREAM_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 <cstddef>
  17. #include <cstring>
  18. #include <boost/type_traits/remove_reference.hpp>
  19. #include "asio/buffered_write_stream_fwd.hpp"
  20. #include "asio/buffer.hpp"
  21. #include "asio/completion_condition.hpp"
  22. #include "asio/detail/bind_handler.hpp"
  23. #include "asio/detail/buffered_stream_storage.hpp"
  24. #include "asio/detail/noncopyable.hpp"
  25. #include "asio/error.hpp"
  26. #include "asio/io_service.hpp"
  27. #include "asio/write.hpp"
  28. #include "asio/detail/push_options.hpp"
  29. namespace asio {
  30. /// Adds buffering to the write-related operations of a stream.
  31. /**
  32. * The buffered_write_stream class template can be used to add buffering to the
  33. * synchronous and asynchronous write operations of a stream.
  34. *
  35. * @par Thread Safety
  36. * @e Distinct @e objects: Safe.@n
  37. * @e Shared @e objects: Unsafe.
  38. *
  39. * @par Concepts:
  40. * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
  41. */
  42. template <typename Stream>
  43. class buffered_write_stream
  44. : private noncopyable
  45. {
  46. public:
  47. /// The type of the next layer.
  48. typedef typename boost::remove_reference<Stream>::type next_layer_type;
  49. /// The type of the lowest layer.
  50. typedef typename next_layer_type::lowest_layer_type lowest_layer_type;
  51. #if defined(GENERATING_DOCUMENTATION)
  52. /// The default buffer size.
  53. static const std::size_t default_buffer_size = implementation_defined;
  54. #else
  55. BOOST_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024);
  56. #endif
  57. /// Construct, passing the specified argument to initialise the next layer.
  58. template <typename Arg>
  59. explicit buffered_write_stream(Arg& a)
  60. : next_layer_(a),
  61. storage_(default_buffer_size)
  62. {
  63. }
  64. /// Construct, passing the specified argument to initialise the next layer.
  65. template <typename Arg>
  66. buffered_write_stream(Arg& a, std::size_t buffer_size)
  67. : next_layer_(a),
  68. storage_(buffer_size)
  69. {
  70. }
  71. /// Get a reference to the next layer.
  72. next_layer_type& next_layer()
  73. {
  74. return next_layer_;
  75. }
  76. /// Get a reference to the lowest layer.
  77. lowest_layer_type& lowest_layer()
  78. {
  79. return next_layer_.lowest_layer();
  80. }
  81. /// Get a const reference to the lowest layer.
  82. const lowest_layer_type& lowest_layer() const
  83. {
  84. return next_layer_.lowest_layer();
  85. }
  86. /// (Deprecated: use get_io_service().) Get the io_service associated with
  87. /// the object.
  88. asio::io_service& io_service()
  89. {
  90. return next_layer_.get_io_service();
  91. }
  92. /// Get the io_service associated with the object.
  93. asio::io_service& get_io_service()
  94. {
  95. return next_layer_.get_io_service();
  96. }
  97. /// Close the stream.
  98. void close()
  99. {
  100. next_layer_.close();
  101. }
  102. /// Close the stream.
  103. asio::error_code close(asio::error_code& ec)
  104. {
  105. return next_layer_.close(ec);
  106. }
  107. /// Flush all data from the buffer to the next layer. Returns the number of
  108. /// bytes written to the next layer on the last write operation. Throws an
  109. /// exception on failure.
  110. std::size_t flush()
  111. {
  112. std::size_t bytes_written = write(next_layer_,
  113. buffer(storage_.data(), storage_.size()));
  114. storage_.consume(bytes_written);
  115. return bytes_written;
  116. }
  117. /// Flush all data from the buffer to the next layer. Returns the number of
  118. /// bytes written to the next layer on the last write operation, or 0 if an
  119. /// error occurred.
  120. std::size_t flush(asio::error_code& ec)
  121. {
  122. std::size_t bytes_written = write(next_layer_,
  123. buffer(storage_.data(), storage_.size()),
  124. transfer_all(), ec);
  125. storage_.consume(bytes_written);
  126. return bytes_written;
  127. }
  128. template <typename WriteHandler>
  129. class flush_handler
  130. {
  131. public:
  132. flush_handler(asio::io_service& io_service,
  133. detail::buffered_stream_storage& storage, WriteHandler handler)
  134. : io_service_(io_service),
  135. storage_(storage),
  136. handler_(handler)
  137. {
  138. }
  139. void operator()(const asio::error_code& ec,
  140. std::size_t bytes_written)
  141. {
  142. storage_.consume(bytes_written);
  143. io_service_.dispatch(detail::bind_handler(handler_, ec, bytes_written));
  144. }
  145. private:
  146. asio::io_service& io_service_;
  147. detail::buffered_stream_storage& storage_;
  148. WriteHandler handler_;
  149. };
  150. /// Start an asynchronous flush.
  151. template <typename WriteHandler>
  152. void async_flush(WriteHandler handler)
  153. {
  154. async_write(next_layer_, buffer(storage_.data(), storage_.size()),
  155. flush_handler<WriteHandler>(get_io_service(), storage_, handler));
  156. }
  157. /// Write the given data to the stream. Returns the number of bytes written.
  158. /// Throws an exception on failure.
  159. template <typename ConstBufferSequence>
  160. std::size_t write_some(const ConstBufferSequence& buffers)
  161. {
  162. typename ConstBufferSequence::const_iterator iter = buffers.begin();
  163. typename ConstBufferSequence::const_iterator end = buffers.end();
  164. size_t total_buffer_size = 0;
  165. for (; iter != end; ++iter)
  166. {
  167. asio::const_buffer buffer(*iter);
  168. total_buffer_size += asio::buffer_size(buffer);
  169. }
  170. if (total_buffer_size == 0)
  171. return 0;
  172. if (storage_.size() == storage_.capacity())
  173. flush();
  174. return copy(buffers);
  175. }
  176. /// Write the given data to the stream. Returns the number of bytes written,
  177. /// or 0 if an error occurred and the error handler did not throw.
  178. template <typename ConstBufferSequence>
  179. std::size_t write_some(const ConstBufferSequence& buffers,
  180. asio::error_code& ec)
  181. {
  182. ec = asio::error_code();
  183. typename ConstBufferSequence::const_iterator iter = buffers.begin();
  184. typename ConstBufferSequence::const_iterator end = buffers.end();
  185. size_t total_buffer_size = 0;
  186. for (; iter != end; ++iter)
  187. {
  188. asio::const_buffer buffer(*iter);
  189. total_buffer_size += asio::buffer_size(buffer);
  190. }
  191. if (total_buffer_size == 0)
  192. return 0;
  193. if (storage_.size() == storage_.capacity() && !flush(ec))
  194. return 0;
  195. return copy(buffers);
  196. }
  197. template <typename ConstBufferSequence, typename WriteHandler>
  198. class write_some_handler
  199. {
  200. public:
  201. write_some_handler(asio::io_service& io_service,
  202. detail::buffered_stream_storage& storage,
  203. const ConstBufferSequence& buffers, WriteHandler handler)
  204. : io_service_(io_service),
  205. storage_(storage),
  206. buffers_(buffers),
  207. handler_(handler)
  208. {
  209. }
  210. void operator()(const asio::error_code& ec, std::size_t)
  211. {
  212. if (ec)
  213. {
  214. std::size_t length = 0;
  215. io_service_.dispatch(detail::bind_handler(handler_, ec, length));
  216. }
  217. else
  218. {
  219. using namespace std; // For memcpy.
  220. std::size_t orig_size = storage_.size();
  221. std::size_t space_avail = storage_.capacity() - orig_size;
  222. std::size_t bytes_copied = 0;
  223. typename ConstBufferSequence::const_iterator iter = buffers_.begin();
  224. typename ConstBufferSequence::const_iterator end = buffers_.end();
  225. for (; iter != end && space_avail > 0; ++iter)
  226. {
  227. std::size_t bytes_avail = buffer_size(*iter);
  228. std::size_t length = (bytes_avail < space_avail)
  229. ? bytes_avail : space_avail;
  230. storage_.resize(orig_size + bytes_copied + length);
  231. memcpy(storage_.data() + orig_size + bytes_copied,
  232. buffer_cast<const void*>(*iter), length);
  233. bytes_copied += length;
  234. space_avail -= length;
  235. }
  236. io_service_.dispatch(detail::bind_handler(handler_, ec, bytes_copied));
  237. }
  238. }
  239. private:
  240. asio::io_service& io_service_;
  241. detail::buffered_stream_storage& storage_;
  242. ConstBufferSequence buffers_;
  243. WriteHandler handler_;
  244. };
  245. /// Start an asynchronous write. The data being written must be valid for the
  246. /// lifetime of the asynchronous operation.
  247. template <typename ConstBufferSequence, typename WriteHandler>
  248. void async_write_some(const ConstBufferSequence& buffers,
  249. WriteHandler handler)
  250. {
  251. typename ConstBufferSequence::const_iterator iter = buffers.begin();
  252. typename ConstBufferSequence::const_iterator end = buffers.end();
  253. size_t total_buffer_size = 0;
  254. for (; iter != end; ++iter)
  255. {
  256. asio::const_buffer buffer(*iter);
  257. total_buffer_size += asio::buffer_size(buffer);
  258. }
  259. if (total_buffer_size == 0)
  260. {
  261. get_io_service().post(detail::bind_handler(
  262. handler, asio::error_code(), 0));
  263. }
  264. else if (storage_.size() == storage_.capacity())
  265. {
  266. async_flush(write_some_handler<ConstBufferSequence, WriteHandler>(
  267. get_io_service(), storage_, buffers, handler));
  268. }
  269. else
  270. {
  271. std::size_t bytes_copied = copy(buffers);
  272. get_io_service().post(detail::bind_handler(
  273. handler, asio::error_code(), bytes_copied));
  274. }
  275. }
  276. /// Read some data from the stream. Returns the number of bytes read. Throws
  277. /// an exception on failure.
  278. template <typename MutableBufferSequence>
  279. std::size_t read_some(const MutableBufferSequence& buffers)
  280. {
  281. return next_layer_.read_some(buffers);
  282. }
  283. /// Read some data from the stream. Returns the number of bytes read or 0 if
  284. /// an error occurred.
  285. template <typename MutableBufferSequence>
  286. std::size_t read_some(const MutableBufferSequence& buffers,
  287. asio::error_code& ec)
  288. {
  289. return next_layer_.read_some(buffers, ec);
  290. }
  291. /// Start an asynchronous read. The buffer into which the data will be read
  292. /// must be valid for the lifetime of the asynchronous operation.
  293. template <typename MutableBufferSequence, typename ReadHandler>
  294. void async_read_some(const MutableBufferSequence& buffers,
  295. ReadHandler handler)
  296. {
  297. next_layer_.async_read_some(buffers, handler);
  298. }
  299. /// Peek at the incoming data on the stream. Returns the number of bytes read.
  300. /// Throws an exception on failure.
  301. template <typename MutableBufferSequence>
  302. std::size_t peek(const MutableBufferSequence& buffers)
  303. {
  304. return next_layer_.peek(buffers);
  305. }
  306. /// Peek at the incoming data on the stream. Returns the number of bytes read,
  307. /// or 0 if an error occurred.
  308. template <typename MutableBufferSequence>
  309. std::size_t peek(const MutableBufferSequence& buffers,
  310. asio::error_code& ec)
  311. {
  312. return next_layer_.peek(buffers, ec);
  313. }
  314. /// Determine the amount of data that may be read without blocking.
  315. std::size_t in_avail()
  316. {
  317. return next_layer_.in_avail();
  318. }
  319. /// Determine the amount of data that may be read without blocking.
  320. std::size_t in_avail(asio::error_code& ec)
  321. {
  322. return next_layer_.in_avail(ec);
  323. }
  324. private:
  325. /// Copy data into the internal buffer from the specified source buffer.
  326. /// Returns the number of bytes copied.
  327. template <typename ConstBufferSequence>
  328. std::size_t copy(const ConstBufferSequence& buffers)
  329. {
  330. using namespace std; // For memcpy.
  331. std::size_t orig_size = storage_.size();
  332. std::size_t space_avail = storage_.capacity() - orig_size;
  333. std::size_t bytes_copied = 0;
  334. typename ConstBufferSequence::const_iterator iter = buffers.begin();
  335. typename ConstBufferSequence::const_iterator end = buffers.end();
  336. for (; iter != end && space_avail > 0; ++iter)
  337. {
  338. std::size_t bytes_avail = buffer_size(*iter);
  339. std::size_t length = (bytes_avail < space_avail)
  340. ? bytes_avail : space_avail;
  341. storage_.resize(orig_size + bytes_copied + length);
  342. memcpy(storage_.data() + orig_size + bytes_copied,
  343. buffer_cast<const void*>(*iter), length);
  344. bytes_copied += length;
  345. space_avail -= length;
  346. }
  347. return bytes_copied;
  348. }
  349. /// The next layer.
  350. Stream next_layer_;
  351. // The data in the buffer.
  352. detail::buffered_stream_storage storage_;
  353. };
  354. } // namespace asio
  355. #include "asio/detail/pop_options.hpp"
  356. #endif // ASIO_BUFFERED_WRITE_STREAM_HPP