use core::marker::PhantomData;
use core::ptr::NonNull;
use std::sync::Arc;
use crate::trace::TracerInternal;
use crate::heap::{HeapInternal, MutatorInternal};
use crate::gc::GcInternal;
use crate::gc::Invariant;
use crate::header::Header;
use crate::roots::RootTable;
use crate::{Brand, Gc, Heap, Mutator, Trace, Tracer};
pub struct Far<'a, B: Brand> {
table: Arc<RootTable>,
slot: usize,
ptr: NonNull<Header>,
_brand: PhantomData<(Invariant<'a>, fn() -> B)>,
}
unsafe impl<B: Brand> Send for Far<'_, B> {}
unsafe impl<B: Brand> Sync for Far<'_, B> {}
impl<'a, B: Brand> Far<'a, B> {
pub fn new<'b>(holder: &Mutator<'a>, target: &Mutator<'b>, gc: Gc<'b, B::Of<'b>>) -> Self {
assert!(!core::ptr::eq(holder.heap(), target.heap()), "同一个堆里的边用 Slot,不用 Far");
let table = target.heap().roots().clone();
let slot = table.claim(gc.header(), holder.heap().id());
let ptr = unsafe { NonNull::new_unchecked(gc.header().cast_mut()) };
Self { table, slot, ptr, _brand: PhantomData }
}
pub fn get<'b>(&self, m: &Mutator<'b>) -> Gc<'b, B::Of<'b>> {
assert!(Arc::ptr_eq(&self.table, m.heap().roots()), "这个 Far 不指向这个堆");
unsafe { Gc::from_data(Header::data(self.ptr.as_ptr()).cast()) }
}
pub fn points_into(&self, heap: &Heap) -> bool {
Arc::ptr_eq(&self.table, heap.roots())
}
fn report(&self, t: &mut Tracer<'_>) {
t.far(Arc::as_ptr(&self.table).addr(), self.ptr.as_ptr());
}
}
impl<B: Brand> Drop for Far<'_, B> {
fn drop(&mut self) {
self.table.release(self.slot);
}
}
unsafe impl<B: Brand> Trace for Far<'_, B> {
fn trace(&self, t: &mut Tracer<'_>) {
self.report(t);
}
fn relocate(&mut self, t: &mut Tracer<'_>) {
self.report(t);
}
}