use std::{future::Future, io, pin::Pin, time::Duration};
#[cfg(feature = "smtp")]
use futures_io::{AsyncRead, AsyncWrite};
#[cfg(feature = "smtp")]
use std::{net::SocketAddr, time::Instant};
#[cfg(feature = "smtp")]
pub trait Io: AsyncRead + AsyncWrite + Send + Unpin {}
#[cfg(feature = "smtp")]
impl<T> Io for T where T: AsyncRead + AsyncWrite + Send + Unpin {}
#[cfg(feature = "smtp")]
pub type BoxIo = Box<dyn Io>;
#[cfg(feature = "smtp")]
pub type Connect<'a> = Pin<Box<dyn Future<Output = io::Result<BoxIo>> + Send + 'a>>;
#[cfg(feature = "smtp")]
pub trait Connector: Send + Sync {
fn connect(&self, address: SocketAddr, deadline: Instant) -> Connect<'_>;
}
#[cfg(feature = "smtp")]
pub type Upgrade<'a> = Pin<Box<dyn Future<Output = io::Result<BoxIo>> + Send + 'a>>;
#[cfg(feature = "smtp")]
pub trait TlsConnector: Send + Sync {
fn upgrade<'a>(&'a self, server_name: &'a str, stream: BoxIo) -> Upgrade<'a>;
}
pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
pub trait Timer: Send + Sync {
fn sleep(&self, duration: Duration) -> Sleep;
}
pub(crate) async fn timeout<T>(
timer: &dyn Timer,
duration: Duration,
operation: impl Future<Output = T>,
) -> io::Result<T> {
futures_lite::pin!(operation);
let sleep = timer.sleep(duration);
futures_lite::pin!(sleep);
futures_lite::future::race(async { Ok(operation.await) }, async {
sleep.await;
Err(io::Error::new(
io::ErrorKind::TimedOut,
"operation timed out",
))
})
.await
}