#read #seek #limited #access #buffered #binary-parser #object

buf_stream_reader

provides a buffered access to a Read object with a limited Seek implementation

3 unstable releases

0.2.0 Feb 8, 2022
0.1.1 Feb 7, 2022
0.1.0 Feb 7, 2022

#11 in #seek

Download history 29/week @ 2024-07-20 20/week @ 2024-07-27 112/week @ 2024-08-03 36/week @ 2024-08-10 50/week @ 2024-08-17 56/week @ 2024-08-24 68/week @ 2024-08-31 14/week @ 2024-09-07 27/week @ 2024-09-14 47/week @ 2024-09-21 32/week @ 2024-09-28 40/week @ 2024-10-05 26/week @ 2024-10-12 2/week @ 2024-10-19 4/week @ 2024-10-26 63/week @ 2024-11-02

97 downloads per month
Used in 2 crates

Custom license

16KB
104 lines

buf_stream_reader

This struct provides a buffered access to a Read object with a limited Seek implementation. In other words, BufStreamReader turns a Read into a Read+Seek, which can be used together with binary parsers such as binread (which is the reason why I created this crate).

Seeking is limited by the following constraints:

  • Only a small bunch of bytes is buffered (defined by the buffer_size parameter of [BufStreamReader::new()])
  • We don't know the end of the stream, using SeekFrom::End is not supported
  • Seeking backward is allowed only if the targeted position is within the current buffer.

Seeking backward as possible as far as there are data in the current buffer

use std::io::{Cursor, Read, Seek, SeekFrom};
use buf_stream_reader::BufStreamReader;
let cursor = Cursor::new(&arr); // points to array with values from \x00 .. \xff
let mut reader = BufStreamReader::new(cursor, 16);

let mut buffer: [u8; 7] = [0; 7];

/* straightly reading 7 bytes works */
assert_eq!(reader.read(&mut buffer).unwrap(), buffer.len());
assert_eq!(&buffer, &arr[0..7]);

/* seeking backwards inside the current buffer */
assert!(reader.seek(SeekFrom::Current(-4)).is_ok());
assert_eq!(reader.read(&mut buffer).unwrap(), 7);
assert_eq!(&buffer, &arr[3..10]);

Seeking backwards is not possible if the destination is not within of behind the current buffer

let cursor = Cursor::new(&arr); // points to array with values from \x00 .. \xff
let mut reader = BufStreamReader::new(cursor, 16);

let mut buffer: [u8; 7] = [0; 7];
assert!(reader.seek(SeekFrom::Start(96)).is_ok());
assert!(reader.seek(SeekFrom::Start(95)).is_err());
assert!(reader.seek(SeekFrom::Current(-1)).is_err());

Seeking forward is not limited, as well as reading beyond buffer limits (as far as data is available, of course)

let cursor = Cursor::new(&arr); // points to array with values from \x00 .. \xff
let mut reader = BufStreamReader::new(cursor, 16);

let mut buffer: [u8; 7] = [0; 7];
assert!(reader.seek(SeekFrom::Start(10)).is_ok());
assert_eq!(reader.read(&mut buffer).unwrap(), buffer.len());
assert_eq!(&buffer, &arr[10..17]);

assert!(reader.seek(SeekFrom::Current(122)).is_ok());
assert_eq!(reader.read(&mut buffer).unwrap(), buffer.len());
assert_eq!(&buffer, &arr[139..146]);

No runtime deps