use std::sync::{Arc, Mutex};
use super::input::PipeInput;
use super::{Output, OutputError};
const WRITE_BATCH: usize = 65_536;
#[derive(Debug)]
pub(crate) struct PipeState {
pub(crate) buffer: Vec<u8>,
pub(crate) writer_open: bool,
}
#[derive(Clone, Debug)]
pub struct Pipe {
state: Arc<Mutex<PipeState>>,
}
impl Pipe {
pub fn new() -> Self {
Self {
state: Arc::new(Mutex::new(PipeState {
buffer: Vec::new(),
writer_open: true,
})),
}
}
pub fn input(&self) -> PipeInput {
PipeInput::new(Arc::clone(&self.state))
}
pub fn output(&self) -> PipeOutput {
PipeOutput::new(Arc::clone(&self.state))
}
}
impl Default for Pipe {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone)]
pub struct PipeOutput {
state: Arc<Mutex<PipeState>>,
}
impl PipeOutput {
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);
}
}