pub struct Removing<'a, T> { /* private fields */ }
Expand description
A cursor-like structure made for cheap iterative removing of elements from vector.
Essentially overhead of the process is one ptr::copy
for each ignored
element + one ptr::copy
for the not yielded tail.
For the comparison with manual Vec::remove
see self
Also, an analog to this may be VecDeque
(if you need to only pop
elements from either of ends) or (unstable as of writing this)
[Vec::drain_filter
] (if you need to remove all matching elements).
However note 2 differences between [Vec::drain_filter
] and Removing
:
Removing
is not iterator (this makes it more universal but less convenient to use)Removing
does not remove elements from the vec when you drop it
The main method of this struct is next
which returns Entry
which can
be used to mutate the vec.
§Examples
use vecrem::VecExt;
let mut vec: Vec<_> = (0..17).collect();
let mut out = Vec::new();
{
let mut rem = vec.removing();
while let Some(entry) = rem.next() {
let value = *entry.value();
if value >= 10 {
break;
}
if value % 2 == 0 {
out.push(entry.remove());
}
}
}
// All ignored and not yielded elements are in the original vec
assert_eq!(vec, [1, 3, 5, 7, 9, 10, 11, 12, 13, 14, 15, 16]);
assert_eq!(out, [0, 2, 4, 6, 8])
§forget behavior
In the same way as [Vec::drain_filter
], for efficient work, Removing
needs to temporarily break vec’s invariants leaving it in an inconsistent
state. The state is made normal in Drop
.
However in rust running destructors is not guaranteed (see mem::forget
,
ManuallyDrop
). As such, on construction Removing
sets vec’s len to
0
(and restores it in Drop
), this means that if Removing
gets leaked
or forgotten - the elements of the vector are forgotten too.
use vecrem::VecExt;
let mut vec = vec![0, 1, 2, 3, 4];
core::mem::forget(vec.removing());
assert_eq!(vec, []);
Implementations§
Source§impl<'a, T> Removing<'a, T>
impl<'a, T> Removing<'a, T>
Sourcepub fn new(vec: &'a mut Vec<T>) -> Self
pub fn new(vec: &'a mut Vec<T>) -> Self
Creates new Removing
instance from given vec.
See also: VecExt::removing