[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <20250407-vec-set-len-v3-3-c5da0d03216e@gmail.com>
Date: Mon, 07 Apr 2025 10:52:33 -0400
From: Tamir Duberstein <tamird@...il.com>
To: Danilo Krummrich <dakr@...nel.org>,
Andrew Ballance <andrewjballance@...il.com>,
Alice Ryhl <aliceryhl@...gle.com>, Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>, Boqun Feng <boqun.feng@...il.com>,
Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <benno.lossin@...ton.me>,
Andreas Hindborg <a.hindborg@...nel.org>, Trevor Gross <tmgross@...ch.edu>
Cc: rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org,
Tamir Duberstein <tamird@...il.com>
Subject: [PATCH v3 3/4] rust: alloc: refactor `Vec::truncate` using
`dec_len`
Use `checked_sub` to satisfy the safety requirements of `dec_len` and
replace nearly the whole body of `truncate` with a call to `dec_len`.
Signed-off-by: Tamir Duberstein <tamird@...il.com>
---
rust/kernel/alloc/kvec.rs | 24 ++++++++----------------
1 file changed, 8 insertions(+), 16 deletions(-)
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index 844154d310f0..d0b46aa36169 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -493,23 +493,15 @@ pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocEr
/// # Ok::<(), Error>(())
/// ```
pub fn truncate(&mut self, len: usize) {
- if len >= self.len() {
- return;
+ if let Some(count) = self.len().checked_sub(len) {
+ // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
+ // equal to `self.len()`.
+ let ptr: *mut [T] = unsafe { self.dec_len(count) };
+
+ // 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) };
}
-
- let drop_range = len..self.len();
-
- // SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
- let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
-
- // SAFETY: By the above bounds check, it is guaranteed that `len < self.capacity()`.
- unsafe { self.set_len(len) };
-
- // SAFETY:
- // - the dropped values are valid `T`s by the type invariant
- // - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
- // len, therefore we have exclusive access to [`new_len`, `old_len`)
- unsafe { ptr::drop_in_place(ptr) };
}
}
--
2.49.0
Powered by blists - more mailing lists