Re: [PATCH v7 13/26] rust: alloc: implement kernel `Vec` type

Danilo Krummrich
2024-09-28T12:43:37Z

On Thu, Sep 26, 2024 at 01:47:04PM +0000, Benno Lossin wrote:
> On 12.09.24 00:52, Danilo Krummrich wrote:
> > + /// Appends an element to the back of the [`Vec`] instance.
> > + ///
> > + /// # Examples
> > + ///
> > + /// ```
> > + /// let mut v = KVec::new();
> > + /// v.push(1, GFP_KERNEL)?;
> > + /// assert_eq!(&v, &[1]);
> > + ///
> > + /// v.push(2, GFP_KERNEL)?;
> > + /// assert_eq!(&v, &[1, 2]);
> > + /// # Ok::<(), Error>(())
> > + /// ```
> > + pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
> > + Vec::reserve(self, 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) };
>
> Why not use `self.spare_capacity_mut()[0].write(v);`?

Before v7 I did exactly that, but in v6 you suggested to use the raw pointer
instead to avoid the bounds check.

>
> If you want to avoid the bounds check, you can do
>
> let first = self.spare_capacity_mut().first();
> // SAFETY: the call to `Vec::reserve` above ensures that `spare_capacity_mut()` is non-empty.
> unsafe { first.unwrap_unchecked() }.write(v);

`first` does a similar check to create the `Option<&T>`, right?. I'd rather keep
the raw pointer access as suggested in v6.