Read i32 from offset from ByteBuffer without &mut self

Quoting bytebuffer::ByteBuffer - Rust

fn read_i32(&mut self) -> i32
fn set_rpos(&mut self, rpos: usize)

So it appears that read an i32 from an arbitrary position, we need a &mut self since we need to first set the rpos. Is there a way to avoid this?

Not really, since that byte buffer holds state and reading values mutates it. You might want to just store a plain Vec<u8>, or use the bytes crate instead (which is far more widely used and actively maintained than bytebuffer).

1 Like

Do we get random access on bytes::Buf or bytes::BufMut ? I can't seem to find the function that lets us set the location of the cursor.

No, and this is for the following reason found in the documentation of the trait:

It can be thought of as an efficient Iterator for collections of bytes.

In particular, there's no guarantee that the full buffer exists in memory any one time.

A Bytes instance is contiguous, and it implements Deref for &[u8] so it can be used like that (e.g. you can index it).

1 Like