The Vec
type has methods for accessing spare capacity, so you can directly write to the uninitialized memory and then update the length. But VecDeque
has no such access, and I recently came across some code where it would have been useful (specifically, inputting bytes from a read
syscall into a queue to pull from later, which I wanted to back with a VecDeque<u8>
).
Specifically, I propose the following methods be added to VecDeque<T, A: Allocator>
(inspired by the similar methods which already exist for Vec
):
/// Returns the remaining spare capacity.
///
/// The exact split point depends on implementation details and is not guaranteed.
///
/// If appending extra elements, you should start by writing to the first slice,
/// then the second if you run out of room, before marking the data as initialized
/// using the [`set_len`](Self::set_len) method.
pub fn spare_capacities_mut(&mut self) -> (&mut [MaybeUninit<T>], &mut [MaybeUninit<T>]);
/// Returns four slices containing the contents and spare capacity, in order.
///
/// If make_contiguous was previously called, all elements of the deque will be in
/// the first slice and the second slice will be empty. Otherwise, the exact split
/// point on implementation details and is not guaranteed. The split point for the
/// uninitialized memory is also an implementation detail.
///
/// If appending extra elements, you should start by writing to the first
/// uninitialized slice, then the second if you run out of room, before marking the
/// data as initialized using the [`set_len`](Self::set_len) method.
pub fn as_slices_with_spare_capacities_mut(&mut self) -> (&mut [T], &mut [T], &mut [MaybeUninit<T>], &mut [MaybeUninit<T>]);
/// Forces the length of the deque to new_len.
///
/// This is a low-level operation that maintains none of the normal invariants of the
/// type. Normally changing the length of a deque is done using one of the safe
/// operations instead, such as [`append()`](Self::append),
/// [`truncate()`](Self::truncate), or [`clear()`](Self::clear).
///
/// # Safety
/// * `new_len` must be less than or equal to [`capacity()`](Self::capacity).
/// * The elements at `old_len..new_len` must be initialized (see
/// [`spare_capacities_mut()`](Self::spare_capacities_mut) for a way to
/// initialize these elements.
pub unsafe fn set_len(&mut self, new_len: usize);
Any of y'all have thoughts about these methods?
EDIT: Removed guarantee about contiguous uninitialized memory that isn't actually provided without changes that worsen VecDeque
.