8

Is it possible to use boost::circular_buffer with boost::asio?

Specifically I want to read a fixed number of bytes with boost::asio::async_write and store them directly in the circular buffer without copying.

Some example code would be very nice!

Robert Hegner
  • 9,014
  • 7
  • 62
  • 98
  • 2
    yes, you can. Some example code would be nice. – Theolodis Nov 08 '13 at 13:07
  • 1
    Look at following members of `circular_buffer`: [`array_one`](http://www.boost.org/doc/libs/1_54_0/libs/circular_buffer/doc/circular_buffer.html#classboost_1_1circular__buffer_1957cccdcb0c4ef7d80a34a990065818d), [`array_two`](http://www.boost.org/doc/libs/1_54_0/libs/circular_buffer/doc/circular_buffer.html#classboost_1_1circular__buffer_1f5081a54afbc2dfc1a7fb20329df7d5b), [`rotate`](http://tinyurl.com/lmg2axt) and [`linearize`](http://tinyurl.com/kv5tddl). You can use `array_one()` and `array_two()` to get internal buffers(slices of one big buffer) and feed `boost::asio::buffer` with them. – Evgeny Panasyuk Nov 08 '13 at 23:24
  • Thanks @EvgenyPanasyuk for these hints. I will try on monday if I can get it to work with a mutable buffer sequence consisting of `array_one` and `array_two`. – Robert Hegner Nov 09 '13 at 13:33
  • Doesn't look like there's an acceptable answer for this one. – Glenn Jan 22 '16 at 23:35
  • Hi @RobertHegner did you ever get this figured out – schuess May 25 '17 at 14:00
  • 1
    You sure you want to *read* using `async_write`? – rustyx Dec 29 '17 at 20:14

1 Answers1

2

As of right now (Boost 1.66), it is not possible to read data into boost::circular_buffer because it doesn't expose any way to reserve space in the underlying buffer, which is a requirement for creating a mutable_buffer needed to call asio::read.

But it is possible to write from boost::circular_buffer:

  boost::circular_buffer<char> cir_buf;

  FillBuffer(cir_buf);

  // Construct a buffer sequence with either 1 or 2 data chunks
  std::vector<boost::asio::const_buffer> buffer_sequence;

  auto arr1 = cir_buf.array_one();
  buffer_sequence.push_back(boost::asio::buffer(arr1.first, arr1.second));

  auto arr2 = cir_buf.array_two();
  if (arr2.second != 0) {
    buffer_sequence.push_back(boost::asio::buffer(arr2.first, arr2.second));
  }

  boost::asio::write(socket_, buffer_sequence);
rustyx
  • 80,671
  • 25
  • 200
  • 267