Recently I tried to obtain the length of a stream (
Read + Seek) and was surprised that there isn’t a nice method for it. I had to manually write this:
let length = stream.seek(SeekFrom::End(0))?; stream.seek(SeekFrom::Start(0))?;
Sure, it’s not terrible, but
stream.len() or something similar would be a lot nicer and easier to read.
Therefore I propose to add the following provided methods to
fn stream_len(&mut self) -> io::Result<u64>: seeks to the end (to get the stream length) and then returns to the original position. Code:
let old_pos = self.seek(SeekFrom::Current(0))?; let len = self.seek(SeekFrom::End(0))?; self.seek(SeekFrom::Start(old_pos))?; Ok(len)
fn seek_start(&mut self) -> io::Result<()>
fn seek_end(&mut self) -> io::Result<u64>
(Alternative names for the last two:
It’s mostly convenience, in particular it avoids the need to import
stream_len() could prevent a common bug: to forget to seek to the beginning after getting the stream length from seeking to the end.
Obviously, this is nothing groundbreaking. But I think it would be nice little addition (in particular
stream_len() – I don’t care about the other two methods as much).
What do you think about this? Any related ideas? And: if most of you agree that this is a good idea: official RFC or just open a PR on the main repo?