Skip to content

Commit 105b808

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 10549d9 commit 105b808

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

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

0 commit comments

Comments
 (0)