Skip to content

Commit d1520f6

Browse files
committed
VecExtensions documentation
1 parent 4842a91 commit d1520f6

File tree

1 file changed

+18
-2
lines changed
  • crates/bevy_ecs/src/storage

1 file changed

+18
-2
lines changed

crates/bevy_ecs/src/storage/mod.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,18 +70,34 @@ impl Drop for AbortOnPanic {
7070
}
7171
}
7272

73+
/// Unsafe extension functions for `Vec<T>`
7374
trait VecExtensions<T> {
74-
unsafe fn swap_remove_nonoverlapping_unchecked(&mut self, index: usize);
75+
/// Removes an element from the vector and returns it.
76+
///
77+
/// The removed element is replaced by the last element of the vector.
78+
///
79+
/// This does not preserve ordering of the remaining elements, but is O(1). If you need to preserve the element order, use [`remove`] instead.
80+
///
81+
/// Unlike [`swap_remove`], this does not panic if `index` is out of bounds.
82+
///
83+
/// # Safety
84+
/// `index < self.len() - 1` must be true.
85+
///
86+
/// [`remove`]: alloc::vec::Vec::remove
87+
/// [`swap_remove`]: alloc::vec::Vec::swap_remove
88+
unsafe fn swap_remove_nonoverlapping_unchecked(&mut self, index: usize) -> T;
7589
}
7690

7791
impl<T> VecExtensions<T> for Vec<T> {
78-
unsafe fn swap_remove_nonoverlapping_unchecked(&mut self, index: usize) {
92+
unsafe fn swap_remove_nonoverlapping_unchecked(&mut self, index: usize) -> T {
93+
let value = core::ptr::read(self.as_mut_ptr().add(index));
7994
let len = self.len();
8095
// We replace self[index] with the last element. Note that if the
8196
// bounds check above succeeds there must be a last element (which
8297
// can be self[index] itself).
8398
let base_ptr = self.as_mut_ptr();
8499
core::ptr::copy_nonoverlapping(base_ptr.add(len - 1), base_ptr.add(index), 1);
85100
self.set_len(len - 1);
101+
value
86102
}
87103
}

0 commit comments

Comments
 (0)