Open mahkoh opened 9 years ago
If we do land this I think it should be called something other than flush because flush is not usually associated with losing or getting rid of data.
Seems like this is analogous to clear
on collections
What's the use-case for discarding the buffered bytes without discarding the actual buffer itself?
A use case would be that after a read that fills the buffer, I can tell a few bytes in that a Request is invalid, and I'd rather use the buffer for a new request, instead of having to allocate again.
On Tue, Mar 24, 2015, 11:25 AM Kevin Ballard notifications@github.com wrote:
What's the use-case for discarding the buffered bytes without discarding the actual buffer itself?
— Reply to this email directly or view it on GitHub https://github.com/rust-lang/rfcs/issues/993#issuecomment-85631671.
This behavior doesn't make sense for std::io::BufReader
, as that wraps another Read
and therefore can't be used for a separate Request (as Read
is stream-based, not message-based, so you can't know that the buffer only contains data from a single Request even if you're using a message-oriented protocol transported over a stream transport like TCP).
For the other implementations of BufRead
:
Cursor
- A Cursor
doesn't ever actually fill up a buffer, it just works on an existing one, so this flush()
would actually be equivalent to calling cursor.seek(SeekFrom::End(0))
(seeking to the end "empties" the buffer, whereas seeking to the beginning would actually just make it start yielding the same bytes it already yielded). More generally, if you want to reuse the buffer, what you actually want is to reuse the underlying storage, in which case you probably want to just call .into_inner()
to get that storage, make any changes necessary, and create a new Cursor
for it.&[u8]
- BufRead
here is similar to Cursor
except you can't seek. flush()
here would be the same as on Cursor
, it would basically just "consume" the whole buffer (by updating the size to have a length of zero).Empty
- trivial implementation, flush()
would do nothingStdinLock
- This is equivalent to BufReader
io::Take
- This is the only type that seems like it has a genuine use for flush()
, because you could use it to read fixed-length records from a stream and discard any records you don't care about. Although you can already do this yourself by saying let limit = take.limit() as usize; take.consume(limit)
(if the Take
wraps a BufRead
; if not, you need to actually read the number of bytes you want to skip and then discard them).Ultimately, I think that this functionality should be provided on individual types as desired, rather than on BufRead
, because it's just not useful for the general category of buffered stream readers (which is to say, there will never be generic code working on arbitrary BufRead
impls that wants this).
There is currently no way to discard the buffered bytes.