Skip to content

Implement fast async API with asynchronous traits  #290

Open
@uselessgoddess

Description

@uselessgoddess

Implement async Doublets trait without dyn Future trait

Pin<Box<...>> from async_trait eats a lot of time, but it can be fixed

How to be

As you know, traits do not support non-dyn return -> impl Trait, but we can write:

trait ReturnImplTrait {
    type Impl;
    
    fn foo(&self) -> Self::Impl;
}

We also write [via #![feature(type_alias_impl_trait)] feature]:

impl ReturnImplTrait for () {
    type Impl = impl Display;

    fn foo(&self) -> Self::Impl {
        "it's really working"
    }
}

But

It's a wrong code:

trait ReturnImplTrait {
    type Impl;

    fn foo<T: Display>(t: T) -> Self::Impl;
}

impl ReturnImplTrait for () {
    type Impl = impl Display;

    fn foo<T: Display>(t: T) -> Self::Impl {
        t
    }
}

Also, not work

trait ReturnImplTrait {
    type Impl: Display;

    fn foo<T: Display>(t: T) -> Self::Impl;
}

impl ReturnImplTrait for () {
    type Impl = impl Display;

    fn foo<T: Display>(t: T) -> Self::Impl {
        t
    }
}

Hm… Use more features and magic!

Forward all generic params to trait-type (use #![feature(generic_associated_types)] feature)

Oh, Miracle

trait ReturnImplTrait {
    type Impl<T>;

    fn foo<T: Display>(t: T) -> Self::Impl<T>;
}

impl ReturnImplTrait for () {
    type Impl<T> = impl Display;

    fn foo<T: Display>(t: T) -> Self::Impl<T> {
        t
    }
}

Ok, use Future

trait AsyncSum {
    type SumFuture<T: Add<U>, U>: Future<Output = <T as Add<U>>::Output>;

    fn sum<T: Add<U>, U>(t: T, u: U) -> Self::SumFuture<T, U>;
}

impl AsyncSum for () {
    type SumFuture<T: Add<U>, U> = impl Future<Output = <T as Add<U>>::Output>;

    fn sum<T: Add<U>, U>(t: T, u: U) -> Self::SumFuture<T, U> {
        async { t.add(u) }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    RustThe most hype languageapi:RustThis affects the apiasync:RustUnblock your codefutures:RustWait better times

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions