4 releases

0.2.0 Jan 4, 2021
0.1.2 Oct 23, 2020
0.1.1 Oct 19, 2020
0.1.0 Oct 15, 2020

#738 in #async

Download history 3588/week @ 2021-08-11 4543/week @ 2021-08-18 4768/week @ 2021-08-25 3136/week @ 2021-09-01 3917/week @ 2021-09-08 3699/week @ 2021-09-15 5007/week @ 2021-09-22 4721/week @ 2021-09-29 3776/week @ 2021-10-06 3945/week @ 2021-10-13 3925/week @ 2021-10-20 2961/week @ 2021-10-27 2171/week @ 2021-11-03 2562/week @ 2021-11-10 3330/week @ 2021-11-17 3211/week @ 2021-11-24

11,723 downloads per month
Used in less than 10 crates

MIT license

14KB
199 lines

Tokio Compat 0.2

tokio-compat-02 = "0.2"

This crate includes utilities around integrating Tokio with other runtimes by allowing the context to be attached to futures. This allows spawning futures on other executors while still using Tokio to drive them. This can be useful if you need to use a Tokio based library in an executor/runtime that does not provide a Tokio context.

Be aware that the .compat() region allows you to use both Tokio 0.2 and 1 features. It is not the case that you opt-out of Tokio 1 when you are inside a Tokio 0.2 compatibility region.

Basic usage:

use hyper::{Client, Uri};
use tokio_compat_02::FutureExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();

    // This will not panic because we are wrapping it in the
    // Tokio 0.2 context via the `FutureExt::compat` fn.
    client
        .get(Uri::from_static("http://tokio.rs"))
        .compat()
        .await?;

    Ok(())
}

Usage on async function:

use hyper::{Client, Uri};
use tokio_compat_02::FutureExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // By calling compat on the async function, everything inside it is able
    // to use Tokio 0.2 features.
    hyper_get().compat().await?;
    Ok(())
}

async fn hyper_get() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();

    // This will not panic because the `main` function wrapped it in the
    // Tokio 0.2 context.
    client
        .get(Uri::from_static("http://tokio.rs"))
        .await?;

    Ok(())
}

Be aware that the constructors of some type require being inside the context. For example, this includes TcpStream and delay_for.

use tokio_02::time::delay_for;
use tokio_compat_02::FutureExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let duration = std::time::Duration::from_secs(1);

    // Call the non-async constructor in the context.
    let time_future = async { delay_for(duration) }.compat().await;

    // Use the constructed `Delay`.
    time_future.compat().await;

    Ok(())
}

Of course the above would also work if the surrounding async function was called with .compat().

Dependencies

~2.5MB
~37K SLoC