use crate::runtime::{blocking, context, io, time, Spawner};
use std::{error, fmt};
cfg_rt_core! {
use crate::task::JoinHandle;
use std::future::Future;
}
#[derive(Debug, Clone)]
pub struct Handle {
pub(super) spawner: Spawner,
pub(super) io_handle: io::Handle,
pub(super) time_handle: time::Handle,
pub(super) clock: time::Clock,
pub(super) blocking_spawner: blocking::Spawner,
}
impl Handle {
pub fn enter<F, R>(&self, f: F) -> R
where
F: FnOnce() -> R,
{
context::enter(self.clone(), f)
}
pub fn current() -> Self {
context::current().expect("not currently running on the Tokio runtime.")
}
pub fn try_current() -> Result<Self, TryCurrentError> {
context::current().ok_or(TryCurrentError(()))
}
}
cfg_rt_core! {
impl Handle {
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.spawner.spawn(future)
}
}
}
pub struct TryCurrentError(());
impl fmt::Debug for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TryCurrentError").finish()
}
}
impl fmt::Display for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("no tokio Runtime has been initialized")
}
}
impl error::Error for TryCurrentError {}