basic_streambuf.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //
  2. // basic_streambuf.hpp
  3. // ~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2008 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/push_options.hpp>
  16. #include <boost/asio/detail/push_options.hpp>
  17. #include <algorithm>
  18. #include <cstring>
  19. #include <limits>
  20. #include <memory>
  21. #include <stdexcept>
  22. #include <streambuf>
  23. #include <vector>
  24. #include <boost/throw_exception.hpp>
  25. #include <boost/asio/detail/pop_options.hpp>
  26. #include <boost/asio/buffer.hpp>
  27. #include <boost/asio/detail/noncopyable.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::const_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. template <typename Allocator = std::allocator<char> >
  99. class basic_streambuf
  100. : public std::streambuf,
  101. private noncopyable
  102. {
  103. public:
  104. #if defined(GENERATING_DOCUMENTATION)
  105. /// The type used to represent the input sequence as a list of buffers.
  106. typedef implementation_defined const_buffers_type;
  107. /// The type used to represent the output sequence as a list of buffers.
  108. typedef implementation_defined mutable_buffers_type;
  109. #else
  110. typedef boost::asio::const_buffers_1 const_buffers_type;
  111. typedef boost::asio::mutable_buffers_1 mutable_buffers_type;
  112. #endif
  113. /// Construct a basic_streambuf object.
  114. /**
  115. * Constructs a streambuf with the specified maximum size. The initial size
  116. * of the streambuf's input sequence is 0.
  117. */
  118. explicit basic_streambuf(
  119. std::size_t max_size = (std::numeric_limits<std::size_t>::max)(),
  120. const Allocator& allocator = Allocator())
  121. : max_size_(max_size),
  122. buffer_(allocator)
  123. {
  124. std::size_t pend = (std::min<std::size_t>)(max_size_, buffer_delta);
  125. buffer_.resize((std::max<std::size_t>)(pend, 1));
  126. setg(&buffer_[0], &buffer_[0], &buffer_[0]);
  127. setp(&buffer_[0], &buffer_[0] + pend);
  128. }
  129. /// Get the size of the input sequence.
  130. /**
  131. * @returns The size of the input sequence. The value is equal to that
  132. * calculated for @c s in the following code:
  133. * @code
  134. * size_t s = 0;
  135. * const_buffers_type bufs = data();
  136. * const_buffers_type::const_iterator i = bufs.begin();
  137. * while (i != bufs.end())
  138. * {
  139. * const_buffer buf(*i++);
  140. * s += buffer_size(buf);
  141. * }
  142. * @endcode
  143. */
  144. std::size_t size() const
  145. {
  146. return pptr() - gptr();
  147. }
  148. /// Get the maximum size of the basic_streambuf.
  149. /**
  150. * @returns The allowed maximum of the sum of the sizes of the input sequence
  151. * and output sequence.
  152. */
  153. std::size_t max_size() const
  154. {
  155. return max_size_;
  156. }
  157. /// Get a list of buffers that represents the input sequence.
  158. /**
  159. * @returns An object of type @c const_buffers_type that satisfies
  160. * ConstBufferSequence requirements, representing all character arrays in the
  161. * input sequence.
  162. *
  163. * @note The returned object is invalidated by any @c basic_streambuf member
  164. * function that modifies the input sequence or output sequence.
  165. */
  166. const_buffers_type data() const
  167. {
  168. return boost::asio::buffer(boost::asio::const_buffer(gptr(),
  169. (pptr() - gptr()) * sizeof(char_type)));
  170. }
  171. /// Get a list of buffers that represents the output sequence, with the given
  172. /// size.
  173. /**
  174. * Ensures that the output sequence can accommodate @c n characters,
  175. * reallocating character array objects as necessary.
  176. *
  177. * @returns An object of type @c mutable_buffers_type that satisfies
  178. * MutableBufferSequence requirements, representing character array objects
  179. * at the start of the output sequence such that the sum of the buffer sizes
  180. * is @c n.
  181. *
  182. * @throws std::length_error If <tt>size() + n > max_size()</tt>.
  183. *
  184. * @note The returned object is invalidated by any @c basic_streambuf member
  185. * function that modifies the input sequence or output sequence.
  186. */
  187. mutable_buffers_type prepare(std::size_t n)
  188. {
  189. reserve(n);
  190. return boost::asio::buffer(boost::asio::mutable_buffer(
  191. pptr(), n * sizeof(char_type)));
  192. }
  193. /// Move characters from the output sequence to the input sequence.
  194. /**
  195. * Appends @c n characters from the start of the output sequence to the input
  196. * sequence. The beginning of the output sequence is advanced by @c n
  197. * characters.
  198. *
  199. * Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and
  200. * no intervening operations that modify the input or output sequence.
  201. *
  202. * @throws std::length_error If @c n is greater than the size of the output
  203. * sequence.
  204. */
  205. void commit(std::size_t n)
  206. {
  207. if (pptr() + n > epptr())
  208. n = epptr() - pptr();
  209. pbump(static_cast<int>(n));
  210. setg(eback(), gptr(), pptr());
  211. }
  212. /// Remove characters from the input sequence.
  213. /**
  214. * Removes @c n characters from the beginning of the input sequence.
  215. *
  216. * @throws std::length_error If <tt>n > size()</tt>.
  217. */
  218. void consume(std::size_t n)
  219. {
  220. if (gptr() + n > pptr())
  221. n = pptr() - gptr();
  222. gbump(static_cast<int>(n));
  223. }
  224. protected:
  225. enum { buffer_delta = 128 };
  226. /// Override std::streambuf behaviour.
  227. /**
  228. * Behaves according to the specification of @c std::streambuf::underflow().
  229. */
  230. int_type underflow()
  231. {
  232. if (gptr() < pptr())
  233. {
  234. setg(&buffer_[0], gptr(), pptr());
  235. return traits_type::to_int_type(*gptr());
  236. }
  237. else
  238. {
  239. return traits_type::eof();
  240. }
  241. }
  242. /// Override std::streambuf behaviour.
  243. /**
  244. * Behaves according to the specification of @c std::streambuf::overflow(),
  245. * with the specialisation that @c std::length_error is thrown if appending
  246. * the character to the input sequence would require the condition
  247. * <tt>size() > max_size()</tt> to be true.
  248. */
  249. int_type overflow(int_type c)
  250. {
  251. if (!traits_type::eq_int_type(c, traits_type::eof()))
  252. {
  253. if (pptr() == epptr())
  254. {
  255. std::size_t buffer_size = pptr() - gptr();
  256. if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta)
  257. {
  258. reserve(max_size_ - buffer_size);
  259. }
  260. else
  261. {
  262. reserve(buffer_delta);
  263. }
  264. }
  265. *pptr() = traits_type::to_char_type(c);
  266. pbump(1);
  267. return c;
  268. }
  269. return traits_type::not_eof(c);
  270. }
  271. void reserve(std::size_t n)
  272. {
  273. // Get current stream positions as offsets.
  274. std::size_t gnext = gptr() - &buffer_[0];
  275. std::size_t pnext = pptr() - &buffer_[0];
  276. std::size_t pend = epptr() - &buffer_[0];
  277. // Check if there is already enough space in the put area.
  278. if (n <= pend - pnext)
  279. {
  280. return;
  281. }
  282. // Shift existing contents of get area to start of buffer.
  283. if (gnext > 0)
  284. {
  285. pnext -= gnext;
  286. std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext);
  287. }
  288. // Ensure buffer is large enough to hold at least the specified size.
  289. if (n > pend - pnext)
  290. {
  291. if (n <= max_size_ && pnext <= max_size_ - n)
  292. {
  293. pend = pnext + n;
  294. buffer_.resize((std::max<std::size_t>)(pend, 1));
  295. }
  296. else
  297. {
  298. std::length_error ex("boost::asio::streambuf too long");
  299. boost::throw_exception(ex);
  300. }
  301. }
  302. // Update stream positions.
  303. setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext);
  304. setp(&buffer_[0] + pnext, &buffer_[0] + pend);
  305. }
  306. private:
  307. std::size_t max_size_;
  308. std::vector<char_type, Allocator> buffer_;
  309. };
  310. } // namespace asio
  311. } // namespace boost
  312. #include <boost/asio/detail/pop_options.hpp>
  313. #endif // BOOST_ASIO_BASIC_STREAMBUF_HPP