diff options
author | Andrew Ballance <andrewjballance@gmail.com> | 2025-03-16 06:16:43 -0500 |
---|---|---|
committer | Danilo Krummrich <dakr@kernel.org> | 2025-04-07 14:41:10 +0200 |
commit | 1679b7159379d11100e4ab7d1de23c8cd7765aa1 (patch) | |
tree | f423ddbae8a3601429ecbe0b7c906ad8d18c751c /rust/kernel | |
parent | 81e1c4dab5d0c508907722f18b028102454d52e6 (diff) |
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>
Diffstat (limited to 'rust/kernel')
-rw-r--r-- | rust/kernel/alloc/kvec.rs | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 8fd941429d7c..7ebec5c4a277 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -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> |