diff --git a/libretrogd/src/utils/io.rs b/libretrogd/src/utils/io.rs new file mode 100644 index 0000000..3753469 --- /dev/null +++ b/libretrogd/src/utils/io.rs @@ -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; +} + +impl StreamSize for T { + fn stream_size(&mut self) -> Result { + 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) + } +} \ No newline at end of file diff --git a/libretrogd/src/utils/mod.rs b/libretrogd/src/utils/mod.rs index 07f93e9..4b7b301 100644 --- a/libretrogd/src/utils/mod.rs +++ b/libretrogd/src/utils/mod.rs @@ -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(low: N, high: N) -> N {