Debian Codegraph @

src/coroutines/read.rs

raw symbols SCIP
1 //! I/O-free coroutine to read bytes into a buffer.
2
3 use std::mem;
4
5 use log::{debug, trace};
6 use thiserror::Error;
7
8 use crate::io::{StreamIo, StreamOutput};
9
10 /// Errors that can occur during the coroutine progression.
11 #[derive(Clone, Debug, Error)]
12 pub enum ReadStreamError {
13 /// The coroutine received an invalid argument.
14 ///
15 /// Occurs when the coroutine receives an I/O response from
16 /// another coroutine, which should not happen if the runtime maps
17 /// correctly the arguments.
18 #[error("Invalid argument: expected {0}, got {1:?}")]
19 InvalidArgument(&'static str, StreamIo),
20 }
21
22 /// Output emitted after a coroutine finishes its progression.
23 #[derive(Clone, Debug)]
24 pub enum ReadStreamResult {
25 /// The coroutine has successfully terminated its progression.
26 Ok(StreamOutput),
27
28 /// A stream I/O needs to be performed to make the coroutine
29 /// progress.
30 Io(StreamIo),
31
32 /// The coroutine reached the End Of File.
33 ///
34 /// Only the consumer can determine if its an error or not.
35 Eof,
36
37 /// An error occured during the coroutine progression.
38 Err(ReadStreamError),
39 }
40
41 /// I/O-free coroutine to read bytes into a buffer.
42 #[derive(Debug)]
43 pub struct ReadStream {
44 buffer: Vec<u8>,
45 }
46
47 impl ReadStream {
48 /// The default read buffer capacity.
49 pub const DEFAULT_CAPACITY: usize = 8 * 1024;
50
51 /// Creates a new coroutine to read bytes using a buffer with
52 /// [`Self::DEFAULT_CAPACITY`] capacity.
53 ///
54 /// See [`Self::with_capacity`] for a custom buffer capacity.
55 pub fn new() -> Self {
56 Self::with_capacity(Self::DEFAULT_CAPACITY)
57 }
58
59 /// Creates a new coroutine to read bytes using a buffer with the
60 /// given capacity.
61 pub fn with_capacity(capacity: usize) -> Self {
62 trace!("init coroutine to read bytes (capacity: {capacity})");
63 let buffer = vec![0; capacity];
64 Self { buffer }
65 }
66
67 /// Returns the buffer capacity.
68 pub fn capacity(&self) -> usize {
69 self.buffer.capacity()
70 }
71
72 /// Shortens the buffer to the given length.
73 pub fn truncate(&mut self, len: usize) {
74 self.buffer.truncate(len);
75 self.buffer.shrink_to(len);
76 }
77
78 /// Replaces the inner buffer with the given one.
79 pub fn replace(&mut self, mut buffer: Vec<u8>) {
80 buffer.fill(0);
81 self.buffer = buffer;
82 }
83
84 /// Makes the read progress.
85 pub fn resume(&mut self, arg: Option<StreamIo>) -> ReadStreamResult {
86 let Some(arg) = arg else {
87 let mut buffer = vec![0; self.buffer.capacity()];
88 mem::swap(&mut buffer, &mut self.buffer);
89 trace!("wants I/O to read bytes");
90 return ReadStreamResult::Io(StreamIo::Read(Err(buffer)));
91 };
92
93 trace!("resume after reading bytes");
94
95 let StreamIo::Read(io) = arg else {
96 return ReadStreamResult::Err(ReadStreamError::InvalidArgument("read output", arg));
97 };
98
99 let output = match io {
100 Ok(output) => output,
101 Err(buffer) => return ReadStreamResult::Io(StreamIo::Read(Err(buffer))),
102 };
103
104 match output.bytes_count {
105 0 => ReadStreamResult::Eof,
106 n => {
107 debug!("read {n}/{} bytes", output.buffer.capacity());
108 ReadStreamResult::Ok(output)
109 }
110 }
111 }
112 }
113
114 impl Default for ReadStream {
115 fn default() -> Self {
116 Self::new()
117 }
118 }
119
120 #[cfg(test)]
121 mod tests {
122 use std::io::{BufReader, Read as _};
123
124 use crate::{
125 coroutines::read::ReadStreamResult,
126 io::{StreamIo, StreamOutput},
127 };
128
129 use super::ReadStream;
130
131 #[test]
132 fn read() {
133 let _ = env_logger::try_init();
134
135 let mut reader = BufReader::new("abcdef".as_bytes());
136
137 let mut read = ReadStream::with_capacity(4);
138 let mut arg = None;
139
140 let output = loop {
141 match read.resume(arg.take()) {
142 ReadStreamResult::Ok(output) => break output,
143 ReadStreamResult::Io(StreamIo::Read(Err(mut buffer))) => {
144 let bytes_count = reader.read(&mut buffer).unwrap();
145 let output = StreamOutput {
146 buffer,
147 bytes_count,
148 };
149 arg = Some(StreamIo::Read(Ok(output)))
150 }
151 other => unreachable!("Unexpected result: {other:?}"),
152 }
153 };
154
155 assert_eq!(output.bytes(), b"abcd");
156
157 read.replace(output.buffer);
158
159 let output = loop {
160 match read.resume(arg.take()) {
161 ReadStreamResult::Ok(output) => break output,
162 ReadStreamResult::Io(StreamIo::Read(Err(mut buffer))) => {
163 let bytes_count = reader.read(&mut buffer).unwrap();
164 let output = StreamOutput {
165 buffer,
166 bytes_count,
167 };
168 arg = Some(StreamIo::Read(Ok(output)))
169 }
170 other => unreachable!("Unexpected result: {other:?}"),
171 }
172 };
173
174 assert_eq!(output.bytes(), b"ef");
175
176 read.replace(output.buffer);
177
178 loop {
179 match read.resume(arg.take()) {
180 ReadStreamResult::Eof => break,
181 ReadStreamResult::Io(StreamIo::Read(Err(mut buffer))) => {
182 let bytes_count = reader.read(&mut buffer).unwrap();
183 let output = StreamOutput {
184 buffer,
185 bytes_count,
186 };
187 arg = Some(StreamIo::Read(Ok(output)))
188 }
189 other => unreachable!("Unexpected result: {other:?}"),
190 }
191 }
192 }
193 }