use crate::fiber::scheduler;
use crate::fiber::inner::JoinHandle;
use std::cell::Cell;
use std::future::Future;
#[derive(Clone, Copy)]
enum State {
Empty,
Basic(*const scheduler::SchedulerPriv),
}
thread_local! {
static EXECUTOR: Cell<State> = Cell::new(State::Empty)
}
pub(crate) fn spawn<T>(future: T) -> JoinHandle<T::Output>
where
T: Future + Send + 'static,
T::Output: Send + 'static,
{
EXECUTOR.with(|current_executor| match current_executor.get() {
State::Basic(basic_scheduler_ptr) => {
let basic_scheduler = unsafe { &*basic_scheduler_ptr };
unsafe { basic_scheduler.spawn(future) }
}
State::Empty => {
drop(future);
panic!("must be called from the context of Tokio runtime configured with `basic_scheduler`");
}
})
}
pub(super) fn with_basic_scheduler<F, R>(
basic_scheduler: &scheduler::SchedulerPriv,
f: F,
) -> R
where
F: FnOnce() -> R,
{
with_state(
State::Basic(basic_scheduler as *const scheduler::SchedulerPriv),
f,
)
}
fn with_state<F, R>(state: State, f: F) -> R
where
F: FnOnce() -> R,
{
EXECUTOR.with(|cell| {
let was = cell.replace(State::Empty);
struct Reset<'a>(&'a Cell<State>, State);
impl Drop for Reset<'_> {
fn drop(&mut self) {
self.0.set(self.1);
}
}
let _reset = Reset(cell, was);
cell.set(state);
f()
})
}