use std::cell::RefCell;
use std::ops::Deref;
pub struct Scope<T>(RefCell<Option<*const T>>)
where
T: ?Sized;
impl<T> Default for Scope<T>
where
T: ?Sized,
{
fn default() -> Self {
Self(RefCell::new(None))
}
}
impl<T> Scope<T>
where
T: ?Sized,
{
#[inline]
pub fn scoped<TFn, TRet>(&self, value: &T, fun: TFn) -> TRet
where
TFn: FnOnce() -> TRet,
{
let mut cleanup_on_drop = CleanupOnDrop {
scope: Some(self),
previous_value: self.take(),
};
self.set(Some(value));
let fun_result = fun();
cleanup_on_drop.cleanup();
fun_result
}
#[inline]
pub fn with<TFn, TRet>(&self, fun: TFn) -> TRet
where
TFn: FnOnce(Option<&T>) -> TRet,
{
let value = self.get();
fun(value)
}
#[inline]
fn set(&self, value: Option<&T>) {
*self.0.borrow_mut() = if let Some(value) = value {
Some(value as *const T)
} else {
None
};
}
#[inline]
fn get(&self) -> Option<&T> {
let self_borrowed = self.0.borrow();
if let Some(value) = self_borrowed.deref() {
Some(unsafe { &*(*value) })
} else {
None
}
}
#[inline]
fn take(&self) -> Option<&T> {
let mut self_borrowed = self.0.borrow_mut();
if let Some(taken) = self_borrowed.take() {
Some(unsafe { &*taken })
} else {
None
}
}
}
struct CleanupOnDrop<'a, T>
where
T: ?Sized,
{
scope: Option<&'a Scope<T>>,
previous_value: Option<&'a T>,
}
impl<'a, T> CleanupOnDrop<'a, T>
where
T: ?Sized,
{
fn cleanup(&mut self) {
if let Some(scope) = self.scope.take() {
scope.set(self.previous_value);
}
}
}
impl<'a, T> Drop for CleanupOnDrop<'a, T>
where
T: ?Sized,
{
fn drop(&mut self) {
self.cleanup();
}
}