-
Notifications
You must be signed in to change notification settings - Fork 0
absurd-future crate refactor #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| /target | ||
| /target-ra | ||
| .envrc | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,18 @@ | ||
| # absurd-future | ||
|
|
||
| [](https://crates.io/crates/absurd-future) | ||
| [](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. | ||
psibi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| [toolchain] | ||
| channel = "1.90.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What's this for?
There was a problem hiding this comment.
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
targetdirectory forrust-analyzerprevents 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).