Skip to main content

engine/io/
pipe.rs

1//! An in-memory pipe connecting an output to an input.
2
3use std::sync::{Arc, Mutex};
4
5use super::input::PipeInput;
6use super::{Output, OutputError};
7
8/// The capacity threshold at which a pipe is considered full.
9///
10/// Pipes are effectively unbounded in the virtual environment; this value
11/// bounds a single `write` batch, not the pipe itself.
12const WRITE_BATCH: usize = 65_536;
13
14/// The shared buffer state behind a pipe's reader and writer halves.
15#[derive(Debug)]
16pub(crate) struct PipeState {
17    /// Bytes written but not yet consumed.
18    pub(crate) buffer: Vec<u8>,
19    /// The writer half is still open (unused today; documents pipe lifetime).
20    pub(crate) writer_open: bool,
21}
22
23/// An in-memory pipe for virtual command coordination.
24///
25/// The producer writes through the [`Output`] half; the consumer reads
26/// through the corresponding `Input` half. Both halves share one buffer,
27/// so everything the producer writes before the consumer starts reading
28/// is available to the consumer — the model the Shell runtime relies on
29/// for sequential pipeline execution.
30#[derive(Clone, Debug)]
31pub struct Pipe {
32    state: Arc<Mutex<PipeState>>,
33}
34
35impl Pipe {
36    /// Creates an empty pipe with both halves open.
37    pub fn new() -> Self {
38        Self {
39            state: Arc::new(Mutex::new(PipeState {
40                buffer: Vec::new(),
41                writer_open: true,
42            })),
43        }
44    }
45
46    /// The input (reader) half.
47    pub fn input(&self) -> PipeInput {
48        PipeInput::new(Arc::clone(&self.state))
49    }
50
51    /// The output (writer) half.
52    pub fn output(&self) -> PipeOutput {
53        PipeOutput::new(Arc::clone(&self.state))
54    }
55}
56
57impl Default for Pipe {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63/// The writer half of a [`Pipe`].
64#[derive(Clone)]
65pub struct PipeOutput {
66    state: Arc<Mutex<PipeState>>,
67}
68
69impl PipeOutput {
70    /// Creates the writer half over shared state.
71    pub(crate) fn new(state: Arc<Mutex<PipeState>>) -> Self {
72        Self { state }
73    }
74}
75
76impl Output for PipeOutput {
77    fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError> {
78        for chunk in bytes.chunks(WRITE_BATCH) {
79            let mut state = self.state.lock().expect("pipe state lock poisoned");
80            state.buffer.extend_from_slice(chunk);
81        }
82        Ok(())
83    }
84}
85
86impl Drop for PipeOutput {
87    fn drop(&mut self) {
88        if let Ok(mut state) = self.state.lock() {
89            state.writer_open = false;
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::io::Input;
98
99    #[test]
100    fn pipe_transfers_data_and_reports_eof() {
101        let pipe = Pipe::new();
102        let mut input = pipe.input();
103        let mut output = pipe.output();
104        output.write(b"hello world").unwrap();
105        drop(output);
106        let mut bytes = Vec::new();
107        input.read_to_end(&mut bytes).unwrap();
108        assert_eq!(bytes, b"hello world");
109    }
110
111    #[test]
112    fn pipe_carries_empty_reader_after_eof() {
113        let pipe = Pipe::new();
114        let mut input = pipe.input();
115        let output = pipe.output();
116        drop(output);
117        let mut byte = [0u8; 1];
118        assert_eq!(input.read(&mut byte).unwrap(), 0);
119    }
120}