Debian Codegraph @

src/coroutines/read-exact.rs

raw symbols SCIP
1 //! I/O-free coroutine to read bytes into a buffer until it reaches a
2 //! given amount of bytes.
3
4 use std::mem;
5
6 use log::{debug, trace};
7 use thiserror::Error;
8
9 use crate::{coroutines::read::ReadStreamResult, io::StreamIo};
10
11 use super::read::{ReadStream, ReadStreamError};
12
13 /// Errors that can occur during the coroutine progression.
14 #[derive(Clone, Debug, Error)]
15 pub enum ReadStreamExactError {
16 /// The coroutine unexpectedly reached the End Of File.
17 #[error("Unexpected EOF, expected to read {0}/{1} more bytes")]
18 UnexpectedEof(usize, usize, Vec<u8>),
19
20 /// Error from the [`Read`] coroutine.
21 #[error(transparent)]
22 Read(#[from] ReadStreamError),
23 }
24
25 /// Output emitted after a coroutine finishes its progression.
26 #[derive(Clone, Debug)]
27 pub enum ReadStreamExactResult {
28 /// The coroutine has successfully terminated its progression.
29 Ok(Vec<u8>),
30
31 /// A stream I/O needs to be performed to make the coroutine
32 /// progress.
33 Io(StreamIo),
34
35 /// An error occured during the coroutine progression.
36 Err(ReadStreamExactError),
37 }
38
39 /// I/O-free coroutine to read bytes into a buffer until it reaches a
40 /// given amount of bytes.
41 #[derive(Debug)]
42 pub struct ReadStreamExact {
43 /// The inner read coroutine.
44 read: ReadStream,
45
46 /// The buffer containing the final read bytes.
47 buffer: Vec<u8>,
48
49 /// The exact amount of bytes to read.
50 max: usize,
51 }
52
53 impl ReadStreamExact {
54 /// Creates a new coroutine to read bytes using a buffer with
55 /// [`Read::DEFAULT_CAPACITY`] capacity.
56 ///
57 /// See [`Self::with_capacity`] for a custom buffer capacity.
58 pub fn new(max: usize) -> Self {
59 Self::with_capacity(ReadStream::DEFAULT_CAPACITY, max)
60 }
61
62 /// Creates a new coroutine to read bytes using a buffer with the
63 /// given capacity.
64 pub fn with_capacity(capacity: usize, max: usize) -> Self {
65 trace!("init coroutine to read exactly {max} bytes (capacity: {capacity})");
66 let read = ReadStream::with_capacity(capacity.min(max));
67 let buffer = Vec::with_capacity(max);
68 Self { read, buffer, max }
69 }
70
71 /// Extends the inner buffer with the given bytes slice.
72 pub fn extend(&mut self, bytes: impl IntoIterator<Item = u8>) {
73 self.buffer.extend(bytes);
74 }
75
76 /// Makes the coroutine progress.
77 pub fn resume(&mut self, mut arg: Option<StreamIo>) -> ReadStreamExactResult {
78 loop {
79 if self.buffer.len() >= self.max {
80 let buffer = mem::take(&mut self.buffer);
81 break ReadStreamExactResult::Ok(buffer);
82 }
83
84 let remaining = self.max - self.buffer.len();
85 debug!("{remaining} remaining bytes to read");
86
87 if remaining < self.read.capacity() {
88 self.read.truncate(remaining);
89 }
90
91 let output = match self.read.resume(arg.take()) {
92 ReadStreamResult::Ok(output) => output,
93 ReadStreamResult::Err(err) => break ReadStreamExactResult::Err(err.into()),
94 ReadStreamResult::Io(io) => break ReadStreamExactResult::Io(io),
95 ReadStreamResult::Eof => {
96 let buffer = mem::take(&mut self.buffer);
97 let err = ReadStreamExactError::UnexpectedEof(remaining, self.max, buffer);
98 break ReadStreamExactResult::Err(err);
99 }
100 };
101
102 self.buffer.extend(output.bytes());
103 self.read.replace(output.buffer);
104 }
105 }
106 }
107
108 #[cfg(test)]
109 mod tests {
110 use std::io::{BufReader, Read as _};
111
112 use crate::{
113 coroutines::read_exact::{ReadStreamExactError, ReadStreamExactResult},
114 io::{StreamIo, StreamOutput},
115 };
116
117 use super::ReadStreamExact;
118
119 #[test]
120 fn read_exact_smaller_capacity() {
121 let _ = env_logger::try_init();
122
123 let mut reader = BufReader::new("abcdef".as_bytes());
124
125 let mut read = ReadStreamExact::with_capacity(3, 4);
126 let mut arg = None;
127
128 let output = loop {
129 match read.resume(arg.take()) {
130 ReadStreamExactResult::Ok(output) => break output,
131 ReadStreamExactResult::Io(StreamIo::Read(Err(mut buffer))) => {
132 let bytes_count = reader.read(&mut buffer).unwrap();
133 let output = StreamOutput {
134 buffer,
135 bytes_count,
136 };
137 arg = Some(StreamIo::Read(Ok(output)))
138 }
139 other => unreachable!("Unexpected result: {other:?}"),
140 }
141 };
142
143 assert_eq!(output, b"abcd");
144
145 let mut remaining = vec![0; 4];
146 let bytes_count = reader.read(&mut remaining).unwrap();
147
148 assert_eq!(bytes_count, 2);
149 assert_eq!(&remaining[..bytes_count], b"ef");
150 }
151
152 #[test]
153 fn read_exact_bigger_capacity() {
154 let _ = env_logger::try_init();
155
156 let mut reader = BufReader::new("abcdef".as_bytes());
157
158 let mut read = ReadStreamExact::with_capacity(5, 4);
159 let mut arg = None;
160
161 let output = loop {
162 match read.resume(arg.take()) {
163 ReadStreamExactResult::Ok(output) => break output,
164 ReadStreamExactResult::Io(StreamIo::Read(Err(mut buffer))) => {
165 let bytes_count = reader.read(&mut buffer).unwrap();
166 let output = StreamOutput {
167 buffer,
168 bytes_count,
169 };
170 arg = Some(StreamIo::Read(Ok(output)))
171 }
172 other => unreachable!("Unexpected result: {other:?}"),
173 }
174 };
175
176 assert_eq!(output, b"abcd");
177
178 let mut remaining = vec![0; 4];
179 let bytes_count = reader.read(&mut remaining).unwrap();
180
181 assert_eq!(bytes_count, 2);
182 assert_eq!(&remaining[..bytes_count], b"ef");
183 }
184
185 #[test]
186 fn read_exact_0() {
187 let _ = env_logger::try_init();
188
189 let mut reader = BufReader::new("abcdef".as_bytes());
190
191 let mut read = ReadStreamExact::with_capacity(5, 0);
192 read.extend("123".as_bytes().to_vec());
193
194 let mut arg = None;
195
196 let output = loop {
197 match read.resume(arg.take()) {
198 ReadStreamExactResult::Ok(output) => break output,
199 ReadStreamExactResult::Io(StreamIo::Read(Err(mut buffer))) => {
200 let bytes_count = reader.read(&mut buffer).unwrap();
201 let output = StreamOutput {
202 buffer,
203 bytes_count,
204 };
205 arg = Some(StreamIo::Read(Ok(output)))
206 }
207 other => unreachable!("Unexpected result: {other:?}"),
208 }
209 };
210
211 assert_eq!(output, b"123");
212 }
213
214 #[test]
215 fn read_eof() {
216 let _ = env_logger::try_init();
217
218 let mut reader = BufReader::new("abcdef".as_bytes());
219
220 let mut read = ReadStreamExact::new(8);
221 let mut arg = None;
222
223 loop {
224 match read.resume(arg.take()) {
225 ReadStreamExactResult::Err(ReadStreamExactError::UnexpectedEof(2, 8, output)) => {
226 break assert_eq!(output, b"abcdef");
227 }
228 ReadStreamExactResult::Io(StreamIo::Read(Err(mut buffer))) => {
229 let bytes_count = reader.read(&mut buffer).unwrap();
230 let output = StreamOutput {
231 buffer,
232 bytes_count,
233 };
234 arg = Some(StreamIo::Read(Ok(output)))
235 }
236 other => unreachable!("Unexpected result: {other:?}"),
237 }
238 }
239 }
240 }