read_buffer
This crate provides ReadBuffer, a wrapper to safely read into a buffer from a Read.
Motivation
With the default way of reading into a buffer using Read::read like this:
use Read;
let data = ;
let mut reader = &data; // Read is implemented for &[u8]
let mut buffer = ;
let length = reader.read?;
assert_eq!;
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:
use Read;
let data = ;
let mut reader = &data;
let mut buffer = ;
// Ignoring the result of Read::read which might fail
#
reader.read;
// Reading too much data
assert_eq!;
let data = ;
let mut reader = &data;
#
reader.read;
// Reading garbage data from previous call to Read::read
assert_eq!;
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.
Examples
use ReadBuffer;
let data = ;
let mut reader = &data;
let mut buffer: = new;
// We are forced to check the Result of read_from to access the data we read
let read_data = buffer.read_from?;
// read_data is a slice over only the data we actually read,
// trying to access the buffer past that point would panic
let eight = read_data;
// let zero = read_data[4]; would panic
assert_eq!;
assert_eq!;
// We can reuse the same buffer for the next read, just as with Read::read
let data = ;
let mut reader = &data;
let read_data = buffer.read_from?;
// Again, we get a slice over only the data that was just read,
// trying to read garbage data from the previous call to read_from
// here would panic
let three = read_data;
// let eight = read_data[3]; would panic
assert_eq!;
assert_eq!;