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.

453 lines
13KB

  1. //
  2. // basic_streambuf.hpp
  3. // ~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 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_BUFFER const_buffers_type;
  114. typedef ASIO_MUTABLE_BUFFER 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. n = std::min<std::size_t>(n, epptr() - pptr());
  220. pbump(static_cast<int>(n));
  221. setg(eback(), gptr(), pptr());
  222. }
  223. /// Remove characters from the input sequence.
  224. /**
  225. * Removes @c n characters from the beginning of the input sequence.
  226. *
  227. * @note If @c n is greater than the size of the input sequence, the entire
  228. * input sequence is consumed and no error is issued.
  229. */
  230. void consume(std::size_t n)
  231. {
  232. if (egptr() < pptr())
  233. setg(&buffer_[0], gptr(), pptr());
  234. if (gptr() + n > pptr())
  235. n = pptr() - gptr();
  236. gbump(static_cast<int>(n));
  237. }
  238. protected:
  239. enum { buffer_delta = 128 };
  240. /// Override std::streambuf behaviour.
  241. /**
  242. * Behaves according to the specification of @c std::streambuf::underflow().
  243. */
  244. int_type underflow()
  245. {
  246. if (gptr() < pptr())
  247. {
  248. setg(&buffer_[0], gptr(), pptr());
  249. return traits_type::to_int_type(*gptr());
  250. }
  251. else
  252. {
  253. return traits_type::eof();
  254. }
  255. }
  256. /// Override std::streambuf behaviour.
  257. /**
  258. * Behaves according to the specification of @c std::streambuf::overflow(),
  259. * with the specialisation that @c std::length_error is thrown if appending
  260. * the character to the input sequence would require the condition
  261. * <tt>size() > max_size()</tt> to be true.
  262. */
  263. int_type overflow(int_type c)
  264. {
  265. if (!traits_type::eq_int_type(c, traits_type::eof()))
  266. {
  267. if (pptr() == epptr())
  268. {
  269. std::size_t buffer_size = pptr() - gptr();
  270. if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta)
  271. {
  272. reserve(max_size_ - buffer_size);
  273. }
  274. else
  275. {
  276. reserve(buffer_delta);
  277. }
  278. }
  279. *pptr() = traits_type::to_char_type(c);
  280. pbump(1);
  281. return c;
  282. }
  283. return traits_type::not_eof(c);
  284. }
  285. void reserve(std::size_t n)
  286. {
  287. // Get current stream positions as offsets.
  288. std::size_t gnext = gptr() - &buffer_[0];
  289. std::size_t pnext = pptr() - &buffer_[0];
  290. std::size_t pend = epptr() - &buffer_[0];
  291. // Check if there is already enough space in the put area.
  292. if (n <= pend - pnext)
  293. {
  294. return;
  295. }
  296. // Shift existing contents of get area to start of buffer.
  297. if (gnext > 0)
  298. {
  299. pnext -= gnext;
  300. std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext);
  301. }
  302. // Ensure buffer is large enough to hold at least the specified size.
  303. if (n > pend - pnext)
  304. {
  305. if (n <= max_size_ && pnext <= max_size_ - n)
  306. {
  307. pend = pnext + n;
  308. buffer_.resize((std::max<std::size_t>)(pend, 1));
  309. }
  310. else
  311. {
  312. std::length_error ex("asio::streambuf too long");
  313. asio::detail::throw_exception(ex);
  314. }
  315. }
  316. // Update stream positions.
  317. setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext);
  318. setp(&buffer_[0] + pnext, &buffer_[0] + pend);
  319. }
  320. private:
  321. std::size_t max_size_;
  322. std::vector<char_type, Allocator> buffer_;
  323. // Helper function to get the preferred size for reading data.
  324. friend std::size_t read_size_helper(
  325. basic_streambuf& sb, std::size_t max_size)
  326. {
  327. return std::min<std::size_t>(
  328. std::max<std::size_t>(512, sb.buffer_.capacity() - sb.size()),
  329. std::min<std::size_t>(max_size, sb.max_size() - sb.size()));
  330. }
  331. };
  332. /// Adapts basic_streambuf to the dynamic buffer sequence type requirements.
  333. #if defined(GENERATING_DOCUMENTATION)
  334. template <typename Allocator = std::allocator<char> >
  335. #else
  336. template <typename Allocator>
  337. #endif
  338. class basic_streambuf_ref
  339. {
  340. public:
  341. /// The type used to represent the input sequence as a list of buffers.
  342. typedef typename basic_streambuf<Allocator>::const_buffers_type
  343. const_buffers_type;
  344. /// The type used to represent the output sequence as a list of buffers.
  345. typedef typename basic_streambuf<Allocator>::mutable_buffers_type
  346. mutable_buffers_type;
  347. /// Construct a basic_streambuf_ref for the given basic_streambuf object.
  348. explicit basic_streambuf_ref(basic_streambuf<Allocator>& sb)
  349. : sb_(sb)
  350. {
  351. }
  352. /// Copy construct a basic_streambuf_ref.
  353. basic_streambuf_ref(const basic_streambuf_ref& other) ASIO_NOEXCEPT
  354. : sb_(other.sb_)
  355. {
  356. }
  357. #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  358. /// Move construct a basic_streambuf_ref.
  359. basic_streambuf_ref(basic_streambuf_ref&& other) ASIO_NOEXCEPT
  360. : sb_(other.sb_)
  361. {
  362. }
  363. #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  364. /// Get the size of the input sequence.
  365. std::size_t size() const ASIO_NOEXCEPT
  366. {
  367. return sb_.size();
  368. }
  369. /// Get the maximum size of the dynamic buffer.
  370. std::size_t max_size() const ASIO_NOEXCEPT
  371. {
  372. return sb_.max_size();
  373. }
  374. /// Get the current capacity of the dynamic buffer.
  375. std::size_t capacity() const ASIO_NOEXCEPT
  376. {
  377. return sb_.capacity();
  378. }
  379. /// Get a list of buffers that represents the input sequence.
  380. const_buffers_type data() const ASIO_NOEXCEPT
  381. {
  382. return sb_.data();
  383. }
  384. /// Get a list of buffers that represents the output sequence, with the given
  385. /// size.
  386. mutable_buffers_type prepare(std::size_t n)
  387. {
  388. return sb_.prepare(n);
  389. }
  390. /// Move bytes from the output sequence to the input sequence.
  391. void commit(std::size_t n)
  392. {
  393. return sb_.commit(n);
  394. }
  395. /// Remove characters from the input sequence.
  396. void consume(std::size_t n)
  397. {
  398. return sb_.consume(n);
  399. }
  400. private:
  401. basic_streambuf<Allocator>& sb_;
  402. };
  403. } // namespace asio
  404. #include "asio/detail/pop_options.hpp"
  405. #endif // !defined(ASIO_NO_IOSTREAM)
  406. #endif // ASIO_BASIC_STREAMBUF_HPP