Skip to content

Commit 524e592

Browse files
tamirdjannau
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 <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Tamir Duberstein <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]>
1 parent 16c5507 commit 524e592

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
@@ -291,15 +291,10 @@ where
291291
pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
292292
self.reserve(1, flags)?;
293293

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

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

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

0 commit comments

Comments
 (0)