1use std::io;
4
5#[derive(Debug)]
7pub enum InputError {
8 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
28pub trait Input: Send + Sync {
33 fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError>;
38
39 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 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#[derive(Clone, Debug)]
81pub struct BytesInput {
82 bytes: Vec<u8>,
83 position: usize,
84}
85
86impl BytesInput {
87 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#[derive(Clone, Debug)]
110pub struct StringInput {
111 lines: Vec<String>,
112 position: usize,
113 offset: usize,
116}
117
118impl StringInput {
119 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 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#[derive(Clone, Copy, Debug, Default)]
155pub struct EmptyInput;
156
157impl EmptyInput {
158 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#[derive(Clone)]
172pub struct PipeInput {
173 inner: std::sync::Arc<std::sync::Mutex<super::pipe::PipeState>>,
174}
175
176impl PipeInput {
177 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}