Skip to content

Commit 2b4fbf6

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 00be0d8 commit 2b4fbf6

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
slice::SliceIndex,
@@ -372,6 +372,42 @@ impl<H, T> HeaderVec<H, T> {
372372
self.header_mut().len = head.into();
373373
}
374374

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

0 commit comments

Comments
 (0)