rust: alloc: use `spare_capacity_mut` to reduce unsafe
Subsystems (2)
PATCH v3 1/1 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 2aac4cd7dae3 ("rust:
alloc: implement kernel Vec type").
---
Changes in v3:
- Clarify unsafe operation by factoring out safe call. (Benno Lossin)
- Link to v2: https://lore.kernel.org/r/[email protected]
Changes in v2:
- Use slice::get_unchecked_mut to ensure we avoid a bounds check.
(Benno Lossin)
- Link to v1: https://lore.kernel.org/r/[email protected]
--- rust/kernel/alloc/kvec.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-)
rust/kernel/alloc/kvec.rs +3 -8
@@ -285,15 +285,10 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {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
---
base-commit: cf25bc61f8aecad9b0c45fe32697e35ea4b13378
change-id: 20250317-vec-push-use-spare-27484fd016a9
Best regards,
Signature · 1 line
Tamir Duberstein <[email protected]>
Quoted 7 lines · Tamir Duberstein
Use
spare_capacity_mutin the implementation ofpushto reduce the use ofunsafe. Both methods were added in commit2aac4cd7dae3("rust:
alloc: implement kernelVectype").Reviewed-by Alice Ryhl <[email protected]>Reviewed-by Benno Lossin <[email protected]>Signed-off-by Tamir Duberstein <[email protected]>
Applied to rust/alloc-next, thanks!