[PATCH v2 7/7] rust: alloc: add Vec::insert_within_capacity

From: Alice Ryhl
Date: Fri Mar 21 2025 - 08:13:14 EST


This adds a variant of Vec::insert that does not allocate memory. This
makes it safe to use this function while holding a spinlock. Rust Binder
uses it for the range allocator fast path.

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

diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index f7f7f9c650f8167ad6f53b0d83e328203445aa1f..38ffd0cf2af6e375f8d4fc2f9afe9295b29e7db0 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -327,6 +327,27 @@ pub fn push_within_capacity(&mut self, v: T) -> Result<(), T> {
Ok(())
}

+ pub fn insert_within_capacity(&mut self, index: usize, element: T) -> Result<(), T> {
+ assert!(index <= self.len());
+
+ if self.len() >= self.capacity() {
+ return Err(element);
+ }
+
+ // SAFETY: This is in bounds since `index <= len < capacity`.
+ let p = unsafe { vec.as_mut_ptr().add(index) };
+ // INVARIANT: This breaks the Vec invariants by making `index` contain an invalid element,
+ // but we restore the invariants below.
+ // SAFETY: Both the src and dst ranges end no later than one element after the length.
+ // Since the length is less than the capacity, both ranges are in bounds of the allocation.
+ unsafe { ptr::copy(p, p.add(1), len - index) };
+ // INVARIANT: This restores the Vec invariants.
+ // SAFETY: The pointer is in-bounds of the allocation.
+ unsafe { ptr::write(p, element) };
+ // SAFETY: Index `len` contains a valid element due to the above copy and write.
+ unsafe { vec.set_len(len + 1) };
+ }
+
/// Removes the last element from a vector and returns it, or `None` if it is empty.
///
/// # Examples

--
2.49.0.395.g12beb8f557-goog