vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! An in-memory pipe connecting an output to an input.

use std::sync::{Arc, Mutex};

use super::input::PipeInput;
use super::{Output, OutputError};

/// The capacity threshold at which a pipe is considered full.
///
/// Pipes are effectively unbounded in the virtual environment; this value
/// bounds a single `write` batch, not the pipe itself.
const WRITE_BATCH: usize = 65_536;

/// The shared buffer state behind a pipe's reader and writer halves.
#[derive(Debug)]
pub(crate) struct PipeState {
    /// Bytes written but not yet consumed.
    pub(crate) buffer: Vec<u8>,
    /// The writer half is still open (unused today; documents pipe lifetime).
    pub(crate) writer_open: bool,
}

/// An in-memory pipe for virtual command coordination.
///
/// The producer writes through the [`Output`] half; the consumer reads
/// through the corresponding `Input` half. Both halves share one buffer,
/// so everything the producer writes before the consumer starts reading
/// is available to the consumer — the model the Shell runtime relies on
/// for sequential pipeline execution.
#[derive(Clone, Debug)]
pub struct Pipe {
    state: Arc<Mutex<PipeState>>,
}

impl Pipe {
    /// Creates an empty pipe with both halves open.
    pub fn new() -> Self {
        Self {
            state: Arc::new(Mutex::new(PipeState {
                buffer: Vec::new(),
                writer_open: true,
            })),
        }
    }

    /// The input (reader) half.
    pub fn input(&self) -> PipeInput {
        PipeInput::new(Arc::clone(&self.state))
    }

    /// The output (writer) half.
    pub fn output(&self) -> PipeOutput {
        PipeOutput::new(Arc::clone(&self.state))
    }
}

impl Default for Pipe {
    fn default() -> Self {
        Self::new()
    }
}

/// The writer half of a [`Pipe`].
#[derive(Clone)]
pub struct PipeOutput {
    state: Arc<Mutex<PipeState>>,
}

impl PipeOutput {
    /// Creates the writer half over shared state.
    pub(crate) fn new(state: Arc<Mutex<PipeState>>) -> Self {
        Self { state }
    }
}

impl Output for PipeOutput {
    fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError> {
        for chunk in bytes.chunks(WRITE_BATCH) {
            let mut state = self.state.lock().expect("pipe state lock poisoned");
            state.buffer.extend_from_slice(chunk);
        }
        Ok(())
    }
}

impl Drop for PipeOutput {
    fn drop(&mut self) {
        if let Ok(mut state) = self.state.lock() {
            state.writer_open = false;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::Input;

    #[test]
    fn pipe_transfers_data_and_reports_eof() {
        let pipe = Pipe::new();
        let mut input = pipe.input();
        let mut output = pipe.output();
        output.write(b"hello world").unwrap();
        drop(output);
        let mut bytes = Vec::new();
        input.read_to_end(&mut bytes).unwrap();
        assert_eq!(bytes, b"hello world");
    }

    #[test]
    fn pipe_carries_empty_reader_after_eof() {
        let pipe = Pipe::new();
        let mut input = pipe.input();
        let output = pipe.output();
        drop(output);
        let mut byte = [0u8; 1];
        assert_eq!(input.read(&mut byte).unwrap(), 0);
    }
}