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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.




[Index of Archives]     [Linux ARM Kernel]     [Linux ARM]     [Linux Omap]     [Fedora ARM]     [IETF Annouce]     [Bugtraq]     [Linux OMAP]     [Linux MIPS]     [eCos]     [Asterisk Internet PBX]     [Linux API]

  Powered by Linux