async_sleep/
impl_async_io.rs1use alloc::boxed::Box;
2use core::time::Duration;
3
4pub use async_io::{Timer, Timer as AsyncIoTimer};
5use futures_util::FutureExt as _;
6
7use crate::{Sleepble, SleepbleWaitBoxFuture};
8
9impl Sleepble for Timer {
11 fn sleep(dur: Duration) -> Self {
12 Self::after(dur)
13 }
14
15 fn wait(self) -> SleepbleWaitBoxFuture {
16 Box::pin(self.map(|_| ()))
17 }
18}
19
20#[cfg(test)]
21mod tests {
22 #[allow(unused_imports)]
23 use super::*;
24
25 #[cfg(feature = "std")]
26 #[tokio::test]
27 async fn test_sleep() {
28 #[cfg(feature = "std")]
29 let now = std::time::Instant::now();
30
31 crate::sleep::sleep::<Timer>(Duration::from_millis(100)).await;
32
33 #[cfg(feature = "std")]
34 {
35 let elapsed_dur = now.elapsed();
36 assert!(elapsed_dur.as_millis() >= 100 && elapsed_dur.as_millis() <= 105);
37 }
38 }
39
40 #[cfg(feature = "rw")]
41 #[cfg(test)]
42 mod rw_tests {
43 use core::time::Duration;
44 use std::{
45 io::ErrorKind as IoErrorKind,
46 net::{TcpListener, TcpStream},
47 time::Instant,
48 };
49
50 use async_io::Async;
51 use futures_lite::future::block_on;
52
53 use crate::{
54 impl_async_io::Timer,
55 rw::{AsyncReadWithTimeoutExt as _, AsyncWriteWithTimeoutExt as _},
56 };
57
58 #[test]
59 fn simple() -> Result<(), Box<dyn std::error::Error>> {
60 block_on(async {
61 let listener = TcpListener::bind("127.0.0.1:0")?;
62
63 let addr = listener.local_addr()?;
64
65 let tcp_stream_c = TcpStream::connect(addr)?;
66 let tcp_stream_s = listener
67 .incoming()
68 .next()
69 .expect("Get next incoming failed")?;
70
71 let mut tcp_stream_c = Async::<TcpStream>::new(tcp_stream_c)?;
72 let mut tcp_stream_s = Async::<TcpStream>::new(tcp_stream_s)?;
73
74 tcp_stream_s
75 .write_with_timeout::<Timer>(b"foo", Duration::from_secs(1))
76 .await?;
77
78 let mut buf = vec![0u8; 5];
79 let n = tcp_stream_c
80 .read_with_timeout::<Timer>(&mut buf, Duration::from_secs(1))
81 .await?;
82 assert_eq!(n, 3);
83 assert_eq!(buf, b"foo\0\0");
84
85 let instant = Instant::now();
86 let two_secs = Duration::from_secs(2);
87 let three_secs = Duration::from_secs(3);
88 let err = tcp_stream_c
89 .read_with_timeout::<Timer>(&mut buf, Duration::from_secs(2))
90 .await
91 .err()
92 .unwrap();
93 assert!(instant.elapsed() >= two_secs);
94 assert!(instant.elapsed() < three_secs);
95 assert_eq!(err.kind(), IoErrorKind::TimedOut);
96 assert_eq!(err.to_string(), "read timeout");
97
98 Ok(())
99 })
100 }
101 }
102}