#read #buffer #byte-buffer #io-read #byte

read_buffer

此软件包提供 ReadBuffer,它是从 Read 中安全地读取到缓冲区的包装器。

4 个稳定版本

1.4.0 2023年6月20日
1.3.0 2023年6月19日
1.2.0 2023年5月6日
1.1.0 2023年4月24日
1.0.0 2023年4月17日

#1143Rust 模式

每月 44 次下载

MIT 许可证

18KB
146

read_buffer

此软件包提供 ReadBufferDynReadBuffer,这两个包装器可以从 Read 安全地将数据读取到缓冲区。

动机

使用默认方式,例如 Read::read 将数据读取到缓冲区,如下所示

use std::io::Read;

let mut reader = [1, 2, 3, 4].as_slice(); // Read is implemented for &[u8]
let mut buffer = [0; 16];

let length = reader.read(&mut buffer)?;
assert_eq!(buffer[..length], [1, 2, 3, 4]);

没有任何阻止你访问比读取的数据更多的缓冲区数据,甚至可以完全忽略 ResultRead::read

use std::io::Read;

let mut reader = [8, 8, 8, 8].as_slice();
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 mut reader = [1, 2, 3].as_slice();

reader.read(&mut buffer);

// Reading garbage data from previous call to Read::read
assert_eq!(buffer[..4], [1, 2, 3, 8]);

ReadBufferDynReadBuffer 提供包装器,只能让你访问实际读取的数据,并在访问数据之前强制你检查 Result

示例

use read_buffer::ReadBuffer;

let mut reader = [8, 8, 8, 8].as_slice();
let mut buffer: ReadBuffer<8> = ReadBuffer::new();

// We are forced to check the Result of read_from to access the data we read
let read_data = buffer.read_from(&mut reader)?;

// 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[3];
// let zero = read_data[4]; would panic

assert_eq!(eight, 8);
assert_eq!(read_data, [8, 8, 8, 8]);

// We can reuse the same buffer for the next read, just as with Read::read

let mut reader = [1, 2, 3].as_slice();

let read_data = buffer.read_from(&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 read_from
// here would panic
let three = read_data[2];
// let eight = read_data[3]; would panic

assert_eq!(three, 3);
assert_eq!(read_data, [1, 2, 3]);

无运行时依赖