gimli-rs / leb128

Read and write DWARF's "Little Endian Base 128" variable length integer encoding
http://gimli-rs.github.io/leb128/leb128/index.html
Apache License 2.0
18 stars 15 forks source link

Return Number of Bytes consumed #20

Closed jaqxues closed 3 years ago

jaqxues commented 3 years ago

With the current implementation, the number of bytes that are consumed is not returned to the user.

About my use case: It involves a BufReader reading a typical Binary file. I do need to seek through some parts of the file and I want to take advantage of the seek_relative functionality (so the buffer does not get re-filled every time if not necessary). However, I would manually need to keep track of the offsets, which is absolutely no problem, except I do not know how many bytes leb128 consumed, which is a shame.

It would be pretty simple to just return a tuple. I am very new to Rust and not confident enough to open a PR, but I hope it gets added soon enough!

philipc commented 3 years ago

Note that seek_relative isn't stable yet (but it should be soon).

I think it would be better to wrap BufReader in your own reader which keeps track of the offset and converts seeks to seek_relative. This will ensure that your manually tracked offset never gets out of sync. This also encapsulates the dependency on BufReader, in case you ever need to use some other Read implementation. Something like:

struct MyReader<R> {
    inner: BufReader<R>,
    pos: usize,
}

impl<R: Read> Read for MyReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.pos += n;
        Ok(n)
    }
}

impl<R: Seek> Seek for MyReader<BufReader<R>> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        // call seek_relative and update self.pos
        ...
    }
}
jaqxues commented 3 years ago

Well I still would prefer a way to get the number of bytes, but thanks!

philipc commented 3 years ago

You can get the number of bytes by querying the position of MyReader before and after the read.