Home > front end >  Will the buffer be overwritten when async read?
Will the buffer be overwritten when async read?

Time:09-04

I want to use boost::async_read after async_read_until. async_read_until can write to buffer some data after delimiter. Can i use safely boost async_read after async_read_until with the same buffer and dont lost data that already in buffer?

CodePudding user response:

It depends.

There are dynamic buffers (streambuf, dynamic_string_buffer etc) that will retain the information.

If you use fixed buffer sequences, you can use Buffer Arithmetic to preserve a part of existing buffer.

It might help to realize the flipside: [async_]read_until guarantees completion when the completion condition is met. However, it may have read more than that into the buffer. This is why consume(n) only consumes the prefix of a dynamic buffer.

In fact when you issue another read[_until] using the same dynamic buffer might actually complete without another asrs.async_read_some on the underlying AsyncReadStream if the existing buffer contents already match the completion condition.

In extreme example, I recently started using this to demonstrate how read operations work on dynamic buffers without doing any true IO: e.g. Unable to get all the data with boost asio read()

Summarizing

Prefer a dynamic buffer that allows you to safely do what you describe.

  • Related