Skip to content

Commit 233c1d2

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 4ac3849 commit 233c1d2

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
@@ -799,6 +799,26 @@ where
799799
}
800800
}
801801
}
802+
/// Removes an element from the vector and returns it.
803+
///
804+
/// The removed element is replaced by the last element of the vector.
805+
///
806+
/// This does not preserve ordering of the remaining elements, but is *O*(1).
807+
/// If you need to preserve the element order, use [`remove`] instead.
808+
pub fn swap_remove(&mut self, index: usize) -> T {
809+
if index > self.len() {
810+
panic!("Index out of range");
811+
}
812+
// SAFETY: index is in range
813+
// self.len() - 1 is in range since at last 1 element exists
814+
unsafe {
815+
let old = ptr::read(self.as_ptr().add(index));
816+
let last = ptr::read(self.as_ptr().add(self.len() - 1));
817+
ptr::write(self.as_mut_ptr().add(index), last);
818+
self.dec_len(1);
819+
old
820+
}
821+
}
802822
}
803823

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

0 commit comments

Comments
 (0)