Skip to main content

externally_driven_async_rt/io/
async_read_ext.rs

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