use core::fmt;
use core::cell::{Cell, UnsafeCell};
use core::marker::PhantomData;
#[cfg(target_os = "linux")]
use core::num::{NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8};
use core::ops::Deref;
use core::ptr::{NonNull, null_mut};
use core::sync::atomic::{AtomicPtr, AtomicU64, AtomicUsize, Ordering};
#[cfg(target_os = "linux")]
use core::sync::atomic::{AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU8};
use std::sync::Arc;
use crate::{Heap, Mutator, Trace, Tracer};
use crate::heap::{HeapInternal, MutatorInternal};
#[cfg(target_os = "linux")]
use crate::heap::{Inner, PublicHeap, PublicHeapInternal, PublicMutator, PublicMutatorInternal};
use crate::layout::Header;
use crate::mark::TracerInternal;
#[cfg(target_os = "linux")]
use crate::shm::Region;
use crate::sync::{PushList, SegVec};
pub type Invariant<'gc> = PhantomData<Cell<&'gc ()>>;
type GcBrand<'gc, T> = PhantomData<(&'gc T, fn(&'gc ()) -> &'gc ())>;
#[repr(transparent)]
pub struct Gc<'gc, T> {
ptr: NonNull<T>,
_brand: GcBrand<'gc, T>,
}
unsafe impl<T: Send + Sync> Send for Gc<'_, T> {}
unsafe impl<T: Send + Sync> Sync for Gc<'_, T> {}
impl<T> Clone for Gc<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Gc<'_, T> {}
pub trait GcInternal {
type Data;
unsafe fn from_data(ptr: *mut Self::Data) -> Self;
fn header(self) -> *const Header;
}
impl<T> GcInternal for Gc<'_, T> {
type Data = T;
unsafe fn from_data(ptr: *mut T) -> Self {
Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, _brand: PhantomData }
}
fn header(self) -> *const Header {
Header::of(self.ptr.as_ptr().cast())
}
}
impl<'gc, T> Gc<'gc, T> {
pub fn as_ptr(self) -> *const T {
self.ptr.as_ptr()
}
pub unsafe fn from_raw(ptr: *const T) -> Self {
unsafe { Self::from_data(ptr.cast_mut()) }
}
pub fn get(self) -> &'gc T {
unsafe { self.ptr.as_ref() }
}
pub fn ptr_eq(a: Self, b: Self) -> bool {
a.ptr == b.ptr
}
}
impl<T> Deref for Gc<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
impl<T: fmt::Debug> fmt::Debug for Gc<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[repr(C)]
pub struct Slot<'gc, T> {
word: AtomicU64,
counted: AtomicUsize,
_brand: PhantomData<Gc<'gc, T>>,
}
pub const UNCOUNTED: usize = usize::MAX;
pub const PROMOTED: usize = usize::MAX - 1;
pub const LOGGED: usize = 1;
pub const WORD_POINTER_MIN: u64 = 0xFFF8 << 48;
pub const WORD_PAYLOAD: u64 = (1 << 48) - 1;
pub const RAW_TAG: u64 = 0xFFFF << 48;
#[inline]
pub fn word_pointer(word: u64) -> Option<*mut u8> {
(word >= WORD_POINTER_MIN).then(|| core::ptr::with_exposed_provenance_mut((word & WORD_PAYLOAD) as usize))
}
#[inline]
fn word_with_pointer(word: u64, data: *const u8) -> u64 {
debug_assert!(word >= WORD_POINTER_MIN, "只改指针字");
(word & !WORD_PAYLOAD) | data.expose_provenance() as u64
}
#[repr(C)]
pub struct RawSlot {
pub word: AtomicU64,
pub counted: AtomicUsize,
}
impl RawSlot {
fn header(word: u64) -> Option<*const Header> {
word_pointer(word).map(|p| Header::of(p))
}
pub fn relocate(&self, to: *const Header) {
let w = self.word.load(Ordering::Acquire);
self.word.store(word_with_pointer(w, Header::data(to)), Ordering::Release);
}
fn uncounted(c: usize) -> bool {
c >= PROMOTED
}
fn from_counted(c: usize) -> Option<*const Header> {
(!Self::uncounted(c) && c & !LOGGED != 0).then(|| Header::of(core::ptr::with_exposed_provenance::<u8>(c & !LOGGED)))
}
pub fn log(&self) -> bool {
let c = self.counted.load(Ordering::Relaxed);
!Self::uncounted(c) && c & LOGGED == 0 && self.counted.compare_exchange(c, c | LOGGED, Ordering::AcqRel, Ordering::Relaxed).is_ok()
}
pub fn is_young(&self) -> bool {
self.counted.load(Ordering::Relaxed) == UNCOUNTED
}
pub fn promote(&self) {
let _ = self.counted.compare_exchange(UNCOUNTED, PROMOTED, Ordering::Relaxed, Ordering::Relaxed);
}
pub fn unlog(&self) {
self.counted.fetch_and(!LOGGED, Ordering::AcqRel);
}
pub fn recount(&self) -> (Option<*const Header>, Option<*const Header>) {
let p = word_pointer(self.word.load(Ordering::Acquire));
let prev = self.counted.swap(p.map_or(0, <*mut u8>::expose_provenance), Ordering::AcqRel);
(p.map(|p| Header::of(p.cast_const())), Self::from_counted(prev))
}
pub fn current(&self) -> Option<*const Header> {
Self::header(self.word.load(Ordering::Acquire))
}
pub fn counted(&self) -> Option<*const Header> {
Self::from_counted(self.counted.load(Ordering::Acquire))
}
}
impl<T> Default for Slot<'_, T> {
fn default() -> Self {
Self { word: AtomicU64::new(0), counted: AtomicUsize::new(UNCOUNTED), _brand: PhantomData }
}
}
impl<'gc, T> From<Option<Gc<'gc, T>>> for Slot<'gc, T> {
fn from(v: Option<Gc<'gc, T>>) -> Self {
Self { word: AtomicU64::new(Self::raw(v)), counted: AtomicUsize::new(UNCOUNTED), _brand: PhantomData }
}
}
impl<'gc, T> From<Gc<'gc, T>> for Slot<'gc, T> {
fn from(v: Gc<'gc, T>) -> Self {
Some(v).into()
}
}
impl<'gc, T> Slot<'gc, T> {
fn raw(v: Option<Gc<'gc, T>>) -> u64 {
v.map_or(0, |g| RAW_TAG | g.ptr.as_ptr().expose_provenance() as u64)
}
fn wrap(word: u64) -> Option<Gc<'gc, T>> {
word_pointer(word).map(|p| unsafe { Gc::from_data(p.cast()) })
}
pub fn get(&self) -> Option<Gc<'gc, T>> {
Self::wrap(self.word.load(Ordering::Acquire))
}
pub fn set(&self, m: &Mutator<'gc>, v: Option<Gc<'gc, T>>) {
self.swap(m, v);
}
pub fn swap(&self, m: &Mutator<'gc>, v: Option<Gc<'gc, T>>) -> Option<Gc<'gc, T>> {
let new = Self::raw(v);
let old = self.word.swap(new, Ordering::AcqRel);
m.written(self.raw_slot(), RawSlot::header(old), RawSlot::header(new));
Self::wrap(old)
}
pub fn compare_exchange(&self, m: &Mutator<'gc>, current: Option<Gc<'gc, T>>, new: Option<Gc<'gc, T>>) -> Result<Option<Gc<'gc, T>>, Option<Gc<'gc, T>>> {
let new = Self::raw(new);
let done = self.word.compare_exchange(Self::raw(current), new, Ordering::AcqRel, Ordering::Acquire);
if let Ok(old) = done {
m.written(self.raw_slot(), RawSlot::header(old), RawSlot::header(new));
}
done.map(Self::wrap).map_err(Self::wrap)
}
}
#[repr(C)]
pub struct WordSlot<'gc> {
word: AtomicU64,
counted: AtomicUsize,
_brand: PhantomData<Gc<'gc, ()>>,
}
impl WordSlot<'_> {
pub fn new(word: u64) -> Self {
Self { word: AtomicU64::new(word), counted: AtomicUsize::new(UNCOUNTED), _brand: PhantomData }
}
#[inline]
pub fn get(&self) -> u64 {
self.word.load(Ordering::Acquire)
}
#[inline]
pub fn set(&self, m: &Mutator<'_>, word: u64) {
let old = self.word.load(Ordering::Relaxed);
self.word.store(word, Ordering::Release);
let (o, n) = (RawSlot::header(old), RawSlot::header(word));
if o != n {
m.written(self.raw_slot(), o, n);
}
}
pub fn set_mut(&mut self, word: u64) {
*self.word.get_mut() = word;
}
fn raw_slot(&self) -> &RawSlot {
unsafe { &*(&raw const *self).cast::<RawSlot>() }
}
}
impl fmt::Debug for WordSlot<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "WordSlot({:#x})", self.get())
}
}
pub trait WordSlotInternal {
fn raw(&self) -> &RawSlot;
}
impl WordSlotInternal for WordSlot<'_> {
fn raw(&self) -> &RawSlot {
self.raw_slot()
}
}
pub trait SlotInternal<'gc> {
type Data;
fn raw_slot(&self) -> &RawSlot;
}
impl<'gc, T> SlotInternal<'gc> for Slot<'gc, T> {
type Data = T;
fn raw_slot(&self) -> &RawSlot {
unsafe { &*(&raw const *self).cast::<RawSlot>() }
}
}
impl<T: fmt::Debug> fmt::Debug for Slot<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Slot").field(&self.get()).finish()
}
}
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> {
unsafe { self.recycle() };
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()
}
unsafe fn recycle(&self) {
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());
}
pub unsafe fn clear_unreached(&self, epoch: u32, parity: bool) {
unsafe { self.recycle() };
for slot in self.slots.iter() {
let old = slot.load();
if old.is_null() {
continue;
}
let new = Header::survivor(old, epoch);
if let Some(new) = new {
unsafe { &*new }.rc_stick(parity);
}
let new = new.map_or(null_mut(), <*const Header>::cast_mut);
if !core::ptr::eq(old, new) {
let _ = slot.ptr.compare_exchange(old, new, Ordering::AcqRel, Ordering::Acquire);
}
}
}
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());
}
}
pub struct Weak<B: Brand> {
table: Arc<RootTable>,
slot: usize,
_brand: PhantomData<fn() -> B>,
}
impl<B: Brand> Weak<B> {
pub fn is_cleared(&self) -> bool {
self.table.slot(self.slot).load().is_null()
}
}
impl<B: Brand> Drop for Weak<B> {
fn drop(&mut self) {
self.table.release(self.slot);
}
}
unsafe impl<B: Brand> Trace for Weak<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut crate::Tracer<'_>) {}
}
impl<'gc> Mutator<'gc> {
pub fn weak<B: Brand>(&self, gc: Gc<'gc, B::Of<'gc>>) -> Weak<B> {
let table = self.heap().weaks().clone();
let slot = table.claim(gc.header(), NO_HOLDER);
Weak { table, slot, _brand: PhantomData }
}
pub fn upgrade<B: Brand>(&self, weak: &Weak<B>) -> Option<Gc<'gc, B::Of<'gc>>> {
assert!(Arc::ptr_eq(&weak.table, self.heap().weaks()), "这个 Weak 不属于这个堆");
let header = weak.table.slot(weak.slot).load();
if header.is_null() {
return None;
}
self.reached(header);
Some(unsafe { Gc::from_data(Header::data(header).cast()) })
}
}
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);
}
}
#[cfg(target_os = "linux")]
pub unsafe trait Shared: Send + Sync {
const NO_EDGES: bool = false;
fn edges(map: &mut EdgeMap, at: u32);
}
#[cfg(target_os = "linux")]
pub const FAR_EDGE: u32 = 1 << 31;
#[derive(Default)]
#[cfg(target_os = "linux")]
pub struct EdgeMap(Vec<u32>);
#[cfg(target_os = "linux")]
impl EdgeMap {
pub fn edge(&mut self, at: u32) {
self.0.push(at);
}
pub fn far(&mut self, at: u32) {
self.0.push(at | FAR_EDGE);
}
pub fn as_slice(&self) -> &[u32] {
&self.0
}
pub fn offset(bytes: usize) -> u32 {
u32::try_from(bytes).expect("公开堆的对象不超过 4 GiB")
}
}
#[cfg(target_os = "linux")]
macro_rules! shared_leaf {
($($ty:ty),* $(,)?) => {$(
unsafe impl Shared for $ty {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
)*};
}
#[cfg(target_os = "linux")]
shared_leaf!(
(), bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64,
NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64,
AtomicBool, AtomicU8, AtomicU16, AtomicU32, AtomicU64, AtomicI8, AtomicI16, AtomicI32, AtomicI64,
);
#[cfg(target_os = "linux")]
unsafe impl<T: ?Sized + Send + Sync> Shared for PhantomData<T> {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
#[cfg(target_os = "linux")]
unsafe impl<T: Shared, const N: usize> Shared for [T; N] {
const NO_EDGES: bool = T::NO_EDGES;
fn edges(map: &mut EdgeMap, at: u32) {
if !T::NO_EDGES {
for i in 0..N {
T::edges(map, at + EdgeMap::offset(i * size_of::<T>()));
}
}
}
}
#[cfg(target_os = "linux")]
pub struct PublicGc<'p, T> {
ptr: NonNull<T>,
_brand: PhantomData<(&'p T, Invariant<'p>)>,
}
#[cfg(target_os = "linux")]
unsafe impl<T: Send + Sync> Send for PublicGc<'_, T> {}
#[cfg(target_os = "linux")]
unsafe impl<T: Send + Sync> Sync for PublicGc<'_, T> {}
#[cfg(target_os = "linux")]
impl<T> Clone for PublicGc<'_, T> {
fn clone(&self) -> Self {
*self
}
}
#[cfg(target_os = "linux")]
impl<T> Copy for PublicGc<'_, T> {}
#[cfg(target_os = "linux")]
impl<'p, T> PublicGc<'p, T> {
pub fn as_ptr(self) -> *const T {
self.ptr.as_ptr()
}
pub fn get(self) -> &'p T {
unsafe { self.ptr.as_ref() }
}
pub fn ptr_eq(a: Self, b: Self) -> bool {
a.ptr == b.ptr
}
}
#[cfg(target_os = "linux")]
pub trait PublicGcInternal {
unsafe fn from_data(ptr: *mut u8) -> Self;
fn offset(self) -> u64;
}
#[cfg(target_os = "linux")]
impl<T> PublicGcInternal for PublicGc<'_, T> {
unsafe fn from_data(ptr: *mut u8) -> Self {
Self { ptr: unsafe { NonNull::new_unchecked(ptr.cast()) }, _brand: PhantomData }
}
fn offset(self) -> u64 {
let addr = self.ptr.as_ptr().addr();
(addr - Region::base_of(addr)) as u64
}
}
#[cfg(target_os = "linux")]
impl<T> Deref for PublicGc<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
#[cfg(target_os = "linux")]
impl<T: fmt::Debug> fmt::Debug for PublicGc<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[repr(transparent)]
#[cfg(target_os = "linux")]
pub struct PublicSlot<'p, T> {
off: AtomicU64,
_brand: PhantomData<PublicGc<'p, T>>,
}
#[cfg(target_os = "linux")]
impl<T> Default for PublicSlot<'_, T> {
fn default() -> Self {
Self { off: AtomicU64::new(0), _brand: PhantomData }
}
}
#[cfg(target_os = "linux")]
impl<'p, T> From<Option<PublicGc<'p, T>>> for PublicSlot<'p, T> {
fn from(v: Option<PublicGc<'p, T>>) -> Self {
Self { off: AtomicU64::new(Self::raw(v)), _brand: PhantomData }
}
}
#[cfg(target_os = "linux")]
impl<'p, T> From<PublicGc<'p, T>> for PublicSlot<'p, T> {
fn from(v: PublicGc<'p, T>) -> Self {
Some(v).into()
}
}
#[cfg(target_os = "linux")]
impl<'p, T> PublicSlot<'p, T> {
fn raw(v: Option<PublicGc<'p, T>>) -> u64 {
v.map_or(0, PublicGc::offset)
}
fn wrap(m: &PublicMutator<'p>, off: u64) -> Option<PublicGc<'p, T>> {
(off != 0).then(|| unsafe { PublicGc::from_data(m.at(off)) })
}
pub fn get(&self, m: &PublicMutator<'p>) -> Option<PublicGc<'p, T>> {
Self::wrap(m, self.off.load(Ordering::Acquire))
}
pub fn set(&self, m: &PublicMutator<'p>, v: Option<PublicGc<'p, T>>) {
self.swap(m, v);
}
pub fn swap(&self, m: &PublicMutator<'p>, v: Option<PublicGc<'p, T>>) -> Option<PublicGc<'p, T>> {
Self::wrap(m, self.off.swap(Self::raw(v), Ordering::AcqRel))
}
pub fn compare_exchange(&self, m: &PublicMutator<'p>, current: Option<PublicGc<'p, T>>, new: Option<PublicGc<'p, T>>) -> Result<Option<PublicGc<'p, T>>, Option<PublicGc<'p, T>>> {
self.off
.compare_exchange(Self::raw(current), Self::raw(new), Ordering::AcqRel, Ordering::Acquire)
.map(|o| Self::wrap(m, o))
.map_err(|o| Self::wrap(m, o))
}
}
#[cfg(target_os = "linux")]
unsafe impl<T: Send + Sync> Shared for PublicSlot<'_, T> {
fn edges(map: &mut EdgeMap, at: u32) {
map.edge(at);
}
}
#[repr(C)]
#[cfg(target_os = "linux")]
pub struct PublicRef<'a, B: PublicBrand> {
off: AtomicU64,
incarnation: AtomicU64,
_brand: PhantomData<(HolderBrand<'a>, fn() -> B)>,
}
#[cfg(target_os = "linux")]
type HolderBrand<'a> = fn(&'a ()) -> &'a ();
#[cfg(target_os = "linux")]
impl<B: PublicBrand> Default for PublicRef<'_, B> {
fn default() -> Self {
Self { off: AtomicU64::new(0), incarnation: AtomicU64::new(0), _brand: PhantomData }
}
}
#[cfg(target_os = "linux")]
impl<'a, B: PublicBrand> PublicRef<'a, B> {
pub fn to<'b>(holder: &PublicMutator<'a>, target: &PublicMutator<'b>, gc: PublicGc<'b, B::Of<'b>>) -> Self {
let r = Self::default();
r.set(holder, target, Some(gc));
r
}
pub fn set<'b>(&self, holder: &PublicMutator<'a>, target: &PublicMutator<'b>, v: Option<PublicGc<'b, B::Of<'b>>>) {
assert!(holder.index() != target.index(), "同一个公开堆里的边用 PublicSlot");
let off = v.map_or(0, PublicGc::offset);
if off != 0 {
target.register(off, holder);
}
self.incarnation.store(target.incarnation(), Ordering::Release);
self.off.store(off, Ordering::Release);
}
pub fn get<'b>(&self, target: &PublicMutator<'b>) -> Option<PublicGc<'b, B::Of<'b>>> {
let off = self.off.load(Ordering::Acquire);
if off == 0 || Inner::heap_of(off) != Some(target.index()) || self.incarnation.load(Ordering::Acquire) != target.incarnation() {
return None;
}
Some(unsafe { PublicGc::from_data(target.at(off)) })
}
pub fn points_into(&self, heap: &PublicHeap) -> bool {
Inner::heap_of(self.off.load(Ordering::Acquire)) == Some(heap.id()) && self.incarnation.load(Ordering::Acquire) == heap.incarnation()
}
}
#[cfg(target_os = "linux")]
unsafe impl<B: PublicBrand> Shared for PublicRef<'_, B> {
fn edges(map: &mut EdgeMap, at: u32) {
map.far(at);
}
}
#[cfg(target_os = "linux")]
pub trait PublicBrand {
type Of<'p>: Shared + 'p;
}
#[cfg(target_os = "linux")]
#[macro_export]
macro_rules! public_brand {
($(#[$meta:meta])* $vis:vis $name:ident = for<$l:lifetime> $ty:ty) => {
$(#[$meta])*
$vis struct $name;
impl $crate::PublicBrand for $name {
type Of<$l> = $ty;
}
};
}
#[cfg(target_os = "linux")]
pub struct Public<B: PublicBrand> {
heap: Arc<Inner>,
entry: u32,
data: NonNull<u8>,
_brand: PhantomData<fn() -> B>,
}
#[cfg(target_os = "linux")]
unsafe impl<B: PublicBrand> Send for Public<B> {}
#[cfg(target_os = "linux")]
unsafe impl<B: PublicBrand> Sync for Public<B> {}
#[cfg(target_os = "linux")]
impl<B: PublicBrand> Public<B> {
pub fn get<'p>(&self, m: &PublicMutator<'p>) -> PublicGc<'p, B::Of<'p>> {
assert!(m.is(&self.heap), "这个 Public 不指向这个堆");
unsafe { PublicGc::from_data(self.data.as_ptr()) }
}
pub fn points_into(&self, heap: &PublicHeap) -> bool {
heap.is(&self.heap)
}
pub fn index(&self) -> u32 {
self.entry
}
pub fn persist(self) -> u32 {
let me = core::mem::ManuallyDrop::new(self);
me.heap.disown_entry(me.entry);
let entry = me.entry;
drop(unsafe { core::ptr::read(&raw const me.heap) });
entry
}
}
#[cfg(target_os = "linux")]
pub trait PublicInternal {
fn new(heap: Arc<Inner>, entry: u32, data: NonNull<u8>) -> Self;
}
#[cfg(target_os = "linux")]
impl<B: PublicBrand> PublicInternal for Public<B> {
fn new(heap: Arc<Inner>, entry: u32, data: NonNull<u8>) -> Self {
Self { heap, entry, data, _brand: PhantomData }
}
}
#[cfg(target_os = "linux")]
impl<B: PublicBrand> Drop for Public<B> {
fn drop(&mut self) {
self.heap.release_entry(self.entry);
}
}
#[cfg(target_os = "linux")]
unsafe impl<B: PublicBrand> Trace for Public<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut Tracer<'_>) {}
}