[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20250321-vec-methods-v2-6-6d9c8a4634cb@google.com>
Date: Fri, 21 Mar 2025 12:10:01 +0000
From: Alice Ryhl <aliceryhl@...gle.com>
To: Danilo Krummrich <dakr@...nel.org>
Cc: Matthew Maurer <mmaurer@...gle.com>, rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org, Alice Ryhl <aliceryhl@...gle.com>
Subject: [PATCH v2 6/7] rust: alloc: add Vec::remove
This is needed by Rust Binder in the range allocator, and by upcoming
GPU drivers during firmware initialization.
Signed-off-by: Alice Ryhl <aliceryhl@...gle.com>
---
rust/kernel/alloc/kvec.rs | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index 866369406ea95e68adea366828552e76e451e24f..f7f7f9c650f8167ad6f53b0d83e328203445aa1f 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -356,6 +356,34 @@ pub fn pop(&mut self) -> Option<T> {
Some(unsafe { self.as_mut_ptr().add(len_sub_1).read() })
}
+ /// Removes the element at the given index.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let mut v = kernel::kvec![1, 2, 3]?;
+ /// assert_eq!(v.remove(1), 2);
+ /// assert_eq!(v, [1, 3]);
+ /// # Ok::<(), Error>(())
+ /// ```
+ pub fn remove(&mut self, i: idx) -> T {
+ // INVARIANT: This breaks the invariants by invalidating the value at index `i`, but we
+ // restore the invariants below.
+ // SAFETY: Since `&self[i]` did not result in a panic, the value at index `i` is valid.
+ let value = unsafe { ptr::read(&self[i]) };
+
+ // SAFETY: We checked that `i` is in-bounds.
+ let p = unsafe { self.as_mut_ptr().add(i) };
+ // INVARIANT: The invariants are still broken, but now the invalid value is the last
+ // element of the vector.
+ // SAFETY: `p.add(1).add(self.len - i - 1)` is `i+1+len-i-1 == len` elements after the
+ // beginning of the vector, so this is in-bounds of the vector.
+ unsafe { ptr::copy(p.add(1), p, self.len - i - 1) };
+ // INVARIANT: This restores the invariants since the invalid element no longer needs to be
+ // valid.
+ self.len = self.len - 1;
+ }
+
/// Creates a new [`Vec`] instance with at least the given capacity.
///
/// # Examples
--
2.49.0.395.g12beb8f557-goog
Powered by blists - more mailing lists