Writing into Uninitialized Buffers in Rust
a year ago
- #Rust
- #Systems Programming
- #Memory Safety
- Uninitialized buffers in Rust have been a long-standing topic with various discussions and proposals.
- John Nunley and Alex Saveau introduced a new approach using a `Buffer` trait, now part of rustix 1.0.
- The `Buffer` trait allows reading into uninitialized buffers safely, supporting `&mut [T]`, `&mut [MaybeUninit<T>]`, and `Vec` spare capacity.
- The trait includes methods like `parts_mut` and `assume_init` to manage buffer operations safely.
- Using `Buffer` with `Vec` spare capacity encapsulates the unsafe `Vec::set_len` call, enhancing safety.
- The `Buffer` trait is generic over `T`, enabling its use beyond bytes, such as with event records in `epoll::wait`.
- Error messages from the `Buffer` trait can be non-obvious, leading to documentation updates in rustix.
- A potential safe alternative using a `Cursor` API is discussed, inspired by `BorrowedCursor`.
- The `Buffer` trait's design avoids the complexity of `BorrowedBuf`'s double cursor pattern.
- The `buffer-trait` library is now available as a standalone implementation of this idea.