1use std::sync::{Arc, Mutex};
4
5use super::input::PipeInput;
6use super::{Output, OutputError};
7
8const WRITE_BATCH: usize = 65_536;
13
14#[derive(Debug)]
16pub(crate) struct PipeState {
17 pub(crate) buffer: Vec<u8>,
19 pub(crate) writer_open: bool,
21}
22
23#[derive(Clone, Debug)]
31pub struct Pipe {
32 state: Arc<Mutex<PipeState>>,
33}
34
35impl Pipe {
36 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 pub fn input(&self) -> PipeInput {
48 PipeInput::new(Arc::clone(&self.state))
49 }
50
51 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#[derive(Clone)]
65pub struct PipeOutput {
66 state: Arc<Mutex<PipeState>>,
67}
68
69impl PipeOutput {
70 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}