This crate provides ReadBuffer, a wrapper to safely read into a buffer from a [Read].
With the default way of reading into a buffer using [Read::read] like this: ```rust use std::io::Read;
let data = [1, 2, 3, 4]; let mut reader = &data[..]; // Read is implemented for &[u8] let mut buffer = [0; 16];
let length = reader.read(&mut buffer)?;
assert_eq!(buffer[..length], [1, 2, 3, 4]);
there's nothing stopping you from accessing more data of the buffer than what was read
or even outright ignoring the [Result] of [Read::read]:
rust
use std::io::Read;
let data = [8, 8, 8, 8]; let mut reader = &data[..]; let mut buffer = [0; 8];
// Ignoring the result of Read::read which might fail
reader.read(&mut buffer);
// Reading too much data assert_eq!(buffer, [8, 8, 8, 8, 0, 0, 0, 0]);
let data = [1, 2, 3]; let mut reader = &data[..];
reader.read(&mut buffer);
// Reading garbage data from previous call to Read::read assert_eq!(buffer[..4], [1, 2, 3, 8]); ```
ReadBuffer provides a wrapper that only lets you access the data that was actually read, and forces you to check the [Result] before accessing the data.
```rust use read_buffer::ReadBuffer;
let data = [8, 8, 8, 8]; let mut reader = &data[..]; let mut buffer: ReadBuffer<8> = ReadBuffer::new();
// We are forced to check the Result of readfrom to access the data we read let readdata = buffer.read_from(&mut reader)?;
// readdata is a slice over only the data we actually read, // trying to access the buffer past that point would panic let eight = readdata[3]; // let zero = read_data[4]; would panic
asserteq!(eight, 8); asserteq!(read_data, [8, 8, 8, 8]);
// We can reuse the same buffer for the next read, just as with Read::read
let data = [1, 2, 3]; let mut reader = &data[..];
let readdata = buffer.readfrom(&mut reader)?;
// Again, we get a slice over only the data that was just read, // trying to read garbage data from the previous call to readfrom // here would panic let three = readdata[2]; // let eight = read_data[3]; would panic
asserteq!(three, 3); asserteq!(read_data, [1, 2, 3]); ```