use super::collectible::{Collectible, DeferredClosure};
use super::collector::Collector;
use std::panic::UnwindSafe;
pub struct Guard {
collector_ptr: *mut Collector,
}
impl Guard {
#[inline]
#[must_use]
pub fn new() -> Self {
let collector_ptr = Collector::current();
unsafe { (*collector_ptr).new_guard(true) };
Self { collector_ptr }
}
#[inline]
pub fn defer(&self, collectible: Box<dyn Collectible>) {
self.collect(Box::into_raw(collectible));
}
#[inline]
pub fn defer_execute<F: 'static + FnOnce() + Sync>(&self, f: F) {
self.defer(Box::new(DeferredClosure::new(f)));
}
#[inline]
pub(super) fn new_for_drop() -> Self {
let collector_ptr = Collector::current();
unsafe {
(*collector_ptr).new_guard(false);
}
Self { collector_ptr }
}
#[inline]
pub(super) fn collect(&self, collectible: *mut dyn Collectible) {
unsafe {
(*self.collector_ptr).reclaim(collectible);
}
}
}
impl Default for Guard {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Drop for Guard {
#[inline]
fn drop(&mut self) {
unsafe {
(*self.collector_ptr).end_guard();
}
}
}
impl UnwindSafe for Guard {}