mysql_connector/connection/
timeout.rs

1use std::{
2    future::Future,
3    io,
4    pin::Pin,
5    task::{Context, Poll},
6    time::Duration,
7};
8
9pub type TimeoutFuture = Pin<Box<dyn Future<Output = ()>>>;
10
11#[must_use = "futures do nothing unless you `.await` or poll them"]
12pub struct Timeout<F: Future> {
13    future: Pin<Box<F>>,
14    delay: TimeoutFuture,
15}
16
17impl<F: Future> Timeout<F> {
18    pub fn new(future: F, sleep: &dyn Fn(Duration) -> TimeoutFuture, timeout: Duration) -> Self {
19        Self {
20            future: Box::pin(future),
21            delay: sleep(timeout),
22        }
23    }
24}
25
26impl<F: Future> Future for Timeout<F> {
27    type Output = Result<F::Output, io::Error>;
28
29    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
30        let this = self.get_mut();
31
32        if let Poll::Ready(x) = this.future.as_mut().poll(cx) {
33            return Poll::Ready(Ok(x));
34        }
35
36        match this.delay.as_mut().poll(cx) {
37            Poll::Ready(_) => Poll::Ready(Err(io::ErrorKind::TimedOut.into())),
38            Poll::Pending => Poll::Pending,
39        }
40    }
41}