Skip to main content

externally_driven_async_rt/io/
frame_reader.rs

1use crate::Context;
2
3use super::AsyncRead;
4
5/// Reads frames of exactly `N` bytes from an [`AsyncRead`].
6///
7/// A partially read frame is kept inside, so unlike [`AsyncReadExt::read_exact`](crate::io::AsyncReadExt::read_exact)
8/// reading a frame can be cancelled and resumed.
9#[must_use]
10pub struct FrameReader<R, const N: usize> {
11    inner: R,
12    buf: [u8; N],
13    filled: usize,
14}
15
16impl<R: AsyncRead, const N: usize> FrameReader<R, N> {
17    /// Wraps a given reader.
18    pub const fn new(inner: R) -> Self {
19        Self {
20            inner,
21            buf: [0; N],
22            filled: 0,
23        }
24    }
25
26    /// Reads the next frame.
27    ///
28    /// Returns `None` if the stream is closed before the first byte of the frame.
29    ///
30    /// # Errors
31    ///
32    /// Returns an error if:
33    ///
34    /// 1. reading fails
35    /// 2. or if the stream is closed in the middle of the frame.
36    ///
37    /// # Cancel safety
38    ///
39    /// This method is cancel safe.
40    pub async fn read_exact<
41        E: 'static,
42        const EVENTS: usize,
43        const TASKS: usize,
44        const TASK_SIZE: usize,
45        const ROOT_TASK_SIZE: usize,
46        const TIMERS: usize,
47        const FDS: usize,
48    >(
49        &mut self,
50        ctx: &Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
51    ) -> Result<Option<[u8; N]>, FrameReaderError<R::Error>> {
52        while self.filled < N {
53            let Some(rest) = self.buf.get_mut(self.filled..) else {
54                unreachable!("filled is below N");
55            };
56            let len = match self.inner.read(ctx, rest).await {
57                Ok(0) if self.filled == 0 => return Ok(None),
58                Ok(0) => return Err(FrameReaderError::UnexpectedEof),
59                Ok(len) => len,
60                Err(err) => return Err(FrameReaderError::Io(err)),
61            };
62            let Some(filled) = self.filled.checked_add(len).filter(|&filled| filled <= N) else {
63                unreachable!("read() reported more read bytes than the buffer has");
64            };
65            self.filled = filled;
66        }
67        self.filled = 0;
68        Ok(Some(self.buf))
69    }
70}
71
72impl<R, const N: usize> FrameReader<R, N> {
73    /// Returns a mutable reference to the wrapped reader.
74    pub const fn get_mut(&mut self) -> &mut R {
75        &mut self.inner
76    }
77}
78
79/// An error returned from [`FrameReader::read_exact`].
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum FrameReaderError<E> {
82    /// Reading failed.
83    Io(E),
84    /// The stream was closed in the middle of the frame.
85    UnexpectedEof,
86}
87
88impl<E: core::fmt::Display> core::fmt::Display for FrameReaderError<E> {
89    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
90        match self {
91            Self::Io(err) => write!(f, "read failed: {err}"),
92            Self::UnexpectedEof => f.write_str("stream closed in the middle of the frame"),
93        }
94    }
95}
96
97impl<E: core::error::Error> core::error::Error for FrameReaderError<E> {}
98
99#[cfg(test)]
100mod tests {
101    use core::{
102        future::{Future, poll_fn},
103        pin::pin,
104        task::{Context, Poll, Waker},
105    };
106
107    use rustix::io::Errno;
108
109    use super::{AsyncRead, FrameReader, FrameReaderError};
110
111    use crate::{LoopStorage, Selector};
112
113    type Storage = LoopStorage<(), 1, 1, 0, 0, 1, 1>;
114
115    struct Chunks {
116        chunks: &'static [&'static [u8]],
117        end: Option<rustix::io::Result<usize>>,
118    }
119
120    impl AsyncRead for Chunks {
121        type Error = Errno;
122
123        fn read<
124            'a,
125            E: 'static,
126            const EVENTS: usize,
127            const TASKS: usize,
128            const TASK_SIZE: usize,
129            const ROOT_TASK_SIZE: usize,
130            const TIMERS: usize,
131            const FDS: usize,
132        >(
133            &'a mut self,
134            _ctx: &'a crate::Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
135            buf: &'a mut [u8],
136        ) -> impl Future<Output = rustix::io::Result<usize>> {
137            poll_fn(move |_| {
138                let Some((chunk, rest)) = self.chunks.split_first() else {
139                    return self.end.map_or(Poll::Pending, Poll::Ready);
140                };
141                let len = buf.len().min(chunk.len());
142                buf[..len].copy_from_slice(&chunk[..len]);
143                self.chunks = rest;
144                Poll::Ready(Ok(len))
145            })
146        }
147    }
148
149    fn poll_once<F: Future>(future: F) -> Poll<F::Output> {
150        pin!(future).poll(&mut Context::from_waker(Waker::noop()))
151    }
152
153    #[test]
154    fn reads_consecutive_frames_from_partial_reads() {
155        static STORAGE: Storage = Storage::new();
156        let selector = Selector::new().unwrap();
157        let ctx = STORAGE.claim(&selector).unwrap().0;
158        let mut reader = FrameReader::<_, 5>::new(Chunks {
159            chunks: &[b"hel", b"lo", b"wor", b"ld"],
160            end: None,
161        });
162
163        assert_eq!(
164            poll_once(reader.read_exact(&ctx)),
165            Poll::Ready(Ok(Some(*b"hello")))
166        );
167        assert_eq!(
168            poll_once(reader.read_exact(&ctx)),
169            Poll::Ready(Ok(Some(*b"world")))
170        );
171    }
172
173    #[test]
174    fn resumes_a_cancelled_read() {
175        static STORAGE: Storage = Storage::new();
176        let selector = Selector::new().unwrap();
177        let ctx = STORAGE.claim(&selector).unwrap().0;
178        let mut reader = FrameReader::<_, 5>::new(Chunks {
179            chunks: &[b"he", b"l"],
180            end: None,
181        });
182
183        assert_eq!(poll_once(reader.read_exact(&ctx)), Poll::Pending);
184
185        reader.inner.chunks = &[b"lo"];
186        assert_eq!(
187            poll_once(reader.read_exact(&ctx)),
188            Poll::Ready(Ok(Some(*b"hello")))
189        );
190    }
191
192    #[test]
193    fn returns_none_when_the_stream_ends_between_frames() {
194        static STORAGE: Storage = Storage::new();
195        let selector = Selector::new().unwrap();
196        let ctx = STORAGE.claim(&selector).unwrap().0;
197        let mut reader = FrameReader::<_, 5>::new(Chunks {
198            chunks: &[b"hello"],
199            end: Some(Ok(0)),
200        });
201
202        assert_eq!(
203            poll_once(reader.read_exact(&ctx)),
204            Poll::Ready(Ok(Some(*b"hello")))
205        );
206        assert_eq!(poll_once(reader.read_exact(&ctx)), Poll::Ready(Ok(None)));
207    }
208
209    #[test]
210    fn fails_when_the_stream_ends_in_the_middle_of_a_frame() {
211        static STORAGE: Storage = Storage::new();
212        let selector = Selector::new().unwrap();
213        let ctx = STORAGE.claim(&selector).unwrap().0;
214        let mut reader = FrameReader::<_, 5>::new(Chunks {
215            chunks: &[b"hel"],
216            end: Some(Ok(0)),
217        });
218
219        assert_eq!(
220            poll_once(reader.read_exact(&ctx)),
221            Poll::Ready(Err(FrameReaderError::UnexpectedEof))
222        );
223    }
224
225    #[test]
226    fn returns_syscall_errors() {
227        static STORAGE: Storage = Storage::new();
228        let selector = Selector::new().unwrap();
229        let ctx = STORAGE.claim(&selector).unwrap().0;
230        let mut reader = FrameReader::<_, 5>::new(Chunks {
231            chunks: &[],
232            end: Some(Err(Errno::CONNRESET)),
233        });
234
235        assert_eq!(
236            poll_once(reader.read_exact(&ctx)),
237            Poll::Ready(Err(FrameReaderError::Io(Errno::CONNRESET)))
238        );
239    }
240}