I would like to skip an arbitrary number of bytes when working with a Read
instance without doing any allocations. After skipping, I need to continue reading the data that follows.
The number of bytes is not known at compile time, so I cannot create a fixed array. Read
also has no skip so I need to read into something, it seems. I do not want to use BufReader
and allocate unnecessary buffers and I do not want to read byte-by-byte as this is inefficient.
Any other options?
Your best bet is to also require Seek
:
use std::io::{self, Read, Seek, SeekFrom};
fn example(mut r: impl Read + Seek) -> io::Result<String> {
r.seek(SeekFrom::Current(5))?;
let mut s = String::new();
r.take(5).read_to_string(&mut s)?;
Ok(s)
}
#[test]
fn it_works() -> io::Result<()> {
use std::io::Cursor;
let s = example(Cursor::new("abcdefghijklmnop"))?;
assert_eq!("fghij", s);
Ok(())
}
If you cannot use Seek
, then see How to advance through data from the std::io::Read trait when Seek isn't implemented?
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With