Skip to content

Commit 5cebd5c

Browse files
WhatAmISupposedToPutHerejannau
authored andcommitted
rust: alloc: Add .resize() to Vec
Similar in function to the one from std, but takes GFP flags. Signed-off-by: Sasha Finkelstein <fnkl.kernel@gmail.com>
1 parent 140cd7d commit 5cebd5c

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

rust/kernel/alloc/kvec.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,33 @@ where
458458
Ok(())
459459
}
460460

461+
/// Resizes the Vec in-place so that `len` is equal to `new_len`.
462+
///
463+
/// If `new_len` is greater than len, the Vec is extended by the difference,
464+
/// with each additional slot filled with `value`.
465+
/// If `new_len` is less than len, the Vec is simply truncated.
466+
fn resize(&mut self, new_len: usize, value: T, flags: Flags) -> Result<(), AllocError>
467+
where
468+
T: Clone,
469+
{
470+
if new_len < self.len() {
471+
self.truncate(new_len);
472+
return Ok(());
473+
}
474+
if new_len == self.len() {
475+
return Ok(());
476+
}
477+
self.reserve(new_len - self.len(), flags)?;
478+
for u in self.spare_capacity_mut() {
479+
u.write(value.clone());
480+
}
481+
// SAFETY: we just initialized them above
482+
unsafe {
483+
self.set_len(new_len);
484+
}
485+
Ok(())
486+
}
487+
461488
/// Clears the vector, removing all values.
462489
///
463490
/// Note that this method has no effect on the allocated capacity

0 commit comments

Comments
 (0)