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

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

 



On 28.09.24 14:43, Danilo Krummrich wrote:
> 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.

Ah I see... Would be pretty useful for me to have my previous comments
easily accessible, I don't usually look at the previous thread. Is
anyone aware of some tools for that?

>> 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.

It does a check, but the optimizer will get rid of it if you use
`unwrap_unchecked` [1]. But feel free to leave it as-is.

[1]: https://godbolt.org/z/zYbMTo86M

---
Cheers,
Benno






[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