use std::prelude::v1::*;
use std::cell::Cell;
use std::fmt;
#[cfg(feature = "unstable-futures")]
use futures2;
thread_local!(static ENTERED: Cell<bool> = Cell::new(false));
pub struct Enter {
on_exit: Vec<Box<Callback>>,
permanent: bool,
#[cfg(feature = "unstable-futures")]
_enter2: futures2::executor::Enter,
}
pub struct EnterError {
_a: (),
}
impl fmt::Debug for EnterError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("EnterError")
.field("reason", &"attempted to run an executor while another executor is already running")
.finish()
}
}
pub fn enter() -> Result<Enter, EnterError> {
ENTERED.with(|c| {
if c.get() {
Err(EnterError { _a: () })
} else {
c.set(true);
Ok(Enter {
on_exit: Vec::new(),
permanent: false,
#[cfg(feature = "unstable-futures")]
_enter2: futures2::executor::enter().unwrap(),
})
}
})
}
impl Enter {
pub fn on_exit<F>(&mut self, f: F) where F: FnOnce() + 'static {
self.on_exit.push(Box::new(f));
}
pub fn make_permanent(mut self) {
self.permanent = true;
}
}
impl fmt::Debug for Enter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Enter").finish()
}
}
impl Drop for Enter {
fn drop(&mut self) {
ENTERED.with(|c| {
assert!(c.get());
if self.permanent {
return
}
for callback in self.on_exit.drain(..) {
callback.call();
}
c.set(false);
});
}
}
trait Callback: 'static {
fn call(self: Box<Self>);
}
impl<F: FnOnce() + 'static> Callback for F {
fn call(self: Box<Self>) {
(*self)()
}
}