-
Notifications
You must be signed in to change notification settings - Fork 13.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a skip
method to the Read
trait
#53294
Comments
https://doc.rust-lang.org/std/io/trait.Seek.html covers the File case at the very least. |
That's true. For skipping large numbers of bytes, Would it be possible to use impl specialization to write a |
What is the status on this ? Has it been discussed somewhere else ? |
For those reaching here and urgently need a solution, this is a quick solution pub struct SkipReader<R> {
inner: R,
skip: usize,
skipped: bool,
}
impl<R> SkipReader<R> {
pub fn new(reader: R, skip: usize) -> Self {
Self {
inner: reader,
skip,
skipped: skip == 0,
}
}
fn skip(&mut self) -> std::io::Result<()>
where
R: std::io::Read,
{
if self.skipped {
return Ok(());
}
// N.B.: This does cost 1k of extra stack space. Be aware.
let mut buf = [0; 1024];
let mut total = 0;
while total < self.skip {
let len = std::cmp::min(self.skip - total, buf.len());
match self.inner.read(&mut buf[..len]) {
Ok(0) => break,
Ok(n) => total += n,
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
};
debug_assert!(total <= self.skip);
}
self.skipped = true;
Ok(())
}
}
impl<R: std::io::Read> std::io::Read for SkipReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if !self.skipped {
self.skip()?;
}
self.inner.read(buf)
}
} |
The
Read
trait doesn't currently offer an optimal way to discard a number of bytes from the data source. Using thebytes()
iterator requires you to evaluate aResult
for each byte you discard and usingread_exact()
requires you to provide a buffer to unnecessarily fill.This solution (borrowed from a StackOverflow answer) seems to work nicely:
I can put a PR together if you'd like.
The text was updated successfully, but these errors were encountered: