Skip to content

Commit aa28ea2

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 <[email protected]>
1 parent 940ac64 commit aa28ea2

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
@@ -455,6 +455,33 @@ where
455455
Ok(())
456456
}
457457

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

0 commit comments

Comments
 (0)