Skip to content

Commit e2b5f0d

Browse files
committed
ADD: spare_capacity_mut() and set_len()
These methods have the same API/Semantic than the std::Vec methods. They are useful when one wants to extend a HeaderVec in place in some complex way like for example appending chars to a u8 headervec with `encode_utf8()`
1 parent 9713321 commit e2b5f0d

1 file changed

Lines changed: 37 additions & 1 deletion

File tree

src/lib.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ extern crate alloc;
44

55
use core::{
66
fmt::Debug,
7-
mem::{self, ManuallyDrop},
7+
mem::{self, ManuallyDrop, MaybeUninit},
88
ops::{Deref, DerefMut, Index, IndexMut},
99
ptr,
1010
ptr::NonNull,
@@ -376,6 +376,42 @@ impl<H, T> HeaderVec<H, T> {
376376
self.header_mut().len = head.into();
377377
}
378378

379+
/// Returns the remaining spare capacity of the vector as a slice of
380+
/// `MaybeUninit<T>`.
381+
///
382+
/// The returned slice can be used to fill the vector with data (e.g. by
383+
/// reading from a file) before marking the data as initialized using the
384+
/// [`set_len`] method.
385+
///
386+
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
387+
unsafe {
388+
core::slice::from_raw_parts_mut(
389+
self.end_ptr_mut() as *mut MaybeUninit<T>,
390+
self.spare_capacity(),
391+
)
392+
}
393+
}
394+
395+
/// Forces the length of the headervec to `new_len`.
396+
///
397+
/// This is a low-level operation that maintains none of the normal
398+
/// invariants of the type. Normally changing the length of a vector
399+
/// is done using one of the safe operations instead. Noteworthy is that
400+
/// this method does not drop any of the elements that are removed when
401+
/// shrinking the vector.
402+
///
403+
/// # Safety
404+
///
405+
/// - `new_len` must be less than or equal to [`capacity()`].
406+
/// - The elements at `old_len..new_len` must be initialized.
407+
pub unsafe fn set_len(&mut self, new_len: usize) {
408+
debug_assert!(
409+
new_len <= self.capacity(),
410+
"new_len is greater than capacity"
411+
);
412+
self.header_mut().len = new_len.into();
413+
}
414+
379415
/// Gives the offset in units of T (as if the pointer started at an array of T) that the slice actually starts at.
380416
#[inline(always)]
381417
const fn offset() -> usize {

0 commit comments

Comments
 (0)