use std::cell::UnsafeCell;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::ops::DerefMut;
use crate::storage::GlobalTermPoolGuard;
use crate::storage::THREAD_TERM_POOL;
pub(crate) struct GcMutex<T> {
inner: UnsafeCell<T>,
}
unsafe impl<T: Send> Send for GcMutex<T> {}
unsafe impl<T: Send + Sync> Sync for GcMutex<T> {}
impl<T> GcMutex<T> {
pub fn new(value: T) -> GcMutex<T> {
GcMutex {
inner: UnsafeCell::new(value),
}
}
pub fn lock(&self) -> GcMutexReadGuard<'_, T> {
GcMutexReadGuard {
mutex: self,
guard: ManuallyDrop::new(THREAD_TERM_POOL.with(|tp| unsafe {
std::mem::transmute::<_, GlobalTermPoolGuard<'_>>(
tp.term_pool().read_recursive().expect("Lock poisoned!"),
)
})),
}
}
pub fn lock_mut(&mut self) -> GcMutexGuard<'_, T> {
GcMutexGuard {
mutex: self,
guard: ManuallyDrop::new(THREAD_TERM_POOL.with(|tp| unsafe {
std::mem::transmute::<_, GlobalTermPoolGuard<'_>>(
tp.term_pool().read_recursive().expect("Lock poisoned!"),
)
})),
}
}
}
pub(crate) struct GcMutexReadGuard<'a, T> {
mutex: &'a GcMutex<T>,
guard: ManuallyDrop<GlobalTermPoolGuard<'a>>,
}
impl<T> Deref for GcMutexReadGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.mutex.inner.get() }
}
}
impl<T> Drop for GcMutexReadGuard<'_, T> {
fn drop(&mut self) {
THREAD_TERM_POOL.with(|tp| {
if self.guard.read_depth() == 1 {
unsafe { tp.trigger_delayed_garbage_collection(&mut self.guard) }
} else {
unsafe { ManuallyDrop::drop(&mut self.guard) };
}
});
}
}
pub(crate) struct GcMutexGuard<'a, T> {
mutex: &'a GcMutex<T>,
guard: ManuallyDrop<GlobalTermPoolGuard<'a>>,
}
impl<T> Deref for GcMutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.mutex.inner.get() }
}
}
impl<T> DerefMut for GcMutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.mutex.inner.get() }
}
}
impl<T> Drop for GcMutexGuard<'_, T> {
fn drop(&mut self) {
THREAD_TERM_POOL.with(|tp| {
if self.guard.read_depth() == 1 {
unsafe { tp.trigger_delayed_garbage_collection(&mut self.guard) }
} else {
unsafe { ManuallyDrop::drop(&mut self.guard) };
}
});
}
}