1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! Helper routines for the asynchronous functions

use std::future::Future;
use std::time::Duration;

/// Spawns a background thread using which ever asynchronous runtime the library is built with
pub fn spawn<T>(future: T)
where T: Future + Send + 'static, T::Output: Send + 'static,
{
    #[cfg(feature = "tokio")]
    if tokio::runtime::Handle::try_current().is_ok() {
        tokio::spawn(future);
    } else {
        std::thread::Builder::new()
            .spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                rt.block_on(future);
            })
            .expect("failed to spawn thread");
    }

    #[cfg(feature = "async-std")]
    std::thread::Builder::new()
        .spawn(move || {
            async_std::task::block_on(future);
        })
        .expect("failed to spawn thread");
}

/// Safely executing blocking code using which ever asynchronous runtime the library is built with
pub fn block_on<F>(mut task: F)
where F: FnMut() -> () + 'static + Send,
{
    #[cfg(feature = "tokio")]
    if tokio::runtime::Handle::try_current().is_ok() {
        tokio::task::spawn_blocking(move || {
            task();
        });
        return;
    }

    #[cfg(feature = "async-std")]
    if async_std::task::try_current().is_some() {
        std::thread::Builder::new()
            .spawn(task)
            .expect("failed to spawn thread");
        return;
    }

    task();
}

/// Executes a future with a specific timeout using which ever asynchronous runtime the library is built with
#[must_use = "this `Option` should be handled"]
pub async fn timeout<F>(duration: Duration, future: F) -> Option<F::Output>
where F: Future
{
    #[cfg(feature = "tokio")]
    return match tokio::time::timeout(duration, future).await {
        Ok(a) => Some(a),
        Err(_) => None
    };

    #[cfg(feature = "async-std")]
    return match async_std::future::timeout(duration, future).await {
        Ok(a) => Some(a),
        Err(_) => None
    };
}