Skip to content

Commit 81e1c4d

Browse files
mrwigglewafflesDanilo Krummrich
authored andcommitted
rust: alloc: add Vec::truncate method
Implement the equivalent to the std's Vec::truncate on the kernel's Vec type. Link: https://lore.kernel.org/r/20250316111644.154602-2-andrewjballance@gmail.com Signed-off-by: Andrew Ballance <andrewjballance@gmail.com> [ Rewrote safety comment of set_len(). - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent fb1bf10 commit 81e1c4d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,41 @@ where
455455

456456
Ok(())
457457
}
458+
459+
/// Shortens the vector, setting the length to `len` and drops the removed values.
460+
/// If `len` is greater than or equal to the current length, this does nothing.
461+
///
462+
/// This has no effect on the capacity and will not allocate.
463+
///
464+
/// # Examples
465+
///
466+
/// ```
467+
/// let mut v = kernel::kvec![1, 2, 3]?;
468+
/// v.truncate(1);
469+
/// assert_eq!(v.len(), 1);
470+
/// assert_eq!(&v, &[1]);
471+
///
472+
/// # Ok::<(), Error>(())
473+
/// ```
474+
pub fn truncate(&mut self, len: usize) {
475+
if len >= self.len() {
476+
return;
477+
}
478+
479+
let drop_range = len..self.len();
480+
481+
// SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
482+
let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
483+
484+
// SAFETY: By the above bounds check, it is guaranteed that `len < self.capacity()`.
485+
unsafe { self.set_len(len) };
486+
487+
// SAFETY:
488+
// - the dropped values are valid `T`s by the type invariant
489+
// - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
490+
// len, therefore we have exclusive access to [`new_len`, `old_len`)
491+
unsafe { ptr::drop_in_place(ptr) };
492+
}
458493
}
459494

460495
impl<T: Clone, A: Allocator> Vec<T, A> {

0 commit comments

Comments
 (0)