Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: CI

on:
push:
branches:
- main
pull_request:
workflow_dispatch:

env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
CARGO_NET_RETRY: 10
RUST_BACKTRACE: 1
RUSTUP_MAX_RETRIES: 10
RUSTFLAGS: "-D warnings"

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}

jobs:
tests:
name: Tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- uses: taiki-e/install-action@v2
with:
tool: just@1.40.0
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.90.0
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
with:
prefix-key: "v1"
cache-workspace-crates: true
cache-on-failure: true
workspaces: |
.
- name: Compile
run: just cargo-compile
- name: Clippy
run: just cargo-clippy-check
- name: Rustfmt
run: just cargo-fmt-check
- name: Run tests
run: just test
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
/target-ra
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's this for?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This expands to target-rust-analyzer.

Basically I have this setting of rust-analyzer enabled: https://rust-analyzer.github.io/book/configuration.html?highlight=target#cargo.targetDir

Setting a different target directory for rust-analyzer prevents build conflicts and improves performance at the cost of more disk usage. This enables a smoother interaction with rust-analyzer when I have to manually run some cargo commands (which seems to be a lot for my workflow).

.envrc
79 changes: 79 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "absurd-future"
version = "0.1.0"
edition = "2021"
license = "MIT"
description = "A future adapter that turns a future that never resolves (returns Infallible) into a future that can resolve to any type."
repository = "https://github.com/user/absurd-future"
keywords = ["future", "async", "infallible", "never"]
categories = ["asynchronous"]

[dependencies]

[dev-dependencies]
tokio = { version = "1.48.0", features = ["rt", "time", "macros", "rt-multi-thread"] }
anyhow = "1.0.100"
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,18 @@
# absurd-future

[![crates.io](https://img.shields.io/crates/v/absurd-future.svg)](https://crates.io/crates/absurd-future)
[![docs.rs](https://docs.rs/absurd-future/badge.svg)](https://docs.rs/absurd-future)

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`.

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](https://academy.fpblock.com/blog/rust-never-type-async-code).

## Usage

For a complete, runnable example of how to use this crate with `tokio::task::JoinSet`, please see the example file: [`examples/tokio.rs`](./examples/tokio.rs).

## License

This project is licensed under the MIT license.
57 changes: 57 additions & 0 deletions examples/tokio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use absurd_future::absurd_future;
use anyhow::{bail, Result};
use std::{convert::Infallible, time::Duration};

use tokio::task::JoinSet;

#[tokio::main]
async fn main() -> Result<()> {
let _result = main_inner().await?;
Ok(())
}

async fn task_one() -> Infallible {
loop {
println!("Hello from task 1");
tokio::time::sleep(Duration::from_secs(1)).await;
}
}

async fn task_two() -> Result<Infallible> {
let mut counter = 1;
loop {
println!("Hello from task 2");
counter += 1;
tokio::time::sleep(Duration::from_secs(1)).await;
if counter >= 3 {
bail!("Counter is >= 3")
}
}
}

async fn main_inner() -> Result<Infallible> {
let mut join_set = JoinSet::new();

join_set.spawn(absurd_future(task_one()));
join_set.spawn(task_two());

match join_set.join_next().await {
Some(result) => match result {
Ok(res) => match res {
Ok(_res) => bail!("Impossible: Infallible witnessed!"),
Err(e) => {
join_set.abort_all();
bail!("Task exited with {e}")
}
},
Err(e) => {
join_set.abort_all();
bail!("Task exited with {e}")
}
},
None => {
join_set.abort_all();
bail!("No tasks found in task set")
}
}
}
23 changes: 23 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# List all recipes
default:
just --list --unsorted

# Run example
example-tokio:
cargo run --example tokio

# cargo compile
cargo-compile:
cargo test --workspace --no-run --locked

# Clippy check
cargo-clippy-check:
cargo clippy --no-deps --workspace --locked --tests --benches --examples -- -Dwarnings

# Rustfmt check
cargo-fmt-check:
cargo fmt --all --check

# Test
test:
-cargo run --example tokio
2 changes: 2 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[toolchain]
channel = "1.90.0"
21 changes: 21 additions & 0 deletions src/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 FP Block

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
106 changes: 106 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//! 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](https://academy.fpblock.com/blog/rust-never-type-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.
//! }
//! ```

use std::{
convert::Infallible,
future::Future,
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};

/// Turn a never-returning future into a future yielding any desired type.
///
/// This struct is created by the [`absurd_future`] function.
///
/// Useful for async tasks that logically don't complete but need to satisfy an
/// interface expecting a concrete output type. Because the inner future never
/// resolves, this future will also never resolve, so the output type `T` is
/// never actually produced.
#[must_use = "futures do nothing unless polled"]
pub struct AbsurdFuture<F, T> {
inner: Pin<Box<F>>,
_marker: PhantomData<fn() -> T>,
}

impl<F, T> AbsurdFuture<F, T> {
/// Creates a new `AbsurdFuture` that wraps the given future.
///
/// The inner future must have an output type of `Infallible`.
pub fn new(inner: F) -> Self {
Self {
inner: Box::pin(inner),
_marker: PhantomData,
}
}
}

impl<F, T> Future for AbsurdFuture<F, T>
where
F: Future<Output = Infallible>,
{
type Output = T;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let inner = self.get_mut().inner.as_mut();
match Future::poll(inner, cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(never) => match never {},
}
}
}

/// Wraps a future that never returns and gives it an arbitrary output type.
///
/// This function makes it easier to create an [`AbsurdFuture`].
///
/// # Type Parameters
///
/// - `F`: The type of the inner future, which must return `Infallible`.
/// - `T`: The desired output type for the wrapped future. This is often inferred.
pub fn absurd_future<F, T>(future: F) -> AbsurdFuture<F, T>
where
F: Future<Output = Infallible>,
{
AbsurdFuture::new(future)
}