Erik Uggeldahl
Erik Uggeldahl

Reputation: 1146

Why do the functions in std::io::Read take a buffer?

Why do the methods in std::io::Read, namely read_to_end, read_to_string, and read_exact take a buffer rather than returning the result? The current return value is a Result<usize> (or Result<()>), but could that not be made into a tuple instead, also containing the result?

Upvotes: 2

Views: 70

Answers (1)

Erik Uggeldahl
Erik Uggeldahl

Reputation: 1146

RFC 517 discusses these functions and describes two reasons for why the functions take buffers over returning values:

  • Performance. When it is known that reading will involve some large number of bytes, the buffer can be preallocated in advance.

  • "Atomicity" concerns. For read_to_end, it's possible to use this API to retain data collected so far even when a read fails in the middle. For read_to_string, this is not the case, because UTF-8 validity cannot be ensured in such cases; but if intermediate results are wanted, one can use read_to_end and convert to a String only at the end.

For the first point, a string can be pre-allocated using the associated function String::with_capacity. A very similar function exists for vectors: Vec::with_capacity.

Upvotes: 3

Related Questions