Crate absurd_future

Crate absurd_future 

Source
Expand description

A future adapter that turns a future that never resolves (i.e., returns Infallible) into a future that can resolve to any type.

This is useful in scenarios where you have a task that runs forever (like a background service) but need to integrate it into an API that expects a specific return type, such as tokio::task::JoinSet.

The core of this crate is the AbsurdFuture struct and the convenient absurd_future function.

For a detailed explanation of the motivation behind this crate and the concept of uninhabited types in Rust async code, see the blog post: How to use Rust’s never type (!) to write cleaner async code.

§Example

use std::convert::Infallible;
use std::future;
use absurd_future::absurd_future;

// A future that never completes.
async fn task_that_never_returns() -> Infallible {
    loop {
        // In a real scenario, this might be `tokio::time::sleep` or another
        // future that never resolves. For this example, we'll just pend forever.
        future::pending::<()>().await;
    }
}

async fn main() {
    // We have a task that never returns, but we want to use it in a
    // context that expects a `Result<(), &str>`.
    let future = task_that_never_returns();

    // Wrap it with `absurd_future` to change its output type.
    let adapted_future: _ = absurd_future::<_, Result<(), &str>>(future);

    // This adapted future will now pend forever, just like the original,
    // but its type signature satisfies the requirement.
}

Structs§

AbsurdFuture
Turn a never-returning future into a future yielding any desired type.

Functions§

absurd_future
Wraps a future that never returns and gives it an arbitrary output type.