use super::AsyncRead;
#[must_use]
pub struct FrameReader<R, const N: usize> {
inner: R,
buf: [u8; N],
filled: usize,
}
impl<R: AsyncRead, const N: usize> FrameReader<R, N> {
pub const fn new(inner: R) -> Self {
Self {
inner,
buf: [0; N],
filled: 0,
}
}
pub async fn read_exact(&mut self) -> Result<Option<[u8; N]>, FrameReaderError<R::Error>> {
while self.filled < N {
let Some(rest) = self.buf.get_mut(self.filled..) else {
unreachable!("filled is below N");
};
let len = match self.inner.read(rest).await {
Ok(0) if self.filled == 0 => return Ok(None),
Ok(0) => return Err(FrameReaderError::UnexpectedEof),
Ok(len) => len,
Err(err) => return Err(FrameReaderError::Io(err)),
};
let Some(filled) = self.filled.checked_add(len).filter(|&filled| filled <= N) else {
unreachable!("read() reported more read bytes than the buffer has");
};
self.filled = filled;
}
self.filled = 0;
Ok(Some(self.buf))
}
}
impl<R, const N: usize> FrameReader<R, N> {
pub const fn get_mut(&mut self) -> &mut R {
&mut self.inner
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameReaderError<E> {
Io(E),
UnexpectedEof,
}
impl<E: core::fmt::Display> core::fmt::Display for FrameReaderError<E> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Io(err) => write!(f, "read failed: {err}"),
Self::UnexpectedEof => f.write_str("stream closed in the middle of the frame"),
}
}
}
impl<E: core::error::Error> core::error::Error for FrameReaderError<E> {}
#[cfg(test)]
mod tests {
use core::{
future::{Future, poll_fn},
pin::pin,
task::{Context, Poll, Waker},
};
use rustix::io::Errno;
use super::{AsyncRead, FrameReader, FrameReaderError};
struct Chunks {
chunks: &'static [&'static [u8]],
end: Option<rustix::io::Result<usize>>,
}
impl AsyncRead for Chunks {
type Error = Errno;
fn read<'a>(
&'a mut self,
buf: &'a mut [u8],
) -> impl Future<Output = rustix::io::Result<usize>> {
poll_fn(move |_| {
let Some((chunk, rest)) = self.chunks.split_first() else {
return self.end.map_or(Poll::Pending, Poll::Ready);
};
let len = buf.len().min(chunk.len());
buf[..len].copy_from_slice(&chunk[..len]);
self.chunks = rest;
Poll::Ready(Ok(len))
})
}
}
fn poll_once<F: Future>(future: F) -> Poll<F::Output> {
pin!(future).poll(&mut Context::from_waker(Waker::noop()))
}
#[test]
fn reads_consecutive_frames_from_partial_reads() {
let mut reader = FrameReader::<_, 5>::new(Chunks {
chunks: &[b"hel", b"lo", b"wor", b"ld"],
end: None,
});
assert_eq!(
poll_once(reader.read_exact()),
Poll::Ready(Ok(Some(*b"hello")))
);
assert_eq!(
poll_once(reader.read_exact()),
Poll::Ready(Ok(Some(*b"world")))
);
}
#[test]
fn resumes_a_cancelled_read() {
let mut reader = FrameReader::<_, 5>::new(Chunks {
chunks: &[b"he", b"l"],
end: None,
});
assert_eq!(poll_once(reader.read_exact()), Poll::Pending);
reader.inner.chunks = &[b"lo"];
assert_eq!(
poll_once(reader.read_exact()),
Poll::Ready(Ok(Some(*b"hello")))
);
}
#[test]
fn returns_none_when_the_stream_ends_between_frames() {
let mut reader = FrameReader::<_, 5>::new(Chunks {
chunks: &[b"hello"],
end: Some(Ok(0)),
});
assert_eq!(
poll_once(reader.read_exact()),
Poll::Ready(Ok(Some(*b"hello")))
);
assert_eq!(poll_once(reader.read_exact()), Poll::Ready(Ok(None)));
}
#[test]
fn fails_when_the_stream_ends_in_the_middle_of_a_frame() {
let mut reader = FrameReader::<_, 5>::new(Chunks {
chunks: &[b"hel"],
end: Some(Ok(0)),
});
assert_eq!(
poll_once(reader.read_exact()),
Poll::Ready(Err(FrameReaderError::UnexpectedEof))
);
}
#[test]
fn returns_syscall_errors() {
let mut reader = FrameReader::<_, 5>::new(Chunks {
chunks: &[],
end: Some(Err(Errno::CONNRESET)),
});
assert_eq!(
poll_once(reader.read_exact()),
Poll::Ready(Err(FrameReaderError::Io(Errno::CONNRESET)))
);
}
}