add stream_size method

this is just a temporary alternative to the currently unstable
stream_len method, because i don't currently want to depend on unstable
rust versions if i don't need to.
This commit is contained in:
Gered 2022-05-29 12:52:58 -04:00
parent 9c35d670fa
commit b28c0f6555
2 changed files with 23 additions and 0 deletions

View file

@ -0,0 +1,22 @@
use std::io::{Error, SeekFrom};
/// Provides a convenience method for determining the total size of a stream. This is provided
/// as a temporary alternative to [std::io::Seek::stream_len] which is currently marked unstable.
pub trait StreamSize {
fn stream_size(&mut self) -> Result<u64, std::io::Error>;
}
impl<T: std::io::Read + std::io::Seek> StreamSize for T {
fn stream_size(&mut self) -> Result<u64, Error> {
let old_pos = self.stream_position()?;
let len = self.seek(SeekFrom::End(0))?;
// Avoid seeking a third time when we were already at the end of the
// stream. The branch is usually way cheaper than a seek operation.
if old_pos != len {
self.seek(SeekFrom::Start(old_pos))?;
}
Ok(len)
}
}

View file

@ -5,6 +5,7 @@ use rand::distributions::uniform::SampleUniform;
use rand::Rng;
pub mod bytes;
pub mod io;
pub mod packbits;
pub fn rnd_value<N: SampleUniform + PartialOrd>(low: N, high: N) -> N {