Skip to content

Commit 373c7d3

Browse files
WhatAmISupposedToPutHerejannau
authored andcommitted
rust: alloc: kvec: WIP(?): Add swap_remove() for AOP series
Signed-off-by: Sasha Finkelstein <fnkl.kernel@gmail.com> Signed-off-by: Janne Grunau <j@jannau.net>
1 parent e47e8ef commit 373c7d3

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

rust/kernel/alloc/kvec.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,26 @@ where
785785
}
786786
}
787787
}
788+
/// Removes an element from the vector and returns it.
789+
///
790+
/// The removed element is replaced by the last element of the vector.
791+
///
792+
/// This does not preserve ordering of the remaining elements, but is *O*(1).
793+
/// If you need to preserve the element order, use [`remove`] instead.
794+
pub fn swap_remove(&mut self, index: usize) -> T {
795+
if index > self.len() {
796+
panic!("Index out of range");
797+
}
798+
// SAFETY: index is in range
799+
// self.len() - 1 is in range since at last 1 element exists
800+
unsafe {
801+
let old = ptr::read(self.as_ptr().add(index));
802+
let last = ptr::read(self.as_ptr().add(self.len() - 1));
803+
ptr::write(self.as_mut_ptr().add(index), last);
804+
self.dec_len(1);
805+
old
806+
}
807+
}
788808
}
789809

790810
impl<T: Clone, A: Allocator> Vec<T, A> {

0 commit comments

Comments
 (0)