Skip to contentSkip to conversation

rust: alloc: add Vec::drain_all

PATCH Benno Lossin 1 participant 1 message Mar 21, 2025 Rust

lore
Share & tools
lore

Benno Lossin

author Reviewed-by
#0 lore raw
Quoted 29 lines · Alice Ryhl

This is like the stdlib method drain, except that it's hard-coded to use the entire vector's range. Rust Binder uses it in the range allocator to take ownership of everything in a vector in a case where reusing the vector is desirable.

Implementing DrainAll in terms of slice::IterMut lets us reuse some nice optimizations in core for the case where T is a ZST.

---
 rust/kernel/alloc/kvec.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
rust/kernel/alloc/kvec.rs +8 -0
index df930ff0d0b85b8b03c9b7932a2b31dfb62612ed..303198509885f5e24b74da5a92382b518de3e1c0 100644
@@ -564,6 +564,30 @@ pub fn truncate(&mut self, len: usize) {
         //   len, therefore we have exclusive access to [`new_len`, `old_len`)
         unsafe { ptr::drop_in_place(ptr) };
     }
+
+    /// Takes ownership of all items in this vector without consuming the allocation.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let mut v = kernel::kvec![0, 1, 2, 3]?;
+    ///

rust/kernel/alloc/kvec.rs pub fn truncate(&mut self, len: usize) { · line 584

Quoted 10 lines
rust/kernel/alloc/kvec.rs +10 -0
+    /// for (i, j) in v.drain_all().enumerate() {
+    ///     assert_eq!(i, j);
+    /// }
+    ///
+    /// assert!(v.capacity() >= 4);
+    /// ```
+    pub fn drain_all(&mut self) -> DrainAll<'_, T> {
+        let len = self.len();
+        // INVARIANT: The first 0 elements are valid.
+        self.len = 0;

With this changed to set_len (or dec_len if only that is available):

---
Cheers,
Benno

Quoted 9 lines
rust/kernel/alloc/kvec.rs +6 -0
+        // INVARIANT: The first `len` elements of the spare capacity are valid values, and as we
+        // just set the length to zero, we may transfer ownership to the `DrainAll` object.
+        DrainAll {
+            elements: self.spare_capacity_mut()[..len].iter_mut(),
+        }
+    }
 }
 
 impl<T: Clone, A: Allocator> Vec<T, A> {