basic_streambuf.hpp 10 KB

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