vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! Input streams.

use std::io;

/// Errors produced by an [`Input`] stream.
#[derive(Debug)]
pub enum InputError {
    /// The underlying stream failed in a host-specific way.
    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)
    }
}

/// A readable byte stream.
///
/// The Engine only knows about bytes; line orientation (if any) is a
/// property of the stream's source.
pub trait Input: Send + Sync {
    /// Reads bytes into `buffer`; returns the number of bytes read.
    ///
    /// Returns `Ok(0)` at end of stream. Implementations may return fewer
    /// bytes than the buffer's length.
    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, InputError>;

    /// Reads until end of stream, appending everything to `out`.
    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]);
        }
    }

    /// Reads a line (terminated by `\n`), appending it to `line`.
    ///
    /// The trailing newline is included. Returns `Ok(false)` when the stream
    /// is exhausted before any byte was read. Bytes are buffered to the
    /// newline and decoded once, so multi-byte UTF-8 sequences survive;
    /// bytes that are not valid UTF-8 are replaced with the Unicode
    /// replacement character.
    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)
    }
}

/// An input over a fixed byte buffer (for example a script body).
#[derive(Clone, Debug)]
pub struct BytesInput {
    bytes: Vec<u8>,
    position: usize,
}

impl BytesInput {
    /// Creates an input over the given bytes.
    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)
    }
}

/// A line-oriented input over static text.
#[derive(Clone, Debug)]
pub struct StringInput {
    lines: Vec<String>,
    position: usize,
    /// Byte offset into the current line, when the caller's buffer was too
    /// small to take the whole line in one read.
    offset: usize,
}

impl StringInput {
    /// Creates a line-oriented input; each element of `lines` is a line
    /// (without newlines).
    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]);
        // Advance within the line first; only a fully consumed line moves
        // to the next one, so no text is ever dropped when the caller's
        // buffer is smaller than the line.
        if offset + count == bytes.len() {
            self.position += 1;
            self.offset = 0;
        } else {
            self.offset = offset + count;
        }
        Ok(count)
    }
}

/// An input that is always at end of stream.
#[derive(Clone, Copy, Debug, Default)]
pub struct EmptyInput;

impl EmptyInput {
    /// Creates an empty input.
    pub fn new() -> Self {
        Self
    }
}

impl Input for EmptyInput {
    fn read(&mut self, _buffer: &mut [u8]) -> Result<usize, InputError> {
        Ok(0)
    }
}

/// The reader half of a [`Pipe`](crate::io::Pipe).
#[derive(Clone)]
pub struct PipeInput {
    inner: std::sync::Arc<std::sync::Mutex<super::pipe::PipeState>>,
}

impl PipeInput {
    /// Creates the reader half over shared pipe state.
    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");
    }
}