Skip to content

Commit 3437a5d

Browse files
committed
feat: add SoAVec::swap_remove
1 parent 95401f1 commit 3437a5d

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

soavec/src/lib.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1002,6 +1002,50 @@ impl<T: SoAble> SoAVec<T> {
10021002
unsafe { T::TupleRepr::drop_in_place(T::TupleRepr::get_pointers(ptr, 0, cap), len) };
10031003
}
10041004
}
1005+
1006+
/// Removes an element from the vector and returns it.
1007+
///
1008+
/// The removed element is replaced by the last element of the vector.
1009+
///
1010+
/// This does not preserve ordering of the remaining elements, but is *O*(n_fields).
1011+
/// If you need to preserve the element order, use [`remove`] instead.
1012+
///
1013+
/// [`remove`]: SoAVec::remove
1014+
///
1015+
/// # Examples
1016+
///
1017+
/// ```
1018+
/// use soavec::soavec;
1019+
///
1020+
/// let mut v = soavec![("foo", "foo"), ("bar", "bar"), ("baz", "baz"), ("qux", "qux")].unwrap();
1021+
///
1022+
/// assert_eq!(v.swap_remove(1).unwrap(), ("bar", "bar"));
1023+
/// assert_eq!(v, soavec![("foo", "foo"), ("qux", "qux"), ("baz", "baz")].unwrap());
1024+
///
1025+
/// assert_eq!(v.swap_remove(0).unwrap(), ("foo", "foo"));
1026+
/// assert_eq!(v, soavec![("baz", "baz"), ("qux", "qux")].unwrap());
1027+
/// ```
1028+
pub fn swap_remove(&mut self, index: u32) -> Result<T, IndexOutOfBoundsError> {
1029+
let len = self.len();
1030+
if index >= len {
1031+
return Err(IndexOutOfBoundsError);
1032+
}
1033+
1034+
let ptr = self.buf.as_mut_ptr();
1035+
let cap = self.capacity();
1036+
1037+
unsafe {
1038+
let value = T::from_tuple(T::TupleRepr::read(ptr, index, cap));
1039+
1040+
let src = T::TupleRepr::get_pointers(ptr, len - 1, cap);
1041+
let dst = T::TupleRepr::get_pointers(ptr, index, cap);
1042+
T::TupleRepr::copy(src, dst, 1);
1043+
1044+
self.buf.set_len(len - 1);
1045+
1046+
Ok(value)
1047+
}
1048+
}
10051049
}
10061050

10071051
impl<T: SoAble> Drop for SoAVec<T> {

0 commit comments

Comments
 (0)