Re: [PATCH 2/2] rust: alloc: add `Vec::dec_len`

Danilo Krummrich
2025-03-16T22:42:00Z

On Sun, Mar 16, 2025 at 06:32:01PM -0400, 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`.
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.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.
> + ///
> + /// # Safety
> + ///
> + /// - `count` must be less than or equal to `self.len`.

Why? We can catch this, no?

We can keep the debug_assert!(), but use self.len.saturating_sub(count) instead.

> + 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] {
>
> --
> 2.48.1
>