use std::future::Future;
use tokio::runtime::{Handle, Runtime};
pub(crate) struct RuntimeGuard {
_runtime: Option<Runtime>,
handle: Handle,
}
impl RuntimeGuard {
pub fn new() -> Result<Self, String> {
match Handle::try_current() {
Ok(handle) => Ok(Self {
_runtime: None,
handle,
}),
Err(_) => {
let rt = Runtime::new().map_err(|e| format!("Failed to create runtime: {e}"))?;
let handle = rt.handle().clone();
Ok(Self {
_runtime: Some(rt),
handle,
})
}
}
}
pub fn block_on<F: Future>(&self, future: F) -> F::Output {
if self._runtime.is_some() {
self.handle.block_on(future)
} else {
tokio::task::block_in_place(|| self.handle.block_on(future))
}
}
}