Skip to content

Commit caafac5

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 96ab22f commit caafac5

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

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,
@@ -379,6 +379,42 @@ impl<H, T> HeaderVec<H, T> {
379379
self.header_mut().len = head.into();
380380
}
381381

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

0 commit comments

Comments
 (0)