1个不稳定版本
0.1.2 | 2023年2月11日 |
---|---|
0.1.1 |
|
0.1.0 |
|
#1674 在 数据结构
6KB
139 行
reusable-vec
一个允许重用所包含值的Vec
包装器。当值初始化成本较高但可以重用时很有用,例如基于堆的容器。
pub struct ReusableVec<T> {
vec: Vec<T>,
len: usize,
}
指向有效项的切片的引用,即 &self.vec[..self.len]
。
示例
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() {
// Reuse members with previously allocated heap storage
let mut expensive = std::mem::take(&mut reused.expensive);
// They may still contain something
expensive.clear();
// Assigning the whole struct safeguards against forgetting to assign new values
// to some of the fields
*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);
}
// Release all items: sets `len` to 0
things.clear_reuse();
// Drop all items: calls `vec.clear()`
// things.clear_drop();
}
}