Reputation: 1384
I am using streambuf as a storage for serial port communication
io_service io;
serial_port sp(io);
sp.open("COM4");
sp.set_option( serial_port_base::baud_rate( 115200 ) );
sp.set_option( serial_port_base::character_size( 8 ) );
sp.set_option( serial_port_base::stop_bits( serial_port_base::stop_bits::one ) );
sp.set_option( serial_port_base::parity( serial_port_base::parity::none ) );
sp.set_option( serial_port_base::flow_control( serial_port_base::flow_control::none ) );
boost::asio::streambuf buffer;
// Fill buffer here
auto size = buffer.size();
std::cout << boost::format("Buffer size: %d") % size << std::endl;
boost::asio::write( sp, buffer );
size = buffer.size();
std::cout << boost::format("Buffer size: %d" ) % size << std::endl;
Output:
Buffer size: 8
Buffer size: 0
Why method size()
return different values?
Upvotes: 1
Views: 198
Reputation: 51971
The boost::asio::write()
operation consumes from the streambuf
's input sequence, and streambuf::size()
returns the size of the input sequence.
In this particular case, the streambuf
's input sequence contained 8 bytes before the write()
operation. The write()
operation blocks until all data from the input sequence has been written or until an error occurs. The write()
operation succeeds, consuming 8 bytes from the input sequence, and returns a value to indicate 8 bytes have been transferred. As all of the input sequence has been consumed, streambuf.size()
returns 0.
For more information on streambuf usage, consider reading this answer.
Upvotes: 4