Skip to main content

externally_driven_async_rt/io/
frame_reader.rs

1use super::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(&mut self) -> Result<Option<[u8; N]>, FrameReaderError<R::Error>> {
39        while self.filled < N {
40            let Some(rest) = self.buf.get_mut(self.filled..) else {
41                unreachable!("filled is below N");
42            };
43            let len = match self.inner.read(rest).await {
44                Ok(0) if self.filled == 0 => return Ok(None),
45                Ok(0) => return Err(FrameReaderError::UnexpectedEof),
46                Ok(len) => len,
47                Err(err) => return Err(FrameReaderError::Io(err)),
48            };
49            let Some(filled) = self.filled.checked_add(len).filter(|&filled| filled <= N) else {
50                unreachable!("read() reported more read bytes than the buffer has");
51            };
52            self.filled = filled;
53        }
54        self.filled = 0;
55        Ok(Some(self.buf))
56    }
57}
58
59impl<R, const N: usize> FrameReader<R, N> {
60    /// Returns a mutable reference to the wrapped reader.
61    pub const fn get_mut(&mut self) -> &mut R {
62        &mut self.inner
63    }
64}
65
66/// An error returned from [`FrameReader::read_exact`].
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum FrameReaderError<E> {
69    /// Reading failed.
70    Io(E),
71    /// The stream was closed in the middle of the frame.
72    UnexpectedEof,
73}
74
75impl<E: core::fmt::Display> core::fmt::Display for FrameReaderError<E> {
76    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
77        match self {
78            Self::Io(err) => write!(f, "read failed: {err}"),
79            Self::UnexpectedEof => f.write_str("stream closed in the middle of the frame"),
80        }
81    }
82}
83
84impl<E: core::error::Error> core::error::Error for FrameReaderError<E> {}
85
86#[cfg(test)]
87mod tests {
88    use core::{
89        future::{Future, poll_fn},
90        pin::pin,
91        task::{Context, Poll, Waker},
92    };
93
94    use rustix::io::Errno;
95
96    use super::{AsyncRead, FrameReader, FrameReaderError};
97
98    struct Chunks {
99        chunks: &'static [&'static [u8]],
100        end: Option<rustix::io::Result<usize>>,
101    }
102
103    impl AsyncRead for Chunks {
104        type Error = Errno;
105
106        fn read<'a>(
107            &'a mut self,
108            buf: &'a mut [u8],
109        ) -> impl Future<Output = rustix::io::Result<usize>> {
110            poll_fn(move |_| {
111                let Some((chunk, rest)) = self.chunks.split_first() else {
112                    return self.end.map_or(Poll::Pending, Poll::Ready);
113                };
114                let len = buf.len().min(chunk.len());
115                buf[..len].copy_from_slice(&chunk[..len]);
116                self.chunks = rest;
117                Poll::Ready(Ok(len))
118            })
119        }
120    }
121
122    fn poll_once<F: Future>(future: F) -> Poll<F::Output> {
123        pin!(future).poll(&mut Context::from_waker(Waker::noop()))
124    }
125
126    #[test]
127    fn reads_consecutive_frames_from_partial_reads() {
128        let mut reader = FrameReader::<_, 5>::new(Chunks {
129            chunks: &[b"hel", b"lo", b"wor", b"ld"],
130            end: None,
131        });
132
133        assert_eq!(
134            poll_once(reader.read_exact()),
135            Poll::Ready(Ok(Some(*b"hello")))
136        );
137        assert_eq!(
138            poll_once(reader.read_exact()),
139            Poll::Ready(Ok(Some(*b"world")))
140        );
141    }
142
143    #[test]
144    fn resumes_a_cancelled_read() {
145        let mut reader = FrameReader::<_, 5>::new(Chunks {
146            chunks: &[b"he", b"l"],
147            end: None,
148        });
149
150        assert_eq!(poll_once(reader.read_exact()), Poll::Pending);
151
152        reader.inner.chunks = &[b"lo"];
153        assert_eq!(
154            poll_once(reader.read_exact()),
155            Poll::Ready(Ok(Some(*b"hello")))
156        );
157    }
158
159    #[test]
160    fn returns_none_when_the_stream_ends_between_frames() {
161        let mut reader = FrameReader::<_, 5>::new(Chunks {
162            chunks: &[b"hello"],
163            end: Some(Ok(0)),
164        });
165
166        assert_eq!(
167            poll_once(reader.read_exact()),
168            Poll::Ready(Ok(Some(*b"hello")))
169        );
170        assert_eq!(poll_once(reader.read_exact()), Poll::Ready(Ok(None)));
171    }
172
173    #[test]
174    fn fails_when_the_stream_ends_in_the_middle_of_a_frame() {
175        let mut reader = FrameReader::<_, 5>::new(Chunks {
176            chunks: &[b"hel"],
177            end: Some(Ok(0)),
178        });
179
180        assert_eq!(
181            poll_once(reader.read_exact()),
182            Poll::Ready(Err(FrameReaderError::UnexpectedEof))
183        );
184    }
185
186    #[test]
187    fn returns_syscall_errors() {
188        let mut reader = FrameReader::<_, 5>::new(Chunks {
189            chunks: &[],
190            end: Some(Err(Errno::CONNRESET)),
191        });
192
193        assert_eq!(
194            poll_once(reader.read_exact()),
195            Poll::Ready(Err(FrameReaderError::Io(Errno::CONNRESET)))
196        );
197    }
198}