use core::fmt;
use core::marker::PhantomData;
use core::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64};
use core::ops::Deref;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use super::heap::{PublicHeapInternal, PublicMutatorInternal};
use crate::block::Finalize;
use crate::gc::Invariant;
use crate::header::Core;
use crate::{Trace, Tracer};
use super::heap::{HEAP_HOLDER, Inner, PublicHeap, PublicMutator};
use super::region::Region;
#[repr(C)]
pub struct PHeader {
pub core: Core,
pub ty: u32,
_pad: u32,
}
pub const PHEADER: usize = size_of::<PHeader>();
const _: () = assert!(PHEADER == 16, "公开堆的对象头是 16 字节");
impl PHeader {
pub fn new(bytes: usize, large: bool, ty: u32) -> Self {
Self { core: Core::new(bytes, large, 0), ty, _pad: 0 }
}
pub fn data(this: *const Self) -> *mut u8 {
this.cast::<u8>().cast_mut().wrapping_add(PHEADER)
}
pub fn of(data: *const u8) -> *const Self {
data.wrapping_sub(PHEADER).cast()
}
}
impl Finalize for PHeader {
unsafe fn finalize(_: *const Core) {}
}
pub unsafe trait Shared: Send + Sync {
const NO_EDGES: bool = false;
fn edges(map: &mut EdgeMap, at: u32);
}
#[derive(Default)]
pub struct EdgeMap(Vec<u32>);
impl EdgeMap {
pub fn edge(&mut self, at: u32) {
self.0.push(at);
}
pub fn as_slice(&self) -> &[u32] {
&self.0
}
pub fn offset(bytes: usize) -> u32 {
u32::try_from(bytes).expect("公开堆的对象不超过 4 GiB")
}
}
macro_rules! leaf {
($($ty:ty),* $(,)?) => {$(
unsafe impl Shared for $ty {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
)*};
}
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,
);
unsafe impl<T: ?Sized + Send + Sync> Shared for PhantomData<T> {
const NO_EDGES: bool = true;
fn edges(_: &mut EdgeMap, _: u32) {}
}
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>()));
}
}
}
}
pub struct PublicGc<'p, T> {
ptr: NonNull<T>,
_brand: PhantomData<(&'p T, Invariant<'p>)>,
}
unsafe impl<T: Send + Sync> Send for PublicGc<'_, T> {}
unsafe impl<T: Send + Sync> Sync for PublicGc<'_, T> {}
impl<T> Clone for PublicGc<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for PublicGc<'_, T> {}
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
}
}
pub trait PublicGcInternal {
unsafe fn from_data(ptr: *mut u8) -> Self;
fn offset(self) -> u64;
}
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
}
}
impl<T> Deref for PublicGc<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
}
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)]
pub struct PublicSlot<'p, T> {
off: AtomicU64,
_brand: PhantomData<PublicGc<'p, T>>,
}
impl<T> Default for PublicSlot<'_, T> {
fn default() -> Self {
Self { off: AtomicU64::new(0), _brand: PhantomData }
}
}
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 }
}
}
impl<'p, T> From<PublicGc<'p, T>> for PublicSlot<'p, T> {
fn from(v: PublicGc<'p, T>) -> Self {
Some(v).into()
}
}
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))
}
}
unsafe impl<T: Send + Sync> Shared for PublicSlot<'_, T> {
fn edges(map: &mut EdgeMap, at: u32) {
map.edge(at);
}
}
#[repr(transparent)]
pub struct PublicRef<'a, B: PublicBrand> {
off: AtomicU64,
_brand: PhantomData<(HolderBrand<'a>, fn() -> B)>,
}
type HolderBrand<'a> = fn(&'a ()) -> &'a ();
impl<B: PublicBrand> Default for PublicRef<'_, B> {
fn default() -> Self {
Self { off: AtomicU64::new(0), _brand: PhantomData }
}
}
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, HEAP_HOLDER | u32::try_from(holder.index()).expect("堆号"));
}
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 {
return None;
}
assert!(Inner::heap_of(off) == Some(target.index()), "这个 PublicRef 不指向这个堆");
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())
}
}
unsafe impl<B: PublicBrand> Shared for PublicRef<'_, B> {
fn edges(map: &mut EdgeMap, at: u32) {
map.edge(at);
}
}
pub trait PublicBrand {
type Of<'p>: Shared + 'p;
}
#[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;
}
};
}
pub struct Public<B: PublicBrand> {
heap: Arc<Inner>,
entry: u32,
data: NonNull<u8>,
_brand: PhantomData<fn() -> B>,
}
unsafe impl<B: PublicBrand> Send for Public<B> {}
unsafe impl<B: PublicBrand> Sync for Public<B> {}
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
}
}
pub trait PublicInternal {
fn new(heap: Arc<Inner>, entry: u32, data: NonNull<u8>) -> Self;
}
impl<B: PublicBrand> PublicInternal for Public<B> {
fn new(heap: Arc<Inner>, entry: u32, data: NonNull<u8>) -> Self {
Self { heap, entry, data, _brand: PhantomData }
}
}
impl<B: PublicBrand> Drop for Public<B> {
fn drop(&mut self) {
self.heap.release_entry(self.entry);
}
}
unsafe impl<B: PublicBrand> Trace for Public<B> {
const NO_EDGES: bool = true;
fn trace(&self, _: &mut Tracer<'_>) {}
}