vce-engine 0.1.1

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

use std::io;

/// Errors produced by an [`Output`] stream.
#[derive(Debug)]
pub enum OutputError {
    /// The underlying stream failed in a host-specific way.
    Io(io::Error),
}

impl std::fmt::Display for OutputError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputError::Io(error) => write!(formatter, "output error: {error}"),
        }
    }
}

impl std::error::Error for OutputError {}

impl From<io::Error> for OutputError {
    fn from(error: io::Error) -> Self {
        OutputError::Io(error)
    }
}

/// A writable byte stream.
pub trait Output: Send + Sync {
    /// Writes all of `bytes`.
    fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError>;

    /// Flushes any buffered state.
    fn flush(&mut self) -> Result<(), OutputError> {
        Ok(())
    }
}

/// An output that accumulates bytes in memory (used by tests and the
/// non-interactive shell).
#[derive(Clone, Debug, Default)]
pub struct BytesOutput {
    bytes: Vec<u8>,
}

impl BytesOutput {
    /// Creates an empty output.
    pub fn new() -> Self {
        Self::default()
    }

    /// The bytes written so far.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Consumes the output, returning the accumulated bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

impl Output for BytesOutput {
    fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError> {
        self.bytes.extend_from_slice(bytes);
        Ok(())
    }
}

/// An output that discards everything (the virtual `/dev/null`).
#[derive(Clone, Copy, Debug, Default)]
pub struct SinkOutput;

impl SinkOutput {
    /// Creates a sink output.
    pub fn new() -> Self {
        Self
    }
}

impl Output for SinkOutput {
    fn write(&mut self, _bytes: &[u8]) -> Result<(), OutputError> {
        Ok(())
    }
}