summaryrefslogtreecommitdiff
path: root/rust/kernel
diff options
context:
space:
mode:
authorAndrew Ballance <andrewjballance@gmail.com>2025-03-16 06:16:42 -0500
committerDanilo Krummrich <dakr@kernel.org>2025-04-07 14:38:02 +0200
commit81e1c4dab5d0c508907722f18b028102454d52e6 (patch)
treef27cade4e6ccf6b57d932b3d38b849476b3e6a4d /rust/kernel
parentfb1bf1067de979c89ae33589e0466d6ce0dde204 (diff)
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>
Diffstat (limited to 'rust/kernel')
-rw-r--r--rust/kernel/alloc/kvec.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index b01dabfe35aa..8fd941429d7c 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -455,6 +455,41 @@ where
Ok(())
}
+
+ /// Shortens the vector, setting the length to `len` and drops the removed values.
+ /// If `len` is greater than or equal to the current length, this does nothing.
+ ///
+ /// This has no effect on the capacity and will not allocate.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let mut v = kernel::kvec![1, 2, 3]?;
+ /// v.truncate(1);
+ /// assert_eq!(v.len(), 1);
+ /// assert_eq!(&v, &[1]);
+ ///
+ /// # Ok::<(), Error>(())
+ /// ```
+ pub fn truncate(&mut self, len: usize) {
+ if len >= self.len() {
+ return;
+ }
+
+ let drop_range = len..self.len();
+
+ // SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
+ let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
+
+ // SAFETY: By the above bounds check, it is guaranteed that `len < self.capacity()`.
+ unsafe { self.set_len(len) };
+
+ // SAFETY:
+ // - the dropped values are valid `T`s by the type invariant
+ // - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
+ // len, therefore we have exclusive access to [`new_len`, `old_len`)
+ unsafe { ptr::drop_in_place(ptr) };
+ }
}
impl<T: Clone, A: Allocator> Vec<T, A> {