[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <aBNcKcS_U_kMOAxu@pollux>
Date: Thu, 1 May 2025 13:34:01 +0200
From: Danilo Krummrich <dakr@...nel.org>
To: Alice Ryhl <aliceryhl@...gle.com>
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 Thu, May 01, 2025 at 11:03:21AM +0000, Alice Ryhl wrote:
> 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.
Generally, that sounds good to me. However, I'd like to avoid unwrap() or
anything that panics from doctests, since they also serve as sample code. Hence,
I think we should showcase how to do things the correct way (as much as
possible).
> > > + /// }
> > > + ///
> > > + /// 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.
I'll leave that up to you. :)
Powered by blists - more mailing lists