use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::ptr::null_mut;
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use std::sync::Arc;
use crate::heap::{HeapInternal, MutatorInternal};
use crate::gc::GcInternal;
use crate::lockfree::{PushList, SegVec};
use crate::header::Header;
use crate::{Gc, Mutator, Trace};
pub trait Brand {
type Of<'gc>: Trace + 'gc;
}
#[macro_export]
macro_rules! brand {
($(#[$meta:meta])* $vis:vis $name:ident = for<$l:lifetime> $ty:ty) => {
$(#[$meta])*
$vis struct $name;
impl $crate::Brand for $name {
type Of<$l> = $ty;
}
};
}
#[derive(Default)]
pub struct Entry {
ptr: AtomicPtr<Header>,
holder: AtomicUsize,
}
pub const NO_HOLDER: usize = 0;
impl Entry {
pub fn load(&self) -> *mut Header {
self.ptr.load(Ordering::Acquire)
}
pub fn store(&self, header: *mut Header) {
self.ptr.store(header, Ordering::Release);
}
}
#[derive(Default)]
pub struct RootTable {
slots: SegVec<Entry>,
returned: PushList<usize>,
ready: UnsafeCell<Vec<usize>>,
cursor: AtomicUsize,
}
unsafe impl Sync for RootTable {}
unsafe impl Send for RootTable {}
impl RootTable {
pub fn claim(&self, header: *const Header, holder: usize) -> usize {
let ready = unsafe { &*self.ready.get() };
let i = self.cursor.fetch_add(1, Ordering::AcqRel);
match ready.get(i).and_then(|&slot| self.slots.get(slot).map(|s| (slot, s))) {
Some((slot, s)) => {
s.holder.store(holder, Ordering::Relaxed);
s.store(header.cast_mut());
slot
}
None => self.slots.push(Entry { ptr: AtomicPtr::new(header.cast_mut()), holder: AtomicUsize::new(holder) }),
}
}
pub fn slot(&self, i: usize) -> &Entry {
self.slots.get(i).expect("根槽号来自 claim")
}
pub fn release(&self, i: usize) {
self.slot(i).store(null_mut());
self.returned.push(i);
}
pub fn relocate(&self, mut f: impl FnMut(*const Header) -> *const Header) {
for slot in self.slots.iter() {
let old = slot.load();
if old.is_null() {
continue;
}
let new = f(old.cast_const());
if !core::ptr::eq(old, new) {
let _ = slot.ptr.compare_exchange(old, new.cast_mut(), Ordering::AcqRel, Ordering::Acquire);
}
}
}
pub unsafe fn pinned(&self, mut f: impl FnMut(*const Header)) {
for slot in self.slots.iter() {
let p = slot.load();
if !p.is_null() && slot.holder.load(Ordering::Relaxed) != NO_HOLDER {
f(p.cast_const());
}
}
}
pub unsafe fn settle(&self) -> Vec<*const Header> {
unsafe { self.settle_outside(|_| false) }
}
pub unsafe fn settle_outside(&self, inside: impl Fn(usize) -> bool) -> Vec<*const Header> {
let ready = unsafe { &mut *self.ready.get() };
let used = self.cursor.swap(0, Ordering::AcqRel).min(ready.len());
ready.drain(..used);
ready.extend(self.returned.take());
self.slots
.iter()
.filter_map(|s| {
let p = s.load();
(!p.is_null() && !inside(s.holder.load(Ordering::Relaxed))).then_some(p.cast_const())
})
.collect()
}
pub unsafe fn clear_dead(&self, inside: impl Fn(usize) -> bool, epoch: u32) {
for slot in self.slots.iter() {
let p = slot.load();
if !p.is_null() && inside(slot.holder.load(Ordering::Relaxed)) && !unsafe { &*p }.is_marked(epoch) {
let _ = slot.ptr.compare_exchange(p, null_mut(), Ordering::AcqRel, Ordering::Relaxed);
}
}
}
}
pub struct Root<B: Brand> {
table: Arc<RootTable>,
slot: usize,
_brand: PhantomData<fn() -> B>,
}
impl<B: Brand> Drop for Root<B> {
fn drop(&mut self) {
self.table.release(self.slot);
}
}
unsafe impl<B: Brand> Trace for Root<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut crate::Tracer<'_>) {}
}
impl<'gc> Mutator<'gc> {
pub fn root<B: Brand>(&self, gc: Gc<'gc, B::Of<'gc>>) -> Root<B> {
let table = self.heap().roots().clone();
let slot = table.claim(gc.header(), NO_HOLDER);
Root { table, slot, _brand: PhantomData }
}
pub fn get<B: Brand>(&self, root: &Root<B>) -> Gc<'gc, B::Of<'gc>> {
assert!(Arc::ptr_eq(&root.table, self.heap().roots()), "这个 Root 不属于这个堆");
let header = root.table.slot(root.slot).load();
unsafe { Gc::from_data(Header::data(header).cast()) }
}
pub fn set<B: Brand>(&self, root: &Root<B>, gc: Gc<'gc, B::Of<'gc>>) {
assert!(Arc::ptr_eq(&root.table, self.heap().roots()), "这个 Root 不属于这个堆");
root.table.slot(root.slot).store(gc.header().cast_mut());
}
}