pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
//! Runtime-neutral SMTP I/O extension points.

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};

/// An asynchronous byte stream accepted by Pata's SMTP engine.
#[cfg(feature = "smtp")]
pub trait Io: AsyncRead + AsyncWrite + Send + Unpin {}

#[cfg(feature = "smtp")]
impl<T> Io for T where T: AsyncRead + AsyncWrite + Send + Unpin {}

/// An owned runtime-neutral byte stream.
#[cfg(feature = "smtp")]
pub type BoxIo = Box<dyn Io>;

/// A boxed TCP connection future.
#[cfg(feature = "smtp")]
pub type Connect<'a> = Pin<Box<dyn Future<Output = io::Result<BoxIo>> + Send + 'a>>;

/// Establishes TCP connections to already-resolved destinations.
#[cfg(feature = "smtp")]
pub trait Connector: Send + Sync {
    /// Connects to one destination before the supplied deadline.
    fn connect(&self, address: SocketAddr, deadline: Instant) -> Connect<'_>;
}

/// A boxed authenticated TLS-upgrade future.
#[cfg(feature = "smtp")]
pub type Upgrade<'a> = Pin<Box<dyn Future<Output = io::Result<BoxIo>> + Send + 'a>>;

/// Upgrades an established SMTP stream using a DNS server name.
#[cfg(feature = "smtp")]
pub trait TlsConnector: Send + Sync {
    /// Performs a client-side TLS handshake and verifies the peer identity.
    fn upgrade<'a>(&'a self, server_name: &'a str, stream: BoxIo) -> Upgrade<'a>;
}

/// A boxed runtime sleep.
pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;

/// Supplies monotonic sleeps without selecting an executor.
pub trait Timer: Send + Sync {
    /// Sleeps for at least `duration`.
    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
}