async_rs/util/
tokio.rs

1use std::{future::Future, io};
2use tokio::runtime::Handle;
3
4/// Check whether we're in a tokio context or not
5pub fn inside_tokio() -> bool {
6    Handle::try_current().is_ok()
7}
8
9/// Block on the given future in a tokio context, creating a new one if required
10pub fn block_on_tokio<T>(fut: impl Future<Output = io::Result<T>>) -> io::Result<T> {
11    if let Ok(handle) = Handle::try_current() {
12        handle.block_on(fut)
13    } else {
14        tokio::runtime::Runtime::new()?.block_on(fut)
15    }
16}