use std::io;
#[derive(Debug)]
pub enum InputError {
Io(io::Error),
}
impl std::fmt::Display for InputError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InputError::Io(error) => write!(formatter, "input error: {error}"),
}
}
}
impl std::error::Error for InputError {}
impl From<io::Error> for InputError {
fn from(error: io::Error) -> Self {
InputError::Io(error)
}
}
pub trait Input: Send + Sync {
fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError>;
fn read_to_end(&mut self, out: &mut Vec<u8>) -> Result<(), InputError> {
let mut scratch = [0u8; 4096];
loop {
let read = self.read(&mut scratch)?;
if read == 0 {
return Ok(());
}
out.extend_from_slice(&scratch[..read]);
}
}
fn read_line(&mut self, line: &mut String) -> Result<bool, InputError> {
let mut bytes = Vec::new();
let mut buffer = [0u8; 1];
let mut any = false;
loop {
match self.read(&mut buffer)? {
0 => break,
_ => {
any = true;
bytes.push(buffer[0]);
if buffer[0] == b'\n' {
break;
}
}
}
}
line.push_str(&String::from_utf8_lossy(&bytes));
Ok(any)
}
}
#[derive(Clone, Debug)]
pub struct BytesInput {
bytes: Vec<u8>,
position: usize,
}
impl BytesInput {
pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
Self {
bytes: bytes.into(),
position: 0,
}
}
}
impl Input for BytesInput {
fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError> {
if self.position >= self.bytes.len() {
return Ok(0);
}
let count = buffer.len().min(self.bytes.len() - self.position);
buffer[..count].copy_from_slice(&self.bytes[self.position..self.position + count]);
self.position += count;
Ok(count)
}
}
#[derive(Clone, Debug)]
pub struct StringInput {
lines: Vec<String>,
position: usize,
offset: usize,
}
impl StringInput {
pub fn new(lines: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
lines: lines.into_iter().map(Into::into).collect(),
position: 0,
offset: 0,
}
}
}
impl Input for StringInput {
fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError> {
if self.position >= self.lines.len() {
return Ok(0);
}
let line = format!("{}\n", self.lines[self.position]);
let bytes = line.as_bytes();
let offset = self.offset;
let count = buffer.len().min(bytes.len() - offset);
buffer[..count].copy_from_slice(&bytes[offset..offset + count]);
if offset + count == bytes.len() {
self.position += 1;
self.offset = 0;
} else {
self.offset = offset + count;
}
Ok(count)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct EmptyInput;
impl EmptyInput {
pub fn new() -> Self {
Self
}
}
impl Input for EmptyInput {
fn read(&mut self, _buffer: &mut [u8]) -> Result<usize, InputError> {
Ok(0)
}
}
#[derive(Clone)]
pub struct PipeInput {
inner: std::sync::Arc<std::sync::Mutex<super::pipe::PipeState>>,
}
impl PipeInput {
pub(crate) fn new(inner: std::sync::Arc<std::sync::Mutex<super::pipe::PipeState>>) -> Self {
Self { inner }
}
}
impl Input for PipeInput {
fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError> {
let mut state = self.inner.lock().expect("pipe state lock poisoned");
if state.buffer.is_empty() {
Ok(0)
} else {
let count = buffer.len().min(state.buffer.len());
buffer[..count].copy_from_slice(&state.buffer[..count]);
state.buffer.drain(..count);
Ok(count)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_line_preserves_multibyte_characters() {
let mut input = BytesInput::new("héllo wörld\nsecond\n");
let mut line = String::new();
assert!(input.read_line(&mut line).unwrap());
assert_eq!(line, "héllo wörld\n");
line.clear();
assert!(input.read_line(&mut line).unwrap());
assert_eq!(line, "second\n");
line.clear();
assert!(!input.read_line(&mut line).unwrap());
}
#[test]
fn read_line_returns_final_line_without_newline() {
let mut input = BytesInput::new("tail");
let mut line = String::new();
assert!(input.read_line(&mut line).unwrap());
assert_eq!(line, "tail");
}
}