Skip to main content

externally_driven_async_rt/io/
async_read_ext.rs

1use core::future::Future;
2
3use crate::{Context, State, io::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<
20        'a,
21        S: State,
22        const TASKS: usize,
23        const TASK_SIZE: usize,
24        const ROOT_TASK_SIZE: usize,
25        const TIMERS: usize,
26        const FDS: usize,
27    >(
28        &'a mut self,
29        ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
30        mut buf: &'a mut [u8],
31    ) -> impl Future<Output = Result<(), ReadExactError<Self::Error>>> {
32        async move {
33            while !buf.is_empty() {
34                let len = match self.read(ctx, buf).await {
35                    Ok(0) => return Err(ReadExactError::UnexpectedEof),
36                    Ok(len) => len,
37                    Err(err) => return Err(ReadExactError::Io(err)),
38                };
39                let Some(rest) = core::mem::take(&mut buf).get_mut(len..) else {
40                    unreachable!("read() reported more read bytes than the buffer has");
41                };
42                buf = rest;
43            }
44            Ok(())
45        }
46    }
47}
48
49impl<T: AsyncRead + ?Sized> AsyncReadExt for T {}
50
51/// An error returned from [`AsyncReadExt::read_exact`].
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum ReadExactError<E> {
54    /// Reading failed.
55    Io(E),
56    /// The stream was closed before the buffer was filled.
57    UnexpectedEof,
58}
59
60impl<E: core::fmt::Display> core::fmt::Display for ReadExactError<E> {
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        match self {
63            Self::Io(err) => write!(f, "read failed: {err}"),
64            Self::UnexpectedEof => f.write_str("stream closed before the buffer was filled"),
65        }
66    }
67}
68
69impl<E: core::error::Error> core::error::Error for ReadExactError<E> {}
70
71#[cfg(test)]
72mod tests {
73    use core::{
74        cell::RefCell,
75        future::{Future, pending, ready},
76        net::SocketAddr,
77        pin::pin,
78        task::{Context, Poll, Waker},
79    };
80
81    use rustix::{
82        io::Errno,
83        net::{AddressFamily, SocketType},
84    };
85
86    use crate::{
87        Selector, State,
88        io::{AsyncRead, AsyncReadExt, ReadExactError},
89        net::TcpStream,
90        testing::{
91            EventLoopTestingExt, Log, TestContext, TestLoop, TestStorage, is_readable, raw_accept,
92        },
93    };
94
95    struct Scripted {
96        data: &'static [u8],
97        max_per_call: usize,
98        error: Option<Errno>,
99        calls: usize,
100    }
101
102    impl Scripted {
103        const fn new(data: &'static [u8], max_per_call: usize, error: Option<Errno>) -> Self {
104            Self {
105                data,
106                max_per_call,
107                error,
108                calls: 0,
109            }
110        }
111    }
112
113    impl AsyncRead for Scripted {
114        type Error = Errno;
115
116        fn read<
117            'a,
118            S: State,
119            const TASKS: usize,
120            const TASK_SIZE: usize,
121            const ROOT_TASK_SIZE: usize,
122            const TIMERS: usize,
123            const FDS: usize,
124        >(
125            &'a mut self,
126            _ctx: &'a crate::Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
127            buf: &'a mut [u8],
128        ) -> impl Future<Output = rustix::io::Result<usize>> {
129            self.calls += 1;
130            if let Some(errno) = self.error {
131                return ready(Err(errno));
132            }
133            let len = buf.len().min(self.max_per_call).min(self.data.len());
134            buf[..len].copy_from_slice(&self.data[..len]);
135            self.data = &self.data[len..];
136            ready(Ok(len))
137        }
138    }
139
140    fn read_exact(
141        storage: &'static TestStorage,
142        reader: &mut Scripted,
143        buf: &mut [u8],
144    ) -> Poll<Result<(), ReadExactError<Errno>>> {
145        let selector = Selector::new().unwrap();
146        let state = RefCell::new(Log::default());
147        let ctx: TestContext<'_> = storage.claim(&selector, &state);
148        let mut cx = Context::from_waker(Waker::noop());
149        pin!(reader.read_exact(&ctx, buf)).poll(&mut cx)
150    }
151
152    #[test]
153    fn read_exact_retries_partial_reads() {
154        let mut reader = Scripted::new(b"hello world!", 3, None);
155        let mut buf = [0; 11];
156        assert_eq!(
157            read_exact(
158                {
159                    static STORAGE: TestStorage = TestStorage::new();
160                    &STORAGE
161                },
162                &mut reader,
163                &mut buf
164            ),
165            Poll::Ready(Ok(()))
166        );
167        assert_eq!(&buf, b"hello world");
168        assert_eq!(reader.calls, 4);
169        assert_eq!(reader.data, b"!");
170    }
171
172    #[test]
173    fn read_exact_into_nothing_never_reads() {
174        let mut reader = Scripted::new(b"hello", 3, None);
175        assert_eq!(
176            read_exact(
177                {
178                    static STORAGE: TestStorage = TestStorage::new();
179                    &STORAGE
180                },
181                &mut reader,
182                &mut []
183            ),
184            Poll::Ready(Ok(()))
185        );
186        assert_eq!(reader.calls, 0);
187    }
188
189    #[test]
190    fn read_exact_fails_when_the_stream_ends_early() {
191        let mut reader = Scripted::new(b"hel", 2, None);
192        let mut buf = [0; 5];
193        assert_eq!(
194            read_exact(
195                {
196                    static STORAGE: TestStorage = TestStorage::new();
197                    &STORAGE
198                },
199                &mut reader,
200                &mut buf
201            ),
202            Poll::Ready(Err(ReadExactError::UnexpectedEof))
203        );
204        assert_eq!(&buf[..3], b"hel");
205        assert_eq!(reader.calls, 3);
206    }
207
208    #[test]
209    fn read_exact_returns_syscall_errors() {
210        let mut reader = Scripted::new(b"hello", 3, Some(Errno::CONNRESET));
211        let mut buf = [0; 5];
212        assert_eq!(
213            read_exact(
214                {
215                    static STORAGE: TestStorage = TestStorage::new();
216                    &STORAGE
217                },
218                &mut reader,
219                &mut buf
220            ),
221            Poll::Ready(Err(ReadExactError::Io(Errno::CONNRESET)))
222        );
223        assert_eq!(reader.calls, 1);
224    }
225
226    #[test]
227    #[cfg_attr(miri, ignore)]
228    fn read_exact_waits_for_the_rest_from_a_socket() {
229        let listener = crate::testing::raw_socket(AddressFamily::INET, SocketType::STREAM);
230        let localhost = SocketAddr::from(([127, 0, 0, 1], 0));
231        rustix::net::bind(&listener, &localhost).unwrap();
232        rustix::net::listen(&listener, 1).unwrap();
233        let addr: SocketAddr = rustix::net::getsockname(&listener)
234            .unwrap()
235            .try_into()
236            .unwrap();
237
238        let mut selector = Selector::new().unwrap();
239        let mut state = RefCell::new(Log::default());
240        let mut event_loop = TestLoop::new(
241            {
242                static STORAGE: TestStorage = TestStorage::new();
243                &STORAGE
244            },
245            &mut selector,
246            &mut state,
247            async move |ctx| {
248                let mut stream = TcpStream::connect(&ctx, addr).await.unwrap();
249                ctx.dispatch(1);
250                let mut buf = [0; 11];
251                stream.read_exact(&ctx, &mut buf).await.unwrap();
252                assert_eq!(&buf, b"hello world");
253                ctx.dispatch(2);
254                pending::<()>().await;
255            },
256        )
257        .unwrap();
258
259        let peer = raw_accept(&listener);
260        event_loop.run_until_events(1);
261
262        rustix::io::write(&peer, b"hello ").unwrap();
263        assert!(is_readable(&event_loop, 1000));
264        assert_eq!(event_loop.drain_events_without_blocking(), Ok(()));
265        assert!(!is_readable(&event_loop, 0));
266        assert_eq!(event_loop.state_mut().events(), [1]);
267
268        rustix::io::write(&peer, b"world").unwrap();
269        event_loop.run_until_events(2);
270        assert_eq!(event_loop.state_mut().events(), [1, 2]);
271    }
272}