rust_utils/
futures.rs

1//! Utilities for dealing with futures and asynchronous Rust APIs
2
3use std::{
4    pin::Pin,
5    future::Future
6};
7use tokio::runtime::{Handle, Runtime};
8use futures::executor::block_on;
9
10/// A future created from `Box::pin()` on an async code block.
11///
12/// Example:
13/// ```
14/// let future: BoxedFuture<()> = Box::pin(
15///     /* async code here */
16/// )
17/// ```
18pub type BoxedFuture<T> = Pin<Box<dyn Future<Output = T>>>;
19
20/// Convenience function to run a future
21/// until it returns a value
22///
23/// This is useful in synchronous contexts where the .await syntax normally can't
24/// be used
25pub fn exec_future<F: Future>(future: F) -> F::Output {
26    if let Ok(handle) = Handle::try_current() {
27        let guard = handle.enter();
28        let val = block_on(future);
29        drop(guard);
30        val
31    }
32    else {
33        let rt = Runtime::new().unwrap();
34        let guard = rt.enter();
35        let val = block_on(future);
36        drop(guard);
37        val
38    }
39}