[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <D8IGFTJXS2A1.9JBD1UKGN4PX@proton.me>
Date: Mon, 17 Mar 2025 10:04:40 +0000
From: Benno Lossin <benno.lossin@...ton.me>
To: Tamir Duberstein <tamird@...il.com>, Danilo Krummrich <dakr@...nel.org>, Andrew Ballance <andrewjballance@...il.com>, Alice Ryhl <aliceryhl@...gle.com>, Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>, Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>, Björn Roy Baron <bjorn3_gh@...tonmail.com>, Andreas Hindborg <a.hindborg@...nel.org>, Trevor Gross <tmgross@...ch.edu>
Cc: rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org
Subject: Re: [PATCH 2/2] rust: alloc: add `Vec::dec_len`
On Sun Mar 16, 2025 at 11:32 PM CET, Tamir Duberstein wrote:
> Add `Vec::dec_len` that reduces the length of the receiver. This method
> is intended to be used from methods that remove elements from `Vec` such
> as `truncate`, `pop`, `remove`, and others. This method is intentionally
> not `pub`.
I think it should be `pub`. Otherwise we're loosing functionality
compared to now. If one decides to give the raw pointer to some C API
that takes ownership of the pointer, then I want them to be able to call
`dec_len` manually.
>
> Signed-off-by: Tamir Duberstein <tamird@...il.com>
> ---
> rust/kernel/alloc/kvec.rs | 15 +++++++++++++++
> 1 file changed, 15 insertions(+)
>
> diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> index d43a1d609434..5d604e04b9a5 100644
> --- a/rust/kernel/alloc/kvec.rs
> +++ b/rust/kernel/alloc/kvec.rs
> @@ -195,6 +195,21 @@ pub unsafe fn inc_len(&mut self, additional: usize) {
> self.len += additional;
> }
>
> + /// Decreases `self.len` by `count`.
> + ///
> + /// Returns a mutable reference to the removed elements.
s/reference/slice/
I would also mention here that the elements won't be dropped when the
user doesn't do that manually using the slice. So explain that this is a
low-level operation and `clear` or `truncate` should be used instead
where possible.
> + ///
> + /// # Safety
> + ///
> + /// - `count` must be less than or equal to `self.len`.
I also think that we should use saturating_sub instead and then not have
to worry about this. (It should still be documented in the function
though). That way this can also be a safe function.
---
Cheers,
Benno
> + unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
> + debug_assert!(count <= self.len());
> + self.len -= count;
> + // SAFETY: The memory between `self.len` and `self.len + count` is guaranteed to contain
> + // `self.len` initialized elements of type `T`.
> + unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(self.len), count) }
> + }
> +
> /// Returns a slice of the entire vector.
> #[inline]
> pub fn as_slice(&self) -> &[T] {
Powered by blists - more mailing lists