dtolnay / async-trait

Type erasure for async trait methods
Apache License 2.0
1.81k stars 84 forks source link

Option to allow 'async fns' to return 'impl Future' instead of 'Box<dyn Future>' #189

Closed wvwwvwwv closed 2 years ago

wvwwvwwv commented 2 years ago

Hi,

First of all, thanks a lot for your great code that has helped us (some developers at work, SAP) a lot. The background of this PR is, we extensively use GAT, generics, and asynchronous functions all over the code base for our project. However, it has been a pain in the a** to manually specify Future types in a trait to emulate async fn, and one of the developers came up with an idea of writing our own macros that would convert #[x]async fn in a trait into type X = impl Future; fn -> X. The first attempt was half-successful that it only covered few cases. So, we decided to shamelessly use your code as a basis to achieve what we want! => The goal is, write a set of macros that automatically generate GATs in a trait for some performance-critical functions where heap-allocation is not an option. => The new macro #[static_future] makes it possible to do so; instead of boxing a future, an impl Future<Outut = Ret> is returned by implicitly adding GATs for subjected async methods.

#[async_trait]
pub trait A {
    #[static_future]
    async fn(&self) -> usize;
}

#[async_trait]
impl A for () {
    #[static_future]
    async fn(&self) -> usize {
        11
    }
}

The generated code for async fn(&self) -> usize returns an impl Future<Output = usize> + 'async_trait.

The current state of the change has some limitations, such as, it requires the user to explicitly activate certain unstable features including GAT, #[static_future] doesn't work with a method having a default implementation. However, it turns out that the coverage is quite good that it can already be applied to some performance-critical traits in our code base.

That said, it'd be really appreciated if you could point out anything inappropriate in the interface and code, or it's even OK for you to say "it is absolutely unacceptable".

Thanks and best regards, wvwwvwwv

wvwwvwwv commented 2 years ago

@dtolnay Can you please review this PR?