Skip to main content

externally_driven_async_rt/io/
frame_reader.rs

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