rust-utils 0.16.0

Various utility routines used in the rust programs I have written
Documentation
//! Utilities for dealing with futures and asynchronous Rust APIs

use std::{
    pin::Pin,
    future::Future
};
use tokio::runtime::{Handle, Runtime};
use futures::executor::block_on;

/// A future created from `Box::pin()` on an async code block.
///
/// Example:
/// ```
/// let future: BoxedFuture<()> = Box::pin(
///     /* async code here */
/// )
/// ```
pub type BoxedFuture<T> = Pin<Box<dyn Future<Output = T>>>;

/// Convenience function to run a future
/// until it returns a value
///
/// This is useful in synchronous contexts where the .await syntax normally can't
/// be used
pub fn exec_future<F: Future>(future: F) -> F::Output {
    if let Ok(handle) = Handle::try_current() {
        let guard = handle.enter();
        let val = block_on(future);
        drop(guard);
        val
    }
    else {
        let rt = Runtime::new().unwrap();
        let guard = rt.enter();
        let val = block_on(future);
        drop(guard);
        val
    }
}