Skip to content

Commit dbb0b84

Browse files
tamirdDanilo Krummrich
authored and
Danilo Krummrich
committed
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 <aliceryhl@google.com> Signed-off-by: Tamir Duberstein <tamird@gmail.com> Link: https://lore.kernel.org/r/20250416-vec-set-len-v4-2-112b222604cd@gmail.com [ Add #[expect(unused)] to dec_len(). - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent 47a17a6 commit dbb0b84

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

rust/kernel/alloc/kvec.rs

+20
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,26 @@ where
201201
self.len = new_len;
202202
}
203203

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

0 commit comments

Comments
 (0)