Skip to main content

externally_driven_async_rt/io/
async_read_ext.rs

1use core::future::Future;
2
3use super::AsyncRead;
4
5/// Helper methods on top of [`AsyncRead`], implemented for every [`AsyncRead`].
6pub trait AsyncReadExt: AsyncRead {
7    /// Fills the whole given buffer, calling [`AsyncRead::read`] until it's done.
8    ///
9    /// # Errors
10    ///
11    /// Returns an error if:
12    ///
13    /// 1. reading fails
14    /// 2. or if the stream is closed before the buffer is filled.
15    ///
16    /// # Cancel safety
17    ///
18    /// This method is not cancel safe: an unknown number of bytes may already be read into `buf`.
19    fn read_exact<'a>(
20        &'a mut self,
21        mut buf: &'a mut [u8],
22    ) -> impl Future<Output = Result<(), ReadExactError<Self::Error>>> {
23        async move {
24            while !buf.is_empty() {
25                let len = match self.read(buf).await {
26                    Ok(0) => return Err(ReadExactError::UnexpectedEof),
27                    Ok(len) => len,
28                    Err(err) => return Err(ReadExactError::Io(err)),
29                };
30                let Some(rest) = core::mem::take(&mut buf).get_mut(len..) else {
31                    unreachable!("read() reported more read bytes than the buffer has");
32                };
33                buf = rest;
34            }
35            Ok(())
36        }
37    }
38}
39
40impl<T: AsyncRead + ?Sized> AsyncReadExt for T {}
41
42/// An error returned from [`AsyncReadExt::read_exact`].
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ReadExactError<E> {
45    /// Reading failed.
46    Io(E),
47    /// The stream was closed before the buffer was filled.
48    UnexpectedEof,
49}
50
51impl<E: core::fmt::Display> core::fmt::Display for ReadExactError<E> {
52    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
53        match self {
54            Self::Io(err) => write!(f, "read failed: {err}"),
55            Self::UnexpectedEof => f.write_str("stream closed before the buffer was filled"),
56        }
57    }
58}
59
60impl<E: core::error::Error> core::error::Error for ReadExactError<E> {}
61
62#[cfg(test)]
63mod tests {
64    use core::{
65        future::Future,
66        pin::pin,
67        task::{Context, Poll, Waker},
68    };
69
70    use rustix::io::Errno;
71
72    use super::{AsyncRead, AsyncReadExt, ReadExactError};
73
74    struct Scripted {
75        data: &'static [u8],
76        max_per_call: usize,
77        error: Option<Errno>,
78        yielding: bool,
79        calls: usize,
80    }
81
82    impl Scripted {
83        const fn new(data: &'static [u8], max_per_call: usize, error: Option<Errno>) -> Self {
84            Self {
85                data,
86                max_per_call,
87                error,
88                yielding: false,
89                calls: 0,
90            }
91        }
92
93        const fn yielding(mut self) -> Self {
94            self.yielding = true;
95            self
96        }
97
98        fn read_now(&mut self, buf: &mut [u8]) -> rustix::io::Result<usize> {
99            if let Some(errno) = self.error {
100                return Err(errno);
101            }
102            let len = buf.len().min(self.max_per_call).min(self.data.len());
103            buf[..len].copy_from_slice(&self.data[..len]);
104            self.data = &self.data[len..];
105            Ok(len)
106        }
107    }
108
109    impl AsyncRead for Scripted {
110        type Error = Errno;
111
112        fn read<'a>(
113            &'a mut self,
114            buf: &'a mut [u8],
115        ) -> impl Future<Output = rustix::io::Result<usize>> {
116            self.calls += 1;
117            let mut pending = self.yielding;
118            core::future::poll_fn(move |cx| {
119                if pending {
120                    pending = false;
121                    cx.waker().wake_by_ref();
122                    return Poll::Pending;
123                }
124                Poll::Ready(self.read_now(buf))
125            })
126        }
127    }
128
129    fn read_exact(
130        reader: &mut Scripted,
131        buf: &mut [u8],
132    ) -> Poll<Result<(), ReadExactError<Errno>>> {
133        let mut cx = Context::from_waker(Waker::noop());
134        pin!(reader.read_exact(buf)).poll(&mut cx)
135    }
136
137    #[test]
138    fn read_exact_retries_partial_reads() {
139        let mut reader = Scripted::new(b"hello world!", 3, None);
140        let mut buf = [0; 11];
141        assert_eq!(read_exact(&mut reader, &mut buf), Poll::Ready(Ok(())));
142        assert_eq!(&buf, b"hello world");
143        assert_eq!(reader.calls, 4);
144        assert_eq!(reader.data, b"!");
145    }
146
147    #[test]
148    fn read_exact_into_nothing_never_reads() {
149        let mut reader = Scripted::new(b"hello", 3, None);
150        assert_eq!(read_exact(&mut reader, &mut []), Poll::Ready(Ok(())));
151        assert_eq!(reader.calls, 0);
152    }
153
154    #[test]
155    fn read_exact_fails_when_the_stream_ends_early() {
156        let mut reader = Scripted::new(b"hel", 2, None);
157        let mut buf = [0; 5];
158        assert_eq!(
159            read_exact(&mut reader, &mut buf),
160            Poll::Ready(Err(ReadExactError::UnexpectedEof))
161        );
162        assert_eq!(&buf[..3], b"hel");
163        assert_eq!(reader.calls, 3);
164    }
165
166    #[test]
167    fn read_exact_returns_syscall_errors() {
168        let mut reader = Scripted::new(b"hello", 3, Some(Errno::CONNRESET));
169        let mut buf = [0; 5];
170        assert_eq!(
171            read_exact(&mut reader, &mut buf),
172            Poll::Ready(Err(ReadExactError::Io(Errno::CONNRESET)))
173        );
174        assert_eq!(reader.calls, 1);
175    }
176
177    #[test]
178    fn read_exact_resumes_after_a_pending_read() {
179        let mut reader = Scripted::new(b"hello world", 6, None).yielding();
180        let mut buf = [0; 11];
181        let mut cx = Context::from_waker(Waker::noop());
182        {
183            let mut read = pin!(reader.read_exact(&mut buf));
184            assert_eq!(read.as_mut().poll(&mut cx), Poll::Pending);
185            assert_eq!(read.as_mut().poll(&mut cx), Poll::Pending);
186            assert_eq!(read.as_mut().poll(&mut cx), Poll::Ready(Ok(())));
187        }
188        assert_eq!(&buf, b"hello world");
189        assert_eq!(reader.calls, 2);
190    }
191}