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) 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        future::{Future, pending},
46        pin::pin,
47        task::{Context, Poll, Waker},
48        time::Duration,
49    };
50
51    use crate::{
52        Selector,
53        testing::{EventLoopTestingExt, Log, TestLoop, TestStorage, socketpair, wait_readable},
54        time::{Instant, Sleep, Timeout, Timers},
55    };
56
57    fn registrations(event_loop: &TestLoop<Log>) -> usize {
58        event_loop.storage().io_waiters().count()
59    }
60
61    fn has_timers(event_loop: &TestLoop<Log>) -> bool {
62        event_loop.storage().timers().next_deadline().is_some()
63    }
64
65    #[test]
66    #[cfg_attr(miri, ignore)]
67    fn future_finishing_first_wins() {
68        let (rx, tx) = socketpair();
69        let mut selector = Selector::new().unwrap();
70        let mut event_loop = TestLoop::new(
71            {
72                static STORAGE: TestStorage = TestStorage::new();
73                &STORAGE
74            },
75            &mut selector,
76            Log::default(),
77            async move |ctx| {
78                let result = ctx
79                    .timeout(Duration::from_secs(60), wait_readable(&ctx, &rx))
80                    .await;
81                ctx.dispatch(result.map_or(0, |()| 1));
82                pending::<()>().await;
83            },
84        )
85        .unwrap();
86        assert!(has_timers(&event_loop));
87        assert_eq!(registrations(&event_loop), 1);
88        event_loop.wake_by_writing(&tx);
89        assert_eq!(event_loop.drain_events_without_blocking(), Ok(()));
90        assert_eq!(event_loop.state_mut().events(), [1]);
91        assert!(!has_timers(&event_loop));
92        assert_eq!(registrations(&event_loop), 0);
93    }
94
95    #[test]
96    #[cfg_attr(miri, ignore)]
97    fn elapsing_drops_the_future() {
98        let (rx, _tx) = socketpair();
99        let mut selector = Selector::new().unwrap();
100        let mut event_loop = TestLoop::new(
101            {
102                static STORAGE: TestStorage = TestStorage::new();
103                &STORAGE
104            },
105            &mut selector,
106            Log::default(),
107            async move |ctx| {
108                let result = ctx
109                    .timeout(Duration::from_millis(10), wait_readable(&ctx, &rx))
110                    .await;
111                ctx.dispatch(result.map_or(0, |()| 1));
112                pending::<()>().await;
113            },
114        )
115        .unwrap();
116        event_loop.run_until_events(1);
117        assert_eq!(event_loop.state_mut().events(), [0]);
118        assert!(!has_timers(&event_loop));
119        assert_eq!(registrations(&event_loop), 0);
120    }
121
122    #[test]
123    #[cfg_attr(miri, ignore)]
124    fn ready_future_beats_a_zero_timeout() {
125        let (rx, tx) = socketpair();
126        rustix::io::write(&tx, b"x").unwrap();
127        let mut selector = Selector::new().unwrap();
128        let mut event_loop = TestLoop::new(
129            {
130                static STORAGE: TestStorage = TestStorage::new();
131                &STORAGE
132            },
133            &mut selector,
134            Log::default(),
135            async move |ctx| {
136                let result = ctx.timeout(Duration::ZERO, wait_readable(&ctx, &rx)).await;
137                ctx.dispatch(result.map_or(0, |()| 1));
138                pending::<()>().await;
139            },
140        )
141        .unwrap();
142        assert_eq!(event_loop.state_mut().events(), [1]);
143        assert!(!has_timers(&event_loop));
144    }
145
146    #[test]
147    fn ready_pinned_future_resolves_and_releases_the_timer() {
148        let timers = &Timers::<1>::new();
149        let mut cx = Context::from_waker(Waker::noop());
150        let sleep = Sleep::new(timers, Instant::now() + Duration::from_secs(60));
151        let mut timeout = pin!(Timeout::new(
152            async {
153                let value = 1;
154                let borrowed = &value;
155                core::future::ready(()).await;
156                *borrowed
157            },
158            sleep,
159        ));
160        assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Ready(Some(1)));
161        assert_eq!(timers.next_deadline(), None);
162    }
163
164    #[test]
165    fn pending_pinned_future_keeps_its_timer_until_dropped() {
166        let timers = &Timers::<1>::new();
167        let mut cx = Context::from_waker(Waker::noop());
168        let sleep = Sleep::new(timers, Instant::now() + Duration::from_secs(60));
169        {
170            let mut timeout = pin!(Timeout::new(
171                async {
172                    let value = 1;
173                    let borrowed = &value;
174                    pending::<()>().await;
175                    *borrowed
176                },
177                sleep,
178            ));
179            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
180            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
181            assert!(timers.next_deadline().is_some());
182        }
183        assert_eq!(timers.next_deadline(), None);
184    }
185}