Skip to content

Commit c315298

Browse files
tamirdDanilo Krummrich
authored andcommitted
rust: alloc: use spare_capacity_mut to reduce unsafe
Use `spare_capacity_mut` in the implementation of `push` to reduce the use of `unsafe`. Both methods were added in commit 2aac4cd ("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>
1 parent 1679b71 commit c315298

File tree

1 file changed

+3
-8
lines changed

1 file changed

+3
-8
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -288,15 +288,10 @@ where
288288
pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
289289
self.reserve(1, flags)?;
290290

291-
// SAFETY:
292-
// - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is
293-
// guaranteed to be part of the same allocated object.
294-
// - `self.len` can not overflow `isize`.
295-
let ptr = unsafe { self.as_mut_ptr().add(self.len) };
291+
let spare = self.spare_capacity_mut();
296292

297-
// SAFETY:
298-
// - `ptr` is properly aligned and valid for writes.
299-
unsafe { core::ptr::write(ptr, v) };
293+
// SAFETY: The call to `reserve` was successful so the spare capacity is at least 1.
294+
unsafe { spare.get_unchecked_mut(0) }.write(v);
300295

301296
// SAFETY: We just initialised the first spare entry, so it is safe to increase the length
302297
// by 1. We also know that the new length is <= capacity because of the previous call to

0 commit comments

Comments
 (0)