agner_utils/
async_yield.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5pub async fn async_yield() {
6    Yield(false).await
7}
8
9struct Yield(bool);
10
11impl Future for Yield {
12    type Output = ();
13    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
14        let flag = &mut self.as_mut().0;
15        if !*flag {
16            *flag = true;
17            cx.waker().wake_by_ref();
18            Poll::Pending
19        } else {
20            Poll::Ready(())
21        }
22    }
23}
24
25#[cfg(test)]
26mod tests {
27    use std::time::{Duration, Instant};
28
29    use crate::future_timeout_ext::FutureTimeoutExt;
30
31    #[tokio::test]
32    async fn timeout_working_properly() {
33        let t0 = Instant::now();
34        assert!(tokio::time::sleep(Duration::from_secs(3))
35            .timeout(Duration::from_secs(1))
36            .await
37            .is_err());
38        eprintln!("{:?}", t0.elapsed());
39    }
40
41    #[tokio::test]
42    async fn timeout_does_not_have_a_chance() {
43        let t0 = Instant::now();
44        assert!(async move {
45            for _i in 1..30 {
46                std::thread::sleep(Duration::from_millis(100))
47            }
48        }
49        .timeout(Duration::from_secs(1))
50        .await
51        .is_ok());
52        eprintln!("{:?}", t0.elapsed());
53    }
54
55    #[tokio::test]
56    async fn timeout_works_again() {
57        let t0 = Instant::now();
58        assert!(async move {
59            for _i in 1..30 {
60                std::thread::sleep(Duration::from_millis(100));
61                crate::async_yield::async_yield().await
62            }
63        }
64        .timeout(Duration::from_secs(1))
65        .await
66        .is_err());
67        eprintln!("{:?}", t0.elapsed());
68    }
69}