Skip to main content

externally_driven_async_rt/time/
timeout.rs

1use core::{future::Future, pin::Pin, task::Poll};
2
3use crate::time::Sleep;
4
5/// A timeout future.
6#[must_use = "futures do nothing unless you `.await` or poll them"]
7pub struct Timeout<'ctx, F, const TIMERS: usize> {
8    future: F,
9    sleep: Sleep<'ctx, TIMERS>,
10}
11
12impl<'ctx, F, const TIMERS: usize> Timeout<'ctx, F, TIMERS> {
13    pub(crate) const fn new(future: F, sleep: Sleep<'ctx, TIMERS>) -> Self {
14        Self { future, sleep }
15    }
16}
17
18impl<F: Future, const TIMERS: usize> Future for Timeout<'_, F, TIMERS> {
19    type Output = Option<F::Output>;
20
21    fn poll(self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
22        // SAFETY: `future` is pinned structurally: `Timeout` never moves it, has no `Drop`, and is
23        // `Unpin` only when `F` is. `sleep` is not pinned structurally, which is fine as `Sleep` is
24        // `Unpin`.
25        let (future, sleep) = unsafe {
26            let this = self.get_unchecked_mut();
27            (Pin::new_unchecked(&mut this.future), &mut this.sleep)
28        };
29        if let Poll::Ready(output) = future.poll(cx) {
30            return Poll::Ready(Some(output));
31        }
32        Pin::new(sleep).poll(cx).map(|()| None)
33    }
34}
35
36impl<F, const TIMERS: usize> core::fmt::Debug for Timeout<'_, F, TIMERS> {
37    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
38        f.write_str("Timeout")
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use core::{
45        cell::RefCell,
46        future::{Future, pending},
47        pin::pin,
48        task::{Context, Poll, Waker},
49        time::Duration,
50    };
51
52    use crate::{
53        Selector,
54        testing::{EventLoopTestingExt, Log, TestLoop, TestStorage, socketpair, wait_readable},
55        time::{Instant, Sleep, Timeout, Timers},
56    };
57
58    fn registrations(event_loop: &TestLoop<Log>) -> usize {
59        event_loop.ctx().storage.io_waiters.count()
60    }
61
62    fn has_timers(event_loop: &TestLoop<Log>) -> bool {
63        event_loop.ctx().storage.timers.next_deadline().is_some()
64    }
65
66    #[test]
67    #[cfg_attr(miri, ignore)]
68    fn future_finishing_first_wins() {
69        let (rx, tx) = socketpair();
70        let mut selector = Selector::new().unwrap();
71        let mut state = RefCell::new(Log::default());
72        let mut event_loop = TestLoop::new(
73            {
74                static STORAGE: TestStorage = TestStorage::new();
75                &STORAGE
76            },
77            &mut selector,
78            &mut state,
79            async move |ctx| {
80                let result = ctx
81                    .timeout(Duration::from_secs(60), wait_readable(&ctx, &rx))
82                    .await;
83                ctx.dispatch(result.map_or(0, |()| 1));
84                pending::<()>().await;
85            },
86        )
87        .unwrap();
88        assert!(has_timers(&event_loop));
89        assert_eq!(registrations(&event_loop), 1);
90        event_loop.wake_by_writing(&tx);
91        assert_eq!(event_loop.drain_events_without_blocking(), Ok(()));
92        assert_eq!(event_loop.state_mut().events(), [1]);
93        assert!(!has_timers(&event_loop));
94        assert_eq!(registrations(&event_loop), 0);
95    }
96
97    #[test]
98    #[cfg_attr(miri, ignore)]
99    fn elapsing_drops_the_future() {
100        let (rx, _tx) = socketpair();
101        let mut selector = Selector::new().unwrap();
102        let mut state = RefCell::new(Log::default());
103        let mut event_loop = TestLoop::new(
104            {
105                static STORAGE: TestStorage = TestStorage::new();
106                &STORAGE
107            },
108            &mut selector,
109            &mut state,
110            async move |ctx| {
111                let result = ctx
112                    .timeout(Duration::from_millis(10), wait_readable(&ctx, &rx))
113                    .await;
114                ctx.dispatch(result.map_or(0, |()| 1));
115                pending::<()>().await;
116            },
117        )
118        .unwrap();
119        event_loop.run_until_events(1);
120        assert_eq!(event_loop.state_mut().events(), [0]);
121        assert!(!has_timers(&event_loop));
122        assert_eq!(registrations(&event_loop), 0);
123    }
124
125    #[test]
126    #[cfg_attr(miri, ignore)]
127    fn ready_future_beats_a_zero_timeout() {
128        let (rx, tx) = socketpair();
129        rustix::io::write(&tx, b"x").unwrap();
130        let mut selector = Selector::new().unwrap();
131        let mut state = RefCell::new(Log::default());
132        let mut event_loop = TestLoop::new(
133            {
134                static STORAGE: TestStorage = TestStorage::new();
135                &STORAGE
136            },
137            &mut selector,
138            &mut state,
139            async move |ctx| {
140                let result = ctx.timeout(Duration::ZERO, wait_readable(&ctx, &rx)).await;
141                ctx.dispatch(result.map_or(0, |()| 1));
142                pending::<()>().await;
143            },
144        )
145        .unwrap();
146        assert_eq!(event_loop.state_mut().events(), [1]);
147        assert!(!has_timers(&event_loop));
148    }
149
150    #[test]
151    fn ready_pinned_future_resolves_and_releases_the_timer() {
152        let timers = &Timers::<1>::new();
153        let mut cx = Context::from_waker(Waker::noop());
154        let sleep = Sleep::new(timers, Instant::now() + Duration::from_secs(60));
155        let mut timeout = pin!(Timeout::new(
156            async {
157                let value = 1;
158                let borrowed = &value;
159                core::future::ready(()).await;
160                *borrowed
161            },
162            sleep,
163        ));
164        assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Ready(Some(1)));
165        assert_eq!(timers.next_deadline(), None);
166    }
167
168    #[test]
169    fn pending_pinned_future_keeps_its_timer_until_dropped() {
170        let timers = &Timers::<1>::new();
171        let mut cx = Context::from_waker(Waker::noop());
172        let sleep = Sleep::new(timers, Instant::now() + Duration::from_secs(60));
173        {
174            let mut timeout = pin!(Timeout::new(
175                async {
176                    let value = 1;
177                    let borrowed = &value;
178                    pending::<()>().await;
179                    *borrowed
180                },
181                sleep,
182            ));
183            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
184            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
185            assert!(timers.next_deadline().is_some());
186        }
187        assert_eq!(timers.next_deadline(), None);
188    }
189}