From: Markus Probst <markus.probst@posteo.de>
To: Lee Jones <lee@kernel.org>, Pavel Machek <pavel@kernel.org>,
Danilo Krummrich <dakr@kernel.org>,
Miguel Ojeda <ojeda@kernel.org>,
Alex Gaynor <alex.gaynor@gmail.com>,
Igor Korotin <igor.korotin.linux@gmail.com>
Cc: Markus Probst <markus.probst@posteo.de>,
Lorenzo Stoakes <lorenzo.stoakes@oracle.com>,
Vlastimil Babka <vbabka@suse.cz>,
"Liam R. Howlett" <Liam.Howlett@oracle.com>,
Uladzislau Rezki <urezki@gmail.com>,
Boqun Feng <boqun.feng@gmail.com>, Gary Guo <gary@garyguo.net>,
bjorn3_gh@protonmail.com, Benno Lossin <lossin@kernel.org>,
Andreas Hindborg <a.hindborg@kernel.org>,
Alice Ryhl <aliceryhl@google.com>,
Trevor Gross <tmgross@umich.edu>,
Daniel Almeida <daniel.almeida@collabora.com>,
linux-leds@vger.kernel.org, rust-for-linux@vger.kernel.org,
linux-kernel@vger.kernel.org
Subject: [PATCH 2/4] rust: add pinned wrapper of Vec
Date: Wed, 08 Oct 2025 18:10:45 +0000 [thread overview]
Message-ID: <20251008181027.662616-3-markus.probst@posteo.de> (raw)
In-Reply-To: <20251008181027.662616-2-markus.probst@posteo.de>
Implement a wrapper of Vec that guarantees that its content will never be
moved, unless the item implements Unpin, allowing PinInit to be
initialized on the Vec.
Signed-off-by: Markus Probst <markus.probst@posteo.de>
---
rust/kernel/alloc/kvec.rs | 86 +++++++++++++++++++++++++++++++++++++++
1 file changed, 86 insertions(+)
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index 3c72e0bdddb8..3576929b2e12 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -21,6 +21,7 @@
slice,
slice::SliceIndex,
};
+use pin_init::PinInit;
mod errors;
pub use self::errors::{InsertError, PushError, RemoveError};
@@ -109,6 +110,11 @@ pub struct Vec<T, A: Allocator> {
_p: PhantomData<A>,
}
+/// A pinned wrapper of the [`Vec`] type.
+///
+/// It is guaranteed that the contents will never be moved, unless T implements Unpin.
+pub struct PinnedVec<T, A: Allocator>(Vec<T, A>);
+
/// Type alias for [`Vec`] with a [`Kmalloc`] allocator.
///
/// # Examples
@@ -121,6 +127,8 @@ pub struct Vec<T, A: Allocator> {
/// # Ok::<(), Error>(())
/// ```
pub type KVec<T> = Vec<T, Kmalloc>;
+/// Type alias for [`PinnedVec`] with a [`Kmalloc`] allocator.
+pub type KPinnedVec<T> = PinnedVec<T, Kmalloc>;
/// Type alias for [`Vec`] with a [`Vmalloc`] allocator.
///
@@ -134,6 +142,8 @@ pub struct Vec<T, A: Allocator> {
/// # Ok::<(), Error>(())
/// ```
pub type VVec<T> = Vec<T, Vmalloc>;
+/// Type alias for [`PinnedVec`] with a [`Vmalloc`] allocator.
+pub type VPinnedVec<T> = PinnedVec<T, Vmalloc>;
/// Type alias for [`Vec`] with a [`KVmalloc`] allocator.
///
@@ -147,6 +157,8 @@ pub struct Vec<T, A: Allocator> {
/// # Ok::<(), Error>(())
/// ```
pub type KVVec<T> = Vec<T, KVmalloc>;
+/// Type alias for [`PinnedVec`] with a [`KVmalloc`] allocator.
+pub type KVPinnedVec<T> = PinnedVec<T, KVmalloc>;
// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements.
unsafe impl<T, A> Send for Vec<T, A>
@@ -1294,6 +1306,80 @@ fn drop(&mut self) {
}
}
+impl<T, A: Allocator> PinnedVec<T, A> {
+ /// Creates a new [`PinnedVec`] instance with at least the given capacity.
+ pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> {
+ Vec::with_capacity(capacity, flags).map(Self)
+ }
+
+ /// Shortens the vector, setting the length to `len` and drops the removed values.
+ /// If `len` is greater than or equal to the current length, this does nothing.
+ ///
+ /// This has no effect on the capacity and will not allocate.
+ pub fn truncate(&mut self, len: usize) {
+ self.0.truncate(len);
+ }
+
+ /// Pin-initializes P and appends it to the back of the [`Vec`] instance without reallocating.
+ pub fn push_pin_init<E, P: PinInit<T, E>>(&mut self, init: P) -> Result<(), E>
+ where
+ E: From<PushError<P>>,
+ {
+ if self.0.len() < self.0.capacity() {
+ let spare = self.0.spare_capacity_mut();
+ // SAFETY: the length is less than the capacity, so `spare` is non-empty.
+ unsafe { init.__pinned_init(spare.get_unchecked_mut(0).as_mut_ptr())? };
+ // SAFETY: We just initialised the first spare entry, so it is safe to
+ // increase the length by 1. We also know that the new length is <= capacity.
+ unsafe { self.0.inc_len(1) };
+ Ok(())
+ } else {
+ Err(E::from(PushError(init)))
+ }
+ }
+
+ /// Removes the last element from a vector and drops it returning true, or false if it is empty.
+ pub fn pop(&mut self) -> bool {
+ if self.is_empty() {
+ return false;
+ }
+
+ // SAFETY: We just checked that the length is at least one.
+ let ptr: *mut [T] = unsafe { self.0.dec_len(1) };
+
+ // SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are
+ // valid elements whose ownership has been transferred to the caller.
+ unsafe { ptr::drop_in_place(ptr) };
+ true
+ }
+}
+
+impl<T, A: Allocator> Deref for PinnedVec<T, A> {
+ type Target = Vec<T, A>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl<T: Unpin, A: Allocator> DerefMut for PinnedVec<T, A> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+}
+
+impl<T, A: Allocator> From<Vec<T, A>> for PinnedVec<T, A> {
+ fn from(value: Vec<T, A>) -> Self {
+ Self(value)
+ }
+}
+
+impl<T: Unpin, A: Allocator> From<PinnedVec<T, A>> for Vec<T, A> {
+ fn from(value: PinnedVec<T, A>) -> Self {
+ value.0
+ }
+}
+
#[macros::kunit_tests(rust_kvec_kunit)]
mod tests {
use super::*;
--
2.49.1
next prev parent reply other threads:[~2025-10-08 18:10 UTC|newest]
Thread overview: 18+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-10-08 18:10 [PATCH 0/4] Add first led driver written in Rust Markus Probst
2025-10-08 18:10 ` [PATCH 1/4] rust: i2c: add read and write byte data abstractions Markus Probst
2025-10-08 18:10 ` Markus Probst [this message]
2025-10-08 18:10 ` [PATCH 3/4] rust: leds: add basic led classdev abstractions Markus Probst
2025-10-08 18:10 ` [PATCH 4/4] leds: add driver for synology atmega1608 controlled LEDs Markus Probst
2025-10-09 12:20 ` Danilo Krummrich
2025-10-09 12:30 ` Markus Probst
2025-10-09 12:41 ` Danilo Krummrich
2025-10-09 13:11 ` Alexandre Courbot
2025-11-23 20:00 ` Pavel Machek
2025-11-23 22:45 ` Markus Probst
2025-10-09 11:36 ` [PATCH 3/4] rust: leds: add basic led classdev abstractions Danilo Krummrich
2025-11-23 19:47 ` Pavel Machek
2025-10-09 11:23 ` [PATCH 2/4] rust: add pinned wrapper of Vec Alice Ryhl
2025-10-09 12:06 ` Markus Probst
2025-10-09 11:29 ` [PATCH 1/4] rust: i2c: add read and write byte data abstractions Alice Ryhl
2025-10-09 12:08 ` Danilo Krummrich
2025-11-23 19:44 ` Pavel Machek
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=20251008181027.662616-3-markus.probst@posteo.de \
--to=markus.probst@posteo.de \
--cc=Liam.Howlett@oracle.com \
--cc=a.hindborg@kernel.org \
--cc=alex.gaynor@gmail.com \
--cc=aliceryhl@google.com \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=dakr@kernel.org \
--cc=daniel.almeida@collabora.com \
--cc=gary@garyguo.net \
--cc=igor.korotin.linux@gmail.com \
--cc=lee@kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=linux-leds@vger.kernel.org \
--cc=lorenzo.stoakes@oracle.com \
--cc=lossin@kernel.org \
--cc=ojeda@kernel.org \
--cc=pavel@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
--cc=tmgross@umich.edu \
--cc=urezki@gmail.com \
--cc=vbabka@suse.cz \
/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