What is the difference between write_all and flush in io::Write trait?

Viewed 41

I am talking about the std::io::Write. The definition flush reads like basically exactly the same as the definition of the write_all function.

I have attempted understanding the difference by checking a couple popular Write implementing libraries like TcpStream but typically I see they just return Ok(()) without doing anything.

Is it okay to just not implement flush if we aren't dealing with some underlying system call for flushing some internal buffer?

1 Answers

write_all ensures that all data in the passed buffer is consumed (whereas write may consume only part of the data). To this effect, write_all will retry automatically until the whole data has been consumed (or an unrecoverable error occurs).

However this does not guarantee that the data has actually been written to disk (or to the underlying medium): it may have been buffered in the program (e.g. in a BufferedWriter) or by the OS. flush waits until all data that was previously consumed has been written to the underlying medium. This makes sense when writing to disk but may not make sense in other contexts, which is why some implementations of flush do nothing.

If you're writing a custom Write implementation, you can keep an empty flush method if "flushing" doesn't make sense for your target.

Related