[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <aBNU-XsWZLZtlmOo@google.com>
Date: Thu, 1 May 2025 11:03:21 +0000
From: Alice Ryhl <aliceryhl@...gle.com>
To: Danilo Krummrich <dakr@...nel.org>
Cc: Matthew Maurer <mmaurer@...gle.com>, rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org, Boqun Feng <boqun.feng@...il.com>
Subject: Re: [PATCH v4 3/7] rust: alloc: add Vec::push_within_capacity
On Wed, Apr 30, 2025 at 05:34:20PM +0200, Danilo Krummrich wrote:
> On Tue, Apr 29, 2025 at 02:44:23PM +0000, Alice Ryhl wrote:
> >
> > + /// Appends an element to the back of the [`Vec`] instance without reallocating.
> > + ///
> > + /// Fails if the vector does not have capacity for the new element.
> > + ///
> > + /// # Examples
> > + ///
> > + /// ```
> > + /// let mut v = KVec::with_capacity(10, GFP_KERNEL)?;
> > + /// for i in 0..10 {
> > + /// v.push_within_capacity(i).unwrap();
>
> I'd prefer to make this
>
> v.push_within_capacity(i).map_err(|_| ENOMEM)?;
>
> instead.
Perhaps we could make a new error type for `push_within_capacity`? That
way, you can use it with question mark directly, and you also get a
proper error message if you unwrap() it.
> > + /// }
> > + ///
> > + /// assert!(v.push_within_capacity(10).is_err());
> > + /// # Ok::<(), Error>(())
> > + /// ```
> > + pub fn push_within_capacity(&mut self, v: T) -> Result<(), T> {
> > + if self.len() < self.capacity() {
> > + // SAFETY: The length is less than the capacity.
> > + unsafe { self.push_within_capacity_unchecked(v) };
> > + Ok(())
> > + } else {
> > + Err(v)
> > + }
> > + }
> >
> > + /// Appends an element to the back of the [`Vec`] instance without reallocating.
> > + ///
> > + /// # Safety
> > + ///
> > + /// The length must be less than the capacity.
>
> NIT: Maybe be more specific and say:
>
> "`self.len()` must be less than `self.capacity()`."
I try to avoid starting sentences with code, but I can do it if you
prefer that. But saying "the length" and "the capacity" does not seem
ambiguous to me.
Alice
Powered by blists - more mailing lists