2

I am trying to implement a function that takes a boost::const_buffer and iterates over its bytes in a loop. I saw that there is a buffers iterator, but it seems to be applicable for boost::asio::buffers_type. I didn't find any examples for simple traversal of a buffer.

So, is it the standard way to access the buffer via buffer_cast into a native type such as char* and then traverse it by traditional methods? Or is there any direct helper function to do this?

Mopparthy Ravindranath
  • 3,014
  • 6
  • 41
  • 78

1 Answers1

2

boost::asio::buffer_cast<>

#include <boost/asio.hpp>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>

namespace asio = boost::asio;

void test(asio::const_buffer const& buffer)
{
    auto first = asio::buffer_cast<const char*>(buffer);
    auto last = first + asio::buffer_size(buffer);

    std::copy(first, last, std::ostream_iterator<char>(std::cout));
    std::cout << std::endl;
}

int main()
{
    std::string s = "hello";

    test(asio::buffer(s));
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • OK, so basically extract the native data and iterate over it. – Mopparthy Ravindranath Jul 31 '17 at 17:28
  • @MupparthyRavindranath yes, a `const_buffer` is a single buffer of bytes. A `const_buffers_1` is a model of a `ConstBufferSequence` concept that contains 1 buffer (its `end()` is equal to its `begin() + 1`). A `ConstBufferSequence` is a sequence of N `const_buffer`s – Richard Hodges Jul 31 '17 at 18:33