pub trait Buffer<T>: Sealed<T> { }Expand description
A memory buffer that may be uninitialized.
There are three types that implement the Buffer trait, and the type you
use determines the return type of the functions that use it:
| If you pass a… | You get back a… |
|---|---|
&mut [u8] | usize, indicating the number of elements initialized. |
&mut [MaybeUninit<u8>] | (&mut [u8], &mut [MaybeUninit<u8>]), holding the initialized and uninitialized subslices. |
SpareCapacity | usize, indicating the number of elements initialized. And the Vec is extended. |
§Examples
Passing a &mut [u8]:
let mut buf = [0_u8; 64];
let nread = read(fd, &mut buf)?;
// `nread` is the number of bytes read.Passing a &mut [MaybeUninit<u8>]:
let mut buf = [MaybeUninit::<u8>::uninit(); 64];
let (init, uninit) = read(fd, &mut buf)?;
// `init` is a `&mut [u8]` with the initialized bytes.
// `uninit` is a `&mut [MaybeUninit<u8>]` with the remaining bytes.Passing a SpareCapacity, via the spare_capacity helper function:
let mut buf = Vec::with_capacity(64);
let nread = read(fd, spare_capacity(&mut buf))?;
// `nread` is the number of bytes read.
// Also, `buf.len()` is now `nread` elements longer than it was before.§Guide to error messages
Sometimes code using Buffer can encounter non-obvious error messages.
Here are some we’ve encountered, along with ways to fix them.
If you see errors like
“cannot move out of self which is behind a mutable reference”
and
“move occurs because x has type &mut [u8], which does not implement the Copy trait”,
replace x with &mut *x. See error_buffer_wrapper in
examples/buffer_errors.rs.
If you see errors like
“type annotations needed”
and
“cannot infer type of the type parameter Buf declared on the function read”,
you may need to change a &mut [] to &mut [0_u8; 0]. See
error_empty_slice in examples/buffer_errors.rs.
If you see errors like
“the trait bound [MaybeUninit<u8>; 1]: Buffer<u8> is not satisfied”,
add a &mut to pass the array by reference instead of by value. See
error_array_by_value in examples/buffer_errors.rs.
If you see errors like
“cannot move out of x, a captured variable in an FnMut closure”,
try replacing x with &mut *x, or, if that doesn’t work, try moving a
let into the closure body. See error_retry_closure and
error_retry_indirect_closure in examples/buffer_errors.rs.
If you see errors like
“captured variable cannot escape FnMut closure body”,
use an explicit loop instead of retry_on_intr, assuming you’re using
that. See error_retry_closure_uninit in examples/buffer_errors.rs.
Implementations on Foreign Types§
impl<T> Buffer<T> for &mut [T]
impl<T> Buffer<T> for &mut Vec<MaybeUninit<T>>
alloc only.impl<T> Buffer<T> for &mut Vec<T>
alloc only.impl<T> Buffer<T> for &mut [MaybeUninit<T>]
impl<T, const N: usize> Buffer<T> for &mut [T; N]
impl<T, const N: usize> Buffer<T> for &mut [MaybeUninit<T>; N]
Implementors§
impl<'a, T> Buffer<T> for SpareCapacity<'a, T>
alloc only.