1
votes

In my project I read various files into different buffers and then want to use boost::asio::streambuf to concatenate these buffers together to speedup the process. I have read the example in http://www.boost.org/doc/libs/1_59_0/doc/html/boost_asio/reference/streambuf.html .

boost::asio::streambuf b;
// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);
size_t n = sock.receive(bufs);
// received data is "committed" from output sequence to input sequence
b.commit(n);
std::istream is(&b);
std::string s;
is >> s;

My question is how can I manually assign multiple char arrays (char buf[512] )to boost::asio::streambuf::mutable_buffers_type bufs in order after I "prepared" bufs? for example, I would like to know if there is a way to do:

    some_copy_func(bufs, array1,copy_size1); 
    some_copy_func(bufs, array2,copy_size2); 
    some_copy_func(bufs, array3,copy_size3);  

after these copies, array1, array2 and array3 will be copied to bufs in the same order. and after I call b.commit(copy_size1+copy_size2+copy_size1), all the buffers in these arrays will be available in b's istream side.

I tried to search boost docs and could not find any methods to do this. I know there is boost::asio::buffer_copy() to allow you copy external buffers to "bufs", but this buffer_copy() will destroy bufs old data. Does anybody have similar experience on this issue? thanks.

1

1 Answers

0
votes

ostream

Simplest way is to use the streambuf as intended... as a streambuf:

boost::asio::streambuf sb;

{
    char a[512], b[512], c[512];
    std::ostream os(&sb);
    os.write(a, sizeof(a));
    os.write(b, sizeof(b));
    os.write(c, sizeof(c));
}

copy

boost::asio::streambuf sb;

{
    boost::asio::streambuf::mutable_buffers_type bufs = sb.prepare(3 * 512);
    auto it = buffers_begin(bufs);
    char a[512], b[512], c[512];

    it = std::copy_n(a, sizeof(a), it);
    it = std::copy_n(b, sizeof(b), it);
    it = std::copy_n(c, sizeof(c), it);

    sb.commit(sizeof(a) + sizeof(b) + sizeof(c));
}