Skip to content

Commit 16c5507

Browse files
mrwigglewafflesjannau
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 <[email protected]> Reviewed-by: Tamir Duberstein <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Andrew Ballance <[email protected]> [ Use checked_sub(), as suggested by Tamir. - Danilo ] Signed-off-by: Danilo Krummrich <[email protected]>
1 parent 52b21a7 commit 16c5507

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
@@ -559,6 +559,33 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
559559

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

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

0 commit comments

Comments
 (0)