reusable-vec-0.1.0 has been yanked.
reusable-vec
A Vec
wrapper that allows reusing contained values.
It’s useful when the values are expensive to initialize, but can be reused, for example heap-based containers.
pub struct ReusableVec<T> {
vec: Vec<T>,
len: usize,
}
Derefs to a slice of valid items, i. e. &self.vec[..self.len]
.
Example
struct Thing {
cheap: u32,
expensive: Vec<u32>,
}
fn main() {
let mut things = reusable_vec::ReusableVec::<Thing>::new();
for _ in 0..2 {
let new_thing = Thing { cheap: 123, expensive: Vec::new() };
if let Some(reused) = things.push_reuse() {
let mut expensive = std::mem::take(&mut reused.expensive);
expensive.clear();
*reused = Thing { expensive, ..new_thing };
} else {
things.push(Thing { expensive: Vec::with_capacity(100), ..new_thing });
}
things.last_mut().unwrap().expensive.push(456);
for thing in &things {
println!("{} {:?}", thing.cheap, thing.expensive);
}
things.clear_reuse();
}
}