Debian Codegraph @

src/coroutines/read-to-end.rs

raw symbols SCIP
1 //! I/O-free coroutine to read bytes into a buffer until it reaches
2 //! EOF.
3
4 use std::mem;
5
6 use log::trace;
7 use thiserror::Error;
8
9 use crate::io::StreamIo;
10
11 use super::read::{ReadStream, ReadStreamError, ReadStreamResult};
12
13 /// Errors that can occur during the coroutine progression.
14 #[derive(Clone, Debug, Error)]
15 pub enum ReadStreamToEndError {
16 /// Error from the [`Read`] coroutine.
17 #[error(transparent)]
18 Read(#[from] ReadStreamError),
19 }
20
21 /// Output emitted after a coroutine finishes its progression.
22 #[derive(Clone, Debug)]
23 pub enum ReadStreamToEndResult {
24 /// The coroutine has successfully terminated its progression.
25 Ok(Vec<u8>),
26
27 /// A stream I/O needs to be performed to make the coroutine
28 /// progress.
29 Io(StreamIo),
30
31 /// An error occured during the coroutine progression.
32 Err(ReadStreamToEndError),
33 }
34
35 /// I/O-free coroutine to read bytes into a buffer until it reaches
36 /// EOF.
37 #[derive(Debug)]
38 pub struct ReadStreamToEnd {
39 /// The inner read coroutine.
40 read: ReadStream,
41
42 /// The buffer containing the read bytes.
43 buffer: Vec<u8>,
44 }
45
46 impl ReadStreamToEnd {
47 /// Creates a new coroutine to read bytes using a buffer with
48 /// [`Read::DEFAULT_CAPACITY`] capacity.
49 ///
50 /// See [`Self::with_capacity`] for a custom buffer capacity.
51 pub fn new() -> Self {
52 Self::with_capacity(ReadStream::DEFAULT_CAPACITY)
53 }
54
55 /// Creates a new coroutine to read bytes using a buffer with the
56 /// given capacity.
57 pub fn with_capacity(capacity: usize) -> Self {
58 trace!("init coroutine to read until EOF (capacity: {capacity})");
59 let read = ReadStream::with_capacity(capacity);
60 let buffer = Vec::with_capacity(capacity);
61 Self { read, buffer }
62 }
63
64 /// Extends the inner buffer with the given bytes slice.
65 pub fn extend(&mut self, bytes: impl IntoIterator<Item = u8>) {
66 self.buffer.extend(bytes);
67 }
68
69 /// Makes the coroutine progress.
70 pub fn resume(&mut self, mut arg: Option<StreamIo>) -> ReadStreamToEndResult {
71 loop {
72 let output = match self.read.resume(arg.take()) {
73 ReadStreamResult::Ok(output) => output,
74 ReadStreamResult::Err(err) => break ReadStreamToEndResult::Err(err.into()),
75 ReadStreamResult::Io(io) => break ReadStreamToEndResult::Io(io),
76 ReadStreamResult::Eof => {
77 let buffer = mem::take(&mut self.buffer);
78 break ReadStreamToEndResult::Ok(buffer);
79 }
80 };
81
82 self.buffer.extend(output.bytes());
83 self.read.replace(output.buffer);
84 }
85 }
86 }
87
88 impl Default for ReadStreamToEnd {
89 fn default() -> Self {
90 Self::new()
91 }
92 }
93
94 #[cfg(test)]
95 mod tests {
96 use std::io::{BufReader, Read as _};
97
98 use crate::{
99 coroutines::read_to_end::ReadStreamToEndResult,
100 io::{StreamIo, StreamOutput},
101 };
102
103 use super::ReadStreamToEnd;
104
105 #[test]
106 fn read_to_end() {
107 let _ = env_logger::try_init();
108
109 let mut reader = BufReader::new("abcdef".as_bytes());
110
111 let mut read = ReadStreamToEnd::with_capacity(4);
112 let mut arg = None;
113
114 let output = loop {
115 match read.resume(arg.take()) {
116 ReadStreamToEndResult::Ok(output) => break output,
117 ReadStreamToEndResult::Io(StreamIo::Read(Err(mut buffer))) => {
118 let bytes_count = reader.read(&mut buffer).unwrap();
119 let output = StreamOutput {
120 buffer,
121 bytes_count,
122 };
123 arg = Some(StreamIo::Read(Ok(output)))
124 }
125 other => unreachable!("Unexpected result: {other:?}"),
126 }
127 };
128
129 assert_eq!(output, b"abcdef");
130 }
131 }