Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

basic_streambuf.hpp 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //
  2. // basic_streambuf.hpp
  3. // ~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2015 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/config.hpp"
  16. #if !defined(ASIO_NO_IOSTREAM)
  17. #include <algorithm>
  18. #include <cstring>
  19. #include <stdexcept>
  20. #include <streambuf>
  21. #include <vector>
  22. #include "asio/basic_streambuf_fwd.hpp"
  23. #include "asio/buffer.hpp"
  24. #include "asio/detail/limits.hpp"
  25. #include "asio/detail/noncopyable.hpp"
  26. #include "asio/detail/throw_exception.hpp"
  27. #include "asio/detail/push_options.hpp"
  28. namespace asio {
  29. /// Automatically resizable buffer class based on std::streambuf.
  30. /**
  31. * The @c basic_streambuf class is derived from @c std::streambuf to associate
  32. * the streambuf's input and output sequences with one or more character
  33. * arrays. These character arrays are internal to the @c basic_streambuf
  34. * object, but direct access to the array elements is provided to permit them
  35. * to be used efficiently with I/O operations. Characters written to the output
  36. * sequence of a @c basic_streambuf object are appended to the input sequence
  37. * of the same object.
  38. *
  39. * The @c basic_streambuf class's public interface is intended to permit the
  40. * following implementation strategies:
  41. *
  42. * @li A single contiguous character array, which is reallocated as necessary
  43. * to accommodate changes in the size of the character sequence. This is the
  44. * implementation approach currently used in Asio.
  45. *
  46. * @li A sequence of one or more character arrays, where each array is of the
  47. * same size. Additional character array objects are appended to the sequence
  48. * to accommodate changes in the size of the character sequence.
  49. *
  50. * @li A sequence of one or more character arrays of varying sizes. Additional
  51. * character array objects are appended to the sequence to accommodate changes
  52. * in the size of the character sequence.
  53. *
  54. * The constructor for basic_streambuf accepts a @c size_t argument specifying
  55. * the maximum of the sum of the sizes of the input sequence and output
  56. * sequence. During the lifetime of the @c basic_streambuf object, the following
  57. * invariant holds:
  58. * @code size() <= max_size()@endcode
  59. * Any member function that would, if successful, cause the invariant to be
  60. * violated shall throw an exception of class @c std::length_error.
  61. *
  62. * The constructor for @c basic_streambuf takes an Allocator argument. A copy
  63. * of this argument is used for any memory allocation performed, by the
  64. * constructor and by all member functions, during the lifetime of each @c
  65. * basic_streambuf object.
  66. *
  67. * @par Examples
  68. * Writing directly from an streambuf to a socket:
  69. * @code
  70. * asio::streambuf b;
  71. * std::ostream os(&b);
  72. * os << "Hello, World!\n";
  73. *
  74. * // try sending some data in input sequence
  75. * size_t n = sock.send(b.data());
  76. *
  77. * b.consume(n); // sent data is removed from input sequence
  78. * @endcode
  79. *
  80. * Reading from a socket directly into a streambuf:
  81. * @code
  82. * asio::streambuf b;
  83. *
  84. * // reserve 512 bytes in output sequence
  85. * asio::streambuf::mutable_buffers_type bufs = b.prepare(512);
  86. *
  87. * size_t n = sock.receive(bufs);
  88. *
  89. * // received data is "committed" from output sequence to input sequence
  90. * b.commit(n);
  91. *
  92. * std::istream is(&b);
  93. * std::string s;
  94. * is >> s;
  95. * @endcode
  96. */
  97. #if defined(GENERATING_DOCUMENTATION)
  98. template <typename Allocator = std::allocator<char> >
  99. #else
  100. template <typename Allocator>
  101. #endif
  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 maximum_size = (std::numeric_limits<std::size_t>::max)(),
  123. const Allocator& allocator = Allocator())
  124. : max_size_(maximum_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 += buf.size();
  144. * }
  145. * @endcode
  146. */
  147. std::size_t size() const ASIO_NOEXCEPT
  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 ASIO_NOEXCEPT
  157. {
  158. return max_size_;
  159. }
  160. /// Get the current capacity of the basic_streambuf.
  161. /**
  162. * @returns The current total capacity of the streambuf, i.e. for both the
  163. * input sequence and output sequence.
  164. */
  165. std::size_t capacity() const ASIO_NOEXCEPT
  166. {
  167. return buffer_.capacity();
  168. }
  169. /// Get a list of buffers that represents the input sequence.
  170. /**
  171. * @returns An object of type @c const_buffers_type that satisfies
  172. * ConstBufferSequence requirements, representing all character arrays in the
  173. * input sequence.
  174. *
  175. * @note The returned object is invalidated by any @c basic_streambuf member
  176. * function that modifies the input sequence or output sequence.
  177. */
  178. const_buffers_type data() const ASIO_NOEXCEPT
  179. {
  180. return asio::buffer(asio::const_buffer(gptr(),
  181. (pptr() - gptr()) * sizeof(char_type)));
  182. }
  183. /// Get a list of buffers that represents the output sequence, with the given
  184. /// size.
  185. /**
  186. * Ensures that the output sequence can accommodate @c n characters,
  187. * reallocating character array objects as necessary.
  188. *
  189. * @returns An object of type @c mutable_buffers_type that satisfies
  190. * MutableBufferSequence requirements, representing character array objects
  191. * at the start of the output sequence such that the sum of the buffer sizes
  192. * is @c n.
  193. *
  194. * @throws std::length_error If <tt>size() + n > max_size()</tt>.
  195. *
  196. * @note The returned object is invalidated by any @c basic_streambuf member
  197. * function that modifies the input sequence or output sequence.
  198. */
  199. mutable_buffers_type prepare(std::size_t n)
  200. {
  201. reserve(n);
  202. return asio::buffer(asio::mutable_buffer(
  203. pptr(), n * sizeof(char_type)));
  204. }
  205. /// Move characters from the output sequence to the input sequence.
  206. /**
  207. * Appends @c n characters from the start of the output sequence to the input
  208. * sequence. The beginning of the output sequence is advanced by @c n
  209. * characters.
  210. *
  211. * Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and
  212. * no intervening operations that modify the input or output sequence.
  213. *
  214. * @note If @c n is greater than the size of the output sequence, the entire
  215. * output sequence is moved to the input sequence and no error is issued.
  216. */
  217. void commit(std::size_t n)
  218. {
  219. if (pptr() + n > epptr())
  220. 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("asio::streambuf too long");
  314. 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) ASIO_NOEXCEPT
  355. : sb_(other.sb_)
  356. {
  357. }
  358. #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  359. /// Move construct a basic_streambuf_ref.
  360. basic_streambuf_ref(basic_streambuf_ref&& other) ASIO_NOEXCEPT
  361. : sb_(other.sb_)
  362. {
  363. }
  364. #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  365. /// Get the size of the input sequence.
  366. std::size_t size() const ASIO_NOEXCEPT
  367. {
  368. return sb_.size();
  369. }
  370. /// Get the maximum size of the dynamic buffer.
  371. std::size_t max_size() const ASIO_NOEXCEPT
  372. {
  373. return sb_.max_size();
  374. }
  375. /// Get the current capacity of the dynamic buffer.
  376. std::size_t capacity() const 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 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. #include "asio/detail/pop_options.hpp"
  406. #endif // !defined(ASIO_NO_IOSTREAM)
  407. #endif // ASIO_BASIC_STREAMBUF_HPP