Apparently boost::asio::async_read
doesn\'t like strings, as the only overload of boost::asio::buffer
allows me to create const_buffer
Another possibility with boost::asio::streambuf
is to use boost::asio::buffer_cast<const char*>()
in conjunction with boost::asio::streambuf::data()
and boost::asio::streambuf::consume()
like this:
const char* header=boost::asio::buffer_cast<const char*>(readbuffer.data());
//Do stuff with header, maybe construct a std::string with std::string(header,header+length)
readbuffer.consume(length);
This won't work with normal streambufs and might be considered dirty, but it seems to be the fastest way of doing it.
It's really buried in the docs...
Given boost::asio::streambuf b
, with size_t buf_size
...
boost::asio::streambuf::const_buffers_type bufs = b.data();
std::string str(boost::asio::buffers_begin(bufs),
boost::asio::buffers_begin(bufs) + buf_size);
A simpler answer would be to convert it in std::string
and manipulate it some what like this
std::string buffer_to_string(const boost::asio::streambuf &buffer)
{
using boost::asio::buffers_begin;
auto bufs = buffer.data();
std::string result(buffers_begin(bufs), buffers_begin(bufs) + buffer.size());
return result;
}
Giving a very concise code for the task.
I think it's more like:
streambuf.commit( number_of_bytes_read );
istream istr( &streambuf );
string s;
istr >> s;
I haven't looked into the basic_streambuf
code, but I believe that should be just one copy into the string.