我需要动态分配数组,所以我需要一个内存池来高效地完成这项工作。我发现https://github.com/fitzgen/bumpalo但看起来它不支持分配直接数组。我应该分配这样一个向量吗:
use bumpalo::{Bump, collections::Vec};
let bump = Bump::new();
let mut v = Vec::new_in(&bump);
每次我需要的时候都要切片?
问题是,我不能强迫向量具有我想要的确切大小。我的数组总是有一个固定的大小(不过大小是在运行时确定的(。我认为Vec是指体积越来越大的东西。
我想拥有数据,并在需要时获得切片。
bumpalo
目前只提供可增长集合,但编写不可增长集合应该很简单。例如:
use std::marker::PhantomData;
use bumpalo::Bump;
#[derive(Debug)]
pub struct BumpArray<'bump, T> {
data: &'bump mut [T],
_marker: PhantomData<T>, // we're dropping T values
}
impl<'bump, T> BumpArray<'bump, T> {
// Just an example - you could also provide `new_with()` or similar
// with different bounds on `T`.
pub fn new_default(bump: &'bump Bump, size: usize) -> Self
where
T: Default,
{
BumpArray {
data: bump.alloc_slice_fill_default(size),
_marker: PhantomData,
}
}
pub fn as_slice(&self) -> &[T] {
self.data
}
pub fn as_slice_mut(&mut self) -> &mut [T] {
self.data
}
}
impl<T> Drop for BumpArray<'_, T> {
fn drop(&mut self) {
if std::mem::needs_drop::<T>() {
for val in self.data.iter_mut() {
unsafe {
std::ptr::drop_in_place(val);
}
}
}
}
}
由于bumpalo不调用drop()
,因此需要手动删除。在这种情况下,我们可以利用所有权,在整个竞技场交易之前更早地对单个元素(对于首先需要掉落的类型(执行掉落。它确实需要一点不安全,但很容易推理。如果您使用的类型不实现Drop
,请随意省略Drop
实现和_marker
字段。