monocoque_core/
timeout.rs1use compio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
6use compio::time::timeout;
7use std::io;
8use std::time::Duration;
9
10pub async fn read_exact_with_timeout<S, B>(
14 stream: &mut S,
15 buf: B,
16 duration: Option<Duration>,
17) -> io::Result<compio::buf::BufResult<(), B>>
18where
19 S: AsyncRead + Unpin,
20 B: compio::buf::IoBufMut,
21{
22 match duration {
23 None => {
24 Ok(stream.read_exact(buf).await)
26 }
27 Some(d) if d.is_zero() => {
28 Err(io::Error::new(
30 io::ErrorKind::WouldBlock,
31 "Non-blocking mode not yet implemented",
32 ))
33 }
34 Some(d) => {
35 match timeout(d, stream.read_exact(buf)).await {
37 Ok(result) => Ok(result),
38 Err(_elapsed) => Err(io::Error::new(
39 io::ErrorKind::TimedOut,
40 "Read operation timed out",
41 )),
42 }
43 }
44 }
45}
46
47pub async fn write_all_with_timeout<S, B>(
51 stream: &mut S,
52 buf: B,
53 duration: Option<Duration>,
54) -> io::Result<compio::buf::BufResult<(), B>>
55where
56 S: AsyncWrite + Unpin,
57 B: compio::buf::IoBuf,
58{
59 match duration {
60 None => {
61 Ok(stream.write_all(buf).await)
63 }
64 Some(d) if d.is_zero() => {
65 Err(io::Error::new(
67 io::ErrorKind::WouldBlock,
68 "Non-blocking mode not yet implemented",
69 ))
70 }
71 Some(d) => {
72 match timeout(d, stream.write_all(buf)).await {
74 Ok(result) => Ok(result),
75 Err(_elapsed) => Err(io::Error::new(
76 io::ErrorKind::TimedOut,
77 "Write operation timed out",
78 )),
79 }
80 }
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
92 fn test_timeout_types() {
93 let _infinite: Option<Duration> = None;
95 let _nonblocking = Some(Duration::ZERO);
96 let _timed = Some(Duration::from_secs(5));
97 }
98}