Re: [PATCH] rust: alloc: use `spare_capacity_mut` to reduce unsafe

Benno Lossin
2025-03-17T14:34:21Z

On Mon Mar 17, 2025 at 12:42 PM CET, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> ---
> rust/kernel/alloc/kvec.rs | 11 ++---------
> 1 file changed, 2 insertions(+), 9 deletions(-)
>
> diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> index ae9d072741ce..d2bc3d02179e 100644
> --- a/rust/kernel/alloc/kvec.rs
> +++ b/rust/kernel/alloc/kvec.rs
> @@ -285,15 +285,8 @@ 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) };
> -
> - // SAFETY:
> - // - `ptr` is properly aligned and valid for writes.
> - unsafe { core::ptr::write(ptr, v) };
> + // The call to `reserve` was successful so the spare capacity is at least 1.
> + self.spare_capacity_mut()[0].write(v);

I think the code uses unsafe to avoid a bounds check, but I'm not 100%
sure. Danilo might remember more info.

---
Cheers,
Benno

>
> // 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,