rust: alloc: add `Vec::dec_len`
authorTamir Duberstein <tamird@gmail.com>
Wed, 16 Apr 2025 17:15:41 +0000 (13:15 -0400)
committerDanilo Krummrich <dakr@kernel.org>
Wed, 23 Apr 2025 10:05:22 +0000 (12:05 +0200)
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`.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250416-vec-set-len-v4-2-112b222604cd@gmail.com
[ Add #[expect(unused)] to dec_len(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
rust/kernel/alloc/kvec.rs

index ca30fad90de51ad07cc65fc5ec870c96fade1605..7671867165a0bd6252dad59565b51424b26c59c7 100644 (file)
@@ -201,6 +201,26 @@ where
         self.len = new_len;
     }
 
+    /// Decreases `self.len` by `count`.
+    ///
+    /// Returns a mutable slice to the elements forgotten by the vector. It is the caller's
+    /// responsibility to drop these elements if necessary.
+    ///
+    /// # Safety
+    ///
+    /// - `count` must be less than or equal to `self.len`.
+    #[expect(unused)]
+    unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
+        debug_assert!(count <= self.len());
+        // INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
+        // self.len)`, hence the updated value of `set.len` represents the exact number of elements
+        // stored within `self`.
+        self.len -= count;
+        // SAFETY: The memory after `self.len()` is guaranteed to contain `count` 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] {