2 // Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8 #ifndef BEAST_TEST_STRING_ISTREAM_HPP
9 #define BEAST_TEST_STRING_ISTREAM_HPP
11 #include <beast/core/async_completion.hpp>
12 #include <beast/core/bind_handler.hpp>
13 #include <beast/core/error.hpp>
14 #include <beast/core/prepare_buffer.hpp>
15 #include <boost/asio/buffer.hpp>
16 #include <boost/asio/io_service.hpp>
22 /** A SyncStream and AsyncStream that reads from a string.
24 This class behaves like a socket, except that written data is simply
25 discarded, and when data is read it comes from a string provided
31 boost::asio::const_buffer cb_;
32 boost::asio::io_service& ios_;
33 std::size_t read_max_;
36 string_istream(boost::asio::io_service& ios,
37 std::string s, std::size_t read_max =
38 (std::numeric_limits<std::size_t>::max)())
40 , cb_(boost::asio::buffer(s_))
46 boost::asio::io_service&
52 template<class MutableBufferSequence>
54 read_some(MutableBufferSequence const& buffers)
57 auto const n = read_some(buffers, ec);
59 throw system_error{ec};
63 template<class MutableBufferSequence>
65 read_some(MutableBufferSequence const& buffers,
68 auto const n = boost::asio::buffer_copy(
69 buffers, prepare_buffer(read_max_, cb_));
73 ec = boost::asio::error::eof;
77 template<class MutableBufferSequence, class ReadHandler>
78 typename async_completion<ReadHandler,
79 void(error_code, std::size_t)>::result_type
80 async_read_some(MutableBufferSequence const& buffers,
81 ReadHandler&& handler)
83 auto const n = boost::asio::buffer_copy(
84 buffers, boost::asio::buffer(s_));
89 ec = boost::asio::error::eof;
90 async_completion<ReadHandler,
91 void(error_code, std::size_t)> completion{handler};
92 ios_.post(bind_handler(
93 completion.handler, ec, n));
94 return completion.result.get();
97 template<class ConstBufferSequence>
99 write_some(ConstBufferSequence const& buffers)
102 auto const n = write_some(buffers, ec);
104 throw system_error{ec};
108 template<class ConstBufferSequence>
110 write_some(ConstBufferSequence const& buffers,
113 return boost::asio::buffer_size(buffers);
116 template<class ConstBuffeSequence, class WriteHandler>
117 typename async_completion<WriteHandler,
118 void(error_code, std::size_t)>::result_type
119 async_write_some(ConstBuffeSequence const& buffers,
120 WriteHandler&& handler)
122 async_completion<WriteHandler,
123 void(error_code, std::size_t)> completion{handler};
124 ios_.post(bind_handler(completion.handler,
125 error_code{}, boost::asio::buffer_size(buffers)));
126 return completion.result.get();