[PATCH 4/5] rust: alloc: add Vec::clear

Alice Ryhl
2025-03-11T14:26:08Z

Our custom Vec type is missing the stdlib method `clear`, thus add it.
It will be used in the miscdevice sample.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
rust/kernel/alloc/kvec.rs | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)

diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index ae9d072741cedbb34bed0be0c20cc75472aa53be..2d213ede2873cef87116a5527e8e24008c970a58 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -395,6 +395,33 @@ pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
(ptr, len, capacity)
}

+ /// Clears the vector, removing all values.
+ ///
+ /// Note that this method has no effect on the allocated capacity
+ /// of the vector.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let mut v = kernel::kvec![1, 2, 3]?;
+ ///
+ /// v.clear();
+ ///
+ /// assert!(v.is_empty());
+ /// # Ok::<(), Error>(())
+ /// ```
+ #[inline]
+ pub fn clear(&mut self) {
+ let elems: *mut [T] = self.as_mut_slice();
+
+ // INVARIANT: This call changes the number of elements to zero.
+ self.len = 0;
+
+ // SAFETY: The values being dropped are valid values of type `T` by the type invariants.
+ // It's okay to invalidate them as we just changed the length to zero.
+ unsafe { ptr::drop_in_place(elems) };
+ }
+
/// Ensures that the capacity exceeds the length by at least `additional` elements.
///
/// # Examples

--
2.49.0.rc0.332.g42c0ae87b1-goog