Re: [PATCH 1/2] rust: alloc: replace `Vec::set_len` with `inc_len`

Alice Ryhl
2025-03-17T10:48:13Z

On Mon, Mar 17, 2025 at 09:58:35AM +0000, Benno Lossin wrote:
> On Sun Mar 16, 2025 at 11:32 PM CET, Tamir Duberstein wrote:
> > Rename `set_len` to `inc_len` and simplify its safety contract.
> > ---
> > rust/kernel/alloc/kvec.rs | 19 +++++++++----------
> > rust/kernel/str.rs | 2 +-
> > rust/kernel/uaccess.rs | 2 +-
> > 3 files changed, 11 insertions(+), 12 deletions(-)
> >
> > diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> > index ae9d072741ce..d43a1d609434 100644
> > --- a/rust/kernel/alloc/kvec.rs
> > +++ b/rust/kernel/alloc/kvec.rs
> > @@ -183,17 +183,16 @@ pub fn len(&self) -> usize {
> > self.len
> > }
> >
> > - /// Forcefully sets `self.len` to `new_len`.
> > + /// Increments `self.len` by `additional`.
>
> I would keep the "Forcefully".
>
> > ///
> > /// # 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.
> > + /// - `self.len + additional` must be less than or equal to [`Self::capacity`].
> > + /// - All elements within the interval [`self.len`,`self.len + additional`) must be initialized.
> > #[inline]
> > - pub unsafe fn set_len(&mut self, new_len: usize) {
> > - debug_assert!(new_len <= self.capacity());
> > - self.len = new_len;
> > + pub unsafe fn inc_len(&mut self, additional: usize) {
> > + debug_assert!(self.len() + additional <= self.capacity());
>
> What if this overflows? Do we always have overflow debugging on when
> debug assertions are enabled? If yes, then this is fine.

I don't think we do.

> > diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
> > index 28e2201604d6..005713839e9e 100644
> > --- a/rust/kernel/str.rs
> > +++ b/rust/kernel/str.rs
> > @@ -840,7 +840,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
> >
> > // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is
> > // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`.
> > - unsafe { buf.set_len(f.bytes_written()) };
> > + unsafe { buf.inc_len(f.bytes_written()) };
>
> This change seems wrong unless the code was wrong to begin with.
>
> Otherwise the change looks good.

The buffer has length zero as it was just created with:

let mut buf = KVec::with_capacity(size, GFP_KERNEL)?;

Alice