Skip to content

Commit 1b04b46

Browse files
tamirdDanilo Krummrich
authored andcommitted
rust: alloc: refactor Vec::truncate using dec_len
Use `checked_sub` to satisfy the safety requirements of `dec_len` and replace nearly the whole body of `truncate` with a call to `dec_len`. Reviewed-by: Andrew Ballance <andrewjballance@gmail.com> 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-3-112b222604cd@gmail.com [ Remove #[expect(unused)] from dec_len(). - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent dbb0b84 commit 1b04b46

File tree

1 file changed

+8
-17
lines changed

1 file changed

+8
-17
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,6 @@ where
209209
/// # Safety
210210
///
211211
/// - `count` must be less than or equal to `self.len`.
212-
#[expect(unused)]
213212
unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
214213
debug_assert!(count <= self.len());
215214
// INVARIANT: We relinquish ownership of the elements within the range `[self.len - count,
@@ -489,23 +488,15 @@ where
489488
/// # Ok::<(), Error>(())
490489
/// ```
491490
pub fn truncate(&mut self, len: usize) {
492-
if len >= self.len() {
493-
return;
491+
if let Some(count) = self.len().checked_sub(len) {
492+
// SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
493+
// equal to `self.len()`.
494+
let ptr: *mut [T] = unsafe { self.dec_len(count) };
495+
496+
// SAFETY: the contract of `dec_len` guarantees that the elements in `ptr` are
497+
// valid elements whose ownership has been transferred to the caller.
498+
unsafe { ptr::drop_in_place(ptr) };
494499
}
495-
496-
let drop_range = len..self.len();
497-
498-
// SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
499-
let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
500-
501-
// SAFETY: By the above bounds check, it is guaranteed that `len < self.capacity()`.
502-
unsafe { self.set_len(len) };
503-
504-
// SAFETY:
505-
// - the dropped values are valid `T`s by the type invariant
506-
// - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
507-
// len, therefore we have exclusive access to [`new_len`, `old_len`)
508-
unsafe { ptr::drop_in_place(ptr) };
509500
}
510501
}
511502

0 commit comments

Comments
 (0)