[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <Z9ckWiW7X0hX5Wvt@pollux>
Date: Sun, 16 Mar 2025 20:19:54 +0100
From: Danilo Krummrich <dakr@...nel.org>
To: Andrew Ballance <andrewjballance@...il.com>
Cc: airlied@...il.com, simona@...ll.ch, maarten.lankhorst@...ux.intel.com,
mripard@...nel.org, tzimmermann@...e.de, corbet@....net,
ojeda@...nel.org, alex.gaynor@...il.com, boqun.feng@...il.com,
gary@...yguo.net, bjorn3_gh@...tonmail.com, benno.lossin@...ton.me,
a.hindborg@...nel.org, aliceryhl@...gle.com, tmgross@...ch.edu,
acourbot@...dia.com, nouveau@...ts.freedesktop.org,
dri-devel@...ts.freedesktop.org, linux-doc@...r.kernel.org,
linux-kernel@...r.kernel.org, rust-for-linux@...r.kernel.org
Subject: Re: [PATCH v2 1/3] rust: alloc: add Vec::truncate method
On Sun, Mar 16, 2025 at 06:16:42AM -0500, Andrew Ballance wrote:
> implement the equivalent to the std's Vec::truncate
> on the kernel's Vec type.
>
> Signed-off-by: Andrew Ballance <andrewjballance@...il.com>
> ---
> rust/kernel/alloc/kvec.rs | 36 ++++++++++++++++++++++++++++++++++++
> 1 file changed, 36 insertions(+)
>
> diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> index ae9d072741ce..18bcc59f0b38 100644
> --- a/rust/kernel/alloc/kvec.rs
> +++ b/rust/kernel/alloc/kvec.rs
> @@ -452,6 +452,42 @@ pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocEr
>
> Ok(())
> }
> +
> + /// Shortens the vector, setting the length to `len` and drops the removed values.
> + /// If `len` is greater than or equal to the current length, this does nothing.
> + ///
> + /// This has no effect on the capacity and will not allocate.
> + /// # Examples
> + ///
> + /// ```
> + /// let mut v = kernel::kvec![1, 2, 3]?;
> + /// v.truncate(1);
> + /// assert_eq!(v.len(), 1);
> + /// assert_eq!(&v, &[1]);
> + ///
> + /// # Ok::<(), Error>(())
> + /// ```
> + pub fn truncate(&mut self, len: usize) {
> + if len >= self.len() {
> + return;
> + }
> +
> + let drop_range = len..self.len();
> +
> + // SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
> + let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
> +
> + // SAFETY:
> + // - this will always shrink the vector because of the above bounds check
> + // - [`new_len`, `self.len`) will be dropped through the call to `drop_in_place` below
We've just figured out that this part is not needed after all, sorry for the
inconvenience. No need to resend for this though, I can remove this line when
applying the patch.
> + unsafe { self.set_len(len) };
> +
> + // SAFETY:
> + // - the dropped values are valid `T`s by the type invariant
> + // - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
> + // len, therefore we have exclusive access to [`new_len`, `old_len`)
> + unsafe { ptr::drop_in_place(ptr) };
> + }
> }
>
> impl<T: Clone, A: Allocator> Vec<T, A> {
> --
> 2.48.1
>
Powered by blists - more mailing lists