use core::{
future::Future,
time::Duration,
};
pub trait AsyncTimeout<F>
where
F: Future + Send,
Self: Future<Output = Result<F::Output, Elapsed>> + Send
{
type Instant: super::Instant;
fn timeout(timeout: Duration, fut: F) -> Self
where
F: Future + Send,
Self: Future<Output = Result<F::Output, Elapsed>> + Send + Sized;
fn timeout_at(deadline: Self::Instant, fut: F) -> Self
where
F: Future + Send,
Self: Future<Output = Result<F::Output, Elapsed>> + Send + Sized;
}
pub trait AsyncLocalTimeout<F: Future>: Future<Output = Result<F::Output, Elapsed>> {
type Instant: super::Instant;
fn timeout_local(timeout: Duration, fut: F) -> Self
where
Self: Sized + Future<Output = Result<F::Output, Elapsed>>,
F: Future;
fn timeout_local_at(deadline: Self::Instant, fut: F) -> Self
where
Self: Sized + Future<Output = Result<F::Output, Elapsed>>,
F: Future;
}
#[derive(Debug, PartialEq, Eq)]
pub struct Elapsed;
impl core::fmt::Display for Elapsed {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "deadline has elapsed")
}
}
impl core::error::Error for Elapsed {}
#[cfg(feature = "std")]
impl From<Elapsed> for std::io::Error {
fn from(_: Elapsed) -> Self {
std::io::ErrorKind::TimedOut.into()
}
}
#[cfg(feature = "tokio")]
impl From<::tokio::time::error::Elapsed> for Elapsed {
fn from(_: ::tokio::time::error::Elapsed) -> Self {
Elapsed
}
}
#[test]
#[cfg(feature = "std")]
fn test_elapsed_error() {
assert_eq!(Elapsed.to_string(), "deadline has elapsed");
let _: std::io::Error = Elapsed.into();
}