When compacting a Rust `Vec<T>` buffer in place, when do you reach for `drain`, `retain`, `dedup`, `extract_if` or `swap_remove`?
answer
- keep, discard or hand over
- range versus predicate
- dedup only sees neighbours
- order versus O(1)
- extract_if since 1.87
basics
~10 sdrain(range) removes a range and yields it; retain keeps what a predicate accepts; dedup removes consecutive duplicates; extract_if (Rust 1.87) removes and yields predicate matches; swap_remove removes one element in O(1) by breaking order.
solid answer
~40 sPick by what you remove and whether you need it back. `drain(..k)` removes a contiguous range and hands it over as an iterator, the way to pass the oldest samples to an archiver. `retain` (or `retain_mut`) removes everything a predicate rejects, visits each element once in order and keeps the survivors' order, but gives the removed values nothing to do but drop. `extract_if(range, pred)`, stable since Rust 1.87, removes predicate matches *and* yields them, so invalid readings can be quarantined. `dedup` removes only *consecutive* duplicates, so it deduplicates fully only a sorted vector. `swap_remove(i)` moves the last element into slot `i`, O(1) but reorders. All of them leave the capacity untouched.
code
rust · 29 lines#[derive(Debug, Clone, Copy, PartialEq)]
struct Sample { ts: u64, value: f32 }
fn main() {
let mut buf = vec![
Sample { ts: 1, value: 0.5 },
Sample { ts: 2, value: f32::NAN },
Sample { ts: 3, value: 0.5 },
Sample { ts: 3, value: 0.5 },
Sample { ts: 4, value: 0.9 },
Sample { ts: 5, value: f32::NAN },
Sample { ts: 6, value: 0.7 },
];
// 1. Hand the oldest two to an archiver; the rest shift down
let archived: Vec<Sample> = buf.drain(..2).collect();
// 2. Move invalid readings out (Rust 1.87+), keeping the order of the rest
let invalid: Vec<Sample> = buf.extract_if(.., |s| s.value.is_nan()).collect();
// 3. Collapse consecutive duplicates (only neighbours are compared)
buf.dedup();
// 4. Drop anything below a threshold without keeping it
buf.retain(|s| s.value >= 0.6);
println!("archived {} invalid {} kept {:?}", archived.len(), invalid.len(), buf);
println!("capacity still {}", buf.capacity());
}go deeper
Know that retain keeps elements a closure accepts and drain removes a range, and that removing from the middle with remove is slow on large vectors.
Choose by selection and ownership: range or predicate, removed values needed or not; know extract_if arrived in Rust 1.87, dedup sees only neighbours and swap_remove breaks order.
Mention the edges: an unexhausted extract_if keeps the rest, a leaked Drain can lose elements, and compaction never returns capacity, so long-lived buffers need an explicit shrink policy.
Compaction strategy affects latency and memory together: in-place methods reuse the buffer and avoid churn, so pair them with a shrink threshold rather than rebuilding vectors.
## The job: shrink a buffer without rebuilding it A time-series buffer appends samples continuously and periodically **compacts**: the oldest samples go to an archiver, invalid readings are set aside, repeated readings collapse, and low values are discarded. Building a new `Vec` each time works, but the standard library offers in-place methods that move each surviving element at most once and **keep the existing capacity**, so the next round of appends does not reallocate. The methods differ along two axes: 1. **What selects the elements**: a contiguous index range, a predicate, an equality with the neighbour, or one index. 2. **Whether you get the removed values back** as owned items or they are simply dropped. | Method | Selects by | Removed values | Order of the rest | Since | |---|---|---|---|---| | `drain(range)` | index range | yielded by an iterator | preserved | 1.6 | | `retain(f)` / `retain_mut(f)` | predicate (keep when true) | dropped | preserved | 1.0 / 1.61 | | `extract_if(range, f)` | predicate (remove when true) within a range | yielded by an iterator | preserved | **1.87** | | `dedup()` / `dedup_by_key(f)` | equal to the previous kept element | dropped | preserved | 1.0 | | `swap_remove(i)` | one index | returned | **not** preserved | 1.0 | | `truncate(k)` | everything from `k` on | dropped | preserved | 1.0 | ## drain: hand a range over `buf.drain(..2)` removes the first two elements and returns a `Drain` iterator yielding them by value; the tail shifts down when the iterator is dropped. If the iterator is dropped early, the remaining removed elements are dropped too. The iterator holds a mutable borrow of the vector until it is gone, and it panics if the range is out of bounds. One documented trap: if the `Drain` is leaked with `mem::forget`, the vector "may have lost and leaked elements arbitrarily, including elements outside the range", which is memory-safe but surprising. ## retain: keep what passes `retain` visits each element **exactly once, in the original order**, and keeps the ones for which the closure returns `true`. Because the visiting order is documented, the closure may consult external state such as a parallel iterator of flags. `retain_mut` gives the closure `&mut T`, so it can update survivors in the same pass. ## extract_if: remove and keep the removed Before Rust 1.87 there was no stable way to remove matches *and* own them in one pass. `extract_if(range, pred)` yields each element for which `pred` returns `true` and leaves the rest in order: - The `range` argument is mandatory; pass `..` for the whole vector. - The closure gets `&mut T`, so it can also modify elements it keeps. - If the returned iterator is not exhausted, because it is dropped early or iteration short-circuits, **the remaining elements are retained**. Use `.for_each(drop)` when you only want the side effect, or `retain_mut` with the negated predicate. The docs note it is equivalent to a loop of `remove(i)` calls but more efficient, because it shifts elements in bulk instead of once per removal. ## dedup: neighbours only `dedup` removes **consecutive** repeated elements using `PartialEq`. `[1, 2, 2, 3, 2]` becomes `[1, 2, 3, 2]`; the final `2` survives because its neighbour is `3`. To remove every duplicate, sort first (or use a `HashSet` when order does not matter). `dedup_by_key` compares a projection, such as a timestamp. ## swap_remove: O(1) at the cost of order `remove(i)` shifts every later element left, which is O(n). `swap_remove(i)` moves the last element into slot `i` and returns the removed value in O(1). Use it in entity lists, particle systems or any collection whose order carries no meaning; never in a time-ordered buffer. ## Smaller tools worth knowing - `truncate(k)` drops everything from index `k` on and keeps the first `k`; it is the cheapest way to cap a buffer from the end. - `pop_if(pred)`, stable since Rust 1.86, pops the last element only when the predicate accepts it, which suits trimming a tail one element at a time. - `split_off(k)` moves the tail into a new `Vec`, allocating for it, when the tail must outlive the original. ## Capacity after compaction None of these methods frees memory: `capacity()` is unchanged afterwards, by design. If a compaction leaves a buffer far smaller than its peak for a long time, follow it with `shrink_to`, as the question on capacity explains.
- In Rust, what happens if the iterator returned by `Vec::extract_if` is dropped after yielding only the first match?Iteration stops there and every element not yet examined stays in the vector, including later matches; std documents that an unexhausted `ExtractIf` retains the remaining elements. If you need every match removed, consume the iterator fully, for example with `collect` or `.for_each(drop)`.
- Why does `vec![1, 2, 2, 3, 2].dedup()` in Rust leave two `2`s?`dedup` compares each element only with the previous kept one, so it removes runs of consecutive duplicates, not all duplicates. The `2` after `3` is not next to another `2`. Sort the vector first, or use `dedup_by_key` on sorted data, to remove every repeat.
- In Rust, when is `Vec::swap_remove` the wrong choice for removing an element?Whenever the order of the remaining elements matters, such as a time-ordered sample buffer or a list shown to users, because it moves the last element into the hole. Use `remove` for one element, or `retain` or `extract_if` for many, which preserve order.
- dedup removes every duplicate even in an unsorted vector
- retain hands the removed elements back to the caller
- Dropping extract_if's iterator early still removes all matches
- Compacting with retain frees the unused capacity
- swap_remove preserves the order of the remaining elements
Assumes Rust 1.99 on edition 2024; Vec::extract_if was stabilised in Rust 1.87 and Vec::pop_if in 1.86, while drain, retain, dedup and swap_remove are far older.