Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip N bytes with Read without allocation? [duplicate]

Tags:

rust

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?

like image 806
puritii Avatar asked Sep 06 '25 23:09

puritii


1 Answers

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:

  • How to idiomatically / efficiently pipe data from Read+Seek to Write?
  • How to create an in-memory object that can be used as a Reader, Writer, or Seek in Rust?
like image 154
Shepmaster Avatar answered Sep 09 '25 06:09

Shepmaster