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

From: Benno Lossin
Date: Tue Sep 10 2024 - 15:34:02 EST


On 10.09.24 20:26, Danilo Krummrich wrote:
> On Tue, Sep 03, 2024 at 12:08:08PM -0700, Boqun Feng wrote:
>> On Fri, Aug 16, 2024 at 02:10:55AM +0200, Danilo Krummrich wrote:
>>> `Vec` provides a contiguous growable array type (such as `Vec`) with
>>> contents allocated with the kernel's allocators (e.g. `Kmalloc`,
>>> `Vmalloc` or `KVmalloc`).
>>>
>>> In contrast to Rust's `Vec` type, the kernel `Vec` type considers the
>>> kernel's GFP flags for all appropriate functions, always reports
>>> allocation failures through `Result<_, AllocError>` and remains
>>> independent from unstable features.
>>>
>>> Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
>>> ---
>> [...]
>>> +
>>> +impl<T, A> Vec<T, A>
>>> +where
>>> + A: Allocator,
>>> +{
>> [...]
>>> + /// Forcefully sets `self.len` to `new_len`.
>>> + ///
>>> + /// # Safety
>>> + ///
>>> + /// - `new_len` must be less than or equal to [`Self::capacity`].
>>> + /// - If `new_len` is greater than `self.len`, all elements within the interval
>>> + /// [`self.len`,`new_len`] must be initialized.
>>
>> Maybe use "[`self.len`, `new_len`)" to indicate `new_len` side is open?
>
> Agreed.

Alternatively just use the rust range operator `self.len..new_len`, it
is exclusive by default (for an inclusive range you can use `..=`).

>> Also `self.len` may confuse people whether it's the old length or new
>> length, could you use `old_len` and add note saying "`old_len` is the
>> length before `set_len()`?

I personally think this is not a big issue, since safety requirements
are preconditions to calling a function (so the function couldn't have
been called yet).

> What about:
>
> /// - If `new_len` is greater than `self.len` (from before calling this function), all elements
> /// within the interval [`self.len`,`new_len`] must be initialized.

You will still apply the range fix, right?

---
Cheers,
Benno