pyo*_*yon 39 garbage-collection allocation lifetime rust
我正在制作一个简单的标记和紧凑的垃圾收集器.没有太多细节,它暴露的API是这样的:
/// Describes the internal structure of a managed object.
pub struct Tag { ... }
/// An unmanaged pointer to a managed object.
pub type Pointer = *mut usize;
/// Mapping from old to new locations.
pub type Adjust = BTreeMap<usize, Pointer>;
/// Mark this object and anything it points to as non-garbage.
pub unsafe fn survive(ptr: Pointer);
pub struct Heap { ... }
impl Heap {
pub fn new() -> Heap;
// Allocate an object with the specified structure.
pub fn allocate(&mut self, tag: Tag) -> Pointer;
/// Move all live objects from `heap` into `self`.
puf unsafe fn reallocate(&mut self, heap: Heap) -> Adjust;
}
Run Code Online (Sandbox Code Playgroud)
这个API显然从根本上说是不安全的.我想重做API(不改变内部,这很好!)来解释以下事实:
当堆进入另一个堆时,所有Pointer
s(分配在其中的对象)Heap
变为无效merge
.
merge
返回Adjust
其值为有效的Pointer
s(分配的对象)self
.
我有以下暂定解决方案:
// Replaces Pointer.
#[derive(Copy, Clone)]
pub struct Object<'a> {
ptr: *mut AtomicUsize,
mark: PhantomData<&'a usize>
}
impl<'a> Object<'a> {
pub fn survive(self); // Now supposed to be perfectly safe!
}
pub type Adjust<'a> = BTreeMap<usize, Object<'a>>;
pub struct Heap { ... }
pub struct Allocator<'a> { ... }
impl Heap {
fn allocator(&'a self) -> Allocator<'a>;
// The following doesn't work:
//
// fn allocate(&'a mut self) -> Object<'a>;
// fn reallocate(&'a mut self, heap: Heap) -> Adjust<'a>;
//
// Because it doesn't allow the user to allocate more
// than one `Object` at a time (!) in a `Heap`.
}
impl<'a> Allocator<'a> {
// Note that the resulting `Object`s are tied to the `Heap`,
// but not to the allocator itself.
fn allocate(&mut self, tag: Tag) -> Object<'a>;
fn reallocate(&mut self, heap: Heap) -> Adjust<'a>;
}
Run Code Online (Sandbox Code Playgroud)
这个设计是否正确?如果没有,需要改变什么?