use crate::krse::thread::{Park, CachedParkThread};
use std::pin::Pin;
use std::task::Context;
use std::task::Poll::Ready;
use std::cell::{Cell, RefCell};
use std::fmt;
use std::marker::PhantomData;
thread_local!(static ENTERED: Cell<bool> = Cell::new(false));
pub(crate) struct Enter {
_p: PhantomData<RefCell<()>>,
}
pub(crate) fn enter() -> Enter {
if let Some(enter) = try_enter() {
return enter;
}
panic!(
"Cannot start a runtime from within a runtime. This happens \
because a function (like `block_on`) attempted to block the \
current thread while the thread is being used to drive \
asynchronous tasks."
);
}
pub(crate) fn try_enter() -> Option<Enter> {
ENTERED.with(|c| {
if c.get() {
None
} else {
c.set(true);
Some(Enter { _p: PhantomData })
}
})
}
impl Enter {
pub(crate) fn block_on<F>(&mut self, mut f: F) -> F::Output
where
F: std::future::Future,
{
let mut park = CachedParkThread::new();
let waker = park.unpark().into_waker();
let mut cx = Context::from_waker(&waker);
let mut f = unsafe { Pin::new_unchecked(&mut f) };
loop {
if let Ready(v) = f.as_mut().poll(&mut cx) {
return v;
}
park.park().unwrap();
}
}
}
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());
c.set(false);
});
}
}