use std::io::{Read, Write};
use std::thread;
use crate::child::Child;
use crate::error::Error;
use crate::stdio::Fd;
use crate::Output;
pub(crate) fn communicate(child: &mut Child, input: Option<&[u8]>) -> Result<Output, Error> {
let stdin = child.take_stdin_writer();
let stdout = child.take_reader(Fd::STDOUT);
let stderr = child.take_reader(Fd::STDERR);
debug_assert!(
input.is_none() || stdin.is_some(),
"communicate given input but stdin was not piped"
);
thread::scope(|scope| -> Result<Output, Error> {
let writer = stdin.map(|mut w| {
let data = input.unwrap_or(&[]).to_vec();
scope.spawn(move || -> std::io::Result<()> {
match w.write_all(&data) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
Err(e) => return Err(e),
}
drop(w); Ok(())
})
});
let out_reader = stdout.map(|mut r| {
scope.spawn(move || -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
r.read_to_end(&mut buf)?;
Ok(buf)
})
});
let err_reader = stderr.map(|mut r| {
scope.spawn(move || -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
r.read_to_end(&mut buf)?;
Ok(buf)
})
});
let status = child.wait()?;
let stdout = join_bytes(out_reader)?;
let stderr = join_bytes(err_reader)?;
if let Some(h) = writer {
h.join().expect("stdin pump thread panicked").map_err(Error::Io)?;
}
Ok(Output { status, stdout, stderr })
})
}
fn join_bytes(h: Option<thread::ScopedJoinHandle<'_, std::io::Result<Vec<u8>>>>) -> Result<Vec<u8>, Error> {
match h {
Some(h) => h.join().expect("reader pump thread panicked").map_err(Error::Io),
None => Ok(Vec::new()),
}
}