basic_streambuf.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //
  2. // basic_streambuf.hpp
  3. // ~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 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 BOOST_ASIO_BASIC_STREAMBUF_HPP
  11. #define BOOST_ASIO_BASIC_STREAMBUF_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #if !defined(BOOST_ASIO_NO_IOSTREAM)
  17. #include <algorithm>
  18. #include <cstring>
  19. #include <stdexcept>
  20. #include <streambuf>
  21. #include <vector>
  22. #include <boost/asio/basic_streambuf_fwd.hpp>
  23. #include <boost/asio/buffer.hpp>
  24. #include <boost/asio/detail/limits.hpp>
  25. #include <boost/asio/detail/noncopyable.hpp>
  26. #include <boost/asio/detail/throw_exception.hpp>
  27. #include <boost/asio/detail/push_options.hpp>
  28. namespace boost {
  29. namespace asio {
  30. /// Automatically resizable buffer class based on std::streambuf.
  31. /**
  32. * The @c basic_streambuf class is derived from @c std::streambuf to associate
  33. * the streambuf's input and output sequences with one or more character
  34. * arrays. These character arrays are internal to the @c basic_streambuf
  35. * object, but direct access to the array elements is provided to permit them
  36. * to be used efficiently with I/O operations. Characters written to the output
  37. * sequence of a @c basic_streambuf object are appended to the input sequence
  38. * of the same object.
  39. *
  40. * The @c basic_streambuf class's public interface is intended to permit the
  41. * following implementation strategies:
  42. *
  43. * @li A single contiguous character array, which is reallocated as necessary
  44. * to accommodate changes in the size of the character sequence. This is the
  45. * implementation approach currently used in Asio.
  46. *
  47. * @li A sequence of one or more character arrays, where each array is of the
  48. * same size. Additional character array objects are appended to the sequence
  49. * to accommodate changes in the size of the character sequence.
  50. *
  51. * @li A sequence of one or more character arrays of varying sizes. Additional
  52. * character array objects are appended to the sequence to accommodate changes
  53. * in the size of the character sequence.
  54. *
  55. * The constructor for basic_streambuf accepts a @c size_t argument specifying
  56. * the maximum of the sum of the sizes of the input sequence and output
  57. * sequence. During the lifetime of the @c basic_streambuf object, the following
  58. * invariant holds:
  59. * @code size() <= max_size()@endcode
  60. * Any member function that would, if successful, cause the invariant to be
  61. * violated shall throw an exception of class @c std::length_error.
  62. *
  63. * The constructor for @c basic_streambuf takes an Allocator argument. A copy
  64. * of this argument is used for any memory allocation performed, by the
  65. * constructor and by all member functions, during the lifetime of each @c
  66. * basic_streambuf object.
  67. *
  68. * @par Examples
  69. * Writing directly from an streambuf to a socket:
  70. * @code
  71. * boost::asio::streambuf b;
  72. * std::ostream os(&b);
  73. * os << "Hello, World!\n";
  74. *
  75. * // try sending some data in input sequence
  76. * size_t n = sock.send(b.data());
  77. *
  78. * b.consume(n); // sent data is removed from input sequence
  79. * @endcode
  80. *
  81. * Reading from a socket directly into a streambuf:
  82. * @code
  83. * boost::asio::streambuf b;
  84. *
  85. * // reserve 512 bytes in output sequence
  86. * boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);
  87. *
  88. * size_t n = sock.receive(bufs);
  89. *
  90. * // received data is "committed" from output sequence to input sequence
  91. * b.commit(n);
  92. *
  93. * std::istream is(&b);
  94. * std::string s;
  95. * is >> s;
  96. * @endcode
  97. */
  98. #if defined(GENERATING_DOCUMENTATION)
  99. template <typename Allocator = std::allocator<char> >
  100. #else
  101. template <typename Allocator>
  102. #endif
  103. class basic_streambuf
  104. : public std::streambuf,
  105. private noncopyable
  106. {
  107. public:
  108. #if defined(GENERATING_DOCUMENTATION)
  109. /// The type used to represent the input sequence as a list of buffers.
  110. typedef implementation_defined const_buffers_type;
  111. /// The type used to represent the output sequence as a list of buffers.
  112. typedef implementation_defined mutable_buffers_type;
  113. #else
  114. typedef BOOST_ASIO_CONST_BUFFER const_buffers_type;
  115. typedef BOOST_ASIO_MUTABLE_BUFFER mutable_buffers_type;
  116. #endif
  117. /// Construct a basic_streambuf object.
  118. /**
  119. * Constructs a streambuf with the specified maximum size. The initial size
  120. * of the streambuf's input sequence is 0.
  121. */
  122. explicit basic_streambuf(
  123. std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)(),
  124. const Allocator& allocator = Allocator())
  125. : max_size_(maximum_size),
  126. buffer_(allocator)
  127. {
  128. std::size_t pend = (std::min<std::size_t>)(max_size_, buffer_delta);
  129. buffer_.resize((std::max<std::size_t>)(pend, 1));
  130. setg(&buffer_[0], &buffer_[0], &buffer_[0]);
  131. setp(&buffer_[0], &buffer_[0] + pend);
  132. }
  133. /// Get the size of the input sequence.
  134. /**
  135. * @returns The size of the input sequence. The value is equal to that
  136. * calculated for @c s in the following code:
  137. * @code
  138. * size_t s = 0;
  139. * const_buffers_type bufs = data();
  140. * const_buffers_type::const_iterator i = bufs.begin();
  141. * while (i != bufs.end())
  142. * {
  143. * const_buffer buf(*i++);
  144. * s += buf.size();
  145. * }
  146. * @endcode
  147. */
  148. std::size_t size() const BOOST_ASIO_NOEXCEPT
  149. {
  150. return pptr() - gptr();
  151. }
  152. /// Get the maximum size of the basic_streambuf.
  153. /**
  154. * @returns The allowed maximum of the sum of the sizes of the input sequence
  155. * and output sequence.
  156. */
  157. std::size_t max_size() const BOOST_ASIO_NOEXCEPT
  158. {
  159. return max_size_;
  160. }
  161. /// Get the current capacity of the basic_streambuf.
  162. /**
  163. * @returns The current total capacity of the streambuf, i.e. for both the
  164. * input sequence and output sequence.
  165. */
  166. std::size_t capacity() const BOOST_ASIO_NOEXCEPT
  167. {
  168. return buffer_.capacity();
  169. }
  170. /// Get a list of buffers that represents the input sequence.
  171. /**
  172. * @returns An object of type @c const_buffers_type that satisfies
  173. * ConstBufferSequence requirements, representing all character arrays in the
  174. * input sequence.
  175. *
  176. * @note The returned object is invalidated by any @c basic_streambuf member
  177. * function that modifies the input sequence or output sequence.
  178. */
  179. const_buffers_type data() const BOOST_ASIO_NOEXCEPT
  180. {
  181. return boost::asio::buffer(boost::asio::const_buffer(gptr(),
  182. (pptr() - gptr()) * sizeof(char_type)));
  183. }
  184. /// Get a list of buffers that represents the output sequence, with the given
  185. /// size.
  186. /**
  187. * Ensures that the output sequence can accommodate @c n characters,
  188. * reallocating character array objects as necessary.
  189. *
  190. * @returns An object of type @c mutable_buffers_type that satisfies
  191. * MutableBufferSequence requirements, representing character array objects
  192. * at the start of the output sequence such that the sum of the buffer sizes
  193. * is @c n.
  194. *
  195. * @throws std::length_error If <tt>size() + n > max_size()</tt>.
  196. *
  197. * @note The returned object is invalidated by any @c basic_streambuf member
  198. * function that modifies the input sequence or output sequence.
  199. */
  200. mutable_buffers_type prepare(std::size_t n)
  201. {
  202. reserve(n);
  203. return boost::asio::buffer(boost::asio::mutable_buffer(
  204. pptr(), n * sizeof(char_type)));
  205. }
  206. /// Move characters from the output sequence to the input sequence.
  207. /**
  208. * Appends @c n characters from the start of the output sequence to the input
  209. * sequence. The beginning of the output sequence is advanced by @c n
  210. * characters.
  211. *
  212. * Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and
  213. * no intervening operations that modify the input or output sequence.
  214. *
  215. * @note If @c n is greater than the size of the output sequence, the entire
  216. * output sequence is moved to the input sequence and no error is issued.
  217. */
  218. void commit(std::size_t n)
  219. {
  220. n = std::min<std::size_t>(n, epptr() - pptr());
  221. pbump(static_cast<int>(n));
  222. setg(eback(), gptr(), pptr());
  223. }
  224. /// Remove characters from the input sequence.
  225. /**
  226. * Removes @c n characters from the beginning of the input sequence.
  227. *
  228. * @note If @c n is greater than the size of the input sequence, the entire
  229. * input sequence is consumed and no error is issued.
  230. */
  231. void consume(std::size_t n)
  232. {
  233. if (egptr() < pptr())
  234. setg(&buffer_[0], gptr(), pptr());
  235. if (gptr() + n > pptr())
  236. n = pptr() - gptr();
  237. gbump(static_cast<int>(n));
  238. }
  239. protected:
  240. enum { buffer_delta = 128 };
  241. /// Override std::streambuf behaviour.
  242. /**
  243. * Behaves according to the specification of @c std::streambuf::underflow().
  244. */
  245. int_type underflow()
  246. {
  247. if (gptr() < pptr())
  248. {
  249. setg(&buffer_[0], gptr(), pptr());
  250. return traits_type::to_int_type(*gptr());
  251. }
  252. else
  253. {
  254. return traits_type::eof();
  255. }
  256. }
  257. /// Override std::streambuf behaviour.
  258. /**
  259. * Behaves according to the specification of @c std::streambuf::overflow(),
  260. * with the specialisation that @c std::length_error is thrown if appending
  261. * the character to the input sequence would require the condition
  262. * <tt>size() > max_size()</tt> to be true.
  263. */
  264. int_type overflow(int_type c)
  265. {
  266. if (!traits_type::eq_int_type(c, traits_type::eof()))
  267. {
  268. if (pptr() == epptr())
  269. {
  270. std::size_t buffer_size = pptr() - gptr();
  271. if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta)
  272. {
  273. reserve(max_size_ - buffer_size);
  274. }
  275. else
  276. {
  277. reserve(buffer_delta);
  278. }
  279. }
  280. *pptr() = traits_type::to_char_type(c);
  281. pbump(1);
  282. return c;
  283. }
  284. return traits_type::not_eof(c);
  285. }
  286. void reserve(std::size_t n)
  287. {
  288. // Get current stream positions as offsets.
  289. std::size_t gnext = gptr() - &buffer_[0];
  290. std::size_t pnext = pptr() - &buffer_[0];
  291. std::size_t pend = epptr() - &buffer_[0];
  292. // Check if there is already enough space in the put area.
  293. if (n <= pend - pnext)
  294. {
  295. return;
  296. }
  297. // Shift existing contents of get area to start of buffer.
  298. if (gnext > 0)
  299. {
  300. pnext -= gnext;
  301. std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext);
  302. }
  303. // Ensure buffer is large enough to hold at least the specified size.
  304. if (n > pend - pnext)
  305. {
  306. if (n <= max_size_ && pnext <= max_size_ - n)
  307. {
  308. pend = pnext + n;
  309. buffer_.resize((std::max<std::size_t>)(pend, 1));
  310. }
  311. else
  312. {
  313. std::length_error ex("boost::asio::streambuf too long");
  314. boost::asio::detail::throw_exception(ex);
  315. }
  316. }
  317. // Update stream positions.
  318. setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext);
  319. setp(&buffer_[0] + pnext, &buffer_[0] + pend);
  320. }
  321. private:
  322. std::size_t max_size_;
  323. std::vector<char_type, Allocator> buffer_;
  324. // Helper function to get the preferred size for reading data.
  325. friend std::size_t read_size_helper(
  326. basic_streambuf& sb, std::size_t max_size)
  327. {
  328. return std::min<std::size_t>(
  329. std::max<std::size_t>(512, sb.buffer_.capacity() - sb.size()),
  330. std::min<std::size_t>(max_size, sb.max_size() - sb.size()));
  331. }
  332. };
  333. /// Adapts basic_streambuf to the dynamic buffer sequence type requirements.
  334. #if defined(GENERATING_DOCUMENTATION)
  335. template <typename Allocator = std::allocator<char> >
  336. #else
  337. template <typename Allocator>
  338. #endif
  339. class basic_streambuf_ref
  340. {
  341. public:
  342. /// The type used to represent the input sequence as a list of buffers.
  343. typedef typename basic_streambuf<Allocator>::const_buffers_type
  344. const_buffers_type;
  345. /// The type used to represent the output sequence as a list of buffers.
  346. typedef typename basic_streambuf<Allocator>::mutable_buffers_type
  347. mutable_buffers_type;
  348. /// Construct a basic_streambuf_ref for the given basic_streambuf object.
  349. explicit basic_streambuf_ref(basic_streambuf<Allocator>& sb)
  350. : sb_(sb)
  351. {
  352. }
  353. /// Copy construct a basic_streambuf_ref.
  354. basic_streambuf_ref(const basic_streambuf_ref& other) BOOST_ASIO_NOEXCEPT
  355. : sb_(other.sb_)
  356. {
  357. }
  358. #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  359. /// Move construct a basic_streambuf_ref.
  360. basic_streambuf_ref(basic_streambuf_ref&& other) BOOST_ASIO_NOEXCEPT
  361. : sb_(other.sb_)
  362. {
  363. }
  364. #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  365. /// Get the size of the input sequence.
  366. std::size_t size() const BOOST_ASIO_NOEXCEPT
  367. {
  368. return sb_.size();
  369. }
  370. /// Get the maximum size of the dynamic buffer.
  371. std::size_t max_size() const BOOST_ASIO_NOEXCEPT
  372. {
  373. return sb_.max_size();
  374. }
  375. /// Get the current capacity of the dynamic buffer.
  376. std::size_t capacity() const BOOST_ASIO_NOEXCEPT
  377. {
  378. return sb_.capacity();
  379. }
  380. /// Get a list of buffers that represents the input sequence.
  381. const_buffers_type data() const BOOST_ASIO_NOEXCEPT
  382. {
  383. return sb_.data();
  384. }
  385. /// Get a list of buffers that represents the output sequence, with the given
  386. /// size.
  387. mutable_buffers_type prepare(std::size_t n)
  388. {
  389. return sb_.prepare(n);
  390. }
  391. /// Move bytes from the output sequence to the input sequence.
  392. void commit(std::size_t n)
  393. {
  394. return sb_.commit(n);
  395. }
  396. /// Remove characters from the input sequence.
  397. void consume(std::size_t n)
  398. {
  399. return sb_.consume(n);
  400. }
  401. private:
  402. basic_streambuf<Allocator>& sb_;
  403. };
  404. } // namespace asio
  405. } // namespace boost
  406. #include <boost/asio/detail/pop_options.hpp>
  407. #endif // !defined(BOOST_ASIO_NO_IOSTREAM)
  408. #endif // BOOST_ASIO_BASIC_STREAMBUF_HPP