展开描述
提供用于处理字节的抽象。
bytes crate 提供了一种高效的字节缓冲结构
(Bytes),以及用于处理缓冲实现
的 trait(Buf、BufMut)。
§Bytes
Bytes 是一个用于存储和操作连续内存切片的高效容器。
它主要面向网络编程场景,但
在其他场景下也同样适用。
Bytes 通过允许多个 Bytes 对象
指向同一段底层内存来简化零拷贝网络编程。它通过引用计数
来追踪内存何时不再需要,
从而可以释放。
可以直接从现有字节存储(如 &[u8]
或 Vec<u8>)构造 Bytes 句柄,但通常先使用 BytesMut 写入再冻结。例如:
use bytes::{BytesMut, BufMut};
let mut buf = BytesMut::with_capacity(1024);
buf.put(&b"hello world"[..]);
buf.put_u16(1234);
let a = buf.split();
assert_eq!(a, b"hello world\x04\xD2"[..]);
buf.put(&b"goodbye world"[..]);
let b = buf.split();
assert_eq!(b, b"goodbye world"[..]);
assert_eq!(buf.capacity(), 998);上面的示例中只分配了一个 1024 大小的缓冲区。句柄
a 和 b 共享该底层缓冲区,并通过索引
维护各自所代表的缓冲区视图。
更多细节参见 结构体文档。
§Buf, BufMut
这两个 trait 提供对缓冲区的读写访问。底层
存储不一定在连续内存中。例如,Bytes 是保证内存连续的
缓冲区,而 rope(绳索) 则将字节分散存储在
不相邻的多个块中。Buf 和 BufMut 通过游标维护当前
在底层字节存储中的位置;每当读取或写入字节时,
游标都会推进。
§Relation with Read and Write
乍看之下,Buf 和 BufMut 在功能上似乎与
std::io::Read 和 std::io::Write 重叠。但二者
用途不同。缓冲区(buffer)是作为参数
传给 Read::read 和 Write::write 的值;Read 和 Write
可能会触发系统调用(syscall),存在失败的可能。而 Buf
和 BufMut 的操作则是不可失败的(infallible)。
重导出§
模块§
- buf
- Utilities for working with buffers.
结构体§
- Bytes
- A cheaply cloneable and sliceable chunk of contiguous memory.
- Bytes
Mut - A unique reference to a contiguous slice of memory.
- TryGet
Error - Error type for the
try_get_methods ofBuf. Indicates that there were not enough remaining bytes in the buffer while attempting to get a value from aBufwith one of thetry_get_methods.