#[cfg(debug_assertions)]
use std::cell::RefCell;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;
use std::mem::transmute;
use std::ops::Deref;
use std::ops::DerefMut;
use std::sync::Arc;
use merc_unsafety::ProtectionIndex;
use merc_utilities::PhantomUnsend;
use crate::Markable;
use crate::Symb;
use crate::SymbolRef;
use crate::Term;
use crate::Transmutable;
use crate::aterm::ATermRef;
use crate::storage::GcMutex;
use crate::storage::GcMutexReadGuard;
use crate::storage::SendContainerProtectionSet;
use crate::storage::THREAD_TERM_POOL;
pub struct Protected<C> {
container: Arc<GcMutex<C>>,
root: ProtectionIndex,
_unsend: PhantomUnsend,
}
impl<C: Markable + Send + Sync + Transmutable + 'static> Protected<C> {
pub fn new(container: C) -> Protected<C> {
let shared = Arc::new(GcMutex::new(container));
let root = THREAD_TERM_POOL.with(|tp| tp.protect_container(shared.clone()));
Protected {
container: shared,
root,
_unsend: Default::default(),
}
}
pub fn write<'env, F, R>(&mut self, f: F) -> R
where
F: for<'g> FnOnce(&'g mut ProtectedWriteGuard<'g, 'env, C::Target<'g>>) -> R,
{
let mutex = unsafe { &mut *(Arc::as_ptr(&self.container) as *mut GcMutex<C>) };
write_scoped(mutex, f)
}
pub fn read(&self) -> ProtectedReadGuard<'_, C> {
ProtectedReadGuard::new(self.container.lock())
}
}
impl<C: Default + Markable + Send + Sync + Transmutable + 'static> Default for Protected<C> {
fn default() -> Self {
Protected::new(Default::default())
}
}
impl<C: Clone + Markable + Send + Sync + Transmutable + 'static> Clone for Protected<C> {
fn clone(&self) -> Self {
Protected::new(self.container.lock().clone())
}
}
impl<C: Hash + Markable> Hash for Protected<C> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.container.lock().hash(state)
}
}
impl<C: PartialEq + Markable> PartialEq for Protected<C> {
fn eq(&self, other: &Self) -> bool {
self.container.lock().eq(&other.container.lock())
}
}
impl<C: PartialOrd + Markable> PartialOrd for Protected<C> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
let c: &C = &other.container.lock();
self.container.lock().partial_cmp(c)
}
}
impl<C: Debug + Markable> Debug for Protected<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c: &C = &self.container.lock();
write!(f, "{c:?}")
}
}
impl<C: Eq + PartialEq + Markable> Eq for Protected<C> {}
impl<C: Ord + PartialEq + PartialOrd + Markable> Ord for Protected<C> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
let c: &C = &other.container.lock();
self.container.lock().partial_cmp(c).unwrap()
}
}
impl<C> Drop for Protected<C> {
fn drop(&mut self) {
THREAD_TERM_POOL.with(|tp| {
tp.drop_container(self.root);
});
}
}
pub struct ProtectedSend<C> {
container: Arc<GcMutex<C>>,
root: ProtectionIndex,
protection_set: SendContainerProtectionSet,
}
impl<C: Markable + Send + Sync + Transmutable + 'static> ProtectedSend<C> {
pub fn new(container: C) -> ProtectedSend<C> {
let shared = Arc::new(GcMutex::new(container));
let protection_set = THREAD_TERM_POOL.with(|tp| tp.send_container_protection_set().clone());
let root = protection_set.lock().expect("Lock poisoned!").protect(shared.clone());
ProtectedSend {
container: shared,
root,
protection_set,
}
}
pub fn write<'env, F, R>(&mut self, f: F) -> R
where
F: for<'g> FnOnce(&'g mut ProtectedWriteGuard<'g, 'env, C::Target<'g>>) -> R,
{
let mutex = unsafe { &mut *(Arc::as_ptr(&self.container) as *mut GcMutex<C>) };
write_scoped(mutex, f)
}
pub fn read(&self) -> ProtectedReadGuard<'_, C> {
ProtectedReadGuard::new(self.container.lock())
}
}
impl<C: Default + Markable + Send + Sync + Transmutable + 'static> Default for ProtectedSend<C> {
fn default() -> Self {
ProtectedSend::new(Default::default())
}
}
impl<C> Drop for ProtectedSend<C> {
fn drop(&mut self) {
let mut guard = match self.protection_set.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
unsafe {
guard.unprotect(self.root);
}
}
}
fn write_scoped<'env, C, F, R>(mutex: &mut GcMutex<C>, f: F) -> R
where
C: Markable + Transmutable,
F: for<'g> FnOnce(&'g mut ProtectedWriteGuard<'g, 'env, C::Target<'g>>) -> R,
{
let mut lock = mutex.lock_mut();
#[cfg(debug_assertions)]
let protected = RefCell::new(Vec::new());
#[cfg(debug_assertions)]
let protected_symbols = RefCell::new(Vec::new());
let container = unsafe { lock.transmute_lifetime_mut() };
let result = f(&mut ProtectedWriteGuard {
container,
_env: PhantomData,
#[cfg(debug_assertions)]
protected: &protected,
#[cfg(debug_assertions)]
protected_symbols: &protected_symbols,
});
#[cfg(debug_assertions)]
{
for term in protected.borrow().iter() {
debug_assert!(lock.contains_term(term), "Term was protected but not actually inserted");
}
for symbol in protected_symbols.borrow().iter() {
debug_assert!(
lock.contains_symbol(symbol),
"Symbol was protected but not actually inserted"
);
}
}
result
}
pub struct ProtectedWriteGuard<'a, 'env, T: ?Sized> {
container: &'a mut T,
_env: PhantomData<&'a mut &'env ()>,
#[cfg(debug_assertions)]
protected: &'a RefCell<Vec<ATermRef<'static>>>,
#[cfg(debug_assertions)]
protected_symbols: &'a RefCell<Vec<SymbolRef<'static>>>,
}
impl<'a, C: ?Sized> ProtectedWriteGuard<'a, '_, C> {
pub unsafe fn protect<'b, T: Term<'a, 'b>>(&self, term: &'b T) -> ATermRef<'static> {
unsafe {
#[cfg(debug_assertions)]
self.protected
.borrow_mut()
.push(transmute::<ATermRef<'_>, ATermRef<'static>>(term.copy()));
transmute::<ATermRef<'_>, ATermRef<'static>>(term.copy())
}
}
pub unsafe fn protect_symbol<'b, S: Symb<'a, 'b>>(&self, symbol: &'b S) -> SymbolRef<'static> {
unsafe {
#[cfg(debug_assertions)]
self.protected_symbols
.borrow_mut()
.push(transmute::<SymbolRef<'_>, SymbolRef<'static>>(symbol.copy()));
transmute::<SymbolRef<'_>, SymbolRef<'static>>(symbol.copy())
}
}
}
impl<T: ?Sized> Deref for ProtectedWriteGuard<'_, '_, T> {
type Target = T;
fn deref(&self) -> &T {
self.container
}
}
impl<T: ?Sized> DerefMut for ProtectedWriteGuard<'_, '_, T> {
fn deref_mut(&mut self) -> &mut T {
self.container
}
}
pub struct ProtectedReadGuard<'a, C> {
reference: GcMutexReadGuard<'a, C>,
}
impl<'a, C> ProtectedReadGuard<'a, C> {
fn new(reference: GcMutexReadGuard<'a, C>) -> Self {
Self { reference }
}
}
impl<'a, C: Transmutable> Deref for ProtectedReadGuard<'a, C> {
type Target = C::Target<'a>;
fn deref(&self) -> &Self::Target {
unsafe { self.reference.transmute_lifetime() }
}
}
#[cfg(test)]
mod tests {
use crate::ATerm;
use crate::ATermRef;
use crate::Protected;
#[test]
fn test_aterm_container() {
merc_utilities::test_logger();
let t = ATerm::from_string("f(g(a),b)").unwrap();
let mut container = Protected::<Vec<ATermRef<'static>>>::new(vec![]);
for _ in 0..1000 {
container.write(|write| write.push(t.get()));
}
}
}