FROMGIT: 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> Bug: 414994413 (cherry picked from commit 1679b7159379d11100e4ab7d1de23c8cd7765aa1 https://github.com/Rust-for-Linux/linux.git alloc-next) Change-Id: I34b82e880ca6335038461be0de38fbb1a6854cba Signed-off-by: Alice Ryhl <aliceryhl@google.com>
This commit is contained in:
committed by
Matthew Maurer
parent
9d37907c65
commit
c40401d665
@@ -556,6 +556,33 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
|
||||
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Resizes the [`Vec`] so that `len` is equal to `new_len`.
|
||||
///
|
||||
/// If `new_len` is smaller than `len`, the `Vec` is [`Vec::truncate`]d.
|
||||
/// If `new_len` is larger, each new slot is filled with clones of `value`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let mut v = kernel::kvec![1, 2, 3]?;
|
||||
/// v.resize(1, 42, GFP_KERNEL)?;
|
||||
/// assert_eq!(&v, &[1]);
|
||||
///
|
||||
/// v.resize(3, 42, GFP_KERNEL)?;
|
||||
/// assert_eq!(&v, &[1, 42, 42]);
|
||||
///
|
||||
/// # Ok::<(), Error>(())
|
||||
/// ```
|
||||
pub fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError> {
|
||||
match new_len.checked_sub(self.len()) {
|
||||
Some(n) => self.extend_with(n, value, flags),
|
||||
None => {
|
||||
self.truncate(new_len);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A> Drop for Vec<T, A>
|
||||
|
||||
Reference in New Issue
Block a user