Skip to content

Commit 5b10b0b

Browse files
tamirdjannau
authored andcommitted
rust: alloc: add Vec::dec_len
Add `Vec::dec_len` that reduces the length of the receiver. This method is intended to be used from methods that remove elements from `Vec` such as `truncate`, `pop`, `remove`, and others. This method is intentionally not `pub`. Reviewed-by: Alice Ryhl <[email protected]> Signed-off-by: Tamir Duberstein <[email protected]> Link: https://lore.kernel.org/r/[email protected] [ Add #[expect(unused)] to dec_len(). - Danilo ] Signed-off-by: Danilo Krummrich <[email protected]>
1 parent 8cfbde1 commit 5b10b0b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,26 @@ where
204204
self.len = new_len;
205205
}
206206

207+
/// Decreases `self.len` by `count`.
208+
///
209+
/// Returns a mutable slice to the elements forgotten by the vector. It is the caller's
210+
/// responsibility to drop these elements if necessary.
211+
///
212+
/// # Safety
213+
///
214+
/// - `count` must be less than or equal to `self.len`.
215+
#[expect(unused)]
216+
unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
217+
debug_assert!(count <= self.len());
218+
// INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
219+
// self.len)`, hence the updated value of `set.len` represents the exact number of elements
220+
// stored within `self`.
221+
self.len -= count;
222+
// SAFETY: The memory after `self.len()` is guaranteed to contain `count` initialized
223+
// elements of type `T`.
224+
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
225+
}
226+
207227
/// Returns a slice of the entire vector.
208228
#[inline]
209229
pub fn as_slice(&self) -> &[T] {

0 commit comments

Comments
 (0)