Skip to content

Commit 1679b71

Browse files
mrwigglewafflesDanilo Krummrich
authored andcommitted
rust: alloc: add Vec::resize method
Implement the equivalent of the rust std's Vec::resize on the kernel's Vec type. Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Tamir Duberstein <tamird@gmail.com> Link: https://lore.kernel.org/r/20250316111644.154602-3-andrewjballance@gmail.com Signed-off-by: Andrew Ballance <andrewjballance@gmail.com> [ Use checked_sub(), as suggested by Tamir. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent 81e1c4d commit 1679b71

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,33 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
556556

557557
Ok(v)
558558
}
559+
560+
/// Resizes the [`Vec`] so that `len` is equal to `new_len`.
561+
///
562+
/// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d.
563+
/// If `new_len` is larger, each new slot is filled with clones of `value`.
564+
///
565+
/// # Examples
566+
///
567+
/// ```
568+
/// let mut v = kernel::kvec![1, 2, 3]?;
569+
/// v.resize(1, 42, GFP_KERNEL)?;
570+
/// assert_eq!(&v, &[1]);
571+
///
572+
/// v.resize(3, 42, GFP_KERNEL)?;
573+
/// assert_eq!(&v, &[1, 42, 42]);
574+
///
575+
/// # Ok::<(), Error>(())
576+
/// ```
577+
pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {
578+
match new_len.checked_sub(self.len()) {
579+
Some(n) => self.extend_with(n, value, flags),
580+
None => {
581+
self.truncate(new_len);
582+
Ok(())
583+
}
584+
}
585+
}
559586
}
560587

561588
impl<T, A> Drop for Vec<T, A>

0 commit comments

Comments
 (0)