Skip to content

Commit

Permalink
ADD: spare_capacity_mut() and set_len()
Browse files Browse the repository at this point in the history
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()`
  • Loading branch information
cehteh committed Jan 10, 2025
1 parent 00be0d8 commit 2b4fbf6
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate alloc;

use core::{
fmt::Debug,
mem::{self, ManuallyDrop},
mem::{self, ManuallyDrop, MaybeUninit},
ops::{Deref, DerefMut, Index, IndexMut},
ptr,
slice::SliceIndex,
Expand Down Expand Up @@ -372,6 +372,42 @@ impl<H, T> HeaderVec<H, T> {
self.header_mut().len = head.into();
}

/// Returns the remaining spare capacity of the vector as a slice of
/// `MaybeUninit<T>`.
///
/// The returned slice can be used to fill the vector with data (e.g. by
/// reading from a file) before marking the data as initialized using the
/// [`set_len`] method.
///
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
unsafe {
core::slice::from_raw_parts_mut(
self.end_ptr_mut() as *mut MaybeUninit<T>,
self.spare_capacity(),
)
}
}

/// Forces the length of the headervec 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 vector
/// is done using one of the safe operations instead. Noteworthy is that
/// this method does not drop any of the elements that are removed when
/// shrinking the vector.
///
/// # Safety
///
/// - `new_len` must be less than or equal to [`capacity()`].
/// - The elements at `old_len..new_len` must be initialized.
pub unsafe fn set_len(&mut self, new_len: usize) {
debug_assert!(
new_len <= self.capacity(),
"new_len is greater than capacity"
);
self.header_mut().len = new_len.into();
}

/// Gives the offset in units of T (as if the pointer started at an array of T) that the slice actually starts at.
#[inline(always)]
const fn offset() -> usize {
Expand Down

0 comments on commit 2b4fbf6

Please sign in to comment.