I have some code that provides me with a pointer to a buffer, and the buffer's size that I need to fill with data. I represent this buffer with a boost::asio::mutable_buffer
instance, but how do I properly use this buffer (e.g. write a string to it, ...) and have boost enforce the buffer boundaries?
Here's some pseudo code:
size_t some_callback(void *ptr, size_t) {
// this function is called by 3rd party
return our_handler(boost::asio::mutable_buffer(ptr, size));
}
size_t our_handler(const boost::asio::mutable_buffer &buffer)
{
const std::string test("test");
// How do I write this string into my buffer?
return test.size();
}
boost::asio::buffer_cast<>()
is what you should use to get access to the pointer used by the buffer.
boost::asio::buffer_size()
is what you should use to get access to the size used.
e.g.
const std::string test("test");
const size_t len = std::min(boost::asio::buffer_size(mybuf), test.length());
memcpy(boost::asio::buffer_cast<void *>(mybuf),
test.c_str(),
len);
const std::string test2("test");
boost::asio::mutable_buffer offset = mybuf + len;
const size_t len2 = std::min(boost::asio::buffer_size(offset), test2.length());
memcpy(boost::asio::buffer_cast<void *>(offset),
test.c_str(),
len2);
boost::asio::mutable_buffer offset2 = offset + len2;
See also:
buffer_cast()
buffer_size()