use core::cell::Cell;
use core::fmt;
use core::marker::PhantomData;
use core::ops::Deref;
use core::ptr::{NonNull, null_mut};
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use crate::Mutator;
use crate::header::Header;
pub(crate) type Invariant<'gc> = PhantomData<Cell<&'gc ()>>;
type Brand<'gc, T> = PhantomData<(&'gc T, fn(&'gc ()) -> &'gc ())>;
pub struct Gc<'gc, T> {
ptr: NonNull<T>,
_brand: Brand<'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> {}
impl<'gc, T> Gc<'gc, T> {
pub(crate) unsafe fn from_data(ptr: *mut T) -> Self {
Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, _brand: PhantomData }
}
pub(crate) fn header(self) -> *const Header {
Header::of(self.ptr.as_ptr().cast())
}
pub fn as_ptr(self) -> *const T {
self.ptr.as_ptr()
}
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> {
ptr: AtomicPtr<T>,
counted: AtomicUsize,
_brand: PhantomData<Gc<'gc, T>>,
}
pub(crate) const UNCOUNTED: usize = usize::MAX;
pub(crate) const LOGGED: usize = 1;
#[repr(C)]
pub(crate) struct RawSlot {
pub(crate) ptr: AtomicPtr<u8>,
pub(crate) counted: AtomicUsize,
}
impl RawSlot {
fn header(p: *mut u8) -> Option<*const Header> {
(!p.is_null()).then(|| Header::of(p))
}
fn from_counted(c: usize) -> Option<*const Header> {
(c != UNCOUNTED && c & !LOGGED != 0).then(|| Header::of(core::ptr::with_exposed_provenance::<u8>(c & !LOGGED)))
}
pub(crate) fn log(&self) -> bool {
let c = self.counted.load(Ordering::Relaxed);
c != UNCOUNTED && c & LOGGED == 0 && self.counted.compare_exchange(c, c | LOGGED, Ordering::AcqRel, Ordering::Relaxed).is_ok()
}
pub(crate) fn unlog(&self) {
self.counted.fetch_and(!LOGGED, Ordering::AcqRel);
}
pub(crate) fn recount(&self) -> (Option<*const Header>, Option<*const Header>) {
let p = self.ptr.load(Ordering::Acquire);
let prev = self.counted.swap(p.expose_provenance(), Ordering::AcqRel);
(Self::header(p), Self::from_counted(prev))
}
pub(crate) fn counted(&self) -> Option<*const Header> {
Self::from_counted(self.counted.load(Ordering::Acquire))
}
}
impl<T> Default for Slot<'_, T> {
fn default() -> Self {
Self { ptr: AtomicPtr::new(null_mut()), 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 { ptr: AtomicPtr::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>>) -> *mut T {
v.map_or(null_mut(), |g| g.ptr.as_ptr())
}
fn wrap(p: *mut T) -> Option<Gc<'gc, T>> {
(!p.is_null()).then(|| unsafe { Gc::from_data(p) })
}
pub fn get(&self) -> Option<Gc<'gc, T>> {
Self::wrap(self.ptr.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.ptr.swap(new, Ordering::AcqRel);
self.barrier(m, old, 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.ptr.compare_exchange(Self::raw(current), new, Ordering::AcqRel, Ordering::Acquire);
if let Ok(old) = done {
self.barrier(m, old, new);
}
done.map(Self::wrap).map_err(Self::wrap)
}
pub(crate) fn store_exclusive(&mut self, v: Option<Gc<'gc, T>>) {
*self.ptr.get_mut() = Self::raw(v);
}
pub(crate) fn raw_slot(&self) -> &RawSlot {
unsafe { &*(&raw const *self).cast::<RawSlot>() }
}
fn barrier(&self, m: &Mutator<'gc>, old: *mut T, new: *mut T) {
let header = |p: *mut T| (!p.is_null()).then(|| Header::of(p.cast()));
m.written(self.raw_slot(), header(old), header(new));
}
}
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()
}
}