From: Alice Ryhl <aliceryhl@google.com>
To: Danilo Krummrich <dakr@kernel.org>
Cc: Matthew Maurer <mmaurer@google.com>,
rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
Alice Ryhl <aliceryhl@google.com>
Subject: [PATCH v4 4/7] rust: alloc: add Vec::drain_all
Date: Tue, 29 Apr 2025 14:44:24 +0000 [thread overview]
Message-ID: <20250429-vec-methods-v4-4-dad4436ff82d@google.com> (raw)
In-Reply-To: <20250429-vec-methods-v4-0-dad4436ff82d@google.com>
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.
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
rust/kernel/alloc/kvec.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 60 insertions(+)
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index 78a602e0f00494a52df0e0aa5eedc68967a3011e..72bc743ec88bf7b91a0a1ffd9f830cfe4f983ffd 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -583,6 +583,31 @@ pub fn truncate(&mut self, len: usize) {
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]?;
+ ///
+ /// for (i, j) in v.drain_all().enumerate() {
+ /// assert_eq!(i, j);
+ /// }
+ ///
+ /// assert!(v.capacity() >= 4);
+ /// # Ok::<(), Error>(())
+ /// ```
+ pub fn drain_all(&mut self) -> DrainAll<'_, T> {
+ let len = self.len();
+ // SAFETY: The length is not greater than the length.
+ let elems = unsafe { self.dec_len(len) };
+ // 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: elems.iter_mut(),
+ }
+ }
}
impl<T: Clone, A: Allocator> Vec<T, A> {
@@ -1070,3 +1095,38 @@ fn into_iter(self) -> Self::IntoIter {
}
}
}
+
+/// An iterator that owns all items in a vector, but does not own its allocation.
+///
+/// # Invariants
+///
+/// Every `&mut T` returned by the iterator references a `T` that the iterator may take ownership
+/// of.
+pub struct DrainAll<'vec, T> {
+ elements: slice::IterMut<'vec, T>,
+}
+
+impl<'vec, T> Iterator for DrainAll<'vec, T> {
+ type Item = T;
+
+ fn next(&mut self) -> Option<T> {
+ let elem: *mut T = self.elements.next()?;
+ // SAFETY: By the type invariants, we may take ownership of this value.
+ Some(unsafe { elem.read() })
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.elements.size_hint()
+ }
+}
+
+impl<'vec, T> Drop for DrainAll<'vec, T> {
+ fn drop(&mut self) {
+ if core::mem::needs_drop::<T>() {
+ let iter = core::mem::take(&mut self.elements);
+ let ptr: *mut [T] = iter.into_slice();
+ // SAFETY: By the type invariants, we own these values so we may destroy them.
+ unsafe { ptr::drop_in_place(ptr) };
+ }
+ }
+}
--
2.49.0.901.g37484f566f-goog
next prev parent reply other threads:[~2025-04-29 14:44 UTC|newest]
Thread overview: 27+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-04-29 14:44 [PATCH v4 0/7] Additional methods for Vec Alice Ryhl
2025-04-29 14:44 ` [PATCH v4 1/7] rust: alloc: add Vec::clear Alice Ryhl
2025-04-29 14:44 ` [PATCH v4 2/7] rust: alloc: add Vec::pop Alice Ryhl
2025-04-29 14:44 ` [PATCH v4 3/7] rust: alloc: add Vec::push_within_capacity Alice Ryhl
2025-04-30 15:34 ` Danilo Krummrich
2025-05-01 11:03 ` Alice Ryhl
2025-05-01 11:34 ` Danilo Krummrich
2025-04-29 14:44 ` Alice Ryhl [this message]
2025-04-30 15:47 ` [PATCH v4 4/7] rust: alloc: add Vec::drain_all Danilo Krummrich
2025-04-29 14:44 ` [PATCH v4 5/7] rust: alloc: add Vec::retain Alice Ryhl
2025-04-30 16:26 ` Danilo Krummrich
2025-05-01 11:10 ` Alice Ryhl
2025-05-01 11:30 ` Danilo Krummrich
2025-05-01 14:24 ` Alice Ryhl
2025-05-02 21:58 ` Miguel Ojeda
2025-05-02 14:13 ` Miguel Ojeda
2025-04-29 14:44 ` [PATCH v4 6/7] rust: alloc: add Vec::remove Alice Ryhl
2025-04-30 16:28 ` Danilo Krummrich
2025-05-01 11:10 ` Alice Ryhl
2025-05-01 11:40 ` Danilo Krummrich
2025-05-01 14:25 ` Alice Ryhl
2025-04-29 14:44 ` [PATCH v4 7/7] rust: alloc: add Vec::insert_within_capacity Alice Ryhl
2025-04-29 15:30 ` Greg KH
2025-04-30 11:24 ` Alice Ryhl
2025-04-30 11:39 ` Greg KH
2025-04-30 12:15 ` Alice Ryhl
2025-04-30 12:36 ` Danilo Krummrich
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20250429-vec-methods-v4-4-dad4436ff82d@google.com \
--to=aliceryhl@google.com \
--cc=dakr@kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=mmaurer@google.com \
--cc=rust-for-linux@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).