1use std::io::{self, ErrorKind, Read};
21use std::vec;
22use std::vec::Vec;
23
24use crate::{CrcCheck, Decoder, Error};
25
26pub const DEFAULT_CAPACITY: usize = 64 * 1024;
28
29#[derive(Debug)]
31pub enum ReadError {
32 Io(io::Error),
35 Frame(Error),
38}
39
40impl core::fmt::Display for ReadError {
41 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42 match self {
43 Self::Io(e) => write!(f, "read failed: {e}"),
44 Self::Frame(e) => write!(f, "bad frame: {e}"),
45 }
46 }
47}
48
49impl std::error::Error for ReadError {
50 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51 match self {
52 Self::Io(e) => Some(e),
53 Self::Frame(e) => Some(e),
54 }
55 }
56}
57
58impl From<io::Error> for ReadError {
59 fn from(e: io::Error) -> Self {
60 Self::Io(e)
61 }
62}
63
64impl From<Error> for ReadError {
65 fn from(e: Error) -> Self {
66 Self::Frame(e)
67 }
68}
69
70#[derive(Debug)] pub struct FrameReader<R> {
80 inner: R,
81 decoder: Decoder<Vec<u8>>,
82 chunk: [u8; 256],
83 pos: usize,
84 len: usize,
85}
86
87impl<R: Read> FrameReader<R> {
88 pub fn new(inner: R) -> Self {
90 Self::with_capacity(inner, DEFAULT_CAPACITY)
91 }
92
93 pub fn with_capacity(inner: R, capacity: usize) -> Self {
96 Self { inner, decoder: Decoder::new(vec![0; capacity]), chunk: [0; 256], pos: 0, len: 0 }
97 }
98
99 #[must_use]
101 pub fn with_crc_check(mut self, check: CrcCheck) -> Self {
102 self.decoder = self.decoder.with_crc_check(check);
103 self
104 }
105
106 pub fn get_ref(&self) -> &R {
108 &self.inner
109 }
110
111 pub fn get_mut(&mut self) -> &mut R {
113 &mut self.inner
114 }
115
116 pub fn into_inner(self) -> R {
118 self.inner
119 }
120}
121
122impl<R: Read> Iterator for FrameReader<R> {
123 type Item = Result<Vec<u8>, ReadError>;
124
125 fn next(&mut self) -> Option<Self::Item> {
126 loop {
127 while self.pos < self.len {
128 let byte = self.chunk.get(self.pos).copied().unwrap_or(0);
129 self.pos += 1;
130 match self.decoder.push(byte) {
131 Ok(Some(frame)) => return Some(Ok(frame.to_vec())),
132 Ok(None) => {}
133 Err(e) => return Some(Err(ReadError::Frame(e))),
134 }
135 }
136 match self.inner.read(&mut self.chunk) {
137 Ok(0) => return None,
138 Ok(n) => {
139 self.pos = 0;
140 self.len = n.min(self.chunk.len());
141 }
142 Err(e) if e.kind() == ErrorKind::Interrupted => {}
143 Err(e) => return Some(Err(ReadError::Io(e))),
144 }
145 }
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::encode_frame;
153
154 fn frame(payload: &[u8]) -> Vec<u8> {
155 let mut out = vec![0u8; payload.len() * 2 + 32];
156 let n = encode_frame(payload, &mut out).unwrap();
157 out.truncate(n);
158 out
159 }
160
161 #[test]
162 fn two_frames_and_noise_then_end() {
163 let mut stream = vec![0x00, 0x42];
164 stream.extend(frame(b"one!"));
165 stream.extend([0x1B, 0x1B, 0x07]);
166 stream.extend(frame(b"two"));
167 let got: Vec<_> = FrameReader::new(stream.as_slice()).map(Result::unwrap).collect();
168 assert_eq!(got, [b"one!".to_vec(), b"two".to_vec()]);
169 }
170
171 #[test]
173 fn an_oversized_frame_is_an_error_then_reading_continues() {
174 let mut stream = frame(&[7; 200]);
175 stream.extend(frame(&[8; 40]));
176 let mut r = FrameReader::with_capacity(stream.as_slice(), 64);
177 assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::BufferFull)))));
178 assert_eq!(r.next().unwrap().unwrap(), [8; 40]);
179 assert!(r.next().is_none());
180 }
181
182 struct Flaky<'a> {
184 error: Option<ErrorKind>,
185 data: &'a [u8],
186 }
187
188 impl Read for Flaky<'_> {
189 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
190 if let Some(kind) = self.error.take() {
191 return Err(kind.into());
192 }
193 self.data.read(buf)
194 }
195 }
196
197 #[test]
199 fn a_timeout_is_reported_and_the_next_call_continues() {
200 let data = frame(b"late");
201 let mut r = FrameReader::new(Flaky { error: Some(ErrorKind::TimedOut), data: &data });
202 assert!(matches!(r.next(), Some(Err(ReadError::Io(e))) if e.kind() == ErrorKind::TimedOut));
203 assert_eq!(r.next().unwrap().unwrap(), b"late");
204 }
205
206 #[test]
208 fn interrupted_is_retried_silently() {
209 let data = frame(b"ok");
210 let mut r = FrameReader::new(Flaky { error: Some(ErrorKind::Interrupted), data: &data });
211 assert_eq!(r.next().unwrap().unwrap(), b"ok");
212 }
213
214 #[test]
215 fn a_damaged_frame_is_a_frame_error_not_an_io_error() {
216 let mut data = frame(b"abcd");
217 data[9] ^= 1;
218 let mut r = FrameReader::new(data.as_slice());
219 assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::FrameCrc { .. })))));
220 }
221
222 #[test]
223 fn the_default_capacity_takes_large_frames() {
224 assert_eq!(DEFAULT_CAPACITY, 65_536);
225 let big = frame(&[7; 2000]);
226 assert_eq!(FrameReader::new(big.as_slice()).next().unwrap().unwrap(), [7; 2000]);
227 }
228
229 #[test]
230 fn read_errors_display_and_chain() {
231 use std::error::Error as _;
232 use std::string::ToString;
233 let frame_error = ReadError::from(Error::BufferFull);
234 assert_eq!(frame_error.to_string(), "bad frame: frame larger than the decoder buffer");
235 assert_eq!(frame_error.source().unwrap().to_string(), "frame larger than the decoder buffer");
236 let io_error = ReadError::from(io::Error::from(ErrorKind::TimedOut));
237 assert!(io_error.to_string().starts_with("read failed: "));
238 assert!(io_error.source().is_some());
239 }
240
241 #[test]
242 fn a_damaged_frame_is_reported_once() {
243 let mut data = frame(b"abcd");
244 data[9] ^= 1;
245 let mut r = FrameReader::new(data.as_slice());
246 assert!(matches!(r.next(), Some(Err(ReadError::Frame(Error::FrameCrc { .. })))));
247 }
248}