Module bytes
Efficient byte buffer management.
bytes provides a robust and performant way to work with byte buffers
without unnecessary allocations.
The crate is built around two primary types:
Bytes is an immutable, reference-counted byte buffer
that enables zero-copy cloning and slicing.
BytesMut is its mutable counterpart that can be efficiently
converted to Bytes when you're done modifying it.
The Buf and BufMut traits provide a cursor-based API
for reading and writing bytes to buffers.
These traits are implemented by various types including
Bytes, BytesMut, and standard types like Vec<u8> and &[u8].
This crate is particularly useful in network programming where efficient buffer management is critical for performance. It's a foundational component of the Tokio ecosystem and is used extensively in async I/O operations.
Examples
Creating and sharing byte buffers efficiently:
use ;
// Create a mutable buffer
let mut buf = with_capacity;
buf.extend_from_slice;
buf.extend_from_slice;
// Convert to immutable Bytes (zero-copy)
let bytes: Bytes = buf.freeze;
// Clone is cheap (reference counted)
let clone = bytes.clone;
// Slicing is also zero-copy
let slice = bytes.slice;
assert_eq!;
Using the Buf trait for reading:
use Buf;
let mut data = &b"\x00\x00\x00\x42rest";
let value = read_u32;
assert_eq!;
assert_eq!;
Modules
- buf Utilities for working with buffers.
Structs
-
TryGetError
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.