rust: alloc: use `spare_capacity_mut` to reduce unsafe
authorTamir Duberstein <tamird@gmail.com>
Tue, 18 Mar 2025 14:52:42 +0000 (10:52 -0400)
committerDanilo Krummrich <dakr@kernel.org>
Mon, 7 Apr 2025 14:59:06 +0000 (16:59 +0200)
Use `spare_capacity_mut` in the implementation of `push` to reduce the
use of `unsafe`. Both methods were added in commit 2aac4cd7dae3 ("rust:
alloc: implement kernel `Vec` type").

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20250318-vec-push-use-spare-v3-1-68741671d1af@gmail.com
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
rust/kernel/alloc/kvec.rs

index 7ebec5c4a27748ad1c4dd27493ec79a33628c1e5..6ac8756989e526a79b476d353c5ef67e92d3d1cc 100644 (file)
@@ -288,15 +288,10 @@ where
     pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         self.reserve(1, flags)?;
 
-        // SAFETY:
-        // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
-        //   guaranteed to be part of the same allocated object.
-        // - `self.len` can not overflow `isize`.
-        let ptr = unsafe { self.as_mut_ptr().add(self.len) };
+        let spare = self.spare_capacity_mut();
 
-        // SAFETY:
-        // - `ptr` is properly aligned and valid for writes.
-        unsafe { core::ptr::write(ptr, v) };
+        // SAFETY: The call to `reserve` was successful so the spare capacity is at least 1.
+        unsafe { spare.get_unchecked_mut(0) }.write(v);
 
         // 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 because of the previous call to