tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
26.59k stars 2.45k forks source link

tokio::time::timeout should support std::future::IntoFuture #6665

Closed alexheretic closed 2 months ago

alexheretic commented 3 months ago

Tokio APIs don't currently support std::future::IntoFuture. In particular tokio::time::timeout & timeout_at.

Example: timeout

struct IntoFooture;

impl std::future::IntoFuture for IntoFooture {
    type Output = ();
    type IntoFuture = std::future::Ready<()>;

    fn into_future(self) -> Self::IntoFuture {
        std::future::ready(())
    }
}

fn foo() -> IntoFooture {
    IntoFooture
}

foo().await; // works

_ = tokio::time::timeout(Duration::from_secs(4), foo()).await; // !compile: `IntoFooture` is not a future

So currently the future must be explicitly converted here to use timeout.

_ = tokio::time::timeout(Duration::from_secs(4), foo().into_future()).await; // works

Solution: Support IntoFuture

If we updated the timeout method to:

pub fn timeout<F>(duration: Duration, future: F) -> Timeout<F::IntoFuture>
where
    F: std::future::IntoFuture,
{...}

The original example would work without the .into_future() explicit call.

MSRV

Note: This requires bumping the msrv to 1.64 as this version stabilised IntoFuture.