Skip to main content

engine/io/
input.rs

1//! Input streams.
2
3use std::io;
4
5/// Errors produced by an [`Input`] stream.
6#[derive(Debug)]
7pub enum InputError {
8    /// The underlying stream failed in a host-specific way.
9    Io(io::Error),
10}
11
12impl std::fmt::Display for InputError {
13    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        match self {
15            InputError::Io(error) => write!(formatter, "input error: {error}"),
16        }
17    }
18}
19
20impl std::error::Error for InputError {}
21
22impl From<io::Error> for InputError {
23    fn from(error: io::Error) -> Self {
24        InputError::Io(error)
25    }
26}
27
28/// A readable byte stream.
29///
30/// The Engine only knows about bytes; line orientation (if any) is a
31/// property of the stream's source.
32pub trait Input: Send + Sync {
33    /// Reads bytes into `buffer`; returns the number of bytes read.
34    ///
35    /// Returns `Ok(0)` at end of stream. Implementations may return fewer
36    /// bytes than the buffer's length.
37    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError>;
38
39    /// Reads until end of stream, appending everything to `out`.
40    fn read_to_end(&mut self, out: &mut Vec<u8>) -> Result<(), InputError> {
41        let mut scratch = [0u8; 4096];
42        loop {
43            let read = self.read(&mut scratch)?;
44            if read == 0 {
45                return Ok(());
46            }
47            out.extend_from_slice(&scratch[..read]);
48        }
49    }
50
51    /// Reads a line (terminated by `\n`), appending it to `line`.
52    ///
53    /// The trailing newline is included. Returns `Ok(false)` when the stream
54    /// is exhausted before any byte was read. Bytes are buffered to the
55    /// newline and decoded once, so multi-byte UTF-8 sequences survive;
56    /// bytes that are not valid UTF-8 are replaced with the Unicode
57    /// replacement character.
58    fn read_line(&mut self, line: &mut String) -> Result<bool, InputError> {
59        let mut bytes = Vec::new();
60        let mut buffer = [0u8; 1];
61        let mut any = false;
62        loop {
63            match self.read(&mut buffer)? {
64                0 => break,
65                _ => {
66                    any = true;
67                    bytes.push(buffer[0]);
68                    if buffer[0] == b'\n' {
69                        break;
70                    }
71                }
72            }
73        }
74        line.push_str(&String::from_utf8_lossy(&bytes));
75        Ok(any)
76    }
77}
78
79/// An input over a fixed byte buffer (for example a script body).
80#[derive(Clone, Debug)]
81pub struct BytesInput {
82    bytes: Vec<u8>,
83    position: usize,
84}
85
86impl BytesInput {
87    /// Creates an input over the given bytes.
88    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
89        Self {
90            bytes: bytes.into(),
91            position: 0,
92        }
93    }
94}
95
96impl Input for BytesInput {
97    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError> {
98        if self.position >= self.bytes.len() {
99            return Ok(0);
100        }
101        let count = buffer.len().min(self.bytes.len() - self.position);
102        buffer[..count].copy_from_slice(&self.bytes[self.position..self.position + count]);
103        self.position += count;
104        Ok(count)
105    }
106}
107
108/// A line-oriented input over static text.
109#[derive(Clone, Debug)]
110pub struct StringInput {
111    lines: Vec<String>,
112    position: usize,
113    /// Byte offset into the current line, when the caller's buffer was too
114    /// small to take the whole line in one read.
115    offset: usize,
116}
117
118impl StringInput {
119    /// Creates a line-oriented input; each element of `lines` is a line
120    /// (without newlines).
121    pub fn new(lines: impl IntoIterator<Item = impl Into<String>>) -> Self {
122        Self {
123            lines: lines.into_iter().map(Into::into).collect(),
124            position: 0,
125            offset: 0,
126        }
127    }
128}
129
130impl Input for StringInput {
131    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError> {
132        if self.position >= self.lines.len() {
133            return Ok(0);
134        }
135        let line = format!("{}\n", self.lines[self.position]);
136        let bytes = line.as_bytes();
137        let offset = self.offset;
138        let count = buffer.len().min(bytes.len() - offset);
139        buffer[..count].copy_from_slice(&bytes[offset..offset + count]);
140        // Advance within the line first; only a fully consumed line moves
141        // to the next one, so no text is ever dropped when the caller's
142        // buffer is smaller than the line.
143        if offset + count == bytes.len() {
144            self.position += 1;
145            self.offset = 0;
146        } else {
147            self.offset = offset + count;
148        }
149        Ok(count)
150    }
151}
152
153/// An input that is always at end of stream.
154#[derive(Clone, Copy, Debug, Default)]
155pub struct EmptyInput;
156
157impl EmptyInput {
158    /// Creates an empty input.
159    pub fn new() -> Self {
160        Self
161    }
162}
163
164impl Input for EmptyInput {
165    fn read(&mut self, _buffer: &mut [u8]) -> Result<usize, InputError> {
166        Ok(0)
167    }
168}
169
170/// The reader half of a [`Pipe`](crate::io::Pipe).
171#[derive(Clone)]
172pub struct PipeInput {
173    inner: std::sync::Arc<std::sync::Mutex<super::pipe::PipeState>>,
174}
175
176impl PipeInput {
177    /// Creates the reader half over shared pipe state.
178    pub(crate) fn new(inner: std::sync::Arc<std::sync::Mutex<super::pipe::PipeState>>) -> Self {
179        Self { inner }
180    }
181}
182
183impl Input for PipeInput {
184    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError> {
185        let mut state = self.inner.lock().expect("pipe state lock poisoned");
186        if state.buffer.is_empty() {
187            Ok(0)
188        } else {
189            let count = buffer.len().min(state.buffer.len());
190            buffer[..count].copy_from_slice(&state.buffer[..count]);
191            state.buffer.drain(..count);
192            Ok(count)
193        }
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn read_line_preserves_multibyte_characters() {
203        let mut input = BytesInput::new("héllo wörld\nsecond\n");
204        let mut line = String::new();
205        assert!(input.read_line(&mut line).unwrap());
206        assert_eq!(line, "héllo wörld\n");
207        line.clear();
208        assert!(input.read_line(&mut line).unwrap());
209        assert_eq!(line, "second\n");
210        line.clear();
211        assert!(!input.read_line(&mut line).unwrap());
212    }
213
214    #[test]
215    fn read_line_returns_final_line_without_newline() {
216        let mut input = BytesInput::new("tail");
217        let mut line = String::new();
218        assert!(input.read_line(&mut line).unwrap());
219        assert_eq!(line, "tail");
220    }
221}