The bytes crate provides Bytes for efficient, immutable, and shareable byte storage, and BytesMut for efficient, mutable buffer management.
Bytes facilitates zero-copy networking by allowing multiple Bytes handles to point to the same underlying memory via reference counting. A common pattern is to use BytesMut to write data into a buffer and then use .split() to create new Bytes handles that share the same underlying allocation. This avoids expensive reallocations and data copying.
When you call .split() on a BytesMut, the resulting handle maintains its own indices into the shared buffer, allowing you to work with different views of the same memory.
use bytes::{BytesMut, BufMut};
let mut buf = BytesMut::with_capacity(1024);
buf.put(&b"hello world"[..]);
buf.put_u16(1234);
// 'a' becomes a handle to the first part of the buffer
let a = buf.split();
assert_eq!(a, b"hello world\x04\xD2"[..]);
// 'buf' now contains the remaining capacity
// 'b' will be the next split
buf.put(&b"goodbye world"[..]);
let b = buf.split();
assert_eq!(b, b"goodbye world"[..]);
assert_eq!(buf.capacity(), 998);